Skip to content

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.

feat(atlas): answer history, ownership, and A-to-B reachability

Martin Vogelb54eb3d0c1c2
diff --git a/graph-ui/src/components/FlowsTab.tsx b/graph-ui/src/components/FlowsTab.tsx
index 4fa36a59f..3949e29c0 100644
--- a/graph-ui/src/components/FlowsTab.tsx
+++ b/graph-ui/src/components/FlowsTab.tsx
@@ -6,8 +6,11 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import {
fetchFlow,
fetchFlows,
+ fetchTrace,
+ searchGraph,
type FlowDetail,
type FlowsPayload,
+ type TracePayload,
} from "../lib/atlas";
import { AddToPromptButton } from "./PromptBasket";
@@ -30,11 +33,117 @@ function flowToMermaid(detail: FlowDetail): string {
return lines.join("\n");
}
+/* One endpoint picker: type ≥2 chars, pick from symbol matches. */
+function EndpointPicker({
+ project,
+ placeholder,
+ value,
+ onPick,
+}: {
+ project: string;
+ placeholder: string;
+ value: string | null;
+ onPick: (qn: string | null) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [options, setOptions] = useState<{ qn: string; name: string; file?: string }[]>([]);
+ useEffect(() => {
+ if (query.trim().length < 2) {
+ setOptions([]);
+ return;
+ }
+ const timer = setTimeout(async () => {
+ try {
+ const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const { rows } = await searchGraph(project, { name_pattern: escaped, limit: 6 });
+ setOptions(
+ rows.map((row) => ({ qn: row.qualified_name, name: row.name, file: row.file })),
+ );
+ } catch {
+ setOptions([]);
+ }
+ }, 250);
+ return () => clearTimeout(timer);
+ }, [project, query]);
+
+ if (value) {
+ return (
+ <span className="inline-flex items-center gap-1.5 bg-popover border border-border/50 rounded-md px-2 py-1">
+ <span className="text-[13px] font-mono text-foreground/80 truncate max-w-[220px]">
+ {value.split(".").slice(-1)[0]}
+ </span>
+ <button
+ onClick={() => onPick(null)}
+ className="text-foreground/30 hover:text-foreground/60 text-[13px] leading-none"
+ >
+ ×
+ </button>
+ </span>
+ );
+ }
+ return (
+ <span className="relative inline-block">
+ <input
+ type="text"
+ placeholder={placeholder}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ className="bg-popover border border-border/50 rounded-md px-2 py-1 text-[13px] text-foreground placeholder-foreground/30 outline-none focus:border-primary/50 w-[180px] transition-all"
+ />
+ {options.length > 0 && (
+ <div className="absolute top-full left-0 mt-1 w-[320px] bg-popover border border-border/60 rounded-md shadow-xl z-20 py-1">
+ {options.map((option) => (
+ <button
+ key={option.qn}
+ onClick={() => {
+ onPick(option.qn);
+ setQuery("");
+ setOptions([]);
+ }}
+ className="flex items-center gap-2 w-full text-left px-3 py-1.5 hover:bg-surface-3 transition-colors"
+ >
+ <span className="text-[13px] font-mono text-foreground/75 truncate">
+ {option.name}
+ </span>
+ <span className="text-[12px] text-foreground/30 truncate ml-auto max-w-[45%]">
+ {option.file}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </span>
+ );
+}
+
export function FlowsTab({ project, flowId, onOpenFlow, onOpenSymbol }: FlowsTabProps) {
const [payload, setPayload] = useState<FlowsPayload | null>(null);
const [detail, setDetail] = useState<FlowDetail | null>(null);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
+ const [traceFrom, setTraceFrom] = useState<string | null>(null);
+ const [traceTo, setTraceTo] = useState<string | null>(null);
+ const [traceMode, setTraceMode] = useState<"calls" | "data">("calls");
+ const [trace, setTrace] = useState<TracePayload | null>(null);
+ const [tracing, setTracing] = useState(false);
+
+ const runTrace = async () => {
+ if (!traceFrom || !traceTo) return;
+ setTracing(true);
+ setTrace(null);
+ try {
+ setTrace(await fetchTrace(project, traceFrom, traceTo, traceMode));
+ } catch (err) {
+ setTrace({
+ mode: traceMode,
+ max_depth: 0,
+ reachable: false,
+ error: err instanceof Error ? err.message : "trace failed",
+ });
+ } finally {
+ setTracing(false);
+ }
+ };
useEffect(() => {
let cancelled = false;
@@ -99,6 +208,76 @@ export function FlowsTab({ project, flowId, onOpenFlow, onOpenSymbol }: FlowsTab
<div className="h-full flex">
{/* Flow list */}
<div className="w-[380px] shrink-0 border-r border-border/40 flex flex-col bg-card/60">
+ <div className="px-4 py-3 border-b border-border/30 shrink-0">
+ <p className="text-[12px] uppercase tracking-widest text-foreground/45 mb-2">
+ Trace A → B
+ </p>
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <EndpointPicker
+ project={project}
+ placeholder="from symbol…"
+ value={traceFrom}
+ onPick={setTraceFrom}
+ />
+ <span className="text-foreground/30 text-[13px]">→</span>
+ <EndpointPicker
+ project={project}
+ placeholder="to symbol…"
+ value={traceTo}
+ onPick={setTraceTo}
+ />
+ <button
+ onClick={() => setTraceMode((mode) => (mode === "calls" ? "data" : "calls"))}
+ className="px-2 py-1 rounded-md bg-popover border border-border/50 text-[12px] text-foreground/60 hover:text-foreground/85 transition-colors"
+ title="Follow control flow (CALLS) or data flow (DATA_FLOWS)"
+ >
+ {traceMode === "calls" ? "control" : "data"}
+ </button>
+ <button
+ onClick={runTrace}
+ disabled={!traceFrom || !traceTo || tracing}
+ className="px-2.5 py-1 rounded-md bg-primary/15 text-primary text-[12px] font-medium hover:bg-primary/25 transition-colors disabled:opacity-40"
+ >
+ {tracing ? "…" : "trace"}
+ </button>
+ </div>
+ {trace && (
+ <div className="mt-2">
+ {trace.error ? (
+ <p className="text-[12px] text-warn/90">{trace.error}</p>
+ ) : trace.reachable ? (
+ <div>
+ <p className="text-[12px] text-good/90 mb-1">
+ reachable in {trace.hops} hop{trace.hops === 1 ? "" : "s"} via{" "}
+ {trace.mode === "data" ? "data flow" : "calls"}
+ </p>
+ <div className="flex items-center gap-1 flex-wrap">
+ {(trace.path ?? []).map((step, index) => (
+ <span key={index} className="flex items-center gap-1">
+ {index > 0 && (
+ <span className="text-foreground/25 text-[12px]">→</span>
+ )}
+ <button
+ onClick={() => onOpenSymbol({ id: step.id })}
+ className="text-[12px] font-mono text-foreground/70 hover:text-primary transition-colors"
+ title={step.file_path}
+ >
+ {step.name}
+ </button>
+ </span>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <p className="text-[12px] text-foreground/45">
+ not reachable within {trace.max_depth} hops (
+ {trace.mode === "data" ? "data flow" : "calls"};{" "}
+ {trace.explored?.toLocaleString("en-US")} nodes explored)
+ </p>
+ )}
+ </div>
+ )}
+ </div>
<div className="px-4 py-3 border-b border-border/30 shrink-0">
<p className="text-[12px] uppercase tracking-widest text-foreground/45">
Flows — entry → terminal
diff --git a/graph-ui/src/components/SymbolTab.tsx b/graph-ui/src/components/SymbolTab.tsx
index 6b72fb563..669422fc5 100644
--- a/graph-ui/src/components/SymbolTab.tsx
+++ b/graph-ui/src/components/SymbolTab.tsx
@@ -8,6 +8,7 @@ import { callTool } from "../api/rpc";
import {
fetchSymbol,
type ConnectionPage,
+ type DataFlowRef,
type SymbolBundle,
type SymbolRef,
} from "../lib/atlas";
@@ -286,6 +287,90 @@ export function SymbolTab({ project, symbolRef, onOpenSymbol, onOpenRegion }: Sy
/>
</div>
+ {/* Why & who — the rationale proxy and the knowledge map. */}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
+ <div className="bg-card border border-border/50 rounded-md p-4">
+ <p className="text-[12px] uppercase tracking-widest text-foreground/40 mb-2">
+ Recent changes to this file
+ </p>
+ {bundle.file_history?.available === false && (
+ <p className="text-[13px] text-foreground/40">
+ No git history readable for this project.
+ </p>
+ )}
+ {bundle.file_history?.available &&
+ (bundle.file_history.recent?.length ?? 0) === 0 && (
+ <p className="text-[13px] text-foreground/40">
+ Untouched in the last year.
+ </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>
+ ))}
+ {bundle.file_history?.available &&
+ (bundle.file_history.commits_1y ?? 0) > 0 && (
+ <p className="text-[12px] text-foreground/40 mt-2">
+ {bundle.file_history.commits_1y?.toLocaleString("en-US")} commits in the
+ last year
+ {bundle.file_history.top_author &&
+ ` · mostly ${bundle.file_history.top_author} (${((bundle.file_history.top_author_share ?? 0) * 100).toFixed(0)}% of ${bundle.file_history.authors} author${(bundle.file_history.authors ?? 0) > 1 ? "s" : ""})`}
+ </p>
+ )}
+ </div>
+ <div className="bg-card border border-border/50 rounded-md p-4">
+ <p className="text-[12px] uppercase tracking-widest text-foreground/40 mb-2">
+ Data flows
+ </p>
+ {(["data_in", "data_out"] as const).map((direction) => {
+ const flows: DataFlowRef[] = bundle[direction] ?? [];
+ if (flows.length === 0) return null;
+ return (
+ <div key={direction} className="mb-2">
+ <p className="text-[12px] text-foreground/35 mb-1">
+ {direction === "data_in" ? "receives from" : "feeds into"}
+ </p>
+ {flows.map((flow) => (
+ <button
+ key={`${direction}-${flow.id}`}
+ onClick={() => onOpenSymbol({ id: flow.id })}
+ className="flex items-center gap-2 w-full text-left px-2 py-[3px] rounded-md hover:bg-surface-3 transition-colors group"
+ >
+ <span className="text-[13px] font-mono text-foreground/65 group-hover:text-primary truncate transition-colors">
+ {flow.name}
+ </span>
+ {flow.detail?.args !== undefined && (
+ <span className="text-[12px] font-mono text-foreground/35 truncate">
+ {String(flow.detail.args)}
+ </span>
+ )}
+ <span className="text-[12px] text-foreground/25 truncate ml-auto shrink-0 max-w-[38%]">
+ {flow.file_path}
+ </span>
+ </button>
+ ))}
+ </div>
+ );
+ })}
+ {(bundle.data_in ?? []).length === 0 &&
+ (bundle.data_out ?? []).length === 0 && (
+ <p className="text-[13px] text-foreground/40">
+ No DATA_FLOWS edges touch this symbol.
+ </p>
+ )}
+ </div>
+ </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.test.ts b/graph-ui/src/lib/atlas.test.ts
index 2aa33f18c..f90292f34 100644
--- a/graph-ui/src/lib/atlas.test.ts
+++ b/graph-ui/src/lib/atlas.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, it } from "vitest";
-import { archRows } from "./atlas";
+import { describe, expect, it, vi } from "vitest";
+import { archRows, fetchTrace } from "./atlas";
import { surprisingCouplings, suggestedQuestions } from "./firstread";
import { squarify } from "./treemap";
import { composePrompt } from "./composer";
@@ -134,3 +134,26 @@ describe("composePrompt", () => {
expect(prompt).toContain("USAGE edges mean the graph could not prove");
});
});
+
+describe("fetchTrace", () => {
+ it("encodes endpoints + mode and returns the trace payload", async () => {
+ const payload = { mode: "data", max_depth: 12, reachable: true, hops: 1 };
+ const mock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(payload),
+ });
+ vi.stubGlobal("fetch", mock);
+ try {
+ const result = await fetchTrace("demo", "pkg.alpha", "#42", "data");
+ expect(result).toEqual(payload);
+ const url = String(mock.mock.calls[0][0]);
+ expect(url).toContain("/api/trace?");
+ expect(url).toContain("project=demo");
+ expect(url).toContain("from=pkg.alpha");
+ expect(url).toContain("to=%2342");
+ expect(url).toContain("mode=data");
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/graph-ui/src/lib/atlas.ts b/graph-ui/src/lib/atlas.ts
index 1754e4c4a..efa3e546c 100644
--- a/graph-ui/src/lib/atlas.ts
+++ b/graph-ui/src/lib/atlas.ts
@@ -56,6 +56,23 @@ export interface ConnectionPage {
items: SymbolRef[];
}
+export interface DataFlowRef {
+ id: number;
+ label?: string;
+ name: string;
+ file_path?: string;
+ detail?: Record<string, unknown>;
+}
+
+export interface FileHistory {
+ available: boolean;
+ commits_1y?: number;
+ recent?: { hash: string; time: number; author: string; subject: string }[];
+ top_author?: string;
+ top_author_share?: number;
+ authors?: number;
+}
+
export interface SymbolBundle {
node: {
id: number;
@@ -76,6 +93,9 @@ export interface SymbolBundle {
tests?: SymbolRef[];
co_change?: { file_path: string; score?: number }[];
similar?: { id: number; name: string; file_path?: string; score?: number }[];
+ data_in?: DataFlowRef[];
+ data_out?: DataFlowRef[];
+ file_history?: FileHistory;
}
export function fetchSymbol(
@@ -235,3 +255,25 @@ export async function searchGraph(
});
return { rows: decodeSearchGroups(payload), total: payload.total ?? 0 };
}
+
+/* ── /api/trace — A→B reachability over calls or data flows ──── */
+
+export interface TracePayload {
+ mode: "calls" | "data";
+ max_depth: number;
+ reachable: boolean;
+ explored?: number;
+ error?: string;
+ hops?: number;
+ path?: { id: number; name: string; file_path?: string }[];
+}
+
+export function fetchTrace(
+ project: string,
+ from: string,
+ to: string,
+ mode: "calls" | "data",
+): Promise<TracePayload> {
+ const params = new URLSearchParams({ project, from, to, mode });
+ return getJson(`/api/trace?${params}`);
+}
diff --git a/src/ui/atlas.h b/src/ui/atlas.h
index 48670614d..ab94d639e 100644
--- a/src/ui/atlas.h
+++ b/src/ui/atlas.h
@@ -45,6 +45,19 @@ void cbm_atlas_flows_cache_clear(void);
char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project);
void cbm_atlas_metrics_cache_clear(void);
+/* ── File history & ownership (atlas_metrics.c) ───────────────────
+ * The rationale proxy: recent commits and authorship of one file, from the
+ * same bounded git-log pass the dashboard churn uses (cached together).
+ * 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);
+
+/* ── 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.
+ * Endpoints resolve by node id (>=0) or qualified name. */
+char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t from_id,
+ const char *from_qn, int64_t to_id, const char *to_qn, const char *mode);
+
/* ── Region lookups (layout_regions.c) ────────────────────────────
* Cache-backed; computing on first use. name_out (optional) receives a
* heap copy the caller frees. Returns region id or -1. */
diff --git a/src/ui/atlas_api.c b/src/ui/atlas_api.c
index 757fbeec1..6a82278d4 100644
--- a/src/ui/atlas_api.c
+++ b/src/ui/atlas_api.c
@@ -293,13 +293,10 @@ static void aa_add_conn_rows(yyjson_mut_doc *doc, yyjson_mut_val *parent, sqlite
yyjson_mut_val *items = yyjson_mut_arr(doc);
while (sqlite3_step(st) == SQLITE_ROW) {
yyjson_mut_val *row = yyjson_mut_obj(doc);
- yyjson_mut_obj_add_strcpy(doc, row, "type",
- (const char *)sqlite3_column_text(st, 0));
+ yyjson_mut_obj_add_strcpy(doc, row, "type", (const char *)sqlite3_column_text(st, 0));
yyjson_mut_obj_add_int(doc, row, "id", sqlite3_column_int64(st, 1));
- yyjson_mut_obj_add_strcpy(doc, row, "label",
- (const char *)sqlite3_column_text(st, 2));
- yyjson_mut_obj_add_strcpy(doc, row, "name",
- (const char *)sqlite3_column_text(st, 3));
+ yyjson_mut_obj_add_strcpy(doc, row, "label", (const char *)sqlite3_column_text(st, 2));
+ yyjson_mut_obj_add_strcpy(doc, row, "name", (const char *)sqlite3_column_text(st, 3));
const char *file = (const char *)sqlite3_column_text(st, 4);
if (file)
yyjson_mut_obj_add_strcpy(doc, row, "file_path", file);
@@ -348,17 +345,16 @@ static void aa_add_connections(yyjson_mut_doc *doc, yyjson_mut_val *root, struct
yyjson_mut_obj_add_int(doc, section, "offset", offset);
const char *rows_sql =
- inbound
- ? "SELECT e.type, n.id, n.label, n.name, n.file_path, n.start_line, "
- "n.qualified_name FROM edges e JOIN nodes n ON n.project=e.project AND "
- "n.id=e.source_id WHERE e.project=?1 AND e.target_id=?2 AND e.type IN "
- "(" AA_CALLISH_TYPES ") ORDER BY CASE e.type WHEN 'CALLS' THEN 0 WHEN "
- "'CALL_REFERENCE' THEN 1 ELSE 2 END, n.id LIMIT ?3 OFFSET ?4"
- : "SELECT e.type, n.id, n.label, n.name, n.file_path, n.start_line, "
- "n.qualified_name FROM edges e JOIN nodes n ON n.project=e.project AND "
- "n.id=e.target_id WHERE e.project=?1 AND e.source_id=?2 AND e.type IN "
- "(" AA_CALLISH_TYPES ") ORDER BY CASE e.type WHEN 'CALLS' THEN 0 WHEN "
- "'CALL_REFERENCE' THEN 1 ELSE 2 END, n.id LIMIT ?3 OFFSET ?4";
+ inbound ? "SELECT e.type, n.id, n.label, n.name, n.file_path, n.start_line, "
+ "n.qualified_name FROM edges e JOIN nodes n ON n.project=e.project AND "
+ "n.id=e.source_id WHERE e.project=?1 AND e.target_id=?2 AND e.type IN "
+ "(" AA_CALLISH_TYPES ") ORDER BY CASE e.type WHEN 'CALLS' THEN 0 WHEN "
+ "'CALL_REFERENCE' THEN 1 ELSE 2 END, n.id LIMIT ?3 OFFSET ?4"
+ : "SELECT e.type, n.id, n.label, n.name, n.file_path, n.start_line, "
+ "n.qualified_name FROM edges e JOIN nodes n ON n.project=e.project AND "
+ "n.id=e.target_id WHERE e.project=?1 AND e.source_id=?2 AND e.type IN "
+ "(" AA_CALLISH_TYPES ") ORDER BY CASE e.type WHEN 'CALLS' THEN 0 WHEN "
+ "'CALL_REFERENCE' THEN 1 ELSE 2 END, n.id LIMIT ?3 OFFSET ?4";
if (sqlite3_prepare_v2(db, rows_sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
sqlite3_bind_int64(st, 2, id);
@@ -384,19 +380,18 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nod
sqlite3_stmt *st = NULL;
const char *node_sql =
- node_id >= 0
- ? "SELECT id, label, name, qualified_name, file_path, start_line, end_line, "
- "json_extract(properties,'$.docstring'), "
- "json_extract(properties,'$.is_entry_point'), "
- "json_extract(properties,'$.is_test'), "
- "json_extract(properties,'$.is_exported') "
- "FROM nodes WHERE project=?1 AND id=?2"
- : "SELECT id, label, name, qualified_name, file_path, start_line, end_line, "
- "json_extract(properties,'$.docstring'), "
- "json_extract(properties,'$.is_entry_point'), "
- "json_extract(properties,'$.is_test'), "
- "json_extract(properties,'$.is_exported') "
- "FROM nodes WHERE project=?1 AND qualified_name=?2 ORDER BY id LIMIT 1";
+ node_id >= 0 ? "SELECT id, label, name, qualified_name, file_path, start_line, end_line, "
+ "json_extract(properties,'$.docstring'), "
+ "json_extract(properties,'$.is_entry_point'), "
+ "json_extract(properties,'$.is_test'), "
+ "json_extract(properties,'$.is_exported') "
+ "FROM nodes WHERE project=?1 AND id=?2"
+ : "SELECT id, label, name, qualified_name, file_path, start_line, end_line, "
+ "json_extract(properties,'$.docstring'), "
+ "json_extract(properties,'$.is_entry_point'), "
+ "json_extract(properties,'$.is_test'), "
+ "json_extract(properties,'$.is_exported') "
+ "FROM nodes WHERE project=?1 AND qualified_name=?2 ORDER BY id LIMIT 1";
if (sqlite3_prepare_v2(db, node_sql, -1, &st, NULL) != SQLITE_OK)
return NULL;
sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
@@ -471,8 +466,7 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nod
while (sqlite3_step(st) == SQLITE_ROW) {
yyjson_mut_val *row = yyjson_mut_obj(doc);
yyjson_mut_obj_add_int(doc, row, "id", sqlite3_column_int64(st, 0));
- yyjson_mut_obj_add_strcpy(doc, row, "name",
- (const char *)sqlite3_column_text(st, 1));
+ yyjson_mut_obj_add_strcpy(doc, row, "name", (const char *)sqlite3_column_text(st, 1));
const char *tf = (const char *)sqlite3_column_text(st, 2);
if (tf)
yyjson_mut_obj_add_strcpy(doc, row, "file_path", tf);
@@ -511,6 +505,63 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nod
yyjson_mut_obj_add_val(doc, root, "co_change", cochange);
}
+ /* Data flows (the "follow the value" family): in and out, with the
+ * arg→param detail the pipeline stored on the edge. */
+ static const char *const data_sql[2] = {
+ "SELECT n.id, n.label, n.name, n.file_path, e.properties FROM edges e JOIN nodes n "
+ "ON n.project=e.project AND n.id=e.source_id WHERE e.project=?1 AND e.target_id=?2 "
+ "AND e.type='DATA_FLOWS' ORDER BY n.id LIMIT 25",
+ "SELECT n.id, n.label, n.name, n.file_path, e.properties FROM edges e JOIN nodes n "
+ "ON n.project=e.project AND n.id=e.target_id WHERE e.project=?1 AND e.source_id=?2 "
+ "AND e.type='DATA_FLOWS' ORDER BY n.id LIMIT 25",
+ };
+ static const char *const data_field[2] = {"data_in", "data_out"};
+ for (int direction = 0; direction < 2; direction++) {
+ if (sqlite3_prepare_v2(db, data_sql[direction], -1, &st, NULL) != SQLITE_OK)
+ continue;
+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_int64(st, 2, id);
+ yyjson_mut_val *arr = yyjson_mut_arr(doc);
+ while (sqlite3_step(st) == SQLITE_ROW) {
+ yyjson_mut_val *row = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_int(doc, row, "id", sqlite3_column_int64(st, 0));
+ yyjson_mut_obj_add_strcpy(doc, row, "label", (const char *)sqlite3_column_text(st, 1));
+ yyjson_mut_obj_add_strcpy(doc, row, "name", (const char *)sqlite3_column_text(st, 2));
+ const char *df = (const char *)sqlite3_column_text(st, 3);
+ if (df)
+ yyjson_mut_obj_add_strcpy(doc, row, "file_path", df);
+ const char *props = (const char *)sqlite3_column_text(st, 4);
+ if (props && props[0] && strcmp(props, "{}") != 0) {
+ yyjson_doc *pdoc = yyjson_read(props, strlen(props), 0);
+ if (pdoc) {
+ yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc));
+ if (copy)
+ yyjson_mut_obj_add_val(doc, row, "detail", copy);
+ yyjson_doc_free(pdoc);
+ }
+ }
+ yyjson_mut_arr_append(arr, row);
+ }
+ sqlite3_finalize(st);
+ yyjson_mut_obj_add_val(doc, root, data_field[direction], arr);
+ }
+
+ /* Recent change history + ownership of the file — the rationale proxy
+ * (the literature's #1 hardest question). */
+ if (file_copy) {
+ char *history = cbm_atlas_file_history_json(store, project, file_copy);
+ if (history) {
+ yyjson_doc *hdoc = yyjson_read(history, strlen(history), 0);
+ if (hdoc) {
+ yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(hdoc));
+ if (copy)
+ yyjson_mut_obj_add_val(doc, root, "file_history", copy);
+ yyjson_doc_free(hdoc);
+ }
+ free(history);
+ }
+ }
+
/* Near-clones (SIMILAR_TO either direction). */
if (sqlite3_prepare_v2(
db,
@@ -526,8 +577,7 @@ char *cbm_atlas_symbol_json(cbm_store_t *store, const char *project, int64_t nod
while (sqlite3_step(st) == SQLITE_ROW) {
yyjson_mut_val *row = yyjson_mut_obj(doc);
yyjson_mut_obj_add_int(doc, row, "id", sqlite3_column_int64(st, 0));
- yyjson_mut_obj_add_strcpy(doc, row, "name",
- (const char *)sqlite3_column_text(st, 1));
+ yyjson_mut_obj_add_strcpy(doc, row, "name", (const char *)sqlite3_column_text(st, 1));
const char *sf = (const char *)sqlite3_column_text(st, 2);
if (sf)
yyjson_mut_obj_add_strcpy(doc, row, "file_path", sf);
diff --git a/src/ui/atlas_flows.c b/src/ui/atlas_flows.c
index 19bf013c1..37eb446d7 100644
--- a/src/ui/atlas_flows.c
+++ b/src/ui/atlas_flows.c
@@ -66,7 +66,11 @@ typedef struct {
char key[1152];
flow_node_t *nodes;
int node_count;
- int32_t *out_edges; /* callee node indices, grouped by caller */
+ int32_t *out_edges; /* callee node indices, grouped by caller (CALLS) */
+ /* DATA_FLOWS adjacency (same node set, its own CSR). */
+ int32_t *data_first; /* per node: index into data_edges, -1 none */
+ int32_t *data_count;
+ int32_t *data_edges;
flow_t *flows;
int flow_count;
int candidates_dropped;
@@ -93,6 +97,9 @@ static void flow_cache_clear_locked(void) {
}
free(g_flow_cache.nodes);
free(g_flow_cache.out_edges);
+ free(g_flow_cache.data_first);
+ free(g_flow_cache.data_count);
+ free(g_flow_cache.data_edges);
free(g_flow_cache.flows);
memset(&g_flow_cache, 0, sizeof(g_flow_cache));
}
@@ -317,8 +324,7 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const char
nodes[n].name = fl_strdup((const char *)sqlite3_column_text(st, 1));
nodes[n].file_path = fl_strdup((const char *)sqlite3_column_text(st, 2));
nodes[n].first_out = -1;
- nodes[n].flagged_entry =
- sqlite3_column_int(st, 3) != 0 || sqlite3_column_int(st, 4) != 0;
+ nodes[n].flagged_entry = sqlite3_column_int(st, 3) != 0 || sqlite3_column_int(st, 4) != 0;
n++;
}
sqlite3_finalize(st);
@@ -386,8 +392,65 @@ static int fl_rebuild_locked(cbm_store_t *store, const char *project, const char
}
sqlite3_finalize(st);
}
+
+ /* DATA_FLOWS among the same callables (the "follow the value" family). */
+ int32_t *dsrc = NULL, *ddst = NULL;
+ int dcap = 0, dne = 0;
+ if (sqlite3_prepare_v2(db,
+ "SELECT source_id, target_id FROM edges WHERE project=?1 AND "
+ "type='DATA_FLOWS'",
+ -1, &st, NULL) == SQLITE_OK) {
+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
+ while (sqlite3_step(st) == SQLITE_ROW) {
+ int32_t si = fl_index_of(idmap, n, sqlite3_column_int64(st, 0));
+ int32_t di = fl_index_of(idmap, n, sqlite3_column_int64(st, 1));
+ if (si < 0 || di < 0 || si == di)
+ continue;
+ if (dne >= dcap) {
+ int nc = dcap ? dcap * 2 : 1024;
+ int32_t *ns = realloc(dsrc, (size_t)nc * sizeof(int32_t));
+ int32_t *nd = realloc(ddst, (size_t)nc * sizeof(int32_t));
+ if (!ns || !nd) {
+ free(ns ? ns : dsrc);
+ free(nd ? nd : ddst);
+ dsrc = ddst = NULL;
+ dne = 0;
+ break;
+ }
+ dsrc = ns;
+ ddst = nd;
+ dcap = nc;
+ }
+ dsrc[dne] = si;
+ ddst[dne] = di;
+ dne++;
+ }
+ sqlite3_finalize(st);
+ }
free(idmap);
+ g_flow_cache.data_first = malloc((size_t)n * sizeof(int32_t));
+ g_flow_cache.data_count = calloc((size_t)n, sizeof(int32_t));
+ g_flow_cache.data_edges = malloc(dne > 0 ? (size_t)dne * sizeof(int32_t) : sizeof(int32_t));
+ if (g_flow_cache.data_first && g_flow_cache.data_count && g_flow_cache.data_edges) {
+ for (int e = 0; e < dne; e++)
+ g_flow_cache.data_count[dsrc[e]]++;
+ int32_t offset = 0;
+ for (int i = 0; i < n; i++) {
+ g_flow_cache.data_first[i] = offset;
+ offset += g_flow_cache.data_count[i];
+ }
+ int32_t *cursor2 = calloc((size_t)n, sizeof(int32_t));
+ if (cursor2) {
+ for (int e = 0; e < dne; e++)
+ g_flow_cache.data_edges[g_flow_cache.data_first[dsrc[e]] + cursor2[dsrc[e]]++] =
+ ddst[e];
+ }
+ free(cursor2);
+ }
+ free(dsrc);
+ free(ddst);
+
for (int e = 0; e < ne; e++) {
nodes[src[e]].out_count++;
nodes[dst[e]].in_count++;
@@ -551,8 +614,7 @@ char *cbm_atlas_flows_json(cbm_store_t *store, const char *project) {
char entry_name[192];
char terminal_name[192];
fl_display_name(&g_flow_cache.nodes[flow->entry], entry_name, sizeof(entry_name));
- fl_display_name(&g_flow_cache.nodes[flow->terminal], terminal_name,
- sizeof(terminal_name));
+ fl_display_name(&g_flow_cache.nodes[flow->terminal], terminal_name, sizeof(terminal_name));
char label[CBM_SZ_512];
snprintf(label, sizeof(label), "%s → %s", entry_name, terminal_name);
yyjson_mut_obj_add_strcpy(doc, obj, "label", label);
@@ -609,3 +671,137 @@ char *cbm_atlas_flow_json(cbm_store_t *store, const char *project, int flow_id)
yyjson_mut_doc_free(doc);
return json;
}
+
+/* ── A→B trace: shortest path over one edge family ────────────── */
+
+enum { TRACE_MAX_DEPTH = 12 };
+
+static int32_t fl_resolve_endpoint(struct sqlite3 *db, const char *project, int64_t id,
+ const char *qn) {
+ if (id < 0 && qn && qn[0] && db) {
+ sqlite3_stmt *st = NULL;
+ if (sqlite3_prepare_v2(db,
+ "SELECT id FROM nodes WHERE project=?1 AND "
+ "qualified_name=?2 ORDER BY id LIMIT 1",
+ -1, &st, NULL) == SQLITE_OK) {
+ sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
+ sqlite3_bind_text(st, 2, qn, -1, SQLITE_STATIC);
+ if (sqlite3_step(st) == SQLITE_ROW)
+ id = sqlite3_column_int64(st, 0);
+ sqlite3_finalize(st);
+ }
+ }
+ if (id < 0)
+ return -1;
+ /* Map the store id into the cache index (nodes are ordered by id). */
+ int lo = 0, hi = g_flow_cache.node_count - 1;
+ while (lo <= hi) {
+ int mid = lo + (hi - lo) / 2;
+ if (g_flow_cache.nodes[mid].id == id)
+ return mid;
+ if (g_flow_cache.nodes[mid].id < id)
+ lo = mid + 1;
+ else
+ hi = mid - 1;
+ }
+ return -1;
+}
+
+char *cbm_atlas_trace_json(cbm_store_t *store, const char *project, int64_t from_id,
+ const char *from_qn, int64_t to_id, const char *to_qn,
+ const char *mode) {
+ if (!store || !project)
+ return NULL;
+ bool data_mode = mode && strcmp(mode, "data") == 0;
+ pthread_mutex_lock(&g_flow_mu);
+ if (fl_ensure_locked(store, project) != 0 || g_flow_cache.node_count == 0) {
+ pthread_mutex_unlock(&g_flow_mu);
+ return NULL;
+ }
+ struct sqlite3 *db = cbm_store_get_db(store);
+ int32_t from = fl_resolve_endpoint(db, project, from_id, from_qn);
+ int32_t to = fl_resolve_endpoint(db, project, to_id, to_qn);
+
+ 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_str(doc, root, "mode", data_mode ? "data" : "calls");
+ yyjson_mut_obj_add_int(doc, root, "max_depth", TRACE_MAX_DEPTH);
+ if (from < 0 || to < 0) {
+ yyjson_mut_obj_add_bool(doc, root, "reachable", false);
+ yyjson_mut_obj_add_str(doc, root, "error",
+ from < 0 ? "source is not an indexed callable"
+ : "target is not an indexed callable");
+ pthread_mutex_unlock(&g_flow_mu);
+ char *json = yyjson_mut_write(doc, 0, NULL);
+ yyjson_mut_doc_free(doc);
+ return json;
+ }
+
+ /* BFS with parent tracking, bounded depth. */
+ int n = g_flow_cache.node_count;
+ int32_t *parent = malloc((size_t)n * sizeof(int32_t));
+ uint8_t *depth = calloc((size_t)n, sizeof(uint8_t));
+ int32_t *queue = malloc((size_t)n * sizeof(int32_t));
+ long long explored = 0;
+ bool found = from == to;
+ if (parent && depth && queue) {
+ for (int i = 0; i < n; i++)
+ parent[i] = -2; /* unvisited */
+ int head = 0, tail = 0;
+ queue[tail++] = from;
+ parent[from] = -1;
+ while (head < tail && !found) {
+ int32_t node = queue[head++];
+ if (depth[node] >= TRACE_MAX_DEPTH)
+ continue;
+ const int32_t first =
+ data_mode ? g_flow_cache.data_first[node] : g_flow_cache.nodes[node].first_out;
+ const int32_t count =
+ data_mode ? g_flow_cache.data_count[node] : g_flow_cache.nodes[node].out_count;
+ for (int e = 0; e < count; e++) {
+ int32_t next = data_mode ? g_flow_cache.data_edges[first + e]
+ : g_flow_cache.out_edges[first + e];
+ if (parent[next] != -2)
+ continue;
+ parent[next] = node;
+ depth[next] = (uint8_t)(depth[node] + 1);
+ explored++;
+ if (next == to) {
+ found = true;
+ break;
+ }
+ queue[tail++] = next;
+ }
+ }
+ }
+ yyjson_mut_obj_add_bool(doc, root, "reachable", found);
+ yyjson_mut_obj_add_int(doc, root, "explored", explored);
+ if (found && parent) {
+ /* Reconstruct, then emit source→target order. */
+ int32_t chain[TRACE_MAX_DEPTH + 2];
+ int chain_len = 0;
+ for (int32_t node = to; node != -1 && chain_len < TRACE_MAX_DEPTH + 2;
+ node = from == node ? -1 : parent[node])
+ chain[chain_len++] = node;
+ yyjson_mut_val *path = yyjson_mut_arr(doc);
+ for (int i = chain_len - 1; i >= 0; i--) {
+ const flow_node_t *node = &g_flow_cache.nodes[chain[i]];
+ yyjson_mut_val *obj = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_int(doc, obj, "id", node->id);
+ yyjson_mut_obj_add_strcpy(doc, obj, "name", node->name ? node->name : "?");
+ if (node->file_path)
+ yyjson_mut_obj_add_strcpy(doc, obj, "file_path", node->file_path);
+ yyjson_mut_arr_append(path, obj);
+ }
+ yyjson_mut_obj_add_val(doc, root, "path", path);
+ yyjson_mut_obj_add_int(doc, root, "hops", chain_len - 1);
+ }
+ free(parent);
+ free(depth);
+ free(queue);
+ pthread_mutex_unlock(&g_flow_mu);
+ char *json = yyjson_mut_write(doc, 0, NULL);
+ yyjson_mut_doc_free(doc);
+ return json;
+}
diff --git a/src/ui/atlas_metrics.c b/src/ui/atlas_metrics.c
index b9f48c5aa..e98790619 100644
--- a/src/ui/atlas_metrics.c
+++ b/src/ui/atlas_metrics.c
@@ -30,8 +30,8 @@
#include <string.h>
enum {
- MX_TOP_N = 10, /* entries per drill-down list */
- MX_HISTORY_MAX = 60, /* snapshots served to the dashboard */
+ MX_TOP_N = 10, /* entries per drill-down list */
+ MX_HISTORY_MAX = 60, /* snapshots served to the dashboard */
MX_CHURN_MIN_CPLX = 10, /* churn×complexity: only genuinely complex files */
};
@@ -137,8 +137,8 @@ static void mx_project_stamp(cbm_store_t *store, const char *project, char *stam
root_path[0] = '\0';
struct sqlite3 *db = cbm_store_get_db(store);
sqlite3_stmt *st = NULL;
- if (db && sqlite3_prepare_v2(db, "SELECT indexed_at, root_path FROM projects WHERE name=?1",
- -1, &st, NULL) == SQLITE_OK) {
+ if (db && sqlite3_prepare_v2(db, "SELECT indexed_at, root_path FROM projects WHERE name=?1", -1,
+ &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
const char *t = (const char *)sqlite3_column_text(st, 0);
@@ -154,13 +154,34 @@ static void mx_project_stamp(cbm_store_t *store, const char *project, char *stam
/* ── Churn: one bounded `git log` pass, cached with everything else ── */
+enum { MX_FILE_RECENT = 3, MX_COMMIT_CAP = 10000 };
+
+typedef struct {
+ char hash[16];
+ long long time;
+ char author[64];
+ char subject[160];
+} mx_commit_t;
+
typedef struct {
- CBMHashTable *counts; /* file_path → (intptr_t)count; keys owned by list */
+ long long count;
+ int recent[MX_FILE_RECENT]; /* commit indices, newest first */
+ int recent_count;
+ CBMHashTable *authors; /* author name → (intptr_t)count; keys borrowed
+ * from the commit array entries */
+} mx_file_stat_t;
+
+typedef struct {
+ CBMHashTable *counts; /* file_path → mx_file_stat_t*; keys owned by list */
char **keys;
int key_count;
int key_cap;
+ mx_commit_t *commits;
+ int commit_count;
} mx_churn_t;
+static void mx_history_cache_store(const char *project, const char *stamp, mx_churn_t *churn);
+
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))
return;
@@ -174,12 +195,14 @@ static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {
#endif
char cmd[CBM_SZ_2K];
snprintf(cmd, sizeof(cmd),
- "git -C \"%s\" log --name-only --pretty=format: --since=\"1 year ago\" "
- "--max-count=10000 2>%s",
+ "git -C \"%s\" log --name-only --pretty=format:COMMIT:%%h:%%ct:%%an:%%s "
+ "--since=\"1 year ago\" --max-count=10000 2>%s",
root_path, null_dev);
FILE *fp = cbm_popen(cmd, "r");
if (!fp)
return;
+ churn->commits = malloc((size_t)MX_COMMIT_CAP * sizeof(mx_commit_t));
+ int current_commit = -1;
char line[CBM_SZ_1K];
while (fgets(line, sizeof(line), fp)) {
size_t len = strlen(line);
@@ -187,8 +210,43 @@ static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {
line[--len] = '\0';
if (len == 0)
continue;
- const char *canon = cbm_ht_get_key(churn->counts, line);
- if (!canon) {
+ if (strncmp(line, "COMMIT:", 7) == 0) {
+ /* COMMIT:<hash>:<epoch>:<author>:<subject> */
+ current_commit = -1;
+ if (churn->commits && churn->commit_count < MX_COMMIT_CAP) {
+ 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, ':');
+ const char *subject = "";
+ if (colon) {
+ *colon = '\0';
+ subject = colon + 1;
+ }
+ mx_commit_t *commit = &churn->commits[churn->commit_count];
+ snprintf(commit->hash, sizeof(commit->hash), "%s", hash);
+ commit->time = atoll(epoch);
+ snprintf(commit->author, sizeof(commit->author), "%s", author);
+ snprintf(commit->subject, sizeof(commit->subject), "%s", subject);
+ current_commit = churn->commit_count;
+ churn->commit_count++;
+ }
+ continue;
+ }
+ mx_file_stat_t *stat = cbm_ht_get(churn->counts, line);
+ const char *canon;
+ if (!stat) {
if (churn->key_count >= churn->key_cap) {
int nc = churn->key_cap ? churn->key_cap * 2 : 1024;
char **grown = realloc(churn->keys, (size_t)nc * sizeof(char *));
@@ -198,22 +256,49 @@ static void mx_churn_scan(const char *root_path, mx_churn_t *churn) {
churn->key_cap = nc;
}
churn->keys[churn->key_count] = strdup(line);
- if (!churn->keys[churn->key_count])
+ stat = calloc(1, sizeof(mx_file_stat_t));
+ if (!churn->keys[churn->key_count] || !stat) {
+ free(stat);
break;
+ }
canon = churn->keys[churn->key_count];
churn->key_count++;
+ cbm_ht_set(churn->counts, canon, stat);
+ }
+ stat->count++;
+ if (current_commit >= 0) {
+ if (stat->recent_count < MX_FILE_RECENT)
+ stat->recent[stat->recent_count++] = current_commit;
+ if (!stat->authors)
+ stat->authors = cbm_ht_create(8);
+ if (stat->authors) {
+ const char *author = churn->commits[current_commit].author;
+ intptr_t acount = (intptr_t)cbm_ht_get(stat->authors, author);
+ cbm_ht_set(stat->authors, author, (void *)(acount + 1));
+ }
}
- intptr_t count = (intptr_t)cbm_ht_get(churn->counts, canon);
- cbm_ht_set(churn->counts, canon, (void *)(count + 1));
}
cbm_pclose(fp);
}
+static void mx_churn_free_stat(const char *key, void *value, void *userdata) {
+ (void)key;
+ (void)userdata;
+ mx_file_stat_t *stat = value;
+ if (stat) {
+ cbm_ht_free(stat->authors);
+ free(stat);
+ }
+}
+
static void mx_churn_free(mx_churn_t *churn) {
+ if (churn->counts)
+ cbm_ht_foreach(churn->counts, mx_churn_free_stat, NULL);
cbm_ht_free(churn->counts);
for (int i = 0; i < churn->key_count; i++)
free(churn->keys[i]);
free(churn->keys);
+ free(churn->commits);
memset(churn, 0, sizeof(*churn));
}
@@ -225,10 +310,9 @@ static void mx_history_path(const char *project, char *out, size_t cap) {
}
static void mx_history_append_and_emit(yyjson_mut_doc *doc, yyjson_mut_val *root,
- const char *project, const char *stamp,
- long long callables, long long dead, double avg_cplx,
- long long tested, long long usage_edges,
- long long callish_edges) {
+ const char *project, const char *stamp, long long callables,
+ long long dead, double avg_cplx, long long tested,
+ long long usage_edges, long long callish_edges) {
if (!cbm_validate_project_name(project))
return;
char path[CBM_SZ_1K];
@@ -412,16 +496,15 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
/* C. Dead code (candidates only; entry/test/exported excluded, matching
* the galaxy's classifier). */
long long dead = 0;
- if (sqlite3_prepare_v2(
- db,
- "SELECT COUNT(*) FROM nodes n WHERE n.project=?1 AND n.label IN "
- "(" CBM_SQL_CALLABLE_LABELS ") AND "
- "COALESCE(json_extract(n.properties,'$.is_entry_point'),0)=0 AND "
- "COALESCE(json_extract(n.properties,'$.is_test'),0)=0 AND "
- "COALESCE(json_extract(n.properties,'$.is_exported'),0)=0 AND "
- "NOT EXISTS (SELECT 1 FROM edges e WHERE e.project=n.project AND "
- "e.target_id=n.id AND e.type IN ('CALLS','CALL_REFERENCE','USAGE'))",
- -1, &st, NULL) == SQLITE_OK) {
+ if (sqlite3_prepare_v2(db,
+ "SELECT COUNT(*) FROM nodes n WHERE n.project=?1 AND n.label IN "
+ "(" CBM_SQL_CALLABLE_LABELS ") AND "
+ "COALESCE(json_extract(n.properties,'$.is_entry_point'),0)=0 AND "
+ "COALESCE(json_extract(n.properties,'$.is_test'),0)=0 AND "
+ "COALESCE(json_extract(n.properties,'$.is_exported'),0)=0 AND "
+ "NOT EXISTS (SELECT 1 FROM edges e WHERE e.project=n.project AND "
+ "e.target_id=n.id AND e.type IN ('CALLS','CALL_REFERENCE','USAGE'))",
+ -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW)
dead = sqlite3_column_int64(st, 0);
@@ -439,8 +522,7 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
tested = sqlite3_column_int64(st, 0);
sqlite3_finalize(st);
}
- if (sqlite3_prepare_v2(db,
- "SELECT COUNT(*) FROM edges WHERE project=?1 AND type='SIMILAR_TO'",
+ if (sqlite3_prepare_v2(db, "SELECT COUNT(*) FROM edges WHERE project=?1 AND type='SIMILAR_TO'",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW)
@@ -453,8 +535,7 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
{
char shadow[CBM_SZ_512];
cbm_store_coverage_shadow_project(shadow, sizeof(shadow), project);
- if (sqlite3_prepare_v2(db,
- "SELECT COUNT(*) FROM nodes WHERE project=?1 AND label='File'",
+ if (sqlite3_prepare_v2(db, "SELECT COUNT(*) FROM nodes WHERE project=?1 AND label='File'",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, shadow, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW)
@@ -470,13 +551,13 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
long long churn_total_commits = 0;
for (int i = 0; i < churn.key_count; i++) {
const char *file = churn.keys[i];
- long long commits = (intptr_t)cbm_ht_get(churn.counts, file);
+ const mx_file_stat_t *stat = cbm_ht_get(churn.counts, file);
+ long long commits = stat ? stat->count : 0;
churn_total_commits += commits;
mx_top_offer(&top_churn, NULL, NULL, file, commits);
intptr_t max_cplx = file_cplx ? (intptr_t)cbm_ht_get(file_cplx, file) : 0;
if (max_cplx >= MX_CHURN_MIN_CPLX)
- mx_top_offer2(&top_risky, NULL, NULL, file, commits * (long long)max_cplx,
- commits);
+ mx_top_offer2(&top_risky, NULL, NULL, file, commits * (long long)max_cplx, commits);
}
/* ── Serialize ───────────────────────────────────────────── */
@@ -513,21 +594,22 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
mx_top_json(doc, root, "top_long", &top_long);
mx_top_json(doc, root, "top_churn", &top_churn);
mx_top_json(doc, root, "top_churn_complex", &top_risky);
- yyjson_mut_obj_add_bool(doc, root, "churn_available", churn.counts != NULL);
+ yyjson_mut_obj_add_bool(doc, root, "churn_available",
+ churn.counts != NULL && churn.commit_count > 0);
yyjson_mut_obj_add_int(doc, root, "churn_total_commits", churn_total_commits);
yyjson_mut_obj_add_int(doc, root, "churn_total_files", churn.key_count);
long long callish = calls_edges + ref_edges + usage_edges;
mx_history_append_and_emit(doc, root, project, stamp, callables, dead,
- callables > 0 ? (double)cplx_sum / (double)callables : 0.0,
- tested, usage_edges, callish);
+ callables > 0 ? (double)cplx_sum / (double)callables : 0.0, tested,
+ usage_edges, callish);
mx_top_free(&top_complex);
mx_top_free(&top_cognitive);
mx_top_free(&top_long);
mx_top_free(&top_churn);
mx_top_free(&top_risky);
- mx_churn_free(&churn);
+ mx_history_cache_store(project, stamp, &churn); /* takes ownership */
cbm_ht_free(file_cplx);
for (int i = 0; i < file_key_count; i++)
free(file_keys[i]);
@@ -538,6 +620,113 @@ static char *mx_build_json(cbm_store_t *store, const char *project, const char *
return json;
}
+/* ── File-history cache: the churn scan, kept for symbol pages ── */
+
+typedef struct {
+ char key[1280];
+ mx_churn_t churn;
+ bool valid;
+} mx_history_cache_t;
+
+static mx_history_cache_t g_hist_cache;
+static pthread_mutex_t g_hist_mu = PTHREAD_MUTEX_INITIALIZER;
+
+/* Takes ownership of `churn`'s contents (called at the end of a metrics
+ * build; the metrics cache key and this one move in lockstep). */
+static void mx_history_cache_store(const char *project, const char *stamp, mx_churn_t *churn) {
+ pthread_mutex_lock(&g_hist_mu);
+ if (g_hist_cache.valid)
+ mx_churn_free(&g_hist_cache.churn);
+ g_hist_cache.churn = *churn;
+ memset(churn, 0, sizeof(*churn));
+ snprintf(g_hist_cache.key, sizeof(g_hist_cache.key), "%s|%s", project, stamp);
+ g_hist_cache.valid = true;
+ pthread_mutex_unlock(&g_hist_mu);
+}
+
+typedef struct {
+ const char *name;
+ long long count;
+ long long total;
+ int distinct;
+} mx_owner_scan_t;
+
+static void mx_owner_iter(const char *key, void *value, void *userdata) {
+ mx_owner_scan_t *scan = userdata;
+ long long count = (intptr_t)value;
+ scan->total += count;
+ scan->distinct++;
+ if (count > scan->count) {
+ scan->count = count;
+ scan->name = key;
+ }
+}
+
+char *cbm_atlas_file_history_json(cbm_store_t *store, const char *project, const char *file_path) {
+ if (!store || !project || !file_path)
+ return NULL;
+ char stamp[128];
+ char root_path[CBM_SZ_1K];
+ mx_project_stamp(store, project, stamp, sizeof(stamp), root_path, sizeof(root_path));
+ char key[1280];
+ snprintf(key, sizeof(key), "%s|%s", project, stamp);
+
+ pthread_mutex_lock(&g_hist_mu);
+ bool fresh = g_hist_cache.valid && strcmp(g_hist_cache.key, key) == 0;
+ pthread_mutex_unlock(&g_hist_mu);
+ if (!fresh) {
+ /* The metrics build populates the cache; run it if needed. */
+ char *metrics = cbm_atlas_metrics_json(store, project);
+ free(metrics);
+ }
+
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ yyjson_mut_val *root = yyjson_mut_obj(doc);
+ yyjson_mut_doc_set_root(doc, root);
+
+ 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
+ ? cbm_ht_get(g_hist_cache.churn.counts, file_path)
+ : NULL;
+ if (!fresh || !g_hist_cache.churn.counts || g_hist_cache.churn.commit_count == 0) {
+ yyjson_mut_obj_add_bool(doc, root, "available", false);
+ } else if (!stat) {
+ yyjson_mut_obj_add_bool(doc, root, "available", true);
+ yyjson_mut_obj_add_int(doc, root, "commits_1y", 0);
+ } else {
+ yyjson_mut_obj_add_bool(doc, root, "available", true);
+ yyjson_mut_obj_add_int(doc, root, "commits_1y", stat->count);
+ yyjson_mut_val *recent = yyjson_mut_arr(doc);
+ for (int i = 0; i < stat->recent_count; i++) {
+ const mx_commit_t *commit = &g_hist_cache.churn.commits[stat->recent[i]];
+ yyjson_mut_val *obj = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_strcpy(doc, obj, "hash", commit->hash);
+ yyjson_mut_obj_add_int(doc, obj, "time", commit->time);
+ yyjson_mut_obj_add_strcpy(doc, obj, "author", commit->author);
+ yyjson_mut_obj_add_strcpy(doc, obj, "subject", commit->subject);
+ yyjson_mut_arr_append(recent, obj);
+ }
+ yyjson_mut_obj_add_val(doc, root, "recent", recent);
+ if (stat->authors) {
+ mx_owner_scan_t scan = {0};
+ cbm_ht_foreach(stat->authors, mx_owner_iter, &scan);
+ if (scan.name) {
+ yyjson_mut_obj_add_strcpy(doc, root, "top_author", scan.name);
+ yyjson_mut_obj_add_real(doc, root, "top_author_share",
+ scan.total > 0 ? (double)scan.count / (double)scan.total
+ : 0.0);
+ yyjson_mut_obj_add_int(doc, root, "authors", scan.distinct);
+ }
+ }
+ }
+ pthread_mutex_unlock(&g_hist_mu);
+
+ char *json = yyjson_mut_write(doc, 0, NULL);
+ yyjson_mut_doc_free(doc);
+ return json;
+}
+
char *cbm_atlas_metrics_json(cbm_store_t *store, const char *project) {
if (!store || !project)
return NULL;
diff --git a/src/ui/http_server.c b/src/ui/http_server.c
index ed02d649d..0aae4d82d 100644
--- a/src/ui/http_server.c
+++ b/src/ui/http_server.c
@@ -54,7 +54,7 @@
#ifdef _WIN32
#include <windows.h>
#include <process.h>
-#include <psapi.h> /* GetProcessMemoryInfo */
+#include <psapi.h> /* GetProcessMemoryInfo */
#include <tlhelp32.h> /* CreateToolhelp32Snapshot, Process32First/Next */
#else
#include <sys/stat.h>
@@ -591,9 +591,8 @@ static void handle_processes(cbm_http_conn_t *c) {
pe.dwSize = sizeof(pe);
for (BOOL ok = Process32First(hSnap, &pe); ok; ok = Process32Next(hSnap, &pe)) {
if (_stricmp(pe.szExeFile, "codebase-memory-mcp.exe") == 0) {
- HANDLE hProc = OpenProcess(
- PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
- FALSE, pe.th32ProcessID);
+ HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,
+ pe.th32ProcessID);
if (hProc) {
PROCESS_MEMORY_COUNTERS ppmc;
FILETIME ftc, fte, ftk, ftu;
@@ -636,13 +635,10 @@ static void handle_processes(cbm_http_conn_t *c) {
"\"command\":\"codebase-memory-mcp\","
"\"is_self\":%s}",
pe.th32ProcessID, cpu_user + cpu_sys,
- (double)proc_rss / (1024.0 * 1024.0),
- elapsed_sec / 86400,
- (elapsed_sec % 86400) / 3600,
- (elapsed_sec % 3600) / 60,
+ (double)proc_rss / (1024.0 * 1024.0), elapsed_sec / 86400,
+ (elapsed_sec % 86400) / 3600, (elapsed_sec % 3600) / 60,
elapsed_sec % 60,
- pe.th32ProcessID == (DWORD)_getpid()
- ? "true" : "false");
+ pe.th32ProcessID == (DWORD)_getpid() ? "true" : "false");
if (pos >= (int)sizeof(buf)) {
pos = (int)sizeof(buf) - 1;
}
@@ -1496,8 +1492,7 @@ static void handle_layout(cbm_http_conn_t *c, const cbm_http_req_t *req) {
char *regions_json = cbm_layout_regions_json(store, scoped_project);
cbm_store_close(store);
if (!regions_json) {
- cbm_http_replyf(c, 500, g_cors_json,
- "{\"error\":\"region computation failed\"}");
+ cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"region computation failed\"}");
return;
}
cbm_http_replyf(c, 200, g_cors_json, "%s", regions_json);
@@ -1528,8 +1523,7 @@ static void handle_layout(cbm_http_conn_t *c, const cbm_http_req_t *req) {
char *scoped_json = cbm_layout_to_json(scoped);
cbm_layout_free(scoped);
if (!scoped_json) {
- cbm_http_replyf(c, 500, g_cors_json,
- "{\"error\":\"JSON serialization failed\"}");
+ cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"JSON serialization failed\"}");
return;
}
cbm_http_replyf(c, 200, g_cors_json, "%s", scoped_json);
@@ -1747,8 +1741,8 @@ static void handle_layout(cbm_http_conn_t *c, const cbm_http_req_t *req) {
/* Open the query store for ?project=... or reply with the right error.
* Returns NULL after replying. */
-static cbm_store_t *atlas_open_project(cbm_http_conn_t *c, const cbm_http_req_t *req,
- char *project, size_t project_cap) {
+static cbm_store_t *atlas_open_project(cbm_http_conn_t *c, const cbm_http_req_t *req, char *project,
+ size_t project_cap) {
if (!cbm_http_query_param(req->query, "project", project, (int)project_cap) ||
project[0] == '\0') {
cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"missing project parameter\"}");
@@ -1829,6 +1823,31 @@ static void handle_atlas_metrics(cbm_http_conn_t *c, const cbm_http_req_t *req)
atlas_reply_json(c, json, 500, "{\"error\":\"metrics computation failed\"}");
}
+/* GET /api/trace?project=X&from=QN|#id&to=QN|#id&mode=calls|data — A→B. */
+static void handle_atlas_trace(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 from_str[1024] = {0};
+ char to_str[1024] = {0};
+ char mode[16] = {0};
+ cbm_http_query_param(req->query, "from", from_str, (int)sizeof(from_str));
+ cbm_http_query_param(req->query, "to", to_str, (int)sizeof(to_str));
+ cbm_http_query_param(req->query, "mode", mode, (int)sizeof(mode));
+ if (!from_str[0] || !to_str[0]) {
+ cbm_store_close(store);
+ cbm_http_replyf(c, 400, g_cors_json, "{\"error\":\"missing from/to parameter\"}");
+ return;
+ }
+ int64_t from_id = from_str[0] == '#' ? strtoll(from_str + 1, NULL, 10) : -1;
+ int64_t to_id = to_str[0] == '#' ? strtoll(to_str + 1, NULL, 10) : -1;
+ char *json = cbm_atlas_trace_json(store, project, from_id, from_id < 0 ? from_str : NULL, to_id,
+ to_id < 0 ? to_str : NULL, mode[0] ? mode : "calls");
+ cbm_store_close(store);
+ atlas_reply_json(c, json, 500, "{\"error\":\"trace failed\"}");
+}
+
/* GET /api/flows?project=X — ranked entry→terminal flows. */
static void handle_atlas_flows(cbm_http_conn_t *c, const cbm_http_req_t *req) {
char project[256] = {0};
@@ -1879,9 +1898,9 @@ static yyjson_val *json_unique_member(yyjson_val *object, const char *name) {
* MCP transport, where the daemon's mutation guard applies. CBM Atlas is the
* human's window on the graph; this list is what that window may see. */
static const char *const UI_RPC_READ_TOOLS[] = {
- "list_projects", "get_code_snippet", "get_graph_schema", "search_graph",
- "search_code", "trace_path", "trace_call_path", "get_architecture",
- "query_graph", "detect_changes", "check_index_coverage", "index_status",
+ "list_projects", "get_code_snippet", "get_graph_schema", "search_graph",
+ "search_code", "trace_path", "trace_call_path", "get_architecture",
+ "query_graph", "detect_changes", "check_index_coverage", "index_status",
};
static bool rpc_tool_is_read_only(const char *name) {
@@ -2148,6 +2167,12 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,
return;
}
+ /* GET /api/trace → CBM Atlas A→B reachability */
+ if (is_get && cbm_http_path_match(req->path, "/api/trace*")) {
+ handle_atlas_trace(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_httpd.c b/tests/test_httpd.c
index 8064fea72..ec0490c50 100644
--- a/tests/test_httpd.c
+++ b/tests/test_httpd.c
@@ -1091,9 +1091,9 @@ TEST(ui_server_rpc_allows_only_ui_read_tools) {
* "allowed and dispatched" — tool-level argument errors still ride inside
* a 200 JSON-RPC envelope. */
static const char *allowed_tools[] = {
- "list_projects", "get_code_snippet", "get_graph_schema", "search_graph",
- "search_code", "trace_path", "trace_call_path", "get_architecture",
- "query_graph", "detect_changes", "check_index_coverage", "index_status",
+ "list_projects", "get_code_snippet", "get_graph_schema", "search_graph",
+ "search_code", "trace_path", "trace_call_path", "get_architecture",
+ "query_graph", "detect_changes", "check_index_coverage", "index_status",
};
char req[1024];
char resp[8192];
@@ -1136,12 +1136,12 @@ TEST(ui_server_rpc_allows_only_ui_read_tools) {
const char *arguments;
int expected_status;
} adr_cases[] = {
- {"{}", 200}, /* no mode → default "get" */
- {"{\"mode\":\"get\"}", 200}, /* explicit read */
- {"{\"mode\":\"sections\"}", 200}, /* header listing */
- {"{\"mode\":\"update\"}", 403}, /* write */
- {"{\"mode\":\"store\"}", 403}, /* legacy write alias */
- {"{\"mode\":1}", 403}, /* non-string mode */
+ {"{}", 200}, /* no mode → default "get" */
+ {"{\"mode\":\"get\"}", 200}, /* explicit read */
+ {"{\"mode\":\"sections\"}", 200}, /* header listing */
+ {"{\"mode\":\"update\"}", 403}, /* write */
+ {"{\"mode\":\"store\"}", 403}, /* legacy write alias */
+ {"{\"mode\":1}", 403}, /* non-string mode */
{"{\"mode\":\"get\",\"mode\":\"update\"}", 403}, /* smuggled duplicate */
};
for (size_t i = 0; i < sizeof(adr_cases) / sizeof(adr_cases[0]); i++) {
@@ -1191,8 +1191,8 @@ TEST(ui_server_atlas_routes_are_wired) {
* falls through to the static handler's 404. This pins the /api/flow
* (singular) route, which once used a "?*" pattern that never matched
* because req->path carries no query string. */
- static const char *const routes[] = {"/api/tree", "/api/symbol", "/api/flows", "/api/flow",
- "/api/metrics"};
+ static const char *const routes[] = {"/api/tree", "/api/symbol", "/api/flows",
+ "/api/flow", "/api/metrics", "/api/trace"};
char req[256];
char resp[4096];
for (size_t i = 0; i < sizeof(routes) / sizeof(routes[0]); i++) {
diff --git a/tests/test_ui.c b/tests/test_ui.c
index 0f402294f..0647b3fab 100644
--- a/tests/test_ui.c
+++ b/tests/test_ui.c
@@ -127,9 +127,9 @@ TEST(config_save_atomically_replaces_a_complete_generation) {
char old_bytes[512] = {0};
#ifdef _WIN32
DWORD old_length = 0;
- bool old_read = ReadFile(old_handle, old_bytes, (DWORD)sizeof(old_bytes) - 1U, &old_length,
- NULL) != 0 &&
- old_length > 0;
+ bool old_read =
+ ReadFile(old_handle, old_bytes, (DWORD)sizeof(old_bytes) - 1U, &old_length, NULL) != 0 &&
+ old_length > 0;
bool old_closed = CloseHandle(old_handle) != 0;
#else
size_t old_length = fread(old_bytes, 1, sizeof(old_bytes) - 1, old_handle);
@@ -862,7 +862,6 @@ TEST(layout_coincident_nodes_bounded) {
#endif
}
-
/* ── CBM Atlas region level ───────────────────────────────────── */
/* Two call communities in two folders, one cross call. The region level must
@@ -897,8 +896,8 @@ static cbm_store_t *regions_fixture(void) {
ids[i] = cbm_store_upsert_node(store, &node);
}
/* Dense intra-community calls, one cross call alpha_one → beta_one. */
- static const int pairs[][2] = {{0, 1}, {1, 2}, {2, 0}, {0, 2},
- {3, 4}, {4, 5}, {5, 3}, {3, 5}, {0, 3}};
+ static const int pairs[][2] = {{0, 1}, {1, 2}, {2, 0}, {0, 2}, {3, 4},
+ {4, 5}, {5, 3}, {3, 5}, {0, 3}};
for (size_t e = 0; e < sizeof(pairs) / sizeof(pairs[0]); e++) {
cbm_edge_t edge;
memset(&edge, 0, sizeof(edge));
@@ -1012,7 +1011,6 @@ TEST(layout_regions_scope_restricts_nodes) {
PASS();
}
-
/* ── CBM Atlas services: tree, symbol bundle, flows ───────────── */
/* The regions fixture plus: a docstring + entry flag on alpha_one, a test
@@ -1103,6 +1101,14 @@ static cbm_store_t *atlas_fixture(int64_t *alpha_one_id_out) {
edge.properties_json = "{\"score\":0.91}";
cbm_store_insert_edge(store, &edge);
+ memset(&edge, 0, sizeof(edge));
+ edge.project = "regions-test";
+ edge.source_id = ids[1]; /* alpha_two */
+ edge.target_id = ids[2]; /* beta_two */
+ edge.type = "DATA_FLOWS";
+ edge.properties_json = "{\"args\":\"payload->config\"}";
+ cbm_store_insert_edge(store, &edge);
+
memset(&edge, 0, sizeof(edge));
edge.project = "regions-test";
edge.source_id = file_ids[0];
@@ -1192,9 +1198,7 @@ TEST(atlas_symbol_bundle_totals_and_sections) {
yyjson_val *callees = yyjson_obj_get(root, "callees");
ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(callees, "total")), 3);
ASSERT_EQ((int)yyjson_arr_size(yyjson_obj_get(callees, "items")), 2);
- ASSERT_EQ((int)yyjson_get_int(
- yyjson_obj_get(yyjson_obj_get(callees, "by_type"), "CALLS")),
- 3);
+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(yyjson_obj_get(callees, "by_type"), "CALLS")), 3);
/* Callers: alpha_three only. */
yyjson_val *callers = yyjson_obj_get(root, "callers");
@@ -1345,6 +1349,109 @@ TEST(atlas_metrics_totals_and_certainty) {
PASS();
}
+TEST(atlas_trace_reachability_calls_and_data) {
+ cbm_layout_regions_cache_clear();
+ cbm_atlas_flows_cache_clear();
+ cbm_store_t *store = atlas_fixture(NULL);
+ ASSERT_NOT_NULL(store);
+
+ /* alpha_one reaches beta_three over CALLS (via beta_one). */
+ char *json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::alpha_one", -1,
+ "regions-test::beta_three", "calls");
+ ASSERT_NOT_NULL(json);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *root = yyjson_doc_get_root(doc);
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "reachable")));
+ yyjson_val *path = yyjson_obj_get(root, "path");
+ ASSERT_GT((int)yyjson_arr_size(path), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(path, 0), "name")), "alpha_one");
+ int hops = (int)yyjson_get_int(yyjson_obj_get(root, "hops"));
+ ASSERT_EQ((int)yyjson_arr_size(path), hops + 1);
+ yyjson_doc_free(doc);
+ free(json);
+
+ /* beta_three does NOT reach alpha_one (calls point the other way and
+ * the beta cycle never calls into alpha). */
+ json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::beta_three", -1,
+ "regions-test::alpha_one", "calls");
+ ASSERT_NOT_NULL(json);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "reachable")));
+ yyjson_doc_free(doc);
+ free(json);
+
+ /* Data mode follows only DATA_FLOWS: alpha_two → beta_two works,
+ * alpha_one → beta_two does not (no data edge from alpha_one). */
+ json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::alpha_two", -1,
+ "regions-test::beta_two", "data");
+ ASSERT_NOT_NULL(json);
+ doc = yyjson_read(json, strlen(json), 0);
+ root = yyjson_doc_get_root(doc);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(root, "mode")), "data");
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(root, "reachable")));
+ ASSERT_EQ((int)yyjson_get_int(yyjson_obj_get(root, "hops")), 1);
+ yyjson_doc_free(doc);
+ free(json);
+
+ json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::alpha_one", -1,
+ "regions-test::beta_two", "data");
+ ASSERT_NOT_NULL(json);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(yyjson_doc_get_root(doc), "reachable")));
+ yyjson_doc_free(doc);
+ free(json);
+
+ /* Unknown endpoint answers with an error, not a crash. */
+ json = cbm_atlas_trace_json(store, "regions-test", -1, "regions-test::nope", -1,
+ "regions-test::beta_two", "calls");
+ ASSERT_NOT_NULL(json);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(yyjson_obj_get(yyjson_doc_get_root(doc), "error"));
+ yyjson_doc_free(doc);
+ free(json);
+
+ cbm_store_close(store);
+ cbm_atlas_flows_cache_clear();
+ cbm_layout_regions_cache_clear();
+ PASS();
+}
+
+TEST(atlas_symbol_data_flows_and_history_shape) {
+ cbm_layout_regions_cache_clear();
+ cbm_atlas_metrics_cache_clear();
+ int64_t alpha_one = -1;
+ cbm_store_t *store = atlas_fixture(&alpha_one);
+ ASSERT_NOT_NULL(store);
+
+ /* alpha_two has an outgoing DATA_FLOWS edge with detail. */
+ char *json = cbm_atlas_symbol_json(store, "regions-test", -1, "regions-test::alpha_two", 10, 0);
+ ASSERT_NOT_NULL(json);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *root = yyjson_doc_get_root(doc);
+ yyjson_val *data_out = yyjson_obj_get(root, "data_out");
+ ASSERT_EQ((int)yyjson_arr_size(data_out), 1);
+ yyjson_val *flow = yyjson_arr_get(data_out, 0);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(flow, "name")), "beta_two");
+ yyjson_val *detail = yyjson_obj_get(flow, "detail");
+ ASSERT_NOT_NULL(detail);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(detail, "args")), "payload->config");
+
+ /* file_history is present and honest: no git at the fixture root, so
+ * available:false (never fabricated history). */
+ yyjson_val *history = yyjson_obj_get(root, "file_history");
+ ASSERT_NOT_NULL(history);
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(history, "available")));
+
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ cbm_atlas_metrics_cache_clear();
+ cbm_layout_regions_cache_clear();
+ PASS();
+}
+
/* ── Suite ────────────────────────────────────────────────────── */
SUITE(ui) {
@@ -1382,4 +1489,6 @@ SUITE(ui) {
RUN_TEST(atlas_symbol_bundle_totals_and_sections);
RUN_TEST(atlas_flows_walk_and_rank);
RUN_TEST(atlas_metrics_totals_and_certainty);
+ RUN_TEST(atlas_trace_reachability_calls_and_data);
+ RUN_TEST(atlas_symbol_data_flows_and_history_shape);
}