Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(blast): --export-viz publishes the radius as the viewer's Context tab (#173)
anirudhkumar-nanonets5d08e4ca525d
diff --git a/.github/actions/graft-blast/action.yml b/.github/actions/graft-blast/action.ymlindex 6f8f374a..08ea019b 100644--- a/.github/actions/graft-blast/action.yml+++ b/.github/actions/graft-blast/action.yml@@ -39,8 +39,9 @@ inputs:default: ""export-viewer:description: >-- Write the standalone viewer to this directory (`graft viz --export`). Empty- skips the export. Publishing it is the caller's job — see blast-pages.yml.+ Write the standalone viewer for this PR's radius to this directory+ (`graft blast --export-viz`). Empty skips the export. Publishing it is the+ caller's job — see blast-pages.yml.required: falsedefault: ""token:@@ -112,17 +113,6 @@ runs:# the comment actually shows instead of summarising the whole repo.$GRAFT build .- - name: Export the interactive viewer- if: inputs.export-viewer != ''- shell: bash- env:- OUT: ${{ inputs.export-viewer }}- TITLE: PR #${{ github.event.pull_request.number }}- GRAFT: ${{ inputs.graft-cmd }}- run: |- set -euo pipefail- $GRAFT viz . --export "$OUT" --title "$TITLE"-- name: Compute the blast radiusid: blastshell: bash@@ -131,14 +121,19 @@ runs:DEPTH: ${{ inputs.depth }}NAME_AREAS: ${{ inputs.name-areas }}VIEWER_URL: ${{ inputs.viewer-url }}+ EXPORT_VIZ: ${{ inputs.export-viewer }}GRAFT: ${{ inputs.graft-cmd }}run: |set -euo pipefailname=""if [ "$NAME_AREAS" = "true" ]; then name="--name"; fi+ # One command for both outputs: the page and the comment then describe the+ # same radius, named once. A second `viz --export` step could drift from it.+ viz=""+ if [ -n "$EXPORT_VIZ" ]; then viz="--export-viz $EXPORT_VIZ"; fi# --name never fails the step: with no key, a spent quota or a refused call# it prints one line on stderr and every area keeps its hub-symbol name.- $GRAFT blast . --base "$BASE" --depth "$DEPTH" $name --format markdown > blast.md+ $GRAFT blast . --base "$BASE" --depth "$DEPTH" $name $viz --format markdown > blast.mdif [ -n "$VIEWER_URL" ]; thenprintf '\n[**Open the interactive graph →**](%s) — click an area to see its dependent symbols at file:line.\n' "$VIEWER_URL" >> blast.mdfidiff --git a/.github/workflows/blast-pages.yml b/.github/workflows/blast-pages.ymlindex e6ae0e82..94f61f5c 100644--- a/.github/workflows/blast-pages.yml+++ b/.github/workflows/blast-pages.yml@@ -53,14 +53,18 @@ jobs:fetch-depth: 0persist-credentials: false- - name: Build the graph and export the viewer+ - name: Build the graph and export the radiusworking-directory: prenv:PR_NUMBER: ${{ github.event.pull_request.number }}+ BASE_REF: ${{ github.event.pull_request.base.ref }}run: |set -euo pipefailnode ../base/dist/cli.js build .- node ../base/dist/cli.js viz . --export ../site --title "PR #$PR_NUMBER"+ # `blast --export-viz`, not `viz --export`: the page a reviewer opens from+ # the comment should be THIS PR's radius — the areas it changed and the+ # areas that depend on them — not the whole repository map.+ node ../base/dist/cli.js blast . --base "origin/$BASE_REF" --export-viz ../site --format text > /dev/null- name: Publish to gh-pagesenv:diff --git a/README.md b/README.mdindex 3cf6360e..9b985c5b 100644--- a/README.md+++ b/README.md@@ -355,6 +355,7 @@ graft blast [dir] # blast radius of a diff: what depends on tgraft blast --base origin/main # diff against the merge base with HEAD — what a PR job runsgraft blast --format markdown # a PR comment: the areas a change can reach, per-symbol detail collapsed under itgraft blast --base origin/main --name # name those areas with one cached LLM call, instead of a full --deep build+graft blast --export-viz site/ # also write the interactive page for this radius (what a PR comment links to)graft blast --depth all --format json # the full transitive closure, machine-readablegraft check [dir] # fail (exit 1) if graft/ has drifted from the code (never auto-refreshes — it's the drift report)diff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.tsindex 98386a5c..c9ec80f8 100644--- a/src/blast/blast-cli.ts+++ b/src/blast/blast-cli.ts@@ -23,6 +23,8 @@ export interface BlastCliOptions {/** Ask a model to name the clusters that have no concept name (one call, cached).* Opt-in: a local `graft blast` must not need a key or a network round-trip. */name?: boolean;+ /** Write the interactive page for this radius here (one self-contained file). */+ exportViz?: string;/** The top-level `--dir` override. */globalDir?: string;}@@ -80,6 +82,7 @@ export async function runBlastCommand(dir: string, opts: BlastCliOptions): Promiconst report = blastRadiusIn(graph, contextDir, diff.files, diff.basis, depth);if (opts.name) await nameClusters(graph, report, contextDir);+ if (opts.exportViz) await exportRadius(report, contextDir, root, opts.exportViz);if (format === "json") {console.log(JSON.stringify(report, null, 2));@@ -130,3 +133,27 @@ async function nameClusters(graph: GraphV1, report: BlastReport, contextDir: strconsole.error(`• --name: ${bits.join(", ")}`);}}++/**+ * Write the interactive page for this radius: the same viewer `graft viz` serves,+ * with the blast graph as its Context tab.+ *+ * Done here rather than in `viz` because the radius is what a reviewer opened the+ * link for, and only `blast` has it — `viz --export` on its own can offer the deep+ * tier's concept map, which a PR build no longer produces.+ */+async function exportRadius(report: BlastReport, contextDir: string, root: string, outDir: string): Promise<void> {+ const { basename, resolve: resolvePath } = await import("node:path");+ const { fileURLToPath } = await import("node:url");+ const { exportViz } = await import("../viz/export.js");+ const { blastVizGraph } = await import("./viz.js");++ const out = exportViz({+ contextDir,+ viewerDir: fileURLToPath(new URL("../viewer/", import.meta.url)), // prebuilt, ships in dist+ outDir: resolvePath(outDir),+ repoName: basename(root),+ contextGraph: blastVizGraph(report),+ });+ console.error(`• --export-viz: ${out.file} (${Math.round(out.bytes / 1024)} kB, ${out.contextNodes} areas, ${out.codeNodes} code nodes)`);+}diff --git a/src/blast/viz.ts b/src/blast/viz.tsnew file mode 100644index 00000000..867e4039--- /dev/null+++ b/src/blast/viz.ts@@ -0,0 +1,106 @@+/**+ * The blast radius as a graph the viewer can draw — the hosted half of the PR+ * comment.+ *+ * The comment can hold about five circles before it stops being readable, and it+ * can never answer the reviewer's next question: which symbols, at which lines.+ * `graft viz --export` already produces a self-contained page, but its Context tab+ * is assembled from the deep tier's concept files, which the PR path deliberately+ * no longer builds — so on a structural build that tab held a single INDEX dot.+ *+ * This closes that gap with no new data and no LLM pass: `blast` has already+ * clustered both sides of the diff and named them (cached, one call), so the same+ * report is emitted here as {@link VizGraph} — amber node per changed area, blue+ * node per affected area, one edge per attribution the walk actually recorded. The+ * comment becomes a summary of this page rather than a separate computation.+ */+import type { VizEdge, VizGraph, VizNode } from "../viz/assemble.js";+import type { BlastReport, ChangedArea, ImpactedModule, TestSignal } from "./blast.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";++const TEST_NOTE: Record<TestSignal, string> = {+ changed: "a test that reaches it changed too",+ stale: "it has tests, and this diff did not touch them",+ none: "no test reaches it",+ na: "no function, method or class changed here",+};++function changedNode(a: ChangedArea): VizNode {+ const reach = a.behavioural > 0 ? ` ${a.reached} of ${a.behavioural} changed functions have a test that reaches them.` : "";+ return {+ id: `changed:${a.key}`,+ name: a.label,+ type: CHANGED,+ summary: `Changed in this PR: ${plural(a.files.length, "file")}, ${plural(a.seeds, "symbol")}. ${TEST_NOTE[a.tests]}.${reach}`,+ sources: a.files,+ };+}++function affectedNode(m: ImpactedModule): VizNode {+ const nearest = m.symbols[0];+ const how = nearest ? ` Nearest hop: ${nearest.name} at depth ${nearest.depth} (${nearest.relation}).` : "";+ return {+ id: `affected:${m.key}`,+ name: m.label,+ type: AFFECTED,+ summary: `Can be affected by this PR: ${plural(m.symbols.length, "dependent symbol")} in ${plural(m.files.length, "file")}.${how}`,+ // `path · span` is the shape the viewer's detail panel already renders, so each+ // line is the exact place to start reading.+ sources: m.symbols.map((s) => `${s.path} · ${s.span}`),+ };+}++/**+ * Build the viewer graph for a report.+ *+ * Nothing is capped here. The caps in the markdown renderer exist because a Mermaid+ * diagram inside a comment cannot lay out more than a handful of circles; this page+ * is force-directed and pannable, which is the entire reason it exists.+ */+export function blastVizGraph(r: BlastReport): VizGraph {+ const nodes: VizNode[] = [...r.areas.map(changedNode), ...r.modules.map(affectedNode)];+ /** Changed path → the id of the area node standing for it. */+ const areaOf = new Map<string, string>();+ for (const a of r.areas) for (const f of a.files) areaOf.set(f, `changed:${a.key}`);++ const edges: VizEdge[] = [];+ const seen = new Set<string>();+ for (const m of r.modules) {+ for (const from of m.from) {+ const source = areaOf.get(from);+ if (!source) continue; // a changed test file: the signal, not an area+ const affected = `affected:${m.key}`;+ const key = `${affected}→${source}`;+ if (seen.has(key)) continue;+ seen.add(key);+ // Edge direction is the DEPENDENCY, affected → changed, not the impact. The+ // viewer words its panels "depends on" / "depended on by" from the edge, so+ // pointing it the other way made an affected area read as the thing being+ // depended upon — backwards, on the one screen a reviewer is reading closely.+ edges.push({+ source: affected,+ target: source,+ relation: "depends_on",+ description: "this area calls or imports code the PR changed",+ });+ }+ }++ return {+ meta: {+ nodeCount: nodes.length,+ edgeCount: edges.length,+ // Changed files no parser claims: named here so a thin graph is explained+ // rather than read as "this PR is safe".+ skippedFiles: r.unindexed.length,+ droppedEdges: 0,+ },+ nodes,+ edges,+ };+}diff --git a/src/cli.ts b/src/cli.tsindex 6918ce53..4b2cb2d6 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -584,8 +584,9 @@ program.option("-d, --depth <n>", 'hops to walk over incoming edges, or "all" for the full closure (default 2)').option("--format <fmt>", "text (default) | markdown | mermaid | json").option("--name", "name the affected areas with one cached LLM call (needs GRAFT_API_KEY); without it, areas are named after their hub symbol")+ .option("--export-viz <dir>", "also write the interactive page for this radius (one self-contained index.html — for CI, GitHub Pages, or an artifact)").option(...NO_REFRESH_FLAG)- .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; refresh?: boolean }) => {+ .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; refresh?: boolean }) => {const dir = queryRoot(dirArg);await refreshBefore(dir, opts);const { runBlastCommand } = await import("./blast/blast-cli.js");@@ -594,6 +595,7 @@ programdepth: opts.depth,format: opts.format,name: opts.name,+ exportViz: opts.exportViz,globalDir: program.opts<GlobalOpts>().dir,});});diff --git a/src/viz/export.ts b/src/viz/export.tsindex 4e2fcb42..c31aa09d 100644--- a/src/viz/export.ts+++ b/src/viz/export.ts@@ -16,7 +16,7 @@*/import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";-import { assembleContextGraph } from "./assemble.js";+import { assembleContextGraph, type VizGraph } from "./assemble.js";export interface VizExportOptions {contextDir: string;@@ -27,6 +27,12 @@ export interface VizExportOptions {repoName: string;/** Shown in the appbar beside the repo name — e.g. "PR #151". */subtitle?: string;+ /**+ * Context graph to inline instead of assembling one from the deep tier's concept+ * files. `graft blast --export-viz` passes the blast radius itself, which is how a+ * PR gets a Context tab worth opening without a `--deep` build.+ */+ contextGraph?: VizGraph;}export interface VizExportResult {@@ -72,7 +78,7 @@ export function exportViz(opts: VizExportOptions): VizExportResult {const css = readFileSync(join(opts.viewerDir, "style.css"), "utf8");const js = readFileSync(join(opts.viewerDir, "app.js"), "utf8");- const context = assembleContextGraph(opts.contextDir);+ const context = opts.contextGraph ?? assembleContextGraph(opts.contextDir);const code = codeGraph(opts.contextDir);// Which tab to open on. The viewer starts on Context, which only a `--deep` build@@ -81,7 +87,8 @@ export function exportViz(opts: VizExportOptions): VizExportResult {// PR path is now structural by design, opening on Context would show a canvas// with one dot while the whole wiring graph sat behind an unadvertised tab.const codeNodes = (code as { nodes?: unknown[] } | null)?.nodes?.length ?? 0;- const defaultTab = context.nodes.length > 1 || codeNodes === 0 ? "context" : "code";+ // A supplied graph is the caller's whole point, so it is always the landing tab.+ const defaultTab = opts.contextGraph || context.nodes.length > 1 || codeNodes === 0 ? "context" : "code";const contextGraph = {...context,meta: { ...context.meta, repoName: opts.repoName, subtitle: opts.subtitle, defaultTab },diff --git a/test/blast-viz.test.ts b/test/blast-viz.test.tsnew file mode 100644index 00000000..6b39340d--- /dev/null+++ b/test/blast-viz.test.ts@@ -0,0 +1,93 @@+/**+ * The blast radius as a viewer graph.+ *+ * This is the Context tab of the page a PR comment links to, so the two things that+ * matter are that it carries the SAME names the comment shows — one computation, not+ * two — and that its edges point the way the viewer words them: the affected area+ * depends on the changed one, never the reverse.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { blastVizGraph } from "../src/blast/viz.js";+import type { BlastReport, ChangedArea, ImpactedModule } from "../src/blast/blast.js";++function mod(label: string, from: string[], symbols: number): ImpactedModule {+ return {+ label, labelSource: "named", key: label,+ files: [`${label}dep.ts`],+ from,+ symbols: Array.from({ length: symbols }, (_, i) => ({+ id: `${label}dep.ts#s${i}`, name: `s${i}`, kind: "function",+ path: `${label}dep.ts`, span: `L${i + 1}-L${i + 3}`, relation: "calls", depth: i + 1,+ })),+ };+}++function area(label: string, files: string[]): ChangedArea {+ return {+ label, labelSource: "named", key: label, files, seeds: files.length,+ tests: "none", testFiles: [], changedTestFiles: [],+ reached: 0, behavioural: 2, unreached: ["doThing", "doOther"], seedNames: ["doThing"],+ };+}++function report(): BlastReport {+ return {+ basis: "origin/main...HEAD", depth: 2,+ changed: [{ path: "src/a.ts", status: "modified", ranges: [{ start: 1, end: 1 }] }],+ unindexed: [".github/workflows/x.yml"],+ deleted: [], seeds: [], impacted: [],+ modules: [mod("Query Freshness Gate", ["src/a.ts", "test/a.test.ts"], 2), mod("MCP Tool Surface", ["src/a.ts"], 1)],+ testModules: [mod("Test Suites", ["src/a.ts"], 9)],+ areas: [area("LLM Failure Gate", ["src/a.ts"])],+ };+}++test("blast viz: one node per area, typed so the viewer colours and legends itself", () => {+ const g = blastVizGraph(report());++ assert.deepEqual(+ g.nodes.map((n) => `${n.type}:${n.name}`),+ ["changed:LLM Failure Gate", "affected:Query Freshness Gate", "affected:MCP Tool Surface"],+ "the names are the comment's names — the page is not a second computation",+ );+ // Test-only dependents stay out here too: 9 symbols of "your tests call this"+ // would be the biggest node on the canvas.+ assert.ok(!g.nodes.some((n) => n.name === "Test Suites"), "test-only clusters are not drawn");+ assert.equal(g.meta.nodeCount, 3);+ assert.equal(g.meta.skippedFiles, 1, "changed files no parser claims are carried, not hidden");+});++test("blast viz: edges are the dependency, so the viewer's wording comes out right", () => {+ const g = blastVizGraph(report());++ assert.deepEqual(g.edges.map((e) => `${e.source} -${e.relation}-> ${e.target}`), [+ "affected:Query Freshness Gate -depends_on-> changed:LLM Failure Gate",+ "affected:MCP Tool Surface -depends_on-> changed:LLM Failure Gate",+ ]);+ // `test/a.test.ts` reached the first module but belongs to no area, so it must not+ // produce a dangling edge the viewer would silently drop.+ assert.equal(g.edges.length, 2);+});++test("blast viz: a node carries where to look and whether its tests moved", () => {+ const g = blastVizGraph(report());+ const [changed, affected] = g.nodes;++ assert.match(changed.summary, /Changed in this PR: 1 file, 1 symbol\. no test reaches it\. 0 of 2 changed functions/);+ assert.deepEqual(changed.sources, ["src/a.ts"]);++ assert.match(affected.summary, /2 dependent symbols in 1 file\. Nearest hop: s0 at depth 1 \(calls\)\./);+ // `path · span` is what the detail panel renders as a jump target.+ assert.deepEqual(affected.sources, ["Query Freshness Gatedep.ts · L1-L3", "Query Freshness Gatedep.ts · L2-L4"]);+});++test("blast viz: nothing is capped, unlike the comment's diagram", () => {+ const r = report();+ r.modules = Array.from({ length: 12 }, (_, i) => mod(`Area ${i}`, ["src/a.ts"], 1));++ const g = blastVizGraph(r);++ assert.equal(g.nodes.length, 13, "a pannable canvas has no reason to drop areas");+ assert.equal(g.edges.length, 12);+});diff --git a/viewer/data.ts b/viewer/data.tsindex 44486337..5ecd4bc5 100644--- a/viewer/data.ts+++ b/viewer/data.ts@@ -68,7 +68,13 @@ export const CHIP_HINT: Record<string, string> = {};/** Node-type → CSS custom property, per tab. */-const CONTEXT_COLORS: Record<string, string> = { system: "--sys", concept: "--con", file: "--fil", api: "--api" };+// `changed` / `affected` come from `graft blast --export-viz`, where the graph is a+// PR's blast radius rather than the concept map: amber for what the diff touched,+// blue for what depends on it. The legend labels itself from these type names.+const CONTEXT_COLORS: Record<string, string> = {+ system: "--sys", concept: "--con", file: "--fil", api: "--api",+ changed: "--fil", affected: "--sys",+};const CODE_COLORS: Record<string, string> = {file: "--k-file", class: "--k-class", function: "--k-fn", method: "--k-method",interface: "--k-iface", type: "--k-type", enum: "--k-enum",