@litfamily/litmuse 0.1.20 → 0.1.21

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/lib/install.mjs CHANGED
@@ -5,11 +5,12 @@ import { preflightDestinations, writeFileAtomic, copyFileAtomic } from './safe-w
5
5
  import { muse, museVersion, installedPlugin } from './muse.mjs';
6
6
  import { stageState, stageBundle, packageVersion } from './bundle.mjs';
7
7
  import { expectedApprovals, approvalStates } from './approvals.mjs';
8
- import { agentFilePlan, installAgentFile } from './agent-file.mjs';
8
+ import { agentFileAsks, 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
11
  import { noticeHash, wasShown, recordShown } from './shown.mjs';
12
12
  import { survey, findings, CLI } from './extensions.mjs';
13
+ import { planRows } from './install-cards.mjs';
13
14
 
14
15
  function remedy(state, detail, p) {
15
16
  const saved = `${p.stage}.saved-${new Date().toISOString().slice(0, 10)}`;
@@ -63,53 +64,98 @@ function samePath(a, b) {
63
64
  return real(a) === real(b);
64
65
  }
65
66
 
66
- export async function install({ env = process.env, flags = {}, interactive = false, ask, print = console.log }) {
67
+ const counted = (list) => {
68
+ const of = (kind, word) => {
69
+ const n = list.filter((a) => a.kind === kind).length;
70
+ return n ? [`${n} ${word}${n === 1 ? '' : 's'}`] : [];
71
+ };
72
+ return `${list.length} (${[...of('hook', 'hook'), ...of('agent', 'agent')].join(', ')})`;
73
+ };
74
+
75
+ export async function install({ env = process.env, flags = {}, interactive = false, ask, print = console.log, cards = null }) {
67
76
  const p = paths(env);
68
77
  const version = packageVersion();
69
78
  const scope = flags.scope || 'user';
70
- print(`LitMuse ${version} installer for Muse Code`);
79
+ // With cards, these lines are drawn as rows and panels instead.
80
+ const plain = cards ? () => {} : print;
81
+ let stage = 'Check';
82
+ const fail = (what, ...notes) => {
83
+ if (cards) {
84
+ cards.panel({
85
+ title: 'INSTALL STOPPED', bad: true,
86
+ sections: [{ rows: [
87
+ { mark: 'fail', label: 'Stage', value: stage }, { mark: 'fail', label: 'Reason', value: what },
88
+ { mark: 'note', label: 'Next', value: notes.length ? 'the lines below' : 'fix this, then run the install again' },
89
+ ] }],
90
+ });
91
+ if (notes.length) print('');
92
+ for (const line of notes) print(line);
93
+ } else for (const line of [`FAIL ${what}`, ...notes]) print(line);
94
+ return 1;
95
+ };
96
+ const section = (heading, lines) => {
97
+ if (cards) {
98
+ cards.text(heading, lines);
99
+ return;
100
+ }
101
+ print('');
102
+ print(heading);
103
+ for (const line of lines) print(line);
104
+ };
105
+ plain(`LitMuse ${version} installer for Muse Code`);
106
+ cards?.intro(`Installs into ${p.data}. Your Muse settings are backed up first.`);
71
107
 
72
108
  const major = Number(process.versions.node.split('.')[0]);
73
109
  if (major < 20) {
74
- print(`FAIL Node.js ${process.versions.node} is too old; LitMuse needs Node.js 20 or newer.`);
75
- return 1;
110
+ return fail(`Node.js ${process.versions.node} is too old; LitMuse needs Node.js 20 or newer.`);
76
111
  }
77
112
  const mv = museVersion(env);
78
113
  if (!mv) {
79
- print('FAIL muse was not found on PATH. Install Muse Code first (https://dev.meta.ai/docs/muse-code), sign in once, then run this again.');
80
- return 1;
114
+ return fail('muse was not found on PATH. Install Muse Code first (https://dev.meta.ai/docs/muse-code), sign in once, then run this again.');
81
115
  }
82
- print(`Host: ${mv}`);
116
+ plain(`Host: ${mv}`);
83
117
 
84
118
  const st = preflightDestinations(p) ?? stageState(p);
85
119
  if (['symlinked', 'foreign', 'modified'].includes(st.state)) {
86
- print(`FAIL destination ${st.state}: ${st.detail}`);
87
- print(remedy(st.state, st.detail, p));
88
- if (st.state === 'modified') for (const line of extensionRemedy(st.changed, p)) print(line);
89
- print('No files written.');
90
- return 1;
120
+ return fail(
121
+ `destination ${st.state}: ${st.detail}`,
122
+ remedy(st.state, st.detail, p),
123
+ ...(st.state === 'modified' ? extensionRemedy(st.changed, p) : []),
124
+ 'No files written.',
125
+ );
91
126
  }
92
127
 
93
128
  const existing = installedPlugin(env);
94
129
  const existingSource = existing?.source?.path;
95
130
  if (existingSource && !samePath(existingSource, p.stage)) {
96
- print(`FAIL Muse already has LitMuse ${existing.version ?? ''} installed from ${existingSource}.`.replace(' ', ' '));
97
- print(`This installer manages the copy in ${p.stage}. Remove the other one first with: muse plugins remove litmuse (this also clears its approvals), then run install again.`);
98
- print('No files written.');
99
- return 1;
131
+ return fail(
132
+ `Muse already has LitMuse ${existing.version ?? ''} installed from ${existingSource}.`.replace(' ', ' '),
133
+ `This installer manages the copy in ${p.stage}. Remove the other one first with: muse plugins remove litmuse (this also clears its approvals), then run install again.`,
134
+ 'No files written.',
135
+ );
100
136
  }
101
137
  const installArgs = existing ? ['plugins', 'update', 'litmuse', '--json'] : ['plugins', 'install', p.stage, '--scope', scope, '--json'];
102
138
  const approvals = expectedApprovals();
103
139
 
104
- print('');
105
- print('Plan');
106
- print(` bundle ${p.stage}${st.state === 'owned' ? ` (replaces LitMuse ${st.version})` : ''}`);
107
- print(` backups ${p.backups} (Muse settings.json and installed.json, when present)`);
108
- print(` receipt ${p.receipt}`);
109
- print(` rules file ${agentFilePlan({ env, flags })}`);
110
- print(` muse muse ${installArgs.join(' ')}`);
111
- print(` approvals up to ${approvals.length} capabilities may need your approval in Muse (hooks and agents):`);
112
- for (const a of approvals) print(` ${a.id}`);
140
+ const plan = [
141
+ ['bundle', `${p.stage}${st.state === 'owned' ? ` (replaces LitMuse ${st.version})` : ''}`],
142
+ ['backups', `${p.backups} (Muse settings.json and installed.json, when present)`],
143
+ ['receipt', p.receipt],
144
+ ['rules file', agentFilePlan({ env, flags })],
145
+ ['muse', `muse ${installArgs.join(' ')}`],
146
+ ['approvals', `up to ${approvals.length} capabilities may need your approval in Muse (hooks and agents):`],
147
+ ];
148
+ if (cards) {
149
+ cards.panel({
150
+ title: `LitMuse ${version} install plan`,
151
+ sections: [{ rows: planRows([['Host', mv], ...plan.map(([label, value]) => [label[0].toUpperCase() + label.slice(1), value]).slice(0, -1), ['Approvals', `up to ${counted(approvals)}`]]) }],
152
+ });
153
+ } else {
154
+ print('');
155
+ print('Plan');
156
+ for (const [label, value] of plan) print(` ${label.padEnd(12)}${value}`);
157
+ for (const a of approvals) print(` ${a.id}`);
158
+ }
113
159
 
114
160
  if (flags.dryRun) {
115
161
  print('');
@@ -126,51 +172,77 @@ export async function install({ env = process.env, flags = {}, interactive = fal
126
172
  const leftovers = [leftoverRuntime(p.data)].filter((d) => existsSync(d));
127
173
 
128
174
  const written = [];
175
+ const steps = cards?.work(`Installing LitMuse ${version}`, 'Install steps', [
176
+ ['Backups', 'save your Muse settings'], ['Bundle', 'copy the plugin bundle'], ['Validate', 'muse plugins validate'], ['Muse', `muse plugins ${existing ? 'update' : 'install'}`],
177
+ ]);
178
+ const step = (name) => {
179
+ stage = name;
180
+ steps?.next();
181
+ };
182
+ const stopped = (...told) => {
183
+ steps?.fail();
184
+ return fail(...told);
185
+ };
186
+ step('Backups');
129
187
  written.push(...backupHostFiles(p));
188
+ step('Bundle');
130
189
  stageBundle(p);
131
190
  written.push(p.stage);
132
191
 
192
+ step('Validate');
133
193
  const validation = muse(env, ['plugins', 'validate', p.stage, '--json']);
134
194
  const diagnostics = validation.json?.diagnostics ?? [];
135
195
  if (!validation.ok || validation.json?.valid !== true || diagnostics.length) {
136
- print('FAIL muse plugins validate rejected the bundle:');
137
- for (const d of diagnostics) print(` ${d.code ?? 'diagnostic'}: ${d.message ?? JSON.stringify(d)}`);
138
- if (!diagnostics.length) print(` ${validation.stderr.trim() || validation.stdout.trim()}`);
139
- print('Muse was left unchanged.');
140
- return 1;
196
+ return stopped(
197
+ 'muse plugins validate rejected the bundle:',
198
+ ...diagnostics.map((d) => ` ${d.code ?? 'diagnostic'}: ${d.message ?? JSON.stringify(d)}`),
199
+ ...(diagnostics.length ? [] : [` ${validation.stderr.trim() || validation.stdout.trim()}`]),
200
+ 'Muse was left unchanged.',
201
+ );
141
202
  }
142
203
 
204
+ step('Muse');
143
205
  const result = muse(env, installArgs);
144
206
  if (!result.ok) {
145
- print(`FAIL ${result.command} exited ${result.status}:`);
146
- print(` ${(result.stderr || result.stdout).trim().split('\n').slice(0, 6).join('\n ')}`);
147
- return 1;
207
+ return stopped(`${result.command} exited ${result.status}:`, ` ${(result.stderr || result.stdout).trim().split('\n').slice(0, 6).join('\n ')}`);
148
208
  }
149
209
  const cachePath = result.json?.installed?.cache_path;
150
210
  written.push(p.museInstalled);
151
211
  if (cachePath) written.push(cachePath);
152
- print('');
153
- print(existing
154
- ? `Installed: LitMuse ${version} is updated in Muse from ${p.stage}. Skills and commands are active now.`
155
- : `Installed: LitMuse ${version} is installed in Muse at ${scope} scope. Skills and commands are active now.`);
212
+ const installed = existing
213
+ ? `LitMuse ${version} is updated in Muse from ${p.stage}. Skills and commands are active now.`
214
+ : `LitMuse ${version} is installed in Muse at ${scope} scope. Skills and commands are active now.`;
215
+ plain('');
216
+ plain(`Installed: ${installed}`);
217
+ steps?.done();
156
218
 
157
219
  let states = approvalStates(muse(env, ['plugins', 'inspect', 'litmuse', '--json']).json);
158
220
  const pending = states.filter((s) => s.status !== 'trusted_enabled');
221
+ const named = (s) => ` ${s.id} (${s.what})`;
222
+ const asksApproval = pending.length > 0 && !flags.approve && interactive && Boolean(ask);
223
+ const questions = Number(asksApproval) + Number(agentFileAsks({ env, flags, interactive, ask, version }));
159
224
  if (pending.length) {
160
225
  let approve = Boolean(flags.approve);
161
226
  const decided = approve;
162
- if (!decided) {
163
- print('');
164
- print(`Muse runs plugin hooks and agents only after you approve them (an update re-arms the agent approvals, and the hook approvals whenever hook code changed). ${pending.length} are waiting:`);
165
- for (const s of pending) print(` ${s.id} (${s.what})`);
227
+ if (!decided && !(cards && asksApproval)) {
228
+ section(`Muse runs plugin hooks and agents only after you approve them (an update re-arms the agent approvals, and the hook approvals whenever hook code changed). ${pending.length} are waiting:`, pending.map(named));
166
229
  }
167
- if (!approve && interactive && ask) {
168
- approve = await ask(`Approve these ${pending.length} LitMuse capabilities now? [y/N] `);
230
+ if (asksApproval) {
231
+ approve = await ask(`Approve these ${pending.length} LitMuse capabilities now? [y/N] `, {
232
+ card: {
233
+ tag: `LIT 1/${questions}`,
234
+ title: 'Approvals',
235
+ note: `Muse runs plugin hooks and agents only after you approve them. Yes approves these ${counted(pending)} now; No prints the commands for later.`,
236
+ yes: `approve ${pending.length}`,
237
+ no: 'not now',
238
+ list: { hint: `l list all ${pending.length}`, heading: `${pending.length} LitMuse capabilities are waiting`, lines: pending.map((s) => (s.kind === 'hook' ? named(s) : ` ${s.id}`)) },
239
+ },
240
+ });
169
241
  }
170
242
  if (approve) {
171
243
  if (decided) {
172
- print('');
173
- print(`Approving ${pending.length} LitMuse capabilities...`);
244
+ plain('');
245
+ plain(`Approving ${pending.length} LitMuse capabilities...`);
174
246
  }
175
247
  const failed = [];
176
248
  for (const s of pending) {
@@ -178,32 +250,35 @@ export async function install({ env = process.env, flags = {}, interactive = fal
178
250
  if (!r.ok) failed.push(`${s.id}: ${(r.stderr || r.stdout).trim().split(/\r?\n/)[0]}`);
179
251
  }
180
252
  written.push(`${p.museSettings} (runtime_capabilities for litmuse)`);
181
- for (const f of failed) print(` FAIL approve ${f}`);
253
+ for (const f of failed) {
254
+ if (cards) cards.row('fail', 'Approve', f);
255
+ else print(` FAIL approve ${f}`);
256
+ }
182
257
  states = approvalStates(muse(env, ['plugins', 'inspect', 'litmuse', '--json']).json);
183
258
  const byId = new Map(states.map((s) => [s.id, s]));
184
259
  const approved = pending.filter((s) => byId.get(s.id)?.status === 'trusted_enabled');
185
260
  const still = states.filter((s) => s.status !== 'trusted_enabled');
186
261
  if (approved.length) {
187
- print('');
188
- print(`Approved ${approved.length} LitMuse capabilities:`);
189
- for (const s of approved) print(` ${s.id} (${s.what})`);
190
- }
191
- if (still.length) {
192
- print('');
193
- print(`${still.length} are still waiting:`);
194
- for (const s of still) print(` ${s.id} (${s.what})`);
195
- } else {
196
- print('No capabilities are still waiting for approval.');
262
+ if (cards) cards.row('done', 'Approved', counted(approved));
263
+ else section(`Approved ${approved.length} LitMuse capabilities:`, approved.map(named));
197
264
  }
198
- } else {
199
- print('');
200
- print('Approval needed. Run these when you are ready (or rerun install with --approve):');
201
- for (const s of pending) print(` muse plugins approve ${s.id}`);
265
+ // With cards, the closing card and the commands after it say what is left.
266
+ if (!cards && still.length) section(`${still.length} are still waiting:`, still.map(named));
267
+ else if (!cards) print('No capabilities are still waiting for approval.');
268
+ } else if (!cards) {
269
+ section('Approval needed. Run these when you are ready (or rerun install with --approve):', pending.map((s) => ` muse plugins approve ${s.id}`));
202
270
  }
203
271
  }
204
272
 
205
- print('');
206
- written.push(...await installAgentFile({ env, flags, interactive, ask, print, version, backupDir: p.backups }));
273
+ plain('');
274
+ let rules = null;
275
+ const rulesRow = (line) => {
276
+ const value = line.replace('AGENT_FILE: ', '');
277
+ rules = { mark: /^(created|updated|unchanged)/.test(value) ? 'done' : /^(off|skipped)/.test(value) ? 'note' : 'warn', label: 'Rules file', value };
278
+ };
279
+ written.push(...await installAgentFile({
280
+ env, flags, interactive, ask, print: cards ? rulesRow : print, version, backupDir: p.backups, tag: `LIT ${questions}/${questions}`,
281
+ }));
207
282
 
208
283
  const left = states.filter((s) => s.status !== 'trusted_enabled').length;
209
284
  // A new version (or a first install) arms the one-time notice for the next Muse session; a same-version reinstall
@@ -219,23 +294,50 @@ export async function install({ env = process.env, flags = {}, interactive = fal
219
294
  }, null, 2)}\n`);
220
295
  written.push(p.receipt);
221
296
 
222
- print('');
223
- print('Written:');
224
- for (const w of written) print(` ${w}`);
225
- print('');
297
+ plain('');
298
+ plain('Written:');
299
+ for (const w of written) plain(` ${w}`);
300
+ plain('');
301
+ if (cards) {
302
+ const names = new Map([
303
+ [p.stage, 'Bundle'], [p.museInstalled, 'Muse plugin list'], [cachePath, 'Muse copy'], [p.museRules, 'Rules file'], [p.notice, 'First-run note'], [p.receipt, 'Receipt'], [p.config, 'Config'],
304
+ ]);
305
+ const nameOf = (path) => names.get(path) ?? (path.startsWith(p.backups) ? 'Backup' : 'Muse settings');
306
+ const waiting = states.filter((s) => s.status !== 'trusted_enabled');
307
+ cards.panel({
308
+ title: `LitMuse ${version} is installed`,
309
+ sections: [
310
+ { head: 'Installed', rows: [
311
+ { label: 'Muse plugin', value: `${existing ? 'updated' : `installed at ${scope} scope`}; skills and commands are active now` },
312
+ ...written.filter((path) => path !== p.museRules).map((path) => ({ label: nameOf(path), value: path })),
313
+ ...(rules ? [rules] : []),
314
+ left === 0 ? { label: 'Approvals', value: 'every hook and agent is approved' } : { mark: 'warn', label: 'Approvals', value: `${counted(waiting)} still to approve; the commands are below` },
315
+ ] },
316
+ { head: 'Next', rows: planRows([
317
+ ...(left ? [['Approve', 'run the commands below']] : []),
318
+ ['Start', 'open Muse in a project and begin a prompt with lit'], ['Check', 'npx @litfamily/litmuse doctor'],
319
+ ]) },
320
+ ],
321
+ });
322
+ if (left) cards.text('Approval needed. Run these when you are ready (or rerun install with --approve):', waiting.map((s) => ` muse plugins approve ${s.id}`));
323
+ }
226
324
  // The notice and the fixed line after it are printed once per text; the live count of folders to check always is.
227
325
  const [fixedLine, ...liveLines] = extensionLines(env);
228
326
  const noticeLines = [...extensionsNotice({ leftovers }), fixedLine];
229
327
  const hash = noticeHash(noticeLines.join('\n'));
230
328
  if (wasShown(p.shown, hash)) {
231
- for (const line of liveLines) print(line);
329
+ if (cards && liveLines.length) cards.text('LitFamily extensions', liveLines);
330
+ else for (const line of liveLines) print(line);
232
331
  } else {
233
- for (const line of [...noticeLines, ...liveLines]) print(line);
332
+ if (cards) cards.text(noticeLines[0], [...noticeLines.slice(1), ...liveLines]);
333
+ else for (const line of [...noticeLines, ...liveLines]) print(line);
234
334
  recordShown(p.shown, hash);
235
335
  }
236
- print('');
237
- print(left === 0
238
- ? 'Status: Ready. Start Muse in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litmuse doctor`.'
239
- : `Status: installed, approval needed for ${left} capabilities. Run the commands above, then \`npx @litfamily/litmuse doctor\`.`);
336
+ if (!cards) {
337
+ print('');
338
+ print(left === 0
339
+ ? 'Status: Ready. Start Muse in a project and begin a prompt with `lit`. Check any time with `npx @litfamily/litmuse doctor`.'
340
+ : `Status: installed, approval needed for ${left} capabilities. Run the commands above, then \`npx @litfamily/litmuse doctor\`.`);
341
+ }
240
342
  return 0;
241
343
  }
package/lib/mark.mjs CHANGED
@@ -100,8 +100,7 @@ const tagline = (width, depth) => {
100
100
 
101
101
  // The mark as printable rows for `cols` cells at `depth`: the art, then one centred tagline.
102
102
  // Below 24 columns it is the single plain line.
103
- export function markRows({ cols = 80, depth = 'none' } = {}) {
104
- const size = markSize(cols);
103
+ export function markRows({ cols = 80, depth = 'none', size = markSize(cols) } = {}) {
105
104
  if (!size) return [FALLBACK];
106
105
  const art = depth === 'none' ? [...MONO_ROWS[size]] : artRows(size, depth);
107
106
  return [...art, tagline(PIXEL_ROWS[size][0].length, depth)];
@@ -5,7 +5,6 @@ import { newerThan } from '../plugin/hooks/lib/common.mjs';
5
5
  import { readManifest } from './bundle.mjs';
6
6
  import { paths } from './paths.mjs';
7
7
  import { gauge } from '../plugin/lib/rewind/gauge.mjs';
8
- import { ink, neon, roundGauge, stagePill } from './sunset.mjs';
9
8
  // One rainbow-tinted line at most (a static ANSI gradient, flash-safe); it marks the adhd turn.
10
9
  import { rainbowLine } from '../plugin/lib/rewind/rainbow.mjs';
11
10
 
@@ -258,7 +257,7 @@ const paint = (code, text, color) => (color ? `\u001b[${code}m${text}\u001b[0m`
258
257
 
259
258
  // Waiting on the user: a paused thread, or a lane that reported failure. A turn where the
260
259
  // model asked a question but left no tool state is not visible to the card.
261
- const waitingOf = (card) => (card.threads?.rows ?? []).some((row) => row.status === 'paused')
260
+ export const waitingOf = (card) => (card.threads?.rows ?? []).some((row) => row.status === 'paused')
262
261
  || (card.lanes ?? []).some((lane) => lane.status === 'failed');
263
262
 
264
263
  // With a pill (truecolor TTY only) the pill stands in for the leading `LIT · `.
@@ -273,7 +272,7 @@ const headlineFor = (card, color, pill = null) => {
273
272
 
274
273
  // Canonical review-lane display names, in REVIEW_LANES order; the strip reads the same
275
274
  // list, so the two cannot drift apart.
276
- const REVIEW_LANE_LABELS = Object.freeze({ goal: 'scope', quality: 'package', security: 'security', qa: 'tests+evidence', context: 'surface' });
275
+ export const REVIEW_LANE_LABELS = Object.freeze({ goal: 'scope', quality: 'package', security: 'security', qa: 'tests+evidence', context: 'surface' });
277
276
  const VERDICT_DOT = Object.freeze({ pass: ['32;1', '●'], fail: ['31;1', '●'], running: ['33;1', '◐'], pending: ['33', '○'] });
278
277
 
279
278
  const laneSegment = (id, verdict, color) => {
@@ -293,7 +292,7 @@ const lanesStrip = (card, color) => {
293
292
  // prints one celebratory line until the freshness window passes, then the card settles on
294
293
  // its own. A published release has no signal the card can see.
295
294
  const BURST_FRESH_MS = 15 * 60 * 1000;
296
- const burstOf = (card, now) => {
295
+ export const burstOf = (card, now) => {
297
296
  const plan = card.plan;
298
297
  if (plan && plan.total > 0 && plan.done >= plan.total && Number.isFinite(plan.mtimeMs) && now - plan.mtimeMs <= BURST_FRESH_MS) {
299
298
  return `✨ done: ${plan.file} · ${plan.done}/${plan.total} rows ticked ✨`;
@@ -305,14 +304,6 @@ const burstOf = (card, now) => {
305
304
  return null;
306
305
  };
307
306
 
308
- // The sunset's light for this card, or null when the burst has the stage: amber while it waits on the user, rainbow
309
- // for the adhd turn, dimmed with no route.
310
- export function cardLight(card) {
311
- if (burstOf(card, card.now ?? Date.now())) return null;
312
- const look = !card.active ? 'sunset' : waitingOf(card) ? 'turn' : card.route === 'lit-adhd' ? 'rainbow' : 'sunset';
313
- return { look, dim: !card.active };
314
- }
315
-
316
307
  // Work is going on: a route is active, its session has not stopped since the record last moved, and something moved
317
308
  // in the last quarter hour. Only then does the watched card move.
318
309
  export function cardWorking(card, { env = process.env, now = card.now ?? Date.now() } = {}) {
@@ -325,9 +316,7 @@ export function cardWorking(card, { env = process.env, now = card.now ?? Date.no
325
316
 
326
317
  // badge: { text, width } from lib/mark.mjs litPill, or null. It is dropped when the headline
327
318
  // would no longer fit `cols`, so the plain headline stays the fallback at every width.
328
- // dress: { caps } paints the thread rows in the sunset's colours (a truecolor terminal with room for the scene); the
329
- // words and widths stay the same.
330
- export function renderCard(card, { badge = null, cols = Infinity, dress = null } = {}) {
319
+ export function renderCard(card, { badge = null, cols = Infinity } = {}) {
331
320
  const out = [];
332
321
  const color = !card.noColor;
333
322
  const plainRest = headlineFor(card, false).length - 'LIT · '.length;
@@ -338,17 +327,11 @@ export function renderCard(card, { badge = null, cols = Infinity, dress = null }
338
327
  const threads = card.threads?.rows ?? [];
339
328
  if (threads.length) {
340
329
  out.push('threads:');
341
- const current = threads.findLastIndex((thread) => !thread.sibling && thread.status === 'active');
342
330
  threads.forEach((thread, index) => {
343
331
  const branch = index === threads.length - 1 && !card.threads.omitted ? '└─' : '├─';
344
332
  const name = thread.pane ? `${thread.skill} · ${thread.pane}` : thread.skill;
345
333
  const where = thread.sibling && !thread.pane ? ` (${thread.session})` : '';
346
- const rail = dress ? ink([...branch].map((ch) => ({ ch, fg: neon(threads.length > 1 ? index / (threads.length - 1) : 0) }))) : branch;
347
- // The current stage is a pill as wide as before: its letters filled, or, with round caps, the two spaces around it.
348
- const plainStage = thread.stage ? ` ${thread.stage} ` : ' ';
349
- const stage = dress && thread.stage && index === current ? stagePill(plainStage, dress.caps) : plainStage;
350
- const meter = dress?.caps ? roundGauge(thread.gauge) : thread.gauge;
351
- out.push(`${rail} ${name}${stage}${thread.status}${thread.gauge ? ` ${meter}` : ''}${where}`);
334
+ out.push(`${branch} ${name}${thread.stage ? ` ${thread.stage}` : ''} ${thread.status}${thread.gauge ? ` ${thread.gauge}` : ''}${where}`);
352
335
  });
353
336
  if (card.threads.omitted) out.push(`+${card.threads.omitted} more`);
354
337
  }
package/lib/sunset.mjs CHANGED
@@ -1,25 +1,20 @@
1
1
  // The status card's sunset, for a person's truecolor terminal only: a half-sunk sun with stars over it and a sea under
2
- // it, painted after the end of each row's words. Words are never touched; a row with no room keeps exactly its text.
2
+ // it, painted only in cells that hold no text.
3
3
  // `t` is seconds into the motion; null is the resting pose. Shapes hold still: only colours move, plus the ASCII sea,
4
4
  // stars and shooting star.
5
5
  import { displayWidth } from '../plugin/lib/rewind/gauge.mjs';
6
6
  import { sample } from './mark.mjs';
7
7
 
8
8
  const ESC = '\u001b';
9
- export const MIN_COLS = 90;
9
+ export const MIN_COLS = 64;
10
10
  export const MAX_WIDTH = 120;
11
11
  export const SUN_W = 18;
12
12
  export const SUN_ROWS = 3;
13
13
  // The moment a single print of a working card shows. No shooting star is in flight then.
14
14
  export const STILL_T = 4;
15
- export const BRAND = Object.freeze(['#ff8f3c', '#ff2d8a']);
16
- const STAGE = Object.freeze(['#b48cff', '#8be9fd']);
17
15
  const NEON = Object.freeze(['#ff2d95', '#b48cff', '#8be9fd']);
18
- const INK = '#0b0e14';
19
- const TRACK = '#2a2340';
20
- const FAINT = '#30363d';
16
+ export const FAINT = '#30363d';
21
17
  const SLIT = '#1a1030';
22
- const CAP = Object.freeze(['', '']);
23
18
 
24
19
  const LOOKS = {
25
20
  sunset: { sun: [['#ffd24a', '#fff0a0'], ['#ff8f3c', '#ffc15a'], ['#ff2d8a', '#ff6b8f']], sea: ['#ffdc73', '#ff9a4a', '#ff4f8b', '#b457d6', '#5a46a8'] },
@@ -33,21 +28,11 @@ export function sceneOn({ depth, env = process.env, cols }) {
33
28
  return depth === 'truecolor' && !light && cols >= MIN_COLS;
34
29
  }
35
30
 
36
- // These terminals draw the rounded caps themselves, whatever the font.
37
- export const roundCaps = (env = process.env) => Boolean(env.WT_SESSION) || env.TERM_PROGRAM === 'vscode';
38
-
39
31
  export const motionOff = (env = process.env) => /^(off|reduced|0)$/i.test(env.LITMUSE_MOTION ?? '');
40
32
 
41
33
  const SGR = /\u001b\[[0-9;]*m/gu;
42
34
  const charCells = (ch) => Math.max(displayWidth(ch), /\p{Emoji_Presentation}/u.test(ch) ? 2 : 0);
43
35
 
44
- // Cells a row's words take, or Infinity when terminals disagree about them (tabs, joined emoji, stray controls).
45
- export function rowCells(row) {
46
- const text = row.replace(SGR, '');
47
- if (/[\p{Cc}‍️\p{Regional_Indicator}]/u.test(text)) return Infinity;
48
- return [...text].reduce((sum, ch) => sum + charCells(ch), 0);
49
- }
50
-
51
36
  // A row cut into rows of at most `width` cells; the colour in force carries on. Control characters are dropped.
52
37
  export function wrapRow(row, width) {
53
38
  const out = [];
@@ -105,33 +90,6 @@ export function ink(cells) {
105
90
  return last ? `${out}${ESC}[0m` : out;
106
91
  }
107
92
 
108
- // Text on a fill graded along two stops. Its first and last characters are padding, which become round caps.
109
- export function gradedPill(text, stops, caps) {
110
- const chars = [...text];
111
- const last = chars.length - 1;
112
- return ink(chars.map((ch, i) => {
113
- const fill = sample(stops, i / last);
114
- if (caps && (i === 0 || i === last)) return { ch: CAP[i === 0 ? 0 : 1], fg: fill };
115
- return { ch, fg: INK, bg: fill, bold: true };
116
- }));
117
- }
118
-
119
- // ` RED ` as the current stage: round caps take its two spaces, otherwise only the letters are filled.
120
- export function stagePill(text, caps) {
121
- if (caps) return gradedPill(text, STAGE, true);
122
- const chars = [...text];
123
- const span = Math.max(1, chars.length - 3);
124
- return ink(chars.map((ch, i) => (i === 0 || i === chars.length - 1 ? null : { ch, fg: INK, bg: sample(STAGE, Math.min(1, (i - 1) / span)), bold: true })));
125
- }
126
-
127
- // `[▉▉░] 2/3` with its brackets as round caps on one smooth track, in the same cells. Anything else is returned as is.
128
- export function roundGauge(text) {
129
- const parts = /^\[([▉░]+)\](.*)$/u.exec(text);
130
- if (!parts) return text;
131
- const tints = [...parts[1]].map((ch, i, all) => (ch === '▉' ? sample(['#ff8f3c', '#ff2d8a'], i / all.length) : TRACK));
132
- return ink([{ ch: CAP[0], fg: tints[0] }, ...tints.map((bg) => ({ ch: ' ', bg })), { ch: CAP[1], fg: tints.at(-1) }]) + parts[2];
133
- }
134
-
135
93
  // The neon a place on the card takes, pink to violet to cyan.
136
94
  export const neon = (k) => (k < 0.5 ? mix(NEON[0], NEON[1], k * 2) : mix(NEON[1], NEON[2], k * 2 - 1));
137
95
 
@@ -148,18 +106,21 @@ const STARS = [[0, -30], [1, -24], [0, -18], [1, -13], [0, -9], [1, -5], [0, 22]
148
106
  const CLEAR = 3;
149
107
 
150
108
  /**
151
- * Where the scene goes on these rows: the lowest three rows in a run with room for the sun, so one long row moves the
152
- * sun up instead of putting it out. `top` is null when there is no room anywhere. Work this out once per state, then
153
- * paint it as often as needed.
109
+ * Where the scene goes over rows of cells, where an empty cell is null: the lowest three rows in a run that leave the
110
+ * sun room, as near its usual place as they allow. `top` is null when there is no room anywhere.
154
111
  */
155
- export function place(rows, width) {
156
- const ends = rows.map(rowCells);
157
- const at = Math.round(width * 0.62);
158
- let top = null;
159
- for (let r = rows.length - SUN_ROWS; r >= 0 && top === null; r -= 1) {
160
- if (at + SUN_W + 2 <= width && [0, 1, 2].every((i) => ends[r + i] + 2 <= at)) top = r;
112
+ export function place(grid, width) {
113
+ const home = Math.round(width * 0.62);
114
+ const free = (r, from, to) => {
115
+ for (let x = from; x < to; x += 1) if (x < 0 || x >= width || grid[r][x]) return false;
116
+ return true;
117
+ };
118
+ const spots = Array.from({ length: Math.max(0, width - SUN_W - 1) }, (_, i) => i).filter((at) => Math.abs(at - home) <= 14).sort((a, b) => Math.abs(a - home) - Math.abs(b - home));
119
+ for (let top = grid.length - SUN_ROWS; top >= 0; top -= 1) {
120
+ const at = spots.find((x) => [0, 1, 2].every((i) => free(top + i, x - 2, x + SUN_W + 2)));
121
+ if (at !== undefined) return { grid, width, at, top, sea: top + 2 };
161
122
  }
162
- return { ends, width, at, top, sea: top === null ? rows.length - 1 : top + 2 };
123
+ return { grid, width, at: home, top: null, sea: grid.length - 1 };
163
124
  }
164
125
 
165
126
  function seaCell(dx, s, stops) {
@@ -173,11 +134,11 @@ function seaCell(dx, s, stops) {
173
134
  }
174
135
 
175
136
  /**
176
- * The scene for one moment: a Map from row index to that row's cells, `width` long and holey; the cells before the
177
- * row's end are always empty. `look` is sunset, turn (amber) or rainbow; `dim` is the resting card's quieter light.
137
+ * The scene for one moment: a Map from row index to that row's cells, `width` long and holey, and holey wherever the
138
+ * grid holds text. `look` is sunset, turn (amber) or rainbow; `dim` is the resting card's quieter light.
178
139
  */
179
140
  export function paint(spot, { t = null, look = 'sunset', dim = false } = {}) {
180
- const { ends, width, at, top, sea } = spot;
141
+ const { grid, width, at, top, sea } = spot;
181
142
  const out = new Map();
182
143
  if (top === null && (t === null || sea < 0)) return out;
183
144
  const s = t ?? 0;
@@ -188,7 +149,11 @@ export function paint(spot, { t = null, look = 'sunset', dim = false } = {}) {
188
149
  if (!out.has(r)) out.set(r, new Array(width).fill(null));
189
150
  return out.get(r);
190
151
  };
191
- const clear = (r, x) => x >= 0 && x < width && x - ends[r] >= CLEAR;
152
+ const clear = (r, x) => {
153
+ if (x < 0 || x >= width) return false;
154
+ for (let d = -CLEAR + 1; d < CLEAR; d += 1) if (grid[r][x + d]) return false;
155
+ return true;
156
+ };
192
157
  const mid = at + SUN_W / 2 - 0.5;
193
158
  if (top !== null) {
194
159
  for (const [r, dx] of STARS) {
@@ -219,14 +184,3 @@ export function paint(spot, { t = null, look = 'sunset', dim = false } = {}) {
219
184
  }
220
185
  return out;
221
186
  }
222
-
223
- // Rows with the scene painted after their words; a row the scene does not reach is returned as it came.
224
- export function paintRows(rows, width, options) {
225
- const spot = place(rows, width);
226
- const tails = paint(spot, options);
227
- return rows.map((text, r) => {
228
- const cells = tails.get(r)?.slice(spot.ends[r]);
229
- const last = cells ? cells.findLastIndex(Boolean) : -1;
230
- return last < 0 ? text : text + ink(cells.slice(0, last + 1));
231
- });
232
- }