Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(web): say how a call edge got into the graph (#1652)
Raghav Chamadiya45420e50566f
diff --git a/packages/api-client/src/types/intelligence.ts b/packages/api-client/src/types/intelligence.tsindex 4caeb9931..d694fa525 100644--- a/packages/api-client/src/types/intelligence.ts+++ b/packages/api-client/src/types/intelligence.ts@@ -19,6 +19,8 @@ export interface CallerCalleeEntry {start_line?: number | null;edge_type: string;confidence: number;+ /** Which resolution strategy produced the edge. Absent on an older index. */+ resolution_origin?: string | null;}export interface CallersCalleesResponse {@@ -86,6 +88,11 @@ export interface ExecutionFlowEntry {depth: number;crosses_community: boolean;communities_visited: number[];+ /** Why the walk stopped, and how each hop resolved. Absent on an older index.+ * `trace_via` is pairwise with `trace`, so it is one shorter. */+ termination?: string | null;+ termination_detail?: Record<string, number> | null;+ trace_via?: (string | null)[] | null;}export interface ExecutionFlowsResponse {diff --git a/packages/server/src/repowise/server/routers/graph/intelligence.py b/packages/server/src/repowise/server/routers/graph/intelligence.pyindex 7925a134f..fc1eab06e 100644--- a/packages/server/src/repowise/server/routers/graph/intelligence.py+++ b/packages/server/src/repowise/server/routers/graph/intelligence.py@@ -2,6 +2,9 @@from __future__ import annotations+from itertools import pairwise+from typing import Any+from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession@@ -158,16 +161,22 @@ async def get_callers_callees(entry = CallerCalleeEntry(symbol_id=other_id,+ # All three columns are nullable while the response fields are not,+ # so each needs the value checked and not just the row: a null here+ # failed validation for the whole call rather than degrading one+ # row of twenty. `symbol_detail` already guarded name and file this+ # way; this endpoint guarded none of them.name=other.name- if other+ if other and other.nameelse (other_id.split("::")[-1] if "::" in other_id else other_id),- kind=other.kind if other else "unknown",+ kind=other.kind if other and other.kind else "unknown",file=other.file_path- if other+ if other and other.file_pathelse (other_id.split("::")[0] if "::" in other_id else other_id),start_line=other.start_line if other else None,edge_type=e.edge_type,confidence=round(e.confidence or 0.0, 3),+ resolution_origin=e.resolution_origin,)if is_caller:@@ -225,11 +234,25 @@ async def get_execution_flows(flows: list[ExecutionFlowEntry] = []for ep_node, ep_score in entry_nodes:- trace = await bfs_trace(session, repo_id, ep_node.node_id, max_depth, node_cache)+ hop_origins: dict[tuple[str, str], str] = {}+ termination: dict[str, Any] = {}+ trace = await bfs_trace(+ session,+ repo_id,+ ep_node.node_id,+ max_depth,+ node_cache,+ hop_origins,+ termination,+ )communities_visited, crosses = await resolve_trace_communities(session, repo_id, trace, node_cache)+ # Null rather than a list of nulls on an older index, so a consumer can+ # tell "no origins recorded" from "this hop has none".+ via = [hop_origins.get(pair) for pair in pairwise(trace)]+flows.append(ExecutionFlowEntry(entry_point=ep_node.node_id,@@ -239,6 +262,9 @@ async def get_execution_flows(depth=len(trace) - 1,crosses_community=crosses,communities_visited=communities_visited,+ termination=termination.get("reason"),+ termination_detail=termination.get("detail") or None,+ trace_via=via if any(via) else None,))diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.pyindex 4412ab792..308c0dc60 100644--- a/packages/server/src/repowise/server/routers/symbols.py+++ b/packages/server/src/repowise/server/routers/symbols.py@@ -421,13 +421,14 @@ async def symbol_detail("name": other.nameif other and other.nameelse (other_id.split("::")[-1] if "::" in other_id else other_id),- "kind": other.kind if other else "unknown",+ "kind": other.kind if other and other.kind else "unknown","file": other.file_pathif other and other.file_pathelse (other_id.split("::")[0] if "::" in other_id else other_id),"start_line": other.start_line if other else None,"edge_type": e.edge_type,"confidence": round(e.confidence or 0.0, 3),+ "resolution_origin": e.resolution_origin,}(callers if inbound else callees).append(entry)callers.sort(key=lambda x: (-x["confidence"], x["name"]))diff --git a/packages/server/src/repowise/server/schemas/intelligence.py b/packages/server/src/repowise/server/schemas/intelligence.pyindex 73d79cfc9..a070ab36f 100644--- a/packages/server/src/repowise/server/schemas/intelligence.py+++ b/packages/server/src/repowise/server/schemas/intelligence.py@@ -23,6 +23,8 @@ class CallerCalleeEntry(BaseModel):start_line: int | None = Noneedge_type: strconfidence: float+ # None on an index built before origins were stamped.+ resolution_origin: str | None = Noneclass CallersCalleesResponse(BaseModel):@@ -90,6 +92,12 @@ class ExecutionFlowEntry(BaseModel):depth: intcrosses_community: boolcommunities_visited: list[int]+ # Why the walk stopped, and how each hop was resolved. Both None/absent on+ # an index predating them. `trace_via` is pairwise with `trace`, so it is+ # one shorter: `trace_via[i]` describes the hop out of `trace[i]`.+ termination: str | None = None+ termination_detail: dict[str, int] | None = None+ trace_via: list[str | None] | None = Noneclass ExecutionFlowsResponse(BaseModel):diff --git a/packages/types/src/graph.ts b/packages/types/src/graph.tsindex 98d6c6b2f..bda30b18d 100644--- a/packages/types/src/graph.ts+++ b/packages/types/src/graph.ts@@ -233,6 +233,64 @@ export interface SymbolNodeSummary {signature?: string | null;}+/**+ * Which resolution strategy produced a `calls` edge. Closed vocabulary owned+ * by `ingestion/models.py::ResolutionOrigin`; the two are edited together.+ * Render via `originDescriptor` (`@repowise-dev/ui/graph/edge-provenance`) —+ * which origins count as a guess is one decision and lives in one place.+ */+export type ResolutionOrigin =+ | "same_file"+ | "self_scope"+ | "enclosing_class"+ | "receiver_same_file"+ | "same_package"+ | "import_scoped"+ | "receiver_same_package"+ | "package_alias"+ | "module_alias"+ | "crate_root"+ | "receiver_import"+ | "import_merged"+ | "same_target"+ | "receiver_global"+ | "global_unique"+ | "receiver_typed_same_file"+ | "receiver_typed_same_package"+ | "receiver_typed_import"+ | "receiver_typed_global"+ | "receiver_field_same_file"+ | "receiver_field_same_package"+ | "receiver_field_import"+ | "receiver_field_global"+ | "self_inherited"+ | "enclosing_inherited";++/**+ * An origin as received, not as declared. An index outlives the bundle reading+ * it, so a newer indexer can stamp a word this build predates —+ * `originDescriptor` degrades those rather than throwing. Same `(string & {})`+ * escape as `SymbolKind`: autocomplete on the vocabulary, no lie about the wire.+ */+export type ResolutionOriginWire = ResolutionOrigin | (string & {});++/**+ * What stopped a traced flow. Closed vocabulary owned by+ * `analysis/execution_flows.py::FlowTermination`. A trace that merely ends+ * reads as "execution ends here" whether it does or whether the walk ran out+ * of things it could follow; this keeps those apart.+ */+export type FlowTermination =+ | "depth_limit"+ | "callees_truncated"+ | "cycle"+ | "confidence_filtered"+ | "excluded_target"+ | "no_callees";++/** A termination as received. See `ResolutionOriginWire`. */+export type FlowTerminationWire = FlowTermination | (string & {});+export interface CallerCalleeEntry {symbol_id: string;name: string;@@ -241,6 +299,8 @@ export interface CallerCalleeEntry {start_line?: number | null;edge_type: string;confidence: number;+ /** Absent on an index built before origins were stamped. */+ resolution_origin?: ResolutionOriginWire | null;}export interface CallersCallees {@@ -316,6 +376,16 @@ export interface ExecutionFlowEntry {depth: number;crosses_community: boolean;communities_visited: number[];+ /** Why the trace stopped. Absent on an index that carries no terminations. */+ termination?: FlowTerminationWire | null;+ /** For `confidence_filtered` only: declined origin -> count. */+ termination_detail?: Record<string, number> | null;+ /**+ * Origin per hop, pairwise with `trace`, so `trace_via[i]` describes the hop+ * from `trace[i]` to `trace[i + 1]` and the array is one shorter. Omitted+ * when no hop carries one.+ */+ trace_via?: (ResolutionOriginWire | null)[] | null;}export interface ExecutionFlows {diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.tsindex b0e2e9f03..84237231b 100644--- a/packages/types/src/symbols.ts+++ b/packages/types/src/symbols.ts@@ -6,6 +6,8 @@* adapters synthesise both before passing data to components.*/+import type { ResolutionOriginWire } from "./graph";+export type SymbolKind =| "function"| "method"@@ -85,6 +87,8 @@ export interface SymbolCallEntry {start_line: number | null;edge_type: string;confidence: number;+ /** Absent on an index built before origins were stamped. */+ resolution_origin?: ResolutionOriginWire | null;}export interface SymbolDetailGraph {@@ -130,6 +134,7 @@ export interface SymbolBodyCall {file: string;edge_type: string;confidence?: number | null;+ resolution_origin?: ResolutionOriginWire | null;}/** Graph-intelligence block for the unified body (optional — degrades when absent). */diff --git a/packages/ui/__tests__/dashboard/execution-flows-panel.test.tsx b/packages/ui/__tests__/dashboard/execution-flows-panel.test.tsxnew file mode 100644index 000000000..f61bebd3b--- /dev/null+++ b/packages/ui/__tests__/dashboard/execution-flows-panel.test.tsx@@ -0,0 +1,66 @@+/**+ * The trace chain marks which link is a guess, so its indexing has to be right:+ * `trace_via` is pairwise, and the hop arriving at pill `i` is `trace_via[i-1]`.+ * An off-by-one here blames the wrong call, which is worse than no mark.+ */++import { describe, it, expect } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import { ExecutionFlowsPanel } from "../../src/dashboard/execution-flows-panel";+import type { ExecutionFlowEntry } from "@repowise-dev/types/graph";++function flow(over: Partial<ExecutionFlowEntry> = {}): ExecutionFlowEntry {+ return {+ entry_point: "src/app.py::handle",+ entry_point_name: "handle",+ entry_point_score: 0.9,+ trace: ["src/app.py::handle", "src/app.py::validate", "src/app.py::persist"],+ depth: 2,+ crosses_community: false,+ communities_visited: [1],+ ...over,+ };+}++function renderPanel(entry: ExecutionFlowEntry) {+ return render(<ExecutionFlowsPanel flows={[entry]} repoId="r1" />);+}++describe("ExecutionFlowsPanel", () => {+ it("renders an empty state with no flows", () => {+ render(<ExecutionFlowsPanel flows={[]} repoId="r1" />);+ expect(screen.getByText("No execution flows")).toBeInTheDocument();+ });++ it("keys the dashed connector only when a shown hop is a name match", () => {+ const { container } = renderPanel(flow({ trace_via: ["same_file", "global_unique"] }));+ // The chain only renders once expanded.+ fireEvent.click(screen.getByText("handle"));+ expect(container.querySelectorAll(".border-dashed").length).toBeGreaterThan(0);+ });++ it("shows no key when every shown hop carries real evidence", () => {+ const { container } = renderPanel(flow({ trace_via: ["same_file", "import_scoped"] }));+ fireEvent.click(screen.getByText("handle"));+ expect(screen.queryByText("resolved by name match")).not.toBeInTheDocument();+ expect(container.querySelectorAll(".border-dashed").length).toBe(0);+ });++ it("shows no key on an index that records no origins", () => {+ const { container } = renderPanel(flow());+ fireEvent.click(screen.getByText("handle"));+ expect(screen.queryByText("resolved by name match")).not.toBeInTheDocument();+ expect(container.querySelectorAll(".border-dashed").length).toBe(0);+ });++ it("names a name-match hop for a reader who cannot see the dash", () => {+ renderPanel(flow({ trace_via: ["global_unique", "same_file"] }));+ fireEvent.click(screen.getByText("handle"));+ expect(screen.getByText(/resolved by name match:/)).toBeInTheDocument();+ });++ it("collapsed rows say nothing about the stop", () => {+ renderPanel(flow({ termination: "depth_limit" }));+ expect(screen.queryByText(/depth limit/i)).not.toBeInTheDocument();+ });+});diff --git a/packages/ui/__tests__/graph/edge-provenance.test.ts b/packages/ui/__tests__/graph/edge-provenance.test.tsnew file mode 100644index 000000000..29198c2ee--- /dev/null+++ b/packages/ui/__tests__/graph/edge-provenance.test.ts@@ -0,0 +1,141 @@+/**+ * The provenance vocabulary is the one place a resolver word becomes English,+ * so what it refuses to say matters as much as what it says.+ *+ * This file pins the product decisions layered on the vocabulary: which+ * origins count as a guess, and that an unknown word degrades rather than+ * blanks.+ *+ * It is NOT what keeps the vocabulary complete, and the list below is not+ * authoritative — that chain is `satisfies Record<ResolutionOrigin, …>` in the+ * module (union to labels, exhaustive at compile time) plus+ * `tests/unit/server/test_wire_vocabulary_parity.py` (Python to union). The+ * list here is a redundant runtime check, so it can only drift by going stale,+ * never by letting an unlabelled origin through.+ */++import { describe, it, expect } from "vitest";+import {+ isNameMatch,+ originDescriptor,+ terminationCopy,+} from "../../src/graph/edge-provenance";+import type { FlowTermination, ResolutionOrigin } from "@repowise-dev/types/graph";++const ALL_ORIGINS: ResolutionOrigin[] = [+ "same_file",+ "self_scope",+ "enclosing_class",+ "receiver_same_file",+ "same_package",+ "import_scoped",+ "receiver_same_package",+ "package_alias",+ "module_alias",+ "crate_root",+ "receiver_import",+ "import_merged",+ "same_target",+ "receiver_global",+ "global_unique",+ "receiver_typed_same_file",+ "receiver_typed_same_package",+ "receiver_typed_import",+ "receiver_typed_global",+ "receiver_field_same_file",+ "receiver_field_same_package",+ "receiver_field_import",+ "receiver_field_global",+ "self_inherited",+ "enclosing_inherited",+];++const ALL_TERMINATIONS: FlowTermination[] = [+ "depth_limit",+ "callees_truncated",+ "cycle",+ "confidence_filtered",+ "excluded_target",+ "no_callees",+];++describe("originDescriptor", () => {+ it("describes every origin the indexer can stamp", () => {+ for (const origin of ALL_ORIGINS) {+ const d = originDescriptor(origin);+ expect(d, origin).not.toBeNull();+ expect(d!.label.length, origin).toBeGreaterThan(0);+ expect(d!.because.length, origin).toBeGreaterThan(0);+ }+ });++ it("reads a because clause as a sentence", () => {+ // Rendered as `Resolved because ${because}`, so a leading capital or a+ // trailing period would show up in the tooltip.+ for (const origin of ALL_ORIGINS) {+ const because = originDescriptor(origin)!.because;+ expect(because[0], origin).toBe(because[0]!.toLowerCase());+ expect(because.endsWith("."), origin).toBe(false);+ }+ });++ it("returns null for no origin, so an older index renders nothing", () => {+ expect(originDescriptor(null)).toBeNull();+ expect(originDescriptor(undefined)).toBeNull();+ expect(originDescriptor("")).toBeNull();+ });++ it("degrades an unrecognised word instead of blanking it", () => {+ // A newer indexer can stamp a word this bundle predates.+ const d = originDescriptor("some_future_strategy");+ expect(d).not.toBeNull();+ expect(d!.tier).not.toBe("name_match");+ });+});++describe("isNameMatch", () => {+ it("marks exactly the four origins that rest on a name alone", () => {+ const marked = ALL_ORIGINS.filter(isNameMatch);+ expect(marked.sort()).toEqual(+ [+ "global_unique",+ "receiver_field_global",+ "receiver_global",+ "receiver_typed_global",+ ].sort(),+ );+ });++ it("does not mark an absent or unrecognised origin", () => {+ expect(isNameMatch(null)).toBe(false);+ expect(isNameMatch("some_future_strategy")).toBe(false);+ });+});++describe("terminationCopy", () => {+ it("describes every reason a walk can stop", () => {+ for (const reason of ALL_TERMINATIONS) {+ const c = terminationCopy(reason);+ expect(c, reason).not.toBeNull();+ expect(c!.sentence.endsWith("."), reason).toBe(true);+ }+ });++ it("separates a gap in our knowledge from a fact about the code", () => {+ // The whole point of the field: a depth cut is our limit, a cycle is the+ // code's shape. Rendering both as "execution ends here" is the bug.+ expect(terminationCopy("depth_limit")!.isLimit).toBe(true);+ expect(terminationCopy("no_callees")!.isLimit).toBe(true);+ expect(terminationCopy("cycle")!.isLimit).toBe(false);+ });++ it("never asserts that a symbol with no recorded calls calls nothing", () => {+ const sentence = terminationCopy("no_callees")!.sentence;+ expect(sentence).toMatch(/could not resolve/i);+ });++ it("returns null when the index carries no termination", () => {+ expect(terminationCopy(null)).toBeNull();+ expect(terminationCopy("invented_reason")).toBeNull();+ });+});diff --git a/packages/ui/__tests__/graph/graph-flow-panel.test.tsx b/packages/ui/__tests__/graph/graph-flow-panel.test.tsxnew file mode 100644index 000000000..522fc7741--- /dev/null+++ b/packages/ui/__tests__/graph/graph-flow-panel.test.tsx@@ -0,0 +1,157 @@+/**+ * The flow panel's job is to stop a trace from reading as an ending.+ */++import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import { GraphFlowPanel } from "../../src/graph/graph-flow-panel";+import type { ExecutionFlowEntry, ExecutionFlows } from "@repowise-dev/types/graph";++function flow(over: Partial<ExecutionFlowEntry> = {}): ExecutionFlowEntry {+ return {+ entry_point: "src/app.py::handle",+ entry_point_name: "handle",+ entry_point_score: 0.9,+ trace: ["src/app.py::handle", "src/app.py::validate", "src/app.py::persist"],+ depth: 2,+ crosses_community: false,+ communities_visited: [1],+ ...over,+ };+}++function flows(...entries: ExecutionFlowEntry[]): ExecutionFlows {+ return { total_entry_points: entries.length, flows: entries };+}++const noop = () => {};++describe("GraphFlowPanel", () => {+ it("says why the selected trace stopped", () => {+ render(+ <GraphFlowPanel+ flows={flows(flow({ termination: "depth_limit" }))}+ activeFlowIdx={0}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.getByText(/stopped at its depth limit/i)).toBeInTheDocument();+ });++ it("stays silent about the stop until a flow is selected", () => {+ // Ten sentences stacked in a 16rem panel is not a reading surface.+ render(+ <GraphFlowPanel+ flows={flows(flow({ termination: "depth_limit" }))}+ activeFlowIdx={null}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.queryByText(/depth limit/i)).not.toBeInTheDocument();+ });++ it("counts the hops that rest on a name alone", () => {+ render(+ <GraphFlowPanel+ flows={flows(flow({ trace_via: ["same_file", "global_unique"] }))}+ activeFlowIdx={null}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.getByText("1 by name")).toBeInTheDocument();+ });++ it("marks nothing when every hop carries real evidence", () => {+ render(+ <GraphFlowPanel+ flows={flows(flow({ trace_via: ["same_file", "import_scoped"] }))}+ activeFlowIdx={null}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.queryByText(/by name/)).not.toBeInTheDocument();+ });++ it("marks nothing on an index that records no origins", () => {+ render(+ <GraphFlowPanel+ flows={flows(flow())}+ activeFlowIdx={null}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.queryByText(/by name/)).not.toBeInTheDocument();+ expect(screen.getByText("2 calls")).toBeInTheDocument();+ });++ it("reports the hop count once, not as two figures", () => {+ // The row used to print "depth 2" beside "3 nodes" — one number said twice.+ render(+ <GraphFlowPanel+ flows={flows(flow())}+ activeFlowIdx={null}+ onSelect={noop}+ onClose={noop}+ missingCount={0}+ />,+ );+ expect(screen.queryByText(/nodes/)).not.toBeInTheDocument();+ });++ it("passes the clicked row's index up", () => {+ const onSelect = vi.fn();+ render(+ <GraphFlowPanel+ flows={flows(+ flow(),+ flow({ entry_point: "src/app.py::other", entry_point_name: "other" }),+ )}+ activeFlowIdx={null}+ onSelect={onSelect}+ onClose={noop}+ missingCount={0}+ />,+ );+ fireEvent.click(screen.getByText("other"));+ expect(onSelect).toHaveBeenCalledWith(1);+ });++ it("still warns when the canvas does not hold the whole trace", () => {+ render(+ <GraphFlowPanel+ flows={flows(flow())}+ activeFlowIdx={0}+ onSelect={noop}+ onClose={noop}+ missingCount={2}+ />,+ );+ expect(screen.getByText(/includes 2 nodes not in the loaded view/i)).toBeInTheDocument();+ });++ it("prefers the missing-node warning over the stop, and shows one line", () => {+ // Two stacked paragraphs grow a panel that floats over the canvas, and+ // naming where a trace stopped is misleading while its nodes are off-view.+ render(+ <GraphFlowPanel+ flows={flows(flow({ termination: "no_callees" }))}+ activeFlowIdx={0}+ onSelect={noop}+ onClose={noop}+ missingCount={1}+ />,+ );+ expect(screen.getByText(/includes 1 node not in the loaded view/i)).toBeInTheDocument();+ expect(screen.queryByText(/No outgoing calls were recorded/i)).not.toBeInTheDocument();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 1931777eb..ef1f41cd3 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -20,6 +20,7 @@"./brand": "./src/brand.ts","./graph": "./src/graph/index.ts","./graph/context": "./src/graph/context.ts",+ "./graph/edge-provenance": "./src/graph/edge-provenance.ts","./graph/elk-layout": "./src/graph/elk-layout.ts","./graph/use-elk-layout": "./src/graph/use-elk-layout.ts","./graph/use-module-filter": "./src/graph/use-module-filter.ts",diff --git a/packages/ui/src/dashboard/execution-flows-panel.tsx b/packages/ui/src/dashboard/execution-flows-panel.tsxindex ed1ae8e1b..07a996e14 100644--- a/packages/ui/src/dashboard/execution-flows-panel.tsx+++ b/packages/ui/src/dashboard/execution-flows-panel.tsx@@ -5,6 +5,7 @@ import { ChevronRight, ChevronDown, Workflow } from "lucide-react";import { Badge } from "../ui/badge";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { EmptyState } from "../shared/empty-state";+import { isNameMatch, originDescriptor, terminationCopy } from "../graph/edge-provenance";import type { ExecutionFlowEntry } from "@repowise-dev/types/graph";interface ExecutionFlowsPanelProps {@@ -15,6 +16,10 @@ interface ExecutionFlowsPanelProps {function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {const [expanded, setExpanded] = useState(false);+ const stop = terminationCopy(flow.termination);+ // Only the hops whose pills are actually drawn, so the key does not promise+ // a dash that sits behind the "+N more" cut.+ const shownVia = (flow.trace_via ?? []).slice(0, 11);const scoreStyle: CSSProperties =flow.entry_point_score >= 0.7@@ -74,15 +79,35 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {<div className="flex flex-wrap items-center gap-y-2">{flow.trace.slice(0, 12).map((sym, i) => {const name = sym.includes("::") ? sym.split("::").pop() : sym.split("/").pop();+ // `trace_via` is pairwise, so the hop arriving at pill `i` is+ // `trace_via[i - 1]`. Dotted marks the hop we would not assert;+ // the title carries the reason, since a 12px rule cannot.+ const hop = originDescriptor(flow.trace_via?.[i - 1]);return (- <span key={i} className="flex items-center">- {i > 0 && (- <span- aria-hidden- className="h-px w-3 shrink-0"- style={{ background: "var(--color-border-hover)" }}- />- )}+ <span+ key={i}+ className="flex items-center"+ {...(hop ? { title: `Reached because ${hop.because}` } : {})}+ >+ {i > 0 &&+ (hop?.tier === "name_match" ? (+ <>+ {/* The dash is the only visual carrier, so the word has+ to exist for a reader who cannot see it. */}+ <span className="sr-only">resolved by name match: </span>+ <span+ aria-hidden+ className="w-3 shrink-0 border-t border-dashed"+ style={{ borderColor: "var(--color-text-tertiary)" }}+ />+ </>+ ) : (+ <span+ aria-hidden+ className="h-px w-3 shrink-0"+ style={{ background: "var(--color-border-hover)" }}+ />+ ))}<spanclassName="rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-0.5 font-mono text-[10px] text-[var(--color-text-secondary)]"title={sym}@@ -98,6 +123,24 @@ function FlowRow({ flow }: { flow: ExecutionFlowEntry }) {</span>)}</div>+ {/* A key, only when there is a dash to decode. The two sibling+ surfaces spell the tier as a word; a chain has no room per link,+ so the encoding is positional and needs naming once. */}+ {shownVia.some(isNameMatch) && (+ <p className="mt-2 flex items-center gap-1.5 text-[10px] text-[var(--color-text-tertiary)]">+ <span+ aria-hidden+ className="w-3 shrink-0 border-t border-dashed"+ style={{ borderColor: "var(--color-text-tertiary)" }}+ />+ resolved by name match+ </p>+ )}+ {stop && (+ <p className="mt-2 text-[10px] leading-snug text-[var(--color-text-tertiary)]">+ {stop.sentence}+ </p>+ )}</div>)}</div>diff --git a/packages/ui/src/graph/edge-provenance.ts b/packages/ui/src/graph/edge-provenance.tsnew file mode 100644index 000000000..6088ed033--- /dev/null+++ b/packages/ui/src/graph/edge-provenance.ts@@ -0,0 +1,236 @@+/**+ * How a call edge got into the graph, in words a reader can act on.+ *+ * The only place the indexer's two closed vocabularies — `resolution_origin`+ * and `termination` — become English, so no two surfaces describe one edge+ * differently. Per design rule 10, only the `name_match` tier is ever marked:+ * a `same_file` edge is not news, an edge resting on a shared name is.+ *+ * Pure data, no React. Lookups are module-scope, so a per-row call costs one+ * property read.+ */++import type { FlowTermination, ResolutionOrigin } from "@repowise-dev/types/graph";++/**+ * `direct` and `scoped` differ in where the evidence came from, not in how+ * good it is: both required a real language rule to reach the target.+ * `name_match` had no such rule. That is the one line worth drawing on screen.+ */+export type OriginTier = "direct" | "scoped" | "name_match";++export interface OriginDescriptor {+ /** Terse, for a chip or a `title`. Sentence case, no trailing period. */+ label: string;+ /** One clause naming the evidence. Reads after "resolved because ". */+ because: string;+ tier: OriginTier;+}++/** `satisfies` below fails the build when the indexer adds a word and nobody+ * writes its label, which would otherwise render as "unrecognised" forever. */+const ORIGINS = {+ // --- direct: the calling file, or the caller's own class ---------------+ same_file: {+ label: "Same file",+ because: "the target is defined in the calling file",+ tier: "direct",+ },+ self_scope: {+ label: "Own class",+ because: "the call names self/this and the caller's class declares it",+ tier: "direct",+ },+ enclosing_class: {+ label: "Own class",+ because: "a bare call bound to the caller's own class",+ tier: "direct",+ },+ receiver_same_file: {+ label: "Receiver in file",+ because: "the receiver names a class in the calling file",+ tier: "direct",+ },+ receiver_typed_same_file: {+ label: "Inferred type, same file",+ because: "the receiver's declared type is a class in this file",+ tier: "direct",+ },+ receiver_field_same_file: {+ label: "Field type, same file",+ because: "the receiver is a field whose type is a class in this file",+ tier: "direct",+ },++ // --- scoped: an import, a package, a module, a supertype ---------------+ same_package: {+ label: "Same package",+ because: "the target is a sibling file needing no import",+ tier: "scoped",+ },+ import_scoped: {+ label: "Imported",+ because: "the name was imported from the defining file",+ tier: "scoped",+ },+ receiver_same_package: {+ label: "Receiver in package",+ because: "the receiver is a class in the same package",+ tier: "scoped",+ },+ package_alias: {+ label: "Package alias",+ because: "the call is qualified by a package the repo declares",+ tier: "scoped",+ },+ module_alias: {+ label: "Module alias",+ because: "the receiver is an imported module",+ tier: "scoped",+ },+ crate_root: {+ label: "Crate root",+ because: "the reference is crate-scoped",+ tier: "scoped",+ },+ receiver_import: {+ label: "Receiver imported",+ because: "the receiver's class was found in an imported file",+ tier: "scoped",+ },+ import_merged: {+ label: "Imported, file unattributed",+ because: "the name is in one of the imported files, and we cannot say which",+ tier: "scoped",+ },+ same_target: {+ label: "Same build target",+ because: "the target is a sibling translation unit of the same build target",+ tier: "scoped",+ },+ receiver_typed_same_package: {+ label: "Inferred type, same package",+ because: "the receiver's declared type is a class in the same package",+ tier: "scoped",+ },+ receiver_typed_import: {+ label: "Inferred type, imported",+ because: "the receiver's declared type was found in an imported file",+ tier: "scoped",+ },+ receiver_field_same_package: {+ label: "Field type, same package",+ because: "the receiver is a field whose type is a class in the same package",+ tier: "scoped",+ },+ receiver_field_import: {+ label: "Field type, imported",+ because: "the receiver is a field whose type was found in an imported file",+ tier: "scoped",+ },+ self_inherited: {+ label: "Inherited",+ because: "the caller's class does not declare it but one ancestor does",+ tier: "scoped",+ },+ enclosing_inherited: {+ label: "Inherited",+ because: "a bare call the caller's class inherits from one ancestor",+ tier: "scoped",+ },++ // --- name_match: no scope evidence, only a name -----------------------+ receiver_global: {+ label: "Name match",+ because: "that class and method pair exists somewhere in the repo",+ tier: "name_match",+ },+ receiver_typed_global: {+ label: "Name match",+ because: "the inferred type and method pair exists somewhere in the repo",+ tier: "name_match",+ },+ receiver_field_global: {+ label: "Name match",+ because: "the field's type and method pair exists somewhere in the repo",+ tier: "name_match",+ },+ global_unique: {+ label: "Name match",+ because: "the name is unique across the repo, so nothing else could match",+ tier: "name_match",+ },+} as const satisfies Record<ResolutionOrigin, OriginDescriptor>;++/** An index outlives the bundle reading it, so a newer indexer can stamp a+ * word this build predates. We know it resolved and not how, so it never+ * wears the name-match mark. */+const UNRECOGNISED: OriginDescriptor = {+ label: "Resolved",+ because: "this build does not recognise how it was resolved",+ tier: "scoped",+};++/** Describe an origin. Never throws; unknown words degrade rather than blank. */+export function originDescriptor(origin: string | null | undefined): OriginDescriptor | null {+ if (!origin) return null;+ return (ORIGINS as Record<string, OriginDescriptor>)[origin] ?? UNRECOGNISED;+}++/** The one predicate a surface should branch on. Everything else is ordinary+ * resolution and gets no decoration. */+export function isNameMatch(origin: string | null | undefined): boolean {+ return originDescriptor(origin)?.tier === "name_match";+}++export interface TerminationCopy {+ /** Terse, for a chip. Sentence case, no trailing period. */+ label: string;+ /** The full claim, and the only place the distinction actually survives. */+ sentence: string;+ /** A gap in what we know, rather than a fact about the code. */+ isLimit: boolean;+}++const TERMINATIONS = {+ depth_limit: {+ label: "Depth limit",+ sentence: "The trace stopped at its depth limit. Execution continues past this point.",+ isLimit: true,+ },+ callees_truncated: {+ label: "Too many callees",+ sentence:+ "This symbol has more outgoing calls than the trace reads, so the next step is unknown rather than absent.",+ isLimit: true,+ },+ cycle: {+ label: "Cycle",+ sentence:+ "Every next step was already on this path. That is recursion or a mutual call, not the end of execution.",+ isLimit: false,+ },+ confidence_filtered: {+ label: "Below threshold",+ sentence:+ "Every next step rested on a name match alone, which we will not assert as a call.",+ isLimit: true,+ },+ excluded_target: {+ label: "Test or fixture",+ sentence: "Every next step was a test, demo or fixture, which traces do not follow.",+ isLimit: false,+ },+ no_callees: {+ label: "No calls recorded",+ sentence:+ "No outgoing calls were recorded here. That can mean this symbol calls nothing, or that we could not resolve what it calls.",+ isLimit: true,+ },+} as const satisfies Record<FlowTermination, TerminationCopy>;++/** Describe a termination. Returns null for an index that carries none. */+export function terminationCopy(reason: string | null | undefined): TerminationCopy | null {+ if (!reason) return null;+ return (TERMINATIONS as Record<string, TerminationCopy>)[reason] ?? null;+}diff --git a/packages/ui/src/graph/graph-flow-panel.tsx b/packages/ui/src/graph/graph-flow-panel.tsxnew file mode 100644index 000000000..5e49d2207--- /dev/null+++ b/packages/ui/src/graph/graph-flow-panel.tsx@@ -0,0 +1,131 @@+"use client";++import { memo } from "react";+import { X } from "lucide-react";+import type { ExecutionFlowEntry, ExecutionFlows } from "@repowise-dev/types/graph";+import { isNameMatch, terminationCopy } from "./edge-provenance";++export interface GraphFlowPanelProps {+ flows: ExecutionFlows;+ activeFlowIdx: number | null;+ onSelect: (idx: number) => void;+ onClose: () => void;+ /** Trace nodes the loaded canvas does not hold, for the active flow only. */+ missingCount: number;+}++/** Hops resolved on a name and nothing else. 0 when the index carries no origins. */+function nameMatchHops(flow: ExecutionFlowEntry): number {+ return (flow.trace_via ?? []).filter(isNameMatch).length;+}++const FlowRow = memo(function FlowRow({+ flow,+ idx,+ isActive,+ onSelect,+}: {+ flow: ExecutionFlowEntry;+ idx: number;+ isActive: boolean;+ onSelect: (idx: number) => void;+}) {+ const guessed = nameMatchHops(flow);+ return (+ <button+ onClick={() => onSelect(idx)}+ className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-colors ${+ isActive+ ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"+ : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"+ }`}+ >+ <div className="font-mono truncate">{flow.entry_point_name}</div>+ <div className="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">+ {/* `depth` is the hop count; `trace.length` was the same number said a+ second way, so the row claimed two figures and had one. */}+ <span className="tabular-nums">{flow.depth} calls</span>+ {guessed > 0 && (+ <span+ className="tabular-nums"+ title={`${guessed} of these hops rests on a matching name alone, with no import, package or type behind it.`}+ >+ {guessed} by name+ </span>+ )}+ {flow.crosses_community && <span>cross-community</span>}+ </div>+ </button>+ );+});++/**+ * The flow list on the graph canvas.+ *+ * Its own component, and memoised, because the canvas it floats over sets+ * state on every pointer move: inline rows there re-parse each flow per frame.+ */+export const GraphFlowPanel = memo(function GraphFlowPanel({+ flows,+ activeFlowIdx,+ onSelect,+ onClose,+ missingCount,+}: GraphFlowPanelProps) {+ const activeFlow = activeFlowIdx === null ? undefined : flows.flows[activeFlowIdx];+ const stop = terminationCopy(activeFlow?.termination);++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs font-medium text-[var(--color-text-primary)]">+ Execution Flows+ </span>+ <div className="flex items-center gap-1.5">+ <span className="text-[10px] text-[var(--color-text-tertiary)] tabular-nums">+ {flows.flows.length} entry points+ </span>+ {/* Same close affordance as the Path Finder panel above. */}+ <button+ onClick={onClose}+ aria-label="Close"+ title="Close"+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ <X className="w-3 h-3" />+ </button>+ </div>+ </div>++ <div className="space-y-1 max-h-60 overflow-y-auto">+ {flows.flows.map((flow, idx) => (+ <FlowRow+ key={flow.entry_point}+ flow={flow}+ idx={idx}+ isActive={activeFlowIdx === idx}+ onSelect={onSelect}+ />+ ))}+ </div>++ {/* One line at most: this panel floats over the canvas, so height is+ borrowed from the thing being read. The missing-node warning wins+ because it also explains why the highlighted path looks short —+ describing where the trace stopped is misleading while the reader+ cannot see the nodes it stopped at. */}+ {missingCount > 0 ? (+ <p className="mt-2 border-t border-[var(--color-border-default)] pt-2 text-[10px] leading-snug text-[var(--color-warning)]">+ This flow includes {missingCount} node{missingCount === 1 ? "" : "s"} not in the+ loaded view — load more nodes to see the full trace.+ </p>+ ) : (+ stop && (+ <p className="mt-2 border-t border-[var(--color-border-default)] pt-2 text-[10px] leading-snug text-[var(--color-text-tertiary)]">+ {stop.sentence}+ </p>+ )+ )}+ </div>+ );+});diff --git a/packages/ui/src/graph/graph-flow.tsx b/packages/ui/src/graph/graph-flow.tsxindex 710faf841..b7335d4fe 100644--- a/packages/ui/src/graph/graph-flow.tsx+++ b/packages/ui/src/graph/graph-flow.tsx@@ -34,6 +34,7 @@ import { GraphToolbar, type ColorMode, type ViewMode, type LayoutMode, type Grapimport { GraphLegend } from "./graph-legend";import { GraphContextMenu } from "./graph-context-menu";import { GraphInspectionPanel } from "./graph-inspection-panel";+import { GraphFlowPanel } from "./graph-flow-panel";import { GraphShortcutHelp } from "./graph-shortcut-help";import type {GraphExport,@@ -252,6 +253,15 @@ export function GraphFlow(props: GraphFlowProps) {// Execution flowsconst [activeFlowIdx, setActiveFlowIdx] = useState<number | null>(null);const [showFlows, setShowFlows] = useState(false);+ // Stable, so the memoised panel does not re-render with the canvas.+ const handleFlowSelect = useCallback(+ (idx: number) => setActiveFlowIdx((cur) => (cur === idx ? null : idx)),+ [],+ );+ const handleFlowsClose = useCallback(() => {+ setShowFlows(false);+ setActiveFlowIdx(null);+ }, []);// Community detail panel (the filter state itself lives in useCommunityFilter)const [communityPanelId, setCommunityPanelId] = useState<number | null>(null);@@ -1136,59 +1146,13 @@ export function GraphFlow(props: GraphFlowProps) {{/* Execution Flows Panel */}{showFlows && executionFlows && executionFlows.flows.length > 0 && (<div className="absolute top-14 right-3 z-10 w-[min(16rem,calc(100vw-1.5rem))]">- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]/95 backdrop-blur-sm shadow-lg shadow-black/20 p-3">- <div className="flex items-center justify-between mb-2">- <span className="text-xs font-medium text-[var(--color-text-primary)]">- Execution Flows- </span>- <div className="flex items-center gap-1.5">- <span className="text-[10px] text-[var(--color-text-tertiary)]">- {executionFlows.flows.length} entry points- </span>- {/* Same close affordance as the Path Finder panel above. */}- <button- onClick={() => {- setShowFlows(false);- setActiveFlowIdx(null);- }}- aria-label="Close"- title="Close"- className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"- >- <X className="w-3 h-3" />- </button>- </div>- </div>- <div className="space-y-1 max-h-60 overflow-y-auto">- {executionFlows.flows.map((flow, idx) => (- <button- key={flow.entry_point}- onClick={() => setActiveFlowIdx(activeFlowIdx === idx ? null : idx)}- className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-colors ${- activeFlowIdx === idx- ? "bg-[var(--color-accent-primary)]/15 text-[var(--color-accent-primary)]"- : "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-overlay)] hover:text-[var(--color-text-primary)]"- }`}- >- <div className="font-mono truncate">{flow.entry_point_name}</div>- <div className="flex items-center gap-2 mt-0.5 text-[10px] text-[var(--color-text-tertiary)]">- <span>depth {flow.depth}</span>- <span>{flow.trace.length} nodes</span>- {flow.crosses_community && (- <span className="text-yellow-500">cross-community</span>- )}- </div>- </button>- ))}- </div>- {activeFlowMissingCount > 0 && (- <p className="mt-2 text-[10px] leading-snug text-[var(--color-warning)]">- This flow includes {activeFlowMissingCount} node- {activeFlowMissingCount === 1 ? "" : "s"} not in the loaded- view — load more nodes to see the full trace.- </p>- )}- </div>+ <GraphFlowPanel+ flows={executionFlows}+ activeFlowIdx={activeFlowIdx}+ onSelect={handleFlowSelect}+ onClose={handleFlowsClose}+ missingCount={activeFlowMissingCount}+ /></div>)}diff --git a/packages/ui/src/graph/index.ts b/packages/ui/src/graph/index.tsindex 72b40ffeb..d81aa2827 100644--- a/packages/ui/src/graph/index.ts+++ b/packages/ui/src/graph/index.ts@@ -11,6 +11,8 @@ export * from "./graph-context-drawer";export * from "./graph-truncation-banner";export * from "./graph-canvas-shell";export * from "./graph-flow";+export * from "./graph-flow-panel";+export * from "./edge-provenance";export * from "./context";export * from "./elk-layout";export * from "./graph-scope-controls";diff --git a/packages/ui/src/symbols/symbol-call-graph.tsx b/packages/ui/src/symbols/symbol-call-graph.tsxindex dc60394e9..81558db6b 100644--- a/packages/ui/src/symbols/symbol-call-graph.tsx+++ b/packages/ui/src/symbols/symbol-call-graph.tsx@@ -3,7 +3,7 @@import { ArrowRight } from "lucide-react";import type { SymbolBodyCall } from "@repowise-dev/types/symbols";import { truncatePath } from "../lib/format";-import { cn } from "../lib/cn";+import { originDescriptor } from "../graph/edge-provenance";interface SymbolCallGraphProps {centerName: string;@@ -21,25 +21,25 @@ function CallNode({entry: SymbolBodyCall;symbolHref?: (id: string) => string;}) {+ // The origin replaces a green/amber/grey confidence dot that carried no key+ // and reached for the health ramp to say something that is not a health+ // band. Only a name match is marked; everything else is ordinary resolution.+ const origin = originDescriptor(entry.resolution_origin);const inner = (- <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 transition-colors hover:border-[var(--color-border-hover)]">- <div className="flex items-center gap-1.5">- <span- className={cn(- "h-1.5 w-1.5 shrink-0 rounded-full",- (entry.confidence ?? 1) >= 0.9- ? "bg-[var(--color-success)]"- : (entry.confidence ?? 1) >= 0.7- ? "bg-[var(--color-caution)]"- : "bg-[var(--color-text-tertiary)]",- )}- />- <span className="truncate font-mono text-xs text-[var(--color-text-primary)]">- {entry.name}- </span>+ <div+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 transition-colors hover:border-[var(--color-border-hover)]"+ {...(origin ? { title: `Resolved because ${origin.because}` } : {})}+ >+ <div className="truncate font-mono text-xs text-[var(--color-text-primary)]">+ {entry.name}</div>- <div className="truncate pl-3 text-[10px] text-[var(--color-text-tertiary)]" title={entry.file}>- {truncatePath(entry.file, 28)}+ <div className="flex items-baseline gap-1.5 text-[10px] text-[var(--color-text-tertiary)]">+ <span className="min-w-0 flex-1 truncate" title={entry.file}>+ {truncatePath(entry.file, 28)}+ </span>+ {/* Not mono: this is an authored category, not a value the machine+ emitted, so it takes the ordinary face like `SeverityMark`. */}+ {origin?.tier === "name_match" && <span className="shrink-0">name match</span>}</div></div>);diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsxindex 547f61d41..28c29af84 100644--- a/packages/ui/src/symbols/symbol-page.tsx+++ b/packages/ui/src/symbols/symbol-page.tsx@@ -74,6 +74,7 @@ export function normalizeSymbolDetailResponse(file: c.file,edge_type: c.edge_type,confidence: c.confidence,+ resolution_origin: c.resolution_origin ?? null,})),callees: data.graph.callees.map((c) => ({symbol_id: c.symbol_id,@@ -81,6 +82,7 @@ export function normalizeSymbolDetailResponse(file: c.file,edge_type: c.edge_type,confidence: c.confidence,+ resolution_origin: c.resolution_origin ?? null,})),},governing_decisions: data.governing_decisions,diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsxindex b1d7e29a2..6a1aacc62 100644--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx@@ -105,6 +105,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {file: c.file,edge_type: c.edge_type,confidence: c.confidence,+ resolution_origin: c.resolution_origin ?? null,})),callees: (callData?.callees ?? []).map((c) => ({symbol_id: c.symbol_id,@@ -112,6 +113,7 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {file: c.file,edge_type: c.edge_type,confidence: c.confidence,+ resolution_origin: c.resolution_origin ?? null,})),pagerank_percentile: metrics?.pagerank_percentile ?? null,betweenness_percentile: metrics?.betweenness_percentile ?? null,diff --git a/tests/unit/server/test_graph_provenance_wire.py b/tests/unit/server/test_graph_provenance_wire.pynew file mode 100644index 000000000..0ad787e44--- /dev/null+++ b/tests/unit/server/test_graph_provenance_wire.py@@ -0,0 +1,219 @@+"""The REST graph surfaces must carry the provenance the walk already computes.++``bfs_trace`` has filled ``hop_origins`` and ``termination`` since P15, and the+MCP tool reads both. The REST twin called the same function and passed neither,+so the dashboard rendered a trace that stops with no way to tell "the code ends+here" from "we could not follow it further" — the distinction the field exists+for. Same shape for ``resolution_origin`` on caller/callee rows, which shipped+a confidence float with nothing to explain it.++The three endpoints are covered together because they are one contract: the+web surfaces render all three through one vocabulary module.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient++from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import GraphEdge, GraphNode, WikiSymbol+from tests.unit.server.conftest import create_test_repo++_FILE = "src/app/service.py"+_ENTRY = "src/app/service.py::handle"+_MID = "src/app/service.py::validate"+_LEAF = "src/app/service.py::persist"+++async def _seed(session_factory, repo_id: str) -> None:+ """A two-hop chain, each hop stamped with a different origin.++ The two origins are chosen from opposite ends of the vocabulary —+ ``same_file`` is direct evidence, ``global_unique`` is a bare name guess —+ so a test asserting the pair also proves the field is per-edge and not a+ constant.+ """+ async with get_session(session_factory) as session:+ for node_id in (_ENTRY, _MID, _LEAF):+ session.add(+ GraphNode(+ repository_id=repo_id,+ node_id=node_id,+ node_type="symbol",+ language="python",+ pagerank=0.5,+ file_path=_FILE,+ name=node_id.split("::")[-1],+ kind="function",+ community_meta_json='{"entry_point_score": 0.9}',+ )+ )+ session.add(+ WikiSymbol(+ repository_id=repo_id,+ file_path=_FILE,+ symbol_id=node_id,+ name=node_id.split("::")[-1],+ qualified_name=node_id.split("::")[-1],+ kind="function",+ language="python",+ )+ )+ for src, tgt, origin in (+ (_ENTRY, _MID, "same_file"),+ (_MID, _LEAF, "global_unique"),+ ):+ session.add(+ GraphEdge(+ repository_id=repo_id,+ source_node_id=src,+ target_node_id=tgt,+ imported_names_json="[]",+ edge_type="calls",+ confidence=0.95,+ resolution_origin=origin,+ )+ )+++async def test_a_traced_flow_says_why_it_stopped(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/execution-flows",+ params={"entry_point": _ENTRY, "max_depth": 5},+ )+ assert resp.status_code == 200+ flow = resp.json()["flows"][0]++ assert flow["trace"] == [_ENTRY, _MID, _LEAF]+ # The leaf records no outgoing call, and the walk had budget left, so the+ # honest reason is that nothing was recorded — not that it was cut short.+ assert flow["termination"] == "no_callees"+++async def test_a_traced_flow_carries_an_origin_per_hop(client: AsyncClient, app) -> None:+ """`trace_via` is pairwise, so it is exactly one shorter than `trace`."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/execution-flows",+ params={"entry_point": _ENTRY, "max_depth": 5},+ )+ flow = resp.json()["flows"][0]++ assert flow["trace_via"] == ["same_file", "global_unique"]+ assert len(flow["trace_via"]) == len(flow["trace"]) - 1+++async def test_a_depth_limited_flow_is_not_reported_as_an_ending(+ client: AsyncClient, app+) -> None:+ """The case the field exists for: the walk stopped, the code did not."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/execution-flows",+ params={"entry_point": _ENTRY, "max_depth": 1},+ )+ flow = resp.json()["flows"][0]++ assert flow["trace"] == [_ENTRY, _MID]+ assert flow["termination"] == "depth_limit"+++async def test_callers_callees_carry_the_origin(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(+ f"/api/graph/{repo['id']}/callers-callees", params={"symbol_id": _MID}+ )+ assert resp.status_code == 200+ body = resp.json()++ assert [c["resolution_origin"] for c in body["callers"]] == ["same_file"]+ assert [c["resolution_origin"] for c in body["callees"]] == ["global_unique"]+++async def test_a_node_with_null_columns_degrades_instead_of_failing_the_response(+ client: AsyncClient, app+) -> None:+ """`name`, `kind` and `file_path` are nullable; the response fields are not.++ Found by this file's own fixture before it stamped a kind, then widened+ when a review pointed out the two siblings had the same gap. The bad row is+ one of up to twenty, so failing the whole call over it loses the nineteen+ that were fine. Each column is left null on its own node, so a failure+ names the column rather than the endpoint.+ """+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])+ bare = "src/app/other.py::mystery" # kind null+ nameless = "src/app/other.py::anon" # name null+ pathless = "src/app/other.py::floating" # file_path null+ async with get_session(app.state.session_factory) as session:+ for node_id, name, kind, file_path in (+ (bare, "mystery", None, "src/app/other.py"),+ (nameless, None, "function", "src/app/other.py"),+ (pathless, "floating", "function", None),+ ):+ session.add(+ GraphNode(+ repository_id=repo["id"],+ node_id=node_id,+ node_type="symbol",+ language="python",+ pagerank=0.1,+ file_path=file_path,+ name=name,+ kind=kind,+ )+ )+ session.add(+ GraphEdge(+ repository_id=repo["id"],+ source_node_id=_MID,+ target_node_id=node_id,+ imported_names_json="[]",+ edge_type="calls",+ confidence=0.9,+ resolution_origin="same_file",+ )+ )++ resp = await client.get(+ f"/api/graph/{repo['id']}/callers-callees", params={"symbol_id": _MID}+ )+ assert resp.status_code == 200+ rows = {c["symbol_id"]: c for c in resp.json()["callees"]}++ # Each falls back to what the node id itself can supply.+ assert rows[bare]["kind"] == "unknown"+ assert rows[nameless]["name"] == "anon"+ assert rows[pathless]["file"] == "src/app/other.py"+++async def test_symbol_detail_carries_the_origin(client: AsyncClient, app) -> None:+ """The drawer and the symbol route read different endpoints for one view."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(+ "/api/symbols/detail", params={"repo_id": repo["id"], "symbol_id": _MID}+ )+ assert resp.status_code == 200+ graph = resp.json()["graph"]++ assert [c["resolution_origin"] for c in graph["callers"]] == ["same_file"]+ assert [c["resolution_origin"] for c in graph["callees"]] == ["global_unique"]diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.pynew file mode 100644index 000000000..c2a75e440--- /dev/null+++ b/tests/unit/server/test_wire_vocabulary_parity.py@@ -0,0 +1,38 @@+"""The two closed vocabularies cross a language boundary, so pin both ends.++``ResolutionOrigin`` and ``FlowTermination`` are declared in Python and copied+into ``packages/types/src/graph.ts`` for the web surfaces. Nothing else makes+the copies agree: a word added on one side renders as "unrecognised" forever on+the other, silently, because both sides degrade rather than throw.++Ceiling: a regex read of the two TypeScript unions. It proves the *member sets*+match, not that the TS file parses.+"""++from __future__ import annotations++import pathlib+import re++from repowise.core.analysis.execution_flows import FLOW_TERMINATION_VALUES+from repowise.core.ingestion.models import RESOLUTION_ORIGIN_VALUES++_TYPES = (+ pathlib.Path(__file__).resolve().parents[3] / "packages/types/src/graph.ts"+)+++def _union_members(alias: str) -> set[str]:+ """The string members of `export type <alias> = "a" | "b" | ...;`."""+ source = _TYPES.read_text(encoding="utf-8")+ match = re.search(rf"export type {alias} =(.*?);", source, re.DOTALL)+ assert match, f"{alias} is not declared in {_TYPES.name}"+ return set(re.findall(r'"([a-z_]+)"', match.group(1)))+++def test_resolution_origin_union_matches_python() -> None:+ assert _union_members("ResolutionOrigin") == set(RESOLUTION_ORIGIN_VALUES)+++def test_flow_termination_union_matches_python() -> None:+ assert _union_members("FlowTermination") == set(FLOW_TERMINATION_VALUES)