@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.
@@ -0,0 +1,379 @@
1
+ // The status card as a framed card: title edge, stage map, task, threads and lanes, skills, and the context on the
2
+ // bottom edge, with the sunset in the cells no text uses. composeCard() lays one state out as rows of cells and returns
3
+ // a painter for any moment; every row is exactly `width` cells. Parts without data are left out.
4
+ import { displayWidth } from '../plugin/lib/rewind/gauge.mjs';
5
+ import { REVIEW_LANES } from '../plugin/hooks/lib/workflow-stack.mjs';
6
+ import { CAP_LEFT, CAP_RIGHT } from './glyphs.mjs';
7
+ import { sample } from './mark.mjs';
8
+ import { REVIEW_LANE_LABELS, burstOf, waitingOf } from './stage-card.mjs';
9
+ import { FAINT, SUN_ROWS, SUN_W, ink, mix, neon, paint, place } from './sunset.mjs';
10
+
11
+ const WHITE = '#e6edf3';
12
+ const DIM = '#7d8590';
13
+ const RAIL = '#46505c';
14
+ const TRACK = '#2a2340';
15
+ const MUTED = '#2d333b';
16
+ const MUTED_TEXT = '#adb5bf';
17
+ const DARK = '#0b0e14';
18
+ const ACCENT = '#8be9fd';
19
+ const VIOLET = '#b48cff';
20
+ const PINK = '#ff2d8a';
21
+ const ORANGE = '#ff8f3c';
22
+ const WARM = '#ff7a45';
23
+ const GREEN = '#6bdb8f';
24
+ const AMBER = '#ffaf3c';
25
+ const RED = '#ff5f6b';
26
+ const BRAND = ['#ffa033', '#ff6a55', '#ff3388'];
27
+ const RAINBOW = ['#ff6b6b', '#ffaf5f', '#ffff87', '#87ff9f', '#87d7ff', '#af87ff', '#ff87d7', '#ff6b6b'];
28
+ export const STAGES = {
29
+ main: ['interview', 'plan', 'work', 'review', 'done'],
30
+ loop: ['PIN', 'RED', 'GREEN', 'VERIFY', 'REVIEW', 'RECORD'],
31
+ research: ['decompose', 'wave', 'expand', 'verify', 'synthesis'],
32
+ };
33
+ const UNIT = { main: 'task', loop: 'criterion', research: 'wave' };
34
+ const MAX_BODY = 40;
35
+
36
+ // Text as cells: one entry per cell, `''` for the second half of a wide character. Controls, joiners and variation
37
+ // selectors are dropped, so a row is as wide as it counts.
38
+ const WIDE = /\p{Emoji_Presentation}/u;
39
+ export function say(text, style = {}) {
40
+ const out = [];
41
+ for (const ch of String(text ?? '').replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}\p{Co}︀-️]|\p{Regional_Indicator}/gu, '')) {
42
+ const cells = Math.max(displayWidth(ch), WIDE.test(ch) ? 2 : 0);
43
+ if (cells === 0) continue;
44
+ out.push({ ch, ...style });
45
+ if (cells === 2) out.push({ ch: '', ...style });
46
+ }
47
+ return out;
48
+ }
49
+
50
+ const gap = (n) => new Array(Math.max(0, n)).fill(null);
51
+ // Cuts to `width` cells, ending in `…` when anything was lost; a wide character is never split.
52
+ function cut(cells, width) {
53
+ if (cells.length <= width) return cells;
54
+ if (width <= 0) return [];
55
+ let end = width - 1;
56
+ if (cells[end]?.ch === '') end -= 1;
57
+ return [...cells.slice(0, end), { ch: '…', fg: DIM }, ...gap(width - end - 1)];
58
+ }
59
+ const spread = (left, right, width) => {
60
+ if (!right.length) return cut(left, width);
61
+ const room = width - right.length - 2;
62
+ if (room < 12) return cut(left, width);
63
+ const kept = cut(left, room);
64
+ return [...kept, ...gap(width - kept.length - right.length), ...right];
65
+ };
66
+ const dot = () => say(' · ', { fg: DIM });
67
+ const joined = (parts) => parts.filter((p) => p?.length).flatMap((p, i) => (i ? [...dot(), ...p] : p));
68
+
69
+ // A pill: round caps in the fill, or a cell of the fill on each side.
70
+ function pill(text, stops, round, { fg = DARK, bold = true, light = null } = {}) {
71
+ const inner = say(text, { fg, bold });
72
+ const last = Math.max(1, inner.length - 1);
73
+ const fill = (i) => {
74
+ const hue = sample(stops.length > 1 ? stops : [stops[0], stops[0]], Math.min(1, Math.max(0, i) / last));
75
+ const near = light === null ? 1 : Math.abs(i / last - light);
76
+ return near < 0.2 ? mix(hue, '#ffffff', (1 - near / 0.2) * 0.6) : hue;
77
+ };
78
+ const body = inner.map((cell, i) => ({ ...cell, bg: fill(cell.ch === '' ? i - 1 : i) }));
79
+ return round
80
+ ? [{ ch: CAP_LEFT, fg: fill(0) }, ...body, { ch: CAP_RIGHT, fg: fill(last) }]
81
+ : [{ ch: ' ', bg: fill(0) }, ...body, { ch: ' ', bg: fill(last) }];
82
+ }
83
+
84
+ // A gauge of `size` cells, ends included, on one smooth track.
85
+ function bar(done, total, size, stops, round) {
86
+ const ratio = total > 0 ? Math.min(1, done / total) : 0;
87
+ const filled = done <= 0 ? 0 : ratio === 1 ? size : Math.min(size - 1, Math.max(1, Math.round(ratio * size)));
88
+ const tint = (i) => (i < filled ? sample(stops, size > 1 ? i / (size - 1) : 0) : TRACK);
89
+ return Array.from({ length: size }, (_, i) => {
90
+ if (round && i === 0) return { ch: CAP_LEFT, fg: tint(0) };
91
+ if (round && i === size - 1) return { ch: CAP_RIGHT, fg: tint(i) };
92
+ return { ch: ' ', bg: tint(i) };
93
+ });
94
+ }
95
+ const pulse = (size, t, offset) => {
96
+ const head = t === null ? -1 : Math.floor((((t / 1.4 + offset) % 1) + 1) % 1 * size);
97
+ return Array.from({ length: size }, (_, i) => ({ ch: '━', fg: i === head ? '#d7dde4' : RAIL }));
98
+ };
99
+ const clock = (ms) => {
100
+ const s = Math.max(0, Math.floor(ms / 1000));
101
+ const m = Math.floor(s / 60);
102
+ const two = (n) => String(n).padStart(2, '0');
103
+ return m < 60 ? `${m}:${two(s % 60)}` : `${Math.floor(m / 60)}:${two(m % 60)}:${two(s % 60)}`;
104
+ };
105
+ const tokens = (n) => (n >= 1e6 ? `${Number((n / 1e6).toFixed(1))}m` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n));
106
+ const fraction = (done, total) => [...say(done, { fg: WHITE, bold: true }), ...say(`/${total}`, { fg: DIM })];
107
+
108
+ /** The state the whole card takes: its word, its colours and its light. */
109
+ export function cardState(card, facts, working) {
110
+ const done = burstOf(card, card.now ?? Date.now()) !== null;
111
+ const failed = (card.lanes ?? []).some((lane) => lane.status === 'failed');
112
+ const tight = (facts.ctx?.percent ?? 0) >= 85;
113
+ if (!card.active) return done ? { id: 'done' } : card.idle ? { id: 'idle', dim: true } : { id: 'ready', dim: true };
114
+ if (done) return { id: 'done' };
115
+ if (failed) return { id: 'error', look: 'turn' };
116
+ if (waitingOf(card)) return { id: 'turn', look: 'turn' };
117
+ if (tight) return { id: 'warning', look: 'turn' };
118
+ if (card.route === 'lit-adhd') return { id: 'rewind', look: 'rainbow' };
119
+ if (card.route === 'review-work') return { id: 'review' };
120
+ return { id: working ? 'working' : 'rest', dim: false };
121
+ }
122
+
123
+ export function composeCard(card, facts, { width, round, working = false, version }) {
124
+ const state = cardState(card, facts, working);
125
+ const { id } = state;
126
+ const inner = width - 4;
127
+ const frames = facts.frames ?? [];
128
+ const frame = frames.findLast((f) => f.status === 'active') ?? frames.at(-1) ?? null;
129
+ const stages = STAGES[frame?.family] ?? null;
130
+ const at = stages ? stages.indexOf(frame.stage) : -1;
131
+ const allDone = id === 'done' && card.active;
132
+ const verdicts = frame?.skill === 'review-work' ? frame.verdicts ?? {} : null;
133
+ const reported = verdicts ? REVIEW_LANES.filter(({ id: lane }) => ['pass', 'fail'].includes(verdicts[lane])).length : 0;
134
+ const lanes = card.lanes ?? [];
135
+ const running = lanes.filter((l) => l.status === 'running');
136
+ const rows = card.threads?.rows ?? [];
137
+ const accent = { turn: AMBER, warning: AMBER, error: RED, done: GREEN }[id] ?? ACCENT;
138
+ const breath = (t) => (t === null ? 0 : 0.5 + 0.5 * Math.sin((t / 2.4) * Math.PI * 2));
139
+ const turning = (k, t) => sample(RAINBOW, (((k + (t ?? 0) / 4.8) % 1) + 1) % 1);
140
+
141
+ const title = card.active ? [...new Set([...frames.map((f) => f.skill).filter(Boolean), ...(frames.length ? [] : [card.route])])].join(' › ') || card.route : id === 'done' ? 'done' : id === 'idle' && frame ? frame.skill : 'ready';
142
+ const word = {
143
+ ready: 'READY', idle: 'idle', done: 'DONE ✓', error: 'LANE FAILED ✗', turn: 'YOUR TURN', warning: 'CONTEXT', rewind: 'REWIND <<',
144
+ review: `REVIEW ${reported}/${REVIEW_LANES.length}`,
145
+ }[id] ?? (frame?.stage ? frame.stage.toUpperCase() : 'LIVE');
146
+
147
+ const brand = (t) => (state.dim
148
+ ? pill('🔥 LIT', BRAND.map((c) => mix(c, MUTED, 0.25)), round)
149
+ : pill('🔥 LIT', id === 'rewind' ? [0, 0.2, 0.4].map((k) => mix(turning(k, t), '#ffffff', 0.25)) : id === 'turn' ? [ORANGE, AMBER] : BRAND.map((c) => mix(c, '#ffffff', 0.2 * breath(t))), round));
150
+
151
+ const stateCells = (t) => {
152
+ if (id === 'rewind') return [...word].flatMap((ch, i) => say(ch, { fg: mix(turning(i / 9, t), '#ffffff', 0.35), bold: true }));
153
+ if (state.dim) return say(id === 'ready' ? 'READY ○' : word, { fg: DIM });
154
+ const hue = mix(accent, '#ffffff', 0.35 * breath(t));
155
+ const tail = ['done', 'error'].includes(id) ? '' : id === 'rest' ? ' ○' : ' ●';
156
+ return [...say(word, { fg: accent, bold: true }), ...say(tail, { fg: hue })];
157
+ };
158
+
159
+ // Stage map: done stages and the rail behind are warm, the current stage is a pill, the rest is dim.
160
+ const count = frame && Number.isInteger(frame.n) && Number.isInteger(frame.total) ? { done: frame.n, total: frame.total, unit: frame.skill === 'review-work' ? 'lane' : frame.unit ?? UNIT[frame.family] } : null;
161
+ const mapCells = (t) => {
162
+ if (!stages || at < 0) return null;
163
+ const stops = [ORANGE, PINK, accent];
164
+ const tone = (k) => sample(stops, Math.min(1, k / Math.max(1, stages.length - 1)));
165
+ const build = ({ rail, short, near }) => stages.flatMap((stage, i) => {
166
+ if (near && Math.abs(i - at) > 1) return [];
167
+ const label = short ? stage.slice(0, 3) : stage;
168
+ const first = near ? i === Math.max(0, at - 1) : i === 0;
169
+ const isDone = i < at || allDone;
170
+ const lead = first ? [] : rail === 0 ? gap(1) : [...gap(1), ...Array.from({ length: rail }, (_, k) => {
171
+ if (i <= at || allDone) return { ch: '━', fg: tone(i - 1 + (k + 0.5) / rail) };
172
+ if (i === at + 1) return { ch: '━', fg: t !== null && Math.floor(t / 0.35) % rail === k ? '#d7dde4' : RAIL };
173
+ return { ch: '─', fg: RAIL };
174
+ }), ...gap(1)];
175
+ if (i === at && !allDone) {
176
+ const light = t === null || id === 'turn' ? null : ((t % 2.4) / 1.2) - 0.2;
177
+ const stop = id === 'turn' || id === 'warning' ? [mix(AMBER, '#ffffff', 0.2), AMBER] : id === 'error' ? ['#ff9aa2', RED] : [VIOLET, accent];
178
+ return [...lead, ...(state.dim ? pill(label, [MUTED], round, { fg: MUTED_TEXT }) : pill(label, stop, round, { light }))];
179
+ }
180
+ return [...lead, ...say(label, { fg: isDone ? tone(i) : DIM, bold: false }), ...gap(1), ...say(isDone ? '✓' : '·', { fg: isDone ? WARM : DIM })];
181
+ });
182
+ const forms = [{ rail: 2 }, { rail: 1 }, { rail: 0 }, { rail: 0, short: true }, { rail: 0, short: true, near: true }].map(build);
183
+ const room = inner - (running.length ? 18 : 0);
184
+ return forms.find((form) => form.length <= room) ?? forms.find((form) => form.length <= inner) ?? forms.at(-1);
185
+ };
186
+
187
+ const laneCells = (t) => {
188
+ if (!running.length) return [];
189
+ const dots = running.slice(0, 4).flatMap((_, i) => {
190
+ const walk = t === null ? 0 : Math.max(0, 1 - Math.abs(((t / 1.6) % 1) * (Math.min(4, running.length) + 1) - 0.5 - i));
191
+ return say('●', { fg: mix(GREEN, '#ffffff', 0.7 * walk) });
192
+ });
193
+ const longest = Math.max(...running.map((l) => l.elapsedMs));
194
+ return [...dots, ...gap(1), ...say(running.length, { fg: WHITE, bold: true }), ...say(` ${running.length === 1 ? 'lane' : 'lanes'} ${clock(longest)}`, { fg: DIM })];
195
+ };
196
+ const toolCells = () => {
197
+ const { tool } = facts;
198
+ if (!tool) return [];
199
+ return [...say(tool.ok ? '✓ ' : '✗ ', { fg: tool.ok ? GREEN : RED, bold: true }), ...say(tool.name, { fg: tool.ok ? WHITE : RED, bold: true }), ...say(` · ${clock(tool.ms)} ago`, { fg: DIM })];
200
+ };
201
+
202
+ // The task lines: the plan, then the goal, each with its gauge and what is next.
203
+ const tasks = [];
204
+ const nextUp = (text) => [...say('next ▸ ', { fg: DIM }), ...say(text, { fg: WHITE })];
205
+ const meter = (done, total) => bar(done, total, Math.max(6, Math.min(8, total) + 2), done >= total ? [GREEN, GREEN] : [ORANGE, PINK], round);
206
+ if (card.plan) {
207
+ const { done, total, next } = card.plan;
208
+ tasks.push(joined([
209
+ [...say('task ', { fg: DIM }), ...fraction(done, total), ...gap(1), ...meter(done, total)],
210
+ next ? nextUp(`${next.row}. ${next.text}`) : say('every row ticked', { fg: GREEN }),
211
+ ]));
212
+ } else if (count && !card.goal) {
213
+ tasks.push([...say(`${count.unit} `, { fg: DIM }), ...fraction(count.done, count.total), ...gap(1), ...meter(count.done, count.total)]);
214
+ }
215
+ if (card.goal) {
216
+ const { met, total, objective, open } = card.goal;
217
+ tasks.push(joined([
218
+ [...say('criterion ', { fg: DIM }), ...fraction(met, total), ...gap(1), ...meter(met, total)],
219
+ open.length ? nextUp(`${open[0].id} ${open[0].text}`) : say(objective, { fg: GREEN }),
220
+ ]));
221
+ }
222
+ if (id === 'ready' && !tasks.length) tasks.push(joined([say('no active route in this workspace', { fg: DIM }), [...say('type ', { fg: DIM }), ...say('lit', { fg: ACCENT, bold: true }), ...say(' and what you want', { fg: DIM })]]));
223
+ if (id === 'idle') tasks.push([...say('back? type ', { fg: DIM }), ...say('lit adhd', { fg: ACCENT, bold: true }), ...say(' to catch up', { fg: DIM })]);
224
+
225
+ // Thread and lane rows share one name column and one gauge column.
226
+ const list = [];
227
+ for (const row of rows) {
228
+ const own = !row.sibling;
229
+ const [, done, total] = /(\d+)\/(\d+)$/.exec(row.gauge ?? '') ?? [];
230
+ const finished = allDone && own;
231
+ list.push({
232
+ name: row.pane ? `${row.skill} · ${row.pane}` : row.skill, stage: row.stage, bold: own && row.status === 'active',
233
+ mark: finished || row.status === 'done' ? ['✓', GREEN] : row.status === 'paused' ? ['‖', AMBER] : row.status === 'idle' ? ['-', DIM] : ['●', GREEN],
234
+ word: finished ? 'done' : row.status === 'active' ? 'running' : row.status,
235
+ count: total ? { done: Number(done), total: Number(total) } : null,
236
+ moving: ['active', 'running'].includes(row.status) && !finished,
237
+ note: own || row.pane ? '' : `other session ${String(row.session).slice(0, 8)}`,
238
+ own,
239
+ });
240
+ }
241
+ const laneRows = lanes.map((lane) => ({
242
+ name: String(lane.type).replace(/^litmuse\//, ''), stage: null, bold: lane.status === 'running', lane: true,
243
+ mark: lane.status === 'running' ? ['●', GREEN] : lane.status === 'failed' ? ['✗', RED] : ['✓', GREEN],
244
+ word: lane.status === 'running' ? 'running' : lane.status, time: clock(lane.elapsedMs), moving: lane.status === 'running', count: null, note: '',
245
+ }));
246
+ const shownLanes = laneRows.filter((l) => l.moving || l.word === 'failed').concat(laneRows.filter((l) => !l.moving && l.word !== 'failed')).slice(0, 8);
247
+ const order = [...list.filter((l) => l.own)];
248
+ if (shownLanes.length >= 2) order.push({ fork: `┬ ${running.length >= 2 ? `${running.length} lanes in parallel` : `${shownLanes.length} lanes`}${laneRows.length > 8 ? ` · +${laneRows.length - 8} more` : ''}` });
249
+ shownLanes.forEach((lane, i) => order.push({ ...lane, lead: `${i === shownLanes.length - 1 ? '└─' : '├─'} ` }));
250
+ order.push(...list.filter((l) => !l.own));
251
+ const widest = (pick) => Math.max(0, ...order.filter((l) => !l.fork).map(pick));
252
+ const nameCol = Math.min(inner >= 90 ? 30 : 22, widest((l) => (l.lead ? 3 : 0) + 2 + say(l.name).length));
253
+ const stageCol = Math.min(10, widest((l) => (l.stage ? say(l.stage).length : 0)));
254
+ const barCol = 7;
255
+ const countCol = widest((l) => (l.count ? `${l.count.done}/${l.count.total}`.length : 0));
256
+ const threadCells = (l, i, t) => {
257
+ if (l.fork) return say(l.fork, { fg: DIM });
258
+ const hue = l.mark[1];
259
+ const name = cut([...say(l.lead ?? '', { fg: DIM }), ...say(`${l.mark[0]} `, { fg: hue }), ...say(l.name, { fg: l.bold ? WHITE : MUTED_TEXT, bold: l.bold })], nameCol);
260
+ const stage = cut(say(l.stage ?? '', { fg: DIM }), stageCol);
261
+ const gauge = l.count ? bar(l.count.done, l.count.total, barCol, [mix(hue, '#ffffff', 0.05), mix(hue, '#ffffff', 0.25)], round) : l.moving ? pulse(barCol, t, i * 0.17) : [];
262
+ const cells = [...name, ...gap(nameCol - name.length + 1)];
263
+ if (stageCol) cells.push(...stage, ...gap(stageCol - stage.length + 1));
264
+ cells.push(...gauge, ...gap(barCol - gauge.length + 1));
265
+ const numbers = l.count ? fraction(l.count.done, l.count.total) : [];
266
+ if (countCol) cells.push(...numbers, ...gap(countCol - numbers.length + 1));
267
+ cells.push(...say(l.word, { fg: hue }));
268
+ if (l.time) cells.push(...gap(1), ...say(l.time, { fg: DIM }));
269
+ if (l.note) cells.push(...dot(), ...say(l.note, { fg: DIM }));
270
+ // The gaps between columns belong to the row: no star falls into them.
271
+ return cells.map((cell) => cell ?? { ch: ' ' });
272
+ };
273
+
274
+ const verdictCells = verdicts && REVIEW_LANES.flatMap(({ id: lane }, i) => {
275
+ const mark = { pass: ['✓', GREEN], fail: ['✗', RED], running: ['●', AMBER], pending: ['·', DIM] }[verdicts[lane]] ?? ['·', DIM];
276
+ return [...(i ? gap(2) : []), ...say(`${REVIEW_LANE_LABELS[lane]} `, { fg: mark[1] === DIM ? DIM : WHITE }), ...say(mark[0], { fg: mark[1], bold: true })];
277
+ });
278
+ const chips = (t) => {
279
+ if (!facts.skills.length) return null;
280
+ const light = t === null || state.dim ? null : ((t % 2.4) / 1.2) - 0.2;
281
+ return [...say('skills ', { fg: DIM }), ...facts.skills.flatMap((skill, i) => [...(i ? gap(1) : []), ...(i === 0
282
+ ? pill(`⚡ ${skill}`, [VIOLET, accent], round, { light })
283
+ : pill(`· ${skill}`, [MUTED], round, { fg: MUTED_TEXT, bold: false }))])];
284
+ };
285
+
286
+ const bodyAt = (t) => {
287
+ const body = [];
288
+ const map = mapCells(t);
289
+ const laneSide = laneCells(t);
290
+ const toolSide = toolCells();
291
+ const sides = [laneSide, toolSide].filter((s) => s.length);
292
+ if (map) body.push(spread(map, laneSide, inner));
293
+ const branch = (i, n) => say(`${i === n - 1 ? '└' : '├'} `, { fg: DIM });
294
+ const lines = [...tasks, ...(verdictCells ? [verdictCells] : [])];
295
+ lines.forEach((cells, i) => {
296
+ const side = i === 0 ? (map ? toolSide : sides.flat().length ? joined(sides) : []) : [];
297
+ body.push(spread([...branch(i, lines.length), ...cells], side, inner));
298
+ });
299
+ if (!lines.length && toolSide.length) body.push(spread(say('└', { fg: DIM }), toolSide, inner));
300
+ if (card.restartTo) body.push(cut([...say('↻ ', { fg: AMBER, bold: true }), ...say(`restart to ${card.restartTo}`, { fg: AMBER, bold: true }), ...say(' · LitMuse was updated after this session loaded it', { fg: DIM })], inner));
301
+ order.forEach((l, i) => body.push(cut(threadCells(l, i, t), inner)));
302
+ if (card.threads?.omitted) body.push(say(`+${card.threads.omitted} more`, { fg: DIM }));
303
+ const skills = chips(t);
304
+ if (skills) body.push(cut(skills, inner));
305
+ return body.slice(0, MAX_BODY).map((cells) => [...cells, ...gap(inner - cells.length)]);
306
+ };
307
+
308
+ const ctxCells = () => {
309
+ const { ctx } = facts;
310
+ if (!ctx) return [];
311
+ const label = say('ctx ', { fg: DIM });
312
+ if (ctx.percent === null) return [...label, ...say(`~${tokens(ctx.used)}`, { fg: ACCENT, bold: true })];
313
+ const hue = ctx.percent >= 85 ? RED : ctx.percent >= 70 ? AMBER : ACCENT;
314
+ return [...label, ...say(`~${ctx.percent}%`, { fg: hue, bold: true }), ...gap(1), ...bar(ctx.percent, 100, 7, ctx.percent >= 85 ? [AMBER, RED] : [VIOLET, VIOLET], round)];
315
+ };
316
+ const footLeft = joined([ctxCells(), facts.branch ? [...say('⎇ ', { fg: DIM }), ...say(facts.branch, { fg: ACCENT })] : [], card.plan ? say(card.plan.file.replace(/^plans\//, ''), { fg: MUTED_TEXT }) : []]);
317
+ const footRight = joined([card.activeMs !== null && card.activeMs !== undefined ? [...say('active ', { fg: DIM }), ...say(clock(card.activeMs), { fg: MUTED_TEXT })] : [], say(`v${version}`, { fg: DIM })]);
318
+
319
+ // Height is free, so a body with no room for the sun grows a little sky under it. The layout is the resting body's;
320
+ // what moves keeps its cells.
321
+ const base = bodyAt(null);
322
+ while (base.length < SUN_ROWS) base.push(gap(inner));
323
+ let spot = place(base, inner);
324
+ for (let n = 0; n < SUN_ROWS && spot.top === null; n += 1) {
325
+ base.push(gap(inner));
326
+ spot = place(base, inner);
327
+ }
328
+ const height = base.length;
329
+ const sunMid = 2 + spot.at + SUN_W / 2;
330
+ const underSun = spot.top !== null && spot.sea === height - 1;
331
+
332
+ const edgeHue = (x, y, t) => {
333
+ const k = Math.floor(x / 4) * 4;
334
+ let hue = id === 'rewind' ? turning(k / width + y * 0.04, t) : id === 'turn' || id === 'warning' ? mix(AMBER, mix(AMBER, FAINT, 0.5), t === null ? 0 : 1 - breath(t)) : id === 'error' ? mix(RED, AMBER, 0.2) : neon(Math.min(1, k / (width - 4)));
335
+ if (!['turn', 'warning', 'error'].includes(id)) hue = mix(hue, '#ffffff', 0.3 * breath(t));
336
+ if (y === 2 && underSun) {
337
+ const far = Math.abs(k - sunMid);
338
+ const near = Math.max(0, 1 - far / 26);
339
+ hue = mix(hue, near > 0.6 ? '#ffd24a' : ORANGE, Math.min(1, near * (0.45 + 0.85 * (0.5 + 0.5 * Math.sin(far * 0.55 - (t ?? 0) * 2.6)))));
340
+ }
341
+ return state.dim ? mix(hue, FAINT, 0.45) : hue;
342
+ };
343
+ // `╭─ left ──── right ─╮`, the right part dropped first, then the left part cut.
344
+ const edgeRow = ([open, close], left, right, y, t) => {
345
+ const rule = (x, ch) => ({ ch, fg: edgeHue(x, y, t) });
346
+ const room = width - 6;
347
+ const keepRight = right.length && left.length + right.length + 5 <= room ? right : [];
348
+ const keepLeft = cut(left, keepRight.length ? left.length : room - 1);
349
+ const cells = [rule(0, open), rule(1, '─'), null, ...keepLeft, ...(keepLeft.length ? [null] : [])];
350
+ const tail = keepRight.length ? [null, ...keepRight, null] : [];
351
+ for (let x = cells.length; x < width - 2 - tail.length; x += 1) cells.push(rule(x, '─'));
352
+ return [...cells, ...tail, rule(width - 2, '─'), rule(width - 1, close)];
353
+ };
354
+ const head = (t) => [...brand(t), ...dot(), ...say(title, state.dim ? { fg: DIM } : { fg: accent, bold: true })];
355
+
356
+ const light = { look: state.look ?? 'sunset', dim: Boolean(state.dim) };
357
+ return {
358
+ state: id,
359
+ height: height + 2,
360
+ grid: (t) => {
361
+ const body = t === null ? base.map((r) => [...r]) : bodyAt(t);
362
+ while (body.length < height) body.push(gap(inner));
363
+ const scene = paint(spot, { ...light, t });
364
+ const wall = (x, t2) => ({ ch: '│', fg: edgeHue(x, 1, t2) });
365
+ return [
366
+ edgeRow(['╭', '╮'], head(t), stateCells(t), 0, t),
367
+ ...body.map((cells, r) => {
368
+ const over = scene.get(r);
369
+ const row = over ? cells.map((cell, x) => cell ?? over[x]) : cells;
370
+ return [wall(0, t), null, ...row, null, wall(width - 1, t)];
371
+ }),
372
+ edgeRow(['╰', '╯'], footLeft, footRight, 2, t),
373
+ ];
374
+ },
375
+ };
376
+ }
377
+
378
+ /** Rows of cells as text; the right wall is placed by column, so a character drawn wider than expected bends nothing. */
379
+ export const cardLines = (grid, width) => grid.map((row) => `${ink(row.slice(0, -1).filter((c) => c === null || c.ch !== ''))}\u001b[${width}G${ink(row.slice(-1))}`);
package/lib/glyphs.mjs ADDED
@@ -0,0 +1,103 @@
1
+ // Whether LitMuse draws round ends (U+E0B6, U+E0B4) on pills and gauges. Every surface asks here, so one terminal never
2
+ // shows both forms. LITMUSE_GLYPHS decides when set (auto, round or nerd, basic or square), then the choice saved by
3
+ // `install --glyphs`; on auto it is the terminal's own word, then, off SSH, whether an icon font is installed here. Only
4
+ // file names in the font folders are read.
5
+ import { readdirSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { readConfig } from './config.mjs';
9
+ import { GLYPH_CHOICES, NPX } from './flags.mjs';
10
+ import { colourDepth } from './mark.mjs';
11
+
12
+ export const CAP_LEFT = '';
13
+ export const CAP_RIGHT = '';
14
+ const MAX_NAMES = 4000;
15
+ const MAX_DEPTH = 3;
16
+ const FONT = /\.(?:ttf|otf|ttc)$/i;
17
+ const ICONS = /nerd[ _-]?font|[ _-]nf[mp]?(?=[ _.-])/i;
18
+ const SETTING = new Map([['auto', 'auto'], ['round', 'round'], ['nerd', 'round'], ['square', 'square'], ['basic', 'square']]);
19
+
20
+ const drawsCaps = (env) => Boolean(env.WT_SESSION || env.KITTY_WINDOW_ID) || env.TERM === 'xterm-kitty'
21
+ || /^(?:vscode|wezterm|ghostty)$/i.test(env.TERM_PROGRAM ?? '');
22
+
23
+ const fontFolders = (env, platform) => {
24
+ const home = env.HOME || homedir();
25
+ if (platform === 'darwin') return [join(home, 'Library', 'Fonts'), '/Library/Fonts'];
26
+ if (platform === 'win32') return [env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'Microsoft', 'Windows', 'Fonts'), env.WINDIR && join(env.WINDIR, 'Fonts')].filter(Boolean);
27
+ return [join(isAbsolute(env.XDG_DATA_HOME ?? '') ? env.XDG_DATA_HOME : join(home, '.local', 'share'), 'fonts'), join(home, '.fonts'), '/usr/local/share/fonts', '/usr/share/fonts'];
28
+ };
29
+
30
+ /** An icon font file is installed. Links are not followed; an unreadable folder or too many names means no. */
31
+ export function iconFontInstalled({ env = process.env, platform = process.platform, folders = fontFolders(env, platform), limit = MAX_NAMES } = {}) {
32
+ const queue = folders.map((path) => [path, 0]);
33
+ let seen = 0;
34
+ for (const [path, depth] of queue) {
35
+ let entries = [];
36
+ try {
37
+ entries = readdirSync(path, { withFileTypes: true });
38
+ } catch { /* no such folder here */ }
39
+ for (const entry of entries) {
40
+ seen += 1;
41
+ if (seen > limit) return false;
42
+ if (entry.isDirectory()) {
43
+ if (depth < MAX_DEPTH) queue.push([join(path, entry.name), depth + 1]);
44
+ } else if (entry.isFile() && FONT.test(entry.name) && ICONS.test(entry.name)) return true;
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+
50
+ // The font folders are read at most once per process.
51
+ let installed = null;
52
+ const iconFontOnce = () => (installed ??= iconFontInstalled());
53
+
54
+ /** A font was added or removed: look again. */
55
+ export const forgetIconFont = () => { installed = null; };
56
+
57
+ /** `{choice, from}`: round, square or auto, and whether LITMUSE_GLYPHS, the saved choice or neither said so. */
58
+ export function glyphChoice(env = process.env) {
59
+ const set = SETTING.get((env.LITMUSE_GLYPHS ?? '').toLowerCase());
60
+ if (set) return { choice: set, from: 'environment' };
61
+ const saved = readConfig(env).glyphs;
62
+ return GLYPH_CHOICES.includes(saved) ? { choice: saved, from: 'saved' } : { choice: 'auto', from: 'default' };
63
+ }
64
+
65
+ export function roundGlyphs(env = process.env, iconFont = iconFontOnce) {
66
+ const { choice } = glyphChoice(env);
67
+ if (choice !== 'auto') return choice === 'round';
68
+ if (drawsCaps(env)) return true;
69
+ return !env.SSH_CONNECTION && iconFont();
70
+ }
71
+
72
+ // What the window on stdout rules out. Without a terminal it says nothing about the window the user will look at.
73
+ function windowLimit(env) {
74
+ if (env.NO_COLOR) return 'NO_COLOR is set; unset it';
75
+ if (/^dumb$/i.test(env.TERM ?? '')) return 'TERM is dumb; use a full terminal';
76
+ if (/;(7|15)$/.test(env.COLORFGBG ?? '')) return 'light ground; use a dark terminal';
77
+ return colourDepth({ env, isTTY: true }) === 'truecolor' ? null : 'fewer colours than truecolor; use a truecolor terminal';
78
+ }
79
+
80
+ /**
81
+ * The ROUND_ENDS line of install, update and doctor. `surface` is whether LitMuse is installed, so that its status card
82
+ * is there; `fontWhy` is why --round could not add the font. An installed font is no proof that the terminal uses it.
83
+ */
84
+ export function roundEndsLine({
85
+ env = process.env, surface = true, tty = Boolean(process.stdout.isTTY), platform = process.platform, fontWhy = null,
86
+ iconFont = () => iconFontInstalled({ env, platform }),
87
+ } = {}) {
88
+ const again = `${NPX} install --yes`;
89
+ const square = (why) => `ROUND_ENDS: square (${why})`;
90
+ const check = (why) => `ROUND_ENDS: check (${why}; show your user the pill in step 7 of ${NPX} install --agent)`;
91
+ if (!surface) return square(`no surface enabled; run ${again} --round`);
92
+ const limit = tty ? windowLimit(env) : null;
93
+ if (limit) return square(limit);
94
+ const { choice, from } = glyphChoice(env);
95
+ if (choice === 'square') return square(`choice is square; ${from === 'environment' ? 'unset LITMUSE_GLYPHS' : `run ${again} --glyphs auto`}`);
96
+ if (choice === 'round') return from === 'saved' || readConfig(env).glyphs === 'round' ? 'ROUND_ENDS: shown' : check('LITMUSE_GLYPHS asks for round ends and no answer is saved');
97
+ if (drawsCaps(env)) return `ROUND_ENDS: ready${tty ? '' : ' in a dark full-colour terminal'}`;
98
+ if (env.SSH_CONNECTION) return square(`SSH; run ${again} --glyphs round when your user sees the pill in step 7 of ${NPX} install --agent as round`);
99
+ if (iconFont()) return check('an icon font is here, and this terminal is not known to use it');
100
+ if (fontWhy) return square(`font not installed (${fontWhy}); run ${again} --round again`);
101
+ if (platform === 'win32') return square('Windows console; use Windows Terminal or VS Code');
102
+ return square(`no icon font; run ${again} --round`);
103
+ }
package/lib/guard.mjs CHANGED
@@ -1,4 +1,6 @@
1
- import { sep } from 'node:path';
1
+ import { lstatSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { isAbsolute, join, resolve, sep } from 'node:path';
2
4
 
3
5
  const FOREIGN_DIRS = new Set(['.claude', '.codex']);
4
6
 
@@ -9,3 +11,38 @@ export function assertSafeWritePath(target) {
9
11
  if (hit) throw new Error(`refused: LitMuse never writes under ${hit}${sep} (${target})`);
10
12
  return target;
11
13
  }
14
+
15
+ export const FONT_FILES = Object.freeze({ font: 'SymbolsNerdFontMono-Regular.ttf', license: 'SymbolsNerdFontMono-LICENSE.txt' });
16
+
17
+ /** XDG_DATA_HOME where it is absolute; by the XDG rule a relative one counts as not set. A slash at its end would hide a link. */
18
+ export const xdgData = (env) => (isAbsolute(env.XDG_DATA_HOME ?? '') ? resolve(env.XDG_DATA_HOME) : null);
19
+
20
+ /** The per-user font folder, or null on Windows, where LitMuse installs no font. */
21
+ export function fontFolder({ env = process.env, platform = process.platform } = {}) {
22
+ const home = env.HOME || homedir();
23
+ if (platform === 'win32') return null;
24
+ return platform === 'darwin' ? join(home, 'Library', 'Fonts') : join(xdgData(env) ?? join(home, '.local', 'share'), 'fonts');
25
+ }
26
+
27
+ /**
28
+ * Why the font folder cannot be used, or null: it, or a folder between it and the user's home (or XDG_DATA_HOME), is a
29
+ * link or no folder. A missing folder is fine.
30
+ */
31
+ export function fontFolderProblem({ env = process.env, platform = process.platform } = {}) {
32
+ const home = env.HOME || homedir();
33
+ const steps = platform === 'darwin' ? [join(home, 'Library'), join(home, 'Library', 'Fonts')]
34
+ : xdgData(env) ? [xdgData(env), join(xdgData(env), 'fonts')]
35
+ : [join(home, '.local'), join(home, '.local', 'share'), join(home, '.local', 'share', 'fonts')];
36
+ for (const step of steps) {
37
+ const st = lstatSync(step, { throwIfNoEntry: false });
38
+ if (st && !st.isDirectory()) return `${step} is ${st.isSymbolicLink() ? 'a link' : 'not a folder'}`;
39
+ }
40
+ return null;
41
+ }
42
+
43
+ // `install --round` is the one write outside LitMuse's folder and Muse's own files: these two names, in that folder.
44
+ export function assertFontPath(target, { env = process.env, platform = process.platform } = {}) {
45
+ const dir = fontFolder({ env, platform });
46
+ if (!dir || !Object.values(FONT_FILES).some((name) => target === join(dir, name))) throw new Error(`refused: ${target} is not an icon font path LitMuse writes`);
47
+ return assertSafeWritePath(target);
48
+ }