codebase-onboarder 0.5.0 → 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.
package/README.md CHANGED
@@ -60,9 +60,12 @@ It lands on a `map` of the repo, then waits:
60
60
 
61
61
  ```
62
62
  codebase > tour
63
+ codebase > hotspots
63
64
  codebase > find resolveImport
64
65
  codebase > deps logger.js
65
- codebase > show logger.js
66
+ codebase > blast pathUtil.js # what breaks if this breaks
67
+ codebase > github # what GitHub says about this repo
68
+ codebase > !git log --oneline -3 # shell, without leaving
66
69
  codebase > exit
67
70
  ```
68
71
 
@@ -70,12 +73,30 @@ It lands on a `map` of the repo, then waits:
70
73
  |---|---|
71
74
  | **map · tour · explain** | What this is, the reading order for a new teammate, and a file or folder explained in prose |
72
75
  | **tree · find · show · deps** | Browse it, search it, read it, and trace what it connects to |
76
+ | **graph · blast · symbols** | The dependency tree as arrows, the transitive blast radius, and a file's outline |
73
77
  | **health · hubs · layers · patterns** | The analysis, in the same words the site uses |
74
- | **stats · security · stack · entry · externals** | Numbers, findings, dependencies, and drift |
78
+ | **coupling · clusters · risks** | Folder traffic as a heat grid, module groups, and everything wrong in one list |
79
+ | **log · hotspots · blame** | Git history, the files that are complex *and* often changed, and who wrote a line |
80
+ | **diagram · docs** | Real Mermaid source, and prose you can print or write to `ONBOARDER.md` |
75
81
  | **cd · rescan · web** | Switch repo, reload from disk, or start the web UI without leaving |
82
+ | **github** | Stars, forks, watchers, license and topics from GitHub, for the repo you have loaded |
83
+ | **Tab · `!cmd`** | Completes commands then file paths; runs a shell command inline |
84
+
85
+ **It also takes a GitHub URL, the way the site does.** Point it at one and it clones, scans and opens that repo:
86
+
87
+ ```
88
+ onboarder explore https://github.com/expressjs/express
89
+ codebase > cd https://github.com/sindresorhus/is.git
90
+ ```
91
+
92
+ The clone is blobless and single-branch — the full history, none of the file contents — because history is half of what this tool has to say (churn × complexity) and the blobs are not. It lands in the OS temp dir and is removed when you `cd` away or leave, so nothing is left behind and nothing you already had open gets deleted. A folder you `cd` to is never touched, whatever it happens to be called.
93
+
94
+ `github` asks GitHub about whatever is loaded: the URL if this session cloned it, otherwise `git remote get-url origin`, so it works in a checkout you were already standing in. It sends `GITHUB_TOKEN` or `GH_TOKEN` when you have one, which turns GitHub's 60-requests-an-hour guest allowance into 5,000 — a browser has nowhere to keep a secret, so this is the one thing the terminal does strictly better than the site. It also separates "GitHub said no" into rate-limited, private-or-gone, and throttled, because those need three different responses.
76
95
 
77
96
  **It is the website's engine, not a reimplementation.** `onboarder explore` runs the same modules in the same order as `POST /api/scan` — `scanRepo` → `detectManifest` → `computeFacts` → `buildSearchIndex` — and the same projections the browser's views are projections of. A second implementation would drift, and a drifted map is worse than no map.
78
97
 
98
+ Where the site draws a canvas, the terminal draws its own idiom from the same numbers: the coupling heat grid becomes block characters (which survive being piped to a file or read in black and white), and the force-directed graph becomes an arrow tree (`→` imports, `←` imported by) that shows the part that answers *what breaks if I break this*.
99
+
79
100
  Details worth knowing:
80
101
 
81
102
  - **Forgiving paths.** `show logger.js` finds `server/logger.js`. A genuinely ambiguous name (`index.js`) lists the candidates instead of guessing — silently picking the wrong file is how a map loses your trust.
@@ -0,0 +1,457 @@
1
+ // The advanced views: the parts of the site that had no terminal equivalent.
2
+ //
3
+ // Everything here is a *projection* of data the engine already computed or of
4
+ // git the repo already contains. Nothing re-implements analysis. Where the web
5
+ // draws a canvas (a heat grid, a force graph) the terminal draws block
6
+ // characters and an arrow tree from the same numbers, because those are the
7
+ // terminal's own idioms — not degraded versions of the web views.
8
+
9
+ import fs from 'node:fs/promises';
10
+ import path from 'node:path';
11
+ import { execFile } from 'node:child_process';
12
+ import { promisify } from 'node:util';
13
+
14
+ import { bold, cyan, dim, ok, warn, bad, panel, row, fit, termWidth } from '../ui.js';
15
+ import { bar, columns, couplingGrid, depTree, labelled, step } from './graphs.js';
16
+ import { fileFacts, resolveTarget } from './session.js';
17
+ import { targetError } from './views.js';
18
+ import { wrapText } from './wrap.js';
19
+ import { gitLog, parseGitLog } from '../../server/gitHistory.js';
20
+ import { analyzeHistory, unavailableHistory } from '../../shared/analyzer/history.js';
21
+ import { parsePorcelainBlame } from '../../server/apiGitBlame.js';
22
+ import { couplingMatrix } from '../../shared/analyzer/patterns.js';
23
+ import { overviewDiagram, layersDiagram, fileDetailDiagram } from '../../shared/diagram/mermaid.js';
24
+ import { fileStaticDoc, folderStaticDoc } from '../../shared/analyzer/docs.js';
25
+
26
+ const run = promisify(execFile);
27
+ const MAX = 200;
28
+
29
+ // Git history is loaded lazily and cached on the repo object. It shells out, and
30
+ // a person who never types `log` or `blame` should not pay for it — and on a
31
+ // large repo that is the difference between an instant prompt and a visible
32
+ // pause. A failure is cached too, so a missing `git` binary costs one failed
33
+ // call rather than one per keystroke.
34
+ export async function loadHistory(repo, { force = false } = {}) {
35
+ if (!force && repo._history !== undefined) return repo._history;
36
+ try {
37
+ const log = await gitLog(repo.root);
38
+ if (!log.ok) {
39
+ repo._history = unavailableHistory(log.reason);
40
+ return repo._history;
41
+ }
42
+ repo._history = analyzeHistory(repo.scan, parseGitLog(log.text), { totalCommits: log.totalCommits });
43
+ } catch (e) {
44
+ repo._history = unavailableHistory('The git history could not be read — the scan itself is unaffected.');
45
+ }
46
+ return repo._history;
47
+ }
48
+
49
+ // ------------------------------------------------------------------- log ---
50
+
51
+ // Recent commits, and the people who wrote them. The site shows this in a
52
+ // history tab; the terminal answer is a compact list, because the question this
53
+ // answers — "who is working on this, and what did they touch lately" — is one
54
+ // glance, not a browsing session.
55
+ export async function log(repo, { limit = 15 } = {}) {
56
+ const h = await loadHistory(repo);
57
+ if (!h.available) return dim(wrapText('No git history: ' + h.reason));
58
+ const w = termWidth();
59
+ const out = [panel('git history', [
60
+ { label: 'commits', value: `${h.commitCount} analyzed` + (h.truncated ? dim(` (of ${h.totalCommits} — log capped)`) : '') },
61
+ { label: 'authors', value: h.authors.slice(0, 4).map((a) => `${a.name} (${a.commits})`).join(', ') || '—' },
62
+ { label: 'window', value: `${String(h.firstCommitAt || '').slice(0, 10)} → ${String(h.lastCommitAt || '').slice(0, 10)}` },
63
+ ])];
64
+
65
+ out.push(dim(fit(' recent commits', Math.max(4, termWidth() - 2))));
66
+ for (const c of h.commits.slice(0, Math.min(Number(limit) || 15, MAX))) {
67
+ // sha / author / date as marker, value, tail, so a narrow terminal drops the
68
+ // date rather than running the row off the edge.
69
+ out.push(labelled(dim(c.hash.slice(0, 8) + ' '), c.author?.name || '?',
70
+ dim(String(c.date || '').slice(0, 10) + ' ' + (c.files?.length || 0) + 'f'), { pad: 4 }));
71
+ }
72
+ if (h.authors.length) {
73
+ out.push(dim(fit(' commits per author', Math.max(4, termWidth() - 2))));
74
+ const max = Math.max(...h.authors.map((a) => a.commits));
75
+ for (const a of h.authors.slice(0, 8)) {
76
+ const tail = dim(String(a.commits).padStart(4)) + (w > 30 ? ' ' + dim(bar(a.commits, max, Math.max(0, Math.min(18, w - 28)))) : '');
77
+ out.push(labelled('', a.name, tail, { pad: 4 }));
78
+ }
79
+ }
80
+ return out.join('\n');
81
+ }
82
+
83
+ const GLYPH_MARK = '●';
84
+
85
+ // ---------------------------------------------------------------- blame ---
86
+
87
+ // Who wrote each line, and when. `git blame --porcelain` through the same parser
88
+ // the site's blame view uses, so a line's author and date are the same answer in
89
+ // both places. Shown as a histogram of authors per line plus the recent
90
+ // commits, because a per-line listing of a 400-line file is a page of output
91
+ // nobody reads.
92
+ export async function blame(repo, { target = '', limit = 20 } = {}) {
93
+ const found = resolveTarget(repo, target);
94
+ if (found.error) return targetError(found);
95
+ if (found.folder) return dim(wrapText(`${found.folder.path || '.'} is a folder — blame a file inside it.`, ' '));
96
+
97
+ const p = found.file.path;
98
+ let raw;
99
+ try {
100
+ const { stdout } = await run('git', ['-C', repo.root, 'blame', '--line-porcelain', '--', p], { maxBuffer: 32 * 1024 * 1024 });
101
+ raw = stdout;
102
+ } catch (e) {
103
+ const why = /not a git repository|Unable to read/.test(String(e.stderr || e.message))
104
+ ? 'This folder is not in a git repository.'
105
+ : 'git blame could not read this file.';
106
+ return dim(wrapText(why));
107
+ }
108
+
109
+ const lines = parsePorcelainBlame(raw);
110
+ if (!lines.length) return dim(wrapText('No blame information for this file.'));
111
+
112
+ const w = termWidth();
113
+ const byAuthor = new Map();
114
+ for (const l of lines) byAuthor.set(l.author, (byAuthor.get(l.author) || 0) + 1);
115
+ const authors = [...byAuthor.entries()].sort((a, b) => b[1] - a[1]);
116
+ const recent = [...new Map(lines.map((l) => [l.sha, l])).values()]
117
+ .sort((a, b) => String(b.date).localeCompare(String(a.date)))
118
+ .slice(0, Math.min(Number(limit) || 20, 10));
119
+
120
+ const out = [panel(p, [
121
+ { label: 'lines', value: String(lines.length) },
122
+ { label: 'authors', value: String(authors.length) },
123
+ { label: 'oldest', value: lines.map((l) => l.date).filter(Boolean).sort()[0]?.slice(0, 10) || '—' },
124
+ { label: 'newest', value: lines.map((l) => l.date).filter(Boolean).sort().pop()?.slice(0, 10) || '—' },
125
+ ])];
126
+
127
+ out.push(dim(fit(' lines per author', Math.max(4, termWidth() - 2))));
128
+ const max = Math.max(...authors.map(([, n]) => n));
129
+ for (const [name, n] of authors) {
130
+ const tail = dim(String(n).padStart(5)) + (w > 34 ? ' ' + dim(bar(n, max, Math.max(0, Math.min(20, w - 30)))) : '');
131
+ out.push(labelled('', name, tail, { pad: 4 }));
132
+ }
133
+ if (recent.length) {
134
+ out.push(dim(fit(' most recent commits touching this file', Math.max(4, termWidth() - 2))));
135
+ for (const c of recent) {
136
+ // Without a separator the author and date ran together into
137
+ // "Amitpandey882026-09-25" — the sha-width fit left no gap.
138
+ out.push(labelled(dim(c.sha.slice(0, 8) + ' '), c.author, dim(String(c.date || '').slice(0, 10)), { pad: 4 }));
139
+ }
140
+ }
141
+ return out.join('\n');
142
+ }
143
+
144
+ // ------------------------------------------------------------- coupling ---
145
+
146
+ // Folder-to-folder traffic as a heat grid. The site draws this on a canvas; a
147
+ // terminal draws density with block characters, which survives being piped to a
148
+ // file, printed, or read by someone who cannot distinguish the colors the web
149
+ // version relies on.
150
+ export function coupling(repo) {
151
+ if (!repo.coupling || !repo.coupling.folders.length) {
152
+ return dim(wrapText('No cross-folder imports — this repo is a single package, or nothing imports across folders.'));
153
+ }
154
+ const grid = couplingGrid(repo, { maxFolders: 10 });
155
+ const head = dim(wrapText('folder-to-folder imports (darker = more edges)', ' '));
156
+ const legend = dim(fit(' ' + [1, 2, 3, 4].map((n) => step(n, 4)).join('') + ' low → high', Math.max(1, termWidth() - 2)));
157
+ return [head, ...grid, legend].join('\n');
158
+ }
159
+
160
+ // ------------------------------------------------------------- clusters ---
161
+
162
+ // Louvain communities, described. The site draws these as colored blobs in a
163
+ // force graph; the terminal names them by the folder they mostly live in, which
164
+ // is the fact a person actually wants ("this repo is really four things") and is
165
+ // the same number, not a picture of it.
166
+ export function clusters(repo, { limit = 8 } = {}) {
167
+ const groups = (repo.facts.communities || []).filter((c) => c.size > 1);
168
+ if (!groups.length) return dim(wrapText('No distinct module clusters — the graph is too small or too interconnected.'));
169
+ const w = termWidth();
170
+ const out = [
171
+ dim(fit(' module clusters', Math.max(1, termWidth() - 2))),
172
+ dim(wrapText('groups of files that import each other more than the rest', ' ')),
173
+ ];
174
+ for (const c of groups.slice(0, Math.min(Number(limit) || 8, MAX))) {
175
+ const folders = tally(c.members);
176
+ const where = Object.entries(folders).sort((a, b) => b[1] - a[1]).slice(0, 3)
177
+ .map(([f, n]) => `${f}/${n}`).join(' ');
178
+ out.push(labelled(ok(GLYPH_MARK + ' '), cyan(where || '(mixed)'), dim(` ${c.size} files`), { pad: 4 }));
179
+ }
180
+ return out.join('\n');
181
+ }
182
+
183
+ function tally(paths) {
184
+ const out = {};
185
+ for (const p of paths) {
186
+ const top = p.includes('/') ? p.slice(0, p.indexOf('/')) : '.';
187
+ out[top] = (out[top] || 0) + 1;
188
+ }
189
+ return out;
190
+ }
191
+
192
+ // ---------------------------------------------------------------- blast ---
193
+
194
+ // What breaks if this file breaks: the transitive set of files that import it,
195
+ // directly or through anything in between. Direct fan-in is on `deps`; this is
196
+ // the number that decides whether a change is a one-file edit or a quarter of
197
+ // the repo, and it is the reason the site has a blast-radius view.
198
+ export function blast(repo, { target = '', limit = 15 } = {}) {
199
+ const found = resolveTarget(repo, target);
200
+ if (found.error) return targetError(found);
201
+ if (found.folder) return dim(wrapText('Name a file, not a folder.', ' '));
202
+
203
+ const p = found.file.path;
204
+ // Walk importers transitively. The reverse graph is built once; the site's
205
+ // health engine does the same condensation with Tarjan, and for a single file
206
+ // this breadth-first walk is the cheap, obvious version of the same answer.
207
+ const reverse = new Map();
208
+ for (const e of repo.scan.edges) {
209
+ if (!reverse.has(e.to)) reverse.set(e.to, []);
210
+ reverse.get(e.to).push(e.from);
211
+ }
212
+ const seen = new Set([p]);
213
+ let frontier = [p];
214
+ const direct = (repo.facts.importers[p] || []).length;
215
+ while (frontier.length) {
216
+ const next = [];
217
+ for (const cur of frontier) {
218
+ for (const parent of reverse.get(cur) || []) {
219
+ if (seen.has(parent)) continue;
220
+ seen.add(parent);
221
+ next.push(parent);
222
+ }
223
+ }
224
+ frontier = next;
225
+ }
226
+ seen.delete(p);
227
+
228
+ const affected = [...seen].sort();
229
+ const w = termWidth();
230
+ const health = repo.health.perFile?.find((f) => f.path === p);
231
+ const out = [panel(p, [
232
+ { label: 'direct', value: `${direct} file${direct === 1 ? '' : 's'} import this` },
233
+ { label: 'transitive', value: `${affected.length} file${affected.length === 1 ? '' : 's'} affected if it breaks` },
234
+ { label: 'blast radius', value: repo.scan.files.length ? Math.round((affected.length / repo.scan.files.length) * 100) + '% of the repo' : '—' },
235
+ ...(health?.blast !== undefined ? [{ label: 'measured', value: health.blastExact ? String(health.blast) : dim('not computed at this size') }] : []),
236
+ ])];
237
+
238
+ if (!affected.length) {
239
+ out.push(ok(wrapText('Nothing imports this, directly or transitively. It is a leaf — safe to change.', ' ')));
240
+ } else {
241
+ out.push(dim(fit(` affected files (${affected.length})`, Math.max(4, w - 2))));
242
+ for (const a of affected.slice(0, Math.min(Number(limit) || 15, MAX))) {
243
+ out.push(labelled(warn(GLYPH_MARK + ' '), a, '', { pad: 4 }));
244
+ }
245
+ const shown = Math.min(Number(limit) || 15, MAX);
246
+ if (affected.length > shown) out.push(dim(fit(` … and ${affected.length - shown} more`, Math.max(4, w - 2))));
247
+ }
248
+ return out.join('\n');
249
+ }
250
+
251
+
252
+ // Files that are both complex and frequently changed. That combination is the
253
+ // thing worth a second look — complexity alone is a style opinion, churn alone
254
+ // is just activity, and the intersection is where bugs live. The same number the
255
+ // site's hotspot view ranks by.
256
+ export async function hotspots(repo, { limit = 12 } = {}) {
257
+ const h = await loadHistory(repo);
258
+ if (!h.available) return dim(wrapText('No git history: ' + h.reason));
259
+ if (!h.perFile.length) return dim(wrapText('No file has been committed in this window.'));
260
+ const w = termWidth();
261
+ const top = h.perFile.slice().sort((a, b) => b.hotspot - a.hotspot).slice(0, Math.min(Number(limit) || 12, MAX));
262
+ const max = Math.max(...top.map((f) => f.hotspot));
263
+ const nameRoom = Math.max(12, w - 34);
264
+ const out = [
265
+ dim(fit(' hotspots', Math.max(1, termWidth() - 2))),
266
+ dim(wrapText('complexity × churn — the files most worth a second look', ' ')),
267
+ ];
268
+ for (const f of top) {
269
+ // The hotspot score is drawn as a bar in the tail, and the bar is the first
270
+ // thing `labelled` drops on a narrow terminal — which is the right order:
271
+ // the path identifies the file, the churn/complexity numbers explain why it
272
+ // is on the list, and the bar is decoration.
273
+ const barRoom = Math.max(0, Math.min(16, w - 40));
274
+ const tail = dim(` ${f.churn}c ${f.complexity}x `) + (barRoom > 4 ? dim(bar(f.hotspot, max, barRoom)) : '');
275
+ out.push(labelled(warn(GLYPH_MARK + ' '), cyan(f.path), tail, { pad: 4 }));
276
+ }
277
+ const solo = h.perFile.filter((f) => f.solo).length;
278
+ if (solo) out.push(dim(wrapText(`${solo} file${solo === 1 ? '' : 's'} changed by exactly one person — a bus factor of 1`, ' ')));
279
+ return out.join('\n');
280
+ }
281
+
282
+ // -------------------------------------------------------------- diagram ---
283
+
284
+ // Real Mermaid source, from the same generator the site's diagram pane uses. A
285
+ // terminal cannot render Mermaid, so the honest thing is to emit it and say
286
+ // where to paste it. The thing a terminal *can* draw is `graph` below, which is
287
+ // the same information in the terminal's own idiom.
288
+ export function diagram(repo, { target = '' } = {}) {
289
+ const w = termWidth();
290
+ const dump = (title, source) => [
291
+ bold(' mermaid — ' + title),
292
+ dim(' paste into any Mermaid renderer, or open it in the web UI'),
293
+ '',
294
+ ...source.split('\n').map((l) => ' ' + fit(l, w - 2)),
295
+ ].join('\n');
296
+
297
+ if (!String(target).trim()) return dump('whole repo', overviewDiagram(repo.scan, repo.facts).source);
298
+
299
+ const found = resolveTarget(repo, target);
300
+ if (found.error) return targetError(found);
301
+ if (found.folder) return dim(wrapText('Name a file, not a folder.', ' '));
302
+ return dump(found.file.path, fileDetailDiagram(repo.scan, repo.facts, found.file.path).source);
303
+ }
304
+
305
+ // The layer stack as Mermaid — the site's "layers" diagram, verbatim.
306
+ export function layerDiagram(repo) {
307
+ const w = termWidth();
308
+ return [
309
+ bold(' mermaid — layers'),
310
+ ...layersDiagram(repo.scan, repo.facts, repo.layers).source.split('\n').map((l) => ' ' + fit(l, w - 2)),
311
+ ].join('\n');
312
+ }
313
+
314
+ // ----------------------------------------------------------------- graph ---
315
+
316
+ // The dependency tree around a file, in arrows. This is the terminal's force
317
+ // graph: `→` is "imports", `←` is "imported by", and a cycle shows up as an
318
+ // arrow pointing back the way it came. Depth-limited because a terminal is not a
319
+ // canvas — an unbounded graph is a screen of noise in both.
320
+ export function graph(repo, { target = '', depth = 2, direction = 'both' } = {}) {
321
+ const found = resolveTarget(repo, target);
322
+ if (found.error) return targetError(found);
323
+ if (found.folder) return dim(wrapText('Name a file, not a folder.', ' '));
324
+
325
+ if (!repo.byPath) repo.byPath = new Map(repo.scan.files.map((f) => [f.path, f]));
326
+ const d = Math.max(1, Math.min(Number(depth) || 2, 6));
327
+ return [
328
+ dim(fit(' graph — ' + found.file.path, Math.max(4, termWidth() - 2))),
329
+ ...depTree(repo, found.file.path, { depth: d, direction }),
330
+ dim(fit(' → imports ← imported by', Math.max(4, termWidth() - 2))),
331
+ ].join('\n');
332
+ }
333
+
334
+ // ------------------------------------------------------------------ docs ---
335
+
336
+ // Prose documentation for a file or a folder, from the same `docs.js` the site
337
+ // generates its reference pages from. With no argument it writes a whole
338
+ // ONBOARDER.md into the repo root — the terminal equivalent of the site's docs
339
+ // generator, and the thing you want when handing a codebase to someone.
340
+ export function docs(repo, { target = '' } = {}) {
341
+ if (String(target).trim()) {
342
+ const found = resolveTarget(repo, target);
343
+ if (found.error) return targetError(found);
344
+ if (found.folder) {
345
+ return [bold(' ' + (found.folder.path || '.')), dim(wrapText(folderStaticDoc(found.folder.path, repo.scan, repo.facts, 0)))].join('\n');
346
+ }
347
+ return [bold(' ' + found.file.path), dim(wrapText(fileStaticDoc(found.file.path, repo.scan, repo.facts)))].join('\n');
348
+ }
349
+
350
+ const lines = [
351
+ `# ${repo.name}`, '',
352
+ `> Generated by \`onboarder docs\` — ${new Date().toISOString().slice(0, 10)}`, '',
353
+ 'A map of this codebase: what it is made of, where to start reading, and which files everything leans on.', '',
354
+ '## Start here', '',
355
+ ];
356
+ for (const stop of repo.tour) lines.push(`- \`${stop.path}\` — ${stop.why}`);
357
+ lines.push('', '## Folders', '');
358
+ for (const folder of repo.scan.folders) {
359
+ lines.push(`- \`${folder.path}\` — ${folderStaticDoc(folder.path, repo.scan, repo.facts, 0)}`);
360
+ }
361
+ return lines.join('\n');
362
+ }
363
+
364
+ // Write the whole-repo doc to disk. Separated from `docs` because this one does
365
+ // I/O and needs to say where it wrote, and because the print form must stay pure
366
+ // for the tests.
367
+ export async function writeDocs(repo, target = 'ONBOARDER.md') {
368
+ const body = docs(repo, {});
369
+ const abs = path.join(repo.root, target);
370
+ await fs.writeFile(abs, body + '\n', 'utf8');
371
+ return abs;
372
+ }
373
+
374
+ // --------------------------------------------------------------- symbols ---
375
+
376
+ // The functions, classes and exports in one file, with line numbers. The site
377
+ // gets this from a Monaco outline panel; the terminal gets a list you can pipe
378
+ // into `grep` or read in one screen.
379
+ export function symbols(repo, { target = '' } = {}) {
380
+ const found = resolveTarget(repo, target);
381
+ if (found.error) return targetError(found);
382
+ if (found.folder) return dim(wrapText('Name a file, not a folder.', ' '));
383
+ const f = found.file;
384
+ const w = termWidth();
385
+ const fns = f.functions || [];
386
+ const classes = f.classes || [];
387
+ const exports = f.exports || [];
388
+ if (!fns.length && !classes.length && !exports.length) {
389
+ return dim(wrapText(`${f.name} has no functions, classes, or exports we can recognize.`));
390
+ }
391
+ const out = [panel(f.path, [
392
+ { label: 'functions', value: String(fns.length) },
393
+ { label: 'classes', value: String(classes.length) },
394
+ { label: 'exports', value: String(exports.length) },
395
+ ])];
396
+ if (classes.length) {
397
+ out.push(dim(fit(' classes', Math.max(2, w - 2))));
398
+ for (const c of classes) out.push(labelled('', cyan(c.name), dim(` line ${c.line ?? '?'}`), { pad: 4 }));
399
+ }
400
+ if (fns.length) {
401
+ out.push(dim(fit(' functions', Math.max(2, w - 2))));
402
+ for (const fn of fns.slice(0, 60)) {
403
+ out.push(labelled('', cyan(fn.name), dim(` ${fn.kind || 'fn'} line ${fn.line ?? '?'}`), { pad: 4 }));
404
+ }
405
+ if (fns.length > 60) out.push(dim(fit(` … and ${fns.length - 60} more`, Math.max(4, w - 2))));
406
+ }
407
+ return out.join('\n');
408
+ }
409
+
410
+ // ----------------------------------------------------------------- risks ---
411
+
412
+ // The problems, gathered in one place: cycles, orphans, dead exports, test
413
+ // coverage, dependency drift. Each has its own command on the site; in a
414
+ // terminal, "what is wrong with this repo" is one question and deserves one
415
+ // answer, so they are collected rather than made you ask five times.
416
+ export function risks(repo) {
417
+ const f = repo.facts;
418
+ const w = termWidth();
419
+ const out = [dim(fit(' risks', Math.max(4, w - 2)))];
420
+
421
+ const findings = [];
422
+ if (f.cycles?.length) findings.push([f.cycles.length, `circular import${f.cycles.length === 1 ? '' : 's'} — the largest is ${f.cycles[0].length} files`]);
423
+ if (f.orphans?.length) findings.push([f.orphans.length, 'files nothing imports — dead code, or entry points we did not see']);
424
+ if (f.deadExports?.length) findings.push([f.deadExports.length, `exports nothing imports (${f.deadExports.slice(0, 2).map((e) => e.name).join(', ')})`]);
425
+ if (f.testCoverage && f.testCoverage.ratio < 50) findings.push([f.testCoverage.ratio + '%', 'of non-test files are touched by a test — coverage is low']);
426
+ if (f.depsDrift?.undeclaredImported?.length) findings.push([f.depsDrift.undeclaredImported.length, `imported but not declared (${f.depsDrift.undeclaredImported.slice(0, 2).join(', ')})`]);
427
+ if (f.depsDrift?.unusedDeclared?.length) findings.push([f.depsDrift.unusedDeclared.length, `declared but never imported (${f.depsDrift.unusedDeclared.slice(0, 2).join(', ')})`]);
428
+
429
+ if (!findings.length) return ok(wrapText('Nothing obvious is wrong with this repo. health and patterns have more.', ' '));
430
+
431
+ // Two layouts. Wide enough: marker, count, then the sentence filling the rest.
432
+ // Narrower than the marker plus a usable sentence: the count moves onto its
433
+ // own line, because a row of "● 11 imported" is worse than useless — the
434
+ // words that carry the meaning get one cell each. Everything is measured as
435
+ // plain text; styling happens last, so no escape sequence is ever sliced.
436
+ const wide = w >= leadWidth() + 14;
437
+ for (const [n, text] of findings) {
438
+ if (wide) {
439
+ const num = String(n).padStart(4);
440
+ const gutter = ' '.repeat(leadWidth() + num.length + 2);
441
+ const room = Math.max(1, w - gutter.length);
442
+ const wrapped = wrapText(text, '', room).split('\n');
443
+ out.push(lead() + dim(num) + ' ' + wrapped[0]
444
+ + (wrapped.length > 1 ? '\n' + gutter + wrapped.slice(1).join('\n' + gutter) : ''));
445
+ } else {
446
+ out.push(fit(lead() + n, Math.max(1, w)));
447
+ out.push(wrapText(text, ' '));
448
+ }
449
+ }
450
+ if (f.cycles?.length) out.push(' ' + dim(fit(f.cycles[0].slice(0, 3).join(' → ') + ' → …', Math.max(4, w - 6))));
451
+ out.push('');
452
+ out.push(dim(fit(' details: health · patterns · deps <file> · externals', Math.max(4, w - 2))));
453
+ return out.join('\n');
454
+ }
455
+
456
+ const leadWidth = () => (' ' + GLYPH_MARK + ' ').length;
457
+ const lead = () => ' ' + GLYPH_MARK + ' ';