@litfamily/litmuse 0.1.12 → 0.1.13

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.
package/bin/litmuse.mjs CHANGED
@@ -14,6 +14,7 @@ import { agentFileState, configCommand, readAgentFileSetting } from '../lib/agen
14
14
  import { buildCard, renderCard } from '../lib/stage-card.mjs';
15
15
  import { styleCommand } from '../lib/style.mjs';
16
16
  import { runRewindCli } from '../plugin/lib/rewind/collect.mjs';
17
+ import { extensionsCommand } from '../lib/extensions.mjs';
17
18
 
18
19
  const HELP = `LitMuse ${packageVersion()}: LitFamily workflows for Meta's Muse Code
19
20
 
@@ -28,6 +29,8 @@ Commands
28
29
  config agentFile on|off: the short LitFamily block in Muse's user rules file (acts at once)
29
30
  style eli5 | asd-ste100 | off | status: the answer style LitMuse adds to every session
30
31
  rewind Cross-session KPI board [--lang ko|en] [--detail] [--json] [--here] [--since 7d] [--max 12] [--session <id>]
32
+ extensions list | check | install | update | remove | prune-backups: the nine LitFamily extensions as Muse
33
+ user skills (litmuse extensions help; writes only with --yes)
31
34
  uninstall Remove the plugin from Muse and the staged bundle
32
35
  help This text
33
36
 
@@ -40,6 +43,7 @@ Options
40
43
  --no-agent-file install: leave Muse's user rules file alone for this run
41
44
  --offline Skip the npm update check
42
45
  --discard-modified uninstall: also remove a bundle edited after install
46
+ --from <p> extensions: use this wjgoarxiv-skills clone instead of LitMuse's cached one
43
47
  --version Print the version`;
44
48
 
45
49
  function parse(argv) {
@@ -56,6 +60,11 @@ function parse(argv) {
56
60
  else if (a === '--discard-modified') flags.discardModified = true;
57
61
  else if (a === '--card') flags.card = true;
58
62
  else if (a === '--scope') flags.scope = argv[++i];
63
+ else if (a === '--from') flags.from = argv[++i];
64
+ else if (a === '--family') flags.family = argv[++i];
65
+ else if (a === '--older-than') flags.olderThan = argv[++i];
66
+ else if (a === '--all') flags.all = true;
67
+ else if (a === '--allow-shadow') flags.allowShadow = true;
59
68
  else if (a === '--help' || a === '-h') flags.help = true;
60
69
  else if (a === '--version' || a === '-v') flags.version = true;
61
70
  else rest.push(a);
@@ -82,6 +91,7 @@ async function main() {
82
91
  print(packageVersion());
83
92
  return 0;
84
93
  }
94
+ if (command === 'extensions') return extensionsCommand({ args, flags, env, print });
85
95
  if (flags.help || command === 'help') {
86
96
  print(HELP);
87
97
  return 0;
package/lib/doctor.mjs CHANGED
@@ -9,6 +9,7 @@ import { stageState, packageVersion, PLUGIN_DIR } from './bundle.mjs';
9
9
  import { approvalStates } from './approvals.mjs';
10
10
  import { checkUpdate } from './update-check.mjs';
11
11
  import { agentFileRow } from './agent-file.mjs';
12
+ import { survey, findings, CLI } from './extensions.mjs';
12
13
 
13
14
  const CATALOG_CAP = 32 * 1024;
14
15
 
@@ -105,6 +106,16 @@ export async function doctor({ env = process.env, flags = {}, print = console.lo
105
106
  }
106
107
  }
107
108
 
109
+ if (mv) {
110
+ const sv = survey(env);
111
+ if (!sv.error) {
112
+ const n = findings(sv).length;
113
+ const installed = sv.rows.filter((r) => r.state === 'installed').length;
114
+ if (n) add('WARN', 'extensions', `${installed} of 9 installed; ${n} thing${n === 1 ? '' : 's'} to look at; run ${CLI} extensions check`, `${CLI} extensions check`);
115
+ else add('INFO', 'extensions', `${installed} of 9 installed, nothing to fix (${CLI} extensions list)`);
116
+ }
117
+ }
118
+
108
119
  const rules = agentFileRow({ env, version: packageVersion() });
109
120
  add(rules.status, rules.label, rules.detail, rules.fix);
110
121
 
@@ -0,0 +1,504 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, relative, resolve, sep } from 'node:path';
6
+ import { MOVED } from '../plugin/hooks/lib/moved.mjs';
7
+ import { SHELF } from '../plugin/hooks/lib/extensions.mjs';
8
+ import { assertSafeWritePath } from './guard.mjs';
9
+ import { muse } from './muse.mjs';
10
+
11
+ // `litmuse extensions <verb>`: the stubs' manual lines (look first, move an occupied folder aside, `muse skills
12
+ // install`) done in code. Muse owns the install and its receipt, the lock in $CONFIG_DIR/skills/.muse/lock.json;
13
+ // LitMuse only moves folders into $CONFIG_DIR/extension-backups/<stamp>/ and keeps a source clone in its own cache.
14
+ // Every write verb prints its plan and changes nothing without --yes. None of this runs in a hook.
15
+
16
+ export const CLI = 'npx @litfamily/litmuse';
17
+ const IDS = Object.keys(MOVED);
18
+ const STAMP = /^\d{8}-\d{6}(-\d+)?$/;
19
+
20
+ export function extPaths(env = process.env) {
21
+ const home = env.HOME || homedir();
22
+ const configHome = env.XDG_CONFIG_HOME || join(home, '.config');
23
+ const cacheHome = env.XDG_CACHE_HOME || join(home, '.cache');
24
+ const museDir = join(configHome, 'muse');
25
+ return {
26
+ home,
27
+ museDir,
28
+ skills: join(museDir, 'skills'),
29
+ lock: join(museDir, 'skills', '.muse', 'lock.json'),
30
+ backups: join(museDir, 'extension-backups'),
31
+ cache: join(cacheHome, 'litmuse', 'extensions-src'),
32
+ };
33
+ }
34
+
35
+ const lstatOrNull = (p) => { try { return lstatSync(p); } catch { return null; } };
36
+
37
+ function readLock(p) {
38
+ try {
39
+ const l = JSON.parse(readFileSync(p.lock, 'utf8'));
40
+ return l && typeof l.skills === 'object' && l.skills ? l.skills : {};
41
+ } catch {
42
+ return {};
43
+ }
44
+ }
45
+
46
+ // Muse prints paths with $CONFIG_DIR and $HOME placeholders, and project paths relative to the workspace.
47
+ function expand(path, p, cwd) {
48
+ const s = String(path);
49
+ if (s.startsWith('$CONFIG_DIR')) return join(p.museDir, s.slice('$CONFIG_DIR'.length));
50
+ if (s.startsWith('$HOME')) return join(p.home, s.slice('$HOME'.length));
51
+ return resolve(cwd, s);
52
+ }
53
+
54
+ // Muse copies a symlinked file as the file it points to and records that content, so a link is hashed the same way.
55
+ // A link to a folder or to nothing gets a value no receipt holds, which reads as a change.
56
+ function fileHashes(dir, base = dir, acc = new Map()) {
57
+ for (const name of readdirSync(dir)) {
58
+ const f = join(dir, name);
59
+ const rel = relative(base, f).split(sep).join('/');
60
+ let st = lstatSync(f);
61
+ if (st.isSymbolicLink()) {
62
+ try { st = statSync(f); } catch { acc.set(rel, 'unreadable link'); continue; }
63
+ if (!st.isFile()) { acc.set(rel, 'link to a folder'); continue; }
64
+ }
65
+ if (st.isDirectory()) fileHashes(f, base, acc);
66
+ else if (st.isFile()) acc.set(rel, `sha256:${createHash('sha256').update(readFileSync(f)).digest('hex')}`);
67
+ }
68
+ return acc;
69
+ }
70
+
71
+ // True when the source folder holds exactly the files, with the same hashes, that Muse recorded at install.
72
+ export function sameAsReceipt(sourceDir, entry) {
73
+ const have = fileHashes(sourceDir);
74
+ const recorded = Array.isArray(entry?.files) ? entry.files : [];
75
+ if (have.size !== recorded.length) return false;
76
+ return recorded.every((f) => have.get(f.relative_path) === f.sha256);
77
+ }
78
+
79
+ const ours = (id, entry) => Boolean(entry?.source?.path) && new RegExp(`[\\\\/]variants[\\\\/]litmuse[\\\\/]${id}$`).test(entry.source.path);
80
+
81
+ function dirSize(dir) {
82
+ let n = 0;
83
+ for (const name of readdirSync(dir)) {
84
+ const st = lstatSync(join(dir, name));
85
+ n += st.isDirectory() ? dirSize(join(dir, name)) : st.size;
86
+ }
87
+ return n;
88
+ }
89
+
90
+ export function humanSize(n) {
91
+ if (n < 1024) return `${n} B`;
92
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
93
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
94
+ }
95
+
96
+ export function listBackups(p) {
97
+ const st = lstatOrNull(p.backups);
98
+ if (!st || !st.isDirectory() || st.isSymbolicLink()) return [];
99
+ return readdirSync(p.backups).sort().filter((n) => STAMP.test(n)).map((name) => {
100
+ const dir = join(p.backups, name);
101
+ const s = lstatSync(dir);
102
+ if (!s.isDirectory() || s.isSymbolicLink()) return null;
103
+ return { name, dir, ids: readdirSync(dir).sort(), bytes: dirSize(dir), at: stampDate(name) };
104
+ }).filter(Boolean);
105
+ }
106
+
107
+ function stampDate(name) {
108
+ const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})/.exec(name);
109
+ return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]) : null;
110
+ }
111
+
112
+ function stamp(d = new Date()) {
113
+ const z = (n) => String(n).padStart(2, '0');
114
+ return `${d.getFullYear()}${z(d.getMonth() + 1)}${z(d.getDate())}-${z(d.getHours())}${z(d.getMinutes())}${z(d.getSeconds())}`;
115
+ }
116
+
117
+ // One dated folder per run, never reused: a second run in the same second gets -2, -3, ...
118
+ function newBackupDir(p) {
119
+ const base = stamp();
120
+ for (let i = 1; ; i += 1) {
121
+ const dir = join(p.backups, i === 1 ? base : `${base}-${i}`);
122
+ if (!existsSync(dir)) return dir;
123
+ }
124
+ }
125
+
126
+ // What Muse and the disk say about each extension id. Read only.
127
+ export function survey(env = process.env, { cwd = process.cwd(), from = null } = {}) {
128
+ const p = extPaths(env);
129
+ // The source to compare against without fetching: --from, or the cached clone when there is one.
130
+ const current = resolveSource({ env, flags: { from }, p });
131
+ const lock = readLock(p);
132
+ const listing = muse(env, ['skills', 'list', '--workspace', cwd, '--trust-workspace', '--json']);
133
+ if (listing.missing) return { error: 'muse was not found on PATH. Install Muse Code first, then run this again.' };
134
+ // Without the listing the same-name guard has nothing to look at, so stop rather than report a clean slate.
135
+ if (!listing.ok || !Array.isArray(listing.json?.skills)) {
136
+ const why = listing.json?.error?.message || (listing.stderr || listing.stdout).trim().split(/\r?\n/)[0] || `exit ${listing.status}`;
137
+ return { error: `muse skills list failed (${why}). Nothing was changed.` };
138
+ }
139
+ const skills = listing.json.skills;
140
+ const diagnostics = listing.json.diagnostics ?? [];
141
+ const rows = IDS.map((id) => {
142
+ const dest = join(p.skills, id);
143
+ const destSkill = join(dest, 'SKILL.md');
144
+ const entry = lock[id] ?? null;
145
+ const st = lstatOrNull(dest);
146
+ let state;
147
+ if (!st) state = entry ? 'record-only' : 'absent';
148
+ else if (st.isSymbolicLink()) state = 'symlinked';
149
+ else if (!st.isDirectory()) state = 'not-a-folder';
150
+ else if (!entry) state = 'user-managed';
151
+ else state = ours(id, entry) ? 'installed' : 'other-source';
152
+ const competing = [];
153
+ let live = null;
154
+ for (const s of skills) {
155
+ if (String(s.name ?? s.id) !== id || !['user', 'project'].includes(s.scope)) continue;
156
+ live = expand(s.path, p, cwd);
157
+ if (live !== destSkill) competing.push({ path: dirname(live), scope: s.scope, live: true });
158
+ }
159
+ for (const d of diagnostics) {
160
+ if (d.code !== 'skill-shadowed' || !new RegExp(`[\\\\/]${id}[\\\\/]SKILL\\.md$`).test(String(d.path))) continue;
161
+ const path = expand(d.path, p, cwd);
162
+ if (path !== destSkill) competing.push({ path: dirname(path), scope: d.scope, live: false });
163
+ }
164
+ const source = entry?.source?.path ?? null;
165
+ return {
166
+ id, family: MOVED[id].family, dest, state, competing,
167
+ shadowed: state === 'installed' && live !== destSkill,
168
+ receipt: entry ? { source, installedAt: entry.installed_at ?? null, updatedAt: entry.updated_at ?? null, files: entry.files?.length ?? 0 } : null,
169
+ sourceGone: Boolean(source) && !existsSync(source),
170
+ matchesCurrent: Boolean(current.variants) && Boolean(entry) && existsSync(join(current.variants, id, 'SKILL.md')) && sameAsReceipt(join(current.variants, id), entry),
171
+ entry,
172
+ };
173
+ });
174
+ return { p, rows, backups: listBackups(p) };
175
+ }
176
+
177
+ // The things `check` flags, each with the exact line that fixes it.
178
+ export function findings(sv) {
179
+ const out = [];
180
+ for (const r of sv.rows) {
181
+ if (r.state === 'user-managed') out.push({ id: r.id, what: `${r.dest} is a folder Muse has no record of (an older or hand-made copy)`, fix: `${CLI} extensions install ${r.id} --yes (moves it aside whole, then installs)` });
182
+ if (r.state === 'symlinked' || r.state === 'not-a-folder') out.push({ id: r.id, what: `${r.dest} is ${r.state === 'symlinked' ? 'a symbolic link' : 'not a folder'}; LitMuse will not move it`, fix: `look at where it points, then move ${r.dest} aside yourself` });
183
+ if (r.state === 'record-only') out.push({ id: r.id, what: `Muse still records ${r.id} but its folder is gone`, fix: `muse skills uninstall ${r.id} (deletes nothing, drops the record)` });
184
+ if (r.sourceGone && r.state === 'installed' && !r.matchesCurrent) out.push({ id: r.id, what: `the source Muse recorded, ${r.receipt.source}, no longer exists`, fix: `${CLI} extensions update ${r.id} --yes` });
185
+ // With no extension here, a same-name skill is simply the user's own; list shows it and install stops on it.
186
+ for (const c of r.state === 'absent' ? [] : r.competing) {
187
+ out.push(c.live
188
+ ? { id: r.id, what: `${c.path} (${c.scope}) outranks the extension in this folder, so Muse loads that copy`, fix: `move or rename ${c.path} to use the extension here` }
189
+ : { id: r.id, what: `${c.path} (${c.scope}) has the same name${c.live ? '' : ' and is shadowed'}`, fix: `keep one copy: move or rename ${c.path}` });
190
+ }
191
+ }
192
+ return out;
193
+ }
194
+
195
+ function git(args, opts = {}) {
196
+ const r = spawnSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 180000, ...opts });
197
+ return { ok: r.status === 0, missing: r.error?.code === 'ENOENT', err: (r.stderr || r.error?.message || '').trim() };
198
+ }
199
+
200
+ const fromHint = `Nothing was changed. Clone ${SHELF} yourself and pass --from <path to the clone>.`;
201
+
202
+ // Finds variants/litmuse. With --from it reads that clone and never writes it. Otherwise LitMuse keeps a shallow,
203
+ // sparse clone in its own cache; `fetch` refreshes it (or makes it). Without `fetch` (a dry run) it only looks.
204
+ export function resolveSource({ env = process.env, flags = {}, p = extPaths(env), fetch = false }) {
205
+ if (flags.from) {
206
+ const root = resolve(flags.from);
207
+ const variants = join(root, 'variants', 'litmuse');
208
+ if (!existsSync(variants)) return { error: `${root} has no variants/litmuse folder; point --from at a wjgoarxiv-skills clone. Nothing was changed.` };
209
+ return { variants, label: `${root} (--from)` };
210
+ }
211
+ const url = env.LITMUSE_EXTENSIONS_REPO || SHELF;
212
+ const variants = join(p.cache, 'variants', 'litmuse');
213
+ const have = existsSync(join(p.cache, '.git'));
214
+ if (!fetch) return have ? { variants, label: `${p.cache} (cached clone of ${url})`, stale: true } : { pending: true, planned: variants, label: `${url}, cloned into ${p.cache}` };
215
+ const cacheSt = lstatOrNull(p.cache);
216
+ if (cacheSt && (cacheSt.isSymbolicLink() || !cacheSt.isDirectory())) return { error: `${p.cache} is a link or not a folder; LitMuse will not use it. ${fromHint}` };
217
+ assertSafeWritePath(p.cache);
218
+ if (have) {
219
+ const f = git(['-C', p.cache, 'fetch', '--quiet', '--depth', '1', 'origin', 'HEAD']);
220
+ const c = f.ok ? git(['-C', p.cache, '-c', 'advice.detachedHead=false', 'checkout', '--quiet', '--detach', 'FETCH_HEAD']) : f;
221
+ if (!c.ok) return { error: `${f.missing ? 'git was not found on PATH' : `could not refresh ${p.cache} from ${url}`}${c.err ? ` (${c.err.split(/\r?\n/)[0]})` : ''}. ${fromHint}` };
222
+ } else {
223
+ mkdirSync(dirname(p.cache), { recursive: true });
224
+ const tmp = `${p.cache}.tmp-${process.pid}`;
225
+ const c = git(['clone', '--quiet', '--depth', '1', '--filter=blob:none', '--sparse', url, tmp]);
226
+ const s = c.ok ? git(['-C', tmp, 'sparse-checkout', 'set', 'variants/litmuse']) : c;
227
+ if (!s.ok) {
228
+ rmSync(tmp, { recursive: true, force: true });
229
+ return { error: `${c.missing ? 'git was not found on PATH' : `could not fetch ${url}`}${s.err ? ` (${s.err.split(/\r?\n/)[0]})` : ''}. ${fromHint}` };
230
+ }
231
+ renameSync(tmp, p.cache);
232
+ }
233
+ if (!existsSync(variants)) return { error: `${p.cache} has no variants/litmuse folder after the fetch. ${fromHint}` };
234
+ return { variants, label: `${p.cache} (${have ? 'refreshed' : 'new'} clone of ${url})` };
235
+ }
236
+
237
+ function targets(args, flags, { allDefault = false } = {}) {
238
+ if (flags.all || (allDefault && !args.length && !flags.family)) return { ids: IDS };
239
+ if (flags.family) {
240
+ const ids = IDS.filter((id) => MOVED[id].family === flags.family);
241
+ const fams = [...new Set(IDS.map((id) => MOVED[id].family))];
242
+ return ids.length ? { ids } : { error: `unknown family ${flags.family}; the families are ${fams.join(', ')}` };
243
+ }
244
+ const bad = args.filter((a) => !IDS.includes(a));
245
+ if (bad.length) return { error: `not a LitMuse extension: ${bad.join(', ')}. The nine: ${IDS.join(', ')}.` };
246
+ if (!args.length) return { error: 'name one or more extensions, or use --family <name> or --all' };
247
+ return { ids: [...new Set(args)] };
248
+ }
249
+
250
+ function stateText(r) {
251
+ switch (r.state) {
252
+ case 'installed': return `installed${r.shadowed ? ' (shadowed here)' : ''} · source ${r.receipt.source} · installed ${r.receipt.installedAt ?? '?'}${r.sourceGone ? ' · source missing' : ''}`;
253
+ case 'absent': return 'not installed';
254
+ case 'user-managed': return `user-managed folder, no Muse record: ${r.dest}`;
255
+ case 'other-source': return `installed by Muse from another source: ${r.receipt.source}`;
256
+ case 'record-only': return 'Muse record without a folder';
257
+ default: return `${r.state}: ${r.dest}`;
258
+ }
259
+ }
260
+
261
+ function listVerb(sv, flags, print) {
262
+ if (flags.json) {
263
+ print(JSON.stringify({
264
+ extensions: sv.rows.map(({ entry, ...r }) => r),
265
+ backups: sv.backups.map(({ name, dir, ids, bytes }) => ({ name, dir, ids, bytes })),
266
+ }, null, 2));
267
+ return 0;
268
+ }
269
+ print('LitFamily extensions for LitMuse (Muse user skills; Muse\'s lock is the receipt)');
270
+ for (const r of sv.rows) {
271
+ print(` ${r.id.padEnd(30)} ${stateText(r)}`);
272
+ for (const c of r.competing) print(` ${''.padEnd(30)} same name: ${c.path} (${c.scope}${c.live ? ', loaded' : ', shadowed'})`);
273
+ }
274
+ return 0;
275
+ }
276
+
277
+ // Not findings: a recorded source that is gone while the installed copy still matches the current source by hash.
278
+ export function notes(sv) {
279
+ return sv.rows.filter((r) => r.state === 'installed' && r.sourceGone && r.matchesCurrent).map((r) => ({
280
+ id: r.id,
281
+ what: `the source Muse recorded, ${r.receipt.source}, no longer exists; the installed copy matches the current source`,
282
+ hint: `${CLI} extensions remove ${r.id} --yes, then extensions install ${r.id} --yes, makes Muse record the current source`,
283
+ }));
284
+ }
285
+
286
+ function checkVerb(sv, print) {
287
+ const f = findings(sv);
288
+ const total = sv.backups.reduce((n, b) => n + b.bytes, 0);
289
+ if (!f.length) print('extensions check: nothing to fix.');
290
+ else {
291
+ print(`extensions check: ${f.length} thing${f.length === 1 ? '' : 's'} to look at.`);
292
+ for (const x of f) {
293
+ print(` ${x.id}: ${x.what}`);
294
+ print(` fix: ${x.fix}`);
295
+ }
296
+ }
297
+ for (const n of notes(sv)) {
298
+ print(` INFO ${n.id}: ${n.what}`);
299
+ print(` if wanted: ${n.hint}`);
300
+ }
301
+ if (sv.backups.length) print(`Backups: ${sv.backups.length} in ${sv.p.backups}, ${humanSize(total)} (list or delete them with ${CLI} extensions prune-backups).`);
302
+ return f.length ? 1 : 0;
303
+ }
304
+
305
+ // Install and update share this: refuse what LitMuse may not touch, move an occupied folder aside, let Muse copy.
306
+ function apply({ env, plan, p, flags, print, verb }) {
307
+ const blocked = plan.filter((x) => x.blocked);
308
+ for (const x of blocked) print(`STOP ${x.id}: ${x.blocked}`);
309
+ if (blocked.length) {
310
+ print('Nothing was changed.');
311
+ return 1;
312
+ }
313
+ const work = plan.filter((x) => x.action !== 'skip');
314
+ for (const x of plan) {
315
+ if (x.action === 'skip') { print(` ${x.id}: ${x.note}`); continue; }
316
+ for (const w of x.warn ?? []) print(` ${x.id}: warning: ${w}`);
317
+ if (x.moveAside) print(` ${x.id}: move ${x.dest} -> ${join(p.backups, '<stamp>', x.id)}`);
318
+ print(` ${x.id}: muse skills install ${x.src} --scope user`);
319
+ }
320
+ if (!work.length) return 0;
321
+ if (!flags.yes || flags.dryRun) {
322
+ print('');
323
+ print(`Dry run: nothing was moved or installed. Rerun with --yes to ${verb}.`);
324
+ return 0;
325
+ }
326
+ let backupDir = null;
327
+ for (const x of work) {
328
+ let moved = null;
329
+ if (x.moveAside) {
330
+ if (!backupDir) {
331
+ const bst = lstatOrNull(p.backups);
332
+ if (bst && (bst.isSymbolicLink() || !bst.isDirectory())) { print(`STOP ${p.backups} is a link or not a folder. Nothing more was changed.`); return 1; }
333
+ assertSafeWritePath(p.backups);
334
+ backupDir = newBackupDir(p);
335
+ mkdirSync(backupDir, { recursive: true });
336
+ }
337
+ moved = join(backupDir, x.id);
338
+ renameSync(x.dest, moved);
339
+ print(`moved ${x.dest} -> ${moved}`);
340
+ }
341
+ const r = muse(env, ['skills', 'install', x.src, '--scope', 'user', '--json']);
342
+ if (!r.ok) {
343
+ const why = r.json?.error?.message || (r.stderr || r.stdout).trim().split(/\r?\n/)[0];
344
+ if (moved && !existsSync(x.dest)) { renameSync(moved, x.dest); print(`put ${x.dest} back`); }
345
+ print(`FAIL muse skills install ${x.id}: ${why}. Stopped here; the extensions after it were left alone.`);
346
+ return 1;
347
+ }
348
+ print(`installed ${x.id} into ${x.dest}`);
349
+ }
350
+ print(`Done. Muse recorded each install in ${p.lock}. A new Muse session picks them up.`);
351
+ return 0;
352
+ }
353
+
354
+ function planFor(sv, ids, src, flags, { update = false } = {}) {
355
+ return ids.map((id) => {
356
+ const r = sv.rows.find((x) => x.id === id);
357
+ const srcDir = join(src.variants ?? src.planned, id);
358
+ const base = { id, dest: r.dest, src: srcDir };
359
+ if (r.state === 'symlinked' || r.state === 'not-a-folder') return { ...base, blocked: `${r.dest} is ${r.state === 'symlinked' ? 'a symbolic link' : 'not a folder'}; LitMuse will not move it` };
360
+ if (update) {
361
+ if (r.state === 'absent') return { ...base, action: 'skip', note: 'not installed (install it with extensions install)' };
362
+ if (r.state === 'record-only') return { ...base, action: 'skip', note: `folder gone; run muse skills uninstall ${id}` };
363
+ if (r.state !== 'installed') return { ...base, action: 'skip', note: `${stateText(r)}; left alone (extensions install moves it aside)` };
364
+ }
365
+ if (src.variants && !existsSync(join(srcDir, 'SKILL.md'))) return { ...base, blocked: `the source has no ${id} edition (${srcDir})` };
366
+ const others = r.competing.filter((c) => c.path !== r.dest);
367
+ if (others.length && !flags.allowShadow && !update) {
368
+ return { ...base, blocked: `another skill with this name is there: ${others.map((c) => `${c.path} (${c.scope})`).join(', ')}. LitMuse leaves it alone; move or rename it, or rerun with --allow-shadow to install anyway` };
369
+ }
370
+ const warn = others.map((c) => `${c.path} (${c.scope}) has the same name; ${c.scope === 'project' ? 'it outranks the extension in that project' : 'Muse will report it as shadowed'}`);
371
+ if (r.state === 'installed' && src.variants && r.entry && sameAsReceipt(srcDir, r.entry)) {
372
+ // A new path with the same files is still current; Muse's lock is Muse's to write, so it keeps the old path.
373
+ return { ...base, action: 'skip', note: `current (same files as ${r.receipt.source})` };
374
+ }
375
+ if (r.state === 'installed' && !src.variants) {
376
+ return { ...base, action: 'skip', note: 'compared after the source is fetched' };
377
+ }
378
+ return { ...base, action: 'install', moveAside: r.state !== 'absent' && r.state !== 'record-only', warn };
379
+ });
380
+ }
381
+
382
+ function installVerb({ env, args, flags, print, cwd, update }) {
383
+ const t = targets(args, flags, { allDefault: update });
384
+ if (t.error) { print(t.error); return 2; }
385
+ const p = extPaths(env);
386
+ const src = resolveSource({ env, flags, p, fetch: Boolean(flags.yes && !flags.dryRun) });
387
+ if (src.error) { print(`FAIL ${src.error}`); return 1; }
388
+ const sv = survey(env, { cwd });
389
+ if (sv.error) { print(`FAIL ${sv.error}`); return 1; }
390
+ print(`Source: ${src.label}${src.pending ? ' (on --yes)' : ''}`);
391
+ if (src.stale) print('Compared with the cached copy; --yes fetches first, so the result may differ.');
392
+ const plan = planFor(sv, t.ids, src, flags, { update });
393
+ return apply({ env, plan, p, flags, print, verb: update ? 'update' : 'install' });
394
+ }
395
+
396
+ function removeVerb({ env, args, flags, print, cwd }) {
397
+ const t = targets(args, flags);
398
+ if (t.error) { print(t.error); return 2; }
399
+ const sv = survey(env, { cwd });
400
+ if (sv.error) { print(`FAIL ${sv.error}`); return 1; }
401
+ const p = sv.p;
402
+ const plan = t.ids.map((id) => sv.rows.find((r) => r.id === id));
403
+ let refused = 0;
404
+ for (const r of plan) {
405
+ if (r.state === 'installed') print(` ${r.id}: move ${r.dest} -> ${join(p.backups, '<stamp>', r.id)}, then muse skills uninstall ${r.id}`);
406
+ else if (r.state === 'record-only') print(` ${r.id}: muse skills uninstall ${r.id} (the folder is already gone)`);
407
+ else if (r.state === 'absent') print(` ${r.id}: not installed`);
408
+ else { refused += 1; print(`REFUSED ${r.id}: ${stateText(r)}. LitMuse removes only a copy Muse installed from a wjgoarxiv-skills edition; move ${r.dest} yourself if you want it gone.`); }
409
+ }
410
+ if (refused) { print('Nothing was changed.'); return 1; }
411
+ const work = plan.filter((r) => r.state === 'installed' || r.state === 'record-only');
412
+ if (!work.length) return 0;
413
+ if (!flags.yes || flags.dryRun) {
414
+ print('');
415
+ print('Dry run: nothing was moved or uninstalled. Rerun with --yes to remove.');
416
+ return 0;
417
+ }
418
+ let backupDir = null;
419
+ for (const r of work) {
420
+ if (r.state === 'installed') {
421
+ if (!backupDir) {
422
+ const bst = lstatOrNull(p.backups);
423
+ if (bst && (bst.isSymbolicLink() || !bst.isDirectory())) { print(`STOP ${p.backups} is a link or not a folder.`); return 1; }
424
+ assertSafeWritePath(p.backups);
425
+ backupDir = newBackupDir(p);
426
+ mkdirSync(backupDir, { recursive: true });
427
+ }
428
+ renameSync(r.dest, join(backupDir, r.id));
429
+ print(`moved ${r.dest} -> ${join(backupDir, r.id)}`);
430
+ }
431
+ const u = muse(env, ['skills', 'uninstall', r.id, '--json']);
432
+ if (!u.ok) { print(`FAIL muse skills uninstall ${r.id}: ${u.json?.error?.message || u.stderr.trim()}`); return 1; }
433
+ print(`Muse dropped its record of ${r.id}`);
434
+ }
435
+ print('Done. Nothing was deleted; the folders are in the backup above.');
436
+ return 0;
437
+ }
438
+
439
+ function pruneVerb({ env, flags, print }) {
440
+ const p = extPaths(env);
441
+ const bst = lstatOrNull(p.backups);
442
+ if (bst && (bst.isSymbolicLink() || !bst.isDirectory())) { print(`FAIL ${p.backups} is a link or not a folder; LitMuse will not delete through it.`); return 1; }
443
+ const all = listBackups(p);
444
+ const days = flags.olderThan == null ? null : Number(flags.olderThan);
445
+ if (days != null && !(days >= 0)) { print('--older-than takes a number of days'); return 2; }
446
+ const cutoff = days == null ? Infinity : Date.now() - days * 86400000;
447
+ const pick = all.filter((b) => days == null || (b.at && b.at.getTime() < cutoff));
448
+ if (!all.length) { print(`No backups in ${p.backups}.`); return 0; }
449
+ print(`Backups in ${p.backups}:`);
450
+ for (const b of all) print(` ${pick.includes(b) ? '*' : ' '} ${b.name} ${humanSize(b.bytes).padStart(9)} ${b.ids.join(', ')}`);
451
+ const bytes = pick.reduce((n, b) => n + b.bytes, 0);
452
+ if (!pick.length) { print(`None is older than ${days} days.`); return 0; }
453
+ if (!flags.yes || flags.dryRun) {
454
+ print('');
455
+ print(`Dry run: ${pick.length} marked * (${humanSize(bytes)}) would be deleted. Rerun with --yes to delete them.`);
456
+ return 0;
457
+ }
458
+ const realRoot = realpathSync(p.backups);
459
+ for (const b of pick) {
460
+ const st = lstatSync(b.dir);
461
+ if (st.isSymbolicLink() || !st.isDirectory() || dirname(realpathSync(b.dir)) !== realRoot) { print(`skipped ${b.dir}: not a plain folder inside ${p.backups}`); continue; }
462
+ rmSync(b.dir, { recursive: true });
463
+ print(`deleted ${b.dir}`);
464
+ }
465
+ print(`Freed ${humanSize(bytes)}.`);
466
+ return 0;
467
+ }
468
+
469
+ export const EXT_HELP = `Usage: litmuse extensions <verb> [options]
470
+
471
+ The nine file-making skills are LitFamily extensions, installed as Muse user skills from the Muse editions in
472
+ wjgoarxiv-skills. These verbs run the stubs' lines for you: look first, move an occupied folder aside into
473
+ $CONFIG_DIR/extension-backups/<stamp>/, then muse skills install. Muse's lock ($CONFIG_DIR/skills/.muse/lock.json)
474
+ is the receipt. Every write verb shows its plan and changes nothing until you add --yes.
475
+
476
+ Verbs
477
+ list [--json] Each extension: not installed, installed (source, time), user-managed, same-name copies
478
+ check What needs a look, each with the line that fixes it (exit 1 when something does)
479
+ install <id...|--family f|--all> Move an existing folder aside, then muse skills install (stops on a same-name skill elsewhere)
480
+ update [<id...>|--all] Refresh the source; reinstall each installed extension whose files changed
481
+ remove <id...> Move the folder aside, then muse skills uninstall; refuses a folder Muse did not install
482
+ prune-backups [--older-than <d>] List the backups with sizes; delete them only with --yes
483
+
484
+ Options
485
+ --yes Do it (without it, every write verb is a dry run)
486
+ --from <path> Use your own wjgoarxiv-skills clone instead of LitMuse's cached clone
487
+ --allow-shadow Install even when a same-name skill sits in another folder (it is never touched)
488
+ --family <name> decks, documents, figures, design or video-covers`;
489
+
490
+ export async function extensionsCommand({ args = [], flags = {}, env = process.env, print = console.log, cwd = process.cwd() }) {
491
+ const [verb, ...rest] = args;
492
+ if (!verb || verb === 'help' || flags.help) { print(EXT_HELP); return 0; }
493
+ if (verb === 'list' || verb === 'check') {
494
+ const sv = survey(env, { cwd, from: flags.from });
495
+ if (sv.error) { print(`FAIL ${sv.error}`); return 1; }
496
+ return verb === 'list' ? listVerb(sv, flags, print) : checkVerb(sv, print);
497
+ }
498
+ if (verb === 'install') return installVerb({ env, args: rest, flags, print, cwd, update: false });
499
+ if (verb === 'update') return installVerb({ env, args: rest, flags, print, cwd, update: true });
500
+ if (verb === 'remove') return removeVerb({ env, args: rest, flags, print, cwd });
501
+ if (verb === 'prune-backups') return pruneVerb({ env, flags, print });
502
+ print(`Unknown extensions verb: ${verb}\n\n${EXT_HELP}`);
503
+ return 2;
504
+ }
package/lib/install.mjs CHANGED
@@ -8,6 +8,7 @@ import { expectedApprovals, approvalStates } from './approvals.mjs';
8
8
  import { agentFilePlan, installAgentFile } from './agent-file.mjs';
9
9
  import { MOVED, movedSkill, installLine } from '../plugin/hooks/lib/moved.mjs';
10
10
  import { SHELF, extensionsNotice, leftoverRuntime } from '../plugin/hooks/lib/extensions.mjs';
11
+ import { survey, findings, CLI } from './extensions.mjs';
11
12
 
12
13
  function remedy(state, detail, p) {
13
14
  const saved = `${p.stage}.saved-${new Date().toISOString().slice(0, 10)}`;
@@ -29,6 +30,16 @@ function extensionRemedy(changed = [], p) {
29
30
  });
30
31
  }
31
32
 
33
+ // Printed after the notice above, from the CLI side: that notice lives in the hook library, and every change there
34
+ // makes Muse ask the user to approve all ten hooks again.
35
+ function extensionLines(env) {
36
+ const lines = [` Muse refuses a folder that is already there. \`${CLI} extensions install <skill>\` moves an old copy aside first, then installs (it shows the plan; add --yes to run it).`];
37
+ const sv = survey(env);
38
+ const n = sv.error ? 0 : findings(sv).length;
39
+ if (n) lines.push(` ${n} thing${n === 1 ? '' : 's'} in your extension folders need${n === 1 ? 's' : ''} a look: run \`${CLI} extensions check\`.`);
40
+ return lines;
41
+ }
42
+
32
43
  function stamp() {
33
44
  return new Date().toISOString().replace(/[:.]/g, '-');
34
45
  }
@@ -212,6 +223,7 @@ export async function install({ env = process.env, flags = {}, interactive = fal
212
223
  for (const w of written) print(` ${w}`);
213
224
  print('');
214
225
  for (const line of extensionsNotice({ leftovers })) print(line);
226
+ for (const line of extensionLines(env)) print(line);
215
227
  print('');
216
228
  print(left === 0
217
229
  ? 'Status: Ready. Start Muse in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litmuse doctor`.'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litfamily/litmuse",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "Installer for LitMuse: skills, hooks and agents that help Meta's Muse Code plan, build, check and hand off work.",
5
5
  "keywords": [
6
6
  "muse",
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "name": "litmuse",
4
4
  "displayName": "LitMuse",
5
- "version": "0.1.12",
5
+ "version": "0.1.13",
6
6
  "description": "LitFamily workflows for Muse Code: bare lit activation, planning, evidence-bound execution, review, research, handoff and Korean prose care.",
7
7
  "compat": {
8
8
  "source": "native",