@osdlc/wayfinder 0.0.1-stage → 0.7.1

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +245 -0
  2. package/CONTRIBUTING.md +62 -0
  3. package/{LICENSE → LICENSE-APACHE} +1 -11
  4. package/LICENSE-MIT +21 -0
  5. package/README.md +505 -2
  6. package/SECURITY.md +44 -0
  7. package/bin/way.js +18 -0
  8. package/dist/app.d.ts +24 -0
  9. package/dist/app.js +24 -0
  10. package/dist/args.d.ts +44 -0
  11. package/dist/args.js +93 -0
  12. package/dist/cache.d.ts +7 -0
  13. package/dist/cache.js +15 -0
  14. package/dist/catalog.d.ts +38 -0
  15. package/dist/catalog.js +61 -0
  16. package/dist/clean-command.d.ts +43 -0
  17. package/dist/clean-command.js +274 -0
  18. package/dist/cli.d.ts +76 -0
  19. package/dist/cli.js +612 -0
  20. package/dist/config-command.d.ts +52 -0
  21. package/dist/config-command.js +342 -0
  22. package/dist/config.d.ts +367 -0
  23. package/dist/config.js +700 -0
  24. package/dist/devlink.d.ts +14 -0
  25. package/dist/devlink.js +30 -0
  26. package/dist/groups.d.ts +34 -0
  27. package/dist/groups.js +38 -0
  28. package/dist/guide.d.ts +32 -0
  29. package/dist/guide.js +411 -0
  30. package/dist/http.d.ts +22 -0
  31. package/dist/http.js +149 -0
  32. package/dist/origin-owner.d.ts +14 -0
  33. package/dist/origin-owner.js +69 -0
  34. package/dist/page.d.ts +15 -0
  35. package/dist/page.js +58 -0
  36. package/dist/providers-command.d.ts +40 -0
  37. package/dist/providers-command.js +132 -0
  38. package/dist/serve.d.ts +97 -0
  39. package/dist/serve.js +678 -0
  40. package/dist/tools.d.ts +46 -0
  41. package/dist/tools.js +102 -0
  42. package/dist/trust-command.d.ts +33 -0
  43. package/dist/trust-command.js +221 -0
  44. package/dist/trust-store.d.ts +18 -0
  45. package/dist/trust-store.js +46 -0
  46. package/dist/tui.d.ts +178 -0
  47. package/dist/tui.js +846 -0
  48. package/dist/web/main.js +2315 -0
  49. package/dist/web/page.html +110 -0
  50. package/dist/web/styles.css +1514 -0
  51. package/dist/xdg.d.ts +10 -0
  52. package/dist/xdg.js +17 -0
  53. package/package.json +54 -9
package/dist/tui.js ADDED
@@ -0,0 +1,846 @@
1
+ /**
2
+ * The terminal UI — browse every task in a repository, and run one.
3
+ *
4
+ * The affordance a browser cannot have: Enter RUNS the selected task, in this
5
+ * shell, with the terminal handed to it. A web view can only ever offer you
6
+ * something to paste.
7
+ *
8
+ * Dependency-free: raw mode, ANSI, and one frame string per keystroke. A TUI
9
+ * toolkit would be a heavier dependency than the code it saves, and this has to
10
+ * keep working from a checkout whose node_modules is the thing you are trying
11
+ * to repair. The CLI routes its output through the `CliIo` seam so
12
+ * `main()` is testable without touching a real stream, but this file writes
13
+ * to `process.stdout` directly — owning the interactive terminal, raw mode,
14
+ * the alternate screen, handing the terminal to a spawned task, is the whole
15
+ * point of it, and that job is outside the seam by design.
16
+ *
17
+ * Collection is asynchronous, which is what most of the state machinery below
18
+ * is for: keystrokes arrive mid-refresh, and a row can be stale.
19
+ */
20
+ import { spawnRunner, streamRunner } from '@osdlc/command-seam';
21
+ import { tasks as allTasks, } from '@osdlc/system-model/detect';
22
+ import { humanAge, humanMs } from '@osdlc/system-model/duration';
23
+ import { matchEntry, terms as splitTerms } from '@osdlc/system-model/match';
24
+ import { paramShape } from '@osdlc/system-model/params';
25
+ import { APP, BIN } from "./app.js";
26
+ import { runArgv, splitArgs } from "./args.js";
27
+ import { cacheDir } from "./cache.js";
28
+ import { collectAndCache, freshStates, fromStore, makeProject, orderedCatalog, readCachedCatalog, } from "./catalog.js";
29
+ import { loadConfig } from "./config.js";
30
+ import { appTrustStore } from "./trust-store.js";
31
+ import { groupOf, runnerLabel } from "./groups.js";
32
+ // ---------------------------------------------------------------- ansi
33
+ const ALT_ON = '\x1b[?1049h';
34
+ const ALT_OFF = '\x1b[?1049l';
35
+ const HIDE = '\x1b[?25l';
36
+ const SHOW = '\x1b[?25h';
37
+ const HOME = '\x1b[H';
38
+ const CLEAR_EOL = '\x1b[K';
39
+ const CLEAR_BELOW = '\x1b[J';
40
+ const COLOR = !process.env['NO_COLOR'] && process.stdout.isTTY;
41
+ const sgr = (code) => (s) => (COLOR ? `\x1b[${code}m${s}\x1b[0m` : s);
42
+ const dim = sgr('2');
43
+ const bold = sgr('1');
44
+ const green = sgr('32');
45
+ const cyan = sgr('36');
46
+ const yellow = sgr('33');
47
+ const red = sgr('31');
48
+ const invert = sgr('7');
49
+ const hit = sgr('1;33');
50
+ /**
51
+ * Compose chunks into one line of exactly `width` columns. Truncation happens
52
+ * on the PLAIN text — measuring a string that already carries escape sequences
53
+ * counts the escapes as columns and wraps the line.
54
+ */
55
+ function line(chunks, width) {
56
+ let used = 0;
57
+ let out = '';
58
+ for (const chunk of chunks) {
59
+ if (used >= width)
60
+ break;
61
+ let text = chunk.text;
62
+ if (used + text.length > width)
63
+ text = text.slice(0, Math.max(0, width - used - 1)) + '…';
64
+ used += text.length;
65
+ out += chunk.paint ? chunk.paint(text) : text;
66
+ }
67
+ return out + CLEAR_EOL;
68
+ }
69
+ // ---------------------------------------------------------------- state
70
+ const ALL = 'all';
71
+ /**
72
+ * The module singleton.
73
+ *
74
+ * Exported for one reason: `runTui` owns a real terminal and never returns, so
75
+ * the selection rule — the thing that must survive a refresh reordering and
76
+ * dropping rows underneath the cursor — is only testable through this and
77
+ * { recompute}. Nothing outside a test writes to it.
78
+ */
79
+ export const state = {
80
+ catalog: null,
81
+ project: makeProject(),
82
+ projectToolsPending: false,
83
+ root: process.cwd(),
84
+ options: {},
85
+ runnerOrder: undefined,
86
+ env: undefined,
87
+ home: undefined,
88
+ store: '',
89
+ cache: [],
90
+ runner: ALL,
91
+ query: '',
92
+ mode: 'fuzzy',
93
+ servicesOnly: false,
94
+ selectedId: null,
95
+ scroll: 0,
96
+ message: '',
97
+ loading: false,
98
+ gate: null,
99
+ confirmingTrust: false,
100
+ entering: null,
101
+ settings: null,
102
+ generation: 0,
103
+ inFlight: null,
104
+ rows: [],
105
+ };
106
+ function reportFor(runner) {
107
+ return state.catalog?.reports.find((r) => r.runner === runner);
108
+ }
109
+ /** How many runners went uncollected for want of trust; 0 when trust is not the reason. */
110
+ function withheldForTrust() {
111
+ if (state.gate?.reason !== 'untrusted')
112
+ return 0;
113
+ return state.catalog?.reports.filter((r) => r.skippedForExec).length ?? 0;
114
+ }
115
+ function tabs() {
116
+ return [ALL, ...(state.catalog?.reports ?? []).map((r) => r.runner)];
117
+ }
118
+ /** The cache verdict for one runner, or undefined when nothing describes it. */
119
+ function cacheFor(runner) {
120
+ return state.cache.find((c) => c.runner === runner);
121
+ }
122
+ /** Every runner whose rows on screen came out of the store and are out of date. */
123
+ function staleRunners() {
124
+ return state.cache.filter((c) => c.state === 'stale');
125
+ }
126
+ /**
127
+ * What the status line says about the rows on screen, in three states.
128
+ *
129
+ * Fresh says NOTHING: a line that is always there is a line nobody reads, and
130
+ * there is nothing here to report.
131
+ *
132
+ * Stale-and-slow is separated from ordinary stale because it is the case the
133
+ * whole cache exists for. A runner this repository has MEASURED at several
134
+ * seconds is why the screen would otherwise have been empty, and telling the
135
+ * user "a moment" in the same voice as a 200ms refresh would waste the one
136
+ * warning that matters. Slow is measured, never declared — a runner that is
137
+ * quick here is not called slow because it is slow elsewhere.
138
+ */
139
+ export function refreshNote(rows, loading) {
140
+ const stale = rows.filter((r) => r.state === 'stale');
141
+ if (stale.length === 0)
142
+ return null;
143
+ const named = (r) => r.estimateMs === null
144
+ ? `${r.runner} (never timed here)`
145
+ : `${r.runner} (~${humanMs(r.estimateMs)})`;
146
+ const slow = stale.filter((r) => r.slow);
147
+ if (!loading) {
148
+ // The refresh is over and these rows are still what the store held: it
149
+ // failed, or it has not been asked for yet. Saying "re-probing" would
150
+ // describe work nobody is doing.
151
+ return {
152
+ slow: slow.length > 0,
153
+ text: `cached rows: ${stale.map((r) => `${r.runner} ${humanAge(r.ageMs)}`).join(', ')} — ^r to re-probe`,
154
+ };
155
+ }
156
+ if (slow.length > 0) {
157
+ const rest = stale.filter((r) => !slow.includes(r));
158
+ return {
159
+ slow: true,
160
+ text: `cached rows — ${slow.map(named).join(', ')} ` +
161
+ `${slow.length === 1 ? 'is' : 'are'} slow to probe here, so this takes a moment` +
162
+ (rest.length > 0 ? `; also re-probing ${rest.map(named).join(', ')}` : ''),
163
+ };
164
+ }
165
+ return { slow: false, text: `cached rows — re-probing ${stale.map(named).join(', ')}` };
166
+ }
167
+ function chainOf(runner) {
168
+ return reportFor(runner)?.chain ?? [];
169
+ }
170
+ function inScope() {
171
+ const catalog = state.catalog;
172
+ if (catalog === null)
173
+ return [];
174
+ return state.runner === ALL ? allTasks(catalog) : (reportFor(state.runner)?.tasks ?? []);
175
+ }
176
+ function visibleRows() {
177
+ const queryTerms = splitTerms(state.query);
178
+ const rows = [];
179
+ for (const task of inScope()) {
180
+ if (state.servicesOnly && !task.persistent.value)
181
+ continue;
182
+ if (queryTerms.length === 0) {
183
+ rows.push({ task, score: 0, labelHits: null });
184
+ continue;
185
+ }
186
+ const m = matchEntry(task, queryTerms, state.mode);
187
+ if (m)
188
+ rows.push({ task, score: m.score, labelHits: m.labelHits });
189
+ }
190
+ if (queryTerms.length)
191
+ rows.sort((a, b) => b.score - a.score);
192
+ return rows;
193
+ }
194
+ /** Index of the selected task, or 0 when its id is no longer present. */
195
+ export function cursor() {
196
+ if (state.selectedId === null)
197
+ return 0;
198
+ const at = state.rows.findIndex((r) => r.task.id === state.selectedId);
199
+ return at === -1 ? 0 : at;
200
+ }
201
+ function select(index) {
202
+ const clamped = Math.max(0, Math.min(index, state.rows.length - 1));
203
+ state.selectedId = state.rows[clamped]?.task.id ?? null;
204
+ }
205
+ // ---------------------------------------------------------------- render
206
+ /** The chain, dimmed except for the leaf, with matched characters picked out. */
207
+ function chainChunks(row) {
208
+ const { path } = row.task;
209
+ const marks = new Set(row.labelHits ?? []);
210
+ const chunks = [];
211
+ let at = 0;
212
+ for (let p = 0; p < path.length; p++) {
213
+ const leaf = p === path.length - 1;
214
+ let run = '';
215
+ let marked = marks.has(at);
216
+ for (const ch of path[p]) {
217
+ const on = marks.has(at);
218
+ if (on !== marked) {
219
+ chunks.push({ text: run, paint: marked ? hit : leaf ? bold : dim });
220
+ run = '';
221
+ marked = on;
222
+ }
223
+ run += ch;
224
+ at++;
225
+ }
226
+ if (run)
227
+ chunks.push({ text: run, paint: marked ? hit : leaf ? bold : dim });
228
+ if (!leaf) {
229
+ chunks.push({ text: ' > ', paint: dim });
230
+ at++; // the " " the label was joined on
231
+ }
232
+ }
233
+ return chunks;
234
+ }
235
+ /**
236
+ * The whole screen as one string.
237
+ *
238
+ * Exported alongside {@link state} and {@link recompute} so the three cache
239
+ * states can be asserted as RENDERED lines rather than as the helper that feeds
240
+ * them — the status line is the surface a user reads, and a note that is
241
+ * correct but composed into the wrong line helps nobody.
242
+ */
243
+ export function frame(width, height) {
244
+ const out = [];
245
+ const total = inScope().length;
246
+ const at = cursor();
247
+ // 1. tabs
248
+ const tabChunks = [];
249
+ for (const name of tabs()) {
250
+ const count = name === ALL
251
+ ? (state.catalog?.reports ?? []).reduce((n, r) => n + r.tasks.length, 0)
252
+ : (reportFor(name)?.tasks.length ?? 0);
253
+ // Marked at the TAB, not per row: the whole runner's rows are as old as
254
+ // each other, so a per-row mark would repeat one fact hundreds of times and
255
+ // the row renderer would have to know about the cache. A leading `~` reads
256
+ // as "about" at a glance and survives NO_COLOR.
257
+ const stale = name === ALL ? staleRunners().length > 0 : cacheFor(name)?.state === 'stale';
258
+ // A bar between groups: tasks, then dependencies, tools and git hooks.
259
+ const prev = tabs()[tabs().indexOf(name) - 1];
260
+ if (name !== ALL && prev !== undefined && prev !== ALL && groupOf(prev) !== groupOf(name)) {
261
+ tabChunks.push({ text: '│', paint: dim });
262
+ }
263
+ const label = name === ALL ? ALL : runnerLabel(name);
264
+ tabChunks.push({
265
+ text: ` ${stale ? '~' : ''}${label} ${count} `,
266
+ paint: name === state.runner ? invert : stale ? yellow : dim,
267
+ });
268
+ }
269
+ const flags = `${state.mode}${state.servicesOnly ? ' services' : ''}${state.catalog?.allowExec ? ' exec' : ''}`;
270
+ const used = tabChunks.reduce((n, c) => n + c.text.length, 0);
271
+ tabChunks.push({ text: ' '.repeat(Math.max(1, width - used - flags.length - 1)) });
272
+ tabChunks.push({ text: flags, paint: dim });
273
+ out.push(line(tabChunks, width));
274
+ // 2. query
275
+ out.push(line([{ text: '> ', paint: cyan }, { text: state.query }, { text: '█', paint: cyan }], width));
276
+ // 3. counts, clock, transient message, probe failures
277
+ out.push(line([
278
+ { text: `${state.rows.length}/${total}`, paint: dim },
279
+ {
280
+ text: state.catalog
281
+ ? ` checked ${new Date(state.catalog.generatedAt).toLocaleTimeString()}`
282
+ : ' collecting',
283
+ paint: dim,
284
+ },
285
+ ...(state.loading && refreshNote(state.cache, true) === null
286
+ ? [{ text: ' refreshing', paint: yellow }]
287
+ : []),
288
+ // The cache's three states. Fresh returns null and says nothing;
289
+ // stale-and-slow paints red so it does not read like the ordinary
290
+ // refresh note beside it.
291
+ ...(() => {
292
+ const note = refreshNote(state.cache, state.loading);
293
+ return note === null ? [] : [{ text: ` ${note.text}`, paint: note.slow ? red : yellow }];
294
+ })(),
295
+ ...(state.message ? [{ text: ` ${state.message}`, paint: yellow }] : []),
296
+ // A note beside the counts, not a modal: you may well have come here to
297
+ // look at what is already collected and run nothing.
298
+ ...(state.confirmingTrust
299
+ ? [{ text: ' trust this repository? y/n', paint: yellow }]
300
+ : withheldForTrust() > 0
301
+ ? [
302
+ {
303
+ text: ` ${withheldForTrust()} hidden — repo not trusted (^s to trust)`,
304
+ paint: yellow,
305
+ },
306
+ ]
307
+ : []),
308
+ ...(state.catalog?.reports ?? [])
309
+ .filter((r) => r.status === 'error')
310
+ .map((r) => ({ text: ` ${r.runner} failed`, paint: red })),
311
+ ], width));
312
+ // 4a. the settings screen, which REPLACES the list while it is open. It is
313
+ // a different view of the same repository rather than an overlay on this
314
+ // one, so nothing below it renders.
315
+ if (state.settings !== null) {
316
+ const room = Math.max(1, height - out.length - 2);
317
+ for (let i = 0; i < room; i++) {
318
+ const text = state.settings[i];
319
+ out.push(text === undefined
320
+ ? CLEAR_EOL
321
+ : line([{ text, paint: text.startsWith(' ') ? undefined : bold }], width));
322
+ }
323
+ out.push(line([{ text: '─'.repeat(width) }], width));
324
+ out.push(line([{ text: `reading only — edit with \`${BIN} config set\` esc back`, paint: dim }], width));
325
+ return HOME + out.join('\r\n') + CLEAR_BELOW;
326
+ }
327
+ // 4. the list, sized by what the chrome leaves. The entry line costs one
328
+ // more row than the key hints it replaces, so the list gives one up while
329
+ // arguments are being typed rather than the bottom line falling off screen.
330
+ const listHeight = Math.max(1, height - out.length - (state.entering ? 5 : 4));
331
+ clampScroll(at, listHeight);
332
+ for (let i = 0; i < listHeight; i++) {
333
+ const row = state.rows[state.scroll + i];
334
+ if (!row) {
335
+ out.push(CLEAR_EOL);
336
+ continue;
337
+ }
338
+ out.push(line([
339
+ { text: state.scroll + i === at ? '> ' : ' ', paint: cyan },
340
+ { text: row.task.persistent.value ? '* ' : ' ', paint: green },
341
+ ...chainChunks(row),
342
+ ], width));
343
+ }
344
+ // 5. what Enter would run — always on screen, so it is never a surprise
345
+ const current = state.rows[at];
346
+ out.push(line([{ text: '-'.repeat(width), paint: dim }], width));
347
+ if (current) {
348
+ const shape = chainOf(current.task.runner)
349
+ .map((c) => c.label)
350
+ .join(' > ');
351
+ const gap = width - current.task.display.length - shape.length - 1;
352
+ out.push(line(gap >= 3
353
+ ? [
354
+ { text: current.task.display, paint: bold },
355
+ { text: ' '.repeat(gap) },
356
+ { text: shape, paint: dim },
357
+ ]
358
+ : [{ text: current.task.display, paint: bold }], width));
359
+ out.push(line([{ text: current.task.doc ?? current.task.detail ?? '', paint: dim }], width));
360
+ }
361
+ else {
362
+ out.push(line([{ text: state.query ? 'no match' : 'nothing collected', paint: dim }], width));
363
+ out.push(line([], width));
364
+ }
365
+ // 6. keys — or, while arguments are being typed, the entry line in their
366
+ // place. It replaces the key hints rather than sitting above them because
367
+ // the keys that matter while typing are the two this line names, and a
368
+ // second row would push the list up mid-task.
369
+ if (state.entering) {
370
+ const { task, text } = state.entering;
371
+ const shape = paramShape(task.parameters);
372
+ out.push(line([
373
+ { text: '$ ', paint: dim },
374
+ { text: task.argv.join(' ') + ' ', paint: bold },
375
+ { text },
376
+ { text: '█', paint: cyan },
377
+ ], width));
378
+ out.push(line([{ text: ` takes ${shape} enter run esc back`, paint: dim }], width));
379
+ }
380
+ else {
381
+ out.push(line([
382
+ {
383
+ text: 'enter run ^y copy tab runner ^e exact ^t services ^s trust ^r refresh , settings esc quit',
384
+ paint: dim,
385
+ },
386
+ ], width));
387
+ }
388
+ return HOME + out.join('\r\n') + CLEAR_BELOW;
389
+ }
390
+ function clampScroll(at, listHeight) {
391
+ if (at < state.scroll)
392
+ state.scroll = at;
393
+ if (at >= state.scroll + listHeight)
394
+ state.scroll = at - listHeight + 1;
395
+ if (state.scroll < 0)
396
+ state.scroll = 0;
397
+ }
398
+ /**
399
+ * Rebuild the visible rows and re-anchor the selection onto a task that is
400
+ * still there.
401
+ *
402
+ * Split out of {@link draw} so it can be exercised without a terminal. It is
403
+ * the whole reason selection is held by task id: a refresh reorders rows and
404
+ * drops some of them, and an index would silently point at a different task —
405
+ * which is the same keystroke running the wrong command.
406
+ */
407
+ export function recompute() {
408
+ state.rows = visibleRows();
409
+ if (state.selectedId !== null && !state.rows.some((r) => r.task.id === state.selectedId)) {
410
+ state.selectedId = state.rows[0]?.task.id ?? null;
411
+ }
412
+ }
413
+ function draw() {
414
+ recompute();
415
+ process.stdout.write(frame(process.stdout.columns || 100, process.stdout.rows || 30));
416
+ }
417
+ /**
418
+ * The settings screen, as text — the same four sections the page shows, in the
419
+ * config schema's own key order, so the two surfaces describe a project the
420
+ * same way.
421
+ *
422
+ * READ ONLY, and it says so on screen. The page can edit because it has a
423
+ * server to POST to and a pointer to click with; giving the terminal the same
424
+ * would mean an input mode per field, which is a larger thing than showing
425
+ * someone what their configuration is. `way config set` is the editor
426
+ * this line points at.
427
+ */
428
+ async function settingsLines() {
429
+ const loaded = await loadConfig(state.root, state.env, state.home);
430
+ const where = (key) => {
431
+ const layer = loaded.sources.get(key) ?? 'default';
432
+ return layer === 'project' ? 'this project' : layer === 'user' ? 'your user config' : 'default';
433
+ };
434
+ const runners = (loaded.effective.runners ?? {});
435
+ const disabled = new Set(runners.disabled ?? []);
436
+ const known = [
437
+ ...new Set([...(state.catalog?.reports ?? []).map((r) => r.runner), ...disabled]),
438
+ ].sort();
439
+ const out = [];
440
+ out.push(`RUNNERS (${where('runners.disabled')})`);
441
+ if (known.length === 0)
442
+ out.push(' no runners detected');
443
+ for (const name of known) {
444
+ out.push(` ${disabled.has(name) ? '[ ]' : '[x]'} ${name}${disabled.has(name) ? ' not collected' : ''}`);
445
+ }
446
+ const order = runners.order ?? [];
447
+ out.push(` order: ${order.length === 0 ? 'alphabetical' : order.join(' ')} (${where('runners.order')})`);
448
+ out.push('');
449
+ out.push(`EXECUTION (trust store)`);
450
+ out.push(state.gate?.trusted === true
451
+ ? ' trusted — runners may spawn probes'
452
+ : withheldForTrust() > 0
453
+ ? ' not trusted — runners that must be run to be read were skipped (^s to trust)'
454
+ : ' execution is off for this project');
455
+ out.push(` allowExec: ${String(loaded.effective.allowExec === true)} (${where('allowExec')})`);
456
+ out.push(' a project file can only turn execution OFF; turning it on is the trust grant');
457
+ out.push('');
458
+ out.push(`DISCOVERY (${where('discovery')})`);
459
+ out.push(` ${String(loaded.effective.discovery)}`);
460
+ out.push('');
461
+ out.push(`EXCLUDED PATHS (${where('excludePaths')})`);
462
+ const excluded = loaded.effective.excludePaths ?? [];
463
+ if (excluded.length === 0)
464
+ out.push(' none');
465
+ for (const path of excluded)
466
+ out.push(` ${path}`);
467
+ out.push('');
468
+ out.push(`file: ${loaded.locations.project}`);
469
+ for (const warning of loaded.warnings)
470
+ out.push(`warning: ${warning}`);
471
+ return out;
472
+ }
473
+ // ---------------------------------------------------------------- actions
474
+ /**
475
+ * Put a task's command on the clipboard.
476
+ *
477
+ * What is copied is not always `display`. A task bound to its own directory
478
+ * gets the `cd` that makes it run, quoted where the directory needs it -
479
+ * without it the paste fails. Enter is unaffected: `runAndExit` spawns with
480
+ * the directory already. The web page's copy buttons apply the same rule
481
+ * (`copyText` in web/view.ts).
482
+ */
483
+ function copy(task) {
484
+ const dir = /^[\w.\-/@+]+$/.test(task.cwd) ? task.cwd : `'${task.cwd.replace(/'/g, "'\\''")}'`;
485
+ const text = task.cwd === '.' ? task.display : `cd ${dir} && ${task.display}`;
486
+ const bin = process.platform === 'darwin' ? 'pbcopy' : 'xclip';
487
+ const args = process.platform === 'darwin' ? [] : ['-selection', 'clipboard'];
488
+ const res = spawnRunner(bin).run(args, { input: text, cwd: state.root });
489
+ return res.exitCode === 0;
490
+ }
491
+ let restored = false;
492
+ /** Idempotent: both `runAndExit` and the exit hook call it. */
493
+ function restoreTerminal() {
494
+ if (restored)
495
+ return;
496
+ restored = true;
497
+ if (process.stdin.isTTY)
498
+ process.stdin.setRawMode(false);
499
+ process.stdout.write(SHOW + ALT_OFF);
500
+ }
501
+ /**
502
+ * Hand the terminal to the selected task and take this process out of the way.
503
+ * It streams through the command seam, so the task owns the terminal while it
504
+ * runs.
505
+ *
506
+ * `argv` is spawned WITHOUT a shell. `display` would be wrong to run — for a
507
+ * parameterised recipe it carries `<placeholders>`, which a shell reads as
508
+ * redirections.
509
+ */
510
+ function runAndExit(task, args = []) {
511
+ // Abandon any in-flight probe before the terminal changes hands.
512
+ state.inFlight?.abort();
513
+ restoreTerminal();
514
+ // Echo what actually RAN, not `display` — for a parameterised task those
515
+ // differ, and printing the placeholder form above a command that did not
516
+ // include it would be a lie about what just happened.
517
+ let argv;
518
+ try {
519
+ argv = runArgv(state.project, task, args);
520
+ }
521
+ catch (err) {
522
+ process.stderr.write(`${APP}: ${err instanceof Error ? err.message : String(err)}\n`);
523
+ process.exit(1);
524
+ }
525
+ process.stdout.write(`${dim('$')} ${bold(argv.join(' '))}\n`);
526
+ // The shape is worth repeating only when it went unanswered: a task run
527
+ // WITH its arguments has just shown them on the line above, and naming the
528
+ // placeholders again would read as a complaint about a command that was
529
+ // complete.
530
+ if (task.parameters.length > 0 && args.length === 0) {
531
+ process.stdout.write(`${dim(` takes ${paramShape(task.parameters)}`)}\n`);
532
+ }
533
+ const [binary, ...rest] = argv;
534
+ const res = streamRunner(binary).run(rest, {
535
+ cwd: task.cwd === '.' ? state.root : `${state.root}/${task.cwd}`,
536
+ quiet: true,
537
+ });
538
+ // A spawn that never started at all — no such binary, no such directory. The
539
+ // row may simply have been wrong: it came out of the store, and the task it
540
+ // named can have been renamed or deleted since. Naming the staleness turns an
541
+ // unexplained failure into one the user can act on.
542
+ if (res.reason === 'spawn') {
543
+ process.stderr.write(`${APP}: ${binary}: ${res.error ?? 'could not start'}\n`);
544
+ const from = cacheFor(task.runner);
545
+ if (from !== undefined && from.state === 'stale') {
546
+ process.stderr.write(`${APP}: that row came from a cached listing of ${task.runner} taken ${humanAge(from.ageMs)}` +
547
+ ` — the task may no longer exist; start ${BIN} again to re-probe\n`);
548
+ }
549
+ }
550
+ process.exit(res.exitCode);
551
+ }
552
+ /**
553
+ * Re-probe. Guarded three ways, all of which the synchronous version got for
554
+ * free: a single in-flight probe, a generation token so a superseded result is
555
+ * discarded, and an abort signal so an abandoned one stops working.
556
+ */
557
+ async function refresh() {
558
+ if (state.loading)
559
+ return;
560
+ const generation = ++state.generation;
561
+ const controller = new AbortController();
562
+ state.inFlight = controller;
563
+ state.loading = true;
564
+ state.message = '';
565
+ draw();
566
+ try {
567
+ // ALWAYS a real probe, never a cache read — ^r means "ask again", and a
568
+ // refresh that could answer from the store would make the one key that
569
+ // guarantees accuracy indistinguishable from doing nothing. It writes the
570
+ // store on the way out, so the next start still paints instantly.
571
+ const collected = await collectAndCache(state.project, state.root, { ...state.options, signal: controller.signal }, state.store);
572
+ if (generation !== state.generation)
573
+ return; // a newer refresh won
574
+ state.catalog = orderedCatalog(collected, state.runnerOrder);
575
+ // Everything on screen was measured just now, so nothing is stale.
576
+ state.cache = freshStates(collected);
577
+ }
578
+ catch (err) {
579
+ if (generation === state.generation) {
580
+ state.message = `refresh failed: ${err instanceof Error ? err.message : String(err)}`;
581
+ }
582
+ }
583
+ finally {
584
+ if (generation === state.generation) {
585
+ state.loading = false;
586
+ state.inFlight = null;
587
+ }
588
+ }
589
+ }
590
+ /**
591
+ * Grant trust, then re-probe in place so the runners appear where the note was.
592
+ *
593
+ * The hint is dropped at the same time: it tells the user to trust the
594
+ * repository, which they just did, and a catalog carrying it after the fact
595
+ * would be instructing them to repeat themselves.
596
+ */
597
+ async function grantTrust() {
598
+ try {
599
+ await appTrustStore({
600
+ ...(state.env !== undefined ? { env: state.env } : {}),
601
+ ...(state.home !== undefined ? { home: state.home } : {}),
602
+ }).trust(state.root);
603
+ }
604
+ catch (err) {
605
+ // Never silent: the keystroke did something, and if it failed the user has
606
+ // to know the runners are still hidden for a reason they can act on.
607
+ state.message = `trust failed: ${err instanceof Error ? err.message : String(err)}`;
608
+ return;
609
+ }
610
+ const { execWithheldHint: _dropped, ...rest } = state.options;
611
+ state.options = { ...rest, allowExec: true };
612
+ if (state.gate)
613
+ state.gate = { ...state.gate, allowExec: true, trusted: true, reason: 'allowed' };
614
+ // Tool modules are code; they load at the next start, not mid-session.
615
+ state.message = state.projectToolsPending
616
+ ? `trusted — re-probing; the project's tools load the next time ${BIN} starts with execution allowed`
617
+ : 'trusted — re-probing';
618
+ // A probe started before the grant was collected under the old gate, and
619
+ // `refresh` drops a request while one is running — so the grant would be
620
+ // announced and never acted on. Abandon that probe first; `refresh` bumps
621
+ // the generation synchronously, so the abandoned one cannot come back and
622
+ // overwrite the new result or its bookkeeping.
623
+ state.inFlight?.abort();
624
+ state.inFlight = null;
625
+ state.loading = false;
626
+ await refresh();
627
+ }
628
+ function cycleRunner(step) {
629
+ const names = tabs();
630
+ const at = names.indexOf(state.runner);
631
+ state.runner = names[(at + step + names.length) % names.length];
632
+ state.selectedId = null;
633
+ state.scroll = 0;
634
+ }
635
+ // ---------------------------------------------------------------- input
636
+ /**
637
+ * One keystroke.
638
+ *
639
+ * Exported for the same reason `state` is: `runTui` owns a real terminal and
640
+ * never returns, so the keys that reach disk — settings, trust — are only
641
+ * reachable from a test through this.
642
+ */
643
+ export function handle(key) {
644
+ const listHeight = Math.max(1, (process.stdout.rows || 30) - 7);
645
+ const move = (n) => {
646
+ select(cursor() + n);
647
+ state.message = '';
648
+ };
649
+ // The armed prompt owns the keyboard for exactly one keystroke. `y` grants;
650
+ // anything else cancels and is swallowed, so the key that cancelled cannot
651
+ // also do its usual job in the same breath.
652
+ if (state.confirmingTrust) {
653
+ state.confirmingTrust = false;
654
+ state.message = '';
655
+ if (key === 'y' || key === 'Y')
656
+ void grantTrust().finally(draw);
657
+ return;
658
+ }
659
+ // The settings screen owns the keyboard while it is open, for the same
660
+ // reason the entry line does: the keys below act on a list that is not on
661
+ // screen.
662
+ if (state.settings !== null) {
663
+ if (key === '\x1b' || key === '\x03' || key === ',' || key === 'q')
664
+ state.settings = null;
665
+ return;
666
+ }
667
+ // Typing arguments owns the keyboard: every key is text or one of the two
668
+ // that end it. Placed before the switch so ^y, tab and the arrows cannot
669
+ // act on a list the user is no longer looking at.
670
+ if (state.entering) {
671
+ const entering = state.entering;
672
+ if (key === '\x1b' || key === '\x03') {
673
+ state.entering = null;
674
+ return;
675
+ }
676
+ if (key === '\r' || key === '\n') {
677
+ state.entering = null;
678
+ runAndExit(entering.task, splitArgs(entering.text));
679
+ return;
680
+ }
681
+ if (key === '\x7f' || key === '\x08') {
682
+ entering.text = entering.text.slice(0, -1);
683
+ return;
684
+ }
685
+ if (key === '\x15') {
686
+ entering.text = '';
687
+ return;
688
+ } // ctrl-u
689
+ if (key.length >= 1 && key >= ' ' && !key.startsWith('\x1b'))
690
+ entering.text += key;
691
+ return;
692
+ }
693
+ switch (key) {
694
+ case '\x03': // ctrl-c
695
+ case '\x1b': // esc
696
+ restoreTerminal();
697
+ process.exit(0);
698
+ break;
699
+ case '\r':
700
+ case '\n': {
701
+ const row = state.rows[cursor()];
702
+ if (!row)
703
+ break;
704
+ // A parameterised recipe collects its arguments first. Running it here
705
+ // would spawn the command without them and hand over the terminal, so
706
+ // the mistake could not even be reported.
707
+ if (row.task.parameters.length > 0)
708
+ state.entering = { task: row.task, text: '' };
709
+ else
710
+ runAndExit(row.task);
711
+ break;
712
+ }
713
+ case '\x19': {
714
+ // ctrl-y
715
+ const row = state.rows[cursor()];
716
+ state.message = row ? (copy(row.task) ? 'copied' : 'clipboard unavailable') : '';
717
+ break;
718
+ }
719
+ case '\x05': // ctrl-e
720
+ state.mode = state.mode === 'fuzzy' ? 'exact' : 'fuzzy';
721
+ state.selectedId = null;
722
+ break;
723
+ case '\x14': // ctrl-t
724
+ state.servicesOnly = !state.servicesOnly;
725
+ state.selectedId = null;
726
+ break;
727
+ case ',':
728
+ // Loaded on open, not on every frame — it is a disk read. A disk read
729
+ // fails: an unparseable config throws, and without the catch that is an
730
+ // unhandled rejection instead of a line the user can act on.
731
+ void settingsLines()
732
+ .then((lines) => {
733
+ state.settings = lines;
734
+ })
735
+ .catch((err) => {
736
+ state.message = `settings unavailable: ${err instanceof Error ? err.message : String(err)}`;
737
+ })
738
+ .finally(draw);
739
+ break;
740
+ case '\x12': // ctrl-r
741
+ void refresh().finally(draw);
742
+ break;
743
+ case '\x13': // ctrl-s
744
+ // Arms the question; `y` answers it. Nothing is written here.
745
+ if (withheldForTrust() > 0)
746
+ state.confirmingTrust = true;
747
+ else
748
+ state.message = 'nothing is withheld';
749
+ break;
750
+ case '\t':
751
+ cycleRunner(1);
752
+ break;
753
+ case '\x1b[Z': // shift-tab
754
+ cycleRunner(-1);
755
+ break;
756
+ case '\x1b[A':
757
+ case '\x10':
758
+ move(-1);
759
+ break;
760
+ case '\x1b[B':
761
+ case '\x0e':
762
+ move(1);
763
+ break;
764
+ case '\x1b[5~':
765
+ move(-listHeight);
766
+ break;
767
+ case '\x1b[6~':
768
+ move(listHeight);
769
+ break;
770
+ case '\x1b[H':
771
+ case '\x01':
772
+ select(0);
773
+ break;
774
+ case '\x1b[F':
775
+ select(state.rows.length - 1);
776
+ break;
777
+ case '\x7f':
778
+ case '\x08':
779
+ state.query = state.query.slice(0, -1);
780
+ state.selectedId = null;
781
+ break;
782
+ case '\x15': // ctrl-u
783
+ state.query = '';
784
+ state.selectedId = null;
785
+ break;
786
+ default:
787
+ if (key.length >= 1 && key >= ' ' && !key.startsWith('\x1b')) {
788
+ state.query += key;
789
+ state.selectedId = null;
790
+ }
791
+ }
792
+ }
793
+ export async function runTui({ project, projectToolsPending, root, options, runnerOrder, gate, env, home, }) {
794
+ if (!process.stdin.isTTY) {
795
+ process.stderr.write(`${APP}: the terminal UI needs a TTY; use --serve for the page, or --json for data.\n`);
796
+ return 2;
797
+ }
798
+ state.project = project;
799
+ state.projectToolsPending = projectToolsPending ?? false;
800
+ state.root = root;
801
+ state.options = options;
802
+ state.runnerOrder = runnerOrder;
803
+ state.gate = gate ?? null;
804
+ state.env = env;
805
+ state.home = home;
806
+ state.store = cacheDir(env, home);
807
+ process.stdout.write(ALT_ON + HIDE);
808
+ process.stdin.setRawMode(true);
809
+ process.stdin.resume();
810
+ process.stdin.setEncoding('utf8');
811
+ process.on('exit', restoreTerminal);
812
+ process.on('SIGINT', () => {
813
+ restoreTerminal();
814
+ process.exit(0);
815
+ });
816
+ process.stdout.on('resize', draw);
817
+ process.stdin.on('data', (chunk) => {
818
+ // A paste or a fast key repeat arrives as one chunk; escape sequences must
819
+ // stay whole, so split on ESC rather than per character.
820
+ for (const key of chunk.split(/(?=\x1b)/)) {
821
+ if (key.startsWith('\x1b') || key.length === 1)
822
+ handle(key);
823
+ else
824
+ for (const ch of key)
825
+ handle(ch);
826
+ }
827
+ draw();
828
+ });
829
+ // Stale-then-refresh. The first paint costs a few file hashes rather than a
830
+ // full probe, so a repository whose slowest runner takes seconds shows its
831
+ // tasks at once — marked as cached — instead of an empty frame. The probe
832
+ // then lands underneath and the rows update in place.
833
+ const stored = await readCachedCatalog(project, root, options, state.store);
834
+ // Only painted when something came OUT of the store: with execution off, a
835
+ // cold store still yields withheld reports, an empty list posing as an answer.
836
+ if (stored.catalog !== null && fromStore(stored)) {
837
+ state.catalog = orderedCatalog(stored.catalog, runnerOrder);
838
+ state.cache = stored.runners;
839
+ }
840
+ draw();
841
+ await refresh();
842
+ draw();
843
+ // The stdin handler drives everything from here; this promise never settles,
844
+ // because every exit path calls `process.exit`.
845
+ return new Promise(() => { });
846
+ }