@litfamily/litgravity 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,641 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, rmdirSync, rmSync, writeFileSync,
4
+ } from 'node:fs';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
7
+ import { paths } from './paths.mjs';
8
+ import { assertSafeWritePath } from './guard.mjs';
9
+ import { packageVersion, parseFrontmatter } from './bundle.mjs';
10
+ import { MOVED_SKILLS } from '../plugin/hooks/lib/routes.mjs';
11
+ import { EXTENSION_SHELF, oldRuntimeDir } from '../plugin/hooks/lib/extensions.mjs';
12
+
13
+ // `litgravity extensions <verb>`: the four install lines of the stubs, done in code. Look for every same-name skill agy
14
+ // could load, move an existing copy whole into a dated folder agy never scans, copy into the emptied place, write a
15
+ // receipt inside the copy. Every write waits for --yes; without it the verb prints what it would do.
16
+ //
17
+ // Writes go only to agy's skill folder for the scope (~/.gemini/config/skills or <workspace>/.agents/skills), to
18
+ // ~/.gemini/extension-backups, and to LitGravity's own source cache. Other folders are read, never written.
19
+
20
+ export const RECEIPT = '.litfamily-extension.json';
21
+ export const VARIANT = 'litgravity';
22
+ const CLI = 'npx @litfamily/litgravity extensions';
23
+
24
+ export function extensionPaths(env = process.env, cwd = process.cwd()) {
25
+ const p = paths(env, cwd);
26
+ const gemini = join(p.home, '.gemini');
27
+ const cacheHome = env.XDG_CACHE_HOME || join(p.home, '.cache');
28
+ return {
29
+ env,
30
+ home: p.home,
31
+ cwd,
32
+ data: p.data,
33
+ userPlugin: p.userPlugin,
34
+ projectPlugin: p.projectPlugin,
35
+ roots: { user: join(gemini, 'config', 'skills'), project: join(cwd, '.agents', 'skills') },
36
+ // The four folders agy 1.5.6 loads bare skills from, in the order it prefers them.
37
+ scan: [join(cwd, '.agents', 'skills'), join(cwd, '_agents', 'skills'), join(gemini, 'config', 'skills'), join(gemini, 'skills')],
38
+ backups: join(gemini, 'extension-backups'),
39
+ cache: join(cacheHome, 'litgravity', 'extensions-src'),
40
+ repo: env.LITGRAVITY_EXTENSIONS_REPO || `${EXTENSION_SHELF}.git`,
41
+ };
42
+ }
43
+
44
+ const lstat = (p) => { try { return lstatSync(p); } catch { return null; } };
45
+ const tilde = (x, home) => (x === home || x.startsWith(`${home}${sep}`) ? `~${x.slice(home.length)}` : x);
46
+
47
+ function skillName(dir) {
48
+ try {
49
+ return parseFrontmatter(readFileSync(join(dir, 'SKILL.md'), 'utf8')).name ?? null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ export function readReceipt(dir) {
56
+ try {
57
+ const r = JSON.parse(readFileSync(join(dir, RECEIPT), 'utf8'));
58
+ return r && typeof r === 'object' && r.variant === VARIANT ? r : null;
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /** One hash over every file of a skill folder (paths and bytes), the receipt left out. */
65
+ export function treeHash(dir) {
66
+ const h = createHash('sha256');
67
+ let files = 0;
68
+ const walk = (d) => {
69
+ for (const name of readdirSync(d).sort()) {
70
+ const full = join(d, name);
71
+ const rel = relative(dir, full).split(sep).join('/');
72
+ if (rel === RECEIPT || name === '.git') continue;
73
+ const st = lstatSync(full);
74
+ if (st.isDirectory()) walk(full);
75
+ else {
76
+ h.update(`${rel}\0`);
77
+ h.update(st.isSymbolicLink() ? `link:${readlinkSync(full)}` : readFileSync(full));
78
+ h.update('\0');
79
+ files += 1;
80
+ }
81
+ }
82
+ };
83
+ walk(dir);
84
+ return { hash: `sha256:${h.digest('hex')}`, files };
85
+ }
86
+
87
+ function dirBytes(dir) {
88
+ let total = 0;
89
+ const walk = (d) => {
90
+ let names = [];
91
+ try { names = readdirSync(d); } catch { return; }
92
+ for (const name of names) {
93
+ const st = lstat(join(d, name));
94
+ if (!st) continue;
95
+ if (st.isDirectory()) walk(join(d, name));
96
+ else total += st.size;
97
+ }
98
+ };
99
+ walk(dir);
100
+ return total;
101
+ }
102
+
103
+ export const human = (n) => (n >= 1048576 ? `${(n / 1048576).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`);
104
+
105
+ /** Where one id stands at one scope: absent, link, not-a-folder, installed (with receipt) or user-managed. */
106
+ export function destState(ep, id, scope) {
107
+ const dest = join(ep.roots[scope], id);
108
+ const st = lstat(dest);
109
+ if (!st) return { state: 'absent', dest };
110
+ if (st.isSymbolicLink()) return { state: 'link', dest };
111
+ if (!st.isDirectory()) return { state: 'not-a-folder', dest };
112
+ const receipt = readReceipt(dest);
113
+ return receipt ? { state: 'installed', dest, receipt } : { state: 'user-managed', dest };
114
+ }
115
+
116
+ /** Every SKILL.md named `id` in the folders agy loads, a `<id>.bak` sibling included. */
117
+ export function sameNameSkills(ep, id) {
118
+ const hits = [];
119
+ const seen = new Set();
120
+ for (const folder of ep.scan) {
121
+ if (seen.has(folder)) continue;
122
+ seen.add(folder);
123
+ let names = [];
124
+ try { names = readdirSync(folder); } catch { continue; }
125
+ for (const name of names.sort()) {
126
+ const dir = join(folder, name);
127
+ if (skillName(dir) === id) hits.push({ path: dir, folder, receipt: Boolean(readReceipt(dir)) });
128
+ }
129
+ }
130
+ return hits;
131
+ }
132
+
133
+ // A link anywhere between the scope's anchor (HOME or the workspace) and the target sends bytes somewhere else.
134
+ function linkOnPath(target, anchor) {
135
+ let cur = target;
136
+ while (cur.startsWith(anchor) && cur !== anchor) {
137
+ const st = lstat(cur);
138
+ if (st?.isSymbolicLink()) return cur;
139
+ cur = dirname(cur);
140
+ }
141
+ return null;
142
+ }
143
+
144
+ function stampNow(date = new Date()) {
145
+ const z = (n) => String(n).padStart(2, '0');
146
+ return `${date.getFullYear()}${z(date.getMonth() + 1)}${z(date.getDate())}-${z(date.getHours())}${z(date.getMinutes())}${z(date.getSeconds())}`;
147
+ }
148
+
149
+ function backupDir(ep, scope, ids, stamp = stampNow()) {
150
+ const base = `${stamp}${scope === 'project' ? '-project' : ''}`;
151
+ for (let n = 1; ; n += 1) {
152
+ const dir = join(ep.backups, n === 1 ? base : `${base}-${n}`);
153
+ if (!ids.some((id) => existsSync(join(dir, id)))) return dir;
154
+ }
155
+ }
156
+
157
+ function git(env, args) {
158
+ const r = spawnSync('git', args, { encoding: 'utf8', timeout: 180000, env: { ...env, GIT_TERMINAL_PROMPT: '0' } });
159
+ if (r.error?.code === 'ENOENT') return { ok: false, missing: true, text: 'git was not found on PATH' };
160
+ const text = `${r.stderr ?? ''}${r.stdout ?? ''}`.trim().split('\n').filter(Boolean).slice(-2).join(' / ');
161
+ return { ok: r.status === 0, stdout: (r.stdout ?? '').trim(), text: text || (r.error ? r.error.message : `exit ${r.status}`) };
162
+ }
163
+
164
+ const fromHint = (verb) => `Nothing was installed. With a clone you already have: ${CLI} ${verb} … --from <path to your wjgoarxiv-skills clone>`;
165
+
166
+ /**
167
+ * The folder that holds variants/litgravity/<id>. `--from` is the user's own clone, read only. Otherwise LitGravity
168
+ * keeps a shallow, sparse clone of only variants/litgravity in its cache; a write verb with --yes clones it once and
169
+ * `update` fetches it. A dry run never touches the network.
170
+ */
171
+ function resolveSource(ep, flags, { refresh, write, verb }) {
172
+ if (flags.from) {
173
+ const root = resolve(ep.cwd, flags.from);
174
+ if (!existsSync(join(root, 'variants', VARIANT))) return { error: `${root} has no variants/${VARIANT}/ folder; point --from at a wjgoarxiv-skills clone.` };
175
+ return { root, label: `${root} (--from)` };
176
+ }
177
+ const cache = ep.cache;
178
+ const label = (extra = '') => `${cache} (LitGravity's clone of ${ep.repo}${extra})`;
179
+ const have = existsSync(join(cache, '.git'));
180
+ const pending = [
181
+ `git clone --depth 1 --filter=blob:none --sparse ${ep.repo} ${cache}`,
182
+ `git -C ${cache} sparse-checkout set variants/${VARIANT}`,
183
+ ];
184
+ if (!have && !write) return { pending, label: label(', not cloned yet') };
185
+ const bad = linkOnPath(cache, ep.home);
186
+ if (bad) return { error: `${bad} is a symbolic link; LitGravity keeps its source clone only in a real folder.` };
187
+ if (!have) {
188
+ const tmp = `${cache}.tmp-${process.pid}`;
189
+ mkdirSync(dirname(cache), { recursive: true });
190
+ const done = (r) => { rmSync(tmp, { recursive: true, force: true }); return r; };
191
+ let r = git(ep.env, ['clone', '--quiet', '--depth', '1', '--filter=blob:none', '--sparse', '--no-tags', ep.repo, tmp]);
192
+ if (r.ok) r = git(ep.env, ['-C', tmp, 'sparse-checkout', 'set', `variants/${VARIANT}`]);
193
+ if (!r.ok) return done({ error: `could not fetch the extension source (${r.text}). ${r.missing ? 'Install git, or use --from.' : 'Offline? Try again online.'}\n${fromHint(verb)}` });
194
+ renameSync(tmp, cache);
195
+ } else if (refresh && write) {
196
+ let r = git(ep.env, ['-C', cache, 'fetch', '--quiet', '--depth', '1', 'origin', 'HEAD']);
197
+ if (r.ok) r = git(ep.env, ['-C', cache, 'checkout', '--quiet', '--detach', 'FETCH_HEAD']);
198
+ if (!r.ok) return { error: `could not refresh ${cache} (${r.text}). Nothing changed.\n${fromHint(verb)}` };
199
+ }
200
+ const commit = git(ep.env, ['-C', cache, 'rev-parse', '--short', 'HEAD']);
201
+ return { root: cache, commit: commit.ok ? commit.stdout : null, label: label(commit.ok ? `, ${commit.stdout}` : ''), refreshed: refresh && write };
202
+ }
203
+
204
+ function pickIds(args, flags) {
205
+ if (flags.all) return { ids: Object.keys(MOVED_SKILLS) };
206
+ if (flags.family) {
207
+ const ids = Object.keys(MOVED_SKILLS).filter((id) => MOVED_SKILLS[id] === flags.family);
208
+ if (!ids.length) return { error: `no family ${flags.family}; the families are ${[...new Set(Object.values(MOVED_SKILLS))].join(', ')}` };
209
+ return { ids };
210
+ }
211
+ const unknown = args.filter((id) => !MOVED_SKILLS[id]);
212
+ if (unknown.length) return { error: `not a LitGravity extension: ${unknown.join(', ')}. The ids are ${Object.keys(MOVED_SKILLS).join(', ')}.` };
213
+ return { ids: [...new Set(args)] };
214
+ }
215
+
216
+ function writeReceipt(dir, src, root, commit, scope, { hash, files }) {
217
+ const receipt = {
218
+ id: basename(src), source: src, variant: VARIANT, installed_at: new Date().toISOString(),
219
+ scope, hash, files, ...(commit ? { source_commit: commit } : {}), installed_by: `litgravity ${packageVersion()}`,
220
+ };
221
+ writeFileSync(join(dir, RECEIPT), `${JSON.stringify(receipt, null, 2)}\n`);
222
+ return receipt;
223
+ }
224
+
225
+ // Plans one copy. A link or a non-folder destination, a missing source and another same-name skill agy loads are
226
+ // problems that stop the whole run before any write; --allow-shadow turns the last kind into a warning.
227
+ function planCopy(ep, id, scope, src, allowShadow) {
228
+ const st = destState(ep, id, scope);
229
+ const anchor = scope === 'user' ? ep.home : ep.cwd;
230
+ const problems = [];
231
+ const warnings = [];
232
+ const bad = linkOnPath(ep.roots[scope], anchor) || linkOnPath(ep.backups, ep.home) || linkOnPath(stagingRoot(ep, scope), anchor);
233
+ if (bad) problems.push(`${bad} is a symbolic link; LitGravity writes only into real folders`);
234
+ try { assertSafeWritePath(st.dest); } catch (err) { problems.push(err.message); }
235
+ if (st.state === 'link' || st.state === 'not-a-folder') {
236
+ problems.push(`${st.dest} is ${st.state === 'link' ? 'a symbolic link' : 'not a folder'}; move it aside by hand first: b=~/.gemini/extension-backups/$(date +%Y%m%d-%H%M%S); mkdir -p "$b" && mv "${st.dest}" "$b/"`);
237
+ }
238
+ if (!existsSync(join(src, 'SKILL.md'))) problems.push(`the source has no ${id}: ${src}/SKILL.md is missing`);
239
+ for (const hit of sameNameSkills(ep, id).filter((h) => h.path !== st.dest)) {
240
+ const line = `another skill named ${id} at ${hit.path}; agy keeps one same-name skill without a word`;
241
+ if (allowShadow) warnings.push(line);
242
+ else problems.push(`${line}. Move it aside or rename it, or rerun with --allow-shadow to install anyway`);
243
+ }
244
+ return { id, scope, src, st, problems, warnings };
245
+ }
246
+
247
+ function printPlan(plan, ep, print) {
248
+ print(`${plan.id}${plan.reason ? ` (${plan.reason})` : ''}`);
249
+ for (const w of plan.warnings) print(` WARN ${w}`);
250
+ if (plan.problems.length) {
251
+ for (const x of plan.problems) print(` STOP ${x}`);
252
+ return;
253
+ }
254
+ print(' check no other same-name skill in the folders agy loads' + (plan.warnings.length ? ' (except the ones above, allowed)' : ''));
255
+ if (plan.st.state !== 'absent') {
256
+ const what = plan.st.state === 'installed' ? 'the installed copy' : 'a folder without a receipt, kept whole';
257
+ print(` move ${tilde(plan.st.dest, ep.home)} -> ${tilde(plan.backup, ep.home)}/${plan.id} (${what})`);
258
+ }
259
+ print(` copy ${plan.src} -> ${tilde(plan.st.dest, ep.home)}`);
260
+ print(` receipt ${tilde(join(plan.st.dest, RECEIPT), ep.home)}`);
261
+ }
262
+
263
+ // The staging folder sits outside every folder agy loads, on the same disk as the destination, so a copy cut short by
264
+ // Ctrl-C or a crash never shows up as a second same-name skill: under the backups for user scope, beside skills/ for a
265
+ // workspace.
266
+ const stagingRoot = (ep, scope) => (scope === 'user' ? join(ep.backups, '.staging') : join(ep.cwd, '.agents', '.litgravity-staging'));
267
+
268
+ // Copy into the staging folder first, so a failed copy changes nothing; then move the old copy aside and put the new
269
+ // one in its place. If that last rename fails, the old copy goes back.
270
+ function applyCopy(plan, source, ep) {
271
+ const { st, src } = plan;
272
+ const staging = stagingRoot(ep, plan.scope);
273
+ mkdirSync(dirname(st.dest), { recursive: true });
274
+ mkdirSync(staging, { recursive: true });
275
+ const tmp = join(staging, `${plan.id}-${process.pid}`);
276
+ try {
277
+ cpSync(src, tmp, { recursive: true, verbatimSymlinks: true, errorOnExist: true, force: false, filter: (s) => basename(s) !== RECEIPT && basename(s) !== '.git' });
278
+ writeReceipt(tmp, src, source.root, source.commit, plan.scope, treeHash(src));
279
+ let moved = null;
280
+ if (lstat(st.dest)) {
281
+ mkdirSync(plan.backup, { recursive: true });
282
+ moved = join(plan.backup, plan.id);
283
+ renameSync(st.dest, moved);
284
+ }
285
+ try {
286
+ renameSync(tmp, st.dest);
287
+ } catch (err) {
288
+ if (moved) {
289
+ try { renameSync(moved, st.dest); } catch { err.keptAt = moved; }
290
+ }
291
+ throw err;
292
+ }
293
+ } finally {
294
+ rmSync(tmp, { recursive: true, force: true });
295
+ try { rmdirSync(staging); } catch { /* not empty, or gone */ }
296
+ }
297
+ }
298
+
299
+ function header(print, verb, scope, ep) {
300
+ print(`LitGravity extensions ${verb} · ${scope} scope (${tilde(ep.roots[scope], ep.home)})`);
301
+ }
302
+
303
+ const doneNote = 'Start a new agy conversation, or type /skills reload, to pick the change up.';
304
+
305
+ async function runCopies({ ep, flags, scope, plans, source, print, verb }) {
306
+ const stopped = plans.filter((x) => x.problems.length);
307
+ for (const plan of plans) printPlan(plan, ep, print);
308
+ if (stopped.length) {
309
+ print('');
310
+ print(`Stopped before writing anything: ${stopped.map((x) => x.id).join(', ')} need${stopped.length === 1 ? 's' : ''} attention (see STOP above).`);
311
+ return 1;
312
+ }
313
+ if (!flags.yes || flags.dryRun) {
314
+ print('');
315
+ print(`Dry run: nothing written. Add --yes to ${verb} ${plans.length === 1 ? 'it' : `these ${plans.length}`}.`);
316
+ return 0;
317
+ }
318
+ const done = [];
319
+ for (const plan of plans) {
320
+ try {
321
+ applyCopy(plan, source, ep);
322
+ } catch (err) {
323
+ print(`FAIL ${plan.id}: ${err.code === 'EXDEV' ? `${plan.st.dest} and ${ep.backups} are on different disks, so the old copy cannot be moved; move it aside by hand` : err.message}`);
324
+ print(err.keptAt ? `${plan.id} is not installed now; the old copy is in ${err.keptAt}.` : `${plan.id} is unchanged.`);
325
+ if (done.length) print(`Already done: ${done.join(', ')}, each with a receipt.`);
326
+ return 1;
327
+ }
328
+ done.push(plan.id);
329
+ }
330
+ print('');
331
+ print(`Done: ${plans.map((x) => x.id).join(', ')} at ${scope} scope, each with a receipt.${plans.some((x) => x.st.state !== 'absent') ? ` Earlier copies are in ${tilde(plans.find((x) => x.backup && x.st.state !== 'absent').backup, ep.home)}.` : ''}`);
332
+ print(doneNote);
333
+ return 0;
334
+ }
335
+
336
+ async function install({ ep, args, flags, scope, print }) {
337
+ const pick = pickIds(args, flags);
338
+ if (pick.error || !pick.ids.length) {
339
+ print(pick.error ?? `Name one or more ids, --family <name> or --all. The ids are ${Object.keys(MOVED_SKILLS).join(', ')}.`);
340
+ return 2;
341
+ }
342
+ header(print, 'install', scope, ep);
343
+ const source = resolveSource(ep, flags, { refresh: false, write: flags.yes && !flags.dryRun, verb: 'install' });
344
+ if (source.error) { print(`FAIL ${source.error}`); return 1; }
345
+ print(`source ${source.label}`);
346
+ if (source.pending) {
347
+ print('');
348
+ for (const id of pick.ids) {
349
+ const st = destState(ep, id, scope);
350
+ const others = sameNameSkills(ep, id).filter((h) => h.path !== st.dest);
351
+ print(`${id}: destination ${st.state === 'absent' ? 'free' : `${st.state}, moved aside first`}${others.length ? `; another same-name skill at ${others.map((h) => h.path).join(', ')} stops the install` : ''}`);
352
+ }
353
+ print('');
354
+ print('Dry run: the source is not cloned yet. With --yes LitGravity first runs:');
355
+ for (const line of source.pending) print(` ${line}`);
356
+ print('then checks, moves aside, copies and writes a receipt as above.');
357
+ return 0;
358
+ }
359
+ print('');
360
+ const backup = backupDir(ep, scope, pick.ids);
361
+ const plans = pick.ids.map((id) => ({ ...planCopy(ep, id, scope, join(source.root, 'variants', VARIANT, id), flags.allowShadow), backup }));
362
+ return runCopies({ ep, flags, scope, plans, source, print, verb: 'install' });
363
+ }
364
+
365
+ async function update({ ep, args, flags, scope, print }) {
366
+ const pick = args.length || flags.family ? pickIds(args, flags) : { ids: Object.keys(MOVED_SKILLS).filter((id) => destState(ep, id, scope).state === 'installed') };
367
+ if (pick.error) { print(pick.error); return 2; }
368
+ header(print, 'update', scope, ep);
369
+ if (!pick.ids.length) {
370
+ print(`No extension with a LitGravity receipt at ${scope} scope. Install one with: ${CLI} install <id>${scope === 'project' ? ' --project' : ''}`);
371
+ return 0;
372
+ }
373
+ const source = resolveSource(ep, flags, { refresh: true, write: flags.yes && !flags.dryRun, verb: 'update' });
374
+ if (source.error) { print(`FAIL ${source.error}`); return 1; }
375
+ print(`source ${source.label}${source.root && !source.refreshed && !flags.from ? ' (a dry run compares with the cached copy without fetching; --yes fetches first, so the result may differ)' : ''}`);
376
+ if (source.pending) {
377
+ print('');
378
+ print('Dry run: the source is not cloned yet, so nothing was compared. With --yes LitGravity first runs:');
379
+ for (const line of source.pending) print(` ${line}`);
380
+ print('then compares each extension with the fetched copy.');
381
+ return 0;
382
+ }
383
+ print('');
384
+ const backup = backupDir(ep, scope, pick.ids);
385
+ const plans = [];
386
+ const receiptOnly = [];
387
+ let refused = 0;
388
+ for (const id of pick.ids) {
389
+ const st = destState(ep, id, scope);
390
+ const src = join(source.root, 'variants', VARIANT, id);
391
+ if (st.state === 'absent') { print(`${id}: not installed at ${scope} scope; install it with ${CLI} install ${id}`); if (args.length) refused += 1; continue; }
392
+ if (st.state !== 'installed') {
393
+ print(`${id}: ${st.dest} has no LitGravity receipt, so update leaves it alone. ${CLI} install ${id} --yes moves it aside and installs a copy with a receipt.`);
394
+ refused += 1;
395
+ continue;
396
+ }
397
+ if (!existsSync(join(src, 'SKILL.md'))) { print(`${id}: the source has no ${id} (${src}); nothing changed`); refused += 1; continue; }
398
+ const want = treeHash(src).hash;
399
+ const have = st.receipt.hash ?? treeHash(st.dest).hash;
400
+ if (want === have) {
401
+ if (st.receipt.source !== src) receiptOnly.push({ id, st, src });
402
+ print(`${id}: current${st.receipt.source !== src ? ` (the receipt names ${st.receipt.source}; it will name ${src})` : ''}`);
403
+ continue;
404
+ }
405
+ plans.push({ ...planCopy(ep, id, scope, src, flags.allowShadow), backup, reason: 'the source changed' });
406
+ }
407
+ const write = flags.yes && !flags.dryRun;
408
+ // Receipts change only after every planned copy went through; a STOP or a failed copy leaves them as they were.
409
+ const code = plans.length ? await runCopies({ ep, flags, scope, plans, source, print, verb: 'update' }) : 0;
410
+ if (code) return code;
411
+ if (write) {
412
+ for (const { st, src } of receiptOnly) {
413
+ const file = join(st.dest, RECEIPT);
414
+ const r = JSON.parse(readFileSync(file, 'utf8'));
415
+ writeFileSync(`${file}.tmp-${process.pid}`, `${JSON.stringify({ ...r, source: src, ...(source.commit ? { source_commit: source.commit } : {}) }, null, 2)}\n`);
416
+ renameSync(`${file}.tmp-${process.pid}`, file);
417
+ }
418
+ } else if (receiptOnly.length && !plans.length) print('Dry run: add --yes to rewrite those receipts.');
419
+ return refused ? 1 : 0;
420
+ }
421
+
422
+ async function remove({ ep, args, flags, scope, print }) {
423
+ const pick = pickIds(args, flags);
424
+ if (pick.error || !pick.ids.length) { print(pick.error ?? 'Name the ids to remove.'); return 2; }
425
+ header(print, 'remove', scope, ep);
426
+ const backup = backupDir(ep, scope, pick.ids);
427
+ const moves = [];
428
+ let refused = 0;
429
+ for (const id of pick.ids) {
430
+ const st = destState(ep, id, scope);
431
+ if (st.state === 'absent') { print(`${id}: not installed at ${scope} scope`); continue; }
432
+ if (st.state !== 'installed') {
433
+ print(`${id}: refused. ${st.dest} ${st.state === 'link' ? 'is a symbolic link' : st.state === 'not-a-folder' ? 'is not a folder' : 'has no LitGravity receipt'}, so it is yours to keep or move; LitGravity removes only copies it installed.`);
434
+ refused += 1;
435
+ continue;
436
+ }
437
+ const bad = linkOnPath(ep.backups, ep.home);
438
+ if (bad) { print(`${id}: refused. ${bad} is a symbolic link.`); refused += 1; continue; }
439
+ print(`${id}`);
440
+ print(` move ${tilde(st.dest, ep.home)} -> ${tilde(backup, ep.home)}/${id} (nothing is deleted)`);
441
+ moves.push({ id, st });
442
+ }
443
+ if (moves.length && (!flags.yes || flags.dryRun)) {
444
+ print('');
445
+ print('Dry run: nothing moved. Add --yes to move them.');
446
+ return refused ? 1 : 0;
447
+ }
448
+ for (const { id, st } of moves) {
449
+ try {
450
+ mkdirSync(backup, { recursive: true });
451
+ renameSync(st.dest, join(backup, id));
452
+ } catch (err) {
453
+ print(`FAIL ${id}: ${err.message}`);
454
+ return 1;
455
+ }
456
+ }
457
+ if (moves.length) {
458
+ print('');
459
+ print(`Moved to ${tilde(backup, ep.home)}. ${doneNote} Clear old backups with: ${CLI} prune-backups`);
460
+ }
461
+ return refused ? 1 : 0;
462
+ }
463
+
464
+ export function listBackups(ep) {
465
+ let names = [];
466
+ try { names = readdirSync(ep.backups); } catch { return []; }
467
+ return names.sort().map((name) => {
468
+ const dir = join(ep.backups, name);
469
+ const st = lstat(dir);
470
+ const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})/.exec(name);
471
+ const at = m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]) : st?.mtime;
472
+ let ids = [];
473
+ try { ids = st?.isDirectory() ? readdirSync(dir) : []; } catch { /* unreadable */ }
474
+ return { name, dir, real: Boolean(st?.isDirectory() && !st.isSymbolicLink()), at, ids, bytes: st?.isDirectory() ? dirBytes(dir) : st?.size ?? 0 };
475
+ });
476
+ }
477
+
478
+ async function pruneBackups({ ep, flags, print }) {
479
+ const given = Object.hasOwn(flags, 'olderThan');
480
+ if (given && !/^\d+(\.\d+)?$/.test(flags.olderThan ?? '')) { print('--older-than takes a number of days'); return 2; }
481
+ const days = given ? Number(flags.olderThan) : null;
482
+ print(`LitGravity extensions prune-backups · ${tilde(ep.backups, ep.home)}`);
483
+ const bad = lstat(ep.backups)?.isSymbolicLink() ? ep.backups : linkOnPath(ep.backups, ep.home);
484
+ if (bad) { print(`FAIL ${bad} is a symbolic link; nothing deleted.`); return 1; }
485
+ const all = listBackups(ep);
486
+ if (!all.length) { print('No backups.'); return 0; }
487
+ const cutoff = days === null ? Infinity : Date.now() - days * 86400000;
488
+ let total = 0;
489
+ const chosen = [];
490
+ for (const b of all) {
491
+ const pick = b.real && (days === null || (b.at && b.at.getTime() < cutoff));
492
+ print(` ${pick ? 'delete' : 'keep '} ${b.name} ${human(b.bytes)} ${b.ids.join(', ')}${b.real ? '' : ' (not a real folder; left alone)'}`);
493
+ if (pick) { chosen.push(b); total += b.bytes; }
494
+ }
495
+ print(`${all.length} backup folder${all.length === 1 ? '' : 's'}, ${human(all.reduce((s, b) => s + b.bytes, 0))} in all.`);
496
+ if (!chosen.length) { print('Nothing to delete.'); return 0; }
497
+ if (!flags.yes || flags.dryRun) {
498
+ print(`Dry run: would delete ${chosen.length} folder${chosen.length === 1 ? '' : 's'} (${human(total)}). Add --yes to delete ${chosen.length === 1 ? 'it' : 'them'}.`);
499
+ return 0;
500
+ }
501
+ for (const b of chosen) {
502
+ if (dirname(b.dir) !== ep.backups || !lstat(b.dir)?.isDirectory()) continue;
503
+ rmSync(b.dir, { recursive: true, force: true });
504
+ }
505
+ print(`Deleted ${chosen.length} folder${chosen.length === 1 ? '' : 's'} (${human(total)}) inside ${tilde(ep.backups, ep.home)}.`);
506
+ return 0;
507
+ }
508
+
509
+ /** Read-only: what each id looks like at both scopes, with every same-name skill agy could load instead. */
510
+ export function extensionRows(ep) {
511
+ return Object.entries(MOVED_SKILLS).map(([id, family]) => {
512
+ const hits = sameNameSkills(ep, id);
513
+ const scopes = {};
514
+ for (const scope of ['user', 'project']) {
515
+ const st = destState(ep, id, scope);
516
+ scopes[scope] = { state: st.state, path: st.dest, ...(st.receipt ? { variant: st.receipt.variant, installed_at: st.receipt.installed_at, source: st.receipt.source } : {}) };
517
+ }
518
+ const live = hits[0]?.path ?? null;
519
+ const competing = hits.filter((h) => h.path !== scopes.user.path && h.path !== scopes.project.path).map((h) => h.path);
520
+ return { id, family, ...scopes, competing, loads: live };
521
+ });
522
+ }
523
+
524
+ /** Read-only findings. `action` ones make check exit 1; each carries the exact line that fixes it. */
525
+ export function checkFindings(ep) {
526
+ const out = [];
527
+ const action = (text, fix) => out.push({ level: 'action', text, fix });
528
+ const info = (text, fix) => out.push({ level: 'info', text, ...(fix ? { fix } : {}) });
529
+ const moveLine = (path) => `b=~/.gemini/extension-backups/$(date +%Y%m%d-%H%M%S)-manual; mkdir -p "$b" && mv "${path}" "$b/"`;
530
+ for (const id of Object.keys(MOVED_SKILLS)) {
531
+ for (const scope of ['user', 'project']) {
532
+ const st = destState(ep, id, scope);
533
+ const flag = scope === 'project' ? ' --project' : '';
534
+ if (st.state === 'link' || st.state === 'not-a-folder') action(`${id}: ${st.dest} is ${st.state === 'link' ? 'a symbolic link' : 'not a folder'}`, moveLine(st.dest));
535
+ else if (st.state === 'user-managed') action(`${id}: ${st.dest} has no receipt (an older or hand-made copy)`, `${CLI} install ${id}${flag} --yes`);
536
+ else if (st.state === 'installed' && st.receipt.source && !existsSync(st.receipt.source)) action(`${id}: the receipt's source ${st.receipt.source} no longer exists`, `${CLI} update ${id}${flag} --yes`);
537
+ }
538
+ const hits = sameNameSkills(ep, id);
539
+ if (hits.length > 1) {
540
+ const keep = hits.find((h) => h.receipt) ?? hits[0];
541
+ for (const h of hits.filter((x) => x !== keep)) {
542
+ action(`${id}: two same-name skills agy loads, ${keep.path} and ${h.path}; agy keeps one without a word${hits[0] !== keep ? `, and ${hits[0].path} wins` : ''}`, moveLine(h.path));
543
+ }
544
+ }
545
+ }
546
+ const backups = listBackups(ep);
547
+ if (backups.length) info(`${backups.length} backup folder${backups.length === 1 ? '' : 's'} in ${tilde(ep.backups, ep.home)}, ${human(backups.reduce((s, b) => s + b.bytes, 0))} in all`, `${CLI} prune-backups --older-than 30`);
548
+ for (const plugin of [ep.userPlugin, ep.projectPlugin]) {
549
+ for (const id of Object.keys(MOVED_SKILLS)) {
550
+ const file = join(plugin, 'skills', id, 'SKILL.md');
551
+ let text = null;
552
+ try { text = readFileSync(file, 'utf8'); } catch { continue; }
553
+ if (!text.includes('wjgoarxiv-skills')) {
554
+ action(`${file} is the full skill from LitGravity 0.1.8 or earlier, where the current release has a stub`, `npx @litfamily/litgravity@latest install${plugin === ep.projectPlugin ? ' --scope project' : ''} --yes`);
555
+ break;
556
+ }
557
+ }
558
+ }
559
+ try {
560
+ const flag = JSON.parse(readFileSync(join(ep.data, 'extensions-notice.json'), 'utf8'));
561
+ if (flag.shown === false) info('the extensions note from the last LitGravity install waits for the next agy conversation');
562
+ } catch { /* no notice queued */ }
563
+ const runtime = oldRuntimeDir(ep.data);
564
+ if (existsSync(runtime)) info(`${runtime} holds engines cached by LitGravity 0.1.8 or earlier; nothing reads it now`, `rm -rf "${runtime}"`);
565
+ return out;
566
+ }
567
+
568
+ function listCmd({ ep, flags, print }) {
569
+ const rows = extensionRows(ep);
570
+ if (flags.json) {
571
+ print(JSON.stringify({ product: 'litgravity', extensions: rows, backups: ep.backups, cache: ep.cache }, null, 2));
572
+ return 0;
573
+ }
574
+ const label = (s) => (s.state === 'installed' ? `installed ${s.installed_at ?? ''} from ${s.source ?? '?'}` : s.state === 'absent' ? 'not installed' : s.state);
575
+ print(`LitGravity extensions (${Object.keys(MOVED_SKILLS).length}, from ${EXTENSION_SHELF})`);
576
+ for (const r of rows) {
577
+ print(`${r.id} [${r.family}]`);
578
+ print(` user ${label(r.user)}`);
579
+ if (r.project.state !== 'absent') print(` project ${label(r.project)}`);
580
+ for (const c of r.competing) print(` ${c === r.loads ? 'shadowed' : 'competing'} by ${c}`);
581
+ if (!r.competing.length && r.user.state !== 'absent' && r.project.state !== 'absent') print(` note both scopes hold a copy; agy loads ${r.loads}`);
582
+ }
583
+ print(`Install with: ${CLI} install <id> [--project] (a dry run; add --yes)`);
584
+ return 0;
585
+ }
586
+
587
+ function checkCmd({ ep, flags, print }) {
588
+ const found = checkFindings(ep);
589
+ const actions = found.filter((f) => f.level === 'action');
590
+ if (flags.json) {
591
+ print(JSON.stringify({ product: 'litgravity', ok: !actions.length, findings: found }, null, 2));
592
+ return actions.length ? 1 : 0;
593
+ }
594
+ print('LitGravity extensions check (read only)');
595
+ for (const f of found) {
596
+ print(`${f.level === 'action' ? 'ACTION' : 'INFO '} ${f.text}`);
597
+ if (f.fix) print(` fix: ${f.fix}`);
598
+ }
599
+ print(actions.length ? `${actions.length} thing${actions.length === 1 ? '' : 's'} need${actions.length === 1 ? 's' : ''} action; nothing was changed.` : 'Clean: nothing needs action.');
600
+ return actions.length ? 1 : 0;
601
+ }
602
+
603
+ export const EXTENSION_HELP = `Usage: litgravity extensions <verb> [options]
604
+
605
+ LitGravity installs the LitFamily extensions (the nine skills that make files) from wjgoarxiv-skills into agy's
606
+ skill folders. It checks for other same-name skills first, moves an existing copy whole into
607
+ ~/.gemini/extension-backups/<date>/, copies the skill in and writes a receipt (${RECEIPT}).
608
+ Every verb that writes is a dry run until you add --yes. Nothing is ever deleted except by prune-backups --yes.
609
+
610
+ Verbs
611
+ list Each extension: not installed, installed (receipt), user-managed, or competing (--json)
612
+ check Read only: duplicates, copies without a receipt, missing sources, backups; exit 1 if any need action
613
+ install <id...> Also --family <name> or --all
614
+ update [<id...>] Fetch the source, reinstall each installed extension whose files changed
615
+ remove <id...> Move a copy LitGravity installed into the backups; a folder without a receipt is refused
616
+ prune-backups List backups with sizes; --older-than <days> picks old ones; --yes deletes
617
+
618
+ Options
619
+ --yes Do it (otherwise print what would happen)
620
+ --project ./.agents/skills in this workspace (default: ~/.gemini/config/skills, every workspace)
621
+ --from <path> Use a wjgoarxiv-skills clone you have (default: LitGravity's own clone in ~/.cache/litgravity)
622
+ --allow-shadow Install even when another same-name skill exists (it stays; a warning is printed)
623
+ --json list and check`;
624
+
625
+ export async function extensions({ env = process.env, args = [], flags = {}, cwd = process.cwd(), print = console.log }) {
626
+ const [verb, ...rest] = args;
627
+ const ep = extensionPaths(env, cwd);
628
+ const scope = flags.scope === 'project' || flags.project ? 'project' : 'user';
629
+ const ctx = { ep, args: rest, flags, scope, print };
630
+ switch (verb) {
631
+ case 'list': return listCmd(ctx);
632
+ case 'check': return checkCmd(ctx);
633
+ case 'install': return install(ctx);
634
+ case 'update': return update(ctx);
635
+ case 'remove': return remove(ctx);
636
+ case 'prune-backups': return pruneBackups(ctx);
637
+ case undefined:
638
+ case 'help': print(EXTENSION_HELP); return 0;
639
+ default: print(`Unknown extensions verb: ${verb}\n\n${EXTENSION_HELP}`); return 2;
640
+ }
641
+ }
package/lib/install.mjs CHANGED
@@ -8,6 +8,7 @@ import { applyRuleFile, planRuleFile, writeAgentFileMode } from './agent-file.mj
8
8
  import { planStatusLine, applyStatusLine } from './statusline.mjs';
9
9
  import { firstLine } from '../plugin/lib/host-exec.mjs';
10
10
  import { extensionNotice, queueExtensionNotice } from '../plugin/hooks/lib/extensions.mjs';
11
+ import { checkFindings, extensionPaths } from './extension-manager.mjs';
11
12
 
12
13
  // Where a copy the user wants to keep goes. agy loads every folder in its plugins folder, so a copy saved beside the
13
14
  // plugin would come back as a second live LitGravity; LitGravity's own data folder is outside every place agy scans.
@@ -152,7 +153,9 @@ export async function install({ env = process.env, flags = {}, interactive = fal
152
153
  product: 'litgravity', version, scope, installedAt: new Date().toISOString(), host: `agy ${host}`, files: count, written,
153
154
  }, null, 2)}\n`);
154
155
  written.push(p.receipt);
155
- written.push(queueExtensionNotice(p.data, version));
156
+ // Existing users: a duplicate or an old copy without a receipt earns one line in the notice. Read only; nothing moves.
157
+ const findings = checkFindings(extensionPaths(env, cwd)).filter((f) => f.level === 'action').length;
158
+ written.push(queueExtensionNotice(p.data, version, { findings }));
156
159
 
157
160
  print('');
158
161
  print(`Installed: LitGravity ${readManifest(PLUGIN_DIR).version} (${count} files) at ${scope} scope.`);
@@ -163,6 +166,6 @@ export async function install({ env = process.env, flags = {}, interactive = fal
163
166
  print('Status: Ready. Start agy in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litgravity doctor`.');
164
167
  print('');
165
168
  print('LitFamily extensions');
166
- for (const line of extensionNotice(p.data)) print(` ${line}`);
169
+ for (const line of extensionNotice(p.data, { findings })) print(` ${line}`);
167
170
  return 0;
168
171
  }