@litfamily/litmuse 0.1.20 → 0.1.22

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.
@@ -1,6 +1,7 @@
1
1
  import { chmodSync, lstatSync, readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { readConfig, writeConfig } from './config.mjs';
4
5
  import { paths } from './paths.mjs';
5
6
  import { packageVersion } from './bundle.mjs';
6
7
  import { writeFileAtomic, copyFileAtomic } from './safe-write.mjs';
@@ -22,17 +23,14 @@ const BLOCK_FILE = join(dirname(fileURLToPath(import.meta.url)), 'agent-file-blo
22
23
  const CONFIG_CMD = 'npx @litfamily/litmuse config agentFile';
23
24
  const QUESTION = 'Add the short LitFamily block to your Muse user rules file? Your own text stays as it is. [Y/n] ';
24
25
 
25
- export const agentFileBody = () => readFileSync(BLOCK_FILE, 'utf8');
26
+ const CARD = {
27
+ title: 'Rules file',
28
+ note: 'Adds the short LitFamily block to your Muse user rules file. Your own text stays as it is; No leaves the file alone, and later installs stop asking.',
29
+ yes: 'add',
30
+ no: 'off',
31
+ };
26
32
 
27
- function readConfig(env) {
28
- try {
29
- const file = paths(env).config;
30
- if (lstatSync(file).isSymbolicLink()) return {};
31
- return JSON.parse(readFileSync(file, 'utf8')) ?? {};
32
- } catch {
33
- return {};
34
- }
35
- }
33
+ export const agentFileBody = () => readFileSync(BLOCK_FILE, 'utf8');
36
34
 
37
35
  /** `{mode, stored}`: `mode` is what acts (LITMUSE_AGENT_FILE, else the stored value, else on); `stored` is only what the user chose. */
38
36
  export function readAgentFileSetting(env = process.env) {
@@ -44,7 +42,7 @@ export function readAgentFileSetting(env = process.env) {
44
42
 
45
43
  export function writeAgentFileSetting(env, mode) {
46
44
  if (!AGENT_FILE_MODES.includes(mode)) throw new Error(`agentFile takes one of: ${AGENT_FILE_MODES.join(', ')}`);
47
- writeFileAtomic(paths(env).config, `${JSON.stringify({ ...readConfig(env), agentFile: mode }, null, 2)}\n`);
45
+ writeConfig(env, { agentFile: mode });
48
46
  }
49
47
 
50
48
  // 'missing', 'file', 'symlink' or 'other', without following a link.
@@ -160,8 +158,15 @@ export function agentFilePlan({ env, flags }) {
160
158
  return `Would add the LitFamily block to ${path} (asks first; --yes adds it, --no-agent-file skips)`;
161
159
  }
162
160
 
161
+ /** True when the install step would ask about the block (a rules file LitMuse cannot write is reported, never asked about). */
162
+ export function agentFileAsks({ env, flags, interactive, ask, version }) {
163
+ const { mode, stored } = readAgentFileSetting(env);
164
+ if (flags.noAgentFile || mode === 'off' || flags.yes || stored === 'on' || !interactive || !ask) return false;
165
+ return agentFileState({ path: paths(env).museRules, version }) === 'absent';
166
+ }
167
+
163
168
  /** The install step: adds or refreshes the block when the setting and the user's answer allow it. Returns the paths it wrote. */
164
- export async function installAgentFile({ env, flags, interactive, ask, print, version, backupDir }) {
169
+ export async function installAgentFile({ env, flags, interactive, ask, print, version, backupDir, tag }) {
165
170
  const path = paths(env).museRules;
166
171
  const { mode, stored } = readAgentFileSetting(env);
167
172
  if (flags.noAgentFile) {
@@ -183,7 +188,7 @@ export async function installAgentFile({ env, flags, interactive, ask, print, ve
183
188
  print(`AGENT_FILE: skipped (add the LitFamily block to ${path}: ${CONFIG_CMD} on)`);
184
189
  return [];
185
190
  }
186
- if (!(await ask(QUESTION, { defaultYes: true }))) {
191
+ if (!(await ask(QUESTION, { defaultYes: true, card: { ...CARD, tag } }))) {
187
192
  writeAgentFileSetting(env, 'off');
188
193
  print(`AGENT_FILE: off (turn on later: ${CONFIG_CMD} on)`);
189
194
  return [];
@@ -0,0 +1,71 @@
1
+ // `litmuse install --agent`: the install guide a coding agent follows and its user can read. Plain text, the same bytes
2
+ // everywhere; printing it reads no setting and starts nothing. The READMEs carry the same steps as a prompt, and
3
+ // test/agent-guide.test.mjs binds the guide, the parser, the installer's questions and both prompts.
4
+ import { CAP_LEFT, CAP_RIGHT } from './glyphs.mjs';
5
+ import { FONT_FILES } from './guard.mjs';
6
+ import { NPX } from './flags.mjs';
7
+
8
+ export const AGENT_LINE = `Agent? See ${NPX} install --agent.`;
9
+ // For a card too narrow for the line above.
10
+ export const AGENT_LINE_SHORT = 'Agent? See install --agent.';
11
+ export const PILL = `${CAP_LEFT} LIT ${CAP_RIGHT}`;
12
+
13
+ export const COMMANDS = Object.freeze({
14
+ preview: `${NPX} install --dry-run --round`,
15
+ install: `${NPX} install --yes --round`,
16
+ update: `${NPX} update --yes --round`,
17
+ doctor: `${NPX} doctor`,
18
+ card: `${NPX} status --card`,
19
+ round: `${NPX} install --yes --glyphs round`,
20
+ square: `${NPX} install --yes --glyphs square`,
21
+ auto: `${NPX} install --yes --glyphs auto`,
22
+ });
23
+
24
+ // `card` is the title of the installer's own question card; the last two are choices the installer takes as flags only.
25
+ export const QUESTIONS = Object.freeze([
26
+ { card: 'Rules file', ask: "Add the short LitFamily block to Muse's user rules file?", base: 'yes', other: 'For no, add --no-agent-file to every install and update command below; it lasts one run.', flag: '--no-agent-file' },
27
+ { card: 'Approvals', ask: 'Approve the LitMuse hooks and agents?', base: 'no', other: 'Your user can choose it later with the "muse plugins approve" commands the install prints.' },
28
+ { ask: 'Install for every project (user scope)?', base: 'yes', other: 'For the current project only, add --scope project to the install line.', flag: '--scope project' },
29
+ { ask: 'Round or square ends on the status card?', base: 'auto', other: 'Add --glyphs round or --glyphs square; step 7 asks this again with a picture.', flag: '--glyphs round' },
30
+ ]);
31
+
32
+ export const agentGuide = () => `LitMuse install guide for coding agents
33
+
34
+ If you are a coding agent and your user asked you to install LitMuse, follow these steps. They are written for your user to read too.
35
+
36
+ 1. Preview. LitMuse needs Node.js 20 or newer and Muse Code ("muse --version").
37
+ ${COMMANDS.preview}
38
+ Show your user what it would change.
39
+
40
+ 2. Ask. Show your user these questions and their defaults.
41
+ - Keep every default? Default: yes.
42
+ ${QUESTIONS.map((q) => ` - ${q.ask} Default: ${q.base}. ${q.other}`).join('\n')}
43
+ - Icon font: --round adds ${FONT_FILES.font} and its licence file (${FONT_FILES.license}) to ~/Library/Fonts on macOS or \${XDG_DATA_HOME:-~/.local/share}/fonts on Linux, only when no icon font is here. On Windows it adds none.
44
+ - What your user will see: the status card. It needs no flag: your user runs "${COMMANDS.card}" in their own terminal, with --watch to keep it open.
45
+
46
+ 3. Wait for your user's yes. Use only this package; add no other source, and do not approve hooks, trust or sign-in for your user.
47
+
48
+ 4. Install.
49
+ ${COMMANDS.install}
50
+
51
+ 5. Update, later.
52
+ ${COMMANDS.update}
53
+
54
+ 6. Check. The install must print a line that starts with ROUND_ENDS:. Then run
55
+ ${COMMANDS.doctor}
56
+ It passes with "LitMuse doctor: PASS". Until your user approves the hooks and agents it says "LitMuse: installed, <n> approvals needed" and exits 1; that is expected. A line that starts with FAIL is a failed step.
57
+ If a step fails, show your user the lines and stop.
58
+
59
+ 7. Rounded ends. Show your user this and ask if both ends are round: ${PILL}
60
+ Ask for an answer from the terminal that will show the status card.
61
+ - Round: ${COMMANDS.round}
62
+ - Boxes or question marks: ${COMMANDS.square}
63
+ An installed symbols font alone is no proof that a terminal uses it. For round ends your user sets the terminal's own font to a full Nerd Font, or adds Symbols Nerd Font Mono as its fallback font (iTerm2: Non-ASCII Font, VS Code: terminal.integrated.fontFamily, kitty: symbol_map). Terminal.app has no fallback setting, so it needs a full Nerd Font as its font.
64
+ - Over SSH, on a phone, or no answer: leave it.
65
+ - Undo: ${COMMANDS.auto}
66
+
67
+ 8. Only your user can
68
+ - approve: run the "muse plugins approve" commands the install printed, then run the doctor command again;
69
+ - restart: quit Muse if it is open and start it again;
70
+ - sign in to Muse, and trust a folder or Git repository when Muse or Git asks.
71
+ `;
@@ -0,0 +1,109 @@
1
+ // What the framed card shows beyond the status record: the planned skills, the git branch, the tool that ran last
2
+ // and how full the context is. All of it is read from records that already exist (LitMuse's own stage record
3
+ // and ledger, Muse's session log and model catalog, .git/HEAD); anything missing stays null and is left out.
4
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
7
+ import { loadStage } from './stage-card.mjs';
8
+ import { paths } from './paths.mjs';
9
+ import { STACK_DROP_MS, readStack } from '../plugin/hooks/lib/workflow-stack.mjs';
10
+
11
+ const TAIL_BYTES = 256 * 1024;
12
+ const RAN_LATELY_MS = 15 * 60 * 1000;
13
+
14
+ // The parsed lines at the end of a JSON-lines file; a link, a missing file or a cut line reads as nothing.
15
+ function tailLines(path, bytes) {
16
+ let fd;
17
+ try {
18
+ if (!lstatSync(path).isFile()) return [];
19
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
20
+ const { size } = fstatSync(fd);
21
+ const buffer = Buffer.alloc(Math.min(size, bytes));
22
+ readSync(fd, buffer, 0, buffer.length, size - buffer.length);
23
+ return buffer.toString('utf8').split('\n').flatMap((line) => {
24
+ try {
25
+ const parsed = JSON.parse(line);
26
+ return parsed && typeof parsed === 'object' ? [parsed] : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ });
31
+ } catch {
32
+ return [];
33
+ } finally {
34
+ if (fd !== undefined) closeSync(fd);
35
+ }
36
+ }
37
+
38
+ // Muse files a session under the day its id was made; the id's first 48 bits are that time.
39
+ function sessionLog(session, env) {
40
+ const hex = /^([0-9a-f]{8})-([0-9a-f]{4})-7/i.exec(session ?? '');
41
+ if (!hex) return null;
42
+ const made = Number.parseInt(hex[1] + hex[2], 16);
43
+ const store = env.LITMUSE_SESSION_STORE || join(env.XDG_DATA_HOME || join(env.HOME || homedir(), '.local', 'share'), 'muse', 'sessions');
44
+ for (const days of [0, -1, 1]) {
45
+ const day = new Date(made + days * 86_400_000).toISOString().slice(0, 10).split('-');
46
+ const path = join(store, ...day, session, 'session.jsonl');
47
+ if (existsSync(path)) return path;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ // The session log does not name its model, so the window is known only when every listed chat model has the same one.
53
+ function contextWindow(env) {
54
+ try {
55
+ const dir = paths(env).museCatalogDir;
56
+ const rows = readdirSync(dir).filter((file) => file.endsWith('.json')).flatMap((file) => JSON.parse(readFileSync(join(dir, file), 'utf8')).rows ?? []);
57
+ const sizes = new Set(rows.filter((row) => row.visibility === 'visible' && row.context_limit).map((row) => row.context_limit));
58
+ return sizes.size === 1 ? [...sizes][0] : null;
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ // How full the context is: Muse's own estimate of the prompt of its last model call. The call's raw counters are not
65
+ // used, because providers differ on whether cached tokens are inside them.
66
+ function contextNow(lines, env) {
67
+ const used = lines.findLast((line) => line.payload?.kind === 'run' && line.payload.event?.kind === 'model_completed')?.payload.event.estimated_prompt_tokens;
68
+ if (!Number.isInteger(used) || used <= 0) return null;
69
+ const limit = contextWindow(env);
70
+ return { used, percent: limit ? Math.min(100, Math.round((used / limit) * 100)) : null };
71
+ }
72
+
73
+ // The last tool call that ended. The ledger is written after each call, so a call still running is not in it.
74
+ function lastTool(ledger, now) {
75
+ const last = ledger.findLast((entry) => /^PostToolUse/.test(entry.event ?? '') && typeof entry.tool === 'string');
76
+ const ms = last ? now - Date.parse(last.ts) : NaN;
77
+ return ms <= RAN_LATELY_MS ? { name: last.tool, ms, ok: last.ok !== false } : null;
78
+ }
79
+
80
+ export function gitBranch(cwd) {
81
+ try {
82
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
83
+ const git = join(dir, '.git');
84
+ if (existsSync(git)) {
85
+ const link = statSync(git).isFile() ? /^gitdir: (.+)$/m.exec(readFileSync(git, 'utf8'))?.[1].trim() : git;
86
+ const head = readFileSync(join(isAbsolute(link) ? link : resolve(dir, link), 'HEAD'), 'utf8').slice(0, 300).trim();
87
+ return /^ref: refs\/heads\/(.+)$/.exec(head)?.[1] ?? (/^[0-9a-f]{7,}$/i.test(head) ? head.slice(0, 7) : null);
88
+ }
89
+ if (dir === dirname(dir)) return null;
90
+ }
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ export function cardFacts({ cwd = process.cwd(), card, env = process.env, now = Date.now() }) {
97
+ const rec = loadStage({ cwd, session: card.session ?? undefined, env });
98
+ const log = card.session ? sessionLog(card.session, env) : null;
99
+ const id = String(card.session ?? '').replace(/[^A-Za-z0-9_-]/g, '_');
100
+ const ledger = id ? tailLines(join(rec?.cwd ?? cwd, '.litmuse', 'ledger', `${id}.jsonl`), 16 * 1024) : [];
101
+ const planned = Array.isArray(rec?.skills) ? rec.skills.map(String) : [];
102
+ return {
103
+ frames: card.session ? readStack(cwd, card.session).frames.filter((f) => f.stage && now - Date.parse(f.at) <= STACK_DROP_MS) : [],
104
+ skills: card.active ? [...new Set([card.route, ...planned])] : [],
105
+ tool: card.active ? lastTool(ledger, now) : null,
106
+ ctx: log ? contextNow(tailLines(log, TAIL_BYTES), env) : null,
107
+ branch: gitBranch(cwd),
108
+ };
109
+ }
package/lib/card-view.mjs CHANGED
@@ -1,97 +1,58 @@
1
- // The status card as a person's terminal shows it: one print with the sunset beside the words, or, with --watch, a
2
- // full-screen card that moves while work goes on. A pipe, --json, NO_COLOR, fewer colours, a light background and a
3
- // narrow terminal never reach the scene.
4
- import { buildCard, cardLight, cardWorking, renderCard } from './stage-card.mjs';
5
- import { colourDepth, litPill, markFor, pillLabel, pillWidth, termColumns } from './mark.mjs';
6
- import { BRAND, MAX_WIDTH, STILL_T, SUN_ROWS, SUN_W, gradedPill, ink, mix, motionOff, neon, paint, paintRows, place, roundCaps, rowCells, sceneOn, wrapRow } from './sunset.mjs';
1
+ // The status card as a person's terminal shows it: one print, or, with --watch, a full-screen card that moves while work
2
+ // goes on. A dark truecolor terminal with room gets the framed card; a pipe, --json, NO_COLOR, fewer colours, a light
3
+ // background and a narrow terminal get the plain one.
4
+ import { buildCard, cardWorking, renderCard } from './stage-card.mjs';
5
+ import { cardFacts } from './card-facts.mjs';
6
+ import { cardLines, composeCard } from './framed-card.mjs';
7
+ import { roundGlyphs } from './glyphs.mjs';
8
+ import { colourDepth, litPill, markFor, pillWidth, termColumns } from './mark.mjs';
9
+ import { MAX_WIDTH, STILL_T, motionOff, sceneOn, wrapRow } from './sunset.mjs';
7
10
 
8
11
  const ESC = '\u001b';
9
12
  export const READ_MS = 1000;
10
13
  export const FRAME_MS = 125;
11
14
 
12
- // The terminal as the card sees it. `scene` is off wherever today's output must stay as it is.
15
+ // The terminal as the card sees it. `framed` is off wherever the plain card must stay as it is.
13
16
  const terminal = (env, stream) => {
14
17
  const tty = stream?.isTTY === true;
15
18
  const depth = colourDepth({ env, isTTY: tty });
16
19
  const cols = termColumns({ env, stream });
17
- return { tty, depth, cols, scene: sceneOn({ depth, env, cols }), caps: roundCaps(env) };
20
+ // The last column stays empty: some terminals wrap on it.
21
+ return { tty, depth, cols, framed: sceneOn({ depth, env, cols }), width: Math.min(MAX_WIDTH, cols - 1) };
18
22
  };
19
23
 
20
- const cardRows = (card, term, version, cols = term.cols) => {
21
- const pill = !term.tty ? null : term.scene ? gradedPill(pillLabel(version), BRAND, term.caps) : litPill(version, term.depth);
22
- return renderCard(card, {
23
- badge: pill && { text: pill, width: pillWidth(version) }, cols, dress: term.scene ? { caps: term.caps } : null,
24
- }).split('\n');
24
+ const plainRows = (card, term, version) => {
25
+ const pill = term.tty ? litPill(version, term.depth) : null;
26
+ return renderCard(card, { badge: pill && { text: pill, width: pillWidth(version) }, cols: term.cols }).split('\n');
25
27
  };
26
28
 
27
- // `litmuse status --card`. The mark's tagline and the blank row under it lend the sun room over a short card.
28
- export function cardText(card, { env = process.env, stream = process.stdout, version }) {
29
+ const framed = (card, term, { env, cwd, version, now, working }) => composeCard(card, cardFacts({ cwd, card, env, now }), { width: term.width, round: roundGlyphs(env), working, version });
30
+
31
+ // `litmuse status --card`.
32
+ export function cardText(card, { env = process.env, stream = process.stdout, cwd = process.cwd(), version, now = card.now ?? Date.now() }) {
29
33
  const term = terminal(env, stream);
30
34
  const mark = term.tty ? `${markFor({ env, stream })}\n`.split('\n').slice(0, -1) : [];
31
- const rows = cardRows(card, term, version);
32
- const light = term.scene ? cardLight(card) : null;
33
- if (!light) return [...mark, ...rows].join('\n');
34
- const art = mark.slice(0, -2);
35
- // The last column stays empty: some terminals wrap on it.
36
- const width = Math.min(MAX_WIDTH, term.cols - 1);
37
- return [...art, ...paintRows([...mark.slice(-2), ...rows], width, { ...light, t: light.dim ? null : STILL_T })].join('\n');
38
- }
39
-
40
- // The watched card inside its neon frame, laid out once per state: the headline sits in the top rule, at least three
41
- // rows of body give the sun its place. frame(t) paints it for one moment.
42
- function framed(rows, width, light) {
43
- const inner = width - 4;
44
- const title = rowCells(rows[0]) <= inner - 4 ? rows[0] : '';
45
- const body = (title ? rows.slice(1) : rows).flatMap((row) => wrapRow(row, inner));
46
- while (body.length < SUN_ROWS) body.push('');
47
- const spot = place(body, inner);
48
- const sunMid = 2 + spot.at + SUN_W / 2;
49
- const lit = light && spot.top !== null && spot.sea === body.length - 1;
50
- const rule = (x, r, t) => {
51
- const i = Math.floor(x / 4) * 4;
52
- let hue = neon(Math.min(1, i / width + r * 0.02));
53
- if (t !== null) hue = mix(hue, '#ffffff', 0.15 + 0.15 * Math.sin((t / 2.4) * Math.PI * 2));
54
- if (r === 2 && lit) {
55
- const near = Math.max(0, 1 - Math.abs(i - sunMid) / 26);
56
- const ring = 0.5 + 0.5 * Math.sin(Math.abs(i - sunMid) * 0.55 - (t ?? 0) * 2.6);
57
- hue = mix(hue, near > 0.6 ? '#ffd24a' : '#ff8f3c', Math.min(1, near * (0.45 + 0.85 * ring)));
58
- }
59
- return light?.dim ? mix(hue, '#30363d', 0.45) : hue;
60
- };
61
- const line = (from, chars, r, t) => ink([...chars].map((ch, i) => (ch === ' ' ? null : { ch, fg: rule(from + i, r, t) })));
62
- // Side walls are placed by column, so a character the terminal draws wider than expected cannot bend the frame.
63
- const wall = (t) => [line(0, '│', 1, t), `${ESC}[${width}G${line(width - 1, '│', 1, t)}`];
64
- const lead = title ? 4 + rowCells(title) : 0;
65
- return (t) => {
66
- const tails = light ? paint(spot, { ...light, t }) : new Map();
67
- const [left, right] = wall(t);
68
- const top = title
69
- ? `${line(0, '╭─ ', 0, t)}${title}${line(lead - 1, ` ${'─'.repeat(width - lead - 1)}╮`, 0, t)}`
70
- : line(0, `╭${'─'.repeat(width - 2)}╮`, 0, t);
71
- return [
72
- top,
73
- ...body.map((text, r) => `${left} ${text}${tails.has(r) ? ink(tails.get(r).slice(Math.min(inner, spot.ends[r]))) : `${ESC}[K`}${right}`),
74
- line(0, `╰${'─'.repeat(width - 2)}╯`, 2, t),
75
- ];
76
- };
35
+ if (!term.framed) return [...mark, ...plainRows(card, term, version)].join('\n');
36
+ const working = cardWorking(card, { env, now });
37
+ const view = framed(card, term, { env, cwd, version, now, working });
38
+ return [...mark, ...cardLines(view.grid(working ? STILL_T : null), term.width)].join('\n');
77
39
  }
78
40
 
79
41
  // What --watch shows for this state and terminal size. `moving` is false whenever the picture cannot change by itself.
80
- export function watchView(card, { env = process.env, stream = process.stdout, version, now = Date.now() }) {
42
+ export function watchView(card, { env = process.env, stream = process.stdout, cwd = process.cwd(), version, now = Date.now() }) {
81
43
  const term = terminal(env, stream);
82
44
  const height = Number(stream.rows) || 24;
83
- const width = Math.min(MAX_WIDTH, term.cols - 1);
84
- let draw;
85
- if (term.scene) {
86
- draw = framed(cardRows(card, term, version, width - 8), width, cardLight(card));
87
- } else {
88
- const rows = cardRows(card, term, version).flatMap((row) => wrapRow(row, term.cols));
89
- draw = () => rows;
45
+ if (!term.framed) {
46
+ const mark = markFor({ env, stream }).split('\n');
47
+ const rows = plainRows(card, term, version).flatMap((row) => wrapRow(row, term.cols));
48
+ const all = mark.length + rows.length <= height ? [...mark, ...rows] : rows;
49
+ return { moving: false, frame: () => all.slice(0, height) };
90
50
  }
91
- const mark = markFor({ env, stream }).split('\n');
92
- const above = mark.length + draw(null).length <= height ? mark : [];
93
- const moving = term.scene && !motionOff(env) && cardWorking(card, { env, now });
94
- return { moving, frame: (t) => [...above, ...draw(t)].slice(0, height) };
51
+ const working = cardWorking(card, { env, now });
52
+ const view = framed(card, term, { env, cwd, version, now, working });
53
+ // A pane too short for the card loses rows from the bottom of its body, never its frame.
54
+ const fit = (grid) => (grid.length > height ? [...grid.slice(0, Math.max(1, height - 1)), grid.at(-1)].slice(0, height) : grid);
55
+ return { moving: working && !motionOff(env), frame: (t) => cardLines(fit(view.grid(t)), term.width) };
95
56
  }
96
57
 
97
58
  /**
@@ -119,7 +80,7 @@ export function watchCard({ cwd = process.cwd(), env = process.env, out = proces
119
80
  if (bytes) out.write(bytes);
120
81
  };
121
82
  const compose = () => {
122
- view = watchView(card, { env, stream: out, version, now: now() });
83
+ view = watchView(card, { env, stream: out, cwd, version, now: now() });
123
84
  };
124
85
  const tick = () => {
125
86
  if (now() - readAt >= READ_MS) {
package/lib/config.mjs ADDED
@@ -0,0 +1,18 @@
1
+ import { lstatSync, readFileSync } from 'node:fs';
2
+ import { paths } from './paths.mjs';
3
+ import { writeFileAtomic } from './safe-write.mjs';
4
+
5
+ // LitMuse's own config.json: the rules-file choice (agentFile) and the round-ends choice (glyphs).
6
+ export function readConfig(env) {
7
+ try {
8
+ const file = paths(env).config;
9
+ if (lstatSync(file).isSymbolicLink()) return {};
10
+ return JSON.parse(readFileSync(file, 'utf8')) ?? {};
11
+ } catch {
12
+ return {};
13
+ }
14
+ }
15
+
16
+ export function writeConfig(env, patch) {
17
+ return writeFileAtomic(paths(env).config, `${JSON.stringify({ ...readConfig(env), ...patch }, null, 2)}\n`);
18
+ }
package/lib/doctor.mjs CHANGED
@@ -10,6 +10,7 @@ import { approvalStates } from './approvals.mjs';
10
10
  import { checkUpdate } from './update-check.mjs';
11
11
  import { agentFileRow } from './agent-file.mjs';
12
12
  import { survey, findings, CLI } from './extensions.mjs';
13
+ import { roundEndsLine } from './glyphs.mjs';
13
14
 
14
15
  const CATALOG_CAP = 32 * 1024;
15
16
 
@@ -143,7 +144,7 @@ export async function doctor({ env = process.env, flags = {}, print = console.lo
143
144
  const summary = fails
144
145
  ? `LitMuse doctor: FAIL (${fails} failing check${fails === 1 ? '' : 's'}${needed ? `, ${needed} approvals needed` : ''})`
145
146
  : needed
146
- ? `LitMuse: installed, ${needed} approvals needed. Run the commands above or \`npx @litfamily/litmuse install --approve\`.`
147
+ ? `LitMuse: installed, ${needed} approvals needed. The person who uses Muse runs the commands above.`
147
148
  : `LitMuse doctor: PASS${warns ? ` (${warns} warning${warns === 1 ? '' : 's'})` : ''}`;
148
149
 
149
150
  if (flags.json) {
@@ -155,6 +156,7 @@ export async function doctor({ env = process.env, flags = {}, print = console.lo
155
156
  }
156
157
  print('');
157
158
  print(summary);
159
+ print(roundEndsLine({ env, surface: Boolean(plugin) && plugin.enabled !== false && st.state !== 'absent' }));
158
160
  }
159
161
  return fails || needed ? 1 : 0;
160
162
  }
package/lib/flags.mjs ADDED
@@ -0,0 +1,35 @@
1
+ // The command line: every flag LitMuse takes. Anything else that starts with a dash is refused, except for `rewind`,
2
+ // which reads its own flags.
3
+ export const NPX = 'npx --yes @litfamily/litmuse@latest';
4
+ export const GLYPH_CHOICES = ['auto', 'round', 'square'];
5
+
6
+ const SWITCHES = new Map([
7
+ ['--dry-run', 'dryRun'], ['--yes', 'yes'], ['-y', 'yes'], ['--approve', 'approve'], ['--json', 'json'], ['--offline', 'offline'],
8
+ ['--no-agent-file', 'noAgentFile'], ['--discard-modified', 'discardModified'], ['--card', 'card'], ['--watch', 'watch'],
9
+ ['--all', 'all'], ['--allow-shadow', 'allowShadow'], ['--round', 'round'], ['--agent', 'agent'],
10
+ ['--help', 'help'], ['-h', 'help'], ['--version', 'version'], ['-v', 'version'],
11
+ ]);
12
+ const VALUES = new Map([['--scope', 'scope'], ['--from', 'from'], ['--family', 'family'], ['--older-than', 'olderThan'], ['--glyphs', 'glyphs']]);
13
+
14
+ export const FLAGS = [...SWITCHES.keys(), ...VALUES.keys()];
15
+
16
+ /** `{command, args, flags, problem}`; `problem` is what makes the line unusable, or null. */
17
+ export function parse(argv) {
18
+ const flags = {};
19
+ const rest = [];
20
+ const problems = [];
21
+ for (let i = 0; i < argv.length; i += 1) {
22
+ const a = argv[i];
23
+ if (SWITCHES.has(a)) flags[SWITCHES.get(a)] = true;
24
+ else if (!VALUES.has(a)) rest.push(a);
25
+ else if (argv[i + 1] === undefined || argv[i + 1].startsWith('-')) problems.push(`${a} needs a value.`);
26
+ else flags[VALUES.get(a)] = argv[++i];
27
+ }
28
+ const command = rest[0] ?? 'help';
29
+ const unknown = command === 'rewind' ? undefined : rest.find((a) => a.startsWith('-'));
30
+ if (unknown) problems.unshift(`Unknown option: ${unknown}.`);
31
+ if (flags.scope && !['user', 'project'].includes(flags.scope)) problems.push('--scope takes user or project.');
32
+ if (flags.glyphs && !GLYPH_CHOICES.includes(flags.glyphs)) problems.push(`--glyphs takes ${GLYPH_CHOICES.join(', ')}.`);
33
+ if ((flags.round || flags.glyphs) && !['install', 'update'].includes(command)) problems.push('--round and --glyphs work with install and update.');
34
+ return { command, args: rest.slice(1), flags, problem: problems[0] ?? null };
35
+ }