codebase-onboarder 0.4.1 → 0.6.0

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,391 @@
1
+ // The interactive session.
2
+ //
3
+ // This is a prompt, not a full-screen TUI, and that is a deliberate choice.
4
+ // A curses app takes the scrollback, the selection, and copy-paste away, and it
5
+ // behaves badly over SSH and inside a tmux pane — which is exactly where people
6
+ // read a codebase. A readline session keeps all of that, prints scrollable
7
+ // output you can select, and degrades to something scriptable. The research
8
+ // agrees: a CLI is a conversation, and a TUI earns its cost only when you are
9
+ // manipulating state with the keyboard rather than reading.
10
+ //
11
+ // Two rules from the design research are load-bearing here:
12
+ // * TTY detection. A session that needs a terminal must never be started by a
13
+ // pipe, a cron job, or CI — so `runExplore` refuses and explains instead of
14
+ // hanging forever waiting for input nobody is there to type.
15
+ // * Flags → env → config precedence. `NO_COLOR` and `COLUMNS` are honored
16
+ // before anything is drawn, so a redirect gets plain, fitted text.
17
+
18
+ import readline from 'node:readline';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ import { openRepo, openRepoOrClone, isGitUrl, remoteUrlFor, closeRemote } from './session.js';
23
+ import { fetchRepoFacts } from './github.js';
24
+ import { CLEAR, EXIT, commandNames, completer, helpText, lookup, shellEscape, tokenize } from './commands.js';
25
+ import { overview, github as githubView } from './views.js';
26
+ import { bold, cyan, dim, ok, bad, paint } from '../ui.js';
27
+ import { configPath, readSettings, serverUrls } from '../../server/config.js';
28
+ import { readPidFile, pidIsAlive } from '../../server/pidfile.js';
29
+ import { expandHome } from '../../server/paths.js';
30
+
31
+ const VERSION = JSON.parse(
32
+ fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')
33
+ ).version;
34
+
35
+ // The one-time note. `onboarder` used to start a web server; now it opens this.
36
+ // Someone who upgrades and has muscle memory for the old thing deserves to be
37
+ // told once where the server went, and then never again.
38
+ const HINT_MARKER = 'explorer-hint-v1';
39
+
40
+ export async function runExplore({ target = '.', flags = {}, out = console.log, err = console.error, version = VERSION } = {}) {
41
+ // The guard. `stdin` matters as much as `stdout`: a session with no input
42
+ // source is a hang, and a hang in CI is worse than any error.
43
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
44
+ out('');
45
+ out(' The terminal explorer needs an interactive terminal.');
46
+ out(dim(' In a script or a pipe, use these instead:'));
47
+ out(dim(' onboarder start start the web UI'));
48
+ out(dim(' onboarder start background start it detached'));
49
+ out(dim(' onboarder status | stop manage a running one'));
50
+ out(dim(' onboarder --help everything else'));
51
+ out('');
52
+ return 0;
53
+ }
54
+
55
+ let repo;
56
+ try {
57
+ // The launch argument accepts a URL for the same reason `cd` does: someone
58
+ // who has never seen this repo should be able to name it and read it. A
59
+ // silent ten-second clone looks like a hang, so the URL case says what it
60
+ // is doing before it starts.
61
+ if (isGitUrl(target)) out(dim(` cloning ${target}…`));
62
+ repo = await openRepoOrClone(target, { onProgress: progressReporter(out) });
63
+ } catch (e) {
64
+ err(' ' + bad((e.message || String(e))));
65
+ err(dim(' Point it at a folder: onboarder explore /path/to/repo'));
66
+ err(dim(' …or a git URL: onboarder explore https://github.com/org/repo'));
67
+ return 1;
68
+ }
69
+
70
+ out('');
71
+ out(overview(repo));
72
+ out('');
73
+ if (await shouldShowHint(flags)) {
74
+ out(dim(' Note: `onboarder` used to start the web server. That is now `onboarder start`'));
75
+ out(dim(' (or the `web` command here) — this session reads the repo directly,'));
76
+ out(dim(' so it needs no server and works offline.'));
77
+ out('');
78
+ }
79
+ return session({ repo, flags, out, err, version });
80
+ }
81
+
82
+ // Scanning a large monorepo is the one genuinely slow thing this does, so it
83
+ // says so. A silent eight seconds is indistinguishable from a hang.
84
+ function progressReporter(out) {
85
+ let last = 0;
86
+ return ({ phase, done }) => {
87
+ if (!process.stdout.isTTY) return;
88
+ const now = Date.now();
89
+ if (phase === 'parse' && done && now - last > 400) {
90
+ last = now;
91
+ out(dim(`\r scanning… ${done} files`));
92
+ }
93
+ };
94
+ }
95
+
96
+ async function shouldShowHint(flags) {
97
+ if (process.env.ONBOARDER_NO_HINT) return false;
98
+ try {
99
+ const marker = path.join(path.dirname(flags.config || configPath()), HINT_MARKER);
100
+ const seen = await fs.promises.stat(marker).then(() => true).catch(() => false);
101
+ if (seen) return false;
102
+ await fs.promises.mkdir(path.dirname(marker), { recursive: true });
103
+ await fs.promises.writeFile(marker, 'shown\n');
104
+ return true;
105
+ } catch {
106
+ // A read-only config home is not a reason to nag on every launch.
107
+ return false;
108
+ }
109
+ }
110
+
111
+ // The read loop. Commands are queued rather than awaited inline, because
112
+ // readline emits the next line while a slow command is still running and two
113
+ // interleaved `cd`s would leave the session pointing at a repo nobody asked
114
+ // for.
115
+ function session({ repo, flags, out, err, version }) {
116
+ const ctx = {
117
+ repo,
118
+ version,
119
+ flags,
120
+ help: (topic) => helpText(ctx, topic),
121
+ rescan: () => reload(ctx, ctx.repo.root),
122
+ loadRepo: (where) => reload(ctx, where),
123
+ github: () => askGithub(ctx),
124
+ web: () => startWeb(ctx),
125
+ };
126
+
127
+ const rl = readline.createInterface({
128
+ input: process.stdin,
129
+ output: process.stdout,
130
+ prompt: promptFor(repo),
131
+ terminal: true,
132
+ historySize: 200,
133
+ // The completer closes over the *current* repo rather than the one captured
134
+ // here, so after a `cd` it completes paths in the new repository. Reading
135
+ // `ctx.repo` at completion time is the whole trick.
136
+ completer: (line) => completer(ctx.repo)(line),
137
+ });
138
+
139
+ let queue = Promise.resolve();
140
+ let closed = false;
141
+ let interrupts = 0;
142
+ let onResize = null;
143
+
144
+ // One poisoned promise must not end the session. `handleLine` catches its own
145
+ // errors, but anything thrown outside it — a prompt write to a closed stream,
146
+ // an error in a command's argument handling — would otherwise reject this
147
+ // chain and silently swallow every command typed afterwards. The session would
148
+ // look alive and do nothing, which is the worst failure mode a REPL has.
149
+ rl.on('line', (line) => {
150
+ queue = queue
151
+ .then(() => handleLine(ctx, line, rl, out, err))
152
+ .catch((e) => {
153
+ err(' ' + bad((e?.message || String(e))));
154
+ if (!closed) {
155
+ try {
156
+ rl.setPrompt(promptFor(ctx.repo));
157
+ rl.prompt();
158
+ } catch {
159
+ // The stream is gone; the close handler finishes the session.
160
+ }
161
+ }
162
+ });
163
+ });
164
+
165
+ // Ctrl-D on an empty line is the universal "I'm done". On a line with text,
166
+ // readline handles it itself; this only sees the empty-line case.
167
+ //
168
+ // Closing does NOT end the session. A piped or fast-typed sequence of commands
169
+ // can already be queued when the last line arrives, and resolving here would
170
+ // throw those away mid-flight — which is exactly what happens to `tour` when
171
+ // its input is followed immediately by `exit`. The exit waits on the queue.
172
+ rl.on('close', () => {
173
+ closed = true;
174
+ // The listener is removed on every exit path, including the interval one
175
+ // below, so a session that ends by any route leaves stdout as it found it.
176
+ if (onResize) process.stdout.off('resize', onResize);
177
+ });
178
+
179
+ // Ctrl-C twice leaves. Once clears the line, which is what readline already
180
+ // does, and matches every other REPL people use.
181
+ rl.on('SIGINT', () => {
182
+ if (closed) return;
183
+ interrupts++;
184
+ if (interrupts >= 2) {
185
+ rl.close();
186
+ return;
187
+ }
188
+ out(dim('\n Ctrl-C again to leave.'));
189
+ rl.setPrompt(promptFor(ctx.repo));
190
+ rl.prompt();
191
+ });
192
+
193
+ // A resize redraws rather than leaving the prompt stranded mid-wrap.
194
+ onResize = () => {
195
+ if (!closed) rl.write(null, { ctrl: true, name: 'l' });
196
+ };
197
+ process.stdout.on('resize', onResize);
198
+
199
+ queue = queue.then(() => rl.prompt());
200
+
201
+ return new Promise((resolve) => {
202
+ const poll = setInterval(() => {
203
+ if (!closed) return;
204
+ clearInterval(poll);
205
+ // Drain whatever is still running, then say goodbye. A command that throws
206
+ // has already been caught in `handleLine`, so this cannot reject.
207
+ queue.then(() => {
208
+ out('');
209
+ out(dim(' bye.'));
210
+ // A clone this session made is a temp directory, and the session is the
211
+ // only thing that knows about it. Removing it last — after the last
212
+ // command has finished reading files out of it — is the only ordering
213
+ // that cannot pull the ground out from under a command still running.
214
+ closeRemote(ctx.repo).catch(() => {});
215
+ resolve(0);
216
+ });
217
+ }, 20);
218
+ });
219
+ }
220
+
221
+ function promptFor(repo) {
222
+ return paint(' ', 'cyan') + bold(repo.name.slice(0, 24)) + paint(' > ', 'gray');
223
+ }
224
+
225
+ async function handleLine(ctx, line, rl, out, err) {
226
+ const words = tokenize(line);
227
+ if (!words.length) {
228
+ rl.prompt();
229
+ return;
230
+ }
231
+ const [name, ...args] = words;
232
+
233
+ // `!cmd` runs a shell command from inside the session and prints its output.
234
+ // It is the only way out to a shell, which is the point: the set of things
235
+ // that can happen here stays small enough to remember.
236
+ if (name.startsWith('!') && name.length > 1) {
237
+ const result = await shellEscape(line.replace(/^!\s*/, ''), ctx.repo.root);
238
+ if (result) out(result);
239
+ rl.setPrompt(promptFor(ctx.repo));
240
+ rl.prompt();
241
+ return;
242
+ }
243
+
244
+ const cmd = lookup(name);
245
+
246
+ if (!cmd) {
247
+ // The nearest command by edit distance is almost always what was meant, and
248
+ // a one-line "did you mean" beats a paragraph about `help`.
249
+ const near = nearest(name);
250
+ err(' ' + bad('Unknown command: ' + name) + (near ? dim(' did you mean `' + near + '`?') : dim(' try `help`')));
251
+ rl.prompt();
252
+ return;
253
+ }
254
+
255
+ try {
256
+ const result = await cmd.run(ctx, args);
257
+ if (result === EXIT) {
258
+ rl.close();
259
+ return;
260
+ }
261
+ if (result === CLEAR) {
262
+ out('\x1b[2J\x1b[3J\x1b[H');
263
+ } else if (result) {
264
+ out(result);
265
+ }
266
+ } catch (e) {
267
+ err(' ' + bad((e.message || String(e))));
268
+ }
269
+ // The prompt carries the repo name, and `cd` can change which repo that is.
270
+ // Re-reading it after every command is cheaper than tracking which commands
271
+ // swap the repo, and it cannot go stale.
272
+ rl.setPrompt(promptFor(ctx.repo));
273
+ rl.prompt();
274
+ }
275
+
276
+ // Swap the loaded repo. Used by `cd` and `rescan`; the scan is the slow part,
277
+ // so the new name reaches the prompt only after it succeeds.
278
+ async function reload(ctx, where) {
279
+ const target = String(where || '').trim();
280
+ if (!target) {
281
+ return ' cd needs a folder or a URL — `cd ../other-repo`, `cd https://github.com/org/repo`.';
282
+ }
283
+
284
+ // `rescan` re-reads the folder the session is already in. Re-cloning the URL
285
+ // to get the same bytes back would be slow and would change the temp
286
+ // directory out from under the session, so a target that resolves to the
287
+ // current root takes the local path even when the repo remembers a URL.
288
+ const reloadingCurrent = !isGitUrl(target) && path.resolve(expandHome(target)) === path.resolve(ctx.repo.root);
289
+ const previous = ctx.repo;
290
+ const next = reloadingCurrent
291
+ ? await openRepo(previous.root)
292
+ : await openRepoOrClone(target, { onProgress: () => {} });
293
+
294
+ // A reload of the current folder produces a repo that has never heard of the
295
+ // URL it was cloned from: `openRepo` reads a directory, and a directory does
296
+ // not know where it came from. Carrying the three fields across is what keeps
297
+ // `rescan` from silently demoting a clone to a nameless temp folder — the
298
+ // prompt, `about` and `github` all read them.
299
+ if (reloadingCurrent) {
300
+ next.gitUrl = previous.gitUrl;
301
+ next.cloneDir = previous.cloneDir;
302
+ next.tempId = previous.tempId;
303
+ if (previous.name !== next.name && !previous.cloneDir) next.name = previous.name;
304
+ }
305
+
306
+ // The old clone is only dropped once the new one has loaded. Doing it the
307
+ // other way round means a typo in a URL leaves you with nothing loaded *and*
308
+ // the repo you were reading deleted from under you.
309
+ if (!reloadingCurrent) await closeRemote(previous);
310
+ ctx.repo = next;
311
+ return '\n' + overview(next);
312
+ }
313
+
314
+ // Ask GitHub about the loaded repo and print the answer. Network failures are
315
+ // the expected case, not the exception — this is a command someone types on a
316
+ // plane — so every one of them comes back as a line of text.
317
+ async function askGithub(ctx) {
318
+ const url = await remoteUrlFor(ctx.repo);
319
+ if (!url) {
320
+ return githubView(ctx.repo, { ok: false, reason: 'This folder has no GitHub remote — there is nothing to ask about.' });
321
+ }
322
+ return githubView(ctx.repo, await fetchRepoFacts(url));
323
+ }
324
+
325
+ // The bridge between the two surfaces. If the server is already up this just
326
+ // prints where it is; if not, it starts it detached, so the person keeps their
327
+ // session. The URL is the same one `onboarder start` would print, because it
328
+ // comes from the same `serverUrls` the CLI and the banner use.
329
+ async function startWeb(ctx) {
330
+ const file = ctx.flags.config || configPath();
331
+ const settings = await readSettings(file).catch(() => null);
332
+ const urls = serverUrls(settings || undefined);
333
+ const recorded = readPidFile(file);
334
+
335
+ if (recorded && pidIsAlive(recorded)) {
336
+ return [' ' + ok('Already running.') + dim(` PID ${recorded}`), ' ' + cyan(urls.local)].join('\n');
337
+ }
338
+
339
+ const { runStartBackground } = await import('../commands.js');
340
+ const code = await runStartBackground({
341
+ // `nonInteractive` is not optional here. With no config on disk,
342
+ // `runStartBackground` hands off to `runSetup`, which opens its own readline
343
+ // on the same stdin this session is already reading — the wizard and the
344
+ // explorer would then compete for keystrokes, and the explorer could process
345
+ // a wizard answer as a command. Inside a session the server either starts
346
+ // from the config that exists or reports that there is none; the person can
347
+ // run `onboarder setup` deliberately if they want the wizard.
348
+ flags: { ...ctx.flags, json: true, nonInteractive: true },
349
+ out: () => {},
350
+ err: () => {},
351
+ });
352
+ if (code !== 0) return ' ' + bad('Could not start the web UI.') + dim(' Try `onboarder doctor`.');
353
+ return [
354
+ ' ' + ok('Web UI started in the background.'),
355
+ ' ' + cyan(urls.local),
356
+ dim(' onboarder logs -f to watch it · onboarder stop to shut it down'),
357
+ ].join('\n');
358
+ }
359
+
360
+ // Cheap "did you mean": plain Levenshtein over the command names, with a
361
+ // distance cap of 2 so a wildly misspelled word gets "try `help`" instead of a
362
+ // confident wrong suggestion. A wrong suggestion is worse than none.
363
+ function nearest(word) {
364
+ const w = String(word).toLowerCase();
365
+ let best = null;
366
+ let bestScore = Infinity;
367
+ for (const name of commandNames()) {
368
+ const d = distance(w, name);
369
+ if (d < bestScore) {
370
+ bestScore = d;
371
+ best = name;
372
+ }
373
+ }
374
+ return bestScore <= 2 ? best : null;
375
+ }
376
+
377
+ function distance(a, b) {
378
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
379
+ for (let i = 1; i <= a.length; i++) {
380
+ const cur = [i];
381
+ for (let j = 1; j <= b.length; j++) {
382
+ cur[j] = Math.min(
383
+ prev[j] + 1,
384
+ cur[j - 1] + 1,
385
+ prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
386
+ );
387
+ }
388
+ prev = cur;
389
+ }
390
+ return prev[b.length];
391
+ }