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(ui): add 3D architecture and route exploration

Martin Vogel79c37032ccf7
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsx
index a7acd22e7..a381a2e08 100644
--- a/graph-ui/src/App.tsx
+++ b/graph-ui/src/App.tsx
@@ -4848,7 +4848,7 @@ export default function App(): JSX.Element {
onGuidanceChange={changeGuidance}
workspacePanel={<>
<div hidden={workspace !== 'architecture'}>
- <ArchitecturePanel projectName={project} overview={overview}
+ <ArchitecturePanel projectName={project} overview={overview} active={workspace === 'architecture'}
readSource={readMapSource}
graph={repositoryReading.snapshot} graphGeneration={repositoryReading.snapshot?.generation} selection={activeGalaxySelection} selectionPanel={mapSelectionPanel}
graphNote={repositoryReading.error ?? (repositoryReading.snapshot
diff --git a/graph-ui/src/architecture/ArchitecturePanel.test.tsx b/graph-ui/src/architecture/ArchitecturePanel.test.tsx
index ee4a64c52..52419d729 100644
--- a/graph-ui/src/architecture/ArchitecturePanel.test.tsx
+++ b/graph-ui/src/architecture/ArchitecturePanel.test.tsx
@@ -64,13 +64,25 @@ async function filter(value: string): Promise<void> {
}
describe('architecture workspace', () => {
+ it('keeps a spatial exploration surface across architecture, dependencies, routes and entry points', async () => {
+ await render({ graph: { nodes: [], edges: [], total_nodes: 0 } });
+ const surface = container.querySelector('[data-testid="spatial-architecture"]');
+ expect(surface).not.toBeNull();
+ for (const view of ['dependencies', 'routes', 'entryPoints']) {
+ await click(`[data-view="${view}"]`);
+ expect(container.querySelector('[data-testid="spatial-architecture"]')).toBe(surface);
+ expect(container.querySelector('[aria-label="Architecture relationships"]')).not.toBeNull();
+ }
+ });
+
it('keeps module, layer, community and indexed-file evidence available in Overview', async () => {
await render();
expect(container.textContent).toContain('41');
expect(container.textContent).toContain('Registered route handlers');
expect(container.textContent).toContain('persist');
expect(container.textContent).toContain('src/storage.ts');
- expect(container.querySelector('details')?.open).toBe(false);
+ const statistics = [...container.querySelectorAll('details')].find(details => details.querySelector('summary')?.textContent === text.summaryDetails);
+ expect(statistics?.open).toBe(false);
});
it('opens a source location at the exact provider line and leaves unknown locations unlinked', async () => {
diff --git a/graph-ui/src/architecture/ArchitecturePanel.tsx b/graph-ui/src/architecture/ArchitecturePanel.tsx
index 9bddcdb83..d52f82593 100644
--- a/graph-ui/src/architecture/ArchitecturePanel.tsx
+++ b/graph-ui/src/architecture/ArchitecturePanel.tsx
@@ -11,10 +11,12 @@ import './architecture.css';
import RepositoryMapView, { RelationshipEvidence } from './RepositoryMap';
import type { RepositoryMapProps } from './RepositoryMap';
import { repositoryMap } from './repository-map';
+import SpatialArchitecture from './SpatialArchitecture';
export interface ArchitecturePanelProps extends Pick<RepositoryMapProps, 'graph' | 'selection' | 'selectionPanel' | 'onSelect' | 'graphNote' | 'readSource'> {
projectName: string;
graphGeneration?: string;
+ active?: boolean;
overview?: ArchitectureOverviewDto;
loading?: boolean;
error?: string;
@@ -236,7 +238,7 @@ function Findings({ view, data, empty, onNavigate }: {
</section>;
}
-function ArchitectureWorkspace({ projectName, overview, loading = false, error, onRefresh, onProjectWalk, onNavigate, graph, selection, selectionPanel, onSelect, graphNote, graphGeneration, readSource }: ArchitecturePanelProps): JSX.Element {
+function ArchitectureWorkspace({ projectName, overview, loading = false, error, onRefresh, onProjectWalk, onNavigate, graph, selection, selectionPanel, onSelect, graphNote, graphGeneration, readSource, active = true }: ArchitecturePanelProps): JSX.Element {
const storage = useMemo(browserStorage, []);
const [config, setConfig] = useState(() => readArchitectureConfig(storage, projectName));
const [saved, setSaved] = useState(true);
@@ -267,11 +269,16 @@ function ArchitectureWorkspace({ projectName, overview, loading = false, error,
: error ? <div role="alert" className="atlas-arch-empty" data-error="true"><p>{text.loadFailed}</p><p className="atlas-arch-error-detail">{error}</p>
{onRefresh && <button className="atlas-arch-action" onClick={onRefresh}>{text.retry}</button>}</div>
: !data ? <Empty>{text.unavailable}</Empty> : null}
+ {ready && data && graph && <div hidden={config.view === 'hotspots'}><SpatialArchitecture project={projectName} generation={graphGeneration} graph={graph} overview={data}
+ view={config.view === 'hotspots' ? 'overview' : config.view} filter={config.filter} active={active && config.view !== 'hotspots'}
+ graphNote={graphNote} onSelect={onSelect} selectionPanel={selectionPanel} onNavigate={onNavigate} onView={view => setConfig(current => ({ ...current, view }))} /></div>}
{ready && data && filtered && <div className="atlas-arch-content" key={`${config.view}:${config.filter}:${graphGeneration ?? ""}`} data-testid="atlas-architecture-content">
+ <details open={!graph || config.view === 'hotspots'}><summary>Source guide and complete findings</summary>
{config.view === 'overview' ? <><RepositoryMapView graph={graph} graphNote={graphNote} overview={data} filter={config.filter} onNavigate={onNavigate} onSelect={onSelect} selection={selection} selectionPanel={selectionPanel} readSource={readSource} />
<details><summary>{text.summaryDetails}</summary><Overview data={data} filtered={filtered} filter={config.filter} onGroup={onGroup} onNavigate={onNavigate} /></details></>
: config.view === 'dependencies' ? <Dependencies data={filtered} empty={empty} onGroup={onGroup} graph={graph} onNavigate={onNavigate} />
: <Findings view={config.view} data={filtered} empty={empty} onNavigate={onNavigate} />}
+ </details>
</div>}
{ready && <details className="atlas-arch-evidence"><summary>{text.evidenceSummary}</summary><p>{text.evidenceDetail}</p></details>}
</section>;
diff --git a/graph-ui/src/architecture/ArchitectureScene.tsx b/graph-ui/src/architecture/ArchitectureScene.tsx
new file mode 100644
index 000000000..b54dc2eb3
--- /dev/null
+++ b/graph-ui/src/architecture/ArchitectureScene.tsx
@@ -0,0 +1,235 @@
+import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
+import { Canvas, useThree } from '@react-three/fiber';
+import { Edges, Html, OrbitControls, OrthographicCamera } from '@react-three/drei';
+import { Box3, CubicBezierCurve3, MOUSE, TOUCH, OrthographicCamera as ThreeOrthographicCamera, Quaternion, QuadraticBezierCurve3, Vector3 } from 'three';
+import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib';
+import type { SemanticEdge, SemanticGraph, SemanticNode } from './semantic-graph';
+import './architecture-scene.css';
+
+export interface ArchitectureSceneProps {
+ model: SemanticGraph;
+ selectedId?: string;
+ selectedEdgeId?: string;
+ onSelect: (id: string) => void;
+ onSelectEdge: (id: string) => void;
+ active?: boolean;
+ planar?: boolean;
+ resetKey?: number;
+}
+
+const PALETTE = { area: '#69e5bc', file: '#8ccff1', symbol: '#c2afff', route: '#ffc98b' } as const;
+const EDGE_COLORS: Record<string, string> = {
+ CALLS: '#a699ed', IMPORTS: '#65bfdb', HTTP_CALLS: '#f4bd7b', ASYNC_CALLS: '#f4bd7b',
+ HANDLES: '#70dbb3', DATA_FLOWS: '#e297bd', INHERITS: '#8ca8ff', IMPLEMENTS: '#8ca8ff',
+};
+
+function dimensions(node: SemanticNode): [number, number, number] {
+ if (node.kind === 'area') return [12, 0.9, 8];
+ if (node.kind === 'file') return [5.5, 2.5, 4];
+ if (node.kind === 'route') return [4.5, 2.5, 4.5];
+ return [3.2, 3.2, 3.2];
+}
+
+function centerOf(node: SemanticNode): Vector3 {
+ return new Vector3(...node.position).add(new Vector3(0, dimensions(node)[1] / 2, 0));
+}
+
+/** Direction is geometric only; the model supplies every relationship and its evidence. */
+function Relationship({ edge, source, target, selected, emphasized, dimmed, showLabel, laneOffset, onSelect, onHover }: {
+ edge: SemanticEdge; source: SemanticNode; target: SemanticNode;
+ selected: boolean; emphasized: boolean; dimmed: boolean; showLabel: boolean;
+ laneOffset: number;
+ onSelect: () => void; onHover: (id?: string) => void;
+}) {
+ const { curve, arrowPosition, arrowRotation, labelPosition } = useMemo(() => {
+ const start = centerOf(source);
+ const end = centerOf(target);
+ const delta = end.clone().sub(start);
+ const distance = delta.length();
+ // A small sideways bow separates reciprocal edges. Height is routing clearance,
+ // never a measurement or an extra dependency.
+ const perpendicular = new Vector3(-delta.z, 0, delta.x).normalize();
+ const midpoint = start.clone().lerp(end, 0.5)
+ .add(new Vector3(0, Math.min(10, 3 + distance * 0.1), 0))
+ .addScaledVector(perpendicular, Math.min(4, distance * 0.09) + laneOffset);
+ const curve = edge.source === edge.target
+ ? new CubicBezierCurve3(start.clone().add(new Vector3(1, 1, 0)), start.clone().add(new Vector3(10 + laneOffset, 10, 7)), start.clone().add(new Vector3(-10 - laneOffset, 10, 7)), end.clone().add(new Vector3(-1, 1, 0)))
+ : new QuadraticBezierCurve3(start, midpoint, end);
+ const arrowAt = 0.79;
+ return {
+ curve,
+ arrowPosition: curve.getPoint(arrowAt),
+ arrowRotation: new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), curve.getTangent(arrowAt).normalize()),
+ labelPosition: curve.getPoint(0.5),
+ };
+ }, [source, target, edge.source, edge.target, laneOffset]);
+ const color = EDGE_COLORS[edge.type] ?? '#85a9b4';
+ const opacity = dimmed ? 0.06 : selected ? 1 : emphasized ? 0.95 : 0.55;
+ return <group>
+ <mesh onClick={event => { event.stopPropagation(); onSelect(); }}
+ onPointerOver={event => { event.stopPropagation(); onHover(edge.id); }}
+ onPointerOut={() => onHover()}>
+ <tubeGeometry args={[curve, 24, 0.34, 4, false]} />
+ <meshBasicMaterial transparent opacity={0} depthWrite={false} />
+ </mesh>
+ <mesh raycast={() => null}>
+ <tubeGeometry args={[curve, 24, selected ? 0.11 : emphasized ? 0.085 : 0.055, 4, false]} />
+ <meshBasicMaterial color={color} transparent opacity={opacity} depthWrite={false} />
+ </mesh>
+ <mesh position={arrowPosition} quaternion={arrowRotation}
+ onClick={event => { event.stopPropagation(); onSelect(); }}>
+ <coneGeometry args={[selected || emphasized ? 0.42 : 0.28, 1.1, 6]} />
+ <meshBasicMaterial color={color} transparent opacity={Math.min(1, opacity + 0.18)} />
+ </mesh>
+ {showLabel && !dimmed && <Html position={labelPosition} center zIndexRange={[30, 20]}>
+ <button type="button" className="architecture-edge-label" onClick={onSelect}
+ style={{ borderColor: color }} aria-label={`Inspect ${edge.type} relationship, ${edge.count} indexed edges`}>
+ {edge.type.replaceAll('_', ' ').toLowerCase()}{edge.count > 1 && <span> ×{edge.count}</span>}
+ </button>
+ </Html>}
+ </group>;
+}
+
+function ArchitectureNode({ node, selected, highlighted, dimmed, onSelect, onHover }: {
+ node: SemanticNode; selected: boolean; highlighted: boolean; dimmed: boolean;
+ onSelect: () => void; onHover: (id?: string) => void;
+}) {
+ const color = PALETTE[node.kind];
+ const size = dimensions(node);
+ const labelY = size[1] + 7;
+ return <group position={node.position}>
+ <mesh position={[0, size[1] / 2, 0]}
+ onClick={event => { event.stopPropagation(); onSelect(); }}
+ onPointerOver={event => { event.stopPropagation(); onHover(node.id); }}
+ onPointerOut={() => onHover()}>
+ {node.kind === 'symbol' ? <icosahedronGeometry args={[1.6, 1]} />
+ : node.kind === 'route' ? <cylinderGeometry args={[2.2, 2.2, size[1], 6]} />
+ : <boxGeometry args={size} />}
+ <meshStandardMaterial color={selected ? color : '#17232c'} roughness={0.7} metalness={0.22}
+ emissive={color} emissiveIntensity={selected ? 0.3 : highlighted ? 0.13 : 0.035}
+ transparent opacity={dimmed ? 0.28 : 0.95} />
+ <Edges color={color} transparent opacity={dimmed ? 0.12 : selected ? 1 : highlighted ? 0.85 : 0.48} />
+ </mesh>
+ {selected && <mesh position={[0, 0.05, 0]} rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>
+ <ringGeometry args={[Math.max(size[0], size[2]) * 0.65, Math.max(size[0], size[2]) * 0.65 + 0.12, 64]} />
+ <meshBasicMaterial color={color} transparent opacity={0.6} depthWrite={false} />
+ </mesh>}
+ <Html position={[0, labelY, 0]} center zIndexRange={selected ? [60, 50] : [20, 10]}>
+ <button type="button" className={`architecture-node-label${selected ? ' is-selected' : ''}${dimmed ? ' is-dimmed' : ''}`}
+ data-kind={node.kind} aria-pressed={selected} onClick={onSelect}
+ onPointerEnter={() => onHover(node.id)} onPointerLeave={() => onHover()}
+ title={`${node.label}\n${node.detail}`}>
+ {selected && <span className="architecture-node-kind"><i style={{ background: color }} />{node.kind === 'area' ? 'Source area' : node.kind}</span>}
+ <strong>{node.label}</strong>
+ {selected && <span className="architecture-node-detail">{node.detail}</span>}
+ </button>
+ </Html>
+ </group>;
+}
+
+function FitArchitecture({ model, planar, resetKey, controls, active }: {
+ model: SemanticGraph; planar: boolean; resetKey: number;
+ controls: RefObject<OrbitControlsImpl | null>; active: boolean;
+}) {
+ const { camera, size, invalidate } = useThree();
+ const layoutKey = model.nodes.map(node => `${node.id}:${node.position.join(',')}`).join('|');
+ const nodesRef = useRef(model.nodes);
+ nodesRef.current = model.nodes;
+ useEffect(() => {
+ if (!(camera instanceof ThreeOrthographicCamera) || size.width < 1 || size.height < 1) return;
+ const bounds = new Box3();
+ for (const node of nodesRef.current) {
+ const center = centerOf(node);
+ const half = new Vector3(...dimensions(node)).multiplyScalar(0.5).addScalar(2);
+ bounds.expandByPoint(center.clone().sub(half));
+ bounds.expandByPoint(center.clone().add(half));
+ }
+ if (bounds.isEmpty()) bounds.set(new Vector3(-12, -2, -12), new Vector3(12, 5, 12));
+ const target = bounds.getCenter(new Vector3());
+ const reach = Math.max(30, bounds.getSize(new Vector3()).length());
+ camera.up.set(0, planar ? 0 : 1, planar ? -1 : 0);
+ camera.position.copy(target).addScaledVector(new Vector3(...(planar ? [0, 1, 0] : [0.8, 1.15, 1.05]) as [number, number, number]).normalize(), reach * 2);
+ camera.near = 0.1;
+ camera.far = Math.max(1000, reach * 6);
+ camera.lookAt(target);
+ camera.updateMatrixWorld();
+ const projected = new Box3();
+ for (const x of [bounds.min.x, bounds.max.x]) for (const y of [bounds.min.y, bounds.max.y]) for (const z of [bounds.min.z, bounds.max.z]) {
+ projected.expandByPoint(new Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse));
+ }
+ const span = projected.getSize(new Vector3());
+ // Keep readable labels inside the canvas, including its narrow inspector layout.
+ camera.zoom = Math.max(0.4, Math.min(Math.max(80, size.width - 160) / Math.max(1, span.x), Math.max(80, size.height - 150) / Math.max(1, span.y)));
+ camera.updateProjectionMatrix();
+ if (controls.current) {
+ controls.current.target.copy(target);
+ controls.current.update();
+ }
+ invalidate();
+ }, [camera, controls, invalidate, layoutKey, model.scopeKey, planar, resetKey, size.width, size.height]);
+ useEffect(() => { if (active) invalidate(); }, [active, invalidate]);
+ return null;
+}
+
+export function ArchitectureScene({ model, selectedId, selectedEdgeId, onSelect, onSelectEdge, active = true, planar = false, resetKey = 0 }: ArchitectureSceneProps) {
+ const [hoveredId, setHoveredId] = useState<string>();
+ const [hoveredEdgeId, setHoveredEdgeId] = useState<string>();
+ const controls = useRef<OrbitControlsImpl | null>(null);
+ const nodesById = useMemo(() => new Map(model.nodes.map(node => [node.id, node])), [model.nodes]);
+ const edgeOffsets = useMemo(() => {
+ const lanes = new Map<string, number>(); const offsets = new Map<string, number>();
+ for (const edge of [...model.edges].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) {
+ const pair = `${edge.source}→${edge.target}`; const lane = lanes.get(pair) ?? 0;
+ offsets.set(edge.id, lane * 2.5); lanes.set(pair, lane + 1);
+ }
+ return offsets;
+ }, [model.edges]);
+ const candidateId = hoveredId ?? selectedId;
+ const focusId = candidateId && nodesById.has(candidateId) ? candidateId : undefined;
+ const candidateEdgeId = hoveredEdgeId ?? selectedEdgeId;
+ const focusEdgeId = model.edges.some(edge => edge.id === candidateEdgeId) ? candidateEdgeId : undefined;
+ const related = useMemo(() => {
+ const ids = new Set<string>();
+ if (focusId) ids.add(focusId);
+ for (const edge of model.edges) {
+ if (edge.source === focusId || edge.target === focusId || edge.id === focusEdgeId) {
+ ids.add(edge.source); ids.add(edge.target);
+ }
+ }
+ return ids;
+ }, [model.edges, focusId, focusEdgeId]);
+ const floorY = Math.min(0, ...model.nodes.map(node => node.position[1])) - 0.14;
+ const extent = Math.max(120, ...model.nodes.map(node => Math.max(Math.abs(node.position[0]), Math.abs(node.position[2])) * 2 + 40));
+ return <div className="architecture-scene" data-testid="architecture-scene" data-projection={planar ? 'plan' : '3d'}
+ style={{ cursor: hoveredId || hoveredEdgeId ? 'pointer' : 'grab' }}>
+ <Canvas frameloop={active ? 'demand' : 'never'} dpr={[1, 1.5]}
+ gl={{ antialias: true, alpha: false, powerPreference: 'low-power' }}
+ role="img" aria-label={`${model.title}. ${model.positionMeaning}. Use the adjacent list to select nodes and inspect relationships.`}>
+ <color attach="background" args={['#0b1118']} />
+ <OrthographicCamera makeDefault position={[80, 100, 100]} near={0.1} far={2000} zoom={5} />
+ <ambientLight intensity={1.6} />
+ <directionalLight position={[30, 80, 20]} intensity={2.4} color="#dcfff3" />
+ <directionalLight position={[-20, 20, -30]} intensity={1.2} color="#a899ff" />
+ <gridHelper args={[extent, Math.min(80, Math.ceil(extent / 12)), '#1c3440', '#15242e']} position={[0, floorY, 0]} />
+ {model.edges.map(edge => {
+ const source = nodesById.get(edge.source);
+ const target = nodesById.get(edge.target);
+ if (!source || !target) return null;
+ const emphasized = edge.id === focusEdgeId || edge.source === focusId || edge.target === focusId;
+ return <Relationship key={edge.id} edge={edge} source={source} target={target}
+ laneOffset={edgeOffsets.get(edge.id) ?? 0}
+ selected={edge.id === selectedEdgeId} emphasized={emphasized} showLabel={edge.id === focusEdgeId}
+ dimmed={related.size > 0 && !emphasized} onSelect={() => onSelectEdge(edge.id)} onHover={setHoveredEdgeId} />;
+ })}
+ {model.nodes.map(node => <ArchitectureNode key={node.id} node={node}
+ selected={node.id === selectedId} highlighted={related.has(node.id)} dimmed={related.size > 0 && !related.has(node.id)}
+ onSelect={() => onSelect(node.id)} onHover={setHoveredId} />)}
+ <OrbitControls ref={controls} makeDefault enabled={active} enableRotate={!planar} enableDamping={false}
+ mouseButtons={{ LEFT: planar ? MOUSE.PAN : MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }}
+ touches={{ ONE: planar ? TOUCH.PAN : TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }}
+ minZoom={0.15} maxZoom={60} rotateSpeed={0.5} zoomSpeed={0.8} maxPolarAngle={Math.PI / 2.05} />
+ <FitArchitecture model={model} planar={planar} resetKey={resetKey} controls={controls} active={active} />
+ </Canvas>
+ <div className="architecture-scene-guide" aria-hidden="true"><span>{planar ? 'PLAN' : '3D MAP'}</span>{planar ? 'Drag to pan · Scroll to zoom' : 'Drag to orbit · Right-drag to pan · Scroll to zoom'}</div>
+ </div>;
+}
diff --git a/graph-ui/src/architecture/SpatialArchitecture.test.tsx b/graph-ui/src/architecture/SpatialArchitecture.test.tsx
new file mode 100644
index 000000000..045105207
--- /dev/null
+++ b/graph-ui/src/architecture/SpatialArchitecture.test.tsx
@@ -0,0 +1,73 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import SpatialArchitecture from './SpatialArchitecture';
+import { loadRouteGraph } from './route-graph-source';
+import type { ArchitectureSceneProps } from './ArchitectureScene';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
+
+vi.mock('./ArchitectureScene', () => ({ ArchitectureScene: (props: ArchitectureSceneProps) => <div data-testid="scene" data-active={String(props.active)}>{props.model.nodes.map(node => <button key={node.id} data-node={node.id} onClick={() => props.onSelect(node.id)}>{node.label}</button>)}</div> }));
+vi.mock('./route-graph-source', () => ({ loadRouteGraph: vi.fn(async () => ({ relationships: [], truncated: false, warnings: [] })) }));
+
+const node: GraphNode = { id: 1, label: 'Function', name: 'start', qualified_name: 'sample.start', file_path: 'src/api/main.ts', start_line: 12, end_line: 30, status: 'entry', x: 0, y: 0, z: 0, size: 1, color: '' };
+const graph: GraphData = { nodes: [node], edges: [], total_nodes: 1 };
+const overview: ArchitectureOverviewDto = { projectName: 'sample', totalSymbols: 1, totalRelations: 0, symbolKinds: [], relationKinds: [], languages: [], groups: [], boundaries: [], layers: [], clusters: [], entryPoints: [], routes: [], hotspots: [], files: [] };
+let host: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host);
+ vi.clearAllMocks();
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); });
+async function click(text: string) {
+ const button = [...host.querySelectorAll('button')].find(button => button.textContent === text);
+ expect(button).toBeDefined(); await act(async () => button!.click());
+}
+it('drills inferred areas to files and symbols before enabling real-node impact actions', async () => {
+ const onSelect = vi.fn(); const onNavigate = vi.fn();
+ await act(async () => root.render(<SpatialArchitecture project="sample" graph={graph} overview={overview} view="overview" filter="" active onSelect={onSelect} onNavigate={onNavigate} onView={vi.fn()} selectionPanel={<button>Analyze selected symbol</button>} />));
+ await click('src/api');
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(host.textContent).not.toContain('Analyze selected symbol');
+ await click('Open area →'); await click('src/api/main.ts'); await click('Open file symbols →'); await click('start');
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(node);
+ expect(host.textContent).toContain('Analyze selected symbol');
+ await click('Open source'); expect(onNavigate).toHaveBeenCalledWith('src/api/main.ts', 12, 'start');
+});
+it('passes hidden-workspace suspension to the scene and preserves the scene across view switches', async () => {
+ const props = { project: 'sample', graph, overview, filter: '', onNavigate: vi.fn(), onView: vi.fn() };
+ await act(async () => root.render(<SpatialArchitecture {...props} view="overview" active />));
+ const scene = host.querySelector('[data-testid="scene"]');
+ await act(async () => root.render(<SpatialArchitecture {...props} view="entryPoints" active={false} />));
+ expect(host.querySelector('[data-testid="scene"]')).toBe(scene);
+ expect(scene?.getAttribute('data-active')).toBe('false');
+});
+it('cancels a route request on generation change and ignores its late result', async () => {
+ let finishOld!: (value: Awaited<ReturnType<typeof loadRouteGraph>>) => void;
+ vi.mocked(loadRouteGraph).mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve; }));
+ const props = { project: 'sample', graph, overview, filter: '', onNavigate: vi.fn(), onView: vi.fn() };
+ await act(async () => root.render(<SpatialArchitecture {...props} view="routes" active generation="old" />));
+ const oldSignal = vi.mocked(loadRouteGraph).mock.calls[0][1]?.signal;
+ await act(async () => root.render(<SpatialArchitecture {...props} view="routes" active generation="new" />));
+ expect(oldSignal?.aborted).toBe(true);
+ await act(async () => finishOld({ relationships: [], truncated: true, warnings: ['STALE RESPONSE'] }));
+ expect(host.textContent).not.toContain('STALE RESPONSE');
+ expect(loadRouteGraph).toHaveBeenCalledTimes(2);
+});
+it('does not load route evidence while the workspace is hidden', async () => {
+ await act(async () => root.render(<SpatialArchitecture project="sample" graph={graph} overview={overview} view="routes" filter="" active={false} onNavigate={vi.fn()} onView={vi.fn()} />));
+ expect(loadRouteGraph).not.toHaveBeenCalled();
+});
+it('keeps the chosen entry identity across reindexing when numeric IDs are reused', async () => {
+ const second = { ...node, id: 2, name: 'other', qualified_name: 'sample.other' };
+ const props = { project: 'sample', overview, filter: '', onNavigate: vi.fn(), onView: vi.fn() };
+ await act(async () => root.render(<SpatialArchitecture {...props} graph={{ nodes: [node, second], edges: [], total_nodes: 2 }} generation="old" view="entryPoints" active />));
+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Entry point"]')!;
+ await act(async () => { select.value = '2'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ await act(async () => root.render(<SpatialArchitecture {...props} graph={{ nodes: [{ ...node, id: 2 }, { ...second, id: 101 }], edges: [], total_nodes: 2 }} generation="new" view="entryPoints" active />));
+ expect(select.value).toBe('101');
+ expect(host.querySelector('[data-testid="scene"]')?.textContent).toBe('other');
+});
diff --git a/graph-ui/src/architecture/SpatialArchitecture.tsx b/graph-ui/src/architecture/SpatialArchitecture.tsx
new file mode 100644
index 000000000..fe266746c
--- /dev/null
+++ b/graph-ui/src/architecture/SpatialArchitecture.tsx
@@ -0,0 +1,144 @@
+import { Component, useEffect, useMemo, useState, type ReactNode } from 'react';
+import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import { ArchitectureScene } from './ArchitectureScene';
+import { buildSemanticGraph, semanticEntryPoints, type SemanticNode, type SemanticView } from './semantic-graph';
+import { loadRouteGraph, type RouteGraphSnapshot } from './route-graph-source';
+import './spatial-architecture.css';
+
+interface Props {
+ project: string; generation?: string; graph: GraphData; overview: ArchitectureOverviewDto;
+ view: SemanticView; filter: string; active: boolean; graphNote?: string;
+ onSelect?: (node: GraphNode) => void; selectionPanel?: ReactNode;
+ onView: (view: SemanticView) => void;
+ onNavigate: (path: string, line?: number, name?: string) => void;
+}
+
+class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() { return { failed: true }; }
+ render() {
+ return this.state.failed ? <div className="spatial-unavailable" role="status">3D rendering is unavailable. Explore the same nodes and relationships in the lists beside the map.</div> : this.props.children;
+ }
+}
+
+const viewNotes: Record<SemanticView, string> = {
+ overview: 'Find the main parts. Select an area to inspect its connections, then open its files.',
+ dependencies: 'Follow directed dependencies. Select a connection to see the indexed source behind it.',
+ entryPoints: 'Choose a starting point and follow its static call graph. Depth measures call distance, not execution order.',
+ routes: 'Explore HTTP and asynchronous connections to indexed endpoints. Registrations without a resolved connection remain visible.',
+};
+const relationKinds = ['CALLS', 'IMPORTS', 'USAGE', 'INHERITS', 'IMPLEMENTS', 'DATA_FLOWS'];
+
+export default function SpatialArchitecture({ project, generation, graph, overview, view, filter, active, graphNote, onSelect, selectionPanel, onNavigate, onView }: Props) {
+ const [areaPath, setAreaPath] = useState<string>();
+ const [filePath, setFilePath] = useState<string>();
+ const [entryChoice, setEntryChoice] = useState<{ node: GraphNode; generation?: string }>();
+ const [depth, setDepth] = useState(2);
+ const [relations, setRelations] = useState<string[]>([]);
+ const [planar, setPlanar] = useState(false);
+ const [resetKey, setResetKey] = useState(0);
+ const [selection, setSelection] = useState<{ scope: string; node?: string; edge?: string }>();
+ const [routeReading, setRouteReading] = useState<{ key: string; snapshot?: RouteGraphSnapshot; error?: string }>();
+ const [routeRevision, setRouteRevision] = useState(0);
+ const [memberLimit, setMemberLimit] = useState(16);
+ const routeKey = `${project}:${generation ?? ''}:${routeRevision}`;
+ useEffect(() => {
+ if (view !== 'routes' || !active) return;
+ const controller = new AbortController();
+ setRouteReading({ key: routeKey });
+ void loadRouteGraph(project, { signal: controller.signal }).then(snapshot => {
+ if (!controller.signal.aborted) setRouteReading({ key: routeKey, snapshot });
+ }).catch((error: unknown) => {
+ if (!controller.signal.aborted) setRouteReading({ key: routeKey, error: error instanceof Error ? error.message : String(error) });
+ });
+ return () => controller.abort();
+ }, [project, routeKey, view, active]);
+ const entries = useMemo(() => semanticEntryPoints(graph, overview.entryPoints.flatMap(entry => entry.qualifiedName ? [entry.qualifiedName] : [])), [graph, overview.entryPoints]);
+ const currentEntry = entries.find(node => entryChoice?.node.qualified_name
+ ? node.qualified_name === entryChoice.node.qualified_name && node.file_path === entryChoice.node.file_path
+ : entryChoice?.generation === generation && node.id === entryChoice?.node.id && node.file_path === entryChoice.node.file_path) ?? entries[0];
+ const routeSnapshot = routeReading?.key === routeKey ? routeReading.snapshot : undefined;
+ const model = useMemo(() => buildSemanticGraph(graph, {
+ view, areaPath, filePath, entryId: currentEntry?.id, entryQualifiedNames: overview.entryPoints.flatMap(entry => entry.qualifiedName ? [entry.qualifiedName] : []), depth, filter, relations,
+ routes: overview.routes, routeSnapshot,
+ }), [graph, view, areaPath, filePath, currentEntry?.id, depth, filter, relations, overview.routes, overview.entryPoints, routeSnapshot]);
+ const scope = `${project}:${generation ?? ''}:${model.scopeKey}:${view}:${filter}`;
+ const selectedNode = selection?.scope === scope ? model.nodes.find(node => node.id === selection.node) : undefined;
+ const selectedEdge = selection?.scope === scope ? model.edges.find(edge => edge.id === selection.edge) : undefined;
+ const nodesById = useMemo(() => new Map(model.nodes.map(node => [node.id, node])), [model.nodes]);
+ const edges = selectedNode ? model.edges.filter(edge => edge.source === selectedNode.id || edge.target === selectedNode.id) : model.edges;
+ const selectNode = (id: string) => {
+ setSelection({ scope, node: id }); setMemberLimit(16);
+ const node = nodesById.get(id);
+ if (node?.graphNode) onSelect?.(node.graphNode);
+ };
+ const openGroup = (node: SemanticNode) => {
+ if (node.kind === 'area') { setAreaPath(node.areaPath); setFilePath(undefined); }
+ else if (node.kind === 'file') setFilePath(node.filePath);
+ if (view === 'routes') onView('dependencies');
+ setSelection(undefined);
+ };
+ const clearScope = () => { setAreaPath(undefined); setFilePath(undefined); setSelection(undefined); };
+ const openSource = (node: GraphNode) => node.file_path && onNavigate(node.file_path, node.start_line, node.name);
+ const inspectMember = (node: GraphNode) => {
+ const current = graph.nodes.find(candidate => candidate.qualified_name && candidate.qualified_name === node.qualified_name && candidate.file_path === node.file_path);
+ if (current) onSelect?.(current);
+ openSource(node);
+ };
+ return <section className="spatial-architecture" data-testid="spatial-architecture" aria-label="Spatial architecture explorer">
+ <div className="spatial-heading"><div><span className="spatial-eyebrow">Repository atlas / {view === 'entryPoints' ? 'entry points' : view}</span><h2>{model.title}</h2><p>{viewNotes[view]}</p></div>
+ <div className="spatial-camera-controls" role="group" aria-label="Map camera">
+ <button aria-pressed={!planar} onClick={() => setPlanar(false)}>3D</button><button aria-pressed={planar} onClick={() => setPlanar(true)}>Plan</button>
+ <button onClick={() => setResetKey(value => value + 1)}>Fit map</button>
+ </div>
+ </div>
+ <div className="spatial-controls">
+ {(view === 'overview' || view === 'dependencies') && <nav aria-label="Architecture location"><button onClick={clearScope}>{project}</button>
+ {areaPath && <><span>/</span><button onClick={() => { setFilePath(undefined); setSelection(undefined); }}>{areaPath}</button></>}{filePath && <><span>/</span><span>{filePath.split('/').at(-1)}</span></>}
+ </nav>}
+ {view === 'entryPoints' && <><label>Start <select aria-label="Entry point" value={currentEntry?.id ?? ''} onChange={event => { const node = entries.find(node => node.id === Number(event.target.value)); setEntryChoice(node ? { node, generation } : undefined); setSelection(undefined); }}>
+ {!entries.length && <option value="">No indexed entry points</option>}{entries.map(node => <option key={node.id} value={node.id}>{node.name} · {node.file_path}</option>)}
+ </select></label><label>Call depth <select aria-label="Call depth" value={depth} onChange={event => setDepth(Number(event.target.value))}>{[1, 2, 3, 4].map(value => <option key={value}>{value}</option>)}</select></label></>}
+ {view === 'routes' && <button onClick={() => setRouteRevision(value => value + 1)}>Refresh connections</button>}
+ {filePath && (view === 'overview' || view === 'dependencies') && <button onClick={() => onNavigate(filePath, 1)}>Read this file</button>}
+ {(view === 'overview' || view === 'dependencies') && <div className="spatial-relations" role="group" aria-label="Relationship types">
+ <button aria-pressed={!relations.length} onClick={() => setRelations([])}>All</button>{relationKinds.map(type => <button key={type} aria-pressed={relations.includes(type)} onClick={() => setRelations(current => current.includes(type) ? current.filter(item => item !== type) : [...current, type])}>{type.replaceAll('_', ' ').toLowerCase()}</button>)}
+ </div>}
+ </div>
+ <div className="spatial-map-layout">
+ <div className="spatial-map"><SceneBoundary key={project}>
+ {model.nodes.length ? <ArchitectureScene model={model} selectedId={selectedNode?.id} selectedEdgeId={selectedEdge?.id} onSelect={selectNode}
+ onSelectEdge={id => setSelection({ scope, edge: id })} active={active} planar={planar} resetKey={resetKey} />
+ : <div className="spatial-unavailable">{filter ? 'No matching graph evidence. Try a broader filter.' : view === 'entryPoints' ? 'No indexed entry points in this snapshot.' : view === 'routes' ? 'No endpoint evidence is available in this snapshot.' : filePath ? 'No indexed symbols in this file. Use “Read this file” to inspect its source.' : 'No source nodes are available in this repository snapshot.'}</div>}
+ </SceneBoundary><div className="spatial-map-caption"><span>{model.positionMeaning}</span><span>Drag to orbit · scroll to zoom · select to inspect</span></div></div>
+ <aside className="spatial-inspector" aria-label="Architecture inspector">
+ {selectedEdge ? <><span className="spatial-eyebrow">Indexed connection</span><h3>{nodesById.get(selectedEdge.source)?.label} <span>→</span> {nodesById.get(selectedEdge.target)?.label}</h3>
+ <p>{selectedEdge.type} · {selectedEdge.count} retained relationships</p>
+ <div className="spatial-evidence">{selectedEdge.evidence.slice(0, memberLimit).map((evidence, index) => <article key={`${evidence.id}:${index}`}>
+ <button disabled={!evidence.source.file_path} onClick={() => openSource(evidence.source)}>{evidence.source.name}</button><span>→ {evidence.type}</span>
+ <button disabled={!evidence.target.file_path} onClick={() => openSource(evidence.target)}>{evidence.target.name}</button>
+ {evidence.routePath && <code>{evidence.routePath}</code>}<small>{evidence.source.file_path}{evidence.source.start_line ? `:${evidence.source.start_line}` : ''}</small>
+ <small>{evidence.id === undefined ? 'Index relationship' : `Edge #${evidence.id}`}{evidence.strategy ? ` · ${evidence.strategy}` : ''}{evidence.via ? ` · ${evidence.via}` : ''}</small>
+ </article>)}</div>{selectedEdge.evidence.length > memberLimit && <button onClick={() => setMemberLimit(value => value + 16)}>More source evidence</button>}
+ </> : selectedNode ? <><span className="spatial-eyebrow">{selectedNode.kind === 'area' ? 'Inferred source area' : selectedNode.kind}</span><h3>{selectedNode.label}</h3><p>{selectedNode.detail}</p>
+ {(selectedNode.kind === 'area' || selectedNode.kind === 'file') && <button className="spatial-primary" onClick={() => openGroup(selectedNode)}>Open {selectedNode.kind === 'area' ? 'area' : 'file symbols'} →</button>}
+ {selectedNode.filePath && <button onClick={() => onNavigate(selectedNode.filePath!, selectedNode.line, selectedNode.label)}>Open source</button>}
+ {!!selectedNode.members.length && <><h4>Source members · {selectedNode.members.length}</h4><div className="spatial-members">{selectedNode.members.slice(0, memberLimit).map(node => <button key={`${node.qualified_name}:${node.id}`} onClick={() => inspectMember(node)}>{node.name}<small>{node.file_path}{node.start_line ? `:${node.start_line}` : ''}</small></button>)}</div>
+ {selectedNode.members.length > memberLimit && <button onClick={() => setMemberLimit(value => value + 16)}>More members</button>}</>}
+ {selectedNode.graphNode && selectionPanel}
+ </> : <><span className="spatial-eyebrow">Read the map</span><h3>Follow a connection.</h3><p>Select a node to inspect its source members. Select an arrow to see what connects the two parts.</p><p className="spatial-muted">Regions come from source paths. Their proximity does not establish a dependency.</p></>}
+ <details className="spatial-node-list" open={!selectedNode && !selectedEdge}><summary>Map nodes · {model.nodes.length}</summary>{model.nodes.map(node => <button key={node.id} aria-pressed={selectedNode?.id === node.id} onClick={() => selectNode(node.id)}><span>{node.label}</span><small>{node.kind} · {node.count}</small></button>)}</details>
+ </aside>
+ </div>
+ <div className="spatial-bottom"><span>{model.nodes.length} / {model.totalNodes} map nodes · {model.edges.length} / {model.totalEdges} connections displayed</span><span>{graph.nodes.length.toLocaleString()} source nodes · {graph.edges.length.toLocaleString()} source edges loaded</span></div>
+ {!!(model.omittedNodes || model.omittedEdges) && <p className="spatial-notice">The map is bounded for readability. {model.omittedNodes} nodes and {model.omittedEdges} connections are outside this view; filter or open an area to inspect a smaller scope.</p>}
+ {view === 'routes' && !routeSnapshot && <p role="status" className="spatial-notice">{routeReading?.key === routeKey && routeReading.error ? `Connections unavailable: ${routeReading.error}` : 'Reading indexed endpoint connections…'}</p>}
+ {model.warnings.map(warning => <p className="spatial-notice" key={warning}>{warning}</p>)}
+ <details className="spatial-relationship-list"><summary>Connections{selectedNode ? ` for ${selectedNode.label}` : ''} · {edges.length}</summary><div aria-label="Architecture relationships">
+ {!edges.length && <p>No matching indexed connections in this view.</p>}{edges.map(edge => <button key={edge.id} aria-pressed={selectedEdge?.id === edge.id} onClick={() => setSelection({ scope, edge: edge.id })}>
+ <span>{nodesById.get(edge.source)?.label} → {nodesById.get(edge.target)?.label}</span><small>{edge.type} · {edge.count}</small></button>)}
+ </div></details>
+ {graphNote && <details className="spatial-coverage"><summary>Index coverage and limits</summary><p>{graphNote}</p></details>}
+ </section>;
+}
diff --git a/graph-ui/src/architecture/architecture-scene.css b/graph-ui/src/architecture/architecture-scene.css
new file mode 100644
index 000000000..114f692da
--- /dev/null
+++ b/graph-ui/src/architecture/architecture-scene.css
@@ -0,0 +1,66 @@
+.architecture-scene {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 480px;
+ overflow: hidden;
+ isolation: isolate;
+ background: #0b1118;
+ border-radius: 12px;
+}
+
+.architecture-scene canvas { display: block; outline: none; touch-action: none; }
+.architecture-scene button { font-family: inherit; }
+
+.architecture-node-label {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ width: max-content;
+ min-width: 78px;
+ max-width: 178px;
+ padding: 9px 12px;
+ border: 1px solid #334754;
+ border-radius: 8px;
+ background: #0e1925ed;
+ color: #e1ecef;
+ box-shadow: 0 5px 20px #03070c66;
+ text-align: left;
+ white-space: normal;
+ cursor: pointer;
+ transition: border-color 100ms, opacity 100ms;
+}
+
+.architecture-node-label:hover, .architecture-node-label:focus-visible { border-color: #8bccdf; outline: 2px solid #8bccdf55; outline-offset: 2px; }
+.architecture-node-label.is-selected { border-color: #83e4c3; background: #13282e; box-shadow: 0 0 0 1px #83e4c326, 0 5px 22px #03070c99; }
+.architecture-node-label.is-dimmed { opacity: 0.28; }
+.architecture-node-label strong { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.35; letter-spacing: 0; }
+.architecture-node-kind { display: flex; gap: 5px; align-items: center; font-size: 9px; line-height: 1.1; color: #9cadba; text-transform: uppercase; letter-spacing: 0.09em; }
+.architecture-node-kind i { display: inline-block; width: 5px; height: 5px; border-radius: 50%; }
+.architecture-node-detail { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10px; line-height: 1.35; color: #91a8b3; }
+.architecture-node-label[data-kind="route"] { border-color: #735d40; }
+.architecture-node-label[data-kind="symbol"] { border-color: #554d70; }
+
+.architecture-edge-label {
+ padding: 4px 7px;
+ border: 1px solid;
+ border-radius: 5px;
+ background: #0b1525f5;
+ color: #e2ebf3;
+ font-size: 10px;
+ line-height: 1.3;
+ white-space: nowrap;
+ cursor: pointer;
+ box-shadow: 0 2px 10px #0008;
+}
+.architecture-edge-label span { color: #9cafbc; }
+.architecture-edge-label:focus-visible { outline: 2px solid #d9efff; outline-offset: 2px; }
+.architecture-scene-guide { position: absolute; bottom: 14px; left: 16px; display: flex; align-items: center; gap: 10px; padding: 7px 10px; border: 1px solid #233641; border-radius: 7px; background: #0b141dcc; color: #879eaa; font-size: 10px; line-height: 1.2; pointer-events: none; }
+.architecture-scene-guide span { color: #94dbc9; letter-spacing: 0.1em; font-size: 9px; }
+@media (max-width: 800px) {
+ .architecture-scene { min-height: 400px; }
+ .architecture-node-label { max-width: 140px; padding: 7px 9px; }
+ .architecture-node-label strong { font-size: 11px; }
+ .architecture-scene-guide { left: 8px; bottom: 8px; font-size: 9px; gap: 6px; }
+}
+@media (prefers-reduced-motion: reduce) { .architecture-node-label { transition: none; } }
diff --git a/graph-ui/src/architecture/route-graph-source.test.ts b/graph-ui/src/architecture/route-graph-source.test.ts
new file mode 100644
index 000000000..7c24d5611
--- /dev/null
+++ b/graph-ui/src/architecture/route-graph-source.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest';
+import { loadRouteGraph } from './route-graph-source';
+import type { QueryGraphResult } from '../provider/rpc-schemas';
+
+const columns = ['source', 'source_qn', 'source_file', 'source_line', 'source_name', 'target', 'target_qn',
+ 'target_file', 'target_line', 'target_name', 'edge_id', 'edge_type', 'route_path', 'via'];
+const row = (id: number) => [String(id), `fixture.caller${id}`, 'src/client.ts', '10', `caller${id}`,
+ '50', 'fixture.route.users', '', '', '/users', String(100 + id), 'HTTP_CALLS', '/users', 'fetch'];
+const empty: QueryGraphResult = { columns, rows: [], total: 0 };
+const isHttpFunction = (query: string) => query.includes('(s:Function)') && query.includes('HTTP_CALLS');
+
+describe('route relationship query loader', () => {
+ it('queries fixed labeled endpoints and retains source-free route evidence', async () => {
+ const queryGraph = vi.fn(async (_project: string, query: string) => isHttpFunction(query)
+ ? { columns, rows: [row(1)], total: 1 } : empty);
+ const result = await loadRouteGraph('actual-project', { client: { queryGraph } });
+ expect(queryGraph).toHaveBeenCalledTimes(6);
+ expect(queryGraph.mock.calls.every(call => call[0] === 'actual-project'
+ && call[1].includes('id(s) AS source') && call[1].includes('LIMIT 301'))).toBe(true);
+ expect(result.relationships[0]).toMatchObject({ type: 'HTTP_CALLS', routePath: '/users', via: 'fetch',
+ source: { id: 1, qualified_name: 'fixture.caller1', file_path: 'src/client.ts' },
+ target: { id: 50, label: 'Route', file_path: undefined } });
+ expect(result.truncated).toBe(false);
+ });
+ it('follows valid continuations and does not silently claim a repeated cursor is complete', async () => {
+ const queryGraph = vi.fn(async (_project: string, query: string, cursor?: string) => {
+ if (!isHttpFunction(query)) return empty;
+ return cursor ? { columns, rows: [row(2)], total: 3, offset: 1, nextOffset: 2, hasMore: true, nextCursor: 'one' }
+ : { columns, rows: [row(1)], total: 3, offset: 0, nextOffset: 1, hasMore: true, nextCursor: 'one' };
+ });
+ const result = await loadRouteGraph('p', { client: { queryGraph } });
+ expect(result.relationships).toHaveLength(2);
+ expect(result.truncated).toBe(true);
+ expect(result.warnings.join(' ')).toContain('limited');
+ });
+ it('preserves prior pages when a later page changes its snapshot or a family is unavailable', async () => {
+ const queryGraph = vi.fn(async (_project: string, query: string, cursor?: string) => {
+ if (!isHttpFunction(query)) throw new Error('Unsupported relationship');
+ return cursor ? { columns, rows: [row(2)], total: 2, offset: 9 }
+ : { columns, rows: [row(1)], total: 2, offset: 0, nextOffset: 1, nextCursor: 'next', hasMore: true };
+ });
+ const result = await loadRouteGraph('p', { client: { queryGraph } });
+ expect(result.relationships.map(edge => edge.source.id)).toEqual([1]);
+ expect(result.truncated).toBe(true);
+ expect(result.warnings.join(' ')).toContain('changed its snapshot');
+ expect(result.warnings.join(' ')).toContain('Unsupported relationship');
+ });
+ it('reads one sentinel past the per-family cap and reports omitted relationships', async () => {
+ const queryGraph = vi.fn(async (_project: string, query: string) => isHttpFunction(query)
+ ? { columns, rows: Array.from({ length: 301 }, (_, id) => row(id)), total: 301 } : empty);
+ const result = await loadRouteGraph('p', { client: { queryGraph } });
+ expect(result.relationships).toHaveLength(300);
+ expect(result.truncated).toBe(true);
+ expect(result.warnings.join(' ')).toContain('300 rows');
+ });
+ it('refuses malformed IDs and unexpected relationship types without inventing graph identities', async () => {
+ const invalid = row(1); invalid[0] = '';
+ const unknown = row(2); unknown[11] = 'CALLS';
+ const queryGraph = vi.fn(async (_project: string, query: string) => isHttpFunction(query)
+ ? { columns, rows: [invalid, unknown], total: 2 } : empty);
+ const result = await loadRouteGraph('p', { client: { queryGraph } });
+ expect(result.relationships).toEqual([]);
+ expect(result.truncated).toBe(true);
+ });
+ it('propagates cancellation so an old project cannot produce a ready result', async () => {
+ const controller = new AbortController(); controller.abort();
+ const queryGraph = vi.fn(async () => empty);
+ await expect(loadRouteGraph('old-project', { signal: controller.signal, client: { queryGraph } })).rejects.toThrow('Aborted');
+ expect(queryGraph).not.toHaveBeenCalled();
+ });
+});
diff --git a/graph-ui/src/architecture/route-graph-source.ts b/graph-ui/src/architecture/route-graph-source.ts
new file mode 100644
index 000000000..68b052702
--- /dev/null
+++ b/graph-ui/src/architecture/route-graph-source.ts
@@ -0,0 +1,116 @@
+import type { GraphNode } from '../galaxy/types';
+import { RpcIntelligenceClient, rowsToObjects } from '../provider/rpc-client';
+import type { RpcClientOptions } from '../provider/rpc-client';
+import type { QueryGraphResult } from '../provider/rpc-schemas';
+
+export interface RouteRelationship {
+ source: GraphNode;
+ target: GraphNode;
+ type: 'HTTP_CALLS' | 'ASYNC_CALLS' | 'HANDLES';
+ id?: number;
+ routePath?: string;
+ via?: string;
+}
+
+/** Independent query evidence; its numeric IDs must never select repository-map nodes. */
+export interface RouteGraphSnapshot {
+ relationships: RouteRelationship[];
+ truncated: boolean;
+ warnings: string[];
+}
+
+interface RouteQuery { source: string; target: string; relations: string }
+const QUERIES: RouteQuery[] = ['Function', 'Method'].flatMap(label => [
+ { source: label, target: 'Route', relations: 'HTTP_CALLS|ASYNC_CALLS' },
+ { source: 'Route', target: label, relations: 'HANDLES' },
+ { source: label, target: 'Route', relations: 'HANDLES' },
+]);
+const ROW_CAP = 300;
+
+function queryText(query: RouteQuery): string {
+ // Only fixed schema labels enter Cypher; project is a separate RPC argument.
+ return `MATCH (s:${query.source})-[r:${query.relations}]->(t:${query.target}) RETURN `
+ + 'id(s) AS source, s.qualified_name AS source_qn, s.file_path AS source_file, '
+ + 's.start_line AS source_line, s.name AS source_name, id(t) AS target, '
+ + 't.qualified_name AS target_qn, t.file_path AS target_file, t.start_line AS target_line, '
+ + 't.name AS target_name, id(r) AS edge_id, type(r) AS edge_type, '
+ + `r.url_path AS route_path, r.via AS via LIMIT ${ROW_CAP + 1}`;
+}
+
+const clean = (value: string | undefined) => value && value !== '{}' && value !== '-' ? value : undefined;
+function integer(value: string | undefined): number | undefined {
+ if (!value?.trim()) return undefined;
+ const result = Number(value);
+ return Number.isSafeInteger(result) && result >= 0 ? result : undefined;
+}
+function endpoint(row: Record<string, string>, side: 'source' | 'target', label: string): GraphNode | undefined {
+ const id = integer(row[side]);
+ if (id === undefined) return undefined;
+ return { id, label, name: clean(row[`${side}_name`]) ?? clean(row[`${side}_qn`]) ?? label,
+ qualified_name: clean(row[`${side}_qn`]), file_path: clean(row[`${side}_file`]),
+ start_line: integer(row[`${side}_line`]) || undefined, x: 0, y: 0, z: 0, size: 1, color: '' };
+}
+
+export interface RouteGraphOptions extends RpcClientOptions {
+ /** Read-only seam for deterministic pagination and incomplete-result tests. */
+ client?: Pick<RpcIntelligenceClient, 'queryGraph'>;
+}
+
+/** Keep useful pages if one relationship family is unavailable or a continuation fails. */
+export async function loadRouteGraph(project: string, options: RouteGraphOptions = {}): Promise<RouteGraphSnapshot> {
+ const client = options.client ?? new RpcIntelligenceClient(options);
+ const results = await Promise.all(QUERIES.map(async query => {
+ const relationships: RouteRelationship[] = [];
+ const warnings: string[] = [];
+ let truncated = false;
+ let first: QueryGraphResult | undefined;
+ let cursor: string | undefined;
+ let rowCount = 0;
+ const seenCursors = new Set<string>();
+ try {
+ do {
+ if (options.signal?.aborted) throw new DOMException('Aborted', 'AbortError');
+ const page = await client.queryGraph(project, queryText(query), cursor);
+ if (first && (page.offset !== rowCount || page.total !== first.total
+ || JSON.stringify(page.columns) !== JSON.stringify(first.columns) || page.rows.length === 0)) {
+ throw new Error('Query continuation changed its snapshot.');
+ }
+ first ??= page;
+ const rows = rowsToObjects(page.columns, page.rows);
+ for (const row of rows.slice(0, Math.max(0, ROW_CAP - rowCount))) {
+ const source = endpoint(row, 'source', query.source);
+ const target = endpoint(row, 'target', query.target);
+ const type = row.edge_type;
+ if (!source || !target || !['HTTP_CALLS', 'ASYNC_CALLS', 'HANDLES'].includes(type)
+ || !query.relations.split('|').includes(type)) {
+ truncated = true;
+ warnings.push('Some route relationship rows had incomplete identities and were omitted.');
+ continue;
+ }
+ relationships.push({ source, target, type: type as RouteRelationship['type'],
+ id: integer(row.edge_id), routePath: clean(row.route_path), via: clean(row.via) });
+ }
+ rowCount += rows.length;
+ const more = Boolean(page.hasMore || page.truncated || page.nextCursor
+ || page.totalRelation === 'gte' || (page.total !== undefined && page.total > rowCount));
+ if (page.warning) warnings.push(page.warning);
+ if (!more && rowCount <= ROW_CAP) break;
+ if (rowCount >= ROW_CAP || !page.nextCursor || seenCursors.has(page.nextCursor)
+ || seenCursors.size >= 20 || (page.nextOffset !== undefined && page.nextOffset !== rowCount)) {
+ truncated = true;
+ warnings.push(`Route relationship lookup was limited to ${Math.min(rowCount, ROW_CAP)} rows for ${query.source} → ${query.target} (${query.relations}).`);
+ break;
+ }
+ seenCursors.add(page.nextCursor);
+ cursor = page.nextCursor;
+ } while (cursor);
+ } catch (error) {
+ if (options.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) throw error;
+ truncated = true;
+ warnings.push(`Could not finish ${query.source} → ${query.target} (${query.relations}): ${error instanceof Error ? error.message : 'query unavailable'}`);
+ }
+ return { relationships, truncated, warnings };
+ }));
+ return { relationships: results.flatMap(result => result.relationships),
+ truncated: results.some(result => result.truncated), warnings: [...new Set(results.flatMap(result => result.warnings))] };
+}
diff --git a/graph-ui/src/architecture/semantic-graph.test.ts b/graph-ui/src/architecture/semantic-graph.test.ts
new file mode 100644
index 000000000..0c5e20179
--- /dev/null
+++ b/graph-ui/src/architecture/semantic-graph.test.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it } from 'vitest';
+import { buildSemanticGraph, semanticEntryPoints } from './semantic-graph';
+import type { GraphData, GraphNode } from '../galaxy/types';
+
+const node = (id: number, file: string, name = `symbol${id}`, status: GraphNode['status'] = 'normal'): GraphNode => ({
+ id, name, label: 'Function', file_path: file, qualified_name: `fixture.${name}`, status,
+ start_line: 10, end_line: 30, x: 0, y: 0, z: 0, color: '', size: 1,
+});
+const fixture: GraphData = { nodes: [node(1, 'src/api/server.ts', 'start', 'entry'),
+ node(2, 'src/service/users.ts', 'users'), node(3, 'src/store/db.ts', 'save'),
+ node(4, 'src/service/read.ts', 'read')], total_nodes: 4, edges: [
+ { id: 1, source: 1, target: 2, type: 'CALLS', line: 15 },
+ { id: 2, source: 2, target: 3, type: 'CALLS' },
+ { id: 3, source: 2, target: 3, type: 'IMPORTS' },
+ { id: 4, source: 2, target: 4, type: 'CALLS' },
+ { id: 5, source: 3, target: 1, type: 'CALLS' },
+] };
+
+describe('semantic architecture projection', () => {
+ it('preserves direction, relationship type and exact source evidence through aggregation', () => {
+ const model = buildSemanticGraph(fixture, { view: 'dependencies' });
+ expect(model.nodes.map(item => item.id)).toEqual(['area:src/api', 'area:src/service', 'area:src/store']);
+ expect(model.edges.find(edge => edge.source === 'area:src/api')).toMatchObject({
+ source: 'area:src/api', target: 'area:src/service', type: 'CALLS', count: 1,
+ });
+ const call = model.edges.find(edge => edge.source === 'area:src/api')!;
+ expect(call.evidence[0].source).toBe(fixture.nodes[0]);
+ expect(call.evidence[0].line).toBe(15);
+ expect(model.edges.filter(edge => edge.source === 'area:src/service' && edge.target === 'area:src/store').map(edge => edge.type).sort())
+ .toEqual(['CALLS', 'IMPORTS']);
+ expect(model.nodes.every(item => item.graphNode === undefined)).toBe(true);
+ expect(buildSemanticGraph(fixture, { view: 'dependencies', relations: [] }).edges).toEqual(model.edges);
+ });
+ it('drills directories into files and files into real selectable symbols', () => {
+ const area = buildSemanticGraph(fixture, { view: 'overview', areaPath: 'src/service' });
+ expect(area.nodes.filter(item => item.kind === 'file').map(item => item.id)).toEqual(['file:src/service/read.ts', 'file:src/service/users.ts']);
+ expect(area.edges.find(edge => edge.target === 'file:src/service/read.ts')).toMatchObject({ source: 'file:src/service/users.ts', target: 'file:src/service/read.ts' });
+ const file = buildSemanticGraph(fixture, { view: 'overview', filePath: 'src/service/users.ts' });
+ expect(file.nodes.find(item => item.kind === 'symbol')?.graphNode).toBe(fixture.nodes[1]);
+ });
+ it('retains external source areas and exact boundary evidence when drilling a file', () => {
+ const model = buildSemanticGraph(fixture, { view: 'dependencies', filePath: 'src/service/users.ts' });
+ const symbol = model.nodes.find(item => item.graphNode === fixture.nodes[1])!;
+ const outside = model.nodes.find(item => item.id === 'area:src/store')!;
+ expect(outside.detail).toBe('External source area · inferred from file paths');
+ const call = model.edges.find(edge => edge.source === symbol.id && edge.target === outside.id && edge.type === 'CALLS')!;
+ expect(call.evidence[0].source).toBe(fixture.nodes[1]);
+ expect(call.evidence[0].target).toBe(fixture.nodes[2]);
+ expect(model.edges.some(edge => edge.source === 'area:src/store' && edge.target === 'area:src/api')).toBe(false);
+ expect(buildSemanticGraph({ ...fixture, nodes: [...fixture.nodes].reverse(), edges: [...fixture.edges].reverse() },
+ { view: 'dependencies', filePath: 'src/service/users.ts' })).toEqual(model);
+ });
+ it('keeps file-level imports on the file instead of assigning them to a symbol', () => {
+ const file = { ...node(10, 'src/service/users.ts', 'users.ts'), label: 'File' };
+ const graph = { ...fixture, nodes: [...fixture.nodes, file], edges: [
+ { source: file.id, target: fixture.nodes[2].id, type: 'IMPORTS' },
+ ] };
+ const model = buildSemanticGraph(graph, { view: 'dependencies', filePath: file.file_path });
+ expect(model.edges[0]).toMatchObject({ source: 'file:src/service/users.ts', target: 'area:src/store', type: 'IMPORTS' });
+ expect(model.edges[0].evidence[0].source).toBe(file);
+ });
+ it('is invariant under backend row ordering and does not mutate the graph', () => {
+ const original = JSON.stringify(fixture);
+ const reversed = { ...fixture, nodes: [...fixture.nodes].reverse(), edges: [...fixture.edges].reverse() };
+ for (const view of ['overview', 'dependencies', 'entryPoints', 'routes'] as const) {
+ expect(buildSemanticGraph(reversed, { view })).toEqual(buildSemanticGraph(fixture, { view }));
+ }
+ expect(JSON.stringify(fixture)).toBe(original);
+ });
+ it('caps visible graph independently and accounts for every omitted projected node and edge', () => {
+ const graph: GraphData = { nodes: Array.from({ length: 70 }, (_, id) => node(id, `services/service${id}/index.ts`)),
+ edges: Array.from({ length: 69 }, (_, id) => ({ source: id, target: id + 1, type: 'CALLS' })), total_nodes: 70 };
+ const model = buildSemanticGraph(graph, { view: 'overview', maxEdges: 5 });
+ expect(model.nodes).toHaveLength(40);
+ expect(model.omittedNodes).toBe(30);
+ expect(model.edges).toHaveLength(5);
+ expect(model.omittedEdges + model.edges.length).toBe(69);
+ expect(model.edges.every(edge => model.nodes.some(item => item.id === edge.source)
+ && model.nodes.some(item => item.id === edge.target))).toBe(true);
+ });
+ it('computes shortest static reachability through cycles and exposes the hop boundary', () => {
+ const model = buildSemanticGraph(fixture, { view: 'entryPoints', entryId: 1, depth: 1 });
+ expect(model.nodes.map(item => [item.label, item.depth])).toEqual([['start', 0], ['users', 1]]);
+ expect(model.warnings.join(' ')).toContain('1-hop boundary');
+ const deep = buildSemanticGraph(fixture, { view: 'entryPoints', entryId: 1, depth: 8 });
+ expect(deep.nodes).toHaveLength(4);
+ expect(deep.nodes.find(item => item.label === 'start')?.depth).toBe(0);
+ expect(deep.nodes.find(item => item.label === 'save')?.depth).toBe(2);
+ expect(deep.edges.some(edge => edge.evidence[0].source.id === 3 && edge.evidence[0].target.id === 1)).toBe(true);
+ expect(deep.edges.every(edge => edge.type === 'CALLS')).toBe(true);
+ expect(deep.positionMeaning).toContain('not runtime execution order');
+ });
+ it('uses entry classifications and exact identities rather than names and excludes tests', () => {
+ const graph: GraphData = { nodes: [node(1, 'a.ts', 'main'), node(2, 'b.ts', 'another'),
+ node(3, 'test.ts', 'test', 'test')], edges: [], total_nodes: 3 };
+ expect(semanticEntryPoints(graph)).toEqual([]);
+ expect(semanticEntryPoints(graph, ['fixture.another', 'fixture.test']).map(item => item.id)).toEqual([2]);
+ expect(buildSemanticGraph(graph, { view: 'entryPoints', entryId: 2 }).nodes[0].graphNode?.id).toBe(2);
+ });
+ it('retains a recursive symbol edge when its source and target are the same', () => {
+ const model = buildSemanticGraph({ ...fixture, edges: [{ source: 1, target: 1, type: 'CALLS' }] }, { view: 'entryPoints' });
+ expect(model.edges).toHaveLength(1);
+ expect(model.edges[0].source).toBe(model.edges[0].target);
+ expect(model.edges[0].evidence[0].source).toBe(fixture.nodes[0]);
+ });
+ it('keeps unresolved endpoints and invalid callsite coordinates honest', () => {
+ const model = buildSemanticGraph({ ...fixture, edges: [
+ { source: 1, target: 2, type: 'CALLS', line: 900 }, { source: 1, target: 99, type: 'CALLS' },
+ ] }, { view: 'dependencies' });
+ expect(model.edges[0].evidence[0].line).toBeUndefined();
+ expect(model.warnings.join(' ')).toContain('endpoint outside');
+ });
+});
+
+describe('route identities and service evidence', () => {
+ const route: GraphNode = { id: 10, label: 'Route', name: '/users', qualified_name: 'fixture.route.users', x: 0, y: 0, z: 0, size: 1, color: '' };
+ it('renders route registrations without manufacturing relationships to named handlers', () => {
+ const model = buildSemanticGraph({ ...fixture, nodes: [...fixture.nodes, route] }, { view: 'routes',
+ routes: [{ method: 'GET', path: '/users', filePath: 'src/api/server.ts', line: 10, handler: 'users', origin: 'source' }] });
+ expect(model.nodes.filter(item => item.kind === 'route')).toHaveLength(2);
+ expect(model.edges).toEqual([]);
+ expect(model.nodes.some(item => item.detail.includes('handler relationship not resolved'))).toBe(true);
+ });
+ it('deduplicates exact indexed route registrations without guessing unresolved source registrations', () => {
+ const model = buildSemanticGraph({ ...fixture, nodes: [...fixture.nodes, route] }, { view: 'routes',
+ routes: [{ method: 'GET', path: '/users', origin: 'index' }] });
+ expect(model.nodes.filter(item => item.kind === 'route')).toHaveLength(1);
+ });
+ it('uses QN and file identity across generations; re-used numeric IDs cannot select a different symbol', () => {
+ const current = { ...fixture.nodes[0], id: 101, start_line: 20 };
+ const unrelated = { ...fixture.nodes[1], id: 1 };
+ const graph = { nodes: [current, unrelated, route], edges: [], total_nodes: 3 };
+ const model = buildSemanticGraph(graph, { view: 'routes', routeSnapshot: { truncated: false, warnings: [], relationships: [
+ { source: fixture.nodes[0], target: { ...route, id: 999 }, type: 'HTTP_CALLS', routePath: '/users' },
+ ] } });
+ expect(model.edges[0].evidence[0].source).toBe(current);
+ expect(model.edges[0].evidence[0].target).toBe(route);
+ expect(model.nodes.find(item => item.kind === 'route')?.graphNode).toBe(route);
+ expect(model.nodes.find(item => item.kind === 'area')?.members).toEqual([current]);
+ });
+ it('keeps callers, paths and explicit handlers as separate typed relationships', () => {
+ const graph = { ...fixture, nodes: [...fixture.nodes, route] };
+ const model = buildSemanticGraph(graph, { view: 'routes', routeSnapshot: { truncated: true, warnings: [], relationships: [
+ { source: fixture.nodes[0], target: route, type: 'HTTP_CALLS', routePath: '/users', via: 'fetch' },
+ { source: route, target: fixture.nodes[1], type: 'HANDLES' },
+ ] } });
+ expect(model.edges.map(edge => edge.type).sort()).toEqual(['HANDLES', 'HTTP_CALLS']);
+ expect(model.nodes.find(item => item.id === 'caller-area:src/api')?.position[0]).toBe(-32);
+ expect(model.nodes.find(item => item.id === 'handler-area:src/service')?.position[0]).toBe(32);
+ expect(model.nodes.find(item => item.kind === 'route')?.position[0]).toBe(0);
+ expect(model.warnings.join(' ')).toContain('missing lines do not prove');
+ });
+ it('keeps a matching route and its caller context when filtering by path', () => {
+ const caller = node(1, 'services/gateway/client.ts', 'request');
+ const graph: GraphData = { nodes: [caller, route], edges: [], total_nodes: 2 };
+ const model = buildSemanticGraph(graph, { view: 'routes', filter: '/users', routeSnapshot: {
+ truncated: false, warnings: [], relationships: [{ source: caller, target: route, type: 'HTTP_CALLS' }],
+ } });
+ expect(model.nodes.map(item => item.kind).sort()).toEqual(['area', 'route']);
+ expect(model.edges).toHaveLength(1);
+ expect(model.edges[0].evidence[0].source).toBe(caller);
+ expect(model.warnings.join(' ')).toContain('one-hop neighbors');
+ });
+ it('retains a path match before its equally connected caller at a tight scene cap', () => {
+ const callers = [node(1, 'services/gateway/client.ts', 'request')];
+ const graph: GraphData = { nodes: [...callers, route], edges: [], total_nodes: 2 };
+ const model = buildSemanticGraph(graph, { view: 'routes', filter: '/users', maxNodes: 1, routeSnapshot: {
+ truncated: false, warnings: [], relationships: callers.map(source => ({ source, target: route, type: 'HTTP_CALLS' as const })),
+ } });
+ expect(model.nodes).toHaveLength(1);
+ expect(model.nodes.some(item => item.kind === 'route')).toBe(true);
+ expect(model.edges).toHaveLength(0);
+ expect(model.omittedNodes).toBe(1);
+ });
+ it('packs large route lanes into compact deterministic bands without overlap', () => {
+ const routes = Array.from({ length: 35 }, (_, id) => ({ ...route, id: 100 + id, name: `/api/${id}`, qualified_name: `fixture.route.${id}` }));
+ const caller = node(1, 'services/gateway/client.ts', 'request');
+ const graph: GraphData = { nodes: [caller, ...routes], edges: [], total_nodes: 36 };
+ const options = { view: 'routes' as const, routeSnapshot: { truncated: false, warnings: [],
+ relationships: routes.map(target => ({ source: caller, target, type: 'HTTP_CALLS' as const })) } };
+ const model = buildSemanticGraph(graph, options);
+ const routeNodes = model.nodes.filter(item => item.kind === 'route');
+ expect(new Set(routeNodes.map(item => item.position[2])).size).toBeLessThanOrEqual(5);
+ expect(Math.max(...routeNodes.map(item => item.position[2])) - Math.min(...routeNodes.map(item => item.position[2]))).toBeLessThanOrEqual(80);
+ const callerX = model.nodes.find(item => item.kind === 'area')!.position[0];
+ expect(Math.min(...routeNodes.map(item => item.position[0])) - callerX).toBeGreaterThan(12);
+ expect(new Set(routeNodes.map(item => item.position.join(','))).size).toBe(35);
+ expect(buildSemanticGraph({ ...graph, nodes: [...graph.nodes].reverse() }, options)).toEqual(model);
+ });
+});
+
+it('packs entry-point siblings while preserving depth order between bands', () => {
+ const root = node(1, 'src/main.ts', 'main', 'entry');
+ const children = Array.from({ length: 30 }, (_, id) => node(id + 2, 'src/work.ts', `work${id}`));
+ const leaf = node(100, 'src/leaf.ts', 'leaf');
+ const graph: GraphData = { nodes: [root, ...children, leaf], total_nodes: 32,
+ edges: [...children.map(child => ({ source: root.id, target: child.id, type: 'CALLS' })),
+ { source: children[0].id, target: leaf.id, type: 'CALLS' }] };
+ const model = buildSemanticGraph(graph, { view: 'entryPoints' });
+ const siblings = model.nodes.filter(item => item.depth === 1);
+ expect(new Set(siblings.map(item => item.position[2])).size).toBeLessThanOrEqual(5);
+ expect(Math.min(...siblings.map(item => item.position[0]))).toBeGreaterThan(model.nodes.find(item => item.depth === 0)!.position[0]);
+ expect(Math.max(...siblings.map(item => item.position[0]))).toBeLessThan(model.nodes.find(item => item.depth === 2)!.position[0]);
+});
diff --git a/graph-ui/src/architecture/semantic-graph.ts b/graph-ui/src/architecture/semantic-graph.ts
new file mode 100644
index 000000000..372929a0a
--- /dev/null
+++ b/graph-ui/src/architecture/semantic-graph.ts
@@ -0,0 +1,332 @@
+import type { RouteRef } from '../core/intelligence-provider';
+import type { GraphData, GraphEdge, GraphNode } from '../galaxy/types';
+import { areaOf, MAP_RELATIONS } from './repository-map';
+import type { RouteGraphSnapshot } from './route-graph-source';
+
+export type SemanticView = 'overview' | 'dependencies' | 'entryPoints' | 'routes';
+export interface SemanticNode {
+ id: string;
+ kind: 'area' | 'file' | 'symbol' | 'route';
+ label: string;
+ detail: string;
+ position: [number, number, number];
+ count: number;
+ /** Present only for a real node from the current repository snapshot. */
+ graphNode?: GraphNode;
+ filePath?: string;
+ line?: number;
+ areaPath?: string;
+ members: GraphNode[];
+ depth?: number;
+}
+export interface SemanticEvidence {
+ source: GraphNode;
+ target: GraphNode;
+ type: string;
+ id?: number;
+ line?: number;
+ strategy?: string;
+ confidence?: number;
+ routePath?: string;
+ via?: string;
+}
+export interface SemanticEdge {
+ id: string;
+ source: string;
+ target: string;
+ type: string;
+ count: number;
+ evidence: SemanticEvidence[];
+}
+export interface SemanticGraph {
+ view: SemanticView;
+ scopeKey: string;
+ title: string;
+ positionMeaning: string;
+ nodes: SemanticNode[];
+ edges: SemanticEdge[];
+ totalNodes: number;
+ totalEdges: number;
+ omittedNodes: number;
+ omittedEdges: number;
+ warnings: string[];
+}
+export interface SemanticGraphOptions {
+ view: SemanticView;
+ areaPath?: string;
+ filePath?: string;
+ entryId?: number;
+ entryQualifiedNames?: string[];
+ depth?: number;
+ filter?: string;
+ relations?: string[];
+ routes?: RouteRef[];
+ routeSnapshot?: RouteGraphSnapshot;
+ maxNodes?: number;
+ maxEdges?: number;
+}
+
+const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
+const identity = (node: GraphNode) => `${node.label}:${node.qualified_name || `#${node.id}`}@${node.file_path ?? ''}`;
+const nodeOrder = (a: GraphNode, b: GraphNode) => compare(identity(a), identity(b));
+const symbolId = (node: GraphNode) => `symbol:${identity(node)}`;
+const sourceNode = (node: GraphNode) => Boolean(node.file_path && node.file_path !== '{}'
+ && !['Project', 'Folder', 'Package', 'Branch', 'Route'].includes(node.label));
+const symbolNode = (node: GraphNode): SemanticNode => ({ id: symbolId(node),
+ kind: node.label === 'Route' ? 'route' : 'symbol', label: node.name,
+ detail: node.file_path ?? node.qualified_name ?? node.label, position: [0, 0, 0],
+ count: 1, graphNode: node, filePath: node.file_path, line: node.start_line,
+ areaPath: node.file_path ? areaOf(node.file_path) : undefined, members: [node] });
+
+/** Use explicit index classifications or exact qualified identities, never a name guess. */
+export function semanticEntryPoints(graph: GraphData, qualifiedNames: string[] = []): GraphNode[] {
+ const names = new Set(qualifiedNames);
+ return graph.nodes.filter(node => ['Function', 'Method'].includes(node.label)
+ && node.status !== 'test' && (node.status === 'entry' || Boolean(node.qualified_name && names.has(node.qualified_name))))
+ .sort((a, b) => (b.out_calls ?? 0) - (a.out_calls ?? 0) || nodeOrder(a, b));
+}
+
+function evidenceFor(edge: GraphEdge, source: GraphNode, target: GraphNode): SemanticEvidence {
+ const verifiedLine = edge.line !== undefined && source.start_line !== undefined && source.end_line !== undefined
+ && edge.line >= source.start_line && edge.line <= source.end_line ? edge.line : undefined;
+ return { source, target, type: edge.type, id: edge.id, line: verifiedLine,
+ strategy: edge.strategy, confidence: edge.confidence };
+}
+
+function aggregate(evidence: SemanticEvidence[], mapNode: (node: GraphNode, edge: SemanticEvidence, side: 'source' | 'target') => string | undefined): SemanticEdge[] {
+ const edges = new Map<string, SemanticEdge>();
+ const seen = new Set<string>();
+ for (const finding of evidence) {
+ const evidenceId = `${identity(finding.source)}:${finding.type}:${identity(finding.target)}:${finding.id ?? ''}:${finding.line ?? ''}`;
+ if (seen.has(evidenceId)) continue;
+ seen.add(evidenceId);
+ const source = mapNode(finding.source, finding, 'source');
+ const target = mapNode(finding.target, finding, 'target');
+ // Area/file internal edges appear on drill-down; real recursive calls remain evidence.
+ if (!source || !target || (source === target && !source.startsWith('symbol:'))) continue;
+ const id = `${source}→${finding.type}→${target}`;
+ const edge = edges.get(id) ?? { id, source, target, type: finding.type, count: 0, evidence: [] };
+ edge.evidence.push(finding); edge.count++; edges.set(id, edge);
+ }
+ return [...edges.values()].map(edge => ({ ...edge, evidence: edge.evidence.sort((a, b) =>
+ compare(`${identity(a.source)}:${identity(a.target)}:${a.id ?? ''}`, `${identity(b.source)}:${identity(b.target)}:${b.id ?? ''}`)) }))
+ .sort((a, b) => compare(a.id, b.id));
+}
+
+function bounded(value: number | undefined, fallback: number, maximum: number): number {
+ return Number.isFinite(value) ? Math.max(1, Math.min(maximum, Math.floor(value!))) : fallback;
+}
+
+/** Stable presentation projection. Scene limits are independent of backend snapshot limits. */
+export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptions): SemanticGraph {
+ const byId = new Map(graph.nodes.map(node => [node.id, node]));
+ const allowed = new Set(options.relations?.length ? options.relations : MAP_RELATIONS);
+ const evidence: SemanticEvidence[] = [];
+ let unresolved = 0;
+ for (const edge of graph.edges) {
+ if (!allowed.has(edge.type as typeof MAP_RELATIONS[number]) && options.view !== 'entryPoints' && options.view !== 'routes') continue;
+ const source = byId.get(edge.source); const target = byId.get(edge.target);
+ if (!source || !target) { unresolved++; continue; }
+ evidence.push(evidenceFor(edge, source, target));
+ }
+ let nodes: SemanticNode[] = [];
+ let edges: SemanticEdge[] = [];
+ const warnings: string[] = [];
+ let title = options.filePath ?? options.areaPath ?? 'Repository structure';
+ let positionMeaning = 'Source areas form a stable directory map. Boxes represent source grouping, not deployed services.';
+ const depth = bounded(options.depth, 3, 8);
+ let rootId: string | undefined;
+
+ if (options.view === 'entryPoints') {
+ const entries = semanticEntryPoints(graph, options.entryQualifiedNames);
+ const requested = options.entryId === undefined ? undefined : byId.get(options.entryId);
+ const root = requested && ['Function', 'Method'].includes(requested.label) && requested.status !== 'test'
+ ? requested : entries[0];
+ const depths = new Map<number, number>();
+ if (root) {
+ rootId = symbolId(root); depths.set(root.id, 0);
+ const outgoing = new Map<number, number[]>();
+ for (const edge of evidence.filter(edge => edge.type === 'CALLS')) {
+ const list = outgoing.get(edge.source.id) ?? []; list.push(edge.target.id); outgoing.set(edge.source.id, list);
+ }
+ const queue = [root.id];
+ for (let index = 0; index < queue.length; index++) {
+ const current = queue[index]; const currentDepth = depths.get(current)!;
+ if (currentDepth >= depth) continue;
+ for (const target of (outgoing.get(current) ?? []).sort((a, b) => nodeOrder(byId.get(a)!, byId.get(b)!))) {
+ if (!depths.has(target)) { depths.set(target, currentDepth + 1); queue.push(target); }
+ if (depths.size >= 1000) break;
+ }
+ if (depths.size >= 1000) { warnings.push('Reachability analysis stopped at 1,000 symbols.'); break; }
+ }
+ nodes = [...depths].map(([id, distance]) => ({ ...symbolNode(byId.get(id)!), depth: distance }));
+ edges = aggregate(evidence.filter(edge => edge.type === 'CALLS' && depths.has(edge.source.id) && depths.has(edge.target.id)), node => symbolId(node));
+ title = root.name;
+ if ([...depths].some(([id, distance]) => distance === depth && (outgoing.get(id) ?? []).some(target => !depths.has(target)))) {
+ warnings.push(`More calls continue beyond the ${depth}-hop boundary.`);
+ }
+ } else warnings.push('No indexed entry-point classification matches this repository snapshot.');
+ positionMeaning = 'Left to right: shortest static call distance from the entry point. This is possible reachability, not runtime execution order.';
+ } else if (options.view === 'routes') {
+ const currentByIdentity = new Map(graph.nodes.map(node => [identity(node), node]));
+ const routeEvidence = evidence.filter(edge => ['HTTP_CALLS', 'ASYNC_CALLS', 'HANDLES'].includes(edge.type));
+ for (const relationship of options.routeSnapshot?.relationships ?? []) {
+ const remap = (node: GraphNode) => node.qualified_name ? currentByIdentity.get(identity(node)) ?? node : node;
+ routeEvidence.push({ ...relationship, source: remap(relationship.source), target: remap(relationship.target) });
+ }
+ const routeNodes = new Map<string, SemanticNode>();
+ const currentNodes = new Set(graph.nodes);
+ const routeKey = (node: GraphNode, edge?: SemanticEvidence): string => {
+ if (node.label === 'Route') {
+ const id = `route:${identity(node)}`;
+ if (!routeNodes.has(id)) routeNodes.set(id, { ...symbolNode(node), id, kind: 'route',
+ graphNode: currentNodes.has(node) ? node : undefined,
+ label: edge?.routePath ?? node.name, detail: node.file_path ?? 'Indexed route; source location unavailable' });
+ return id;
+ }
+ const area = node.file_path ? areaOf(node.file_path) : undefined;
+ const role = edge?.type === 'HANDLES' ? 'handler' : 'caller';
+ const id = area ? `${role}-area:${area}` : `${role}:${identity(node)}`;
+ let group = routeNodes.get(id);
+ if (!group) {
+ group = { id, kind: area ? 'area' : 'symbol', label: area ?? node.name,
+ detail: `${role === 'handler' ? 'Handler' : 'Caller'} source area; inferred from file paths`,
+ position: [0, 0, 0], count: 0, areaPath: area, members: [] };
+ routeNodes.set(id, group);
+ }
+ if (!group.members.some(member => identity(member) === identity(node))) { group.members.push(node); group.count++; }
+ return id;
+ };
+ edges = aggregate(routeEvidence, (node, edge) => routeKey(node, edge));
+ for (const node of graph.nodes.filter(node => node.label === 'Route')) routeKey(node);
+ for (const route of options.routes ?? []) {
+ const alreadyRepresented = graph.nodes.some(node => node.label === 'Route'
+ && [route.path, `${route.method ?? ''} ${route.path}`.trim()].includes(node.name)
+ && (!route.filePath || node.file_path === route.filePath)
+ && (route.origin === 'index' || (route.filePath && route.line && node.start_line === route.line)));
+ if (alreadyRepresented) continue;
+ // A textual registration is useful navigation, but cannot establish an edge or handler identity.
+ const id = `registration:${route.method ?? ''}:${route.path}@${route.filePath ?? ''}:${route.line ?? ''}`;
+ routeNodes.set(id, { id, kind: 'route', label: `${route.method ? `${route.method} ` : ''}${route.path}`,
+ detail: `${route.origin === 'source' ? 'Source' : 'Index'} registration · handler relationship not resolved`,
+ position: [0, 0, 0], count: 1, filePath: route.filePath, line: route.line, members: [] });
+ }
+ nodes = [...routeNodes.values()];
+ for (const node of nodes) node.members.sort(nodeOrder);
+ warnings.push(...options.routeSnapshot?.warnings ?? []);
+ if (options.routeSnapshot?.truncated) warnings.push('Route relationships are partial; missing lines do not prove that services are disconnected.');
+ title = 'Requests across source areas';
+ positionMeaning = 'Caller areas → route paths → handler areas. Only recorded HTTP, async and handler relationships become lines; isolated routes are registrations.';
+ } else {
+ const groups = new Map<string, SemanticNode>();
+ const nodeGroups = new Map<number, string>();
+ for (const node of graph.nodes.filter(sourceNode).sort(nodeOrder)) {
+ const area = areaOf(node.file_path!);
+ if (options.areaPath && area !== options.areaPath) continue;
+ if (options.filePath && node.file_path !== options.filePath) continue;
+ if (options.filePath) {
+ if (['File', 'Module'].includes(node.label)) continue;
+ const result = symbolNode(node); groups.set(result.id, result); nodeGroups.set(node.id, result.id);
+ continue;
+ }
+ const kind = options.areaPath ? 'file' : 'area';
+ const path = options.areaPath ? node.file_path! : area;
+ const id = `${kind}:${path}`;
+ const group = groups.get(id) ?? { id, kind, label: path, detail: '', position: [0, 0, 0], count: 0,
+ filePath: kind === 'file' ? path : undefined, areaPath: area, members: [] };
+ group.members.push(node); group.count++; groups.set(id, group); nodeGroups.set(node.id, id);
+ }
+ let scopedEvidence = evidence;
+ if (options.areaPath || options.filePath) {
+ const inScope = (node: GraphNode) => sourceNode(node)
+ && (!options.areaPath || areaOf(node.file_path!) === options.areaPath)
+ && (!options.filePath || node.file_path === options.filePath);
+ scopedEvidence = evidence.filter(edge => inScope(edge.source) || inScope(edge.target));
+ for (const edge of scopedEvidence) {
+ if (inScope(edge.source) === inScope(edge.target)) continue;
+ const inside = inScope(edge.source) ? edge.source : edge.target;
+ const outside = inside === edge.source ? edge.target : edge.source;
+ if (!sourceNode(outside)) continue;
+ // File/module imports remain attributed to the real file, never
+ // guessed onto an arbitrary symbol in the opened file.
+ if (!nodeGroups.has(inside.id) && options.filePath && ['File', 'Module'].includes(inside.label)) {
+ const id = `file:${options.filePath}`;
+ const group: SemanticNode = groups.get(id) ?? { id, kind: 'file', label: options.filePath,
+ detail: 'File-level dependencies', position: [0, 0, 0], count: 0,
+ filePath: options.filePath, areaPath: areaOf(options.filePath), members: [] };
+ if (!group.members.includes(inside)) { group.members.push(inside); group.count++; }
+ groups.set(id, group); nodeGroups.set(inside.id, id);
+ }
+ if (!nodeGroups.has(inside.id)) continue;
+ const areaPath = areaOf(outside.file_path!);
+ const id = `area:${areaPath}`;
+ const group: SemanticNode = groups.get(id) ?? { id, kind: 'area', label: areaPath,
+ detail: 'External source area · inferred from file paths', position: [0, 0, 0],
+ count: 0, areaPath, members: [] };
+ if (!group.members.includes(outside)) { group.members.push(outside); group.count++; }
+ groups.set(id, group); nodeGroups.set(outside.id, id);
+ }
+ }
+ nodes = [...groups.values()].map(node => ({ ...node, members: node.members.sort(nodeOrder),
+ detail: node.detail || `${new Set(node.members.map(member => member.file_path)).size} files · ${node.count} indexed nodes` }));
+ edges = aggregate(scopedEvidence, node => nodeGroups.get(node.id));
+ if (options.view === 'dependencies') title = options.filePath ?? options.areaPath ?? 'Dependencies between source areas';
+ }
+
+ const filter = options.filter?.trim().toLowerCase();
+ const matching = new Set<string>();
+ if (filter) {
+ for (const node of nodes) {
+ if (`${node.label} ${node.detail} ${node.members.map(member => member.name).join(' ')}`.toLowerCase().includes(filter)) matching.add(node.id);
+ }
+ const context = new Set(matching);
+ for (const edge of edges) {
+ if (matching.has(edge.source) || matching.has(edge.target)) { context.add(edge.source); context.add(edge.target); }
+ }
+ nodes = nodes.filter(node => context.has(node.id));
+ edges = edges.filter(edge => context.has(edge.source) && context.has(edge.target));
+ if (context.size > matching.size) warnings.push('Showing filter matches and their one-hop neighbors for relationship context.');
+ }
+ const totalNodes = nodes.length; const totalEdges = edges.length;
+ const degrees = new Map<string, number>();
+ for (const edge of edges) for (const id of [edge.source, edge.target]) degrees.set(id, (degrees.get(id) ?? 0) + edge.count);
+ nodes.sort((a, b) => (a.id === rootId ? -1 : b.id === rootId ? 1 : 0)
+ || Number(matching.has(b.id)) - Number(matching.has(a.id))
+ || (a.depth ?? 0) - (b.depth ?? 0) || (degrees.get(b.id) ?? 0) - (degrees.get(a.id) ?? 0) || compare(a.id, b.id));
+ nodes = nodes.slice(0, bounded(options.maxNodes, 40, 80)).sort((a, b) => compare(a.id, b.id));
+ const visibleIds = new Set(nodes.map(node => node.id));
+ edges = edges.filter(edge => visibleIds.has(edge.source) && visibleIds.has(edge.target))
+ .sort((a, b) => Number(matching.has(b.source) || matching.has(b.target)) - Number(matching.has(a.source) || matching.has(a.target))
+ || b.count - a.count || compare(a.id, b.id)).slice(0, bounded(options.maxEdges, 100, 200));
+ const columns = Math.max(1, Math.ceil(Math.sqrt(nodes.length)));
+ const rows = Math.ceil(nodes.length / columns);
+ const lanes = new Map<number, SemanticNode[]>();
+ for (const node of nodes) {
+ const lane = options.view === 'entryPoints' ? node.depth ?? 0
+ : node.kind === 'route' ? 0 : node.id.startsWith('handler') ? 1 : -1;
+ const items = lanes.get(lane) ?? []; items.push(node); lanes.set(lane, items);
+ }
+ // Compact each semantic lane into at most five rows. Widen the distance
+ // between depth/role bands so a large lane never crosses the next one.
+ const widestBand = Math.max(1, ...[...lanes.values()].map(items => Math.ceil(items.length / 5)));
+ const laneSpacing = Math.max(options.view === 'routes' ? 32 : 24, (widestBand - 1) * 20 + 24);
+ nodes.forEach((node, index) => {
+ if (options.view === 'entryPoints' || options.view === 'routes') {
+ const lane = options.view === 'entryPoints' ? node.depth ?? 0
+ : node.kind === 'route' ? 0 : node.id.startsWith('handler') ? 1 : -1;
+ const siblings = lanes.get(lane)!;
+ const laneColumns = Math.ceil(siblings.length / 5);
+ const laneRows = Math.ceil(siblings.length / laneColumns);
+ const siblingIndex = siblings.indexOf(node);
+ node.position = [lane * laneSpacing + (Math.floor(siblingIndex / laneRows) - (laneColumns - 1) / 2) * 20,
+ options.view === 'entryPoints' ? lane * 3 : 0, (siblingIndex % laneRows - (laneRows - 1) / 2) * 20];
+ } else node.position = [(index % columns - (columns - 1) / 2) * 24,
+ node.kind === 'symbol' ? 12 : node.kind === 'file' ? 6 : 0,
+ (Math.floor(index / columns) - (rows - 1) / 2) * 24];
+ });
+ if (unresolved) warnings.push(`${unresolved} relationships have an endpoint outside the loaded repository snapshot.`);
+ if (graph.total_nodes > graph.nodes.length) warnings.push('The loaded repository snapshot contains only part of the indexed graph.');
+ return { view: options.view, scopeKey: `${options.view}:${options.areaPath ?? ''}:${options.filePath ?? ''}:${rootId ?? ''}:${filter ?? ''}`,
+ title, positionMeaning, nodes, edges, totalNodes, totalEdges, omittedNodes: totalNodes - nodes.length,
+ omittedEdges: totalEdges - edges.length, warnings: [...new Set(warnings)] };
+}
diff --git a/graph-ui/src/architecture/spatial-architecture.css b/graph-ui/src/architecture/spatial-architecture.css
new file mode 100644
index 000000000..e698ec42f
--- /dev/null
+++ b/graph-ui/src/architecture/spatial-architecture.css
@@ -0,0 +1,46 @@
+.spatial-architecture { --spatial-line: #27443e; --spatial-muted: #91ada7; margin: 20px 0 28px; border: 1px solid var(--spatial-line); border-radius: 14px; background: #0b1517; overflow: hidden; color: #deece7; }
+.spatial-heading { display:flex; justify-content:space-between; align-items:flex-start; gap:20px; padding:24px 24px 18px; }
+.spatial-eyebrow { color:#6be7ba; font: 11px/1.5 var(--atlas-mono, monospace); text-transform:uppercase; letter-spacing: .14em; }
+.atlas-architecture .spatial-heading h2 { margin:6px 0; font-size:24px; font-weight:550; letter-spacing:-.035em; text-transform:none; }
+.spatial-heading p { margin:8px 0 0; max-width:740px; font-size:13px; line-height:1.6; color:var(--spatial-muted); }
+.spatial-architecture button, .spatial-architecture select { color:inherit; border:1px solid var(--spatial-line); border-radius:5px; background:#101e21; padding:7px 10px; font:inherit; font-size:12px; cursor:pointer; }
+.spatial-architecture button:hover, .spatial-architecture button[aria-pressed=true] { color:#85f0c3; background:#17332e; border-color:#449e7b; }
+.spatial-architecture button:focus-visible, .spatial-architecture select:focus-visible, .spatial-architecture summary:focus-visible { outline:2px solid #8ce9f7; outline-offset:3px; }
+.spatial-architecture button:disabled { opacity:.5; cursor:default; }
+.spatial-camera-controls { display:flex; gap:4px; flex-shrink:0; }
+.spatial-controls { display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:12px; padding:12px 20px; border-block:1px solid var(--spatial-line); }
+.spatial-controls nav, .spatial-controls label, .spatial-relations { display:flex; gap:7px; align-items:center; font-size:12px; }
+.spatial-controls nav { min-width:0; flex-wrap:wrap; }
+.spatial-controls select { max-width:min(48vw,500px); }
+.spatial-relations { flex-wrap:wrap; }
+.spatial-relations button { font-size:10px; padding:5px 7px; }
+.spatial-map-layout { display:grid; grid-template-columns:minmax(0, 1fr) 300px; }
+.spatial-map { position:relative; height:clamp(490px,55vh,720px); min-width:0; background:radial-gradient(ellipse at 45% 45%,#12252d,#080f14 75%); overflow:hidden; }
+.spatial-map-caption { position:absolute; pointer-events:none; bottom:0; left:0; right:0; display:flex; flex-wrap:wrap; justify-content:space-between; gap:8px; background:linear-gradient(transparent,#080f14); color:#91ada7; padding:30px 18px 14px; font-size:10px; }
+.spatial-map .architecture-scene-guide { display:none; }
+.spatial-map .architecture-node-label:not(.is-selected) { padding:6px 9px; min-width:0; max-width:150px; background:#0e1925e8; }
+.spatial-inspector { padding:20px; min-width:0; max-height:clamp(490px,55vh,720px); overflow:auto; border-left:1px solid var(--spatial-line); background:#0d191c; }
+.spatial-inspector h3 { font-size:18px; font-weight:500; overflow-wrap:anywhere; margin:10px 0; }
+.spatial-inspector h3 span { color:#6be7ba; }
+.spatial-inspector h4 { margin:20px 0 10px; font-size:11px; text-transform:uppercase; letter-spacing:.1em; color:#91ada7; }
+.spatial-inspector p { font-size:12px; line-height:1.65; overflow-wrap:anywhere; }
+.spatial-inspector > button { margin:5px 6px 5px 0; }
+.spatial-inspector .spatial-primary { border-color:#449e7b; background:#16322b; color:#90f0c9; }
+.spatial-muted { color:var(--spatial-muted); }
+.spatial-members, .spatial-node-list { display:flex; flex-direction:column; gap:5px; }
+.spatial-members button, .spatial-node-list button { display:block; width:100%; text-align:left; margin:4px 0; overflow-wrap:anywhere; }
+.spatial-architecture small { display:block; font-size:10px; color:var(--spatial-muted); overflow-wrap:anywhere; margin-top:4px; }
+.spatial-node-list { margin-top:24px; }
+.spatial-architecture summary { font-size:12px; color:var(--spatial-muted); cursor:pointer; padding:8px 0; }
+.spatial-evidence article { padding:12px 0; border-bottom:1px solid var(--spatial-line); font-size:11px; display:flex; flex-direction:column; gap:4px; }
+.spatial-evidence article button { text-align:left; overflow-wrap:anywhere; }
+.spatial-evidence code { color:#a7b6ff; overflow-wrap:anywhere; }
+.spatial-bottom { display:flex; justify-content:space-between; flex-wrap:wrap; gap:8px; padding:12px 20px; border-top:1px solid var(--spatial-line); color:var(--spatial-muted); font-size:11px; }
+.spatial-notice { padding:0 20px; font-size:11px; line-height:1.6; color:#d7be8b; }
+.spatial-relationship-list, .spatial-coverage { padding:0 20px 12px; }
+.spatial-relationship-list > div { display:grid; grid-template-columns:repeat(auto-fit,minmax(250px,1fr)); gap:6px; }
+.spatial-relationship-list button { text-align:left; overflow-wrap:anywhere; }
+.spatial-coverage p { font-size:11px; line-height:1.6; color:var(--spatial-muted); }
+.spatial-unavailable { display:flex; align-items:center; justify-content:center; min-height:480px; padding:30px; text-align:center; color:var(--spatial-muted); font-size:14px; line-height:1.7; }
+@media(max-width:1050px) { .spatial-map-layout { grid-template-columns:minmax(0,1fr) 250px; } .spatial-heading { flex-wrap:wrap; } }
+@media(max-width:760px) { .spatial-map-layout { display:block; } .spatial-map { height:480px; } .spatial-inspector { max-height:360px; border-left:0; border-top:1px solid var(--spatial-line); } .spatial-heading { padding:18px; } .spatial-controls select { max-width:65vw; } }
diff --git a/tests/test_language_count_contract.sh b/tests/test_language_count_contract.sh
index 57d26186c..33c9a01cb 100644
--- a/tests/test_language_count_contract.sh
+++ b/tests/test_language_count_contract.sh
@@ -67,6 +67,7 @@ EXEMPT=(
'tests/repro/repro_grammar_scripting.c' # scripting-grammar probe scope (12)
'tests/test_grammar_probe_b.c' # grammar probe scope (12)
'tests/test_language_count_contract.sh' # this file, which names the numbers above
+ 'graph-ui/verification/pr-2068/audit-architecture.json' # captured README badges in the dated PR browser audit, not current support claims
'pkg/winget/manifests/' # version-pinned published manifests: 0.8.1
# really did ship 155, and rewriting a
# released manifest would falsify it