Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(ui): why is this here — per-symbol git history with linked evidence
Martin Vogel11bdc081477a
diff --git a/graph-ui/src/components/SymbolTab.tsx b/graph-ui/src/components/SymbolTab.tsxindex a66187d1d..2feea8fac 100644--- a/graph-ui/src/components/SymbolTab.tsx+++ b/graph-ui/src/components/SymbolTab.tsx@@ -13,6 +13,14 @@ import {type SymbolRef,} from "../lib/atlas";import { fetchImpact, impactSentence, type ImpactPayload } from "../lib/impact";+import {+ commitUrl,+ fetchSymbolHistory,+ linkifyRefs,+ refUrl,+ type SymbolCommit,+ type SymbolHistoryPayload,+} from "../lib/rationale";import { AddToPromptButton } from "./PromptBasket";import { MetricChip } from "./MetricChip";import { TriggerTree } from "./TriggerTree";@@ -140,6 +148,53 @@ function ConnectionList({);}+/* One commit line: hash · subject · author · date. With a forge base the+ * hash links to the commit and "#123" subject refs link to /issues/123+ * (forges route that to PRs too); without one everything stays plain. */+function CommitRow({ commit, remote }: { commit: SymbolCommit; remote?: string }) {+ return (+ <div className="flex items-baseline gap-2 py-[3px]">+ {remote ? (+ <a+ href={commitUrl(remote, commit.hash)}+ target="_blank"+ rel="noopener noreferrer"+ className="text-[12px] font-mono text-foreground/35 hover:text-foreground/70 shrink-0 transition-colors"+ >+ {commit.hash}+ </a>+ ) : (+ <span className="text-[12px] font-mono text-foreground/35 shrink-0">+ {commit.hash}+ </span>+ )}+ <span className="text-[13px] text-foreground/70 truncate flex-1">+ {remote+ ? linkifyRefs(commit.subject).map((segment, index) =>+ segment.ref !== undefined ? (+ <a+ key={index}+ href={refUrl(remote, segment.ref)}+ target="_blank"+ rel="noopener noreferrer"+ className="text-primary/70 hover:text-primary transition-colors"+ >+ {segment.text}+ </a>+ ) : (+ <span key={index}>{segment.text}</span>+ ),+ )+ : commit.subject}+ </span>+ <span className="text-[12px] text-foreground/35 shrink-0">+ {commit.author} ·{" "}+ {new Date(commit.time * 1000).toISOString().slice(0, 10)}+ </span>+ </div>+ );+}+export function SymbolTab({project,symbolRef,@@ -155,12 +210,17 @@ export function SymbolTab({const [repoInfo, setRepoInfo] = useState<RepoInfo | null>(null);const [impact, setImpact] = useState<ImpactPayload | null>(null);const [impactError, setImpactError] = useState<string | null>(null);+ const [history, setHistory] = useState<SymbolHistoryPayload | null>(null);+ const [historyLoading, setHistoryLoading] = useState(false);+ const [historyError, setHistoryError] = useState<string | null>(null);useEffect(() => {let cancelled = false;setBundle(null);setError(null);setCode(null);+ setHistory(null);+ setHistoryError(null);fetchSymbol(project, symbolRef, limit, 0).then((payload) => {if (!cancelled) setBundle(payload);@@ -250,6 +310,24 @@ export function SymbolTab({].join(" · "): null;+ /* The trace is a deliberate click: each call runs one git subprocess+ * (git log -L) on the server, so it is never fetched automatically. */+ const canTrace = Boolean(node.file_path && node.start_line && node.end_line);+ const loadHistory = async () => {+ if (!node.file_path || !node.start_line || !node.end_line) return;+ setHistoryLoading(true);+ setHistoryError(null);+ try {+ setHistory(+ await fetchSymbolHistory(project, node.file_path, node.start_line, node.end_line),+ );+ } catch (err) {+ setHistoryError(err instanceof Error ? err.message : "failed");+ } finally {+ setHistoryLoading(false);+ }+ };+const loadCode = async () => {if (!node.qualified_name) return;setCodeLoading(true);@@ -500,18 +578,11 @@ export function SymbolTab({</p>)}{(bundle.file_history?.recent ?? []).map((commit) => (- <div key={commit.hash} className="flex items-baseline gap-2 py-[3px]">- <span className="text-[12px] font-mono text-foreground/35 shrink-0">- {commit.hash}- </span>- <span className="text-[13px] text-foreground/70 truncate flex-1">- {commit.subject}- </span>- <span className="text-[12px] text-foreground/35 shrink-0">- {commit.author} ·{" "}- {new Date(commit.time * 1000).toISOString().slice(0, 10)}- </span>- </div>+ <CommitRow+ key={commit.hash}+ commit={commit}+ remote={bundle.file_history?.remote_url}+ />))}{bundle.file_history?.available &&(bundle.file_history.commits_1y ?? 0) > 0 && (@@ -568,6 +639,73 @@ export function SymbolTab({)}</div>+ {/* Why is this here? — the recorded rationale: on-demand git log -L+ * over this symbol's own line range, not the whole file's. */}+ {canTrace && (+ <div className="bg-card border border-border/50 rounded-md p-4 mb-4">+ <p className="text-[12px] uppercase tracking-widest text-foreground/40 mb-2">+ Why is this here?+ </p>+ {node.docstring && (+ <p className="text-[12px] text-foreground/40 mb-2">+ The docstring above is the stated intent; below is the recorded+ history.+ </p>+ )}+ {!history && (+ <button+ onClick={loadHistory}+ disabled={historyLoading}+ className="px-2.5 py-1 rounded-md bg-primary/15 text-primary text-[13px] font-medium hover:bg-primary/25 transition-colors disabled:opacity-40"+ >+ Trace this symbol's history+ </button>+ )}+ {historyLoading && (+ <p className="text-[13px] text-foreground/40 mt-2">+ Reading git history…+ </p>+ )}+ {historyError && (+ <p className="text-[13px] text-foreground/40 mt-2">+ History unavailable: {historyError}+ </p>+ )}+ {history && !history.available && (+ <p className="text-[13px] text-foreground/40">+ No git history is readable for this symbol's file.+ </p>+ )}+ {history?.available && (+ <>+ <div className="space-y-px">+ {(history.commits ?? []).map((commit) => (+ <CommitRow+ key={commit.hash}+ commit={commit}+ remote={history.remote_url}+ />+ ))}+ </div>+ {(history.commits ?? []).length === 0 && (+ <p className="text-[13px] text-foreground/40">+ No commits recorded for this line range.+ </p>+ )}+ {history.truncated && (+ <p className="text-[12px] text-foreground/40 mt-1">+ showing {history.max_commits} (capped)+ </p>+ )}+ </>+ )}+ <p className="text-[12px] text-foreground/35 mt-3">+ History follows this symbol's line range through renames (git log+ -L). PR and issue links open the forge — titles are not fetched.+ </p>+ </div>+ )}+<div className="grid grid-cols-1 lg:grid-cols-3 gap-4"><div className="bg-card border border-border/40 rounded-md p-4"><p className="text-[12px] uppercase tracking-widest text-foreground/45 mb-2">diff --git a/graph-ui/src/lib/atlas.ts b/graph-ui/src/lib/atlas.tsindex 38c0102c0..7655846d6 100644--- a/graph-ui/src/lib/atlas.ts+++ b/graph-ui/src/lib/atlas.ts@@ -69,6 +69,9 @@ export interface DataFlowRef {export interface FileHistory {available: boolean;+ /* Normalized https forge base for commit/#ref links; absent when the+ * repo has no usable remote. */+ remote_url?: string;commits_1y?: number;recent?: { hash: string; time: number; author: string; subject: string }[];top_author?: string;diff --git a/graph-ui/src/lib/questions.ts b/graph-ui/src/lib/questions.tsindex 002106e3e..6c8be3c4f 100644--- a/graph-ui/src/lib/questions.ts+++ b/graph-ui/src/lib/questions.ts@@ -71,8 +71,8 @@ export const QUESTION_FAMILIES: QuestionFamily[] = [id: "F7",question: "Why was it built this way?",status: "partial",- hint: "Symbol view: docs, ADR panel, file history",- gap: "Docstrings, ADRs and commit subjects are linked; the symbol→PR/issue→decision chain is not built yet",+ hint: "Symbol view: docs, ADR panel, file history, and 'Why is this here?' traces a symbol's own git history",+ gap: "Symbol-level history with linked commits and PR/issue refs is here; PR/issue titles and ADR-to-symbol links are not fetched or joined yet",},{id: "F8",diff --git a/graph-ui/src/lib/rationale.test.ts b/graph-ui/src/lib/rationale.test.tsnew file mode 100644index 000000000..af0572e4f--- /dev/null+++ b/graph-ui/src/lib/rationale.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { commitUrl, linkifyRefs, refUrl } from "./rationale";++describe("linkifyRefs", () => {+ it("splits a multi-ref subject into plain and ref segments", () => {+ expect(linkifyRefs("fix(ui): honest axes (#123, closes #45)")).toEqual([+ { text: "fix(ui): honest axes (" },+ { text: "#123", ref: 123 },+ { text: ", closes " },+ { text: "#45", ref: 45 },+ { text: ")" },+ ]);+ });++ it("keeps a ref-free subject as one plain segment", () => {+ expect(linkifyRefs("chore: bump version")).toEqual([+ { text: "chore: bump version" },+ ]);+ });++ it("handles refs at the start and the end of the subject", () => {+ expect(linkifyRefs("#7 then #8")).toEqual([+ { text: "#7", ref: 7 },+ { text: " then " },+ { text: "#8", ref: 8 },+ ]);+ });++ it("leaves '#' without digits as plain text", () => {+ expect(linkifyRefs("port to c# — see issue #")).toEqual([+ { text: "port to c# — see issue #" },+ ]);+ });+});++describe("forge URLs", () => {+ it("builds commit and issue/PR URLs from the remote base", () => {+ const remote = "https://github.com/DeusData/codebase-memory-mcp";+ expect(commitUrl(remote, "617a4b14")).toBe(+ "https://github.com/DeusData/codebase-memory-mcp/commit/617a4b14",+ );+ expect(refUrl(remote, 123)).toBe(+ "https://github.com/DeusData/codebase-memory-mcp/issues/123",+ );+ });+});diff --git a/graph-ui/src/lib/rationale.ts b/graph-ui/src/lib/rationale.tsnew file mode 100644index 000000000..5971bba71--- /dev/null+++ b/graph-ui/src/lib/rationale.ts@@ -0,0 +1,75 @@+/* Rationale-evidence data layer: /api/symbol-history — the recorded "why"+ * for one symbol: git log -L over its own line range, followed through+ * renames. Each call costs one git subprocess on the server, so it is+ * fetched on demand (a button), never automatically. */+import { fetchJsonFrom } from "./whyfetch";++export interface SymbolCommit {+ hash: string;+ time: number;+ author: string;+ subject: string;+}++export interface SymbolHistoryPayload {+ max_commits: number;+ /* Normalized https forge base (e.g. "https://github.com/owner/repo");+ * absent when the repo has no usable remote — then hashes render as+ * plain text and #refs stay unlinked. */+ remote_url?: string;+ available: boolean;+ /* Newest first, at most max_commits; absent on the unavailable paths. */+ commits?: SymbolCommit[];+ truncated: boolean;+}++export async function fetchSymbolHistory(+ project: string,+ file: string,+ start: number,+ end: number,+): Promise<SymbolHistoryPayload> {+ const params = new URLSearchParams({+ project,+ file,+ start: String(start),+ end: String(end),+ });+ const payload = await fetchJsonFrom<SymbolHistoryPayload & { error?: string }>(+ `/api/symbol-history?${params}`,+ );+ if (payload.error) throw new Error(payload.error);+ return payload;+}++/* One piece of a commit subject: plain text, or a "#123" issue/PR ref+ * (then ref carries the number). */+export interface SubjectSegment {+ text: string;+ ref?: number;+}++/* Split a commit subject into plain segments and linkable "#123" refs.+ * A bare "#" without digits stays plain text. */+export function linkifyRefs(subject: string): SubjectSegment[] {+ const segments: SubjectSegment[] = [];+ const pattern = /#(\d+)/g;+ let cursor = 0;+ for (let match = pattern.exec(subject); match; match = pattern.exec(subject)) {+ if (match.index > cursor) segments.push({ text: subject.slice(cursor, match.index) });+ segments.push({ text: match[0], ref: Number(match[1]) });+ cursor = match.index + match[0].length;+ }+ if (cursor < subject.length) segments.push({ text: subject.slice(cursor) });+ return segments;+}++export function commitUrl(remote: string, hash: string): string {+ return `${remote}/commit/${hash}`;+}++/* Forges route /issues/N to the pull request when N is a PR, so one link+ * shape covers both kinds of ref. */+export function refUrl(remote: string, ref: number): string {+ return `${remote}/issues/${ref}`;+}diff --git a/graph-ui/tsconfig.tsbuildinfo b/graph-ui/tsconfig.tsbuildinfoindex ddc6aeb64..03dbfbc07 100644--- a/graph-ui/tsconfig.tsbuildinfo+++ b/graph-ui/tsconfig.tsbuildinfo@@ -1 +1 @@-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/changestab.tsx","./src/components/commandk.tsx","./src/components/controltab.tsx","./src/components/dashboardtab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/flowstab.tsx","./src/components/graphloader.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.deadcode.test.tsx","./src/components/graphtab.filters.test.tsx","./src/components/graphtab.regions.test.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/halolayer.tsx","./src/components/metricchip.tsx","./src/components/minimap.tsx","./src/components/missedcallout.tsx","./src/components/modulestab.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.showmore.test.tsx","./src/components/nodedetailpanel.test.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/overviewtab.tsx","./src/components/projectcard.tsx","./src/components/projectswitcher.tsx","./src/components/promptbasket.tsx","./src/components/regionpanel.tsx","./src/components/regiontooltip.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/symboltab.tsx","./src/components/tabbar.tsx","./src/components/triggertree.tsx","./src/components/wikihovercard.test.tsx","./src/components/wikihovercard.tsx","./src/components/wikipanel.test.tsx","./src/components/wikipanel.tsx","./src/components/wikitier.ts","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.ts","./src/lib/atlas.test.ts","./src/lib/atlas.ts","./src/lib/colors.ts","./src/lib/complexity.test.ts","./src/lib/complexity.ts","./src/lib/composer.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/findings.test.ts","./src/lib/findings.ts","./src/lib/firstread.ts","./src/lib/flowgroup.test.ts","./src/lib/flowgroup.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/impact.test.ts","./src/lib/impact.ts","./src/lib/questions.test.ts","./src/lib/questions.ts","./src/lib/regions.test.ts","./src/lib/regions.ts","./src/lib/treemap.ts","./src/lib/types.ts","./src/lib/utils.ts","./src/lib/why.test.ts","./src/lib/why.ts","./src/lib/whyfetch.ts","./src/test/setup.ts","./src/wiki/entries.test.ts","./src/wiki/entries.ts"],"version":"5.9.3"}\ No newline at end of file+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/rpc.ts","./src/components/changestab.tsx","./src/components/commandk.tsx","./src/components/controltab.tsx","./src/components/dashboardtab.tsx","./src/components/displaysettingsmenu.tsx","./src/components/edgelines.tsx","./src/components/errorboundary.tsx","./src/components/filterpanel.tsx","./src/components/flowstab.tsx","./src/components/graphloader.tsx","./src/components/graphscene.test.ts","./src/components/graphscene.tsx","./src/components/graphtab.deadcode.test.tsx","./src/components/graphtab.filters.test.tsx","./src/components/graphtab.regions.test.tsx","./src/components/graphtab.test.ts","./src/components/graphtab.tsx","./src/components/halolayer.tsx","./src/components/metricchip.tsx","./src/components/minimap.tsx","./src/components/missedcallout.tsx","./src/components/modulestab.tsx","./src/components/nodecloud.tsx","./src/components/nodedetailpanel.showmore.test.tsx","./src/components/nodedetailpanel.test.tsx","./src/components/nodedetailpanel.tsx","./src/components/nodelabels.tsx","./src/components/nodetooltip.tsx","./src/components/overviewtab.tsx","./src/components/projectcard.tsx","./src/components/projectswitcher.tsx","./src/components/promptbasket.tsx","./src/components/regionpanel.tsx","./src/components/regiontooltip.tsx","./src/components/resizehandle.tsx","./src/components/sidebar.tsx","./src/components/statstab.test.tsx","./src/components/statstab.tsx","./src/components/symboltab.tsx","./src/components/tabbar.tsx","./src/components/triggertree.tsx","./src/components/wikihovercard.test.tsx","./src/components/wikihovercard.tsx","./src/components/wikipanel.test.tsx","./src/components/wikipanel.tsx","./src/components/wikitier.ts","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/card.tsx","./src/components/ui/checkbox.tsx","./src/components/ui/input.tsx","./src/components/ui/scroll-area.tsx","./src/components/ui/separator.tsx","./src/hooks/usegraphdata.test.ts","./src/hooks/usegraphdata.ts","./src/hooks/useprojects.ts","./src/lib/atlas.test.ts","./src/lib/atlas.ts","./src/lib/colors.ts","./src/lib/complexity.test.ts","./src/lib/complexity.ts","./src/lib/composer.ts","./src/lib/density.test.ts","./src/lib/density.ts","./src/lib/findings.test.ts","./src/lib/findings.ts","./src/lib/firstread.ts","./src/lib/flowgroup.test.ts","./src/lib/flowgroup.ts","./src/lib/i18n.test.ts","./src/lib/i18n.ts","./src/lib/impact.test.ts","./src/lib/impact.ts","./src/lib/questions.test.ts","./src/lib/questions.ts","./src/lib/rationale.test.ts","./src/lib/rationale.ts","./src/lib/regions.test.ts","./src/lib/regions.ts","./src/lib/treemap.ts","./src/lib/types.ts","./src/lib/utils.ts","./src/lib/why.test.ts","./src/lib/why.ts","./src/lib/whyfetch.ts","./src/test/setup.ts","./src/wiki/entries.test.ts","./src/wiki/entries.ts"],"version":"5.9.3"}\ No newline at end of filediff --git a/src/ui/atlas.h b/src/ui/atlas.hindex 8cde1b450..8a7e0d373 100644--- a/src/ui/atlas.h+++ b/src/ui/atlas.h@@ -51,6 +51,12 @@ void cbm_atlas_metrics_cache_clear(void);* Returns {"available":false} JSON when the project has no git history. */char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, const char *file_path);+/* Per-symbol rationale evidence: `git log -L start,end:file` (bounded,+ * on-demand) with the forge base URL for commit/#ref links. */+char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project,+ const char *file_path, long long start_line,+ long long end_line);+/* ── A→B trace (atlas_flows.c) ────────────────────────────────────* Reachability between two callables over CALLS ("calls") or DATA_FLOWS* ("data"): shortest path within a bounded depth, honest about the bound.diff --git a/src/ui/atlas_metrics.c b/src/ui/atlas_metrics.cindex e98790619..a9db96b32 100644--- a/src/ui/atlas_metrics.c+++ b/src/ui/atlas_metrics.c@@ -181,6 +181,7 @@ typedef struct {} mx_churn_t;static void mx_history_cache_store(const char *project, const char *stamp, mx_churn_t *churn);+static void mx_remote_url(const char *root_path, char *out, size_t cap);static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {if (!root_path || !root_path[0] || !cbm_validate_shell_path_arg(root_path))@@ -684,6 +685,12 @@ char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, constyyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);+ /* Forge base for the UI's commit/#ref links (absent when no remote). */+ char remote[CBM_SZ_1K];+ mx_remote_url(root_path, remote, sizeof(remote));+ if (remote[0])+ yyjson_mut_obj_add_strcpy(doc, root, "remote_url", remote);+pthread_mutex_lock(&g_hist_mu);fresh = g_hist_cache.valid && strcmp(g_hist_cache.key, key) == 0;const mx_file_stat_t *stat = fresh && g_hist_cache.churn.counts@@ -753,3 +760,157 @@ char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project) {pthread_mutex_unlock(&g_mx_mu);return json;}++/* ── Rationale evidence: forge base URL + per-symbol history ────── */++/* Normalize the origin remote to a browsable https base ("" if none):+ * git@host:owner/repo(.git) and ssh://git@host/owner/repo(.git) become+ * https://host/owner/repo; https URLs just lose the .git suffix. The+ * UI turns commit hashes and #123 refs in subjects into links with it. */+static void mx_remote_url(const char *root_path, char *out, size_t cap) {+ out[0] = '\0';+ if (!root_path || !root_path[0] || !cbm_validate_shell_path_arg(root_path))+ return;+#ifdef _WIN32+ const char *null_dev = "NUL";+#else+ const char *null_dev = "/dev/null";+#endif+ char cmd[CBM_SZ_2K];+ snprintf(cmd, sizeof(cmd), "git -C \"%s\" config --get remote.origin.url 2>%s", root_path,+ null_dev);+ FILE *fp = cbm_popen(cmd, "r");+ if (!fp)+ return;+ char line[CBM_SZ_1K] = {0};+ if (!fgets(line, sizeof(line), fp)) {+ cbm_pclose(fp);+ return;+ }+ cbm_pclose(fp);+ size_t len = strlen(line);+ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r' || line[len - 1] == ' '))+ line[--len] = '\0';+ if (len == 0)+ return;+ char https[CBM_SZ_1K] = {0};+ if (strncmp(line, "git@", 4) == 0) {+ /* git@host:owner/repo -> https://host/owner/repo */+ char *colon = strchr(line + 4, ':');+ if (!colon)+ return;+ *colon = '\0';+ snprintf(https, sizeof(https), "https://%s/%s", line + 4, colon + 1);+ } else if (strncmp(line, "ssh://", 6) == 0) {+ const char *rest = line + 6;+ const char *at = strchr(rest, '@');+ if (at)+ rest = at + 1;+ snprintf(https, sizeof(https), "https://%s", rest);+ } else if (strncmp(line, "https://", 8) == 0 || strncmp(line, "http://", 7) == 0) {+ snprintf(https, sizeof(https), "%s", line);+ } else {+ return; /* local paths and exotic transports: no link base */+ }+ size_t hlen = strlen(https);+ if (hlen > 4 && strcmp(https + hlen - 4, ".git") == 0)+ https[hlen - 4] = '\0';+ while ((hlen = strlen(https)) > 0 && https[hlen - 1] == '/')+ https[hlen - 1] = '\0';+ snprintf(out, cap, "%s", https);+}++char *cbm_atlas_symbol_history_json(cbm_store_t *store, const char *project,+ const char *file_path, long long start_line,+ long long end_line) {+ if (!store || !project || !file_path || !file_path[0])+ return NULL;+ if (start_line < 1 || end_line < start_line || end_line > 10000000)+ return NULL;+ char stamp[128];+ char root_path[CBM_SZ_1K];+ mx_project_stamp(store, project, stamp, sizeof(stamp), root_path, sizeof(root_path));++ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);+ yyjson_mut_val *root = yyjson_mut_obj(doc);+ yyjson_mut_doc_set_root(doc, root);+ yyjson_mut_obj_add_int(doc, root, "max_commits", 12);++ /* The file path lands inside a quoted shell argument; the same guard+ * the churn scan applies to the root covers metacharacters here. */+ if (!root_path[0] || !cbm_validate_shell_path_arg(root_path) ||+ !cbm_validate_shell_path_arg(file_path) || strstr(file_path, "..")) {+ yyjson_mut_obj_add_bool(doc, root, "available", false);+ char *json = yyjson_mut_write(doc, 0, NULL);+ yyjson_mut_doc_free(doc);+ return json;+ }+ char remote[CBM_SZ_1K];+ mx_remote_url(root_path, remote, sizeof(remote));+ if (remote[0])+ yyjson_mut_obj_add_strcpy(doc, root, "remote_url", remote);++#ifdef _WIN32+ const char *null_dev = "NUL";+#else+ const char *null_dev = "/dev/null";+#endif+ /* -L follows the symbol's line range through renames and rewrites —+ * per-symbol "why", not per-file. --no-patch keeps output to the+ * COMMIT: lines; anything else is skipped by the parser anyway. */+ char cmd[CBM_SZ_2K];+ snprintf(cmd, sizeof(cmd),+ "git -C \"%s\" log --no-patch --max-count=12 "+ "--pretty=format:COMMIT:%%h:%%ct:%%an:%%s -L %lld,%lld:\"%s\" 2>%s",+ root_path, start_line, end_line, file_path, null_dev);+ FILE *fp = cbm_popen(cmd, "r");+ if (!fp) {+ yyjson_mut_obj_add_bool(doc, root, "available", false);+ char *json = yyjson_mut_write(doc, 0, NULL);+ yyjson_mut_doc_free(doc);+ return json;+ }+ yyjson_mut_val *commits = yyjson_mut_arr(doc);+ int count = 0;+ char line[CBM_SZ_1K];+ while (fgets(line, sizeof(line), fp)) {+ size_t len = strlen(line);+ while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))+ line[--len] = '\0';+ if (strncmp(line, "COMMIT:", 7) != 0)+ continue;+ char *cursor = line + 7;+ char *hash = cursor;+ char *colon = strchr(cursor, ':');+ if (!colon)+ continue;+ *colon = '\0';+ cursor = colon + 1;+ char *epoch = cursor;+ colon = strchr(cursor, ':');+ if (!colon)+ continue;+ *colon = '\0';+ cursor = colon + 1;+ char *author = cursor;+ colon = strchr(cursor, ':');+ if (!colon)+ continue;+ *colon = '\0';+ const char *subject = colon + 1;+ yyjson_mut_val *obj = yyjson_mut_obj(doc);+ yyjson_mut_obj_add_strcpy(doc, obj, "hash", hash);+ yyjson_mut_obj_add_int(doc, obj, "time", strtoll(epoch, NULL, 10));+ yyjson_mut_obj_add_strcpy(doc, obj, "author", author);+ yyjson_mut_obj_add_strcpy(doc, obj, "subject", subject);+ yyjson_mut_arr_append(commits, obj);+ count++;+ }+ int status = cbm_pclose(fp);+ yyjson_mut_obj_add_bool(doc, root, "available", status == 0 || count > 0);+ yyjson_mut_obj_add_val(doc, root, "commits", commits);+ yyjson_mut_obj_add_bool(doc, root, "truncated", count >= 12);+ char *json = yyjson_mut_write(doc, 0, NULL);+ yyjson_mut_doc_free(doc);+ return json;+}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 64d474763..b29c142da 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -1929,6 +1929,31 @@ static void handle_atlas_trace(cbm_http_conn_t *c, const cbm_http_req_t *req) {atlas_reply_json(c, json, 500, "{\"error\":\"trace failed\"}");}+/* GET /api/symbol-history?project=X&file=PATH&start=N&end=N — per-symbol+ * git history (log -L over the symbol's line range), on demand. */+static void handle_atlas_symbol_history(cbm_http_conn_t *c, const cbm_http_req_t *req) {+ char project[256] = {0};+ cbm_store_t *store = atlas_open_project(c, req, project, sizeof(project));+ if (!store)+ return;+ char file[1024] = {0};+ char start_str[32] = {0};+ char end_str[32] = {0};+ cbm_http_query_param(req->query, "file", file, (int)sizeof(file));+ cbm_http_query_param(req->query, "start", start_str, (int)sizeof(start_str));+ cbm_http_query_param(req->query, "end", end_str, (int)sizeof(end_str));+ long long start_line = strtoll(start_str, NULL, 10);+ long long end_line = strtoll(end_str, NULL, 10);+ if (!file[0] || start_line < 1 || end_line < start_line) {+ cbm_store_close(store);+ cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"missing or invalid file/start/end\"}");+ return;+ }+ char *json = cbm_atlas_symbol_history_json(store, project, file, start_line, end_line);+ cbm_store_close(store);+ atlas_reply_json(c, json, 500, "{\"error\":\"symbol history failed\"}");+}+/* GET /api/impact?project=X&node=QN|#id — reverse reachability: who could* notice a change to this symbol, at what distance, in which regions, and* which test functions reach it. */@@ -2479,6 +2504,12 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,return;}+ /* GET /api/symbol-history → per-symbol git log -L evidence */+ if (is_get && cbm_http_path_match(req->path, "/api/symbol-history*")) {+ handle_atlas_symbol_history(c, req);+ return;+ }+/* GET /api/flows → CBM Atlas flow list */if (is_get && cbm_http_path_match(req->path, "/api/flows*")) {handle_atlas_flows(c, req);diff --git a/tests/test_ui.c b/tests/test_ui.cindex 56d6ed952..4de211432 100644--- a/tests/test_ui.c+++ b/tests/test_ui.c@@ -1845,6 +1845,80 @@ static const char *WHY_SAMPLE_C = "void beta(void);\n"" }\n""}\n";+/* Per-symbol history: `git log -L` over the symbol's line range, with the+ * forge base URL normalized for the UI's commit/#ref links. Runs against a+ * real throwaway git repo; environments without git pass through (the+ * feature itself degrades to available:false the same way). */+TEST(atlas_symbol_history_log_l_and_remote) {+ /* Invalid input never spawns a subprocess. */+ cbm_store_t *probe = cbm_store_open_memory();+ ASSERT_NOT_NULL(probe);+ cbm_store_upsert_project(probe, "hist-test", "/tmp/nonexistent-hist");+ ASSERT_NULL(cbm_atlas_symbol_history_json(probe, "hist-test", "src/w1.c", 0, 3));+ ASSERT_NULL(cbm_atlas_symbol_history_json(probe, "hist-test", "src/w1.c", 5, 3));+ /* Traversal in the file path is refused, honestly. */+ char *json = cbm_atlas_symbol_history_json(probe, "hist-test", "../etc/passwd", 1, 3);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "available")));+ yyjson_doc_free(doc);+ free(json);+ cbm_store_close(probe);++#ifdef _WIN32+ if (system("git --version >NUL 2>&1") != 0)+#else+ if (system("git --version >/dev/null 2>&1") != 0)+#endif+ PASS(); /* no git in this environment; the guarded paths above ran */++ char tmpl[] = "/tmp/cbm_hist_XXXXXX";+ char *root = cbm_mkdtemp(tmpl);+ ASSERT_NOT_NULL(root);+ char dir[1024];+ snprintf(dir, sizeof(dir), "%s/src", root);+ cbm_mkdir_p(dir, 0755);+ char file[1024];+ snprintf(file, sizeof(file), "%s/src/w1.c", root);+ FILE *fp = cbm_fopen(file, "wb");+ ASSERT_NOT_NULL(fp);+ fputs("int a(void) {\n return 1;\n}\n\nint b(void) {\n return 2;\n}\n", fp);+ fclose(fp);+ char cmd[2048];+ snprintf(cmd, sizeof(cmd),+ "git -C \"%s\" init -q && git -C \"%s\" add . && "+ "git -C \"%s\" -c user.name=Test -c [email protected] commit -qm \"seed a for #42\" "+ "&& git -C \"%s\" remote add origin [email protected]:foo/bar.git",+ root, root, root, root);+ if (system(cmd) != 0) {+ (void)th_rmtree(root);+ PASS(); /* git present but unusable here (sandboxed config, etc.) */+ }++ cbm_store_t *store = cbm_store_open_memory();+ ASSERT_NOT_NULL(store);+ cbm_store_upsert_project(store, "hist-test", root);+ json = cbm_atlas_symbol_history_json(store, "hist-test", "src/w1.c", 1, 3);+ ASSERT_NOT_NULL(json);+ doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *hroot = yyjson_doc_get_root(doc);+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(hroot, "available")));+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(hroot, "remote_url")),+ "https://github.com/foo/bar");+ yyjson_val *commits = yyjson_obj_get(hroot, "commits");+ ASSERT_EQ((int)yyjson_arr_size(commits), 1);+ yyjson_val *commit = yyjson_arr_get(commits, 0);+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(commit, "subject")), "seed a for #42");+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(commit, "author")), "Test");+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(hroot, "truncated")));+ yyjson_doc_free(doc);+ free(json);+ cbm_store_close(store);+ (void)th_rmtree(root);+ PASS();+}+TEST(atlas_why_extracts_guard_chains) {char tmpl[] = "/tmp/cbm_why_XXXXXX";char *root = cbm_mkdtemp(tmpl);@@ -2004,5 +2078,6 @@ SUITE(ui) {RUN_TEST(atlas_symbol_overflow_tail_and_dataflow_presence);RUN_TEST(atlas_blast_buckets_files_by_region);RUN_TEST(atlas_handout_is_selfcontained_and_escaped);+ RUN_TEST(atlas_symbol_history_log_l_and_remote);RUN_TEST(atlas_why_extracts_guard_chains);}