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
fix(blast): rank the hub symbol, and name the areas on the published page (#171)
anirudhkumar-nanonets73f81e5212e1
diff --git a/.github/workflows/blast-cache.yml b/.github/workflows/blast-cache.ymlindex 9df0e31b..be1f7e20 100644--- a/.github/workflows/blast-cache.yml+++ b/.github/workflows/blast-cache.yml@@ -10,8 +10,8 @@ name: Blast cacheon:push:branches: [main]- # graft/ holds LLM-written names keyed by content hash; a manual run is the way to- # refill the cache after the 7-day eviction window on a quiet repo.+ # graft/ holds the LLM-written area names, keyed by content hash; a manual run is+ # the way to refill the cache after the 7-day eviction window on a quiet repo.workflow_dispatch:permissions:@@ -24,6 +24,7 @@ concurrency:jobs:prime:runs-on: ubuntu-latest+ timeout-minutes: 20steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4with:@@ -40,7 +41,7 @@ jobs:- name: Build the CLI from this commitrun: npm ci && npm run build- - name: Build the graph and name every area+ - name: Build the graph, the concept layer, and name every areaenv:GRAFT_API_KEY: ${{ secrets.GRAFT_API_KEY }}GRAFT_BASE_URL: ${{ secrets.GRAFT_BASE_URL }}diff --git a/.github/workflows/blast-pages.yml b/.github/workflows/blast-pages.ymlindex 94f61f5c..72645cc2 100644--- a/.github/workflows/blast-pages.yml+++ b/.github/workflows/blast-pages.yml@@ -53,18 +53,42 @@ jobs:fetch-depth: 0persist-credentials: false+ # Same cache the comment job reads (see blast-cache.yml). Both jobs name the+ # same clusters, so sharing the cache is what keeps the page's bubbles worded+ # exactly like the comment's — two independent LLM calls could word them+ # differently and make the link look like a different analysis.+ - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0+ with:+ path: pr/graft+ key: graft-${{ github.event.pull_request.base.sha }}+ restore-keys: |+ graft-+- 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 }}+ # `--name` reads a key, so the page gets the same concept names the comment+ # shows instead of hub-symbol fallbacks. The PR's code is never executed+ # here (see the header) — naming only sends its source text to the model,+ # and every returned label is sanitised before it reaches the page.+ GRAFT_API_KEY: ${{ secrets.GRAFT_API_KEY }}+ GRAFT_BASE_URL: ${{ secrets.GRAFT_BASE_URL }}+ GRAFT_MODEL: ${{ secrets.GRAFT_MODEL }}run: |set -euo pipefailnode ../base/dist/cli.js build .# `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` is not optional here even though it costs one call: without it+ # every bubble falls back to its hub symbol, so the page reads `cli.ts` and+ # `exportViz` where the comment reads "CLI Entry Point" and "Visualization+ # Export". The point of the page is that a reviewer recognises the feature.+ node ../base/dist/cli.js blast . --base "origin/$BASE_REF" \+ --name --title "PR #$PR_NUMBER" --export-viz ../site --format text > /dev/null- name: Publish to gh-pagesenv:@@ -87,9 +111,14 @@ jobs:fimkdir -p "pr/$PR_NUMBER"cp ../site/index.html "pr/$PR_NUMBER/index.html"+ # Pages runs Jekyll over a branch source unless this file exists, and+ # Jekyll would try to render the export as a template rather than serve+ # it. Written every time, so a rebuilt or force-pushed branch cannot lose+ # it and start silently mangling every viewer.+ touch .nojekyllgit config user.name "github-actions[bot]"git config user.email "41898282+github-actions[bot]@users.noreply.github.com"- git add "pr/$PR_NUMBER"+ git add .nojekyll "pr/$PR_NUMBER"git commit -m "viz: PR #$PR_NUMBER" || { echo "nothing changed"; exit 0; }git push origin gh-pagesdiff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.tsindex c9ec80f8..931972d3 100644--- a/src/blast/blast-cli.ts+++ b/src/blast/blast-cli.ts@@ -4,7 +4,8 @@* Kept out of cli.ts (argument wiring only) so the diff → seeds → walk → render* chain stays unit-testable without shelling out, matching `graph/traverse-cli.ts`.*/-import { resolve } from "node:path";+import { execFileSync } from "node:child_process";+import { basename, resolve } from "node:path";import { contextDirFor } from "../context/node-file.js";import { loadGraphCached } from "../graph/load.js";import type { GraphV1 } from "../graph/types.js";@@ -25,6 +26,10 @@ export interface BlastCliOptions {name?: boolean;/** Write the interactive page for this radius here (one self-contained file). */exportViz?: string;+ /** Subtitle beside the repo name on the exported page, e.g. "PR #171". Same+ * meaning as `graft viz --title`. Without it a reader of a published page has no+ * way to tell which pull request they are looking at. */+ title?: string;/** The top-level `--dir` override. */globalDir?: string;}@@ -82,7 +87,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 (opts.exportViz) await exportRadius(report, contextDir, root, opts.exportViz, opts.title);if (format === "json") {console.log(JSON.stringify(report, null, 2));@@ -134,6 +139,28 @@ async function nameClusters(graph: GraphV1, report: BlastReport, contextDir: str}}+/**+ * What to call the repository in the appbar.+ *+ * `basename(root)` is right for someone running this in their own clone, but CI+ * checks a pull request out into a directory named for the job — ours is literally+ * `pr` — which titled the published page "pr". The origin remote is the repository,+ * so it wins when there is one; a detached tarball checkout still falls back.+ */+export function repoLabel(root: string): string {+ try {+ const url = execFileSync("git", ["-C", root, "remote", "get-url", "origin"], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ }).trim();+ const name = url.replace(/\.git$/, "").split(/[/:]/).pop();+ if (name) return name;+ } catch {+ // No remote, or no git at all: the directory name is the best guess left.+ }+ return basename(root);+}+/*** Write the interactive page for this radius: the same viewer `graft viz` serves,* with the blast graph as its Context tab.@@ -142,8 +169,14 @@ async function nameClusters(graph: GraphV1, report: BlastReport, contextDir: str* 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");+async function exportRadius(+ report: BlastReport,+ contextDir: string,+ root: string,+ outDir: string,+ subtitle?: string,+): Promise<void> {+ const { 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");@@ -152,7 +185,8 @@ async function exportRadius(report: BlastReport, contextDir: string, root: strincontextDir,viewerDir: fileURLToPath(new URL("../viewer/", import.meta.url)), // prebuilt, ships in distoutDir: resolvePath(outDir),- repoName: basename(root),+ repoName: repoLabel(root),+ subtitle,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/blast.ts b/src/blast/blast.tsindex 8d591ca5..d625fc81 100644--- a/src/blast/blast.ts+++ b/src/blast/blast.ts@@ -277,6 +277,9 @@ function changedAreas(): ChangedArea[] {const changedTests = new Set(changed.filter((c) => TEST_PATH.test(c.path)).map((c) => c.path));const nodeById = new Map(graph.nodes.map((n) => [n.id, n]));+ /** How many edges point AT each node — how central it is in the graph. */+ const inDegree = new Map<string, number>();+ for (const e of graph.edges) inDegree.set(e.target, (inDegree.get(e.target) ?? 0) + 1);/** Incoming edge sources per node id, resolved to the source's file path. */const incoming = new Map<string, Set<string>>();for (const e of graph.edges) {@@ -304,6 +307,8 @@ function changedAreas(coarsen(groups, MAX_AREAS);const byKey = new Map<string, ChangedArea>();+ /** Hub candidates per area, ranked once every seed has been seen. */+ const candidates = new Map<ChangedArea, { name: string; behavioural: boolean; degree: number }[]>();for (const [dir, paths] of groups) {const area: ChangedArea = {label: dir, labelSource: "symbol", key: dir,@@ -326,13 +331,11 @@ function changedAreas(if (!area.testFiles.includes(t)) area.testFiles.push(t);if (changedTests.has(t) && !area.changedTestFiles.includes(t)) area.changedTestFiles.push(t);}- if (!behavioural) {- // Types last: a label naming an interface says less than one naming the- // function that changed beside it.- area.seedNames.push(node.name);- continue;- }- area.seedNames.unshift(node.name);+ candidates.set(area, [+ ...(candidates.get(area) ?? []),+ { name: node.name, behavioural, degree: inDegree.get(node.id) ?? 0 },+ ]);+ if (!behavioural) continue;area.behavioural++;if (from.size > 0) area.reached++;else area.unreached.push(node.name);@@ -341,6 +344,13 @@ function changedAreas(}for (const area of byKey.values()) {+ // The hub is the most-depended-on function in the area, not whichever symbol the+ // file walk happened to end on: `LlmFailureGate` rather than `transportRetries`.+ // Behaviour outranks types, since nothing calls an interface.+ area.seedNames = (candidates.get(area) ?? [])+ .sort((a, b) =>+ Number(b.behavioural) - Number(a.behavioural) || b.degree - a.degree || a.name.localeCompare(b.name))+ .map((c) => c.name);const concept = sharedConcept(area.files, index);area.label = concept ?? hubLabel(area.seedNames, area.key);area.labelSource = concept ? "concept" : "symbol";diff --git a/src/cli.ts b/src/cli.tsindex 4b2cb2d6..e0b2d785 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -585,8 +585,9 @@ program.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("--title <text>", "subtitle beside the repo name on the exported page (e.g. \"PR #171\")").option(...NO_REFRESH_FLAG)- .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; refresh?: boolean }) => {+ .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; title?: string; refresh?: boolean }) => {const dir = queryRoot(dirArg);await refreshBefore(dir, opts);const { runBlastCommand } = await import("./blast/blast-cli.js");@@ -596,6 +597,7 @@ programformat: opts.format,name: opts.name,exportViz: opts.exportViz,+ title: opts.title,globalDir: program.opts<GlobalOpts>().dir,});});diff --git a/src/viz/export.ts b/src/viz/export.tsindex c31aa09d..f5138917 100644--- a/src/viz/export.ts+++ b/src/viz/export.ts@@ -73,8 +73,19 @@ function inlineJson(value: unknown): string {.replace(/\u2029/g, "\\u2029");}+/** The two tags this exporter rewrites, verbatim from viewer/index.html. */+const LINK_TAG = '<link rel="stylesheet" href="/style.css">';+const SCRIPT_TAG = '<script type="module" src="/app.js"></script>';+export function exportViz(opts: VizExportOptions): VizExportResult {const html = readFileSync(join(opts.viewerDir, "index.html"), "utf8");++ // Checked on the SOURCE, before anything is inlined. Checking the assembled page+ // instead looks equivalent and is not: a stylesheet comment or a bundled string+ // containing one of these tags would fail an export that was in fact correct.+ if (!html.includes(LINK_TAG) || !html.includes(SCRIPT_TAG)) {+ throw new Error("viz export: viewer/index.html no longer matches the asset tags this exporter rewrites");+ }const css = readFileSync(join(opts.viewerDir, "style.css"), "utf8");const js = readFileSync(join(opts.viewerDir, "app.js"), "utf8");@@ -106,14 +117,8 @@ export function exportViz(opts: VizExportOptions): VizExportResult {// full of them — the first version of this put the original `<script src>` tag// back into the page via a stray `$&` in app.js. A function is taken verbatim.const page = html- .replace('<link rel="stylesheet" href="/style.css">', () => `<style>\n${css}\n</style>`)- .replace('<script type="module" src="/app.js"></script>', () => `${data}\n<script type="module">\n${js}\n</script>`);-- // A replacement that silently did nothing would ship a page fetching /app.js from- // the domain root, which 404s on Pages and shows an empty viewer.- if (page.includes('href="/style.css"') || page.includes('src="/app.js"')) {- throw new Error("viz export: viewer/index.html no longer matches the asset tags this exporter rewrites");- }+ .replace(LINK_TAG, () => `<style>\n${css}\n</style>`)+ .replace(SCRIPT_TAG, () => `${data}\n<script type="module">\n${js}\n</script>`);mkdirSync(opts.outDir, { recursive: true });const file = join(opts.outDir, "index.html");diff --git a/test/blast-viz.test.ts b/test/blast-viz.test.tsindex 6b39340d..9abfe5c3 100644--- a/test/blast-viz.test.ts+++ b/test/blast-viz.test.ts@@ -8,7 +8,12 @@*/import { test } from "node:test";import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { basename, join } from "node:path";+import { tmpdir } from "node:os";+import { execFileSync } from "node:child_process";import { blastVizGraph } from "../src/blast/viz.js";+import { repoLabel } from "../src/blast/blast-cli.js";import type { BlastReport, ChangedArea, ImpactedModule } from "../src/blast/blast.js";function mod(label: string, from: string[], symbols: number): ImpactedModule {@@ -91,3 +96,17 @@ test("blast viz: nothing is capped, unlike the comment's diagram", () => {assert.equal(g.nodes.length, 13, "a pannable canvas has no reason to drop areas");assert.equal(g.edges.length, 12);});++test("blast viz: the page is titled after the repository, not the checkout directory", () => {+ // CI checks a pull request out into a directory named for the job — ours is `pr` —+ // so a published page announced itself as "pr". The remote is the repository.+ const dir = mkdtempSync(join(tmpdir(), "pr"));+ assert.equal(repoLabel(dir), basename(dir), "no remote: the directory name is all there is");++ execFileSync("git", ["-C", dir, "init", "-q"]);+ execFileSync("git", ["-C", dir, "remote", "add", "origin", "[email protected]:NanoNets/Graft.git"]);+ assert.equal(repoLabel(dir), "Graft", "an ssh remote names the repo, not the owner or the path");++ execFileSync("git", ["-C", dir, "remote", "set-url", "origin", "https://github.com/NanoNets/Graft"]);+ assert.equal(repoLabel(dir), "Graft", "and an https remote with no .git suffix reads the same");+});diff --git a/test/blast.test.ts b/test/blast.test.tsindex 7c8a70e0..f28f6f9f 100644--- a/test/blast.test.ts+++ b/test/blast.test.ts@@ -202,6 +202,23 @@ test("blast: an unknown --base names the CI cause (checkout depth), not a git inassert.match(r.stderr, /fetch-depth: 0/);});+test("blast: an area is named after its most-depended-on function, not the last one seen", () => {+ const d = builtRepo();+ // `add` is called by total (and transitively by report); `unused` is called by+ // nothing. Editing both must label the area `add`, whichever order the walk sees+ // them in — before this, the label was whatever symbol the file ended on.+ writeFileSync(+ join(d, "src", "math.ts"),+ "export function add(a: number, b: number): number {\n return a + b + 0;\n}\n" ++ "export function unused(): number {\n return 41 + 1;\n}\n",+ );++ const report = blastJson([d]);+ assert.equal(report.areas.length, 1);+ assert.equal(report.areas[0].seedNames[0], "add", `ranked hub, got ${report.areas[0].seedNames.join(", ")}`);+ assert.equal(report.areas[0].label, "add");+});+test("blast: a clean tree reports the last commit rather than nothing at all", () => {const d = builtRepo();writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);diff --git a/test/viz-export.test.ts b/test/viz-export.test.tsindex f8ad14b0..6e3b4a90 100644--- a/test/viz-export.test.ts+++ b/test/viz-export.test.ts@@ -154,3 +154,15 @@ test("viz export: refuses to write a page whose asset tags it did not rewrite","a silently un-inlined page 404s wherever it is published — fail loudly instead",);});++test("viz export: asset-path text inside the assets does not fail a correct export", () => {+ // The guard used to inspect the assembled page, so a stylesheet comment or a+ // bundled string mentioning one of the tags failed an export that was fine.+ const dir = viewerDir('const doc = \'<script type="module" src="/app.js"></script>\';');+ writeFileSync(join(dir, "style.css"), '/* replaces <link rel="stylesheet" href="/style.css"> */ x{}');++ const res = exportViz({ contextDir: contextDir(), viewerDir: dir, outDir: out(), repoName: "demo" });+ const page = readFileSync(res.file, "utf8");+ assert.match(page, /replaces <link rel="stylesheet" href="\/style\.css">/, "the comment survives inlining");+ assert.match(page, /window\.__GRAFT_DATA__/, "and the export still happened");+});