Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat: quote the line where the edge happens — in the comment, the CLI, and one shared helper (#180)

anirudhkumar-nanonetsfbbcf9de0d2e
diff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.ts
index f64b9add..4e16ac2c 100644
--- a/src/blast/blast-cli.ts
+++ b/src/blast/blast-cli.ts
@@ -100,7 +100,7 @@ export async function runBlastCommand(dir: string, opts: BlastCliOptions): Promi
console.log(diagram ?? "%% no dependents to draw");
return;
}
- process.stdout.write(format === "markdown" ? markdownReport(report) : textReport(report));
+ process.stdout.write(format === "markdown" ? markdownReport(report, { root }) : textReport(report));
}
/**
diff --git a/src/blast/evidence.ts b/src/blast/evidence.ts
new file mode 100644
index 00000000..add3a1db
--- /dev/null
+++ b/src/blast/evidence.ts
@@ -0,0 +1,192 @@
+/**
+ * Turning a report into code a reader can see.
+ *
+ * `blast` knows which lines changed (git's hunks) and which symbols reach them
+ * (the walk), and both the hosted panel and the PR comment want to SHOW that
+ * rather than cite a line number the reader has to go and look up. The shaping
+ * lives here so the two surfaces quote the same lines: a comment that disagreed
+ * with the page it links to would be worse than one that said less.
+ */
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { Evidence, EvidenceLine } from "../viz/assemble.js";
+import type { Impacted, Seed } from "./blast.js";
+import type { ChangedFile, DiffLine } from "./diff.js";
+
+const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
+
+/** Symbols given their own snippet per node. Past this the panel is a file listing
+ * rather than a summary — the rest are still counted in the headline. */
+export const MAX_EVIDENCE = 4;
+/** Lines shown per snippet before it folds. A handful is a hunk you can read at a
+ * glance; a 30-line refactor is a diff view's job, not a panel's. */
+const MAX_LINES = 6;
+
+/** `L12-L34` → the numbers, so a label is something a reader can type. */
+export function spanRange(span: string): { start: number; end: number } | null {
+ const m = /^L(\d+)(?:-L(\d+))?$/.exec(span);
+ if (!m) return null;
+ const start = Number(m[1]);
+ return { start, end: m[2] === undefined ? start : Number(m[2]) };
+}
+
+function labelFor(name: string, path: string, span: string): string {
+ const r = spanRange(span);
+ return r ? `${name} · ${path}:${r.start}-${r.end}` : `${name} · ${path}`;
+}
+
+/** Keep the first {@link MAX_LINES}, and say how many were left. */
+function fold(lines: EvidenceLine[]): { lines: EvidenceLine[]; more?: number } {
+ if (lines.length <= MAX_LINES) return { lines };
+ return { lines: lines.slice(0, MAX_LINES), more: lines.length - MAX_LINES };
+}
+
+const asEvidenceLines = (lines: DiffLine[]): EvidenceLine[] =>
+ lines.map((l) => ({ n: l.n, sign: l.sign, text: l.text }));
+
+/**
+ * The hunks of `file` that fall inside `span`.
+ *
+ * A file's diff is split by symbol rather than shown whole, because two unrelated
+ * edits in one file are two answers — a panel that merges them makes the reader do
+ * the separating.
+ */
+function hunksIn(
+ file: ChangedFile,
+ span: { start: number; end: number } | null,
+): { lines: EvidenceLine[]; dropped: number } {
+ const out: EvidenceLine[] = [];
+ let dropped = 0;
+ for (const h of file.hunks) {
+ if (span && (h.end < span.start || h.start > span.end)) continue;
+ out.push(...asEvidenceLines(h.lines));
+ dropped += h.dropped;
+ }
+ return { lines: out, dropped };
+}
+
+/** Evidence for one changed symbol: what this PR did to it. */
+export function seedEvidence(seed: Seed, file: ChangedFile | undefined): Evidence | null {
+ if (!file) return null;
+ const span = seed.wholeFile ? null : spanRange(seed.span);
+ const { lines, dropped } = hunksIn(file, span);
+ if (lines.length === 0 && dropped === 0) return null;
+ const folded = fold(lines);
+ const more = (folded.more ?? 0) + dropped;
+ return {
+ label: seed.wholeFile ? seed.path : labelFor(seed.name, seed.path, seed.span),
+ note: file.status === "added" ? "new file" : seed.wholeFile ? "outside any symbol" : undefined,
+ lines: folded.lines,
+ more: more > 0 ? more : undefined,
+ };
+}
+
+const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+/**
+ * The first line inside a span that mentions one of `needles`, with its number.
+ *
+ * This is the whole trick behind "why is this symbol here": the edge says A calls
+ * B, and this finds the line where it does it. Shared so `blast`'s panel, its
+ * comment and `graft callers` all quote the same line for the same edge.
+ */
+export function referenceLine(
+ path: string,
+ span: string,
+ needles: RegExp[],
+ read: (path: string) => string[] | null,
+): { n: number; text: string } | null {
+ const range = spanRange(span);
+ const lines = read(path);
+ if (!range || !lines) return null;
+ for (const [i, text] of lines.slice(range.start - 1, range.end).entries()) {
+ if (needles.some((re) => re.test(text))) return { n: range.start + i, text };
+ }
+ return null;
+}
+
+/** A symbol name, matched as a whole word — `export` must not hit `exportViz`. */
+export const wordRe = (name: string): RegExp => new RegExp(`\\b${escapeRe(name)}\\b`);
+
+/**
+ * Evidence for one dependent symbol: the line that reaches the diff.
+ *
+ * Nothing changed here, so there is no hunk to show — the useful line is the one
+ * naming a changed symbol or module, which answers "why am I in this blast radius
+ * at all". Found by reading the symbol's span off disk.
+ *
+ * When no line names the diff, this returns nothing rather than quoting the span's
+ * first line: for a file-level dependent that first line is `/**`, and a panel that
+ * shows it has spent a code block to say nothing.
+ */
+export function impactedEvidence(
+ sym: Impacted,
+ reach: ReachTerms,
+ read: (path: string) => string[] | null,
+): Evidence | null {
+ // A changed symbol's own name is the strongest signal; a file-level dependent
+ // usually reaches the diff through its import line, which names a MODULE
+ // instead, so both are tried in that order.
+ const byName = referenceLine(sym.path, sym.span, reach.names.map(wordRe), read);
+ if (byName) {
+ const hit = reach.names.find((n) => wordRe(n).test(byName.text));
+ return {
+ label: labelFor(sym.name, sym.path, sym.span),
+ note: `${sym.relation} ${hit}`,
+ lines: [{ n: byName.n, sign: " ", text: byName.text }],
+ };
+ }
+
+ const byModule = referenceLine(sym.path, sym.span, reach.modules, read);
+ if (byModule) {
+ return {
+ label: labelFor(sym.name, sym.path, sym.span),
+ note: sym.relation,
+ lines: [{ n: byModule.n, sign: " ", text: byModule.text }],
+ };
+ }
+
+ // No line names the diff — an indirect reach (a dynamic import, a re-export),
+ // or a symbol whose whole file is the span. Quoting its first line means
+ // quoting `/**`, so the block is dropped instead: the path stays in `sources`
+ // and the panel simply says less.
+ return null;
+}
+
+/** What a line has to mention to be the line that reaches the diff. */
+export interface ReachTerms {
+ /** Changed symbol names, longest first. */
+ names: string[];
+ /** `from "./data.js"` for each changed file, matched on the module specifier so
+ * a common stem like `data` cannot match a variable of the same name. */
+ modules: RegExp[];
+}
+
+export function reachTerms(seeds: Seed[], changed: ChangedFile[]): ReachTerms {
+ const names = [...new Set(seeds.filter((s) => !s.wholeFile).map((s) => s.name))].sort((a, b) => b.length - a.length);
+ const stems = [...new Set(changed.map((f) => f.path.replace(/\.[^./]+$/, "").split("/").pop() ?? ""))].filter(Boolean);
+ return {
+ names,
+ modules: stems.map((stem) => new RegExp(`["'\`][^"'\`]*\\b${escapeRe(stem)}(\\.[a-z]+)?["'\`]`)),
+ };
+}
+
+/** Read each file once, and never fail: a snippet is a nicety, and a symbol whose
+ * file moved under us must not take the whole page down. */
+export function fileReader(root: string | undefined): (path: string) => string[] | null {
+ const cache = new Map<string, string[] | null>();
+ return (path: string) => {
+ if (root === undefined) return null;
+ const hit = cache.get(path);
+ if (hit !== undefined) return hit;
+ let lines: string[] | null = null;
+ try {
+ lines = readFileSync(join(root, path), "utf8").split("\n");
+ } catch {
+ // Deleted, renamed under us, or unreadable: no snippet, no failure.
+ lines = null;
+ }
+ cache.set(path, lines);
+ return lines;
+ };
+}
diff --git a/src/blast/render.ts b/src/blast/render.ts
index 6e77b41d..bdb8bad4 100644
--- a/src/blast/render.ts
+++ b/src/blast/render.ts
@@ -12,7 +12,9 @@
* against a cap of ten) and told a reviewer nothing per box — `src/graph/write.ts`
* on its own is not a unit anyone reasons about.
*/
-import type { BlastReport, TestSignal } from "./blast.js";
+import type { BlastReport, Impacted, TestSignal } from "./blast.js";
+import type { Evidence } from "../viz/assemble.js";
+import { fileReader, impactedEvidence, reachTerms } from "./evidence.js";
/** Diagram cap. Everything past it folds into one aggregate circle carrying the
* dropped counts, so the picture shrinks but never lies. */
@@ -98,8 +100,15 @@ export function mermaidDiagram(r: BlastReport): string | null {
return lines.join("\n");
}
-/** The PR-comment body: diagram, then one table, then everything else collapsed. */
-export function markdownReport(r: BlastReport): string {
+/**
+ * The PR-comment body: diagram, then one table, then everything else collapsed.
+ *
+ * `root` is the repository the report was taken in. With it, the collapsed symbol
+ * list quotes the line that reaches the diff — the same line the hosted page shows,
+ * from the same helper. Without it the list is unchanged, so a caller that has no
+ * checkout (a test, a piped report) loses nothing but the snippet.
+ */
+export function markdownReport(r: BlastReport, opts: { root?: string } = {}): string {
const out: string[] = [];
const symbols = r.modules.reduce((n, m) => n + m.symbols.length, 0);
@@ -122,7 +131,9 @@ export function markdownReport(r: BlastReport): string {
}
out.push("");
- out.push(...detailSections(r, symbols));
+ const reach = reachTerms(r.seeds, r.changed);
+ const read = fileReader(opts.root);
+ out.push(...detailSections(r, symbols, (s) => impactedEvidence(s, reach, read)));
const caveats = caveatLines(r);
if (caveats.length > 0) {
@@ -196,7 +207,7 @@ function impactTable(r: BlastReport): string[] {
* inside a details block without it, and `<strong>` rather than `**` because it
* processes no emphasis inside `<summary>` either.
*/
-function detailSections(r: BlastReport, symbols: number): string[] {
+function detailSections(r: BlastReport, symbols: number, evidence?: (s: Impacted) => Evidence | null): string[] {
const out: string[] = [];
if (symbols > 0) {
@@ -210,6 +221,11 @@ function detailSections(r: BlastReport, symbols: number): string[] {
for (const s of mod.symbols) {
if (listed++ >= MAX_SYMBOLS_LISTED) break;
out.push(`- \`${s.path}:${s.span}\` — ${s.name} (${s.relation}, depth ${s.depth})`);
+ // The line that reaches the diff, quoted from the same helper the hosted
+ // panel uses — a comment that disagreed with the page it links to would be
+ // worse than one that said less. Collapsed, so the comment stays short.
+ const [line] = evidence?.(s)?.lines ?? [];
+ if (line) out.push(` \`\`\`${line.n}: ${line.text.trim()}\`\`\``);
}
out.push("");
if (listed >= MAX_SYMBOLS_LISTED) {
diff --git a/src/blast/viz.ts b/src/blast/viz.ts
index db63e225..17f4a733 100644
--- a/src/blast/viz.ts
+++ b/src/blast/viz.ts
@@ -18,154 +18,26 @@
* affected side shows the line that reaches the diff. Both come from data already
* on hand — git's patch, and the file on disk — so the panel costs nothing.
*/
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import type { Evidence, EvidenceLine, VizEdge, VizGraph, VizNode } from "../viz/assemble.js";
-import type { BlastReport, ChangedArea, Impacted, ImpactedModule, Seed, TestSignal } from "./blast.js";
-import type { ChangedFile, DiffLine } from "./diff.js";
+import type { Evidence, VizEdge, VizGraph, VizNode } from "../viz/assemble.js";
+import type { BlastReport, ChangedArea, ImpactedModule, Seed, TestSignal } from "./blast.js";
+import type { ChangedFile } from "./diff.js";
+import {
+ MAX_EVIDENCE,
+ type ReachTerms,
+ fileReader,
+ impactedEvidence,
+ reachTerms,
+ seedEvidence,
+} from "./evidence.js";
const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
-/** Node-type names, which double as the viewer's legend labels. */
-const CHANGED = "changed";
-const AFFECTED = "affected";
-
-/** Symbols given their own snippet per node. Past this the panel is a file listing
- * rather than a summary — the rest are still counted in the headline. */
-const MAX_EVIDENCE = 4;
-/** Lines shown per snippet before it folds. A handful is a hunk you can read at a
- * glance; a 30-line refactor is a diff view's job, not a panel's. */
-const MAX_LINES = 6;
-
/** Kinds that carry behaviour — what "did a test reach it" is asked of. */
const BEHAVIOURAL = new Set(["function", "method", "class", "constructor"]);
-/** `L12-L34` → the numbers, so a label is something a reader can type. */
-function spanRange(span: string): { start: number; end: number } | null {
- const m = /^L(\d+)(?:-L(\d+))?$/.exec(span);
- if (!m) return null;
- const start = Number(m[1]);
- return { start, end: m[2] === undefined ? start : Number(m[2]) };
-}
-
-function labelFor(name: string, path: string, span: string): string {
- const r = spanRange(span);
- return r ? `${name} · ${path}:${r.start}-${r.end}` : `${name} · ${path}`;
-}
-
-/** Keep the first {@link MAX_LINES}, and say how many were left. */
-function fold(lines: EvidenceLine[]): { lines: EvidenceLine[]; more?: number } {
- if (lines.length <= MAX_LINES) return { lines };
- return { lines: lines.slice(0, MAX_LINES), more: lines.length - MAX_LINES };
-}
-
-const asEvidenceLines = (lines: DiffLine[]): EvidenceLine[] =>
- lines.map((l) => ({ n: l.n, sign: l.sign, text: l.text }));
-
-/**
- * The hunks of `file` that fall inside `span`.
- *
- * A file's diff is split by symbol rather than shown whole, because two unrelated
- * edits in one file are two answers — a panel that merges them makes the reader do
- * the separating.
- */
-function hunksIn(
- file: ChangedFile,
- span: { start: number; end: number } | null,
-): { lines: EvidenceLine[]; dropped: number } {
- const out: EvidenceLine[] = [];
- let dropped = 0;
- for (const h of file.hunks) {
- if (span && (h.end < span.start || h.start > span.end)) continue;
- out.push(...asEvidenceLines(h.lines));
- dropped += h.dropped;
- }
- return { lines: out, dropped };
-}
-
-/** Evidence for one changed symbol: what this PR did to it. */
-function seedEvidence(seed: Seed, file: ChangedFile | undefined): Evidence | null {
- if (!file) return null;
- const span = seed.wholeFile ? null : spanRange(seed.span);
- const { lines, dropped } = hunksIn(file, span);
- if (lines.length === 0 && dropped === 0) return null;
- const folded = fold(lines);
- const more = (folded.more ?? 0) + dropped;
- return {
- label: seed.wholeFile ? seed.path : labelFor(seed.name, seed.path, seed.span),
- note: file.status === "added" ? "new file" : seed.wholeFile ? "outside any symbol" : undefined,
- lines: folded.lines,
- more: more > 0 ? more : undefined,
- };
-}
-
-const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-
-/**
- * Evidence for one dependent symbol: the line that reaches the diff.
- *
- * Nothing changed here, so there is no hunk to show — the useful line is the one
- * naming a changed symbol or module, which answers "why am I in this blast radius
- * at all". Found by reading the symbol's span off disk.
- *
- * When no line names the diff, this returns nothing rather than quoting the span's
- * first line: for a file-level dependent that first line is `/**`, and a panel that
- * shows it has spent a code block to say nothing.
- */
-function impactedEvidence(
- sym: Impacted,
- reach: ReachTerms,
- read: (path: string) => string[] | null,
-): Evidence | null {
- const span = spanRange(sym.span);
- const lines = read(sym.path);
- if (!span || !lines) return null;
-
- const body = lines.slice(span.start - 1, span.end);
- for (const [i, text] of body.entries()) {
- const hit = reach.names.find((n) => new RegExp(`\\b${escapeRe(n)}\\b`).test(text));
- if (hit !== undefined) {
- return {
- label: labelFor(sym.name, sym.path, sym.span),
- note: `${sym.relation} ${hit}`,
- lines: [{ n: span.start + i, sign: " ", text }],
- };
- }
- // A file-level dependent usually reaches the diff through its import line, and
- // that line names a MODULE, not one of the changed symbols.
- const mod = reach.modules.find((re) => re.test(text));
- if (mod !== undefined) {
- return {
- label: labelFor(sym.name, sym.path, sym.span),
- note: sym.relation,
- lines: [{ n: span.start + i, sign: " ", text }],
- };
- }
- }
-
- // No line names the diff — an indirect reach, or a symbol whose whole file is
- // the span. Quoting its first line means quoting `/**`, which answers nothing;
- // the path stays in `sources` and the panel simply says less.
- return null;
-}
-
-/** What a line has to mention to be the line that reaches the diff. */
-interface ReachTerms {
- /** Changed symbol names, longest first. */
- names: string[];
- /** `from "./data.js"` for each changed file, matched on the module specifier so
- * a common stem like `data` cannot match a variable of the same name. */
- modules: RegExp[];
-}
-
-function reachTerms(seeds: Seed[], changed: ChangedFile[]): ReachTerms {
- const names = [...new Set(seeds.filter((s) => !s.wholeFile).map((s) => s.name))].sort((a, b) => b.length - a.length);
- const stems = [...new Set(changed.map((f) => f.path.replace(/\.[^./]+$/, "").split("/").pop() ?? ""))].filter(Boolean);
- return {
- names,
- modules: stems.map((stem) => new RegExp(`["'\`][^"'\`]*\\b${escapeRe(stem)}(\\.[a-z]+)?["'\`]`)),
- };
-}
+/** Node-type names, which double as the viewer's legend labels. */
+const CHANGED = "changed";
+const AFFECTED = "affected";
/** One sentence about the tests, rather than the two that used to say it twice. */
function testNote(a: ChangedArea): string {
@@ -338,23 +210,3 @@ export function blastVizGraph(r: BlastReport, opts: { root?: string } = {}): Viz
edges,
};
}
-
-/** Read each file once, and never fail: a snippet is a nicety, and a symbol whose
- * file moved under us must not take the whole page down. */
-function fileReader(root: string | undefined): (path: string) => string[] | null {
- const cache = new Map<string, string[] | null>();
- return (path: string) => {
- if (root === undefined) return null;
- const hit = cache.get(path);
- if (hit !== undefined) return hit;
- let lines: string[] | null = null;
- try {
- lines = readFileSync(join(root, path), "utf8").split("\n");
- } catch {
- // Deleted, renamed under us, or unreadable: no snippet, no failure.
- lines = null;
- }
- cache.set(path, lines);
- return lines;
- };
-}
diff --git a/src/cli.ts b/src/cli.ts
index 880af035..43103619 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -168,6 +168,28 @@ async function refreshBefore(dir: string, opts: { refresh?: boolean }): Promise<
* as it is on disk, no rebuild. */
const NO_REFRESH_FLAG = ["--no-refresh", "skip the freshness check — answer from the graph as-is"] as const;
+const VIZ_TABS = ["context", "code", "outline"] as const;
+type VizTab = (typeof VIZ_TABS)[number];
+
+/**
+ * `--tabs context,code` → the tabs to write into an exported page.
+ *
+ * An unknown name is a caller mistake worth failing on rather than silently
+ * dropping: a page exported with a typo'd tab list would be missing a tab and
+ * nothing would say why. Undefined means "all of them", which is the default the
+ * exporter already applies.
+ */
+function parseTabs(raw: string | undefined): VizTab[] | undefined {
+ if (raw === undefined) return undefined;
+ const want = raw.split(",").map((t) => t.trim()).filter(Boolean);
+ const bad = want.filter((t) => !VIZ_TABS.includes(t as VizTab));
+ if (bad.length > 0 || want.length === 0) {
+ console.error(`✗ --tabs takes a comma-separated subset of ${VIZ_TABS.join(", ")}${bad.length ? ` — got "${bad.join('", "')}"` : ""}`);
+ process.exit(1);
+ }
+ return want as VizTab[];
+}
+
/**
* Commands that own the upgrade story themselves (`version`, `upgrade`) or must
* not editorialize on stderr at startup (`mcp` runs its own upkeep at boot, and
@@ -591,7 +613,8 @@ program
.option("--no-open", "don't open the browser")
.option("--export <dir>", "write one self-contained index.html instead of serving (for CI, GitHub Pages, or a build artifact)")
.option("--title <text>", "subtitle shown beside the repo name in an exported page (e.g. \"PR #151\")")
- .action(async (dirArg: string | undefined, opts: { port: string; open: boolean; export?: string; title?: string }) => {
+ .option("--tabs <list>", "tabs the exported page offers, comma separated: context,code,outline (default: all three)")
+ .action(async (dirArg: string | undefined, opts: { port: string; open: boolean; export?: string; title?: string; tabs?: string }) => {
const dir = noteQuery(queryRoot(dirArg));
const { existsSync } = await import("node:fs");
const { resolve, basename } = await import("node:path");
@@ -617,6 +640,7 @@ program
outDir: resolve(opts.export),
repoName: basename(root),
subtitle: opts.title,
+ tabs: parseTabs(opts.tabs),
});
const kb = Math.round(out.bytes / 1024);
console.log(
diff --git a/src/graph/traverse-cli.ts b/src/graph/traverse-cli.ts
index 462e07ae..a378d0a2 100644
--- a/src/graph/traverse-cli.ts
+++ b/src/graph/traverse-cli.ts
@@ -12,6 +12,7 @@
* tool (`src/mcp/tools.ts`), so both surfaces render identical reports.
*/
import { resolve } from "node:path";
+import { fileReader, referenceLine, wordRe } from "../blast/evidence.js";
import { contextDirFor } from "../context/node-file.js";
import { withSavings, savingsFor, type Savings } from "../context/savings.js";
import { loadGraphCached } from "./load.js";
@@ -40,12 +41,40 @@ export function headerOf(n: NodeV1): string {
}
/** `showDepth` is set for multi-hop walks (depth > 1), matching the old
- * `graft impact` output which tagged every hit with its BFS depth. */
-export function hitLine(direction: Direction, hit: EdgeHit, showDepth: boolean): string {
+ * `graft impact` output which tagged every hit with its BFS depth.
+ *
+ * `quote`, when given, is the call site itself — the line inside the hit where it
+ * references the symbol. An edge that says "total calls add" is a claim; the line
+ * under it is the evidence, and it saves opening the file to check.
+ */
+export function hitLine(direction: Direction, hit: EdgeHit, showDepth: boolean, quote?: Quote): string {
const arrow = ARROW[direction];
const depthTag = showDepth ? ` [depth ${hit.depth}]` : "";
const label = hit.node ? `${hit.node.name} (${hit.node.path}:${hit.node.span})` : `${hit.id} (unresolved import)`;
- return ` ${hit.relation} ${arrow} ${label}${depthTag}`;
+ const line = ` ${hit.relation} ${arrow} ${label}${depthTag}`;
+ return quote ? `${line}\n ${quote.n}: ${quote.text.trim()}` : line;
+}
+
+/** A quoted source line: where the edge actually happens. */
+interface Quote {
+ n: number;
+ text: string;
+}
+
+/**
+ * The call site for one hit, or nothing.
+ *
+ * Only for a resolved hit whose span we can read: an unresolved import has no
+ * file, and a hit at depth 2+ references something in between rather than the
+ * symbol asked about, so quoting it would point at the wrong line.
+ */
+function quoteFor(
+ hit: EdgeHit,
+ name: string,
+ read: (path: string) => string[] | null,
+): Quote | undefined {
+ if (!hit.node || hit.depth > 1) return undefined;
+ return referenceLine(hit.node.path, hit.node.span, [wordRe(name)], read) ?? undefined;
}
/** Tokens-saved baseline for a callers/callees walk: the files of the matched
@@ -200,10 +229,12 @@ export function runCallersCommand(query: string, dir: string, opts: CallersCliOp
}
const lines: string[] = [];
+ // One reader for the whole walk: several hits usually live in the same file.
+ const read = fileReader(root);
for (const { symbol, hits } of results) {
lines.push(headerOf(symbol));
if (hits.length === 0) lines.push(looseNoteFor(direction, symbol.name, matches.length));
- else for (const h of hits) lines.push(hitLine(direction, h, showDepth));
+ else for (const h of hits) lines.push(hitLine(direction, h, showDepth, quoteFor(h, symbol.name, read)));
lines.push("");
}
const body = lines.join("\n").replace(/\n+$/, "\n");
diff --git a/test/blast-render.test.ts b/test/blast-render.test.ts
index 6e1b11cf..1346c5ac 100644
--- a/test/blast-render.test.ts
+++ b/test/blast-render.test.ts
@@ -11,6 +11,9 @@
*/
import { test } from "node:test";
import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
import { markdownReport, mermaidDiagram, textReport } from "../src/blast/render.js";
import type { BlastReport, ChangedArea, ImpactedModule, TestSignal } from "../src/blast/blast.js";
@@ -140,3 +143,27 @@ test("blast markdown: test-only dependents are counted, never mixed into the are
assert.match(textReport(report()), /1 test suite also references this code \(not listed\)/);
});
+
+test("markdown: the collapsed list quotes the line that reaches the diff", () => {
+ const root = mkdtempSync(join(tmpdir(), "graft-render-"));
+ mkdirSync(join(root, "core"), { recursive: true });
+ // `mod("core/")` puts its symbols in core/dep.ts at L1-L3, and line 1 is what
+ // makes this file part of the radius at all.
+ writeFileSync(
+ join(root, "core", "dep.ts"),
+ 'import { thing } from "./f0.js";\nexport function s0() {\n return thing();\n}\n',
+ );
+
+ const md = markdownReport(report(), { root });
+ const quoted = '`1: import { thing } from "./f0.js";`';
+ assert.ok(md.includes(quoted), "the reaching line is shown");
+ // It must stay BELOW the fold: the comment's job is five circles and a table,
+ // and this is the part nobody reads by default.
+ assert.ok(md.indexOf(quoted) > md.indexOf("<details>"), "quoted inside the collapsed section");
+ assert.ok(md.indexOf(quoted) > md.indexOf("```mermaid"), "never above the diagram");
+
+ // No checkout, no snippet — and nothing else changes.
+ const bare = markdownReport(report());
+ assert.ok(!bare.includes(quoted));
+ assert.ok(bare.includes("`core/dep.ts:L1-L3` — s0 (calls, depth 1)"), "the symbol is still listed");
+});
diff --git a/test/graph-traverse-cli.test.ts b/test/graph-traverse-cli.test.ts
index 8d012248..c6132c1e 100644
--- a/test/graph-traverse-cli.test.ts
+++ b/test/graph-traverse-cli.test.ts
@@ -195,3 +195,22 @@ test('graft callers: no graph at all is a stderr error, exit 1', () => {
assert.equal(r.status, 1);
assert.match(r.stderr, /graft build/);
});
+
+test('graft callers: quotes the call site, and only where it is the right line', () => {
+ const d = builtRepo();
+ const r = runCli(['callers', 'add', d]);
+ assert.equal(r.status, 0);
+ // `sub` calls `add` on line 5 of the fixture. The edge is a claim; this is the
+ // evidence, and it saves opening the file to check.
+ assert.match(r.stdout, /calls ← sub \(src\/math\.ts:[^)]*\)\n\s+5: return add\(a, -b\);/);
+
+ // A second-hop hit references what is BETWEEN it and the symbol, not the symbol
+ // itself, so quoting it would point at the wrong line.
+ const deep = runCli(['callers', 'add', d, '--depth', '2']);
+ assert.match(deep.stdout, /calls ← compute \(src\/math\.ts:[^)]*\) \[depth 2\]\n/);
+ assert.ok(!/\[depth 2\]\n\s+\d+:/.test(deep.stdout), 'no quote on a second-hop hit');
+
+ // --json is a data contract: the quote is a text-output nicety and must stay out.
+ const json = JSON.parse(runCli(['callers', 'add', d, '--json']).stdout);
+ assert.ok(!JSON.stringify(json).includes('return add(a, -b)'));
+});
diff --git a/test/viz-export.test.ts b/test/viz-export.test.ts
index 2795b6bc..f7f1b9fc 100644
--- a/test/viz-export.test.ts
+++ b/test/viz-export.test.ts
@@ -16,6 +16,7 @@ import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
+import { execFileSync } from "node:child_process";
import { exportViz } from "../src/viz/export.js";
const VIEWER_HTML = `<!doctype html>
@@ -180,3 +181,20 @@ test("viz export: tabs can be trimmed, and the payload goes with them", () => {
assert.match(readFileSync(one.file, "utf8"), /codeGraph: null/);
assert.ok(all.codeNodes > 0 && readFileSync(all.file, "utf8").length > readFileSync(one.file, "utf8").length);
});
+
+test("viz --tabs: a bad tab name fails loudly rather than exporting a page missing a tab", () => {
+ const run = (args: string[]): { status: number; stderr: string } => {
+ try {
+ execFileSync(process.execPath, ["--import", "tsx", "src/cli.ts", ...args], { encoding: "utf8", stdio: "pipe" });
+ return { status: 0, stderr: "" };
+ } catch (err) {
+ const e = err as { status?: number; stderr?: string };
+ return { status: e.status ?? 1, stderr: e.stderr ?? "" };
+ }
+ };
+
+ const bad = run(["viz", ".", "--export", out(), "--tabs", "context,graph"]);
+ assert.equal(bad.status, 1);
+ assert.match(bad.stderr, /--tabs takes a comma-separated subset of context, code, outline — got "graph"/);
+ assert.equal(run(["viz", ".", "--export", out(), "--tabs", ""]).status, 1, "an empty list is a mistake too");
+});