Skip to content

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

feat(blast): suggest who to tag, from git history over each affected area (#246)

anirudhkumar-nanonetsec3fc4151b39
diff --git a/.github/actions/graft-blast/action.yml b/.github/actions/graft-blast/action.yml
index 08ea019b..62b62cc9 100644
--- a/.github/actions/graft-blast/action.yml
+++ b/.github/actions/graft-blast/action.yml
@@ -1,7 +1,8 @@
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.
+ affect and who has worked on it, and post that 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.
@@ -26,6 +27,13 @@ inputs:
thirteen minutes per run.
required: false
default: "true"
+ suggest-reviewers:
+ description: >-
+ Name the people behind each affected area, read from git history, so the author
+ can tag them. Needs the same `fetch-depth: 0` checkout the diff already needs.
+ Set false to leave people out of the comment entirely.
+ required: false
+ default: "true"
comment:
description: Post/update the PR comment. Set false to only produce the outputs.
required: false
@@ -120,20 +128,44 @@ runs:
BASE: ${{ inputs.base != '' && inputs.base || format('origin/{0}', github.event.pull_request.base.ref) }}
DEPTH: ${{ inputs.depth }}
NAME_AREAS: ${{ inputs.name-areas }}
+ SUGGEST_REVIEWERS: ${{ inputs.suggest-reviewers }}
+ # Both, because they are two different keys on the same person: CI knows the
+ # login, while the commits in the diff carry the email. Excluding on one alone
+ # tells roughly half of all authors to tag themselves.
+ PR_AUTHOR: ${{ github.event.pull_request.user.login }}
+ PR_AUTHOR_EMAIL: ${{ github.event.pull_request.user.email }}
VIEWER_URL: ${{ inputs.viewer-url }}
EXPORT_VIZ: ${{ inputs.export-viewer }}
GRAFT: ${{ inputs.graft-cmd }}
run: |
set -euo pipefail
- name=""
- if [ "$NAME_AREAS" = "true" ]; then name="--name"; fi
- # One command for both outputs: the page and the comment then describe the
- # same radius, named once. A second `viz --export` step could drift from it.
- viz=""
- if [ -n "$EXPORT_VIZ" ]; then viz="--export-viz $EXPORT_VIZ"; fi
+ # An ARRAY, not a string: a value here can contain a space (a git display
+ # name does), and word-splitting an interpolated string is the same class of
+ # bug as interpolating a workflow expression into shell text. Nothing is
+ # ever `eval`ed. Note that a literal GitHub expression cannot appear even in
+ # a comment in this block — the template engine evaluates `run:` before bash
+ # ever sees it, and an empty one fails the whole action to load.
+ args=(blast . --base "$BASE" --depth "$DEPTH")
# --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 $viz --format markdown > blast.md
+ if [ "$NAME_AREAS" = "true" ]; then args+=(--name); fi
+ # One command for both outputs: the page and the comment then describe the
+ # same radius, named once. A second `viz --export` step could drift from it.
+ if [ -n "$EXPORT_VIZ" ]; then args+=(--export-viz "$EXPORT_VIZ"); fi
+ if [ "$SUGGEST_REVIEWERS" = "true" ]; then
+ # Both keys for the same person, and neither is reliable alone: CI has the
+ # login, the commits have the email, and the webhook usually leaves the
+ # email empty. `graft blast` also excludes every author in the diff range
+ # itself, which is what actually covers the empty-email case.
+ authors=()
+ if [ -n "$PR_AUTHOR" ]; then authors+=("$PR_AUTHOR"); fi
+ if [ -n "$PR_AUTHOR_EMAIL" ]; then authors+=("$PR_AUTHOR_EMAIL"); fi
+ if [ ${#authors[@]} -gt 0 ]; then args+=(--pr-author "${authors[@]}"); fi
+ else
+ args+=(--no-owners)
+ fi
+ args+=(--format markdown)
+ $GRAFT "${args[@]}" > 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
diff --git a/.github/workflows/blast-pages.yml b/.github/workflows/blast-pages.yml
index ed972fbd..bd4e1eb6 100644
--- a/.github/workflows/blast-pages.yml
+++ b/.github/workflows/blast-pages.yml
@@ -66,8 +66,10 @@ jobs:
case "$NUMBER" in
"" | *[!0-9]*) echo "not a pull request number: $NUMBER" >&2; exit 1 ;;
esac
+ # `author` is the login only — an email is not in this payload, and the
+ # commits in the range carry the identity `blast` really matches on.
gh api "repos/$REPO/pulls/$NUMBER" --jq \
- '"number=\(.number)", "base_ref=\(.base.ref)", "base_sha=\(.base.sha)"' >> "$GITHUB_OUTPUT"
+ '"number=\(.number)", "base_ref=\(.base.ref)", "base_sha=\(.base.sha)", "author=\(.user.login)"' >> "$GITHUB_OUTPUT"
# 1. The tooling, from the base branch — never from the PR.
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
@@ -114,6 +116,7 @@ jobs:
env:
PR_NUMBER: ${{ steps.pr.outputs.number }}
BASE_REF: ${{ steps.pr.outputs.base_ref }}
+ PR_AUTHOR: ${{ steps.pr.outputs.author }}
# `--name` reads a key, so the page gets the same concept names the comment
# shows instead of hub-symbol fallbacks. The PR's code is never executed
# here (see the header) — naming only sends its source text to the model,
@@ -136,8 +139,14 @@ jobs:
# `--format markdown`, not text: one run produces both the page and the
# comment body, so the two can never describe different radii or word the
# same area differently.
+ #
+ # `--pr-author` is belt to `blast`'s own braces: it already drops everyone
+ # who authored a commit in the range, which covers the author under the
+ # name and email git actually records. The login is passed too for the one
+ # case that misses — a squash merge attributed to a different identity.
node ../base/dist/cli.js blast . --base "origin/$BASE_REF" \
- --name --title "PR #$PR_NUMBER" --export-viz ../site --format markdown > ../blast.md
+ --name --title "PR #$PR_NUMBER" --pr-author "$PR_AUTHOR" \
+ --export-viz ../site --format markdown > ../blast.md
cat ../blast.md >> "$GITHUB_STEP_SUMMARY"
- name: Publish to gh-pages
diff --git a/.mailmap b/.mailmap
new file mode 100644
index 00000000..48dc5b58
--- /dev/null
+++ b/.mailmap
@@ -0,0 +1,24 @@
+# Canonical identities.
+#
+# Left of the angle brackets is the identity git should REPORT; on the right is
+# the identity a commit actually carries. Nothing is rewritten — git applies this
+# as a lookup when it reads history (`%aN`/`%aE`, `git shortlog`, `git blame`).
+#
+# Every canonical address here is the person's GitHub noreply address, which is
+# what makes them mentionable: `graft blast` reads a handle out of that form and
+# refuses to guess one from anything else, so without a line here a contributor
+# who commits under a personal or work address is printed as plain text a PR
+# author has to tag by hand.
+#
+# Each mapping below was resolved by GitHub itself (the commits API reports the
+# account it links an authoring email to) rather than matched on name.
+
+# Not linked to any account on GitHub's side; mapped on the strength of the
+# identical display name and its three commits sitting among the others.
+anirudhkumar-nanonets <[email protected]> <[email protected]>
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a54410bc..ed8a5dbc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,29 @@
# Changelog
+## Unreleased
+
+### Added
+
+- **`graft blast` suggests who to tag.** The comment already named the areas a
+ diff changes and the areas it can affect; it now names the people behind them,
+ read from git history with no API call and no config file. One `git log` per
+ area over that area's own files, weighted towards recent work (120-day
+ half-life), with areas the diff only *reaches* counted at 0.6 against a changed
+ area's 1.0 — the person whose code your change can break is exactly the
+ reviewer the diff alone would never surface. The markdown report gains a `Tag:`
+ line under the tests line and a collapsed `Who knows this code` table; the
+ exported page gains initials badges on each bubble, a *Who knows this* block in
+ the detail panel, and a `people` legend toggle.
+
+ A handle is never guessed: only a GitHub noreply commit address resolves to
+ `@mention`, and anyone else is printed as a plain unlinked name, because a
+ guessed mention pings a stranger. A repo can fix that for good with a
+ `.mailmap` entry, which git applies to the names `blast` reads. Merge commits,
+ bots, everyone who authored a commit in the diff range, and — for a local run
+ with no `--base` — your own git identity are all excluded. `--no-owners` turns
+ the layer off; `--pr-author <who...>` takes logins, names or emails; the
+ bundled action gains a `suggest-reviewers` input, defaulting true.
+
## 0.13.0
### Added
diff --git a/README.md b/README.md
index d75d2358..3d60265e 100644
--- a/README.md
+++ b/README.md
@@ -358,6 +358,7 @@ graft blast --base origin/main # diff against the merge base with HEAD —
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 --export-viz site/ # also write the interactive page for this radius (what a PR comment links to)
+graft blast --no-owners # skip "who to tag" — by default git history names the people behind each area
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)
diff --git a/src/blast/blast-cli.ts b/src/blast/blast-cli.ts
index 4e16ac2c..20eb1568 100644
--- a/src/blast/blast-cli.ts
+++ b/src/blast/blast-cli.ts
@@ -30,6 +30,11 @@ export interface BlastCliOptions {
* meaning as `graft viz --title`. Without it a reader of a published page has no
* way to tell which pull request they are looking at. */
title?: string;
+ /** Suggest who to tag, from git history over each area. On by default; `--no-owners`
+ * turns the whole layer off for a repo that would rather not name people. */
+ owners?: boolean;
+ /** The PR author: logins, names or emails to keep out of their own suggestions. */
+ prAuthor?: string[];
/** The top-level `--dir` override. */
globalDir?: string;
}
@@ -87,6 +92,21 @@ export async function runBlastCommand(dir: string, opts: BlastCliOptions): Promi
const report = blastRadiusIn(graph, contextDir, diff.files, diff.basis, depth);
if (opts.name) await nameClusters(graph, report, contextDir);
+ // After naming, never before: a reviewer's reason cites area LABELS, and the
+ // naming pass is what gives an area its final one.
+ if (opts.owners !== false) {
+ const { attachOwners, diffAuthors, localIdentity } = await import("./owners.js");
+ // Everyone who wrote a commit in this range, plus whatever the caller named.
+ // The range is the reliable half: CI knows the author's login but almost never
+ // their commit email, and the email is what git history is keyed on.
+ //
+ // With no --base there is no range — this is the local "what am I about to
+ // push" case — so the local git identity stands in for it. Without that, the
+ // one person certain to have written the change is the top name in its own
+ // list of who to ask about it.
+ const authors = opts.base === undefined ? localIdentity(root) : diffAuthors(root, opts.base);
+ attachOwners(root, report, { exclude: [...authors, ...(opts.prAuthor ?? [])] });
+ }
if (opts.exportViz) await exportRadius(report, contextDir, root, opts.exportViz, opts.title);
if (format === "json") {
diff --git a/src/blast/blast.ts b/src/blast/blast.ts
index d625fc81..7189d848 100644
--- a/src/blast/blast.ts
+++ b/src/blast/blast.ts
@@ -17,6 +17,7 @@ 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";
+import type { Owner, Reviewer } from "./owners.js";
const SPAN_RE = /^L(\d+)-L(\d+)$/;
@@ -74,6 +75,9 @@ export interface ImpactedModule {
symbols: Impacted[];
/** Changed files whose edges reached this module — the diagram's arrows. */
from: string[];
+ /** Who has worked on these files, best first. Filled in by `attachOwners`;
+ * absent when the radius was taken outside a git repository. */
+ owners?: Owner[];
}
/**
@@ -109,6 +113,8 @@ export interface ChangedArea {
/** Changed symbol names, behaviour first — the backstop label and the naming
* prompt both read from this. */
seedNames: string[];
+ /** Who has worked on these files, best first — see {@link ImpactedModule.owners}. */
+ owners?: Owner[];
}
export interface BlastReport {
@@ -127,6 +133,9 @@ export interface BlastReport {
areas: ChangedArea[];
/** Test-only dependents, kept out of `modules` so they cannot crowd it out. */
testModules: ImpactedModule[];
+ /** Who to tag, ranked across every area. Absent outside a git repository, and
+ * empty when the author is the only person in the history. */
+ reviewers?: Reviewer[];
}
function spanBounds(span: string): { start: number; end: number } | null {
diff --git a/src/blast/owners.ts b/src/blast/owners.ts
new file mode 100644
index 00000000..c811493e
--- /dev/null
+++ b/src/blast/owners.ts
@@ -0,0 +1,311 @@
+/**
+ * Who to tag on a pull request: the people whose fingerprints are on the areas
+ * this diff changes or can affect.
+ *
+ * The blast report already answers "what does this reach"; the author's next
+ * question is "who do I ask about it", and git has the answer without a single
+ * API call. One `git log` per area over that area's OWN files, scored by recency,
+ * ranked, capped.
+ *
+ * Two rules keep the output honest, and both exist because a wrong name here is
+ * worse than no name:
+ *
+ * - A handle is only ever printed when git actually carries one (the GitHub
+ * noreply address, which anything merged through the web UI has). With no
+ * handle the display name is printed unlinked — a guessed `@mention` pings a
+ * stranger, and there is no cheap way to verify a guess.
+ * - An owner has to hold {@link MIN_SHARE} of an area's weight to be named. That
+ * drops a drive-by typo fix next to a real owner, and keeps it when the
+ * drive-by is all the history there is.
+ *
+ * Everything here is best-effort: no git, no repository, a detached tarball
+ * checkout or a shallow clone leaves the report exactly as it was and the comment
+ * simply says nothing about people.
+ */
+import { spawnSync } from "node:child_process";
+import { resolve } from "node:path";
+import type { BlastReport } from "./blast.js";
+
+/** One person's claim on one area. */
+export interface Owner {
+ /** Display name as git reports it, with `.mailmap` already applied. */
+ name: string;
+ /** GitHub handle, when the commit email carries one. Never guessed. */
+ handle?: string;
+ /** Commits of theirs that touched this area's files. */
+ commits: number;
+ /** Recency-weighted weight of those commits — the ranking key. */
+ score: number;
+ /** Their most recent commit here, ms since the epoch. */
+ last: number;
+}
+
+/** One person's claim across the whole report: what the tag line prints. */
+export interface Reviewer extends Owner {
+ /** Area labels they own, heaviest first. */
+ areas: string[];
+}
+
+export interface OwnerOptions {
+ /** Logins, names or emails to drop — the PR author, so they are not told to
+ * tag themselves. Matched case-insensitively against all three. */
+ exclude?: string[];
+ /** Clock, so a test can plant history at a fixed distance from "now". */
+ now?: number;
+}
+
+/**
+ * Recency half-life. A commit from four months ago counts half as much as one
+ * from today, so the person who rewrote a module last month outranks the person
+ * who created it two years ago and moved on — which is the reviewer an author
+ * actually wants.
+ */
+const HALF_LIFE_MS = 120 * 24 * 60 * 60 * 1000;
+
+/**
+ * History window and commit cap, per area.
+ *
+ * Both are bounds on the walk, not on the answer: at 36 months a commit is worth
+ * 0.002 of a fresh one, so nothing outside the window could survive the share
+ * floor anyway, and the pair keeps one `git log` off a large repo's full history.
+ */
+const SINCE = "36.months";
+const MAX_COMMITS = 400;
+
+/** Files passed to one `git log`. A very wide area is sampled rather than blowing
+ * the argument list; the sample is the area's own sorted file list, so it is
+ * stable between runs rather than whichever files git happened to yield. */
+const MAX_PATHSPEC = 80;
+
+/** Share of an area's total weight an owner must hold to be named. */
+const MIN_SHARE = 0.15;
+
+/** Names listed per area, and in the tag line. */
+export const MAX_PER_AREA = 2;
+export const MAX_REVIEWERS = 3;
+
+/**
+ * Weight of an area a diff only *reaches*, against one it edits.
+ *
+ * Not zero, because the person whose code your change can break is exactly the
+ * reviewer the diff alone would never surface — that is what the blast radius is
+ * for. Not one either: the author of the code you edited knows it better.
+ */
+const AFFECTED_WEIGHT = 0.6;
+
+/**
+ * A GitHub handle out of a commit email, or null.
+ *
+ * Both noreply forms are accepted: the modern `12345+name@` and the legacy bare
+ * `name@`. The character class is GitHub's own username rule (alphanumerics and
+ * interior hyphens, 39 max) so an address that merely ends in the right domain
+ * cannot smuggle something unmentionable into a comment body.
+ */
+export function githubHandle(email: string): string | null {
+ const m = /^(?:\d+\+)?([A-Za-z0-9](?:-?[A-Za-z0-9]){0,38})@users\.noreply\.github\.com$/i.exec(email.trim());
+ return m ? m[1] : null;
+}
+
+/** Bots write commits and are never reviewers. */
+function isBot(name: string, email: string): boolean {
+ return /\[bot\]/i.test(name) || /\[bot\]@/i.test(email) || /^(github-actions|dependabot|renovate)(\[bot\])?$/i.test(name.trim());
+}
+
+/** Run git in `root`, or null when git fails — not a repo, no git, no history. */
+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;
+}
+
+/**
+ * The people behind `files`, best first.
+ *
+ * `--no-merges` because a merge commit's author is whoever pressed the button,
+ * not whoever wrote the code. `%aN`/`%aE` rather than `%an`/`%ae` so git applies
+ * the repository's `.mailmap` for us — which is the supported way to give a
+ * contributor whose work address has no handle a noreply one, at no new config
+ * cost to graft.
+ */
+export function ownersFor(root: string, files: string[], opts: OwnerOptions = {}): Owner[] {
+ const paths = [...files].sort().slice(0, MAX_PATHSPEC);
+ if (paths.length === 0) return [];
+
+ const now = opts.now ?? Date.now();
+ const out = git(resolve(root), [
+ "log",
+ "--no-merges",
+ `--since=${SINCE}`,
+ "-n",
+ String(MAX_COMMITS),
+ "--format=\x01%H\x02%aI\x02%aN\x02%aE",
+ "--name-only",
+ "--",
+ ...paths,
+ ]);
+ if (out === null) return [];
+
+ const wanted = new Set(paths);
+ const people = new Map<string, Owner & { seen: Set<string> }>();
+ let commit: { hash: string; at: number; weight: number; name: string; email: string } | null = null;
+
+ for (const line of out.split("\n")) {
+ if (line.startsWith("\x01")) {
+ const [hash, iso, name, email] = line.slice(1).split("\x02");
+ const at = Date.parse(iso ?? "");
+ commit = Number.isFinite(at)
+ ? { hash, at, weight: Math.pow(0.5, (now - at) / HALF_LIFE_MS), name: name ?? "", email: email ?? "" }
+ : null;
+ continue;
+ }
+ // A pathspec'd `git log --name-only` already lists only matching files, but
+ // the set is re-checked here so a future flag change cannot silently start
+ // crediting whoever touched an unrelated file in the same commit.
+ if (commit === null || !wanted.has(line)) continue;
+ if (isBot(commit.name, commit.email)) continue;
+
+ const handle = githubHandle(commit.email) ?? undefined;
+ const key = (handle ?? commit.email).toLowerCase();
+ const prev = people.get(key);
+ if (!prev) {
+ people.set(key, {
+ name: commit.name, handle, commits: 1, score: commit.weight, last: commit.at,
+ seen: new Set([commit.hash]),
+ });
+ continue;
+ }
+ // One commit touching six files in the area is one commit, not six.
+ if (prev.seen.has(commit.hash)) continue;
+ prev.seen.add(commit.hash);
+ prev.commits += 1;
+ prev.score += commit.weight;
+ prev.last = Math.max(prev.last, commit.at);
+ }
+
+ const excluded = new Set((opts.exclude ?? []).map((e) => e.trim().toLowerCase()).filter(Boolean));
+ const isExcluded = (o: Owner, email: string) =>
+ excluded.has(email.toLowerCase()) ||
+ excluded.has(o.name.toLowerCase()) ||
+ (o.handle !== undefined && excluded.has(o.handle.toLowerCase()));
+
+ const kept = [...people].filter(([email, o]) => !isExcluded(o, email)).map(([, o]) => o);
+ // The floor is a SHARE of what is left after the author is dropped, not of the
+ // whole area. On a repo where one person wrote everything, their own PR would
+ // otherwise leave every remaining contributor under the floor and report nobody.
+ const total = kept.reduce((n, o) => n + o.score, 0);
+ return kept
+ .filter((o) => total === 0 || o.score / total >= MIN_SHARE)
+ .sort((a, b) => b.score - a.score || b.commits - a.commits || a.name.localeCompare(b.name))
+ .slice(0, MAX_PER_AREA)
+ .map(({ name, handle, commits, score, last }) => ({ name, handle, commits, score, last }));
+}
+
+/**
+ * Everyone who authored a commit in `base...HEAD` — the people whose work this
+ * pull request IS.
+ *
+ * This is the exclusion that actually fires in CI. The obvious source for "who
+ * opened this" is `pull_request.user.email` from the webhook, but GitHub almost
+ * never populates it, so excluding on the login alone leaves anyone whose commits
+ * carry a work address being suggested as a reviewer of their own PR. The commits
+ * in the range carry exactly the name and email git will match on later.
+ *
+ * Co-authors count too: a pair-programmed commit has two people on it and neither
+ * of them is a reviewer of it.
+ */
+export function diffAuthors(root: string, base: string): string[] {
+ const out = git(resolve(root), ["log", "--format=%aN%n%aE%n%(trailers:key=Co-authored-by,valueonly)", `${base}...HEAD`]);
+ if (out === null) return [];
+ const names = new Set<string>();
+ for (const raw of out.split("\n")) {
+ const line = raw.trim();
+ if (line === "") continue;
+ // A co-author trailer is `Name <email>`; both halves are worth excluding.
+ const m = /^(.*?)\s*<([^>]+)>$/.exec(line);
+ if (m) {
+ if (m[1]) names.add(m[1]);
+ names.add(m[2]);
+ continue;
+ }
+ names.add(line);
+ }
+ return [...names];
+}
+
+/**
+ * Whoever git would sign a commit as, here and now.
+ *
+ * The local counterpart of {@link diffAuthors}. `graft blast` with no `--base`
+ * compares the working tree against HEAD, so there is no commit range to read
+ * authors from — and without this, the one person guaranteed to have written the
+ * change being examined is also the top name in its own "who to tag" list.
+ */
+export function localIdentity(root: string): string[] {
+ const dir = resolve(root);
+ const out = [git(dir, ["config", "user.name"]), git(dir, ["config", "user.email"])];
+ return out.map((v) => v?.trim() ?? "").filter((v) => v !== "");
+}
+
+/**
+ * Fill in `owners` on every area and module, and rank the report's `reviewers`.
+ *
+ * Called AFTER `--name`, because a reviewer's reason cites area labels and the
+ * naming pass is what gives an area its final label.
+ */
+export function attachOwners(root: string, report: BlastReport, opts: OwnerOptions = {}): void {
+ const ranked = new Map<string, Reviewer & { weighted: number }>();
+
+ const visit = (label: string, files: string[], weight: number): Owner[] => {
+ const owners = ownersFor(root, files, opts);
+ for (const o of owners) {
+ const key = (o.handle ?? o.name).toLowerCase();
+ const prev = ranked.get(key);
+ if (!prev) {
+ ranked.set(key, { ...o, areas: [label], weighted: o.score * weight });
+ continue;
+ }
+ prev.areas.push(label);
+ prev.commits += o.commits;
+ prev.score += o.score;
+ prev.weighted += o.score * weight;
+ prev.last = Math.max(prev.last, o.last);
+ // A handle found on any one area is the handle: a contributor who has some
+ // commits from the web UI and some from a laptop should still be taggable.
+ if (prev.handle === undefined && o.handle !== undefined) prev.handle = o.handle;
+ }
+ return owners;
+ };
+
+ for (const area of report.areas) area.owners = visit(area.label, area.files, 1);
+ for (const mod of report.modules) mod.owners = visit(mod.label, mod.files, AFFECTED_WEIGHT);
+
+ report.reviewers = [...ranked.values()]
+ .sort((a, b) => b.weighted - a.weighted || b.commits - a.commits || a.name.localeCompare(b.name))
+ .slice(0, MAX_REVIEWERS)
+ .map(({ weighted: _weighted, ...r }) => r);
+}
+
+/** `9d ago`, `3mo ago` — how a comment says when someone was last in here. */
+export function sinceLabel(last: number, now: number = Date.now()): string {
+ const days = Math.max(0, Math.round((now - last) / (24 * 60 * 60 * 1000)));
+ if (days < 1) return "today";
+ if (days === 1) return "yesterday";
+ if (days < 31) return `${days}d ago`;
+ const months = Math.round(days / 30);
+ return months < 24 ? `${months}mo ago` : `${Math.round(days / 365)}y ago`;
+}
+
+/** `@handle`, or the bare name when git carries no handle for them. */
+export function mention(o: Owner): string {
+ return o.handle !== undefined ? `@${o.handle}` : o.name;
+}
+
+/** ISO day, for an exported page that has to stay truthful when opened later. */
+export function isoDay(ms: number): string {
+ return new Date(ms).toISOString().slice(0, 10);
+}
diff --git a/src/blast/render.ts b/src/blast/render.ts
index bdb8bad4..9f6fbe1b 100644
--- a/src/blast/render.ts
+++ b/src/blast/render.ts
@@ -12,9 +12,10 @@
* 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, Impacted, TestSignal } from "./blast.js";
+import type { BlastReport, ChangedArea, ImpactedModule, Impacted, TestSignal } from "./blast.js";
import type { Evidence } from "../viz/assemble.js";
import { fileReader, impactedEvidence, reachTerms } from "./evidence.js";
+import { MAX_REVIEWERS, mention, sinceLabel, type Owner } from "./owners.js";
/** Diagram cap. Everything past it folds into one aggregate circle carrying the
* dropped counts, so the picture shrinks but never lies. */
@@ -23,6 +24,9 @@ const MAX_MODULE_BOXES = 5;
const MAX_TABLE_ROWS = 6;
/** Symbols listed in the one collapsed list of everything. */
const MAX_SYMBOLS_LISTED = 60;
+/** Rows in the collapsed ownership table. Past this it is a `git shortlog`, not a
+ * hint about who to ask. */
+const MAX_OWNER_ROWS = 8;
/**
* A quoted Mermaid label. Every line is escaped on its own and only then joined
@@ -117,6 +121,10 @@ export function markdownReport(r: BlastReport, opts: { root?: string } = {}): st
out.push(headline(r, symbols));
const testLine = testHeadline(r);
if (testLine) out.push(testLine);
+ // Above the diagram on purpose: it is the one line in this comment the author
+ // ACTS on rather than reads, and it costs a single row before the picture.
+ const tag = tagLine(r);
+ if (tag) out.push(tag);
if (symbols > 0) {
const diagram = mermaidDiagram(r);
@@ -130,6 +138,12 @@ export function markdownReport(r: BlastReport, opts: { root?: string } = {}): st
out.push(...impactTable(r));
}
+ const owners = ownerSection(r);
+ if (owners.length > 0) {
+ out.push("");
+ out.push(...owners);
+ }
+
out.push("");
const reach = reachTerms(r.seeds, r.changed);
const read = fileReader(opts.root);
@@ -200,6 +214,92 @@ function impactTable(r: BlastReport): string[] {
return rows;
}
+/**
+ * The tag line: who to ask, and why them.
+ *
+ * A handle is printed only where git carried one — `mention` never invents an
+ * `@`, because a guessed mention pings a stranger who has nothing to do with the
+ * change. A bare name is bolded instead, so it still reads as a person.
+ *
+ * Null on a repository where the author is the only name in the history: an
+ * empty "Tag:" is worse than no line, and every solo project would carry one.
+ */
+function tagLine(r: BlastReport): string | null {
+ const people = r.reviewers ?? [];
+ if (people.length === 0) return null;
+ const total = r.areas.length + r.modules.length;
+ const bits = people.map((p) => {
+ const who = p.handle !== undefined ? `@${p.handle}` : `**${p.name}**`;
+ // Three or more areas is a count, not a list: naming eleven of them turns the
+ // one actionable line in the comment into the longest paragraph in it.
+ const why = p.areas.length >= 3 ? `${p.areas.length} of ${total} areas` : p.areas.join(", ");
+ return `${who} — ${why}`;
+ });
+ return `Tag: ${bits.join(" · ")}`;
+}
+
+/** `Shrish Dwivedi — 57 commits, last 9d ago`, for one cell of the table. */
+function ownerCell(owners: Owner[] | undefined, now: number): string {
+ if (owners === undefined || owners.length === 0) {
+ // Said in words rather than left blank: "nobody else" is a real answer, and an
+ // empty cell reads as a renderer that failed.
+ return "_only you — nobody else has touched these files_";
+ }
+ return owners
+ .map((o) => `${mention(o)} — ${plural(o.commits, "commit")}, last ${sinceLabel(o.last, now)}`)
+ .join(" · ");
+}
+
+/**
+ * The collapsed evidence behind the tag line: one row per area, both sides.
+ *
+ * Kept collapsed and kept below the impact table because it justifies a decision
+ * the author has already been handed at the top. Nothing here is a gate — the
+ * caveat says so, since a table of names next to a diff invites being read as
+ * CODEOWNERS.
+ */
+function ownerSection(r: BlastReport): string[] {
+ if (r.reviewers === undefined) return []; // taken outside a git repository
+ const rows: { label: string; side: string; owners?: Owner[] }[] = [
+ ...r.areas.map((a: ChangedArea) => ({ label: a.label, side: "changed", owners: a.owners })),
+ ...r.modules.map((m: ImpactedModule) => ({ label: m.label, side: "affected", owners: m.owners })),
+ ];
+ const named = rows.filter((row) => (row.owners?.length ?? 0) > 0);
+ if (named.length === 0) return [];
+
+ const now = Date.now();
+ const people = new Set<string>();
+ for (const row of rows) for (const o of row.owners ?? []) people.add(o.handle ?? o.name);
+
+ const out = ["<details>"];
+ out.push(
+ `<summary><strong>Who knows this code</strong> — ${plural(people.size, "person", "people")} ` +
+ `across ${plural(rows.length, "area")}</summary>`,
+ );
+ out.push("");
+ out.push("| Area | Who knows it |");
+ out.push("| --- | --- |");
+ // Areas with names first: a row saying "only you" is context, not an answer, so
+ // it must never be what the cap spends its budget on.
+ const ordered = [...named, ...rows.filter((row) => !named.includes(row))];
+ for (const row of ordered.slice(0, MAX_OWNER_ROWS)) {
+ out.push(`| **${row.label}** · ${row.side} | ${ownerCell(row.owners, now)} |`);
+ }
+ if (ordered.length > MAX_OWNER_ROWS) {
+ out.push(`| _…${plural(ordered.length - MAX_OWNER_ROWS, "further area")}_ | |`);
+ }
+ out.push("");
+ out.push(
+ "_Ownership is git history over each area's own files, weighted towards recent work " +
+ "(120-day half-life). Merge commits and bots are dropped, and you are dropped from your own PR. " +
+ "A name with no `@` has no GitHub handle in its commit email — tag them by hand, or add a " +
+ "`.mailmap` entry. A suggestion from history, not a CODEOWNERS rule._",
+ );
+ out.push("");
+ out.push("</details>");
+ return out;
+}
+
/**
* Everything a reviewer might want and nobody reads by default, in three sections.
*
@@ -336,6 +436,15 @@ export function textReport(r: BlastReport): string {
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)`, "");
}
+ if (r.reviewers !== undefined && r.reviewers.length > 0) {
+ const now = Date.now();
+ lines.push("who to tag");
+ for (const p of r.reviewers.slice(0, MAX_REVIEWERS)) {
+ const why = p.areas.length >= 3 ? `${p.areas.length} areas` : p.areas.join(", ");
+ lines.push(` ${mention(p)} — ${why} · ${plural(p.commits, "commit")}, last ${sinceLabel(p.last, now)}`);
+ }
+ lines.push("");
+ }
for (const line of caveatLines(r)) lines.push(line.replace(/⚠️ /, "⚠ "), "");
return lines.join("\n").replace(/\n+$/, "\n");
}
diff --git a/src/blast/viz.ts b/src/blast/viz.ts
index 17f4a733..5cb359d2 100644
--- a/src/blast/viz.ts
+++ b/src/blast/viz.ts
@@ -18,9 +18,10 @@
* affected side shows the line that reaches the diff. Both come from data already
* on hand — git's patch, and the file on disk — so the panel costs nothing.
*/
-import type { Evidence, VizEdge, VizGraph, VizNode } from "../viz/assemble.js";
+import type { Evidence, NodeOwner, VizEdge, VizGraph, VizNode } from "../viz/assemble.js";
import type { BlastReport, ChangedArea, ImpactedModule, Seed, TestSignal } from "./blast.js";
import type { ChangedFile } from "./diff.js";
+import { isoDay, type Owner } from "./owners.js";
import {
MAX_EVIDENCE,
type ReachTerms,
@@ -32,6 +33,13 @@ import {
const plural = (n: number, one: string, many = `${one}s`): string => `${n} ${n === 1 ? one : many}`;
+/** Owners as the page carries them: no scores, since a weight nobody can check is
+ * not evidence — the commit count and the date are what a reader can verify. */
+function nodeOwners(owners: Owner[] | undefined): NodeOwner[] | undefined {
+ if (owners === undefined || owners.length === 0) return undefined;
+ return owners.map((o) => ({ name: o.name, handle: o.handle, commits: o.commits, last: isoDay(o.last) }));
+}
+
/** Kinds that carry behaviour — what "did a test reach it" is asked of. */
const BEHAVIOURAL = new Set(["function", "method", "class", "constructor"]);
@@ -101,6 +109,7 @@ function changedNode(a: ChangedArea, seeds: Seed[], byPath: Map<string, ChangedF
summary: changedSummary(a, mine),
sources: a.files,
evidence: evidence.length > 0 ? evidence : undefined,
+ owners: nodeOwners(a.owners),
};
}
@@ -125,6 +134,7 @@ function affectedNode(
summary: `Not edited by this PR. ${plural(m.symbols.length, "symbol")} here ${m.symbols.length === 1 ? "reaches" : "reach"} code it changed${how}`,
sources: m.symbols.map((s) => `${s.path} · ${s.span}`),
evidence: evidence.length > 0 ? evidence : undefined,
+ owners: nodeOwners(m.owners),
};
}
diff --git a/src/cli.ts b/src/cli.ts
index fc83c6e7..27f925c1 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -732,8 +732,10 @@ program
.option("--name", "name the affected areas with one cached LLM call (needs GRAFT_API_KEY); without it, areas are named after their hub symbol")
.option("--export-viz <dir>", "also write the interactive page for this radius (one self-contained index.html — for CI, GitHub Pages, or an artifact)")
.option("--title <text>", "subtitle beside the repo name on the exported page (e.g. \"PR #171\")")
+ .option("--no-owners", "do not suggest who to tag (by default, git history names the people behind each affected area)")
+ .option("--pr-author <who...>", "GitHub login, git name or email of the PR author, so they are left out of their own suggestions")
.option(...NO_REFRESH_FLAG)
- .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; title?: string; refresh?: boolean }) => {
+ .action(async (dirArg: string | undefined, opts: { base?: string; depth?: string; format?: string; name?: boolean; exportViz?: string; title?: string; owners?: boolean; prAuthor?: string[]; refresh?: boolean }) => {
const dir = noteQuery(queryRoot(dirArg));
await refreshBefore(dir, opts);
const { runBlastCommand } = await import("./blast/blast-cli.js");
@@ -744,6 +746,8 @@ program
name: opts.name,
exportViz: opts.exportViz,
title: opts.title,
+ owners: opts.owners,
+ prAuthor: opts.prAuthor,
globalDir: program.opts<GlobalOpts>().dir,
});
});
diff --git a/src/viz/assemble.ts b/src/viz/assemble.ts
index 815e5215..dcad4c3e 100644
--- a/src/viz/assemble.ts
+++ b/src/viz/assemble.ts
@@ -24,6 +24,24 @@ export interface VizNode {
/** Code to show under the node, in place of `sources`. Set by
* `blast --export-viz`, where every node stands for real changed lines. */
evidence?: Evidence[];
+ /** Who has worked on this area, best first. Set by `blast --export-viz`. */
+ owners?: NodeOwner[];
+}
+
+/**
+ * One contributor on a node, as the exported page carries them.
+ *
+ * `last` is an ISO day rather than "9d ago" so the page stays truthful when it is
+ * opened a fortnight after it was published — the viewer does the arithmetic at
+ * read time. `handle` is absent whenever git carried no GitHub address for them,
+ * and the viewer must then render the name unlinked.
+ */
+export interface NodeOwner {
+ name: string;
+ handle?: string;
+ commits: number;
+ /** `YYYY-MM-DD` of their most recent commit in this area. */
+ last: string;
}
export interface VizEdge {
diff --git a/test/blast-owners.test.ts b/test/blast-owners.test.ts
new file mode 100644
index 00000000..b4dc8e48
--- /dev/null
+++ b/test/blast-owners.test.ts
@@ -0,0 +1,206 @@
+/**
+ * Who the comment tells you to tag.
+ *
+ * Every case here is a way this feature can do real damage rather than merely be
+ * unhelpful: naming a bot, naming the author back to themselves, or — worst —
+ * inventing an `@mention` for someone whose commit email carries no handle, which
+ * pings a stranger who has nothing to do with the change.
+ *
+ * The fixture is a real repository with planted history, because the whole
+ * feature is a `git log` and a stub of git would only assert the parser against
+ * itself. Commit dates are set explicitly so the recency weighting is testable at
+ * all: `now` is passed in, and the fixture's commits sit at known distances from it.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { attachOwners, diffAuthors, githubHandle, localIdentity, ownersFor, sinceLabel } from "../src/blast/owners.js";
+import type { BlastReport, ChangedArea, ImpactedModule } from "../src/blast/blast.js";
+
+const DAY = 24 * 60 * 60 * 1000;
+/** The fixture's "today". Fixed so a commit planted 10 days back stays 10 days
+ * back whenever the suite runs. */
+const NOW = Date.parse("2026-08-27T12:00:00Z");
+
+interface Author {
+ name: string;
+ email: string;
+}
+
+const SHRISH: Author = { name: "Shrish Dwivedi", email: "[email protected]" };
+const FRANKIE: Author = { name: "Frankie-Xu", email: "[email protected]" };
+const DRIVE_BY: Author = { name: "Passing Stranger", email: "[email protected]" };
+const BOT: Author = { name: "dependabot[bot]", email: "49699333+dependabot[bot]@users.noreply.github.com" };
+const AUTHOR: Author = { name: "anirudhkumar-nanonets", email: "[email protected]" };
+
+function git(root: string, args: string[], env: Record<string, string> = {}): void {
+ execFileSync("git", args, {
+ cwd: root,
+ stdio: ["ignore", "ignore", "pipe"],
+ env: { ...process.env, ...env },
+ });
+}
+
+/** Commit `file` as `who`, `daysAgo` before {@link NOW}. */
+function commit(root: string, who: Author, file: string, daysAgo: number, body: string): void {
+ const full = join(root, file);
+ mkdirSync(join(full, ".."), { recursive: true });
+ writeFileSync(full, body);
+ const when = new Date(NOW - daysAgo * DAY).toISOString();
+ git(root, ["add", file]);
+ git(root, ["commit", "-m", `touch ${file}`], {
+ GIT_AUTHOR_NAME: who.name,
+ GIT_AUTHOR_EMAIL: who.email,
+ GIT_AUTHOR_DATE: when,
+ GIT_COMMITTER_NAME: who.name,
+ GIT_COMMITTER_EMAIL: who.email,
+ GIT_COMMITTER_DATE: when,
+ });
+}
+
+/**
+ * A repository where ownership of two files is unambiguous and different.
+ *
+ * `src/a.ts` — Shrish recently and often, Frankie once, a stranger once long ago.
+ * `src/b.ts` — Frankie only, plus a bot.
+ */
+function fixture(): string {
+ const root = mkdtempSync(join(tmpdir(), "graft-owners-"));
+ git(root, ["init", "-q", "-b", "main"]);
+ git(root, ["config", "user.name", "t"]);
+ git(root, ["config", "user.email", "[email protected]"]);
+
+ commit(root, DRIVE_BY, "src/a.ts", 700, "// typo fix\n");
+ commit(root, SHRISH, "src/a.ts", 40, "// a1\n");
+ commit(root, SHRISH, "src/a.ts", 20, "// a2\n");
+ commit(root, SHRISH, "src/a.ts", 9, "// a3\n");
+ commit(root, FRANKIE, "src/a.ts", 3, "// a4\n");
+ commit(root, AUTHOR, "src/a.ts", 1, "// a5\n");
+
+ commit(root, FRANKIE, "src/b.ts", 12, "// b1\n");
+ commit(root, BOT, "src/b.ts", 2, "// bumped\n");
+ return root;
+}
+
+test("ranks recent, frequent contributors above old drive-by commits", () => {
+ const owners = ownersFor(fixture(), ["src/a.ts"], { now: NOW });
+ const names = owners.map((o) => o.name);
+
+ assert.equal(names[0], SHRISH.name, "three recent commits should outrank one from three days ago");
+ assert.ok(!names.includes(DRIVE_BY.name), "a single commit from two years back is below the share floor");
+ const shrish = owners[0];
+ assert.equal(shrish.commits, 3);
+ assert.equal(shrish.last, NOW - 9 * DAY);
+});
+
+test("never invents a handle, and always finds a real one", () => {
+ // The author is excluded, as every real call does: with them in, they take the
+ // second of the two per-area slots and Frankie never reaches the assertion.
+ const owners = ownersFor(fixture(), ["src/a.ts"], { now: NOW, exclude: [AUTHOR.name] });
+ const shrish = owners.find((o) => o.name === SHRISH.name);
+ const frankie = owners.find((o) => o.name === FRANKIE.name);
+
+ // The whole safety property of this feature: a work address yields NO handle,
+ // so the comment prints a bare name that the author has to tag by hand.
+ assert.equal(shrish?.handle, undefined);
+ assert.equal(frankie?.handle, "Frankie-Xu");
+});
+
+test("drops bots and the PR author", () => {
+ const root = fixture();
+
+ const b = ownersFor(root, ["src/b.ts"], { now: NOW });
+ assert.deepEqual(b.map((o) => o.name), [FRANKIE.name], "dependabot is not a reviewer");
+
+ // Excluded by GitHub login, by git name and by commit email in turn — CI knows
+ // the login, a local run knows the email, and a squash-merge alias may differ
+ // from both.
+ for (const who of ["anirudhkumar-nanonets", "[email protected]", AUTHOR.name]) {
+ const a = ownersFor(root, ["src/a.ts"], { now: NOW, exclude: [who] });
+ assert.ok(!a.some((o) => o.name === AUTHOR.name), `"${who}" should exclude the author`);
+ }
+});
+
+test("the share floor yields when there is nobody else", () => {
+ const root = mkdtempSync(join(tmpdir(), "graft-owners-solo-"));
+ git(root, ["init", "-q", "-b", "main"]);
+ git(root, ["config", "user.name", "t"]);
+ git(root, ["config", "user.email", "[email protected]"]);
+ commit(root, DRIVE_BY, "src/only.ts", 600, "// one commit, long ago\n");
+
+ // The same commit that loses to a real owner in the first test wins here: the
+ // floor is a share of what remains, so "the only person who ever touched this"
+ // is never filtered down to nobody.
+ const owners = ownersFor(root, ["src/only.ts"], { now: NOW });
+ assert.deepEqual(owners.map((o) => o.name), [DRIVE_BY.name]);
+});
+
+test("outside a git repository the whole layer stays silent", () => {
+ const notARepo = mkdtempSync(join(tmpdir(), "graft-owners-nogit-"));
+ writeFileSync(join(notARepo, "a.ts"), "// x\n");
+ assert.deepEqual(ownersFor(notARepo, ["a.ts"], { now: NOW }), []);
+});
+
+test("attachOwners fills both sides and ranks changed areas above affected ones", () => {
+ const root = fixture();
+ const area: ChangedArea = {
+ label: "A", labelSource: "symbol", key: "src/", files: ["src/a.ts"], seeds: 1,
+ tests: "none", testFiles: [], changedTestFiles: [], reached: 0, behavioural: 1,
+ unreached: [], seedNames: ["doThing"],
+ };
+ const mod: ImpactedModule = {
+ label: "B", labelSource: "symbol", key: "src/b", files: ["src/b.ts"], symbols: [], from: ["src/a.ts"],
+ };
+ const report = {
+ basis: "t", depth: 2, changed: [], unindexed: [], deleted: [], seeds: [], impacted: [],
+ modules: [mod], areas: [area], testModules: [],
+ } as unknown as BlastReport;
+
+ attachOwners(root, report, { now: NOW, exclude: [AUTHOR.name] });
+
+ assert.ok((area.owners?.length ?? 0) > 0, "the changed area gets owners");
+ assert.deepEqual(mod.owners?.map((o) => o.name), [FRANKIE.name], "so does the affected module");
+ assert.equal(report.reviewers?.[0].name, SHRISH.name, "the changed area outweighs the affected one");
+ // Frankie owns one of each, so their reason cites both labels.
+ const frankie = report.reviewers?.find((r) => r.name === FRANKIE.name);
+ assert.deepEqual(frankie?.areas.sort(), ["A", "B"]);
+});
+
+test("the two ways an author is kept out of their own suggestions", () => {
+ const root = fixture();
+
+ // CI: every author in the range. `HEAD~2...HEAD` is Frankie's b1 and the bot's
+ // bump, so Frankie is the author of this "PR" and not a reviewer of it.
+ const authors = diffAuthors(root, "HEAD~2");
+ assert.ok(authors.includes(FRANKIE.email), `expected Frankie's email in ${JSON.stringify(authors)}`);
+ const a = ownersFor(root, ["src/a.ts"], { now: NOW, exclude: authors });
+ assert.ok(!a.some((o) => o.name === FRANKIE.name), "an author of the range is not a reviewer of it");
+
+ // Local: no range exists, so the git identity stands in. Without this, `graft
+ // blast` on a dirty tree tells you to tag yourself.
+ git(root, ["config", "user.name", SHRISH.name]);
+ git(root, ["config", "user.email", SHRISH.email]);
+ const me = localIdentity(root);
+ assert.deepEqual(me, [SHRISH.name, SHRISH.email]);
+ const local = ownersFor(root, ["src/a.ts"], { now: NOW, exclude: me });
+ assert.ok(!local.some((o) => o.name === SHRISH.name), "the local identity is not their own reviewer");
+});
+
+test("handle parsing accepts both noreply forms and nothing else", () => {
+ assert.equal(githubHandle("[email protected]"), "Frankie-Xu");
+ assert.equal(githubHandle("[email protected]"), "qoole");
+ assert.equal(githubHandle("[email protected]"), null);
+ // A lookalike domain must not become a mention.
+ assert.equal(githubHandle("[email protected]"), null);
+});
+
+test("sinceLabel reads as a person would say it", () => {
+ assert.equal(sinceLabel(NOW, NOW), "today");
+ assert.equal(sinceLabel(NOW - DAY, NOW), "yesterday");
+ assert.equal(sinceLabel(NOW - 9 * DAY, NOW), "9d ago");
+ assert.equal(sinceLabel(NOW - 90 * DAY, NOW), "3mo ago");
+ assert.equal(sinceLabel(NOW - 800 * DAY, NOW), "2y ago");
+});
diff --git a/viewer/data.ts b/viewer/data.ts
index 96db8b14..263a241c 100644
--- a/viewer/data.ts
+++ b/viewer/data.ts
@@ -10,6 +10,16 @@ export interface VizNode {
summary: string;
sources: string[];
evidence?: Evidence[];
+ owners?: NodeOwner[];
+}
+
+/** A contributor on a node — see `NodeOwner` in src/viz/assemble.ts. */
+export interface NodeOwner {
+ name: string;
+ handle?: string;
+ commits: number;
+ /** `YYYY-MM-DD`; the viewer turns it into "9d ago" when it renders. */
+ last: string;
}
export interface VizEdge {
diff --git a/viewer/detail.ts b/viewer/detail.ts
index 0ba3907c..03d416cc 100644
--- a/viewer/detail.ts
+++ b/viewer/detail.ts
@@ -3,7 +3,7 @@
* both directions — amber "Depends on" (outgoing) and teal "Depended on by"
* (incoming), mirroring the focus-mode edge colors.
*/
-import { type Evidence, type VizGraph, colorToken, cvar } from "./data.js";
+import { type Evidence, type NodeOwner, type VizGraph, colorToken, cvar } from "./data.js";
function esc(s: string): string {
return s.replace(/&/g, "&amp;").replace(/</g, "&lt;");
@@ -31,6 +31,59 @@ function evidenceBlock(e: Evidence): string {
`</div>`;
}
+/**
+ * Initials for an avatar: `Frankie-Xu` → FX, `Shrish Dwivedi` → SD, `qoole` → QO.
+ *
+ * Two glyphs, always, so a column of them lines up. A single-word name falls back
+ * to its first two letters rather than one, which reads as a bullet.
+ */
+export function initials(name: string): string {
+ const parts = name.split(/[\s._-]+/).filter(Boolean);
+ const joined = parts.length >= 2 ? parts[0][0] + parts[1][0] : (parts[0] ?? "?").slice(0, 2);
+ return joined.toUpperCase();
+}
+
+/** `9d ago` from the ISO day the export carried, computed when the page is read
+ * rather than when it was written — a PR page outlives its build. */
+export function sinceDay(iso: string, now: number = Date.now()): string {
+ const at = Date.parse(`${iso}T00:00:00Z`);
+ if (!Number.isFinite(at)) return iso;
+ const days = Math.max(0, Math.round((now - at) / 86400000));
+ if (days < 1) return "today";
+ if (days === 1) return "yesterday";
+ if (days < 31) return `${days}d ago`;
+ const months = Math.round(days / 30);
+ return months < 24 ? `${months}mo ago` : `${Math.round(days / 365)}y ago`;
+}
+
+/**
+ * Who has worked on this area.
+ *
+ * A handle renders as `@handle`; a contributor git carried no GitHub address for
+ * renders as a plain name, and the block says once why they are not clickable —
+ * the alternative is guessing a mention, which pings a stranger.
+ */
+function ownerBlock(owners: NodeOwner[]): string {
+ const rows = owners
+ .map((o) => {
+ const who = o.handle ? `@${esc(o.handle)}` : esc(o.name);
+ const cls = o.handle ? "own-name mono" : "own-name";
+ return `<div class="own">` +
+ `<span class="av">${esc(initials(o.handle ?? o.name))}</span>` +
+ `<span class="own-txt">` +
+ `<span class="${cls}">${who}</span>` +
+ `<span class="own-why">${o.commits} commit${o.commits === 1 ? "" : "s"} here · last ${esc(sinceDay(o.last))}</span>` +
+ `</span></div>`;
+ })
+ .join("");
+ const unlinked = owners.filter((o) => !o.handle);
+ const note = unlinked.length
+ ? `<div class="own-note">⚠ ${esc(unlinked.map((o) => o.name).join(", "))} ` +
+ `${unlinked.length === 1 ? "has" : "have"} no GitHub handle in their commit email.</div>`
+ : "";
+ return `<div class="owners">${rows}${note}</div>`;
+}
+
export function renderDetail(
host: HTMLElement,
graph: VizGraph | null,
@@ -55,6 +108,13 @@ export function renderDetail(
let html = `<span class="d-type"><span class="sw" style="background:${color}"></span>${esc(node.type)}</span>`;
html += `<h3>${esc(node.name)}</h3>`;
if (node.summary) html += `<p class="summary">${esc(node.summary)}</p>`;
+ // Above the code, below the summary: a reader decides who to ask before they
+ // decide which line to read.
+ if (node.owners?.length) {
+ html += `<div class="d-label"><span class="dot" style="background:var(--con)"></span>` +
+ `Who knows this · ${node.owners.length}</div>`;
+ html += ownerBlock(node.owners);
+ }
// Evidence replaces the plain path list wherever it exists: a reader wants the
// lines, and showing both would say the same thing twice.
if (node.evidence?.length) {
diff --git a/viewer/graph.ts b/viewer/graph.ts
index eb701c11..922439e8 100644
--- a/viewer/graph.ts
+++ b/viewer/graph.ts
@@ -17,7 +17,8 @@ import {
forceSimulation, forceManyBody, forceLink, forceCenter, forceCollide,
type Simulation, type SimulationNodeDatum,
} from "d3-force";
-import { type VizGraph, type VizEdge, famOf, REST, chipKey, colorToken, cvar } from "./data.js";
+import { type VizGraph, type VizEdge, type NodeOwner, famOf, REST, chipKey, colorToken, cvar } from "./data.js";
+import { initials } from "./detail.js";
interface SimNode extends SimulationNodeDatum {
id: string;
@@ -25,6 +26,7 @@ interface SimNode extends SimulationNodeDatum {
type: string;
deg: number;
r: number;
+ owners?: NodeOwner[];
fx?: number | null;
fy?: number | null;
}
@@ -39,12 +41,49 @@ interface SimEdge {
const NS = "http://www.w3.org/2000/svg";
+/** Initials shown on a bubble before the rest become a count. Two faces read as
+ * "someone else owns this"; five read as a pie chart nobody asked for. */
+const MAX_BADGES = 2;
+
function el<K extends keyof SVGElementTagNameMap>(tag: K, attrs: Record<string, string | number>): SVGElementTagNameMap[K] {
const node = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, String(v));
return node;
}
+/**
+ * The contributor stack on a bubble: up to {@link MAX_BADGES} sets of initials,
+ * then a `+N`, fanned out from the node's upper right.
+ *
+ * Drawn once at build time and only shown or hidden afterwards, because the
+ * simulation moves the parent group rather than these — a per-tick redraw of two
+ * circles per node is the one thing that would make a large graph stutter.
+ */
+function ownerBadges(node: SimNode): SVGGElement | null {
+ const owners = node.owners ?? [];
+ if (owners.length === 0) return null;
+ const shown = owners.slice(0, MAX_BADGES);
+ const rest = owners.length - shown.length;
+ const chips = [...shown.map((o) => initials(o.handle ?? o.name)), ...(rest > 0 ? [`+${rest}`] : [])];
+
+ const g = el("g", { "pointer-events": "none" });
+ chips.forEach((text, i) => {
+ // A 45° fan off the top-right, one radius out, so the stack never covers the
+ // node's own colour and never collides with the name under it.
+ const cx = node.r * 0.72 + i * 13;
+ const cy = -node.r * 0.72 + i * 8;
+ g.appendChild(el("circle", { cx, cy, r: 8, fill: cvar("--panel"), stroke: cvar("--con"), "stroke-width": 1.2 }));
+ const t = el("text", {
+ x: cx, y: cy + 3, "text-anchor": "middle", "font-size": 7.5, "font-weight": 700, fill: cvar("--con"),
+ });
+ t.textContent = text;
+ const title = el("title", {});
+ title.textContent = owners.map((o) => `${o.handle ? `@${o.handle}` : o.name} — ${o.commits} commits`).join("\n");
+ g.append(t, title);
+ });
+ return g;
+}
+
export class GraphView {
private svg: SVGSVGElement;
private defs!: SVGDefsElement;
@@ -53,13 +92,16 @@ export class GraphView {
private nodes: SimNode[] = [];
private edges: SimEdge[] = [];
private edgeEls: { path: SVGPathElement; label: SVGTextElement; edge: SimEdge }[] = [];
- private nodeEls: { group: SVGGElement; circle: SVGCircleElement; ring: SVGCircleElement; label: SVGTextElement; node: SimNode }[] = [];
+ private nodeEls: { group: SVGGElement; circle: SVGCircleElement; ring: SVGCircleElement; label: SVGTextElement; badges: SVGGElement | null; node: SimNode }[] = [];
private view = { x: 0, y: 0, k: 1 };
private tab: "context" | "code" = "context";
selected: string | null = null;
query = "";
hiddenRels: Record<string, boolean> = {};
hiddenTypes: Record<string, boolean> = {};
+ /** The contributor badges on each bubble. A decoration, not a filter — toggling
+ * it never changes which nodes are on the canvas. */
+ showOwners = true;
onSelect: (id: string | null) => void = () => {};
constructor(svg: SVGSVGElement) {
@@ -106,7 +148,7 @@ export class GraphView {
const angle = (i / Math.max(1, graph.nodes.length)) * Math.PI * 2;
const d = deg[n.id] ?? 0;
return {
- id: n.id, name: n.name, type: n.type,
+ id: n.id, name: n.name, type: n.type, owners: n.owners,
deg: d, r: 11 + Math.min(13, d * 2.6),
x: p?.x ?? W / 2 + Math.cos(angle) * Math.min(W, H) / 4,
y: p?.y ?? H / 2 + Math.sin(angle) * Math.min(W, H) / 4,
@@ -155,11 +197,13 @@ export class GraphView {
const circle = el("circle", { r: node.r, opacity: 0.92 });
const label = el("text", { y: node.r + 15, "text-anchor": "middle", "font-size": 11.5, "font-weight": 600 });
label.textContent = node.name;
+ const badges = ownerBadges(node);
group.append(ring, circle, label);
+ if (badges) group.appendChild(badges);
group.addEventListener("click", (ev) => { ev.stopPropagation(); this.select(node.id); });
this.bindDrag(group, node);
this.viewport.appendChild(group);
- return { group, circle, ring, label, node };
+ return { group, circle, ring, label, badges, node };
});
}
@@ -226,7 +270,7 @@ export class GraphView {
}
}
- for (const { group, circle, ring, label, node } of this.nodeEls) {
+ for (const { group, circle, ring, label, badges, node } of this.nodeEls) {
const shown = nodeShown(node);
group.style.display = shown ? "" : "none";
if (!shown) continue;
@@ -239,6 +283,7 @@ export class GraphView {
ring.setAttribute("stroke", color);
ring.setAttribute("opacity", node.id === this.selected ? "0.55" : "0");
label.setAttribute("fill", cvar("--ink"));
+ if (badges) badges.style.display = this.showOwners ? "" : "none";
}
}
diff --git a/viewer/main.ts b/viewer/main.ts
index 289b0c0c..12aa7ce2 100644
--- a/viewer/main.ts
+++ b/viewer/main.ts
@@ -91,6 +91,24 @@ function renderLegend(): void {
});
host.appendChild(chip);
}
+
+ // A decoration toggle, not a type filter: it sits after the type chips, carries
+ // its own class, and deliberately does NOT feed `updateShownCount` — hiding a
+ // face hides no node.
+ const graphHasOwners = graph.nodes.some((n) => n.owners?.length);
+ if (graphHasOwners) {
+ const chip = document.createElement("button");
+ chip.type = "button";
+ chip.className = "lchip lchip-people" + (view.showOwners ? "" : " off");
+ chip.innerHTML = `<span class="sw" style="background:${cvar("--con")}"></span>people`;
+ chip.title = "Show who has worked on each area";
+ chip.addEventListener("click", () => {
+ view.showOwners = !view.showOwners;
+ renderLegend();
+ view.restyle();
+ });
+ host.appendChild(chip);
+ }
}
function updateShownCount(): void {
diff --git a/viewer/style.css b/viewer/style.css
index 416b777f..7c9e9647 100644
--- a/viewer/style.css
+++ b/viewer/style.css
@@ -138,3 +138,17 @@ svg.graph:active{cursor:grabbing}
.ev-l.add .ev-s{color:var(--ok,#2E9E6B)}
.ev-l.del .ev-s{color:var(--warn,#D9534F)}
.ev-more{font-size:11px;color:var(--muted);padding:3px 9px 5px}
+
+/* ---- contributors: who has worked on an area (blast --export-viz) ---- */
+.lchip.lchip-people{border-color:var(--con);color:var(--con)}
+.owners{display:flex;flex-direction:column;gap:2px;margin:6px 0 2px}
+.own{display:flex;align-items:center;gap:9px;padding:6px 8px;border-radius:7px;background:var(--panel2);border:1px solid var(--border2)}
+.av{
+ width:25px;height:25px;border-radius:50%;flex:none;display:grid;place-items:center;
+ font-family:ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
+ font-size:10px;font-weight:700;color:var(--con);background:var(--chip);border:1px solid var(--con);
+}
+.own-txt{display:flex;flex-direction:column;min-width:0;gap:1px}
+.own-name{font-size:12.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.own-why{font-size:11px;color:var(--muted);font-variant-numeric:tabular-nums}
+.own-note{font-size:11px;color:var(--muted);padding:3px 8px 0;line-height:1.45}