Skip to content

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

feat(blast): blast radius of a diff, posted on every PR (#151)

anirudhkumar-nanonets42c499114c21
diff --git a/.github/actions/graft-blast/action.yml b/.github/actions/graft-blast/action.yml
new file mode 100644
index 00000000..6f8f374a
--- /dev/null
+++ b/.github/actions/graft-blast/action.yml
@@ -0,0 +1,175 @@
+name: graft blast radius
+description: >-
+ Index the repository with graft, work out what the pull request's diff can
+ affect, and post it on the PR as one sticky comment with a Mermaid diagram.
+ Requires a checkout with `fetch-depth: 0` — the diff is taken against the merge
+ base, which a shallow clone does not contain.
+
+inputs:
+ base:
+ description: >-
+ Ref to diff against. Defaults to the PR's base ref; the diff is taken from its
+ merge base with HEAD, so commits others merged into the base are not attributed
+ to this PR.
+ required: false
+ default: ""
+ depth:
+ description: 'Hops to walk over incoming edges, or "all" for the full closure.'
+ required: false
+ default: "2"
+ name-areas:
+ description: >-
+ Name the affected areas with one cached LLM call (`graft blast --name`). Needs
+ GRAFT_API_KEY; without one every area is named after its hub symbol, which is
+ still a name a reviewer can grep. This replaces `build --deep` on the PR path:
+ summarising every file in the repo to label six clusters cost ~356 calls and
+ thirteen minutes per run.
+ required: false
+ default: "true"
+ comment:
+ description: Post/update the PR comment. Set false to only produce the outputs.
+ required: false
+ default: "true"
+ viewer-url:
+ description: >-
+ Public URL of the exported viewer for this PR, linked from the comment. Leave
+ empty to omit the link. The comment holds five circles and a table; the graph
+ a reviewer can actually click through lives here.
+ required: false
+ 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.
+ required: false
+ default: ""
+ token:
+ description: "Token used to post the comment. Needs `pull-requests: write` permission."
+ required: false
+ default: ${{ github.token }}
+ graft-cmd:
+ description: >-
+ How to invoke graft. The default installs the published CLI, which is what any
+ repo consuming this action wants. graft's OWN workflow overrides it with a
+ locally built binary (see setup-cmd) so a PR's comment is produced by the code
+ in that PR — otherwise this action would review new work with the last release,
+ which cannot run a command the release does not have yet.
+ required: false
+ default: npx --yes @nanonets/graft@latest
+ setup-cmd:
+ description: >-
+ Command run before graft, for the locally-built case (e.g. `npm ci && npm run
+ build`). Empty by default.
+ required: false
+ default: ""
+
+outputs:
+ markdown:
+ description: The comment body (also written to $GITHUB_STEP_SUMMARY).
+ value: ${{ steps.blast.outputs.markdown }}
+
+runs:
+ using: composite
+ steps:
+ # No checkout here on purpose: checkout policy belongs to the calling workflow
+ # (ref, submodules, credentials), and doing it twice would silently discard
+ # whatever the caller had set up. A missing merge base is reported by `graft
+ # blast` itself, naming `fetch-depth: 0` as the fix.
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: "20"
+
+ - name: Prepare the CLI
+ if: inputs.setup-cmd != ''
+ shell: bash
+ env:
+ SETUP_CMD: ${{ inputs.setup-cmd }}
+ run: bash -c "$SETUP_CMD"
+
+ # graft/ is git-ignored (it is a local cache), so the only place a name can
+ # survive between runs is GitHub's cache. Restore-only here: a cache saved by a
+ # PR job is scoped to that PR's branch and no other PR could read it, so the
+ # useful entry is always the one a push-to-main job saved (see blast-cache.yml).
+ - uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ with:
+ path: graft
+ key: graft-${{ github.event.pull_request.base.sha }}
+ restore-keys: |
+ graft-
+
+ - name: Build the graph
+ id: build
+ shell: bash
+ # Every workflow value reaches the script through env, never through `${{ }}`
+ # inside the shell text: a branch name is attacker-controllable on a fork PR,
+ # and inline interpolation is how that becomes command injection.
+ env:
+ GRAFT: ${{ inputs.graft-cmd }}
+ run: |
+ set -uo pipefail
+ # Structural only: ~4s, no API key, and it is all `blast` reads. The LLM tier
+ # is no longer on this path — `blast --name` below pays for the six labels
+ # 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 radius
+ id: blast
+ shell: bash
+ env:
+ BASE: ${{ inputs.base != '' && inputs.base || format('origin/{0}', github.event.pull_request.base.ref) }}
+ DEPTH: ${{ inputs.depth }}
+ NAME_AREAS: ${{ inputs.name-areas }}
+ VIEWER_URL: ${{ inputs.viewer-url }}
+ GRAFT: ${{ inputs.graft-cmd }}
+ run: |
+ set -euo pipefail
+ name=""
+ if [ "$NAME_AREAS" = "true" ]; then name="--name"; 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
+ if [ -n "$VIEWER_URL" ]; then
+ printf '\n[**Open the interactive graph →**](%s) — click an area to see its dependent symbols at file:line.\n' "$VIEWER_URL" >> blast.md
+ fi
+ cat blast.md >> "$GITHUB_STEP_SUMMARY"
+ {
+ echo "markdown<<GRAFT_EOF"
+ cat blast.md
+ echo "GRAFT_EOF"
+ } >> "$GITHUB_OUTPUT"
+
+ - name: Post or update the comment
+ if: inputs.comment == 'true' && github.event.pull_request.number != ''
+ shell: bash
+ env:
+ GH_TOKEN: ${{ inputs.token }}
+ PR: ${{ github.event.pull_request.number }}
+ REPO: ${{ github.repository }}
+ run: |
+ set -euo pipefail
+ # One comment per PR, edited in place: a new comment on every push turns a
+ # busy PR into a wall of stale diagrams. The marker is how the comment is
+ # found again, and it stays invisible in the rendered body.
+ marker='<!-- graft-blast-radius -->'
+ printf '%s\n' "$marker" > body.md
+ cat blast.md >> body.md
+ # `--paginate` runs the filter per page, so a match could print more than one
+ # line across pages; the first is the comment we own.
+ existing=$(gh api "repos/$REPO/issues/$PR/comments" --paginate \
+ --jq "map(select(.body | startswith(\"$marker\"))) | .[0].id // empty" | head -1)
+ if [ -n "$existing" ]; then
+ gh api -X PATCH "repos/$REPO/issues/comments/$existing" -F [email protected] >/dev/null
+ else
+ gh api -X POST "repos/$REPO/issues/$PR/comments" -F [email protected] >/dev/null
+ fi
diff --git a/.github/workflows/blast-cache.yml b/.github/workflows/blast-cache.yml
new file mode 100644
index 00000000..9df0e31b
--- /dev/null
+++ b/.github/workflows/blast-cache.yml
@@ -0,0 +1,62 @@
+name: Blast cache
+
+# Primes the graph + area-name cache that PR runs read.
+#
+# This job exists because of how GitHub scopes caches: one saved by a pull-request
+# job belongs to that PR's branch and no other PR can read it, while one saved on
+# the default branch is readable by every branch and PR in the repo. So PR-to-PR
+# reuse of area names can only come from here — a PR restores main's cache, pays for
+# the clusters its own diff changed, and nothing else.
+on:
+ 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.
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: blast-cache
+ cancel-in-progress: true
+
+jobs:
+ prime:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ # Enough history for a wide diff below: naming only ever sees the clusters
+ # a walk produces, so a one-commit window would fill the cache one area at
+ # a time and most PRs would still miss.
+ fetch-depth: 60
+ persist-credentials: false
+
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: "20"
+
+ - name: Build the CLI from this commit
+ run: npm ci && npm run build
+
+ - name: Build the graph and name every area
+ env:
+ GRAFT_API_KEY: ${{ secrets.GRAFT_API_KEY }}
+ GRAFT_BASE_URL: ${{ secrets.GRAFT_BASE_URL }}
+ GRAFT_MODEL: ${{ secrets.GRAFT_MODEL }}
+ run: |
+ set -euo pipefail
+ node dist/cli.js build .
+ # A wide window on purpose: the blast radius of the last fifty commits
+ # covers most of what any PR will reach, and naming batches them. Falls
+ # back to the root commit when the history is shorter than the window.
+ base=$(git rev-parse HEAD~50 2>/dev/null || git rev-list --max-parents=0 HEAD | head -1)
+ # `|| true`: this job's product is the cache, and a naming hiccup on a
+ # single batch must not turn main red.
+ node dist/cli.js blast . --base "$base" --depth 2 --name --format text > /dev/null || true
+
+ - uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ with:
+ path: graft
+ key: graft-${{ github.sha }}
diff --git a/.github/workflows/blast-pages.yml b/.github/workflows/blast-pages.yml
new file mode 100644
index 00000000..e6ae0e82
--- /dev/null
+++ b/.github/workflows/blast-pages.yml
@@ -0,0 +1,113 @@
+name: Blast viewer
+
+# Publishes the interactive viewer for a pull request to GitHub Pages, and links it
+# from the blast-radius comment.
+#
+# `pull_request_target`, not `pull_request`, because publishing needs write access to
+# the gh-pages branch and a `pull_request` job on a fork PR has none. That choice
+# carries the standard hazard: this workflow runs with the BASE repo's permissions
+# while the PR's code is attacker-controlled on a fork. So it checks out the base
+# ref for the tooling, builds the CLI from the BASE commit, and only ever reads the
+# PR's files as data — never runs a script from the PR (no `npm ci` on the PR's
+# package.json, no postinstall). The graph is built from the PR's source text by a
+# tree-sitter parser, which executes none of it.
+on:
+ pull_request_target:
+ branches: [main]
+ types: [opened, synchronize, reopened, closed]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: blast-pages-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ publish:
+ if: github.event.action != 'closed'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ pull-requests: write
+ steps:
+ # 1. The tooling, from the base branch — never from the PR.
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ path: base
+ persist-credentials: false
+
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: "20"
+
+ - name: Build the CLI from the base commit
+ working-directory: base
+ run: npm ci && npm run build
+
+ # 2. The PR's code, as data only.
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ ref: refs/pull/${{ github.event.pull_request.number }}/merge
+ path: pr
+ fetch-depth: 0
+ persist-credentials: false
+
+ - name: Build the graph and export the viewer
+ working-directory: pr
+ env:
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ run: |
+ set -euo pipefail
+ node ../base/dist/cli.js build .
+ node ../base/dist/cli.js viz . --export ../site --title "PR #$PR_NUMBER"
+
+ - name: Publish to gh-pages
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ REPO: ${{ github.repository }}
+ run: |
+ set -euo pipefail
+ git clone --depth 1 --branch gh-pages "https://x-access-token:[email protected]/$REPO.git" pages \
+ || git clone --depth 1 "https://x-access-token:[email protected]/$REPO.git" pages
+ cd pages
+ # `checkout --orphan` keeps the index, so on a repo with no gh-pages yet
+ # (where the fallback clone above landed on the default branch) the first
+ # commit would carry every file of main and Pages would serve the repo.
+ if ! git checkout gh-pages 2>/dev/null; then
+ git checkout --orphan gh-pages
+ git rm -rf --cached . >/dev/null
+ # The exported page lives outside this clone, so clean cannot reach it.
+ git clean -fdq
+ fi
+ mkdir -p "pr/$PR_NUMBER"
+ cp ../site/index.html "pr/$PR_NUMBER/index.html"
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git add "pr/$PR_NUMBER"
+ git commit -m "viz: PR #$PR_NUMBER" || { echo "nothing changed"; exit 0; }
+ git push origin gh-pages
+
+ # A merged or closed PR's page is dead weight — and on a busy repo, thousands of
+ # 1 MB files. Removed with the PR, not on a timer.
+ cleanup:
+ if: github.event.action == 'closed'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - name: Remove this PR's page
+ env:
+ GH_TOKEN: ${{ github.token }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ REPO: ${{ github.repository }}
+ run: |
+ set -euo pipefail
+ git clone --depth 1 --branch gh-pages "https://x-access-token:[email protected]/$REPO.git" pages || exit 0
+ cd pages
+ [ -d "pr/$PR_NUMBER" ] || exit 0
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git rm -r --quiet "pr/$PR_NUMBER"
+ git commit -m "viz: drop PR #$PR_NUMBER" && git push origin gh-pages
diff --git a/.github/workflows/blast.yml b/.github/workflows/blast.yml
new file mode 100644
index 00000000..e54f1b70
--- /dev/null
+++ b/.github/workflows/blast.yml
@@ -0,0 +1,45 @@
+name: Blast radius
+
+# graft's own PRs run the action graft ships, so the comment format is reviewed the
+# same way the code is. `pull_request` (not `_target`) on purpose: the job reads the
+# PR's code, so it must not carry write access to secrets a fork could reach.
+on:
+ pull_request:
+ branches: [main]
+
+permissions:
+ contents: read
+
+jobs:
+ blast:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+
+ - uses: ./.github/actions/graft-blast
+ with:
+ depth: "2"
+ # graft reviews its own PRs with the code IN the PR, not with the last
+ # release — a release cannot run a command the PR is adding.
+ setup-cmd: npm ci && npm run build
+ graft-cmd: node dist/cli.js
+ # A fork's PR gets no secrets, so naming would fail anyway; every area then
+ # carries its hub-symbol name, which is still reviewable.
+ name-areas: ${{ github.event.pull_request.head.repo.fork == false }}
+ # Linked only once Pages is actually serving: set the repo variable
+ # BLAST_VIEWER_BASE (e.g. https://nanonets.github.io/Graft) after pointing
+ # Pages at the gh-pages branch that blast-pages.yml writes. Unset, the
+ # comment simply has no link rather than a link that 404s.
+ viewer-url: ${{ vars.BLAST_VIEWER_BASE != '' && format('{0}/pr/{1}/', vars.BLAST_VIEWER_BASE, github.event.pull_request.number) || '' }}
+ env:
+ GRAFT_API_KEY: ${{ secrets.GRAFT_API_KEY }}
+ # Wire format stays `openai` for any OpenAI-compatible gateway; these two
+ # point it at whichever one holds the key above.
+ GRAFT_BASE_URL: ${{ secrets.GRAFT_BASE_URL }}
+ GRAFT_MODEL: ${{ secrets.GRAFT_MODEL }}
diff --git a/README.md b/README.md
index 8caf6359..3cf6360e 100644
--- a/README.md
+++ b/README.md
@@ -351,16 +351,23 @@ graft grep "<regex>" -i --fixed # case-insensitive; treat the pattern as a
graft map [dir] # token-budgeted repo orientation — dir clusters, hubs, hotspots (no LLM, no key)
graft map --max-dirs N # raise/lower the number of directories shown
+graft blast [dir] # blast radius of a diff: what depends on the lines this change touched (no LLM, no key)
+graft blast --base origin/main # diff against the merge base with HEAD — what a PR job runs
+graft blast --format markdown # a PR comment: the areas a change can reach, per-symbol detail collapsed under it
+graft blast --base origin/main --name # name those areas with one cached LLM call, instead of a full --deep build
+graft blast --depth all --format json # the full transitive closure, machine-readable
+
graft check [dir] # fail (exit 1) if graft/ has drifted from the code (never auto-refreshes — it's the drift report)
graft check --json # print the drift report as JSON
-# ask / skeleton / callers / grep / map all refresh the graph first if the working tree moved:
+# ask / skeleton / callers / grep / map / blast all refresh the graph first if the working tree moved:
# --no-refresh # answer from the graph exactly as it is on disk
# GRAFT_NO_REFRESH=1 # same, for every command
# GRAFT_REFRESH=hash # hash every file instead of trusting size+mtime
graft viz [dir] # see the graph: serves an interactive viewer on localhost
graft viz --port 5000 --no-open # pick a port; don't auto-open the browser
+graft viz --export site/ --title "PR #12" # one self-contained index.html — for CI, GitHub Pages, or a build artifact
graft init [dir] # pick which agents to wire (prompts on a terminal; writes nothing until you choose)
graft init --dry-run # list every file it would touch, then exit
diff --git a/package.json b/package.json
index c54e1eca..9ba56777 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@nanonets/graft",
- "version": "0.11.0",
+ "version": "0.12.0",
"description": "Build a repo's context graph as a folder of linked markdown files: a local, regenerable cache that every query keeps in sync with your code.",
"keywords": [
"ai",
diff --git a/src/ai/failure.ts b/src/ai/failure.ts
new file mode 100644
index 00000000..7aa1d76c
--- /dev/null
+++ b/src/ai/failure.ts
@@ -0,0 +1,79 @@
+/**
+ * When to stop calling a provider that is failing (#127).
+ *
+ * Both LLM passes of `build --deep` — the per-file concept summaries
+ * (`context/build.ts`) and the per-file crux pass (`graph/enrich.ts`) — used to
+ * catch every error per file, keep going, and finish with a clean exit. On an
+ * 884-file repo behind a gateway whose token quota was spent that produced 1,617
+ * failed calls, a normal success footer, and a graph whose meaning tier was
+ * missing; the degradation surfaced days later as bad `ask` results.
+ *
+ * One gate, shared by both passes, so they agree on what "the provider stopped
+ * working" means and a caller can report it once.
+ */
+
+/** Consecutive failures that end a pass. One flaky file is normal; five in a row is
+ * a provider that is not going to start working, and each further call is spend
+ * with no chance of a result. */
+export const MAX_CONSECUTIVE_FAILURES = 5;
+
+/**
+ * Errors no amount of retrying fixes: the key is wrong, or the account/quota is
+ * spent. Matched on the message because that is all a provider-neutral transport
+ * carries — over-matching costs a build that was going to fail anyway, while
+ * under-matching just falls back to the consecutive-failure cutoff.
+ */
+export function terminalReason(message: string): string | null {
+ const m = message.toLowerCase();
+ if (/quota|insufficient[_ ]funds|insufficient[_ ]quota|billing|payment required|402/.test(m)) {
+ return "the provider reports the quota/credit for this key is exhausted";
+ }
+ if (/\b401\b|\b403\b|unauthorized|invalid api key|invalid_api_key|authentication/.test(m)) {
+ return "the provider rejected the API key";
+ }
+ return null;
+}
+
+/**
+ * Failure bookkeeping for one LLM pass: how many units failed, how many were
+ * skipped once it gave up, and the human-readable reason it did.
+ *
+ * Single-threaded by construction — every mutation happens between awaits in the
+ * pass's own worker — so no locking is needed despite the concurrency above it.
+ */
+export class LlmFailureGate {
+ /** Units (files) whose call failed. */
+ failed = 0;
+ /** Units never attempted because the pass had already given up. */
+ skipped = 0;
+ /** Why the pass stopped, when it did. */
+ fatal?: string;
+ private consecutive = 0;
+
+ /** True once the pass should stop issuing calls. */
+ get stopped(): boolean {
+ return this.fatal !== undefined;
+ }
+
+ /** Record a failed unit; sets {@link fatal} when this failure is the last straw. */
+ record(message: string): void {
+ this.failed++;
+ this.consecutive++;
+ const terminal = terminalReason(message);
+ if (terminal) {
+ this.fatal = `${terminal} — stopped after ${this.failed} failed file(s). First error: ${message}`;
+ } else if (this.consecutive >= MAX_CONSECUTIVE_FAILURES) {
+ this.fatal = `${this.consecutive} files in a row failed, so the pass stopped rather than keep calling. Last error: ${message}`;
+ }
+ }
+
+ /** Record a success — a failure run only counts while it is unbroken. */
+ succeeded(): void {
+ this.consecutive = 0;
+ }
+
+ /** Record a unit that was not attempted because the pass had stopped. */
+ skip(): void {
+ this.skipped++;
+ }
+}
diff --git a/src/ai/llm/anthropic.ts b/src/ai/llm/anthropic.ts
index b58de7cc..88f50ce2 100644
--- a/src/ai/llm/anthropic.ts
+++ b/src/ai/llm/anthropic.ts
@@ -15,6 +15,7 @@
* signatures survive a multi-turn loop.
*/
import Anthropic from "@anthropic-ai/sdk";
+import { transportRetries } from "./types.js";
import type { ChatModel, ChatRequest, ChatResponse, Message, ToolCall, ToolSpec, Usage } from "./types.js";
const PROVIDER = "anthropic";
@@ -41,7 +42,9 @@ export class AnthropicChatModel implements ChatModel {
constructor(opts: AnthropicChatModelOptions) {
this.model = opts.model;
this.label = opts.label ?? `${PROVIDER}:${opts.model}`;
- this.client = opts.client ?? new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl });
+ this.client =
+ opts.client ??
+ new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl, maxRetries: transportRetries() });
}
async create(req: ChatRequest): Promise<ChatResponse> {
diff --git a/src/ai/llm/openai.ts b/src/ai/llm/openai.ts
index b62bfb40..a5d52be7 100644
--- a/src/ai/llm/openai.ts
+++ b/src/ai/llm/openai.ts
@@ -10,6 +10,7 @@
* input count so {@link Usage.input} is uncached-only.
*/
import OpenAI from "openai";
+import { transportRetries } from "./types.js";
import type { ChatModel, ChatRequest, ChatResponse, Message, ToolCall, ToolSpec, Usage } from "./types.js";
const PROVIDER = "openai";
@@ -98,6 +99,7 @@ export class OpenAIChatModel implements ChatModel {
apiKey: opts.apiKey,
baseURL: opts.baseUrl,
defaultHeaders: opts.headers,
+ maxRetries: transportRetries(),
});
}
diff --git a/src/ai/llm/types.ts b/src/ai/llm/types.ts
index 3607506b..6cd9bcd5 100644
--- a/src/ai/llm/types.ts
+++ b/src/ai/llm/types.ts
@@ -111,3 +111,16 @@ export interface ChatModel {
readonly label: string;
create(req: ChatRequest): Promise<ChatResponse>;
}
+
+/**
+ * How many times the transport retries a failed request before the error reaches
+ * the caller. Both SDKs retry only what is worth retrying (429 and 5xx, honouring
+ * `Retry-After`) with exponential backoff, so this is the knob that separates a
+ * transient rate limit from a real failure — #127 lost whole files to the first
+ * 429 a shared gateway threw. Env-overridable because a metered corporate gateway
+ * may want fewer, and a flaky local proxy more.
+ */
+export function transportRetries(): number {
+ const raw = Number(process.env.GRAFT_LLM_RETRIES);
+ return Number.isFinite(raw) && raw >= 0 ? Math.floor(raw) : 4;
+}
diff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.ts
new file mode 100644
index 00000000..98386a5c
--- /dev/null
+++ b/src/blast/blast-cli.ts
@@ -0,0 +1,132 @@
+/**
+ * CLI wiring for `graft blast` — the command a CI job runs on a pull request.
+ *
+ * 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 { contextDirFor } from "../context/node-file.js";
+import { loadGraphCached } from "../graph/load.js";
+import type { GraphV1 } from "../graph/types.js";
+import { blastRadiusIn, type BlastReport } from "./blast.js";
+import { changedFiles, refExists } from "./diff.js";
+import { markdownReport, mermaidDiagram, textReport } from "./render.js";
+
+export type BlastFormat = "text" | "markdown" | "mermaid" | "json";
+
+export interface BlastCliOptions {
+ /** Base ref to diff against (`origin/main`); omitted → working tree vs HEAD. */
+ base?: string;
+ /** Raw `--depth`: a positive integer, or `all`/`full`/`max`. Default 2. */
+ depth?: string;
+ format?: string;
+ /** 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;
+ /** The top-level `--dir` override. */
+ globalDir?: string;
+}
+
+const DEFAULT_DEPTH = 2;
+
+function resolveFormat(raw: string | undefined): BlastFormat {
+ if (raw === undefined) return "text";
+ if (raw === "text" || raw === "markdown" || raw === "mermaid" || raw === "json") return raw;
+ console.error(`✗ --format must be text, markdown, mermaid or json, got "${raw}"`);
+ process.exit(1);
+}
+
+/** Same grammar as `graft callers --depth`, so the two commands stay learnable together. */
+function resolveDepth(raw: string | undefined): number {
+ if (raw === undefined) return DEFAULT_DEPTH;
+ if (/^(all|full|max)$/i.test(raw)) return Number.POSITIVE_INFINITY;
+ const d = Number(raw);
+ if (!Number.isFinite(d) || d < 1) {
+ console.error(`✗ --depth must be a positive number or "all", got "${raw}"`);
+ process.exit(1);
+ }
+ return Math.floor(d);
+}
+
+export async function runBlastCommand(dir: string, opts: BlastCliOptions): Promise<void> {
+ const root = resolve(dir);
+ const contextDir = contextDirFor(root, opts.globalDir);
+ const format = resolveFormat(opts.format);
+ const depth = resolveDepth(opts.depth);
+
+ const graph = loadGraphCached(contextDir);
+ if (!graph) {
+ console.error(`✗ no graph found at ${contextDir} — run \`graft build\` first`);
+ process.exit(1);
+ }
+
+ // An unknown base is the most common CI misconfiguration by a distance: an
+ // `actions/checkout` without `fetch-depth: 0` leaves the base branch absent, and
+ // git's own message ("unknown revision or path not in the working tree") sends
+ // people looking for a typo instead of the checkout depth.
+ if (opts.base !== undefined && !refExists(root, opts.base)) {
+ console.error(
+ `✗ base ref "${opts.base}" is not in this checkout.\n` +
+ " In CI, fetch enough history for the merge base: actions/checkout with `fetch-depth: 0`.",
+ );
+ process.exit(1);
+ }
+
+ const diff = changedFiles(root, opts.base);
+ if (!diff) {
+ console.error(`✗ could not read a diff in ${root} — is this a git repository?`);
+ process.exit(1);
+ }
+
+ const report = blastRadiusIn(graph, contextDir, diff.files, diff.basis, depth);
+ if (opts.name) await nameClusters(graph, report, contextDir);
+
+ if (format === "json") {
+ console.log(JSON.stringify(report, null, 2));
+ return;
+ }
+ if (format === "mermaid") {
+ const diagram = mermaidDiagram(report);
+ // Exit 0 with a comment, not an error: "nothing depends on this diff" is a
+ // legitimate answer, and a CI step must not fail on it.
+ console.log(diagram ?? "%% no dependents to draw");
+ return;
+ }
+ process.stdout.write(format === "markdown" ? markdownReport(report) : textReport(report));
+}
+
+/**
+ * Name the clusters left on their symbol backstop, then report what it cost.
+ *
+ * Everything here is best-effort by construction: no key, a spent quota or a
+ * refused call leaves the backstop labels in place and the command still exits 0,
+ * because a PR check must not fail over a cosmetic layer.
+ */
+async function nameClusters(graph: GraphV1, report: BlastReport, contextDir: string): Promise<void> {
+ const { applyNames, ChatNamer } = await import("./name.js");
+ const { resolveConfig } = await import("../ai/providers.js");
+ const cfg = resolveConfig({ contextDir });
+
+ let namer;
+ if (cfg.chatModel) {
+ namer = new ChatNamer(cfg.chatModel);
+ } else if (cfg.apiKey) {
+ const { createChatModel } = await import("../ai/llm/factory.js");
+ namer = new ChatNamer(createChatModel({
+ provider: cfg.provider, apiKey: cfg.apiKey, model: cfg.model,
+ baseUrl: cfg.baseUrl, headers: cfg.headers,
+ }));
+ }
+
+ const stats = await applyNames(graph, report, { namer, contextDir });
+ if (!namer) {
+ console.error("• --name: no API key (GRAFT_API_KEY), so areas keep their symbol names");
+ return;
+ }
+ if (stats.error) console.error(`• --name: naming failed (${stats.error}) — areas keep their symbol names`);
+ else if (stats.named + stats.cached + stats.declined > 0) {
+ const bits = [`${stats.named} named`, `${stats.cached} cached`];
+ if (stats.declined > 0) bits.push(`${stats.declined} left as symbols (mixed)`);
+ console.error(`• --name: ${bits.join(", ")}`);
+ }
+}
diff --git a/src/blast/blast.ts b/src/blast/blast.ts
new file mode 100644
index 00000000..8d591ca5
--- /dev/null
+++ b/src/blast/blast.ts
@@ -0,0 +1,522 @@
+/**
+ * Blast radius of a diff: what else in the repo depends on the lines this change
+ * touched.
+ *
+ * The whole command is a join between two things graft already has — git's changed
+ * line ranges (`diff.ts`) and the wiring graph's incoming edges (`traverse.ts`) —
+ * so there is no new graph logic here, only the seeding rule:
+ *
+ * changed line → the innermost symbol whose span contains it → seed
+ *
+ * Seeding by SYMBOL rather than by file is what makes the answer worth reading: a
+ * 400-line file with a one-line edit reports the dependents of that one function,
+ * not of everything the file happens to define. The file node is seeded too, so
+ * importers (whose edge targets the file, not the symbol) are still found.
+ */
+import { impactOfMany, type EdgeHit } from "../graph/traverse.js";
+import type { GraphV1, NodeV1 } from "../graph/types.js";
+import { dirLabel, moduleIndex, parentDir, shortLabel, type ModuleIndex } from "./modules.js";
+import type { ChangedFile } from "./diff.js";
+
+const SPAN_RE = /^L(\d+)-L(\d+)$/;
+
+export interface BlastOptions {
+ /** BFS depth over incoming edges; `Infinity` for the full closure. */
+ depth: number;
+ /** Concept/directory labels. Built from the context dir when omitted. */
+ modules?: ModuleIndex;
+}
+
+/** A changed symbol the walk started from. */
+export interface Seed {
+ id: string;
+ name: string;
+ kind: string;
+ path: string;
+ span: string;
+ /** True for a whole-file seed (an added file, or a change outside any symbol). */
+ wholeFile: boolean;
+}
+
+/** One dependent symbol, and how the walk reached it. */
+export interface Impacted {
+ id: string;
+ name: string;
+ kind: string;
+ path: string;
+ span: string;
+ relation: string;
+ depth: number;
+}
+
+/**
+ * Where a cluster's label came from — the rungs of the naming ladder.
+ *
+ * `concept` — a concept node from a `--deep` build claims every file in the cluster.
+ * `named` — `graft blast --name` asked a model to name this cluster (see name.ts).
+ * `symbol` — the deterministic backstop: the cluster's most significant symbol.
+ *
+ * A bare directory is never a label. The whole point of the picture is that a
+ * reviewer reads what is affected, and `src/graph/` tells them nothing they could
+ * not get from the diff — but it must never be replaced by a guess either, so the
+ * backstop names a real symbol rather than inventing a feature name.
+ */
+export type LabelSource = "concept" | "named" | "symbol";
+
+/** Dependents grouped for the diagram: the unit a reviewer actually thinks in. */
+export interface ImpactedModule {
+ label: string;
+ labelSource: LabelSource;
+ /** Stable identity for the cluster, independent of its label: the concept name
+ * or the directory it was grouped by. Naming and its cache key hang off this. */
+ key: string;
+ files: string[];
+ symbols: Impacted[];
+ /** Changed files whose edges reached this module — the diagram's arrows. */
+ from: string[];
+}
+
+/**
+ * Whether the diff brought its tests along.
+ *
+ * `changed` — a test file that reaches this area was edited in this PR.
+ * `stale` — tests reach it and the diff left every one of them alone.
+ * `none` — nothing under `test/` reaches it at all.
+ * `na` — no function, method or class changed here, so there is nothing to
+ * ask the question of: a types-only file, or config and wiring.
+ */
+export type TestSignal = "changed" | "stale" | "none" | "na";
+
+/** One area of the diff: the changed files a reviewer thinks of as one thing. */
+export interface ChangedArea {
+ label: string;
+ labelSource: LabelSource;
+ /** The directory the cluster was grouped by — see {@link ImpactedModule.key}. */
+ key: string;
+ /** Changed, indexed, non-test files grouped under this label. */
+ files: string[];
+ /** Changed symbols seeded from those files. */
+ seeds: number;
+ tests: TestSignal;
+ /** Test files with an edge into this area, and those of them the diff changed. */
+ testFiles: string[];
+ changedTestFiles: string[];
+ /** Test reach, over the area's exported functions/methods/classes only. */
+ reached: number;
+ behavioural: number;
+ /** Names of the behavioural symbols no test reaches, for the collapsed detail. */
+ unreached: string[];
+ /** Changed symbol names, behaviour first — the backstop label and the naming
+ * prompt both read from this. */
+ seedNames: string[];
+}
+
+export interface BlastReport {
+ basis: string;
+ depth: number;
+ changed: ChangedFile[];
+ /** Changed paths the graph has no node for: unsupported language, or deleted. */
+ unindexed: string[];
+ /** Changed paths that were deleted, called out because their dependents are
+ * unknowable from a graph built at the post-change commit. */
+ deleted: string[];
+ seeds: Seed[];
+ impacted: Impacted[];
+ modules: ImpactedModule[];
+ /** The diff itself, grouped: the left-hand side of the diagram. */
+ areas: ChangedArea[];
+ /** Test-only dependents, kept out of `modules` so they cannot crowd it out. */
+ testModules: ImpactedModule[];
+}
+
+function spanBounds(span: string): { start: number; end: number } | null {
+ const m = SPAN_RE.exec(span);
+ return m ? { start: Number(m[1]), end: Number(m[2]) } : null;
+}
+
+/**
+ * The innermost symbols whose spans overlap any changed range in `path`.
+ *
+ * "Innermost" matters for a method: a changed line inside `Cache.get` overlaps both
+ * the class span and the method span, and seeding the class would report everyone
+ * who touches any part of `Cache`. Nesting is resolved by keeping, for each range,
+ * only symbols that contain no other matched symbol.
+ */
+function seedsForFile(graph: GraphV1, path: string, ranges: { start: number; end: number }[]): NodeV1[] {
+ const symbols: { node: NodeV1; start: number; end: number }[] = [];
+ for (const n of graph.nodes) {
+ if (n.kind === "file" || n.path !== path) continue;
+ const b = spanBounds(n.span);
+ if (b) symbols.push({ node: n, ...b });
+ }
+ if (symbols.length === 0) return [];
+
+ const hit = new Map<string, NodeV1>();
+ for (const r of ranges) {
+ const overlapping = symbols.filter((s) => s.start <= r.end && s.end >= r.start);
+ // Drop any symbol that strictly contains another overlapping one (the class
+ // around a changed method), keeping the tightest description of the edit.
+ for (const s of overlapping) {
+ const containsAnother = overlapping.some(
+ (o) => o !== s && o.start >= s.start && o.end <= s.end,
+ );
+ if (!containsAnother) hit.set(s.node.id, s.node);
+ }
+ }
+ return [...hit.values()];
+}
+
+/** Compute the blast radius of `changed` against `graph`. */
+export function blastRadius(
+ graph: GraphV1,
+ changed: ChangedFile[],
+ basis: string,
+ opts: BlastOptions,
+): BlastReport {
+ const fileNodes = new Map<string, NodeV1>();
+ for (const n of graph.nodes) if (n.kind === "file") fileNodes.set(n.path, n);
+
+ const seeds: Seed[] = [];
+ const unindexed: string[] = [];
+ const deleted: string[] = [];
+ /** Seed nodes per changed file, kept for the area grouping and the test signal. */
+ const seedNodes = new Map<string, NodeV1[]>();
+ /** Merged dependents, keyed by node id, at the shallowest depth any file reached
+ * them — plus which changed files did the reaching. */
+ const merged = new Map<string, { hit: Impacted; from: Set<string> }>();
+
+ for (const file of changed) {
+ if (file.status === "deleted") {
+ deleted.push(file.path);
+ continue;
+ }
+ const fileNode = fileNodes.get(file.path);
+ if (!fileNode) {
+ unindexed.push(file.path);
+ continue;
+ }
+
+ // No hunk ranges (a rename with no content change, a mode change) or an added
+ // file: the unit of change is the file itself.
+ const symbolSeeds = file.ranges.length > 0 ? seedsForFile(graph, file.path, file.ranges) : [];
+ for (const node of symbolSeeds) {
+ seeds.push({ id: node.id, name: node.name, kind: node.kind, path: node.path, span: node.span, wholeFile: false });
+ }
+ if (symbolSeeds.length === 0) {
+ seeds.push({
+ id: fileNode.id, name: fileNode.name, kind: fileNode.kind,
+ path: fileNode.path, span: fileNode.span, wholeFile: true,
+ });
+ }
+
+ // One walk PER CHANGED FILE, not one walk over every seed at once. A combined
+ // walk records the depth a node was first reached at but not by which seed, so
+ // the diagram could only draw "every changed file reaches every module" — a
+ // cross-product that tells a reviewer nothing. Walking per file costs one
+ // adjacency build each (cheap: the graph is already in memory) and buys arrows
+ // that are true.
+ //
+ // The FILE node is a seed only when no symbol matched. `imports` edges target
+ // the file id, so seeding it alongside symbols would pull in every importer of
+ // the file — a one-line edit to one function would report every module that
+ // imports the module, which is the noise this command exists to avoid. With no
+ // symbol seeds (a change to a top-level constant, a new import, a file with no
+ // extracted symbols) the file IS the unit of change, and its importers are the
+ // only dependents there are.
+ const walkSeeds = symbolSeeds.length > 0 ? symbolSeeds : [fileNode];
+ seedNodes.set(file.path, walkSeeds);
+ const hits = impactOfMany(graph, walkSeeds, opts.depth, "in");
+ for (const h of hits) {
+ if (!hasNode(h)) continue;
+ const hit = toImpacted(h);
+ const prev = merged.get(hit.id);
+ if (!prev) merged.set(hit.id, { hit, from: new Set([file.path]) });
+ else {
+ prev.from.add(file.path);
+ // Keep the shallowest reach: a symbol two hops from one changed file and one
+ // hop from another is one hop away from this PR.
+ if (hit.depth < prev.hit.depth) prev.hit = hit;
+ }
+ }
+ }
+
+ const impacted = [...merged.values()].map((m) => m.hit);
+ const origins = new Map([...merged].map(([id, m]) => [id, m.from]));
+ const index = opts.modules ?? emptyIndex();
+ const grouped = groupByModule(impacted, changed, origins, index);
+
+ return {
+ basis,
+ depth: opts.depth,
+ changed,
+ unindexed,
+ deleted,
+ seeds,
+ impacted,
+ modules: grouped.modules,
+ testModules: grouped.testModules,
+ areas: changedAreas(graph, changed, seedNodes, index, grouped.modules),
+ };
+}
+
+/**
+ * Group the changed files into areas, and work out whether each one's tests moved.
+ *
+ * The diff's own side of the diagram used to be one box per changed file, which can
+ * never fit: a 24-file PR drew ten arbitrary paths. Grouped by the same concept
+ * labels the dependents use, the same PR is three or four circles — and once the
+ * files are grouped, "did a test that reaches this move too?" is one question per
+ * circle instead of per file.
+ */
+function changedAreas(
+ graph: GraphV1,
+ changed: ChangedFile[],
+ seedNodes: Map<string, NodeV1[]>,
+ index: ModuleIndex,
+ modules: ImpactedModule[],
+): 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]));
+ /** 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) {
+ const path = nodeById.get(e.source)?.path;
+ if (!path || !TEST_PATH.test(path)) continue;
+ const at = incoming.get(e.target) ?? new Set<string>();
+ at.add(path);
+ incoming.set(e.target, at);
+ }
+
+ // Group by DIRECTORY, not by concept. Concepts in a well-summarised repo are
+ // near-file-grained — graft's own PR produced nine of them, one file each — so
+ // grouping the diff by concept groups nothing: the left side was nine circles
+ // with near-identical truncated names. A directory is the coarser unit reviewers
+ // already use, and a concept name is only worth borrowing when one concept
+ // happens to claim the whole group.
+ const groups = new Map<string, string[]>();
+ for (const path of seedNodes.keys()) {
+ // A changed test file is the signal, not the source of a blast radius. Drawing
+ // it as an area would put "your tests changed" on both sides of the arrow.
+ if (TEST_PATH.test(path)) continue;
+ const dir = dirLabel(path);
+ groups.set(dir, [...(groups.get(dir) ?? []), path]);
+ }
+ coarsen(groups, MAX_AREAS);
+
+ const byKey = new Map<string, ChangedArea>();
+ for (const [dir, paths] of groups) {
+ const area: ChangedArea = {
+ label: dir, labelSource: "symbol", key: dir,
+ files: [], seeds: 0, tests: "none", testFiles: [], changedTestFiles: [],
+ reached: 0, behavioural: 0, unreached: [], seedNames: [],
+ };
+ byKey.set(dir, area);
+ for (const path of paths) {
+ const nodes = seedNodes.get(path) ?? [];
+ area.files.push(path);
+ area.seeds += nodes.length;
+
+ for (const node of nodes) {
+ // Reach is measured over behaviour only. Counting interfaces and type aliases
+ // would sink every ratio: nothing "calls" a type, so a fully tested area of
+ // typed code would report a third of its symbols as unreached.
+ const behavioural = node.kind === "function" || node.kind === "method" || node.kind === "class";
+ const from = incoming.get(node.id) ?? new Set<string>();
+ for (const t of from) {
+ 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);
+ area.behavioural++;
+ if (from.size > 0) area.reached++;
+ else area.unreached.push(node.name);
+ }
+ }
+ }
+
+ for (const area of byKey.values()) {
+ const concept = sharedConcept(area.files, index);
+ area.label = concept ?? hubLabel(area.seedNames, area.key);
+ area.labelSource = concept ? "concept" : "symbol";
+ area.files.sort();
+ area.testFiles.sort();
+ area.changedTestFiles.sort();
+ area.tests =
+ area.behavioural === 0 ? "na"
+ : area.changedTestFiles.length > 0 ? "changed"
+ : area.testFiles.length > 0 ? "stale"
+ : "none";
+ }
+
+ // Ordered by how much each area actually reaches, because the diagram caps this
+ // list and folds the rest into one circle. Ordered by size instead, the fold ends
+ // up holding the best-connected areas and the tail circle collects every arrow —
+ // the same mistake, one level up, as capping changed FILES in diff order.
+ const reach = (a: ChangedArea) =>
+ modules.filter((m) => m.from.some((f) => a.files.includes(f))).length;
+ return [...byKey.values()].sort(
+ (a, b) => reach(b) - reach(a) || b.files.length - a.files.length || a.label.localeCompare(b.label),
+ );
+}
+
+/** Convenience wrapper: build the module index from a context dir. */
+export function blastRadiusIn(
+ graph: GraphV1,
+ contextDir: string,
+ changed: ChangedFile[],
+ basis: string,
+ depth: number,
+): BlastReport {
+ return blastRadius(graph, changed, basis, { depth, modules: moduleIndex(contextDir) });
+}
+
+function hasNode(h: EdgeHit): h is EdgeHit & { node: NodeV1 } {
+ // Unresolved endpoints (an import module string no node exists for) carry no
+ // location, so they can neither be grouped nor opened — dropped rather than
+ // rendered as a box with no file behind it.
+ return h.node !== null;
+}
+
+function toImpacted(h: EdgeHit & { node: NodeV1 }): Impacted {
+ return {
+ id: h.node.id, name: h.node.name, kind: h.node.kind,
+ path: h.node.path, span: h.node.span, relation: h.relation, depth: h.depth,
+ };
+}
+
+function emptyIndex(): ModuleIndex {
+ return { hasConcepts: false, labelOf: (p) => p, conceptOf: () => null };
+}
+
+/**
+ * The concept claiming EVERY file in a cluster, or null when they disagree.
+ *
+ * Unanimity is the point: a concept that covers three of five files describes
+ * something narrower than the cluster, and stamping its name on the whole thing is
+ * how a diagram starts lying about what it drew.
+ */
+function sharedConcept(paths: string[], index: ModuleIndex): string | null {
+ const concepts = new Set(paths.map((p) => index.conceptOf(p)));
+ const [only] = concepts;
+ return concepts.size === 1 && only ? shortLabel(only) : null;
+}
+
+/**
+ * The deterministic backstop label: the cluster's most significant symbol.
+ *
+ * Reached with no concept, no cache and no API key, so this is what guarantees a
+ * circle never carries a bare directory. It is a fact rather than a guess — the
+ * reviewer can grep the name — which is why it beats borrowing a neighbouring
+ * concept: on graft's own graph that borrowing labelled the freshness gate
+ * "Graph Extraction and Loading", which misleads worse than any path.
+ */
+export function hubLabel(names: string[], fallback: string): string {
+ const [head] = names.filter(Boolean);
+ // The hub alone, with no "+8" tail: how many symbols came with it is already the
+ // circle's second line and the table's own column, and repeating it in the label
+ // turned "writeGraph" into "writeGraph +8", which reads as a version number.
+ return head ? shortLabel(head) : fallback;
+}
+
+/**
+ * Group dependents into modules. `origins` carries, per dependent, the changed
+ * files whose walk actually reached it — so a module's `from` is the real arrow
+ * set, not every changed file in the PR.
+ */
+function groupByModule(
+ impacted: Impacted[],
+ changed: ChangedFile[],
+ origins: Map<string, Set<string>>,
+ modules: ModuleIndex,
+): { modules: ImpactedModule[]; testModules: ImpactedModule[] } {
+ const changedPaths = new Set(changed.map((c) => c.path));
+ const byKey = new Map<string, ImpactedModule>();
+
+ for (const hit of impacted) {
+ // A dependent inside a file the PR already changes is not "reach" — it is the
+ // diff. Reviewers see it in the diff itself; repeating it as blast radius is
+ // what makes these comments feel like noise.
+ if (changedPaths.has(hit.path)) continue;
+ // Cluster by concept where one exists, else by directory. Clustering and
+ // LABELLING are separate steps now: the key only has to be stable, while the
+ // label goes through the ladder below and may end up naming a symbol.
+ const key = modules.conceptOf(hit.path) ?? dirLabel(hit.path);
+ let mod = byKey.get(key);
+ if (!mod) {
+ mod = { label: key, labelSource: "symbol", key, files: [], symbols: [], from: [] };
+ byKey.set(key, mod);
+ }
+ mod.symbols.push(hit);
+ if (!mod.files.includes(hit.path)) mod.files.push(hit.path);
+ }
+
+ for (const mod of byKey.values()) {
+ const from = new Set<string>();
+ for (const s of mod.symbols) for (const p of origins.get(s.id) ?? []) from.add(p);
+ mod.from = [...from].sort();
+ mod.files.sort();
+ mod.symbols.sort((a, b) => a.depth - b.depth || a.path.localeCompare(b.path));
+ // Shallowest symbol first after that sort, so it is the cluster's hub: the
+ // thing one hop from the diff rather than an arbitrary member.
+ const concept = sharedConcept(mod.files, modules);
+ mod.label = concept ?? hubLabel(mod.symbols.map((s) => s.name), mod.key);
+ mod.labelSource = concept ? "concept" : "symbol";
+ }
+
+ // Test-only modules are separated, not just sorted last. On a repo with a test
+ // per module they are the majority of the graph's dependents — graft's own 24-file
+ // PR produced 31 modules, 24 of them a single test file — so leaving them in the
+ // same list means they crowd out every module a reviewer needs whatever the caps
+ // are. "Your tests reference the thing you changed" is one line, not 24 sections.
+ const bySize = (a: ImpactedModule, b: ImpactedModule) =>
+ b.symbols.length - a.symbols.length || a.label.localeCompare(b.label);
+ const all = [...byKey.values()];
+ return {
+ modules: all.filter((m) => !isTestOnly(m)).sort(bySize),
+ testModules: all.filter(isTestOnly).sort(bySize),
+ };
+}
+
+/**
+ * Directory groups the diff is folded down to before anything is drawn.
+ *
+ * Kept here rather than in the renderer because it is a statement about the diff,
+ * not about the picture: five areas is roughly what a reviewer holds in their head,
+ * and the renderer then draws all of them.
+ */
+const MAX_AREAS = 5;
+
+/**
+ * Fold directory groups into their parents until there are at most `max`.
+ *
+ * The deepest group goes first, and only into a parent that already exists, so
+ * `src/ai/llm/` joins `src/ai/` rather than everything collapsing towards the repo
+ * root. When no group has an existing parent, one is created — but never at the top
+ * level, since a single `(root)` area is no grouping at all.
+ */
+function coarsen(groups: Map<string, string[]>, max: number): void {
+ const depth = (dir: string) => dir.split("/").length;
+ while (groups.size > max) {
+ const keys = [...groups.keys()].sort((a, b) => depth(b) - depth(a) || (groups.get(a)!.length - groups.get(b)!.length));
+ const pick =
+ keys.find((k) => groups.has(parentDir(k)) && parentDir(k) !== "") ??
+ keys.find((k) => parentDir(k) !== "");
+ if (!pick) return;
+ const parent = parentDir(pick);
+ groups.set(parent, [...(groups.get(parent) ?? []), ...groups.get(pick)!]);
+ groups.delete(pick);
+ }
+}
+
+const TEST_PATH = /(^|\/)(tests?|specs?|__tests__)\/|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py|rb)$/i;
+
+/** True when every file in the module is a test file. */
+function isTestOnly(mod: ImpactedModule): boolean {
+ return mod.files.length > 0 && mod.files.every((f) => TEST_PATH.test(f));
+}
diff --git a/src/blast/diff.ts b/src/blast/diff.ts
new file mode 100644
index 00000000..09ced68a
--- /dev/null
+++ b/src/blast/diff.ts
@@ -0,0 +1,167 @@
+/**
+ * What a PR touched, read from git: changed files plus the *line ranges* inside
+ * them, which is what turns a diff into graph seeds (an enclosing-symbol lookup
+ * per changed line, see `blast.ts`).
+ *
+ * Git is shelled out to rather than parsed from a library because the CI job
+ * this feeds already has git — and `--unified=0` gives exactly the post-image
+ * line ranges we need, with no context lines to subtract back out.
+ */
+import { spawnSync } from "node:child_process";
+import { resolve } from "node:path";
+
+export type ChangeStatus = "added" | "modified" | "deleted" | "renamed";
+
+/** A contiguous run of changed lines, in POST-image (new file) line numbers. */
+export interface LineRange {
+ start: number;
+ end: number;
+}
+
+export interface ChangedFile {
+ /** Repo-relative posix path, post-image (the new name for a rename). */
+ path: string;
+ status: ChangeStatus;
+ /** Pre-image path, renames only. */
+ oldPath?: string;
+ /** Post-image changed line ranges. Empty for a pure delete or a mode-only change. */
+ ranges: LineRange[];
+}
+
+export interface DiffResult {
+ /** Human label for what was compared, e.g. "origin/main...HEAD". */
+ basis: string;
+ files: ChangedFile[];
+}
+
+const HUNK_RE = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
+
+/** Run git in `root`, or return null when git fails (not a repo, unknown ref). */
+function git(root: string, args: string[]): string | null {
+ const res = spawnSync("git", ["-c", "core.quotePath=false", ...args], {
+ cwd: root,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ maxBuffer: 64 * 1024 * 1024,
+ });
+ if (res.error || res.status !== 0 || typeof res.stdout !== "string") return null;
+ return res.stdout;
+}
+
+/** True when `ref` names something git can resolve — checked before diffing so
+ * an unknown `--base` fails with a caller-facing message, not a git stack. */
+export function refExists(root: string, ref: string): boolean {
+ return git(resolve(root), ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]) !== null;
+}
+
+/**
+ * The diff arguments for a base ref, and the label to show for it.
+ *
+ * `<base>...HEAD` (three dots) diffs against the MERGE BASE, not the tip of the
+ * base branch — the difference matters on every PR whose base branch moved after
+ * it was cut: two-dot would attribute other people's merges to this PR and
+ * inflate the blast radius with files the author never touched.
+ */
+function rangeArgs(base: string): { args: string[]; basis: string } {
+ return { args: [`${base}...HEAD`], basis: `${base}...HEAD` };
+}
+
+/**
+ * Changed files + post-image line ranges.
+ *
+ * With no `base` this reports the working tree against HEAD (the local
+ * "what am I about to push" case), falling back to the last commit when the
+ * tree is clean — so the command answers something useful when run by hand,
+ * and CI passes `--base` for the real PR range.
+ */
+export function changedFiles(root: string, base?: string): DiffResult | null {
+ const dir = resolve(root);
+ if (base !== undefined) {
+ const { args, basis } = rangeArgs(base);
+ const files = diffFiles(dir, args);
+ return files === null ? null : { basis, files };
+ }
+
+ const working = diffFiles(dir, ["HEAD"]);
+ if (working === null) return null;
+ if (working.length > 0) return { basis: "working tree vs HEAD", files: working };
+
+ const last = diffFiles(dir, ["HEAD~1...HEAD"]);
+ if (last === null) return { basis: "working tree vs HEAD", files: [] };
+ return { basis: "HEAD~1...HEAD", files: last };
+}
+
+/** Both git passes for one range: name-status (statuses, renames) then hunks. */
+function diffFiles(dir: string, range: string[]): ChangedFile[] | null {
+ const status = git(dir, ["diff", "--name-status", "--find-renames", "-z", ...range, "--"]);
+ if (status === null) return null;
+ const files = parseNameStatus(status);
+ if (files.length === 0) return files;
+
+ const patch = git(dir, [
+ "diff",
+ "--unified=0",
+ "--no-color",
+ "--no-ext-diff",
+ "--find-renames",
+ ...range,
+ "--",
+ ]);
+ if (patch !== null) applyHunks(files, patch);
+ return files;
+}
+
+/**
+ * `--name-status -z` output: NUL-separated fields, where a rename spends THREE
+ * fields (`R096`, old, new) and everything else spends two. Splitting on NUL and
+ * walking with a cursor is the only way to read it — a line-oriented parse
+ * silently pairs a rename's old path with the next file's status.
+ */
+function parseNameStatus(out: string): ChangedFile[] {
+ const fields = out.split("\0").filter((f) => f !== "");
+ const files: ChangedFile[] = [];
+ for (let i = 0; i < fields.length; ) {
+ const code = fields[i++];
+ if (code.startsWith("R") || code.startsWith("C")) {
+ const oldPath = fields[i++];
+ const path = fields[i++];
+ if (path === undefined) break;
+ files.push({ path, status: "renamed", oldPath, ranges: [] });
+ continue;
+ }
+ const path = fields[i++];
+ if (path === undefined) break;
+ if (code.startsWith("A")) files.push({ path, status: "added", ranges: [] });
+ else if (code.startsWith("D")) files.push({ path, status: "deleted", ranges: [] });
+ else files.push({ path, status: "modified", ranges: [] });
+ }
+ return files;
+}
+
+/** Attach each hunk's post-image range to its file. */
+function applyHunks(files: ChangedFile[], patch: string): void {
+ const byPath = new Map(files.map((f) => [f.path, f]));
+ let current: ChangedFile | undefined;
+ for (const line of patch.split("\n")) {
+ if (line.startsWith("+++ ")) {
+ const raw = line.slice(4);
+ current = raw === "/dev/null" ? undefined : byPath.get(stripPrefix(raw));
+ continue;
+ }
+ if (!line.startsWith("@@") || !current) continue;
+ const m = HUNK_RE.exec(line);
+ if (!m) continue;
+ const start = Number(m[1]);
+ // `+N,0` is a pure deletion: nothing survives in the post-image, and git
+ // reports the line BEFORE the gap. Recording that single line is what keeps
+ // "the body of foo() lost 10 lines" attributable to foo() at all.
+ const count = m[2] === undefined ? 1 : Number(m[2]);
+ current.ranges.push(count === 0 ? { start, end: start } : { start, end: start + count - 1 });
+ }
+}
+
+/** `b/src/x.ts` → `src/x.ts`, minus any trailing tab-separated timestamp. */
+function stripPrefix(raw: string): string {
+ const untabbed = raw.split("\t")[0];
+ return untabbed.startsWith("b/") ? untabbed.slice(2) : untabbed;
+}
diff --git a/src/blast/modules.ts b/src/blast/modules.ts
new file mode 100644
index 00000000..ab81ea96
--- /dev/null
+++ b/src/blast/modules.ts
@@ -0,0 +1,98 @@
+/**
+ * Module labels for the blast diagram — the "what part of the system is this?"
+ * layer, so a reviewer reads `Graph Extraction and Loading` instead of eleven
+ * file paths.
+ *
+ * Two sources, best first:
+ * 1. the deep tier's concept nodes (`graft/*.md`), whose frontmatter lists the
+ * source files each concept was synthesized from. This is why `blast` is
+ * worth running on a `build --deep` graph: the grouping is the product.
+ * 2. the file's directory, when no concept claims it (a breadth-tier graph, or
+ * a file added by this very PR and therefore absent from the concept layer).
+ */
+import { readNodes } from "../context/node-file.js";
+
+export interface ModuleIndex {
+ /** Label for a repo-relative path — a concept name when one claims the file. */
+ labelOf(path: string): string;
+ /** The claiming concept's name, or null when only the directory fallback applies.
+ * Callers that group files need to tell the two apart: a shared concept is a real
+ * grouping signal, a shared directory is only a shared directory. */
+ conceptOf(path: string): string | null;
+ /** True when at least one concept node was read (i.e. a --deep graph). */
+ hasConcepts: boolean;
+}
+
+/**
+ * Build the path → module-label lookup for a context dir.
+ *
+ * A file can be cited by several concepts; the SMALLEST claiming concept wins.
+ * A concept grounded in three files says something specific about those three,
+ * while a forty-file concept is closer to "the codebase" — picking the tighter
+ * one keeps the diagram's boxes meaningful.
+ */
+export function moduleIndex(contextDir: string): ModuleIndex {
+ const claims = new Map<string, { label: string; size: number }>();
+ const nodes = readNodes(contextDir);
+ for (const node of nodes) {
+ if (!node.name) continue;
+ for (const src of node.sources) {
+ const prev = claims.get(src.path);
+ if (!prev || node.sources.length < prev.size) {
+ claims.set(src.path, { label: node.name, size: node.sources.length });
+ }
+ }
+ }
+ return {
+ hasConcepts: nodes.length > 0,
+ labelOf: (path: string) => shortLabel(claims.get(path)?.label ?? dirLabel(path)),
+ conceptOf: (path: string) => claims.get(path)?.label ?? null,
+ };
+}
+
+/** Longest label a circle can hold before the text overruns it. */
+const MAX_LABEL = 30;
+
+/**
+ * Clause breaks a long concept name can be cut at.
+ *
+ * A concept name is a sentence fragment, so it has real joints: everything after
+ * "via", "and", a colon or an opening parenthesis is elaboration. Cutting there
+ * leaves a phrase that still reads as a name — "Incremental Build" rather than
+ * "Incremental Build via…" — which is why these cuts take no ellipsis.
+ */
+const CLAUSE_BREAK = /\s(?:\(|—|-\s)|:\s|\s(?:via|and|for|with|using|in|across|over|from|of|by|to)\s/i;
+
+/**
+ * A concept name trimmed to fit a node.
+ *
+ * Concept names are written for a reader with the whole file in front of them, so
+ * they run long and some carry a `Concept: ` prefix from the synthesis prompt.
+ * "Reciprocal-Rank Fusion for Workspace Federation" is a fine node title in `graft
+ * viz` and unreadable inside a circle.
+ */
+export function shortLabel(label: string): string {
+ const bare = label.replace(/^concepts?:\s*/i, "").trim();
+ if (bare.length <= MAX_LABEL) return bare;
+
+ const at = CLAUSE_BREAK.exec(bare);
+ if (at && at.index >= 8 && at.index <= MAX_LABEL) return bare.slice(0, at.index).trimEnd();
+
+ // No usable joint: a word-boundary cut, marked, because this one really does stop
+ // mid-phrase and a reader must not take the fragment for the whole name.
+ const cut = bare.lastIndexOf(" ", MAX_LABEL);
+ return `${bare.slice(0, cut > MAX_LABEL / 2 ? cut : MAX_LABEL).trimEnd()}…`;
+}
+
+/** The parent directory of a directory label, or "" at the top level. */
+export function parentDir(dir: string): string {
+ const trimmed = dir.replace(/\/$/, "");
+ const cut = trimmed.lastIndexOf("/");
+ return cut === -1 ? "" : `${trimmed.slice(0, cut)}/`;
+}
+
+/** Fallback label: the file's directory, or `(root)` for a top-level file. */
+export function dirLabel(path: string): string {
+ const cut = path.lastIndexOf("/");
+ return cut === -1 ? "(root)" : path.slice(0, cut) + "/";
+}
diff --git a/src/blast/name.ts b/src/blast/name.ts
new file mode 100644
index 00000000..589a0eba
--- /dev/null
+++ b/src/blast/name.ts
@@ -0,0 +1,263 @@
+/**
+ * Naming the clusters a diff reaches — the rung of the ladder between a concept
+ * node and the symbol backstop (see {@link LabelSource}).
+ *
+ * The point is scope. Getting labels from `build --deep` means summarising every
+ * file in the repo — 356 calls and thirteen minutes on graft's own repo — to put
+ * names on the six clusters a PR actually touches, and it still misses: only 40% of
+ * this repo's files are claimed by a concept, so the rest fall back to a path. Here
+ * the unit of work is the cluster, not the file: one request names all of them from
+ * data the graph already holds (paths and symbol names — no file reads), and the
+ * answer is cached by content hash so the next PR pays nothing for a cluster whose
+ * files did not change.
+ *
+ * Two rules keep it honest:
+ * - a cluster spanning unrelated features must come back "mixed", and then keeps
+ * its symbol backstop rather than a flattering name;
+ * - a failure of any kind — no key, spent quota, refused call, malformed answer —
+ * leaves every label exactly as it was and never fails the caller.
+ */
+import { createHash } from "node:crypto";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { CACHE_DIR } from "../context/node-file.js";
+import type { ChatModel } from "../ai/llm/types.js";
+import type { GraphV1 } from "../graph/types.js";
+import type { BlastReport, ChangedArea, ImpactedModule } from "./blast.js";
+import { shortLabel } from "./modules.js";
+
+/** One cluster to name: its identity, its files and the symbols inside it. */
+export interface Cluster {
+ key: string;
+ files: string[];
+ symbols: string[];
+}
+
+/** Anything that can turn clusters into names. A model in production, a stub in tests. */
+export interface Namer {
+ /** Names by cluster key. A key the namer chose not to name is simply absent. */
+ name(clusters: Cluster[]): Promise<Map<string, string>>;
+}
+
+export interface NameStats {
+ /** Labels taken from the cache, and labels that cost a call. */
+ cached: number;
+ named: number;
+ /** Clusters the namer declined ("mixed") or could not answer for. */
+ declined: number;
+ /** Set when naming was attempted and failed outright; the reason, for one line
+ * in the report. Never thrown: a comment without names still beats no comment. */
+ error?: string;
+}
+
+const SYSTEM_PROMPT = `You name parts of a codebase for a pull-request reviewer.
+
+You are given clusters of files that a change can affect. For each cluster, answer with the FEATURE or SUBSYSTEM those files implement, as a developer on the team would refer to it in conversation.
+
+Rules:
+- 2 to 4 words, Title Case. No trailing "Module", "System", "Layer", "Manager" or "Handler" unless the team would genuinely say it.
+- Name the RESPONSIBILITY, not the mechanics: "Query Freshness Gate", "Workspace Federation", "Asset Bundling". Never restate a path or a directory name, and never name it after the language or the file type.
+- If the files in a cluster serve two or more unrelated responsibilities, answer exactly "mixed" for that cluster. A wrong name is worse than no name, because a reviewer will trust it.
+- Answer for every cluster key you are given, and invent no other keys.`;
+
+const NAMES_SCHEMA = {
+ type: "object",
+ properties: {
+ names: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ key: { type: "string", description: "the cluster key, copied verbatim" },
+ name: { type: "string", description: '2-4 word Title Case name, or "mixed"' },
+ },
+ required: ["key", "name"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["names"],
+ additionalProperties: false,
+} as const;
+
+/** Symbols shown per cluster. Enough to characterise it; not a file listing. */
+const SYMBOLS_PER_CLUSTER = 8;
+
+/**
+ * Clusters per request. A PR's diagram needs six, so one batch covers it — the cap
+ * is for the cache-priming job, which deliberately walks a wide diff and can hand
+ * over fifty clusters at once. Past a dozen the prompt stops being a list and the
+ * model starts dropping keys.
+ */
+const CLUSTERS_PER_CALL = 12;
+
+function clusterPrompt(clusters: Cluster[]): string {
+ return clusters
+ .map((c) => {
+ const files = c.files.slice(0, 10).join(", ");
+ const symbols = c.symbols.slice(0, SYMBOLS_PER_CLUSTER).join(", ");
+ return `key: ${c.key}\n files: ${files}\n symbols: ${symbols || "(none extracted)"}`;
+ })
+ .join("\n\n");
+}
+
+/** The production namer: one forced-tool call for every cluster at once. */
+export class ChatNamer implements Namer {
+ constructor(private readonly model: ChatModel) {}
+
+ async name(clusters: Cluster[]): Promise<Map<string, string>> {
+ const res = await this.model.create({
+ messages: [
+ { role: "system", content: SYSTEM_PROMPT },
+ { role: "user", content: clusterPrompt(clusters) },
+ ],
+ tools: [{ name: "record_names", description: "Record one name per cluster.", parameters: NAMES_SCHEMA as unknown as Record<string, unknown> }],
+ responseFormat: { kind: "tool", name: "record_names" },
+ temperature: 0,
+ maxTokens: 1024,
+ });
+
+ const out = new Map<string, string>();
+ const call = res.toolCalls[0]?.args as { names?: { key?: string; name?: string }[] } | undefined;
+ for (const row of call?.names ?? []) {
+ if (!row?.key || !row?.name) continue;
+ const clean = sanitize(row.name);
+ // "mixed" is an answer, not a name: the cluster keeps its backstop.
+ if (!clean || /^mixed$/i.test(clean)) continue;
+ out.set(row.key, clean);
+ }
+ return out;
+ }
+}
+
+/**
+ * A model-written string on its way into a Mermaid label and a markdown table.
+ *
+ * Symbol names from a fork's diff reach the prompt, so the answer is untrusted
+ * input: anything that could close a label, open a tag or start a table cell is
+ * stripped here rather than at each render site.
+ */
+export function sanitize(raw: string): string {
+ const flat = raw.replace(/[\r\n]+/g, " ").replace(/[<>"'`|(){}[\]#]/g, "").replace(/\s+/g, " ").trim();
+ return shortLabel(flat);
+}
+
+/**
+ * The cache key for a cluster: what it contains, not what it is called.
+ *
+ * Member paths pin the shape and each member's `body_hash` pins the content, so a
+ * cluster is renamed only when the code in it actually changes. Without this the
+ * same area gets a slightly different name on every PR and two comments stop being
+ * comparable — the failure the cache exists to prevent.
+ */
+export function clusterHash(files: string[], hashes: Map<string, string>): string {
+ const parts = [...files].sort().map((f) => `${f}:${hashes.get(f) ?? "?"}`);
+ return createHash("sha256").update(parts.join("\n")).digest("hex").slice(0, 16);
+}
+
+function cachePath(contextDir: string): string {
+ return join(contextDir, CACHE_DIR, "areas.json");
+}
+
+export function loadNameCache(contextDir: string): Record<string, string> {
+ try {
+ const raw = JSON.parse(readFileSync(cachePath(contextDir), "utf8")) as unknown;
+ return raw && typeof raw === "object" ? (raw as Record<string, string>) : {};
+ } catch {
+ // A missing or corrupt cache is a cache miss, never an error: the names are
+ // derivable again, and refusing to run because a cache file is bad is worse.
+ return {};
+ }
+}
+
+export function saveNameCache(contextDir: string, names: Record<string, string>): void {
+ const path = cachePath(contextDir);
+ try {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, `${JSON.stringify(names, null, 2)}\n`);
+ } catch {
+ // Best-effort: an unwritable cache costs a call next time, nothing more.
+ }
+}
+
+/** File-node content hashes, which is what a cluster's identity is built from. */
+function fileHashes(graph: GraphV1): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const n of graph.nodes) if (n.kind === "file") out.set(n.path, n.body_hash ?? "");
+ return out;
+}
+
+type Labelled = ImpactedModule | ChangedArea;
+
+function symbolsOf(c: Labelled): string[] {
+ return "symbols" in c ? c.symbols.map((s) => s.name) : c.seedNames;
+}
+
+/**
+ * Fill in labels for every cluster still sitting on its symbol backstop.
+ *
+ * Clusters already named by a concept node are left alone: a concept was written
+ * from whole file bodies, which is strictly more than the paths and symbol names
+ * this pass can see.
+ */
+export async function applyNames(
+ graph: GraphV1,
+ report: BlastReport,
+ opts: { namer?: Namer; contextDir: string },
+): Promise<NameStats> {
+ const stats: NameStats = { cached: 0, named: 0, declined: 0 };
+ // `testModules` are deliberately absent: the comment shows them as a file count in
+ // one collapsed line and nowhere else, so naming them buys nothing and can push a
+ // normal PR over CLUSTERS_PER_CALL into a second request.
+ const targets: Labelled[] = [...report.modules, ...report.areas]
+ .filter((c) => c.labelSource === "symbol");
+ if (targets.length === 0) return stats;
+
+ const hashes = fileHashes(graph);
+ const cache = loadNameCache(opts.contextDir);
+ const pending: { cluster: Cluster; targets: Labelled[] }[] = [];
+ /** Clusters sharing a hash share a name — and one call, not several. */
+ const byHash = new Map<string, Labelled[]>();
+ for (const t of targets) {
+ const hash = clusterHash(t.files, hashes);
+ byHash.set(hash, [...(byHash.get(hash) ?? []), t]);
+ }
+
+ for (const [hash, group] of byHash) {
+ const hit = cache[hash];
+ if (hit) {
+ for (const t of group) { t.label = hit; t.labelSource = "named"; }
+ stats.cached++;
+ continue;
+ }
+ pending.push({
+ cluster: { key: hash, files: group[0].files, symbols: symbolsOf(group[0]) },
+ targets: group,
+ });
+ }
+
+ if (pending.length === 0 || !opts.namer) return stats;
+
+ const named = new Map<string, string>();
+ for (let i = 0; i < pending.length; i += CLUSTERS_PER_CALL) {
+ const batch = pending.slice(i, i + CLUSTERS_PER_CALL);
+ try {
+ for (const [k, v] of await opts.namer.name(batch.map((p) => p.cluster))) named.set(k, v);
+ } catch (err) {
+ // Every label already holds its backstop, so there is nothing to undo — and a
+ // later batch failing must not discard the names an earlier one returned.
+ stats.error = err instanceof Error ? err.message : String(err);
+ break;
+ }
+ }
+
+ for (const p of pending) {
+ const name = named.get(p.cluster.key);
+ if (!name) { stats.declined++; continue; }
+ for (const t of p.targets) { t.label = name; t.labelSource = "named"; }
+ cache[p.cluster.key] = name;
+ stats.named++;
+ }
+ if (stats.named > 0) saveNameCache(opts.contextDir, cache);
+ return stats;
+}
diff --git a/src/blast/render.ts b/src/blast/render.ts
new file mode 100644
index 00000000..6e77b41d
--- /dev/null
+++ b/src/blast/render.ts
@@ -0,0 +1,326 @@
+/**
+ * Renderers for a {@link BlastReport}: the Mermaid+markdown comment body a CI job
+ * posts, and a plain-text report for a terminal.
+ *
+ * The diagram is the product here — a reviewer should see which areas a change
+ * reaches, and whether its tests moved, before reading a single path — so the
+ * markdown leads with it and keeps every per-symbol list collapsed underneath.
+ * GitHub renders Mermaid natively in comments, so there is nothing to host.
+ *
+ * Both sides of the diagram are drawn at the same grain: areas, not files. The
+ * first version drew one box per changed file, which cannot fit a real PR (24 files
+ * 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";
+
+/** Diagram cap. Everything past it folds into one aggregate circle carrying the
+ * dropped counts, so the picture shrinks but never lies. */
+const MAX_MODULE_BOXES = 5;
+/** Rows in the table under the diagram. */
+const MAX_TABLE_ROWS = 6;
+/** Symbols listed in the one collapsed list of everything. */
+const MAX_SYMBOLS_LISTED = 60;
+
+/**
+ * A quoted Mermaid label. Every line is escaped on its own and only then joined
+ * with `<br/>` — escaping the joined string would eat the tag's own angle brackets
+ * and render the literal text "br/" inside the node.
+ */
+function label(...lines: string[]): string {
+ return `"${lines.map(escapeLabel).join("<br/>")}"`;
+}
+
+/** Quotes end a Mermaid label, and angle brackets would inject markup into it. */
+function escapeLabel(text: string): string {
+ return text.replace(/"/g, "#quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
+
+const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
+
+function depthLabel(depth: number): string {
+ return Number.isFinite(depth) ? `depth ${depth}` : "full closure";
+}
+
+/**
+ * Node colours, taken from `graft viz`'s own palette (viewer/style.css) so the two
+ * pictures of the same graph read as one thing: teal is "depends on your change"
+ * (`--k-method`), grey is the overflow circle (`--edge`). One hue for one kind of
+ * thing, now that the diff itself is not drawn. Fill AND text colour are set
+ * explicitly, because a GitHub comment renders in either theme and a node that
+ * inherits one of them is illegible in the other.
+ */
+const VIZ = {
+ reachedFill: "#D9EDF3", reachedStroke: "#3AA7C9", reachedInk: "#0E313C",
+ tailFill: "#EEF2F3", tailStroke: "#9AA4A9", tailInk: "#3A4247",
+} as const;
+
+/** The glyph carried on a changed circle. Meaning lives in the diagram's key. */
+const TEST_GLYPH: Record<TestSignal, string> = { changed: "✓", stale: "⚠", none: "✗", na: "–" };
+
+/**
+ * The diagram: one circle per area that can be affected, and nothing else.
+ *
+ * Everything about the changed side is gone on purpose. Drawing which of your edits
+ * reaches which area is a many-to-many relation, so it can only ever render as a
+ * mesh — nine arrows over eleven circles at its tidiest — and the reviewer has to
+ * trace lines to read it. That relation still exists in the table's "Reached from"
+ * column, where a reader can look it up when they want it, so the picture is free
+ * to answer the only question it is asked at a glance: what can break?
+ *
+ * `TB`, not `LR`: with no edges, top-bottom is what lays unconnected nodes out as a
+ * row instead of a tall column.
+ *
+ * Returns null when there is nothing to draw — an empty diagram frame reads as a
+ * broken renderer, and the caller has a sentence for "no dependents found".
+ */
+export function mermaidDiagram(r: BlastReport): string | null {
+ const shown = r.modules.slice(0, MAX_MODULE_BOXES);
+ if (shown.length === 0) return null;
+ const hidden = r.modules.slice(MAX_MODULE_BOXES);
+
+ const lines = ["flowchart TB"];
+ shown.forEach((m, i) => {
+ lines.push(` A${i}((${label(m.label, plural(m.symbols.length, "symbol"))}))`);
+ });
+ const TAIL = "AX";
+ if (hidden.length > 0) {
+ const symbols = hidden.reduce((n, m) => n + m.symbols.length, 0);
+ lines.push(` ${TAIL}((${label(plural(hidden.length, "smaller area"), plural(symbols, "symbol"))}))`);
+ }
+
+ lines.push(` classDef reached fill:${VIZ.reachedFill},stroke:${VIZ.reachedStroke},stroke-width:1.5px,color:${VIZ.reachedInk};`);
+ lines.push(` class ${shown.map((_, i) => `A${i}`).join(",")} reached;`);
+ if (hidden.length > 0) {
+ lines.push(` classDef tail fill:${VIZ.tailFill},stroke:${VIZ.tailStroke},stroke-width:1px,color:${VIZ.tailInk};`);
+ lines.push(` class ${TAIL} tail;`);
+ }
+ return lines.join("\n");
+}
+
+/** The PR-comment body: diagram, then one table, then everything else collapsed. */
+export function markdownReport(r: BlastReport): string {
+ const out: string[] = [];
+ const symbols = r.modules.reduce((n, m) => n + m.symbols.length, 0);
+
+ out.push("### 🌱 graft blast radius");
+ out.push("");
+ out.push(headline(r, symbols));
+ const testLine = testHeadline(r);
+ if (testLine) out.push(testLine);
+
+ if (symbols > 0) {
+ const diagram = mermaidDiagram(r);
+ if (diagram) {
+ out.push("");
+ out.push("```mermaid");
+ out.push(diagram);
+ out.push("```");
+ }
+ out.push("");
+ out.push(...impactTable(r));
+ }
+
+ out.push("");
+ out.push(...detailSections(r, symbols));
+
+ const caveats = caveatLines(r);
+ if (caveats.length > 0) {
+ out.push("");
+ for (const line of caveats) out.push(line);
+ }
+ out.push("");
+ out.push(`<sub>\`graft blast\` · ${r.basis} · ${depthLabel(r.depth)} · ${plural(r.changed.length, "changed file")}</sub>`);
+ return out.join("\n") + "\n";
+}
+
+function headline(r: BlastReport, symbols: number): string {
+ const areas = plural(r.areas.length, "area");
+ if (symbols === 0) {
+ return `**Nothing outside this diff depends on it.** ${areas} changed; no indexed dependents at ${depthLabel(r.depth)}.`;
+ }
+ return `**${areas} changed → ${plural(r.modules.length, "area")} can be affected.** ${plural(symbols, "dependent symbol")}, ${depthLabel(r.depth)}.`;
+}
+
+/**
+ * One sentence on whether the diff brought its tests. Leads with the areas that
+ * have no tests at all, since that is the only state worth a reviewer's comment.
+ */
+function testHeadline(r: BlastReport): string | null {
+ if (r.areas.length === 0) return null;
+ const none = r.areas.filter((a) => a.tests === "none");
+ const stale = r.areas.filter((a) => a.tests === "stale");
+ const changed = r.areas.filter((a) => a.tests === "changed");
+ const parts: string[] = [];
+ if (none.length > 0) parts.push(`**no test reaches ${none.map((a) => a.label).join(", ")}**`);
+ if (stale.length > 0) parts.push(`${stale.map((a) => a.label).join(", ")} ${stale.length === 1 ? "has tests" : "have tests"} the diff did not touch`);
+ if (changed.length > 0) parts.push(`${plural(changed.length, "area")} updated ${changed.length === 1 ? "its" : "their"} tests`);
+ if (parts.length === 0) return null;
+ return `Tests: ${parts.join("; ")}.`;
+}
+
+/**
+ * The table replaces 31 collapsed sections that held one bullet each. One row per
+ * affected area, with the nearest symbol to start reading at — a reviewer wants a
+ * place to look, not an inventory.
+ */
+function impactTable(r: BlastReport): string[] {
+ const shown = r.modules.slice(0, MAX_TABLE_ROWS);
+ const hidden = r.modules.slice(MAX_TABLE_ROWS);
+ const areaOf = new Map<string, string>();
+ for (const a of r.areas) for (const f of a.files) areaOf.set(f, a.label);
+
+ const rows = ["| Can be affected | Symbols | Nearest hop | Reached from |", "| --- | --: | --- | --- |"];
+ for (const mod of shown) {
+ const nearest = mod.symbols[0];
+ const hop = nearest ? `\`${nearest.path}:${nearest.span}\` ${nearest.name} — ${nearest.relation}, depth ${nearest.depth}` : "—";
+ // Two names, then a count. Six area names in one cell is what turned this
+ // column into a wall wider than the rest of the table put together.
+ const names = [...new Set(mod.from.map((f) => areaOf.get(f) ?? f))];
+ const from = names.length === 0 ? "—"
+ : names.length <= 2 ? names.join(", ")
+ : `${names.slice(0, 2).join(", ")} +${names.length - 2}`;
+ rows.push(`| ${mod.label} | ${mod.symbols.length} | ${hop} | ${from} |`);
+ }
+ if (hidden.length > 0) {
+ const symbols = hidden.reduce((n, m) => n + m.symbols.length, 0);
+ rows.push(`| _${plural(hidden.length, "smaller area")}_ | ${symbols} | ${hidden.slice(0, 3).map((m) => m.label).join(", ")}${hidden.length > 3 ? ", …" : ""} | see below |`);
+ }
+ return rows;
+}
+
+/**
+ * Everything a reviewer might want and nobody reads by default, in three sections.
+ *
+ * The blank line after each `</summary>` is required: GitHub renders no markdown
+ * 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[] {
+ const out: string[] = [];
+
+ if (symbols > 0) {
+ out.push("<details>");
+ out.push(`<summary><strong>All ${plural(symbols, "dependent symbol")}</strong>, grouped by area</summary>`);
+ out.push("");
+ let listed = 0;
+ for (const mod of r.modules) {
+ out.push(`**${mod.label}** — ${plural(mod.symbols.length, "symbol")} in ${plural(mod.files.length, "file")}`);
+ out.push("");
+ 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})`);
+ }
+ out.push("");
+ if (listed >= MAX_SYMBOLS_LISTED) {
+ out.push(`…${plural(symbols - listed, "further symbol")} not listed.`);
+ out.push("");
+ break;
+ }
+ }
+ out.push("</details>");
+ }
+
+ if (r.areas.length > 0) {
+ const by = (s: TestSignal) => r.areas.filter((a) => a.tests === s).length;
+ const states = [
+ by("changed") > 0 ? `${by("changed")} ✓` : "",
+ by("stale") > 0 ? `${by("stale")} ⚠` : "",
+ by("none") > 0 ? `${by("none")} ✗` : "",
+ by("na") > 0 ? `${by("na")} –` : "",
+ ].filter(Boolean).join(" · ");
+ out.push("<details>");
+ out.push(`<summary><strong>Test signal</strong> per changed area — ${states}</summary>`);
+ out.push("");
+ // The caveat leads, because the ratios below invite being read as coverage: a
+ // test that drives the CLI in a subprocess produces no edge at all, so a
+ // well-tested area can honestly report 1 of 25.
+ out.push("_Reached = a node under a test path has a resolved edge into the changed symbol. It undercounts anything called indirectly — through a CLI, a spawned process or a dynamic import — so read a low ratio as “look here”, never as a coverage gate._");
+ out.push("");
+ for (const a of r.areas) {
+ const bits = a.behavioural > 0 ? [`${a.reached} of ${a.behavioural} reached`] : [];
+ if (a.changedTestFiles.length > 0) bits.push(`${plural(a.changedTestFiles.length, "test file")} changed here: ${a.changedTestFiles.map((f) => `\`${f}\``).join(", ")}`);
+ else if (a.testFiles.length > 0) bits.push(`${plural(a.testFiles.length, "test file")} ${a.testFiles.length === 1 ? "reaches" : "reach"} it, none changed here`);
+ else if (a.behavioural > 0) bits.push("no test file reaches it");
+ else bits.push("no function, method or class changed here");
+ out.push(`- ${TEST_GLYPH[a.tests]} **${a.label}** — ${bits.join(" · ")}`);
+ if (a.unreached.length > 0) {
+ out.push(` - not reached: ${a.unreached.slice(0, 8).map((n) => `\`${n}\``).join(", ")}${a.unreached.length > 8 ? `, …${a.unreached.length - 8} more` : ""}`);
+ }
+ }
+ out.push("");
+ out.push("</details>");
+ }
+
+ if (r.testModules.length > 0) {
+ const symbolCount = r.testModules.reduce((n, m) => n + m.symbols.length, 0);
+ const files = new Set(r.testModules.flatMap((m) => m.files));
+ out.push("<details>");
+ out.push(`<summary>${plural(files.size, "test suite")} also ${files.size === 1 ? "references" : "reference"} this code</summary>`);
+ out.push("");
+ out.push(`${plural(symbolCount, "symbol")}, kept out of the diagram and the table so they cannot crowd out the areas a reviewer has to look at.`);
+ out.push("");
+ for (const f of [...files].sort().slice(0, 20)) out.push(`- \`${f}\``);
+ if (files.size > 20) out.push(`- …${files.size - 20} more`);
+ out.push("");
+ out.push("</details>");
+ }
+
+ return out;
+}
+
+/**
+ * What the report cannot see. These are the lines that keep a diagram honest: a
+ * reader who is not told that four changed files are unindexed will read "no
+ * dependents" as "safe".
+ */
+function caveatLines(r: BlastReport): string[] {
+ const out: string[] = [];
+ if (r.deleted.length > 0) {
+ out.push(
+ `⚠️ ${plural(r.deleted.length, "deleted file")} (${r.deleted.slice(0, 5).join(", ")}) — ` +
+ "their dependents cannot be computed from a graph built at this commit, since the files are gone from it.",
+ );
+ }
+ if (r.unindexed.length > 0) {
+ out.push(
+ `⚠️ ${plural(r.unindexed.length, "changed file")} not in the graph (${r.unindexed.slice(0, 5).join(", ")}) — ` +
+ "no parser claims the extension, or the index predates the file.",
+ );
+ }
+ return out;
+}
+
+/** Terminal report: same content, no markdown scaffolding. */
+export function textReport(r: BlastReport): string {
+ const symbols = r.modules.reduce((n, m) => n + m.symbols.length, 0);
+ const lines = [
+ `blast radius — ${r.basis} (${depthLabel(r.depth)})`,
+ ` changed: ${plural(r.changed.length, "file")} in ${plural(r.areas.length, "area")}, ${plural(r.seeds.length, "seed symbol")}`,
+ ` impacted: ${plural(symbols, "symbol")} in ${plural(r.modules.length, "area")}`,
+ "",
+ ];
+
+ for (const a of r.areas) {
+ lines.push(`${TEST_GLYPH[a.tests]} ${a.label} — ${plural(a.files.length, "changed file")}, ${a.reached}/${a.behavioural} reached by a test`);
+ }
+ if (r.areas.length > 0) lines.push("");
+
+ for (const mod of r.modules) {
+ lines.push(`${mod.label} — ${plural(mod.symbols.length, "symbol")} in ${plural(mod.files.length, "file")}`);
+ for (const s of mod.symbols.slice(0, 25)) {
+ lines.push(` ${s.relation} ← ${s.name} (${s.path}:${s.span}) [depth ${s.depth}]`);
+ }
+ const hidden = mod.symbols.length - 25;
+ if (hidden > 0) lines.push(` …${plural(hidden, "more symbol")}`);
+ lines.push("");
+ }
+ if (symbols === 0) lines.push("no indexed dependents outside the changed files themselves", "");
+ if (r.testModules.length > 0) {
+ const files = new Set(r.testModules.flatMap((m) => m.files));
+ lines.push(`${plural(files.size, "test suite")} also ${files.size === 1 ? "references" : "reference"} this code (not listed)`, "");
+ }
+ for (const line of caveatLines(r)) lines.push(line.replace(/⚠️ /, "⚠ "), "");
+ return lines.join("\n").replace(/\n+$/, "\n");
+}
+
diff --git a/src/cli.ts b/src/cli.ts
index d0ce96db..6918ce53 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -184,6 +184,7 @@ program
.option("-j, --concurrency <n>", "files summarized in parallel during --deep (default 5)")
.option("--no-reuse", "re-parse every file instead of replaying unchanged ones from the extraction cache")
.option("--lsp", "add compiler-grade call edges via a language server if one is installed (opt-in, slower; e.g. rust-analyzer, clangd)")
+ .option("--allow-partial", "with --deep: exit 0 even when some files' summaries failed (default: a degraded meaning tier exits 1)")
.option(
"--follow-submodules",
"include initialized Git submodules recursively; persisted for later builds and automatic refreshes",
@@ -207,6 +208,7 @@ program
concurrency?: string;
reuse?: boolean;
lsp?: boolean;
+ allowPartial?: boolean;
includeDir?: string[];
followSubmodules?: boolean;
},
@@ -288,6 +290,8 @@ program
}
// --deep: concept nodes first, then the wiring graph links cards up to them.
+ let conceptErrors: string[] = [];
+ let conceptFatal: string | undefined;
if (deep) {
const c = await engine.init(dir, {
extensions: opts.extensions,
@@ -301,6 +305,8 @@ program
`✓ concepts: ${c.nodes} nodes, ${c.links} links from ${c.files} files (${c.summarized} read, ${c.cached} cached)`,
);
for (const e of c.errors) console.error(`✗ ${e}`);
+ conceptErrors = c.errors;
+ conceptFatal = c.fatal;
}
// Wiring graph — always; LLM meaning only with --deep.
@@ -328,6 +334,37 @@ program
const rel = relative(process.cwd(), g.contextDir) || "graft";
console.log(` ${rel}/ is git-ignored (added automatically) — a local cache; teammates run \`graft build\` to get their own.`);
+
+ // #127: a --deep run whose LLM calls failed used to print the same success
+ // footer and exit 0, so a quota-exhausted build looked identical to a clean
+ // one and `graft check` still said "in sync" (it only ever checked Tier-1).
+ // The structural graph IS still written and every successful summary is
+ // cached, so this is a loud warning about a degraded tier, not a rollback.
+ if (deep) {
+ const m = g.meaning;
+ const failed =
+ m.failedFiles > 0 || m.fatal !== undefined || conceptErrors.length > 0 || conceptFatal !== undefined;
+ if (failed) {
+ const ready = m.computed + m.cached;
+ const total = ready + m.stale + m.pending;
+ const pct = total > 0 ? Math.round((ready / total) * 100) : 0;
+ console.error("");
+ console.error(`✗ the deep pass did not complete — the meaning tier is incomplete.`);
+ if (conceptFatal) console.error(` concepts: ${conceptFatal}`);
+ if (m.fatal) console.error(` summaries: ${m.fatal}`);
+ if (m.failedFiles > 0) {
+ const skipped = m.skippedFiles > 0 ? `, ${m.skippedFiles} never attempted` : "";
+ console.error(` ${m.failedFiles} file(s) failed to summarize${skipped}.`);
+ }
+ if (conceptErrors.length > 0) console.error(` ${conceptErrors.length} concept-pass error(s).`);
+ console.error(` meaning coverage: ${ready}/${total} symbols (${pct}%).`);
+ console.error(
+ " Nothing computed was lost: re-run `graft build --deep` to resume from what is cached.\n" +
+ " Pass --allow-partial to accept a degraded meaning tier and exit 0.",
+ );
+ if (!opts.allowPartial) process.exitCode = 1;
+ }
+ }
});
program
@@ -434,7 +471,9 @@ program
.argument(...DIR_ARG)
.option("-p, --port <port>", "port to serve on", "4400")
.option("--no-open", "don't open the browser")
- .action(async (dirArg: string | undefined, opts: { port: string; open: boolean }) => {
+ .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 }) => {
const dir = queryRoot(dirArg);
const { existsSync } = await import("node:fs");
const { resolve, basename } = await import("node:path");
@@ -451,6 +490,23 @@ program
process.exit(1);
}
const viewerDir = fileURLToPath(new URL("./viewer/", import.meta.url)); // prebuilt
+
+ if (opts.export) {
+ const { exportViz } = await import("./viz/export.js");
+ const out = exportViz({
+ contextDir,
+ viewerDir,
+ outDir: resolve(opts.export),
+ repoName: basename(root),
+ subtitle: opts.title,
+ });
+ const kb = Math.round(out.bytes / 1024);
+ console.log(
+ `graft viz → ${out.file} (${kb} kB, ${out.contextNodes} concept nodes, ${out.codeNodes} code nodes)`,
+ );
+ return;
+ }
+
const srv = await startVizServer({
contextDir,
viewerDir,
@@ -517,6 +573,31 @@ program
},
);
+program
+ .command("blast")
+ .description(
+ "Blast radius of a diff: what depends on the lines this change touched ($0, no LLM). " +
+ "Built for CI — `--format markdown` is a PR comment with a Mermaid diagram.",
+ )
+ .argument(...DIR_ARG)
+ .option("--base <ref>", "diff against this ref's merge base with HEAD (e.g. origin/main); default: the working tree vs HEAD")
+ .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(...NO_REFRESH_FLAG)
+ .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; refresh?: boolean }) => {
+ const dir = queryRoot(dirArg);
+ await refreshBefore(dir, opts);
+ const { runBlastCommand } = await import("./blast/blast-cli.js");
+ await runBlastCommand(dir, {
+ base: opts.base,
+ depth: opts.depth,
+ format: opts.format,
+ name: opts.name,
+ globalDir: program.opts<GlobalOpts>().dir,
+ });
+ });
+
program
.command("grep")
.description("Regex search over indexed files, hits grouped by enclosing symbol and ranked by coupling ($0, no LLM)")
diff --git a/src/context/build.ts b/src/context/build.ts
index da6c3ace..f6440803 100644
--- a/src/context/build.ts
+++ b/src/context/build.ts
@@ -19,6 +19,7 @@ import { relPosix } from "../util/paths.js";
import { readSourceFile } from "../util/source.js";
import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";
import type { Summarizer } from "../ai/summarize.js";
+import { LlmFailureGate } from "../ai/failure.js";
import type { FileSummary, SynthNode, Synthesizer } from "../ai/synthesize.js";
import {
CACHE_DIR,
@@ -77,6 +78,12 @@ export interface BuildResult {
nodes: number;
links: number;
errors: string[];
+ /** Files whose summary call failed, and files never attempted once the pass gave
+ * up — reported as data so the CLI can exit non-zero without reading messages (#127). */
+ failedFiles: number;
+ skippedFiles: number;
+ /** Why the summarize phase stopped early, when it did. */
+ fatal?: string;
}
/** The gitignored LLM-call cache: per-file summaries + per-batch synthesis. */
@@ -135,9 +142,17 @@ export async function buildContext(dir: string, opts: BuildOptions): Promise<Bui
nodes: 0,
links: 0,
errors: [],
+ failedFiles: 0,
+ skippedFiles: 0,
};
// Phase 1: summarize each file, concurrent, content-hash cached.
+ //
+ // The gate is shared with the crux pass (`graph/enrich.ts`): once the provider has
+ // clearly stopped serving — a spent quota, a rejected key — the remaining files are
+ // not attempted. This pass is where #127's 1,617 doomed calls were spent, one per
+ // file, before the build exited 0.
+ const gate = new LlmFailureGate();
const work = await mapWithConcurrency(files, Math.max(1, opts.concurrency ?? 8), async (file, i): Promise<FileWork | undefined> => {
const rel = relPosix(root, file);
opts.onProgress?.({ phase: "summarize", index: i, total: files.length, file: rel });
@@ -156,17 +171,29 @@ export async function buildContext(dir: string, opts: BuildOptions): Promise<Bui
result.cached++;
return { rel, hash, summary: hit.summary };
}
+ // A cache hit is still served after the gate closes (it costs nothing) — only
+ // the call is skipped.
+ if (gate.stopped) {
+ gate.skip();
+ return { rel, hash };
+ }
try {
const summary = await opts.summarizer.summarize(code, { path: rel });
cache.summaries[rel] = { hash, summary };
result.summarized++;
maybeFlush();
+ gate.succeeded();
return { rel, hash, summary };
} catch (err) {
- result.errors.push(`${rel}: ${errMsg(err)}`);
+ const message = errMsg(err);
+ result.errors.push(`${rel}: ${message}`);
+ gate.record(message);
return { rel, hash }; // covered (counts against staleness) but not summarized
}
});
+ result.failedFiles = gate.failed;
+ result.skippedFiles = gate.skipped;
+ result.fatal = gate.fatal;
// Phase 1 done: persist every summary before the (also LLM-backed) synthesis
// phase, so an interruption there never discards phase-1 work.
diff --git a/src/graph/build.ts b/src/graph/build.ts
index 65a33773..059eb3a1 100644
--- a/src/graph/build.ts
+++ b/src/graph/build.ts
@@ -283,22 +283,14 @@ export async function buildGraph(
const edges = resolveEdges(nodes, rawEdges, { goModules: readGoModules(root, repoFiles) });
- // graph.json is its own Tier-2 cache: fold in the prior meaning layer so an
- // unchanged body is never re-summarized (and a Tier-1-only run never wipes it).
- const prior = readGraph(wiringPath(outDir));
- const priorById = new Map((prior?.nodes ?? []).map((n) => [n.id, n]));
- const meaning = await enrichGraph(nodes, priorById, sources, {
- summarizer: opts.summarizer,
- concurrency: opts.concurrency,
- onProgress: ({ index, total, node }) =>
- opts.onProgress?.({ phase: "enrich", index, total, file: node }),
- });
- errors.push(...meaning.errors);
-
// Guard 5 (minimum-substance): node counts aren't known until nodes are
// assembled, so the merge-tiny-scopes-into-root guard runs here.
const scopes = applyMinSubstanceGuard(discoveredScopes, nodes);
+ // Assemble the graph BEFORE the meaning pass, so the crux pass can checkpoint it to
+ // disk periodically (#128): crux/summary mutate node objects in place and never
+ // change the node/edge SET, so `meta` stays valid; the opt-in LSP pass below is the
+ // only thing that adds edges, and it runs before the final write.
const graph: GraphV1 = {
meta: {
version: 1,
@@ -311,6 +303,22 @@ export async function buildGraph(
edges,
};
+ // graph.json is its own Tier-2 cache: fold in the prior meaning layer so an
+ // unchanged body is never re-summarized (and a Tier-1-only run never wipes it).
+ // Read BEFORE the first checkpoint can overwrite wiring.json.
+ const prior = readGraph(wiringPath(outDir));
+ const priorById = new Map((prior?.nodes ?? []).map((n) => [n.id, n]));
+ const meaning = await enrichGraph(nodes, priorById, sources, {
+ summarizer: opts.summarizer,
+ concurrency: opts.concurrency,
+ onProgress: ({ index, total, node }) =>
+ opts.onProgress?.({ phase: "enrich", index, total, file: node }),
+ // Periodic durability flush of partial crux; the next run folds it back in by
+ // body_hash, so an interrupted --deep run never repays the crux it computed.
+ checkpoint: () => writeGraph(graph, outDir),
+ });
+ errors.push(...meaning.errors);
+
// Opt-in compiler-grade enrichment (adds lsp_resolved call edges in place).
// Runs on the assembled graph so callee positions map back to nodes; never
// touches the extraction cache (Tier-1 stays pristine, cold==incremental).
diff --git a/src/graph/check.ts b/src/graph/check.ts
index 59a602a8..d33a9437 100644
--- a/src/graph/check.ts
+++ b/src/graph/check.ts
@@ -36,6 +36,10 @@ export interface GraphCheckResult {
stale: string[];
/** Nodes never summarized (reported for context; not counted as drift). */
pending: number;
+ /** Committed nodes in total — the denominator that turns `pending` into a
+ * coverage figure. A deep build that lost most of its LLM calls (#127) is only
+ * distinguishable from a deliberate Tier-1 build by the SHARE that is missing. */
+ nodes: number;
}
export interface GraphCheckOptions {
@@ -61,6 +65,7 @@ export async function checkGraph(
changed: [],
stale: [],
pending: 0,
+ nodes: 0,
};
const committed = readGraph(wiringPath(outDir));
@@ -96,6 +101,7 @@ export async function checkGraph(
}
const committedById = new Map(committed.nodes.map((n) => [n.id, n]));
+ result.nodes = committedById.size;
for (const [id, node] of committedById) {
const now = current.get(id);
if (now === undefined) result.removed.push(id);
@@ -123,7 +129,12 @@ export function formatGraphCheckReport(r: GraphCheckResult): string {
return "graph check: NO GRAPH\n\nNo graft/.graph/wiring.json found. Run `graft build` first.";
}
if (r.ok) {
- const note = r.pending ? ` (${r.pending} node(s) not yet summarized — run \`graft build --deep\`)` : "";
+ // A share, not a bare count: "1203 not yet summarized" reads the same whether
+ // the repo was never deep-built or a deep build failed most of its calls.
+ const pct = r.nodes > 0 ? Math.round(((r.nodes - r.pending) / r.nodes) * 100) : 0;
+ const note = r.pending
+ ? ` (meaning tier ${pct}% complete — ${r.pending} of ${r.nodes} node(s) not yet summarized; run \`graft build --deep\`)`
+ : "";
return `graph check: OK — the wiring graph is in sync with the code.${note}`;
}
diff --git a/src/graph/enrich.ts b/src/graph/enrich.ts
index 3f7157a1..75598e19 100644
--- a/src/graph/enrich.ts
+++ b/src/graph/enrich.ts
@@ -20,6 +20,7 @@
* only and is never used to re-slice.
*/
import type { CruxSummarizer, NodeCrux, NodeRef } from "../ai/crux.js";
+import { LlmFailureGate } from "../ai/failure.js";
import type { Crux, NodeV1 } from "./types.js";
/** Cap on the stored crux: an over-long pick is trimmed to its leading slice. */
@@ -35,6 +36,21 @@ export interface EnrichOptions {
concurrency?: number;
/** Progress is reported per file (one LLM call each), as files finish — not per node. */
onProgress?: (info: { index: number; total: number; node: string }) => void;
+ /**
+ * Durability flush of the (partially) enriched graph, called from the per-file
+ * completion handler at most once every {@link CHECKPOINT_MS}. Without it, crux
+ * only reached wiring.json at build end, so an interrupted --deep run discarded
+ * every crux it had already computed and paid for (#128). Single-threaded, so it
+ * never interleaves with a node mutation.
+ */
+ checkpoint?: () => void;
+}
+
+/** How often the crux pass flushes partial progress to disk. Read at call time (not
+ * module load) so a test seam `GRAFT_CRUX_CHECKPOINT_MS=0` (flush on every completed
+ * file) takes effect. */
+function checkpointMs(): number {
+ return Number(process.env.GRAFT_CRUX_CHECKPOINT_MS ?? 15000);
}
export interface EnrichStats {
@@ -43,6 +59,16 @@ export interface EnrichStats {
stale: number; // body changed, left with an outdated summary (no LLM this run)
pending: number; // never summarized and not computed this run
errors: string[];
+ /** Files whose LLM call failed outright. The count `errors` used to only imply —
+ * a caller has to be able to decide "this build is degraded" without parsing
+ * message strings (#127). */
+ failedFiles: number;
+ /** Files never attempted, because {@link EnrichStats.fatal} stopped the pass. */
+ skippedFiles: number;
+ /** Set when the pass gave up early: quota/auth rejection, or a run of failures
+ * that says the provider is not going to start working. The reason is written
+ * for a human — it is what `graft build --deep` exits non-zero with. */
+ fatal?: string;
}
export async function enrichGraph(
@@ -51,7 +77,15 @@ export async function enrichGraph(
sources: Map<string, string>,
opts: EnrichOptions = {},
): Promise<EnrichStats> {
- const stats: EnrichStats = { cached: 0, computed: 0, stale: 0, pending: 0, errors: [] };
+ const stats: EnrichStats = {
+ cached: 0,
+ computed: 0,
+ stale: 0,
+ pending: 0,
+ errors: [],
+ failedFiles: 0,
+ skippedFiles: 0,
+ };
// Which nodes actually need an LLM call this run (after cache carry-over).
const dirty: NodeV1[] = [];
@@ -100,19 +134,47 @@ export async function enrichGraph(
const files = [...byFile.keys()];
const limit = Math.max(1, opts.concurrency ?? DEFAULT_CONCURRENCY);
let done = 0;
+ const flushEvery = checkpointMs();
+ let lastCheckpoint = Date.now();
+
+ // Shared with the concept pass (`context/build.ts`), so both agree on when a
+ // provider has stopped working. Counted across the whole pass, not per worker:
+ // with `-j 5` the interleaving is what a user sees as "everything is failing now".
+ const gate = new LlmFailureGate();
await mapWithConcurrency(files, limit, async (path) => {
const fileNodes = byFile.get(path)!;
const source = sources.get(path)!;
const lineCount = source.split("\n").length;
+ // Once the pass is fatal, the remaining files are not attempted: every call
+ // would fail the same way, and on a metered gateway each one still costs a
+ // request. They are counted so the caller can report what was left undone.
+ if (gate.stopped) {
+ gate.skip();
+ for (const node of fileNodes) {
+ if (node.summary_state === "stale") stats.stale++;
+ else stats.pending++;
+ }
+ // Still reported, so the caller's progress counter reaches `total` instead of
+ // freezing at the file that broke — the abort is announced by the build's
+ // summary, not by a stalled line.
+ opts.onProgress?.({ index: done++, total: files.length, node: path });
+ return;
+ }
+
const refs: NodeRef[] = fileNodes.map((n) => {
const [startLine, endLine] = spanLines(n.span, lineCount);
return { id: n.id, kind: n.kind, signature: n.signature, startLine, endLine };
});
const { results, error } = await collectFileCrux(summarizer, path, source, refs);
- if (error) stats.errors.push(`${path}: ${error}`);
+ if (error) {
+ stats.errors.push(`${path}: ${error}`);
+ gate.record(error);
+ } else {
+ gate.succeeded();
+ }
for (const node of fileNodes) {
const r = results.size > 0 ? results.get(node.id) : undefined;
@@ -130,8 +192,19 @@ export async function enrichGraph(
// Report on completion so the counter climbs monotonically under concurrency.
opts.onProgress?.({ index: done++, total: files.length, node: path });
+
+ // Flush partial crux to disk periodically, so a killed --deep run keeps what it
+ // has already computed (#128). Throttled by wall-clock; the caller's checkpoint
+ // writes wiring.json atomically, and the next run folds it back in by body_hash.
+ if (opts.checkpoint && Date.now() - lastCheckpoint >= flushEvery) {
+ lastCheckpoint = Date.now();
+ opts.checkpoint();
+ }
});
+ stats.failedFiles = gate.failed;
+ stats.skippedFiles = gate.skipped;
+ stats.fatal = gate.fatal;
return stats;
}
diff --git a/src/graph/write.ts b/src/graph/write.ts
index 8b993a88..ede60bb6 100644
--- a/src/graph/write.ts
+++ b/src/graph/write.ts
@@ -8,7 +8,7 @@
* timestamps, so rebuilding an unchanged repo produces a byte-identical file and
* git diffs stay minimal.
*/
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { EdgeV1, GraphV1, NodeV1 } from "./types.js";
@@ -41,7 +41,28 @@ export function writeGraph(graph: GraphV1, outDir: string): string {
};
const path = wiringPath(outDir);
mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, JSON.stringify(sorted, null, 2) + "\n");
+ // Atomic write (temp + rename): the crux pass now checkpoints wiring.json
+ // periodically (#128), and a --deep run is exactly what gets killed mid-flush
+ // (SIGTERM/CI timeout/laptop sleep). A partial writeFileSync would leave a
+ // truncated, unparseable graph; rename swaps it in atomically on the same fs.
+ //
+ // pid in the temp name, and removed when the write fails — the same discipline
+ // `writeJsonAtomic` (util/state.ts) documents: a fixed name lets a concurrent
+ // build (a manual `graft build` racing the refresh child) write the same scratch
+ // file and hand the loser a corrupt graph, and a failed rename would otherwise
+ // leave a full-size orphan behind that nothing ever cleans up.
+ const tmp = `${path}.${process.pid}.tmp`;
+ try {
+ writeFileSync(tmp, JSON.stringify(sorted, null, 2) + "\n");
+ renameSync(tmp, path);
+ } catch (e) {
+ try {
+ rmSync(tmp, { force: true });
+ } catch {
+ /* nothing more we can do */
+ }
+ throw e;
+ }
return path;
}
diff --git a/src/viz/export.ts b/src/viz/export.ts
new file mode 100644
index 00000000..4e2fcb42
--- /dev/null
+++ b/src/viz/export.ts
@@ -0,0 +1,115 @@
+/**
+ * `graft viz --export <dir>`: the same viewer, as one self-contained HTML file.
+ *
+ * This exists so a PR comment has somewhere real to point. A Mermaid diagram in a
+ * comment can hold about five circles before it stops being readable, and it can
+ * never hold the thing a reviewer actually wants next — click an area, see its
+ * dependent symbols at exact `file:line`. Every other tool in this space solved
+ * that the same way: keep a small table in the comment and link out to a hosted
+ * view. Exporting rather than hosting keeps graft's promise intact — no account, no
+ * server, no telemetry; the artifact is a file you can open with `file://`, publish
+ * to GitHub Pages, or attach to a build.
+ *
+ * The output inlines the CSS, the bundled JS and both graphs, because a file served
+ * from a Pages subdirectory cannot rely on absolute asset paths (`/app.js` resolves
+ * to the domain root, not the PR's folder) and a reader must not need a web server.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { assembleContextGraph } from "./assemble.js";
+
+export interface VizExportOptions {
+ contextDir: string;
+ /** Where index.html, app.js and style.css were bundled (dist/viewer). */
+ viewerDir: string;
+ /** Directory to write index.html into. Created if absent. */
+ outDir: string;
+ repoName: string;
+ /** Shown in the appbar beside the repo name — e.g. "PR #151". */
+ subtitle?: string;
+}
+
+export interface VizExportResult {
+ file: string;
+ bytes: number;
+ contextNodes: number;
+ codeNodes: number;
+ /** Tab the exported page opens on — see the reasoning in {@link exportViz}. */
+ defaultTab: "context" | "code";
+}
+
+/** The wiring graph as the viewer's endpoint would have served it, or null. */
+function codeGraph(contextDir: string): unknown {
+ const file = join(contextDir, ".graph", "wiring.json");
+ if (!existsSync(file)) return null;
+ try {
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as { meta?: { version?: number } };
+ return parsed?.meta?.version === 1 ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * JSON safe to drop inside a `<script>` element.
+ *
+ * `</script>` anywhere in the data — a summary quoting HTML, a symbol named after a
+ * tag — would close the element and spill the rest of the graph into the page as
+ * text. `<` is escaped as a unicode sequence, which is still valid JSON to the
+ * parser and inert to the HTML tokenizer.
+ */
+function inlineJson(value: unknown): string {
+ return JSON.stringify(value ?? null)
+ .replace(/</g, "\\u003c")
+ // Line and paragraph separators are legal in a JSON string and illegal in a
+ // JavaScript source line, so an unescaped one is a syntax error at load time.
+ .replace(/\u2028/g, "\\u2028")
+ .replace(/\u2029/g, "\\u2029");
+}
+
+export function exportViz(opts: VizExportOptions): VizExportResult {
+ const html = readFileSync(join(opts.viewerDir, "index.html"), "utf8");
+ const css = readFileSync(join(opts.viewerDir, "style.css"), "utf8");
+ const js = readFileSync(join(opts.viewerDir, "app.js"), "utf8");
+
+ const context = assembleContextGraph(opts.contextDir);
+ const code = codeGraph(opts.contextDir);
+
+ // Which tab to open on. The viewer starts on Context, which only a `--deep` build
+ // fills: a structural build writes wiring cards (no frontmatter, so nothing to
+ // assemble) and INDEX.md, and INDEX alone assembles to a single node. Since the
+ // 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";
+ const contextGraph = {
+ ...context,
+ meta: { ...context.meta, repoName: opts.repoName, subtitle: opts.subtitle, defaultTab },
+ };
+
+ const data = [
+ "<script>window.__GRAFT_DATA__ = {",
+ ` contextGraph: ${inlineJson(contextGraph)},`,
+ ` codeGraph: ${inlineJson(code)}`,
+ "};</script>",
+ ].join("\n");
+
+ // Replacer FUNCTIONS, not replacement strings: `$&`, `$\'` and friends are
+ // substitution patterns inside a replacement string, and a minified bundle is
+ // 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");
+ }
+
+ mkdirSync(opts.outDir, { recursive: true });
+ const file = join(opts.outDir, "index.html");
+ writeFileSync(file, page);
+ return { file, bytes: Buffer.byteLength(page), contextNodes: contextGraph.nodes.length, codeNodes, defaultTab };
+}
diff --git a/test/blast-name.test.ts b/test/blast-name.test.ts
new file mode 100644
index 00000000..865a5482
--- /dev/null
+++ b/test/blast-name.test.ts
@@ -0,0 +1,163 @@
+/**
+ * The naming layer, whose whole job is to be honest about where a label came from.
+ *
+ * Three properties are asserted here because breaking any of them makes the PR
+ * comment worse than no comment at all:
+ * - a cluster's name is keyed by its CONTENT, so the same area is not renamed on
+ * every PR and two comments stay comparable;
+ * - a declined ("mixed") cluster keeps its symbol backstop instead of taking a
+ * flattering name for files that serve two unrelated features;
+ * - any failure — no key, spent quota, malformed answer — leaves every label as
+ * it was and never throws, since a check must not fail over cosmetics.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { applyNames, clusterHash, sanitize, type Cluster, type Namer } from "../src/blast/name.js";
+import type { BlastReport, ImpactedModule } from "../src/blast/blast.js";
+import type { GraphV1 } from "../src/graph/types.js";
+
+function graph(hashes: Record<string, string>): GraphV1 {
+ return {
+ meta: { version: 1, generated: "", root: "." } as GraphV1["meta"],
+ nodes: Object.entries(hashes).map(([path, body_hash]) => ({
+ id: path, name: path, kind: "file", path, span: "L1-L9",
+ signature: null, exported: true, origin: "ast", body_hash, chars: 10,
+ })) as GraphV1["nodes"],
+ edges: [],
+ };
+}
+
+function mod(key: string, files: string[], symbols: string[]): ImpactedModule {
+ return {
+ label: symbols[0] ?? key,
+ labelSource: "symbol",
+ key,
+ files,
+ from: [],
+ symbols: symbols.map((name, i) => ({
+ id: `${files[0]}#${name}`, name, kind: "function", path: files[0],
+ span: `L${i + 1}-L${i + 2}`, relation: "calls", depth: 1,
+ })),
+ };
+}
+
+function report(modules: ImpactedModule[]): BlastReport {
+ return {
+ basis: "origin/main...HEAD", depth: 2, changed: [], unindexed: [], deleted: [],
+ seeds: [], impacted: [], modules, testModules: [], areas: [],
+ };
+}
+
+/** Records what it was asked, answers from a fixed table. */
+function stubNamer(answers: Record<string, string>): Namer & { calls: Cluster[][] } {
+ const calls: Cluster[][] = [];
+ return {
+ calls,
+ async name(clusters) {
+ calls.push(clusters);
+ const out = new Map<string, string>();
+ for (const c of clusters) if (answers[c.symbols[0]]) out.set(c.key, answers[c.symbols[0]]);
+ return out;
+ },
+ };
+}
+
+const dir = () => mkdtempSync(join(tmpdir(), "graft-name-"));
+
+test("blast name: a cluster is keyed by content, so unchanged code is never renamed", () => {
+ const files = ["src/a.ts", "src/b.ts"];
+ const before = new Map([["src/a.ts", "h1"], ["src/b.ts", "h2"]]);
+ const reordered = new Map([["src/b.ts", "h2"], ["src/a.ts", "h1"]]);
+ const edited = new Map([["src/a.ts", "h1"], ["src/b.ts", "CHANGED"]]);
+
+ assert.equal(clusterHash(files, before), clusterHash([...files].reverse(), reordered),
+ "member order must not change the key");
+ assert.notEqual(clusterHash(files, before), clusterHash(files, edited),
+ "editing a member's body must change the key");
+});
+
+test("blast name: names are written to the cache, then served from it without a call", async () => {
+ const contextDir = dir();
+ const g = graph({ "src/graph/refresh.ts": "h1" });
+ const namer = stubNamer({ ensureFreshGraph: "Query Freshness Gate" });
+
+ const first = report([mod("src/graph/", ["src/graph/refresh.ts"], ["ensureFreshGraph"])]);
+ const cold = await applyNames(g, first, { namer, contextDir });
+ assert.deepEqual([cold.named, cold.cached, cold.declined], [1, 0, 0]);
+ assert.equal(first.modules[0].label, "Query Freshness Gate");
+ assert.equal(first.modules[0].labelSource, "named", "the report says where the label came from");
+
+ const onDisk = JSON.parse(readFileSync(join(contextDir, ".cache", "areas.json"), "utf8")) as Record<string, string>;
+ assert.deepEqual(Object.values(onDisk), ["Query Freshness Gate"]);
+
+ const second = report([mod("src/graph/", ["src/graph/refresh.ts"], ["ensureFreshGraph"])]);
+ const warm = await applyNames(g, second, { namer, contextDir });
+ assert.deepEqual([warm.named, warm.cached], [0, 1]);
+ assert.equal(second.modules[0].label, "Query Freshness Gate");
+ assert.equal(namer.calls.length, 1, "a cache hit must not reach the model");
+});
+
+test("blast name: a concept label outranks naming, and a declined cluster keeps its symbol", async () => {
+ const contextDir = dir();
+ const g = graph({ "src/a.ts": "h1", "src/mixed.ts": "h2" });
+ const namer = stubNamer({ hubOne: "Real Feature Name" });
+
+ const r = report([
+ mod("src/", ["src/a.ts"], ["hubOne"]),
+ mod("src/mixed/", ["src/mixed.ts"], ["hubTwo"]),
+ ]);
+ // A concept node already named this one: naming must not touch it, since a
+ // concept is written from whole file bodies and knows strictly more.
+ r.modules[0].label = "Written By A Concept";
+ r.modules[0].labelSource = "concept";
+
+ const stats = await applyNames(g, r, { namer, contextDir });
+
+ assert.equal(r.modules[0].label, "Written By A Concept");
+ assert.deepEqual(namer.calls[0].map((c) => c.symbols[0]), ["hubTwo"], "only the backstop cluster is sent");
+ // hubTwo is absent from the stub's table, which is how a "mixed" answer arrives.
+ assert.equal(r.modules[1].label, "hubTwo");
+ assert.equal(r.modules[1].labelSource, "symbol");
+ assert.deepEqual([stats.named, stats.declined], [0, 1]);
+});
+
+test("blast name: test-only clusters are never named, since nothing renders them", async () => {
+ const contextDir = dir();
+ const g = graph({ "src/a.ts": "h1", "test/a.test.ts": "h2" });
+ const namer = stubNamer({ hubOne: "Real Feature Name" });
+
+ const r = report([mod("src/", ["src/a.ts"], ["hubOne"])]);
+ r.testModules = [mod("test/", ["test/a.test.ts"], ["describesThings"])];
+
+ await applyNames(g, r, { namer, contextDir });
+
+ assert.deepEqual(namer.calls[0].map((c) => c.symbols[0]), ["hubOne"], "only the drawn cluster is sent");
+ assert.equal(r.testModules[0].label, "describesThings", "the test cluster keeps its backstop");
+});
+
+test("blast name: a failing namer reports the reason and leaves every label alone", async () => {
+ const contextDir = dir();
+ const g = graph({ "src/a.ts": "h1" });
+ const r = report([mod("src/", ["src/a.ts"], ["hubOne"])]);
+
+ const stats = await applyNames(g, r, {
+ contextDir,
+ namer: { async name() { throw new Error("402 quota exhausted"); } },
+ });
+
+ assert.match(stats.error ?? "", /quota exhausted/);
+ assert.equal(r.modules[0].label, "hubOne", "the backstop survives a failed call");
+ assert.equal(r.modules[0].labelSource, "symbol");
+});
+
+test("blast name: a model's answer is untrusted text and is stripped before rendering", () => {
+ // Symbol names from a fork's diff reach the prompt, so the answer could carry
+ // anything that closes a Mermaid label or opens a markdown table cell.
+ assert.equal(sanitize('Auth "Gate" <img src=x>'), "Auth Gate img src=x");
+ assert.equal(sanitize("Pipe | Table"), "Pipe Table");
+ assert.equal(sanitize(" spaced out "), "spaced out");
+ assert.equal(sanitize("An Extremely Long Feature Name That Never Fits A Circle").length <= 31, true);
+});
diff --git a/test/blast-render.test.ts b/test/blast-render.test.ts
new file mode 100644
index 00000000..6e1b11cf
--- /dev/null
+++ b/test/blast-render.test.ts
@@ -0,0 +1,142 @@
+/**
+ * The comment body's shape, which is the part that lies if it gets it wrong.
+ *
+ * Two bugs live in this file's history. The first `mermaidDiagram` capped the
+ * changed-file boxes in diff order and then drew only the arrows whose source box
+ * happened to survive: on graft's own 23-file PR that left five of six modules with
+ * no arrow, so the picture said "nothing depends on any of this" — the opposite of
+ * the report underneath it. The second let test-only modules into the same list as
+ * real ones, and a repo with a test per module then reported 31 impacted modules,
+ * 24 of them a single test file. Both are asserted against here.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { markdownReport, mermaidDiagram, textReport } from "../src/blast/render.js";
+import type { BlastReport, ChangedArea, ImpactedModule, TestSignal } from "../src/blast/blast.js";
+
+function mod(label: string, from: string[], symbols: number): ImpactedModule {
+ return {
+ label,
+ labelSource: "concept",
+ 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: "L1-L3", relation: "calls", depth: 1,
+ })),
+ };
+}
+
+function area(label: string, files: string[], tests: TestSignal): ChangedArea {
+ // "na" is the types-only case: no function, method or class changed, so the
+ // question does not apply and the area must not be reported as untested.
+ return {
+ label, labelSource: "concept", key: label, files, seeds: files.length, tests,
+ testFiles: tests === "none" || tests === "na" ? [] : ["test/a.test.ts"],
+ changedTestFiles: tests === "changed" ? ["test/a.test.ts"] : [],
+ reached: tests === "changed" || tests === "stale" ? 1 : 0,
+ behavioural: tests === "na" ? 0 : 1,
+ unreached: tests === "none" ? ["doThing"] : [],
+ seedNames: ["doThing"],
+ };
+}
+
+/** Seven affected areas from four changed ones, so both caps are exercised. */
+function report(): BlastReport {
+ const changed = Array.from({ length: 12 }, (_, i) => ({
+ path: `src/f${i}.ts`,
+ status: "modified" as const,
+ ranges: [{ start: 1, end: 1 }],
+ }));
+ return {
+ basis: "origin/main...HEAD",
+ depth: 2,
+ changed,
+ unindexed: [],
+ deleted: [],
+ seeds: [],
+ impacted: [],
+ modules: [
+ mod("core/", ["src/f0.ts", "src/f6.ts"], 3),
+ mod("api/", ["src/f6.ts"], 2),
+ mod("cli/", ["src/f0.ts"], 2),
+ mod("db/", ["src/f11.ts"], 1),
+ mod("http/", ["src/f0.ts"], 1),
+ mod("sync/", ["src/f11.ts"], 1),
+ mod("viz/", ["src/f6.ts"], 1),
+ ],
+ testModules: [mod("test/", ["src/f0.ts"], 9)],
+ areas: [
+ area("graph build", ["src/f0.ts", "src/f1.ts"], "changed"),
+ area("deep pass", ["src/f6.ts"], "stale"),
+ area("blast", ["src/f11.ts"], "none"),
+ area("types", ["src/f2.ts"], "na"),
+ ],
+ };
+}
+
+test("blast diagram: circles for what can break, and nothing else", () => {
+ const diagram = mermaidDiagram(report()) ?? assert.fail("expected a diagram");
+
+ // TB, not LR: with no edges, top-bottom lays unconnected nodes out as a row.
+ assert.match(diagram, /^flowchart TB$/m);
+ assert.match(diagram, /A0\(\("core\/<br\/>3 symbols"\)\)/);
+ // Two of seven affected areas are past the cap: one grey circle carries both.
+ assert.match(diagram, /AX\(\("2 smaller areas<br\/>2 symbols"\)\)/);
+ assert.ok(!diagram.includes("A5(("), "the sixth area must fold into the tail, not be drawn");
+
+ // The mesh is the thing this diagram exists without. Arrows, the changed side and
+ // the glyph key all left together; the attribution lives in the table's column.
+ assert.ok(!diagram.includes("-->"), `no arrows may be drawn:\n${diagram}`);
+ assert.ok(!diagram.includes("linkStyle"), "nothing to style with no links");
+ assert.ok(!/\bD\d\(\(/.test(diagram), "no changed-area circles");
+ assert.ok(!diagram.includes("KEY"), "no key node");
+});
+
+test("blast diagram: colours are explicit, so either GitHub theme is legible", () => {
+ const diagram = mermaidDiagram(report()) ?? assert.fail("expected a diagram");
+
+ assert.match(diagram, /classDef reached fill:#[0-9A-F]{6},stroke:#[0-9A-F]{6},stroke-width:1\.5px,color:#[0-9A-F]{6};/i);
+ assert.match(diagram, /classDef tail fill:#[0-9A-F]{6}/i);
+ assert.match(diagram, /^\s+class A0,A1,A2,A3,A4 reached;/m);
+});
+
+test("blast markdown: one table and three collapsed sections, no per-module headers", () => {
+ const body = markdownReport(report());
+
+ assert.match(body, /\*\*4 areas changed → 7 areas can be affected\.\*\* 11 dependent symbols, depth 2\./);
+ // The types-only area is absent from this sentence on purpose: an area where no
+ // function changed has no test question to answer, and reporting it as untested
+ // is how a report earns the reviewer's distrust.
+ assert.match(body, /Tests: \*\*no test reaches blast\*\*; deep pass has tests the diff did not touch; 1 area updated its tests\./);
+ assert.match(body, /- – \*\*types\*\* — no function, method or class changed here/);
+
+ // Six rows plus a tail row, not 31 sections with one bullet each.
+ const rows = body.split("\n").filter((l) => l.startsWith("| "));
+ assert.equal(rows.length, 9, `header, divider, 6 areas and the tail:\n${rows.join("\n")}`);
+ assert.match(body, /\| core\/ \| 3 \| `core\/dep\.ts:L1-L3` s0 — calls, depth 1 \| graph build, deep pass \|/);
+ assert.match(body, /\| _1 smaller area_ \| 1 \|/);
+
+ const sections = body.split("\n").filter((l) => l.startsWith("<summary>"));
+ assert.equal(sections.length, 3, `all symbols, test signal, test suites:\n${sections.join("\n")}`);
+ // GitHub renders no markdown emphasis inside <summary>, so asterisks would show.
+ assert.match(body, /<summary><strong>All 11 dependent symbols<\/strong>, grouped by area<\/summary>/);
+ // A ratio in the summary would read as coverage; the state counts cannot.
+ assert.match(body, /<summary><strong>Test signal<\/strong> per changed area — 1 ✓ · 1 ⚠ · 1 ✗ · 1 –<\/summary>/);
+ assert.match(body, /Reached = a node under a test path has a resolved edge/);
+ assert.ok(!body.includes("<summary>**"), "asterisks would render literally");
+});
+
+test("blast markdown: test-only dependents are counted, never mixed into the areas", () => {
+ const body = markdownReport(report());
+
+ // The 9 test-file symbols are outside the headline, the diagram and the table…
+ assert.match(body, /\*\*4 areas changed → 7 areas can be affected\.\*\* 11 dependent symbols/);
+ assert.ok(!body.includes("| test/ |"), "a test-only area must not take a table row");
+ // …and present as one collapsed line, so the count is not quietly lost.
+ assert.match(body, /<summary>1 test suite also references this code<\/summary>/);
+ assert.match(body, /9 symbols, kept out of the diagram and the table/);
+
+ assert.match(textReport(report()), /1 test suite also references this code \(not listed\)/);
+});
diff --git a/test/blast.test.ts b/test/blast.test.ts
new file mode 100644
index 00000000..7c8a70e0
--- /dev/null
+++ b/test/blast.test.ts
@@ -0,0 +1,214 @@
+/**
+ * `graft blast` — the blast radius of a diff, which is what the CI job posts on a
+ * pull request.
+ *
+ * The behaviour worth pinning down is the SEEDING rule, because that is what makes
+ * the answer different from "every file that imports this module": a one-line edit
+ * inside one function reports that function's dependents, and says nothing about
+ * the untouched function next to it in the same file. The fixture below is built
+ * for exactly that check — `add` and `mul` live in one file with separate callers.
+ *
+ * Runs the real CLI through a real git repo (the command reads git, so a fake diff
+ * would prove nothing about the parsing).
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { join } from "node:path";
+import { runCli, tmpRepo } from "./helpers.js";
+
+const MATH = `export function add(a: number, b: number): number {
+ return a + b;
+}
+
+export function mul(a: number, b: number): number {
+ return a * b;
+}
+`;
+
+/** `add`'s body only — same line count, so `mul`'s span never moves. */
+const MATH_EDITED = `export function add(a: number, b: number): number {
+ return b + a;
+}
+
+export function mul(a: number, b: number): number {
+ return a * b;
+}
+`;
+
+function git(dir: string, ...args: string[]): void {
+ const r = spawnSync("git", args, { cwd: dir, encoding: "utf8" });
+ assert.equal(r.status, 0, `git ${args.join(" ")} failed: ${r.stderr}`);
+}
+
+/**
+ * A committed, built repo: `add`/`mul` in one file, one caller each, and one
+ * second-hop caller of `add`'s caller so `--depth` has something to walk.
+ */
+function builtRepo(): string {
+ const d = tmpRepo("blast");
+ mkdirSync(join(d, "src"), { recursive: true });
+ writeFileSync(join(d, "src", "math.ts"), MATH);
+ writeFileSync(
+ join(d, "src", "total.ts"),
+ 'import { add } from "./math.js";\nexport function total(xs: number[]): number {\n return xs.reduce((s, x) => add(s, x), 0);\n}\n',
+ );
+ writeFileSync(
+ join(d, "src", "area.ts"),
+ 'import { mul } from "./math.js";\nexport function area(w: number, h: number): number {\n return mul(w, h);\n}\n',
+ );
+ writeFileSync(
+ join(d, "src", "report.ts"),
+ 'import { total } from "./total.js";\nexport function report(xs: number[]): string {\n return `sum=${total(xs)}`;\n}\n',
+ );
+ writeFileSync(join(d, "README.md"), "# fixture\n");
+
+ git(d, "init", "-b", "main");
+ git(d, "config", "user.email", "[email protected]");
+ git(d, "config", "user.name", "test");
+ git(d, "add", "-A");
+ git(d, "commit", "-m", "initial");
+
+ const build = runCli(["build", d]);
+ assert.equal(build.status, 0, build.describe());
+ // The build writes ignore rules for its own cache dir; commit them so a later
+ // `git add -A` in a test is the test's own edit and nothing else.
+ git(d, "add", "-A");
+ git(d, "commit", "-m", "index");
+ return d;
+}
+
+/** Parse `--format json` output, failing with the whole run on bad JSON. */
+function blastJson(args: string[]): {
+ basis: string;
+ changed: { path: string; status: string; ranges: { start: number; end: number }[] }[];
+ unindexed: string[];
+ deleted: string[];
+ seeds: { name: string; path: string; wholeFile: boolean }[];
+ impacted: { name: string; path: string; depth: number; relation: string }[];
+ modules: { label: string; files: string[]; symbols: { name: string }[]; from: string[] }[];
+} {
+ const r = runCli(["blast", ...args, "--format", "json"]);
+ assert.equal(r.status, 0, r.describe());
+ try {
+ return JSON.parse(r.stdout);
+ } catch {
+ assert.fail(`not JSON:\n${r.describe()}`);
+ }
+}
+
+test("blast: an edit inside one function reports that function's dependents, not the file's", () => {
+ const d = builtRepo();
+ writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);
+
+ const report = blastJson([d]);
+
+ assert.deepEqual(report.seeds.map((s) => s.name), ["add"], "only the edited function is a seed");
+ const names = report.impacted.map((i) => i.name);
+ assert.ok(names.includes("total"), `expected total in ${JSON.stringify(names)}`);
+ assert.ok(names.includes("report"), `expected the second hop in ${JSON.stringify(names)}`);
+ // The point of seeding by symbol: `area` calls `mul`, which this diff never
+ // touched, even though it sits in the same changed file.
+ assert.ok(!names.includes("area"), `area must not be reported: ${JSON.stringify(names)}`);
+});
+
+test("blast --depth: one hop stops at the direct caller", () => {
+ const d = builtRepo();
+ writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);
+
+ const names = blastJson([d, "--depth", "1"]).impacted.map((i) => i.name);
+ assert.deepEqual(names, ["total"]);
+});
+
+test("blast --base: diffs against the merge base, and reports the ranges it read", () => {
+ const d = builtRepo();
+ git(d, "checkout", "-b", "feature");
+ writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);
+ git(d, "add", "-A");
+ git(d, "commit", "-m", "tweak add");
+
+ const report = blastJson([d, "--base", "main"]);
+
+ assert.equal(report.basis, "main...HEAD");
+ assert.deepEqual(report.changed.map((c) => c.path), ["src/math.ts"]);
+ assert.deepEqual(report.changed[0].ranges, [{ start: 2, end: 2 }], "the one changed line");
+ assert.ok(report.impacted.some((i) => i.name === "total"));
+});
+
+test("blast: a changed file no parser claims is reported, never silently dropped", () => {
+ const d = builtRepo();
+ writeFileSync(join(d, "README.md"), "# fixture\n\nnow with prose\n");
+
+ const report = blastJson([d]);
+
+ assert.deepEqual(report.unindexed, ["README.md"]);
+ assert.deepEqual(report.impacted, [], "nothing to walk from an unindexed file");
+});
+
+test("blast: a deleted file is called out, since its dependents are not in this graph", () => {
+ const d = builtRepo();
+ rmSync(join(d, "src", "area.ts"));
+
+ const report = blastJson([d]);
+
+ assert.deepEqual(report.deleted, ["src/area.ts"]);
+ const text = runCli(["blast", d]);
+ assert.equal(text.status, 0, text.describe());
+ assert.match(text.stdout, /1 deleted file/);
+});
+
+test("blast --format markdown: diagram first, detail collapsed under it", () => {
+ const d = builtRepo();
+ writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);
+
+ const r = runCli(["blast", d, "--format", "markdown"]);
+ assert.equal(r.status, 0, r.describe());
+ assert.match(r.stdout, /```mermaid\nflowchart TB/);
+ // Circles for what can break, labelled by area — never one box per changed file,
+ // and never a bare path: with no concept node, the hub symbol names the area.
+ assert.match(r.stdout, /A0\(\("total<br\/>2 symbols"\)\)/);
+ assert.match(r.stdout, /\| Can be affected \| Symbols \| Nearest hop \| Reached from \|/);
+ assert.match(r.stdout, /<details>/);
+ assert.match(r.stdout, /`src\/total\.ts:L\d+-L\d+` — total \(calls, depth 1\)/);
+ // The fixture ships no tests, so the one changed area must say so — in the glyph
+ // on its circle and in the collapsed section.
+ assert.match(r.stdout, /✗/);
+ assert.match(r.stdout, /no test file reaches it/);
+ // Labels carry a line break as markup, not as the literal text of the tag.
+ assert.ok(!/br\/\d+ file/.test(r.stdout), "the <br/> in a node label must survive escaping");
+});
+
+test("blast --format mermaid: bare diagram, and a comment (not a failure) when there is nothing to draw", () => {
+ const d = builtRepo();
+ writeFileSync(join(d, "src", "math.ts"), MATH_EDITED);
+ const drawn = runCli(["blast", d, "--format", "mermaid"]);
+ assert.equal(drawn.status, 0, drawn.describe());
+ assert.match(drawn.stdout, /^flowchart TB/);
+
+ // A README-only diff has no dependents: a CI step must not fail on that.
+ writeFileSync(join(d, "src", "math.ts"), MATH);
+ writeFileSync(join(d, "README.md"), "# fixture\n\nprose\n");
+ const empty = runCli(["blast", d, "--format", "mermaid"]);
+ assert.equal(empty.status, 0, empty.describe());
+ assert.match(empty.stdout, /no dependents to draw/);
+});
+
+test("blast: an unknown --base names the CI cause (checkout depth), not a git internal", () => {
+ const d = builtRepo();
+ const r = runCli(["blast", d, "--base", "origin/nope"]);
+ assert.equal(r.status, 1, r.describe());
+ assert.match(r.stderr, /base ref "origin\/nope" is not in this checkout/);
+ assert.match(r.stderr, /fetch-depth: 0/);
+});
+
+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);
+ git(d, "add", "-A");
+ git(d, "commit", "-m", "tweak add");
+
+ const report = blastJson([d]);
+ assert.equal(report.basis, "HEAD~1...HEAD");
+ assert.ok(report.impacted.some((i) => i.name === "total"));
+});
diff --git a/test/cli-deep-failure.test.ts b/test/cli-deep-failure.test.ts
new file mode 100644
index 00000000..a9406950
--- /dev/null
+++ b/test/cli-deep-failure.test.ts
@@ -0,0 +1,131 @@
+/**
+ * #127, at the process boundary: `graft build --deep` against a provider that
+ * rejects every call must EXIT NON-ZERO and say the meaning tier is incomplete.
+ *
+ * The reported case was an 884-file repo behind a gateway with a hard token quota:
+ * 1,617 files failed with 429, the build printed its normal success footer, and
+ * exited 0 — so the degradation was only discovered days later through bad `ask`
+ * results. A local server standing in for that gateway is the only way to pin the
+ * exit code down, since the failure lives in the CLI's reporting, not in a unit.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createServer, type Server } from "node:http";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { join } from "node:path";
+import { tmpRepo } from "./helpers.js";
+
+/** A gateway that answers every request the way an exhausted quota does. */
+async function quotaExhaustedServer(): Promise<{ url: string; close: () => Promise<void>; calls: () => number }> {
+ let calls = 0;
+ const server: Server = createServer((req, res) => {
+ calls++;
+ res.writeHead(429, { "content-type": "application/json" });
+ res.end(
+ JSON.stringify({
+ error: { message: "Request exceeds your current quota, please check your plan and billing details", type: "insufficient_quota" },
+ }),
+ );
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const addr = server.address();
+ if (addr === null || typeof addr === "string") throw new Error("no port");
+ return {
+ url: `http://127.0.0.1:${addr.port}/v1`,
+ calls: () => calls,
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
+ };
+}
+
+function repo(files: number): string {
+ const d = tmpRepo("deepfail");
+ mkdirSync(join(d, "src"), { recursive: true });
+ for (let i = 0; i < files; i++) {
+ writeFileSync(join(d, "src", `m${i}.ts`), `export function run${i}(): number {\n return ${i};\n}\n`);
+ }
+ return d;
+}
+
+/**
+ * Runs the build ASYNCHRONOUSLY on purpose. `spawnSync` would deadlock: the stand-in
+ * gateway is served by this very process's event loop, which a synchronous spawn
+ * blocks — so the child would wait forever for a response that cannot be sent.
+ */
+async function runBuild(
+ dir: string,
+ baseUrl: string,
+ extra: string[] = [],
+): Promise<{ status: number | null; stderr: string; stdout: string }> {
+ const child = spawn(
+ process.execPath,
+ [
+ "--import", "tsx", "src/cli.ts",
+ "--provider", "openai",
+ "--api-key", "test-key",
+ "--base-url", baseUrl,
+ "--model", "test-model",
+ "build", dir, "--deep", "-j", "1",
+ ...extra,
+ ],
+ {
+ // No transport retries: the SDK's backoff is correct behaviour but would make
+ // this test spend seconds waiting to learn what the first response already said.
+ env: { ...process.env, GRAFT_LLM_RETRIES: "0" },
+ },
+ );
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8").on("data", (c: string) => (stdout += c));
+ child.stderr.setEncoding("utf8").on("data", (c: string) => (stderr += c));
+ const status = await new Promise<number | null>((resolve) => child.on("close", resolve));
+ return { status, stdout, stderr };
+}
+
+test("#127: a quota-exhausted --deep build exits 1 and says the meaning tier is incomplete", async () => {
+ const gateway = await quotaExhaustedServer();
+ try {
+ const d = repo(20);
+ const r = await runBuild(d, gateway.url);
+
+ assert.equal(r.status, 1, `expected a failing exit\n${r.stderr}`);
+ assert.match(r.stderr, /the deep pass did not complete/);
+ assert.match(r.stderr, /quota\/credit for this key is exhausted/);
+ // Nothing summarized at all: the denominator is every node in the graph (file
+ // nodes carry a summary too), so it is matched loosely on purpose.
+ assert.match(r.stderr, /meaning coverage: 0\/\d+ symbols \(0%\)/);
+ assert.match(r.stderr, /re-run `graft build --deep` to resume/);
+ // The structural tier still succeeded and is still written — this is a loud
+ // warning about a degraded tier, not a rolled-back build.
+ assert.match(r.stdout, /✓ wiring: /);
+ } finally {
+ await gateway.close();
+ }
+});
+
+test("#127: --allow-partial keeps the same report but exits 0, for callers that accept a partial tier", async () => {
+ const gateway = await quotaExhaustedServer();
+ try {
+ const d = repo(5);
+ const r = await runBuild(d, gateway.url, ["--allow-partial"]);
+
+ assert.equal(r.status, 0, `expected --allow-partial to exit 0\n${r.stderr}`);
+ assert.match(r.stderr, /the deep pass did not complete/);
+ } finally {
+ await gateway.close();
+ }
+});
+
+test("#127: the doomed calls stop instead of one per file", async () => {
+ const gateway = await quotaExhaustedServer();
+ try {
+ const d = repo(40);
+ await runBuild(d, gateway.url);
+ // 40 files, plus the concept pass ahead of the crux pass. The old behaviour was
+ // one call per file per pass and a clean exit; the bound here is what "stopped
+ // early" means in requests, which is the part that costs money.
+ assert.ok(gateway.calls() < 20, `expected the passes to give up early, saw ${gateway.calls()} requests`);
+ } finally {
+ await gateway.close();
+ }
+});
diff --git a/test/graph-enrich-checkpoint.test.ts b/test/graph-enrich-checkpoint.test.ts
new file mode 100644
index 00000000..1be4ab7d
--- /dev/null
+++ b/test/graph-enrich-checkpoint.test.ts
@@ -0,0 +1,77 @@
+/**
+ * #128: the crux pass used to reach wiring.json only at build end, so an interrupted
+ * `--deep` run discarded every crux it had already computed and paid for. `enrichGraph`
+ * now flushes partial progress via a `checkpoint` callback, and (as it always has) folds
+ * a prior graph back in by `body_hash`. Together those mean a killed run keeps its crux
+ * and the next run replays it rather than re-issuing the LLM calls. These tests exercise
+ * that with a fake summarizer, no real model.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { enrichGraph } from "../src/graph/enrich.js";
+import type { CruxSummarizer, FileCruxInput, NodeCrux } from "../src/ai/crux.js";
+import type { NodeV1 } from "../src/graph/types.js";
+
+/** A CruxSummarizer that records which files it was asked to summarize (so a test can
+ * prove a file was, or was NOT, re-issued) and returns a trivial crux for each node. */
+class RecordingCrux implements CruxSummarizer {
+ calls: string[] = [];
+ async describeFile(input: FileCruxInput): Promise<NodeCrux[]> {
+ this.calls.push(input.path);
+ return input.nodes.map((n) => ({ id: n.id, summary: `crux ${n.id}`, crux_start: 0, crux_end: 0 }));
+ }
+}
+
+function methodNode(path: string, name: string, hash: string): NodeV1 {
+ return {
+ id: `${path}#${name}`, name, kind: "method", path, span: "L1-L3",
+ signature: `${name}()`, exported: true, origin: "ast", body_hash: hash,
+ summary_state: "pending", summary: null, crux: null,
+ };
+}
+
+const FILES = ["a.ts", "b.ts", "c.ts", "d.ts"];
+function fixture(): { nodes: NodeV1[]; sources: Map<string, string> } {
+ const nodes = FILES.map((f, i) => methodNode(f, "run", `h${i}`));
+ const sources = new Map(FILES.map((f) => [f, "class X {\n run() { return 1; }\n}\n"]));
+ return { nodes, sources };
+}
+
+test("#128: the crux pass flushes partial progress mid-run (checkpoint), not only at the end", async () => {
+ const { nodes, sources } = fixture();
+ const prev = process.env.GRAFT_CRUX_CHECKPOINT_MS;
+ process.env.GRAFT_CRUX_CHECKPOINT_MS = "0"; // flush on every completed file
+ try {
+ const readyAtCheckpoint: number[] = [];
+ await enrichGraph(nodes, new Map(), sources, {
+ summarizer: new RecordingCrux(),
+ concurrency: 1, // deterministic completion order for the snapshot assertion
+ checkpoint: () => readyAtCheckpoint.push(nodes.filter((n) => n.summary_state === "ready").length),
+ });
+ // A checkpoint fired DURING the pass (before the build's final write), and the
+ // count of persisted-ready nodes climbed — i.e. an interruption would have kept them.
+ assert.ok(readyAtCheckpoint.length > 0, "checkpoint fired during the pass");
+ assert.ok(readyAtCheckpoint.some((n) => n > 0 && n < FILES.length), "partial progress was flushable");
+ assert.equal(nodes.filter((n) => n.summary_state === "ready").length, FILES.length, "all ended ready");
+ } finally {
+ if (prev === undefined) delete process.env.GRAFT_CRUX_CHECKPOINT_MS;
+ else process.env.GRAFT_CRUX_CHECKPOINT_MS = prev;
+ }
+});
+
+test("#128: a rerun replays checkpointed crux by body_hash instead of re-issuing it", async () => {
+ const { nodes, sources } = fixture();
+ // Simulate an interrupted run that checkpointed the first two files as ready.
+ const prior = new Map(
+ nodes.slice(0, 2).map((n) => [n.id, { ...n, summary: `crux ${n.id}`, crux: null, summary_state: "ready" as const }]),
+ );
+ // The next run starts from fresh (pending) nodes with the SAME body_hash.
+ const fresh = FILES.map((f, i) => methodNode(f, "run", `h${i}`));
+ const rec = new RecordingCrux();
+ const stats = await enrichGraph(fresh, prior, sources, { summarizer: rec });
+
+ assert.ok(!rec.calls.includes("a.ts") && !rec.calls.includes("b.ts"), "already-done files are NOT re-summarized");
+ assert.ok(rec.calls.includes("c.ts") && rec.calls.includes("d.ts"), "only the unfinished files run");
+ assert.equal(stats.cached, 2, "two crux carried over from the interrupted run");
+ assert.equal(stats.computed, 2, "two freshly computed");
+});
diff --git a/test/graph-enrich-failures.test.ts b/test/graph-enrich-failures.test.ts
new file mode 100644
index 00000000..37843333
--- /dev/null
+++ b/test/graph-enrich-failures.test.ts
@@ -0,0 +1,122 @@
+/**
+ * #127: a `--deep` build whose LLM calls failed used to degrade file by file and
+ * still exit 0 — an 884-file run logged 1,617 quota rejections, printed the normal
+ * success footer, and left `graft check` saying "in sync".
+ *
+ * Two behaviours are asserted here, both with a fake summarizer (no network):
+ * - the pass STOPS instead of issuing a doomed call per remaining file — on a
+ * quota/auth rejection immediately, and otherwise after a run of failures;
+ * - the failure is reported as DATA (`failedFiles`/`skippedFiles`/`fatal`), which
+ * is what lets the CLI exit non-zero without parsing message strings.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { enrichGraph } from "../src/graph/enrich.js";
+import type { CruxSummarizer, FileCruxInput, NodeCrux } from "../src/ai/crux.js";
+import type { NodeV1 } from "../src/graph/types.js";
+
+/** Fails every call with `message`, counting how many calls it was asked for. */
+class FailingCrux implements CruxSummarizer {
+ calls = 0;
+ constructor(private readonly message: string) {}
+ async describeFile(_input: FileCruxInput): Promise<NodeCrux[]> {
+ this.calls++;
+ throw new Error(this.message);
+ }
+}
+
+/** Fails only for the named files; every other file summarizes normally. */
+class FlakyCrux implements CruxSummarizer {
+ calls: string[] = [];
+ constructor(private readonly failing: Set<string>) {}
+ async describeFile(input: FileCruxInput): Promise<NodeCrux[]> {
+ this.calls.push(input.path);
+ if (this.failing.has(input.path)) throw new Error("500 upstream hiccup");
+ return input.nodes.map((n) => ({ id: n.id, summary: `crux ${n.id}`, crux_start: 0, crux_end: 0 }));
+ }
+}
+
+function node(path: string): NodeV1 {
+ return {
+ id: `${path}#run`, name: "run", kind: "function", path, span: "L1-L3",
+ signature: "run()", exported: true, origin: "ast", body_hash: `h-${path}`,
+ summary_state: "pending", summary: null, crux: null,
+ };
+}
+
+/** `n` single-symbol files, each its own LLM call. */
+function fixture(n: number): { nodes: NodeV1[]; sources: Map<string, string> } {
+ const paths = Array.from({ length: n }, (_, i) => `f${i}.ts`);
+ return {
+ nodes: paths.map(node),
+ sources: new Map(paths.map((p) => [p, "export function run() {\n return 1;\n}\n"])),
+ };
+}
+
+test("#127: a quota rejection stops the pass instead of failing every remaining file", async () => {
+ const { nodes, sources } = fixture(40);
+ const summarizer = new FailingCrux("429 Request exceeds your current quota, please check your plan");
+
+ const stats = await enrichGraph(nodes, new Map(), sources, { summarizer, concurrency: 1 });
+
+ assert.match(stats.fatal ?? "", /quota\/credit for this key is exhausted/);
+ // The whole point: 40 files, one call. (`collectFileCrux` re-asks for symbols the
+ // model omitted, but a thrown error ends that loop, so a failure costs one call.)
+ assert.equal(summarizer.calls, 1, "the pass stopped at the first quota rejection");
+ assert.equal(stats.failedFiles, 1);
+ assert.equal(stats.skippedFiles, 39);
+ assert.equal(stats.computed, 0);
+ assert.equal(stats.pending, 40, "every symbol is still reported as unsummarized");
+});
+
+test("#127: a rejected API key is terminal too, and names the key as the cause", async () => {
+ const { nodes, sources } = fixture(10);
+ const summarizer = new FailingCrux("401 Unauthorized: invalid api key");
+
+ const stats = await enrichGraph(nodes, new Map(), sources, { summarizer, concurrency: 1 });
+
+ assert.match(stats.fatal ?? "", /rejected the API key/);
+ assert.equal(stats.failedFiles, 1);
+ assert.equal(stats.skippedFiles, 9);
+});
+
+test("#127: an unclassified error gives up only after a run of failures", async () => {
+ const { nodes, sources } = fixture(30);
+ const summarizer = new FailingCrux("503 upstream unavailable");
+
+ const stats = await enrichGraph(nodes, new Map(), sources, { summarizer, concurrency: 1 });
+
+ // Not terminal by message, so the cutoff is consecutive failures — five files
+ // tried, the rest skipped rather than 30 doomed calls.
+ assert.equal(stats.failedFiles, 5);
+ assert.equal(stats.skippedFiles, 25);
+ assert.match(stats.fatal ?? "", /5 files in a row failed/);
+});
+
+test("#127: isolated failures are counted but never stop a build that is working", async () => {
+ const { nodes, sources } = fixture(12);
+ const summarizer = new FlakyCrux(new Set(["f3.ts", "f7.ts"]));
+
+ const stats = await enrichGraph(nodes, new Map(), sources, { summarizer, concurrency: 1 });
+
+ assert.equal(stats.fatal, undefined, "two scattered failures are not a dead provider");
+ assert.equal(summarizer.calls.length, 12, "every file was attempted exactly once");
+ assert.equal(stats.failedFiles, 2);
+ assert.equal(stats.skippedFiles, 0);
+ assert.equal(stats.computed, 10);
+ assert.equal(stats.pending, 2);
+ assert.equal(stats.errors.length, 2);
+});
+
+test("#127: a clean pass reports no failure at all — the flags are not noise", async () => {
+ const { nodes, sources } = fixture(4);
+ const stats = await enrichGraph(nodes, new Map(), sources, {
+ summarizer: new FlakyCrux(new Set()),
+ concurrency: 2,
+ });
+
+ assert.equal(stats.fatal, undefined);
+ assert.equal(stats.failedFiles, 0);
+ assert.equal(stats.skippedFiles, 0);
+ assert.equal(stats.computed, 4);
+});
diff --git a/test/graph-refresh.test.ts b/test/graph-refresh.test.ts
index 14d22d64..60f86623 100644
--- a/test/graph-refresh.test.ts
+++ b/test/graph-refresh.test.ts
@@ -174,18 +174,26 @@ test("a refresh leaves the statusline stats alone, so the Stop hook still fires"
});
test("a failed rebuild still answers from the graph on disk", async (t) => {
- if (process.getuid?.() === 0) return t.skip("root writes anywhere, so a read-only directory proves nothing");
+ // Windows lands here too, not just root: the denial below is a directory mode, and
+ // Windows ignores those outright (see the helper). Before writeGraph became atomic
+ // this test denied by chmod-ing the FILE, which Windows *does* honour — so the
+ // Windows leg used to pass, and silently started replacing the read-only graph
+ // through the rename instead. Skipping says so rather than asserting vacuously.
+ const why = chmodDenialUnavailable();
+ if (why) return t.skip(why);
const d = repo();
await buildGraph(d);
const before = readFileSync(wiringPath(outOf(d)), "utf8");
writeFileSync(join(d, "src", "math.ts"), `${MATH}export const X = 1;\n`);
// Make the graph write itself fail: the query must degrade to the old graph, not
- // start erroring because a rebuild couldn't happen.
- const graphFile = wiringPath(outOf(d));
- chmodSync(graphFile, 0o400);
+ // start erroring because a rebuild couldn't happen. writeGraph is atomic (temp +
+ // rename), and a rename can replace a read-only FILE, so the unwritable target has
+ // to be the DIRECTORY — which is also the realistic "can't write here" case.
+ const graphDir = dirname(wiringPath(outOf(d)));
+ chmodSync(graphDir, 0o500); // r-x: the temp write fails, old wiring.json stays put
const r = await ensureFreshGraph(d);
- chmodSync(graphFile, 0o600);
+ chmodSync(graphDir, 0o700);
assert.equal(r.refreshed, false);
assert.match(r.note ?? "", /refresh skipped/);
diff --git a/test/viz-export.test.ts b/test/viz-export.test.ts
new file mode 100644
index 00000000..f8ad14b0
--- /dev/null
+++ b/test/viz-export.test.ts
@@ -0,0 +1,156 @@
+/**
+ * `graft viz --export`: one self-contained file, which is what makes a per-PR
+ * hosted view possible without a server.
+ *
+ * The three assertions that matter are all about the inlining, because each failure
+ * mode ships a page that looks fine locally and is broken where it is published:
+ * - no absolute asset paths survive (`/app.js` resolves to the domain root, so a
+ * Pages subdirectory would 404 and show an empty viewer);
+ * - `$&` and friends in the minified bundle are NOT treated as replacement
+ * patterns — the first version of the exporter put the original `<script src>`
+ * tag back into the page that way;
+ * - `</script>` inside graph data cannot close the data element.
+ */
+import { test } from "node:test";
+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 { exportViz } from "../src/viz/export.js";
+
+const VIEWER_HTML = `<!doctype html>
+<html lang="en">
+<head>
+<link rel="stylesheet" href="/style.css">
+</head>
+<body>
+<header class="appbar"><div class="brand"><b>graft</b><span id="repoName"></span></div></header>
+<script type="module" src="/app.js"></script>
+</body>
+</html>
+`;
+
+function viewerDir(appJs = "console.log('app');"): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-viewer-"));
+ writeFileSync(join(dir, "index.html"), VIEWER_HTML);
+ writeFileSync(join(dir, "style.css"), ":root{--k-method:#3AA7C9}");
+ writeFileSync(join(dir, "app.js"), appJs);
+ return dir;
+}
+
+function contextDir(summary = "Alpha coordinates the show."): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-ctx-"));
+ writeFileSync(
+ join(dir, "alpha.md"),
+ `---
+name: Alpha
+slug: alpha
+type: system
+sources:
+ - path: src/a.ts
+ hash: abc123
+links: []
+---
+<!-- context:generated:start -->
+## Summary
+${summary}
+<!-- context:generated:end -->
+`,
+ );
+ mkdirSync(join(dir, ".graph"), { recursive: true });
+ writeFileSync(
+ join(dir, ".graph", "wiring.json"),
+ JSON.stringify({
+ meta: { version: 1, nodeCount: 1, edgeCount: 0 },
+ nodes: [{ id: "src/a.ts#go", name: "go", kind: "function", path: "src/a.ts", span: "L1-L3", signature: null, summary: null, crux: null }],
+ edges: [],
+ }),
+ );
+ return dir;
+}
+
+function out(): string {
+ return mkdtempSync(join(tmpdir(), "graft-out-"));
+}
+
+test("viz export: one file, with both graphs and every asset inlined", () => {
+ const res = exportViz({ contextDir: contextDir(), viewerDir: viewerDir(), outDir: out(), repoName: "demo", subtitle: "PR #7" });
+ const page = readFileSync(res.file, "utf8");
+
+ assert.equal(res.contextNodes, 1);
+ assert.equal(res.codeNodes, 1);
+ // Nothing may be left for a server to serve.
+ assert.ok(!page.includes('href="/style.css"'), "the stylesheet link must be gone");
+ assert.ok(!page.includes('src="/app.js"'), "the script src must be gone");
+ assert.match(page, /<style>\n:root\{--k-method:#3AA7C9\}\n<\/style>/);
+ assert.match(page, /window\.__GRAFT_DATA__ = \{/);
+ // The subtitle is how a reader knows WHICH pull request they opened.
+ assert.match(page, /"subtitle":"PR #7"/);
+ assert.match(page, /"repoName":"demo"/);
+});
+
+test("viz export: opens on the tab that has content, not on an empty Context tab", () => {
+ // A structural `graft build` writes wiring cards (no frontmatter) plus INDEX.md,
+ // and a frontmatter-less file still assembles to one node named after itself — so
+ // the Context tab the viewer starts on holds exactly one dot. Exporting from that
+ // build used to publish precisely that, with the whole wiring graph hidden behind
+ // an unadvertised tab.
+ const sparse = exportViz({ contextDir: contextDir(), viewerDir: viewerDir(), outDir: out(), repoName: "demo" });
+ assert.equal(sparse.contextNodes, 1);
+ assert.equal(sparse.defaultTab, "code", "one node is not a graph — open on the code graph");
+ assert.match(readFileSync(sparse.file, "utf8"), /"defaultTab":"code"/);
+
+ // A real concept layer is the better landing place.
+ const deep = contextDir();
+ writeFileSync(join(deep, "beta.md"), "---\nname: Beta\nslug: beta\ntype: concept\nsources: []\nlinks: []\n---\n");
+ const rich = exportViz({ contextDir: deep, viewerDir: viewerDir(), outDir: out(), repoName: "demo" });
+ assert.equal(rich.defaultTab, "context");
+
+ // And with no wiring graph there is nothing to switch to.
+ const noCode = mkdtempSync(join(tmpdir(), "graft-ctx-"));
+ writeFileSync(join(noCode, "alpha.md"), "---\nname: Alpha\nslug: alpha\ntype: system\nsources: []\nlinks: []\n---\n");
+ const only = exportViz({ contextDir: noCode, viewerDir: viewerDir(), outDir: out(), repoName: "demo" });
+ assert.equal(only.codeNodes, 0);
+ assert.equal(only.defaultTab, "context");
+});
+
+test("viz export: a bundle containing $& is inlined verbatim, not re-substituted", () => {
+ // esbuild output is full of `$&`-shaped sequences; as a replacement STRING they
+ // expand to the matched text, which put `<script src="/app.js">` back in the page.
+ const res = exportViz({
+ contextDir: contextDir(),
+ viewerDir: viewerDir('const re = "$&"; const other = "$\'" + "$`";'),
+ outDir: out(),
+ repoName: "demo",
+ });
+ const page = readFileSync(res.file, "utf8");
+
+ assert.match(page, /const re = "\$&"/, "the bundle must survive byte for byte");
+ assert.ok(!page.includes('src="/app.js"'), "no substitution may resurrect the asset tag");
+});
+
+test("viz export: graph data cannot close the script element it lives in", () => {
+ const res = exportViz({
+ contextDir: contextDir("A summary that ends with </script><img src=x> on purpose."),
+ viewerDir: viewerDir(),
+ outDir: out(),
+ repoName: "demo",
+ });
+ const page = readFileSync(res.file, "utf8");
+
+ assert.ok(!page.includes("</script><img"), "the closing tag must be escaped inside the data");
+ // Escaping `<` alone is enough — `\u003c/script>` cannot be an end tag — and it
+ // keeps the payload readable if anyone opens the file.
+ assert.match(page, /\\u003c\/script>/, "< is escaped as a JSON unicode sequence");
+});
+
+test("viz export: refuses to write a page whose asset tags it did not rewrite", () => {
+ const dir = viewerDir();
+ writeFileSync(join(dir, "index.html"), '<html><head><link rel="stylesheet" href="/style.css"></head><body><script src="/app.js"></script></body></html>');
+
+ assert.throws(
+ () => exportViz({ contextDir: contextDir(), viewerDir: dir, outDir: out(), repoName: "demo" }),
+ /no longer matches the asset tags/,
+ "a silently un-inlined page 404s wherever it is published — fail loudly instead",
+ );
+});
diff --git a/viewer/data.ts b/viewer/data.ts
index 56477604..44486337 100644
--- a/viewer/data.ts
+++ b/viewer/data.ts
@@ -20,7 +20,12 @@ export interface VizEdge {
}
export interface VizGraph {
- meta: { repoName?: string; nodeCount: number; edgeCount: number; skippedFiles?: number; droppedEdges?: number };
+ meta: {
+ repoName?: string; subtitle?: string;
+ /** Set by `graft viz --export`: the tab whose graph actually has content. */
+ defaultTab?: "context" | "code";
+ nodeCount: number; edgeCount: number; skippedFiles?: number; droppedEdges?: number;
+ };
nodes: VizNode[];
edges: VizEdge[];
}
@@ -78,7 +83,20 @@ export function cvar(name: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
+/**
+ * Graphs inlined by `graft viz --export`, when the page was exported rather than
+ * served. The static file has no server behind it, so a fetch would 404 — but the
+ * viewer must not care which way it was opened, so this is the only place that
+ * knows the difference.
+ */
+interface InlinedData {
+ contextGraph?: VizGraph;
+ codeGraph?: unknown;
+}
+const inlined = (globalThis as { __GRAFT_DATA__?: InlinedData }).__GRAFT_DATA__;
+
export async function loadContextGraph(): Promise<VizGraph> {
+ if (inlined?.contextGraph) return inlined.contextGraph;
const res = await fetch("/api/context-graph");
return (await res.json()) as VizGraph;
}
@@ -94,9 +112,15 @@ interface CodeGraphV1 {
/** Fetch graph.json and reshape it into the viewer's graph form (null if absent). */
export async function loadCodeGraph(): Promise<VizGraph | null> {
- const res = await fetch("/api/code-graph");
- if (!res.ok) return null;
- const raw = (await res.json()) as CodeGraphV1;
+ let raw: CodeGraphV1;
+ if (inlined) {
+ if (!inlined.codeGraph) return null;
+ raw = inlined.codeGraph as CodeGraphV1;
+ } else {
+ const res = await fetch("/api/code-graph");
+ if (!res.ok) return null;
+ raw = (await res.json()) as CodeGraphV1;
+ }
const nodes: VizNode[] = raw.nodes.map((n) => ({
id: n.id,
name: n.name,
@@ -112,8 +136,11 @@ export async function loadCodeGraph(): Promise<VizGraph | null> {
return { meta: { nodeCount: nodes.length, edgeCount: edges.length }, nodes, edges };
}
-/** Subscribe to the server's live-reload channel. */
+/** Subscribe to the server's live-reload channel, when there is a server at all. */
export function onServerChange(handler: () => void): void {
+ // An exported page has no /events endpoint, and EventSource retries a failed
+ // connection forever — a console error every few seconds on a static file.
+ if (inlined) return;
const source = new EventSource("/events");
source.onmessage = (ev) => {
if (ev.data === "change") handler();
diff --git a/viewer/main.ts b/viewer/main.ts
index e94184ef..49132ad7 100644
--- a/viewer/main.ts
+++ b/viewer/main.ts
@@ -264,9 +264,16 @@ async function loadAll(): Promise<void> {
const [context, code] = await Promise.all([loadContextGraph(), loadCodeGraph()]);
state.context = context;
state.code = code;
- $("repoName").textContent = context.meta.repoName ?? "";
- document.title = `graft viz — ${context.meta.repoName ?? ""}`;
- setTab(state.tab);
+ // The subtitle only exists on an exported page (`graft viz --export --title`),
+ // where the same file is published per pull request and the reader needs to know
+ // WHICH one they opened.
+ const where = [context.meta.repoName, context.meta.subtitle].filter(Boolean).join(" · ");
+ $("repoName").textContent = where;
+ document.title = `graft viz — ${where}`;
+ // An exported page says which tab holds its content: a structural build has no
+ // concept nodes, so the default Context tab would open on an empty canvas.
+ const wanted = context.meta.defaultTab;
+ setTab(wanted && wanted !== state.tab ? wanted : state.tab);
}
onServerChange(() => {