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): expand architecture exploration and streamline workspaces

Martin Vogeld0f148bb5a1e
diff --git a/Makefile.cbm b/Makefile.cbm
index f1430d943..be47b2de4 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -318,13 +318,13 @@ PREPROCESSOR_SRC = $(CBM_DIR)/preprocessor.cpp
SQLITE_WRITER_SRC = $(CBM_DIR)/sqlite_writer.c
# Store module (new)
-STORE_SRCS = src/store/store.c
+STORE_SRCS = src/store/store.c src/store/architecture_projection.c
# Cypher module (new)
CYPHER_SRCS = src/cypher/cypher.c
# MCP server module (new)
-MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c
+MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c src/mcp/architecture_jobs.c
# Shared MCP daemon coordination and local transport
DAEMON_SRCS = \
@@ -563,6 +563,7 @@ TEST_STORE_SRCS = \
tests/test_store_edges.c \
tests/test_store_search.c \
tests/test_store_arch.c \
+ tests/test_architecture_projection.c \
tests/test_store_bulk.c \
tests/test_store_pragmas.c \
tests/test_store_checkpoint.c \
diff --git a/graph-ui/package-lock.json b/graph-ui/package-lock.json
index 5b96ab157..95fa659bb 100644
--- a/graph-ui/package-lock.json
+++ b/graph-ui/package-lock.json
@@ -17,7 +17,8 @@
"react-dom": "19.2.8",
"react-markdown": "10.1.0",
"remark-gfm": "4.0.1",
- "three": "0.183.2"
+ "three": "0.183.2",
+ "yaml": "2.8.2"
},
"devDependencies": {
"@types/node": "20.19.43",
@@ -6283,6 +6284,21 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/yaml": {
+ "version": "2.8.2",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",
+ "integrity": "sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==",
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ },
"node_modules/zustand": {
"version": "5.0.15",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.15.tgz",
diff --git a/graph-ui/package.json b/graph-ui/package.json
index 7d90436d4..64c379e78 100644
--- a/graph-ui/package.json
+++ b/graph-ui/package.json
@@ -83,6 +83,7 @@
"react-dom": "19.2.8",
"react-markdown": "10.1.0",
"remark-gfm": "4.0.1",
- "three": "0.183.2"
+ "three": "0.183.2",
+ "yaml": "2.8.2"
}
}
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsx
index a381a2e08..71718e470 100644
--- a/graph-ui/src/App.tsx
+++ b/graph-ui/src/App.tsx
@@ -118,15 +118,14 @@ import type { JSX, KeyboardEvent } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import AtlasChrome, { CLOSE_COMMAND_SEARCH_EVENT, OPEN_COMMAND_SEARCH_EVENT } from './app/AtlasChrome';
+import { AtlasTreeIndexDetails } from './app/AtlasTree';
import ArchitecturePanel from './architecture/ArchitecturePanel';
import SelectionContextPanel from './why/SelectionContext';
import ChangeAnalysisWorkspace from './impact/ChangeAnalysisWorkspace';
import type { SelectionImpactTarget } from './impact/selection-impact';
import SourceEvidenceDrawer, { fileQualifiedName, type SourceEvidenceTarget } from './architecture/SourceEvidenceDrawer';
import { setUiLogProject } from './app/ui-log-install';
-import DaemonAlerts from './diagnostics/DaemonAlerts';
import DiagnosticsPanel from './diagnostics/DiagnosticsPanel';
-import { useDaemonLogFeed } from './diagnostics/useDaemonLogFeed';
import { resolveRepositorySelection, useRepositorySnapshot } from './architecture/repository-source';
import ActivityPanel from './agents/ActivityPanel';
import WelcomePanel from './app/WelcomePanel';
@@ -748,9 +747,9 @@ export default function App(): JSX.Element {
const [workspace, setWorkspace] = useState<Workspace>(() => {
try {
const requested = new URLSearchParams(window.location.search).get('workspace');
- if (requested === 'explore' || requested === 'galaxy' || requested === 'architecture' || requested === 'agents' || requested === 'system') return requested;
+ if (requested === 'explore' || requested === 'galaxy' || requested === 'architecture' || requested === 'agents' || requested === 'coverage' || requested === 'system') return requested;
const saved = localStorage.getItem('cbm.workspace');
- return saved === 'explore' || saved === 'galaxy' || saved === 'agents' || saved === 'system' ? saved : 'architecture';
+ return saved === 'explore' || saved === 'galaxy' || saved === 'agents' || saved === 'coverage' || saved === 'system' ? saved : 'architecture';
} catch { return 'architecture'; }
});
const changeWorkspace = (value: Workspace): void => {
@@ -764,6 +763,7 @@ export default function App(): JSX.Element {
try { return localStorage.getItem('cbm.workspace.setup') !== 'done'; } catch { return false; }
});
const [browserAiOpen, setBrowserAiOpen] = useState(false);
+ const [codeDetailsOpen, setCodeDetailsOpen] = useState(false);
const [readerSelection, setReaderSelection] = useState<ReaderSelection>();
const [pinnedCode, setPinnedCode] = useState<SelectedCodeSnapshot>();
const [fileSymbols, setFileSymbols] = useState<FileSymbolResult & { project: string; path: string; status: 'loading' | 'ready' | 'error' }>({ project: '', path: '', symbols: [], message: '', status: 'ready' });
@@ -776,17 +776,10 @@ export default function App(): JSX.Element {
setWhyDismissed(true);
try { localStorage.setItem('cbm.workspace.setup', 'done'); } catch { /* Session-only preference. */ }
};
- const [guidance, setGuidance] = useState<Guidance>(() => {
- try { return localStorage.getItem('cbm.explanation-depth') === 'explained' ? 'explained' : 'brief'; }
- catch { return 'brief'; }
- });
- const changeGuidance = (value: Guidance): void => {
- setGuidance(value);
- try { localStorage.setItem('cbm.explanation-depth', value); } catch { /* Session-only preference. */ }
- };
+ const guidance: Guidance = 'brief';
const client = useMemo(() => new RpcIntelligenceClient({}), []);
const api = useMemo(() => new AtlasApi({}), []);
- const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
+ const [diagnosticsPath, setDiagnosticsPath] = useState<string>();
/*
* What the projects panel asks the server. The list comes over /rpc like
@@ -816,9 +809,6 @@ export default function App(): JSX.Element {
}, []);
const [project, setProject] = useState('');
- const [logScopeChoice, setLogScopeChoice] = useState<{ project: string; scope: 'project' | 'daemon' }>();
- const logScope = logScopeChoice?.project === project ? logScopeChoice.scope : 'project';
- const daemonLogFeed = useDaemonLogFeed(api, Boolean(project), 3000, logScope === 'project' ? project : undefined);
const [projectDetail, setProjectDetail] = useState('resolving project ...');
const [serverOk, setServerOk] = useState<boolean | undefined>(undefined);
const [counts, setCounts] = useState<{ nodes?: number; edges?: number }>({});
@@ -4527,6 +4517,11 @@ export default function App(): JSX.Element {
if (!qualifiedName) throw new Error(workspaceText.sourceOutsideSnapshot);
return client.getCodeSnippet(project, qualifiedName, { startLine, maxLines });
}, [client, project, repositoryReading.snapshot]);
+ const clearGraphSelection = () => {
+ setGalaxySelection(undefined);
+ setGalaxySelectionProject('');
+ setChatGraphSelection(undefined);
+ };
const inspectorImpactTarget = inspector.filePath ? { filePath: inspector.filePath,
qualifiedName: inspector.symbol?.qualifiedName, id: inspector.symbol ? inspectorNode?.id : undefined,
name: inspector.symbol?.name, line: inspectorNode?.start_line } : undefined;
@@ -4572,7 +4567,6 @@ export default function App(): JSX.Element {
selectionContext={<SelectionContextPanel graph={evidenceGraph}
selected={inspector.symbol ? inspectorNode : undefined} path={inspector.filePath}
agents={agents.state} onNavigate={navigateEvidence} />}
- impact={<button className="atlas-analysis-action" disabled={!inspector.filePath} onClick={() => openSelectionImpact(inspectorImpactTarget)}>{workspaceText.selectionImpact} →</button>}
pinned={pinnedCode?.project === project}
onTogglePin={() => setPinnedCode(current => current?.project === project ? undefined : { ...liveCode,
selection: liveCode.selection ? { ...liveCode.selection } : undefined })}
@@ -4585,6 +4579,7 @@ export default function App(): JSX.Element {
const galaxy = (
<GalaxyPanel
project={project}
+ onClearSelection={clearGraphSelection}
selectionPanel={workspace === 'galaxy' ? mapSelectionPanel : undefined}
visible={workspace === 'galaxy' || (workspace === 'explore' && galaxyOn)}
workspaceExpanded={workspace === 'galaxy'}
@@ -4788,35 +4783,33 @@ export default function App(): JSX.Element {
const clearAttachment = (id: string): void => {
setChatAttachment(current => current?.id === id ? undefined : current);
};
- const clearGraphSelection = (id: string): void => {
+ const clearChatGraphSelection = (id: string): void => {
setChatGraphSelection(current => current?.id === id ? undefined : current);
};
return (
<AtlasChrome
- workspaceStatus={<DaemonAlerts key={`${project}:${logScope}`} project={project} scope={logScope}
- onScopeChange={scope => setLogScopeChoice({ project, scope })} reading={daemonLogFeed} coverage={coverage} coverageKnown={coverageAsked} coverageError={coverageError} onDiagnose={() => setDiagnosticsOpen(true)} />}
workspace={workspace}
projectSwitcher={<ProjectSwitcher currentProject={project} listProjects={projectsSource.listProjects}
onSelectProject={openProject} onManageProjects={() => setProjectsOpen(true)} />}
- onWorkspaceChange={changeWorkspace}
+ onWorkspaceChange={value => { setDiagnosticsPath(undefined); changeWorkspace(value); }}
onOpenBrowserAi={() => setBrowserAiOpen(open => !open)}
onOpenSystem={() => changeWorkspace('system')}
daemonState={serverOk === undefined ? 'checking' : serverOk ? 'connected' : 'disconnected'}
chatOpen={browserAiOpen}
chatDock={<BrowserChatDock open={browserAiOpen} onClose={() => setBrowserAiOpen(false)}
- pendingContext={chatGraphSelection} onContextConsumed={clearGraphSelection} onContextRemoved={clearGraphSelection}
+ showCollapsed={workspace === 'explore'} onOpen={() => setBrowserAiOpen(true)}
+ pendingContext={chatGraphSelection} onContextConsumed={clearChatGraphSelection} onContextRemoved={clearChatGraphSelection}
context={browserGraphContext(inspector.ir, project, inspector.filePath, inspector.symbol ? workspacePathOf(inspector.symbol.uri) : '')}
attachment={chatAttachment} onAttachmentConsumed={clearAttachment} onAttachmentRemoved={clearAttachment} />}
readerActions={<>
<button type="button" disabled={!liveSelection} aria-keyshortcuts="Control+Shift+L Meta+Shift+L"
onClick={() => { if (liveSelection) attachSelection(liveSelection); }}>{workspaceText.askSelection}</button>
+ <button type="button" disabled={!inspector.filePath} onClick={() => openSelectionImpact(inspectorImpactTarget)}>{workspaceText.assessImpact}</button>
+ <button type="button" aria-expanded={codeDetailsOpen} onClick={() => setCodeDetailsOpen(open => !open)}>{workspaceText.codeDetails}</button>
</>}
- globalOverlay={<><DiagnosticsPanel project={project} client={client} coverage={coverageAsked ? coverage : undefined}
- coverageError={coverageError} active={diagnosticsOpen} onClose={() => setDiagnosticsOpen(false)}
- path={(workspace === 'architecture' || workspace === 'galaxy') ? activeGalaxySelection?.file_path : activePath || undefined}
- onNavigate={path => { setDiagnosticsOpen(false); navigateEvidence(path); }}
- onCoverage={reading => { setCoverage(reading.index); setCoverageMeta({ ...reading.answer.metadata }); setCoverageAsked(true); setCoverageError(''); setOverviewRevision(value => value + 1); }} />
+ readerDetails={codeDetailsOpen ? selectedCode : undefined}
+ globalOverlay={<>
{(impactOpen || analysisSelection?.project === project) && <div className="atlas-analysis-overlay" role="dialog" aria-label={workspaceText.changeAnalysis} onKeyDown={event => {
event.stopPropagation();
if (event.key === 'Escape') { setAnalysisSelection(undefined); if (impactOpen) collapseExplain(); }
@@ -4824,12 +4817,16 @@ export default function App(): JSX.Element {
selectedTarget={analysisSelection?.project === project ? analysisSelection.target : (workspace === 'architecture' || workspace === 'galaxy') ? mapImpactTarget : inspectorImpactTarget}
initialMode={analysisSelection?.project === project ? 'selection' : 'worktree'} expectedGeneration={repositoryReading.snapshot?.generation}
onOpenSource={target => navigateEvidence(target.filePath, target.line, target.name)}
- onDiagnose={() => setDiagnosticsOpen(true)} onClose={() => { setAnalysisSelection(undefined); if (impactOpen) collapseExplain(); }} /></div>}
+ onDiagnose={() => {
+ setDiagnosticsPath((workspace === 'architecture' || workspace === 'galaxy') ? activeGalaxySelection?.file_path : activePath || undefined);
+ setAnalysisSelection(undefined); if (impactOpen) collapseExplain();
+ changeWorkspace('coverage');
+ }} onClose={() => { setAnalysisSelection(undefined); if (impactOpen) collapseExplain(); }} /></div>}
{sourceEvidence?.project === project && <SourceEvidenceDrawer key={`${project}:${sourceEvidence.target.filePath}:${sourceEvidence.target.line ?? 1}`}
project={project} target={sourceEvidence.target} graph={evidenceGraph} client={client}
onClose={() => setSourceEvidence(undefined)} onExplore={exploreEvidence} />}
- {welcomeOpen && <WelcomePanel workspace={workspace} guidance={guidance}
- onWorkspace={changeWorkspace} onGuidance={changeGuidance} onContinue={finishSetup}
+ {welcomeOpen && <WelcomePanel workspace={workspace}
+ onWorkspace={changeWorkspace} onContinue={finishSetup}
onLocalAi={() => { finishSetup(); setBrowserAiOpen(true); }} />}
{projectsOpen && <ProjectsPanel project={project} source={projectsSource}
onOpenProject={openProject} onClose={() => setProjectsOpen(false)} />}
@@ -4845,10 +4842,11 @@ export default function App(): JSX.Element {
onClose={() => setSettingsOpen(false)} />}
</>}
guidance={guidance}
- onGuidanceChange={changeGuidance}
workspacePanel={<>
<div hidden={workspace !== 'architecture'}>
<ArchitecturePanel projectName={project} overview={overview} active={workspace === 'architecture'}
+ onClearSelection={clearGraphSelection}
+ coverage={coverageAsked && coverageMeta.generation === repositoryReading.snapshot?.generation ? coverage : undefined}
readSource={readMapSource}
graph={repositoryReading.snapshot} graphGeneration={repositoryReading.snapshot?.generation} selection={activeGalaxySelection} selectionPanel={mapSelectionPanel}
graphNote={repositoryReading.error ?? (repositoryReading.snapshot
@@ -4869,6 +4867,14 @@ export default function App(): JSX.Element {
<SystemWorkspace api={api} project={project} active={workspace === 'system'} version={ATLAS_VERSION}
onOpenProjects={() => setProjectsOpen(true)} />
</div>
+ <div hidden={workspace !== 'coverage'}>
+ <DiagnosticsPanel project={project} client={client} coverage={coverageAsked ? coverage : undefined}
+ coverageError={coverageError} active={workspace === 'coverage'} path={diagnosticsPath}
+ indexDetails={<AtlasTreeIndexDetails rows={rows} note={treeNoteParts.join('; ')}
+ noteIsAbsence={treeError.length > 0 || coverageError.length > 0 || !project} truncations={coverage.truncations} />}
+ onNavigate={path => { changeWorkspace('explore'); navigateEvidence(path); }}
+ onCoverage={reading => { setCoverage(reading.index); setCoverageMeta({ ...reading.answer.metadata }); setCoverageAsked(true); setCoverageError(''); setOverviewRevision(value => value + 1); }} />
+ </div>
</>}
version={ATLAS_VERSION}
buildSuffix={ATLAS_BUILD_SUFFIX}
@@ -4877,7 +4883,7 @@ export default function App(): JSX.Element {
onSelectTab={openFile}
onCloseTab={closeTab}
tree={{
- explained: guidance === 'explained',
+ explained: false,
projectName: project.length > 0 ? project : messages.app.noProject,
rows,
cursor,
@@ -4918,7 +4924,6 @@ export default function App(): JSX.Element {
}
menus={menus}
status={status}
- selectionInspector={selectedCode}
galaxy={galaxy}
zones={{
leftWidth: shownZones.leftWidth,
diff --git a/graph-ui/src/app/AtlasChrome.tsx b/graph-ui/src/app/AtlasChrome.tsx
index 856c407b1..66200923a 100644
--- a/graph-ui/src/app/AtlasChrome.tsx
+++ b/graph-ui/src/app/AtlasChrome.tsx
@@ -36,6 +36,7 @@ import Hint from '../ui/tooltip/Hint';
import { LAYOUT_DEFAULT } from '../layout/layout-model';
import Splitter from '../layout/Splitter';
import { workspaceStrings } from './workspace-strings';
+import GraphEdgeControls from '../graph/GraphEdgeControls';
import type { Workspace, Guidance } from './workspace-strings';
/** Ein Menuepunkt: sein Buchstaben-Kuerzel und der Rest des Wortes. */
@@ -145,6 +146,7 @@ export interface AtlasChromeProps {
/** Persistent code context, shared by the Explore sidebar and chat column. */
selectionInspector?: ReactNode;
readerActions?: ReactNode;
+ readerDetails?: ReactNode;
onOpenSystem?: () => void;
daemonState?: 'connected' | 'disconnected' | 'checking';
globalOverlay?: ReactNode;
@@ -153,7 +155,6 @@ export interface AtlasChromeProps {
workspacePanel?: ReactNode;
workspaceStatus?: ReactNode;
guidance?: Guidance;
- onGuidanceChange?: (guidance: Guidance) => void;
/** Versions-Chip, zur Buildzeit injiziert. Nur die Fassung, ohne Zusatz. */
version: string;
/**
@@ -534,7 +535,11 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
*/
const [commandFocused, setCommandFocused] = useState(false);
const [chatWidth, setChatWidth] = useState(420);
- const [graphHeight, setGraphHeight] = useState(380);
+ const [graphShare, setGraphShare] = useState(1 / 3);
+ const [chatColumnHeight, setChatColumnHeight] = useState(600);
+ const chatColumn = useRef<HTMLDivElement>(null);
+ const graphSpace = Math.max(1, chatColumnHeight - 8);
+ const graphHeight = graphSpace * graphShare;
const [searchOpen, setSearchOpen] = useState(false);
const searchDialog = useRef<HTMLDialogElement>(null);
const searchButton = useRef<HTMLButtonElement>(null);
@@ -565,8 +570,19 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
element.className = 'atlas-galaxy-mount';
return element;
});
- const graphBelowChat = props.chatOpen === true &&
- (props.workspace ?? 'explore') === 'explore' && props.galaxy !== undefined;
+ const explorerDock = isExplore && !hasInspector && props.chatDock !== undefined && props.galaxy !== undefined;
+ const showChatColumn = props.chatOpen === true || explorerDock;
+ const graphBelowChat = (props.chatOpen === true || explorerDock) && isExplore && props.galaxy !== undefined;
+ useLayoutEffect(() => {
+ const element = chatColumn.current;
+ if (!element || !showChatColumn) return;
+ const measure = () => { if (element.clientHeight > 0) setChatColumnHeight(element.clientHeight); };
+ measure();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [showChatColumn]);
useLayoutEffect(() => {
const host = graphBelowChat ? chatGalaxyHost.current : inlineGalaxyHost.current;
if (host !== null && galaxyMount !== null) host.appendChild(galaxyMount);
@@ -630,7 +646,7 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
*/
const zones = props.zones ?? LAYOUT_DEFAULT;
const hasSide =
- hasInspector || props.twin !== undefined || props.galaxy !== undefined || props.llm !== undefined;
+ hasInspector || props.twin !== undefined || (props.galaxy !== undefined && !graphBelowChat) || props.llm !== undefined;
const stopTabKeys = (event: KeyboardEvent<HTMLInputElement>): void => {
if (event.key === 'Escape') {
@@ -643,7 +659,7 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
};
return (
- <div className="atlas-shell" data-workspace={props.workspace ?? 'explore'} data-guidance={props.guidance ?? 'brief'} data-chat-open={props.chatOpen === true} data-has-status={props.workspaceStatus !== undefined}>
+ <div className="atlas-shell" data-workspace={props.workspace ?? 'explore'} data-guidance={props.guidance ?? 'brief'} data-chat-open={showChatColumn} data-has-status={props.workspaceStatus !== undefined}>
<header className="atlas-header" data-testid="atlas-header">
<h1 className="atlas-brand">{messages.app.brand}</h1>
<span className="atlas-version" data-testid="atlas-version">
@@ -697,91 +713,7 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
aria-expanded={searchOpen} onClick={openSearch}>
{workspaceStrings.search}<kbd>{workspaceStrings.searchShortcut}</kbd>
</button>
- <details className="atlas-tools-menu" onClick={(event) => {
- if ((event.target as HTMLElement).closest('button')) event.currentTarget.open = false;
- }} onKeyDown={(event) => {
- if (event.key === 'Escape') { event.currentTarget.open = false; event.currentTarget.querySelector('summary')?.focus(); }
- }}>
- <summary>{workspaceStrings.tools}</summary>
- <nav className="atlas-menu" data-testid="atlas-menu" aria-label={messages.menu.ariaLabel}>
- {MENU_ITEMS.map((item) => {
- const wiring = props.menus?.[item.key];
- return wiring === undefined ? null : (
- <span className="atlas-menu-group" key={item.key}>
- <Hint name={`menu-${item.key}`} text={wiring.title}>
- <button
- type="button"
- className="atlas-menu-item"
- data-state={wiring.state}
- data-menu={item.key}
- data-testid="atlas-menu-item"
- aria-pressed={wiring.state === 'on'}
- onClick={wiring.onSelect}
- >
- <span className="atlas-menu-key">[{item.key}]</span>
- {item.rest}
- </button>
- </Hint>
- {(wiring.extras ?? [])
- .filter((extra) => extra.key !== 'bug' && extra.key !== 'impact')
- .map((extra) => {
- const parts = splitMenuLabel(extra.label);
- return (
- <Hint
- key={extra.key}
- name={`menu-${item.key}-${extra.key}`}
- text={extra.title}
- >
- <button
- type="button"
- className="atlas-menu-item"
- /*
- * `off` und nicht ein dritter
- * Wert: ein Eintrag der
- * Atlas-Zeile schaltet eine
- * Flaeche auf, die beim Zeichnen
- * der Zeile noch zu ist. `on`
- * waere die Behauptung, sie
- * stuende schon da.
- */
- data-state="off"
- data-menu={`${item.key}-${extra.key}`}
- data-testid="atlas-menu-item"
- onClick={extra.onSelect}
- >
- {parts.key.length > 0 && (
- <span className="atlas-menu-key">[{parts.key}]</span>
- )}
- {parts.rest}
- </button>
- </Hint>
- );
- })}
- </span>
- );
- })}
- {/*
- * Was die Klammer bedeutet, in der Zeile selbst.
- *
- * Seit dem 2026-08-29 gilt ein Menuebuchstabe nur mit
- * Alt/Option (src/app/keyboard.ts nennt den Grund: blanke
- * Buchstaben gehoeren dem Tippen). Ein `[a]` ohne diese
- * Angabe waere genau die Sorte Versprechen, die dieser
- * Zyklus aus der Zeile entfernt hat.
- */}
- <span className="atlas-menu-legend" data-testid="atlas-menu-legend">
- {messages.menu.legend}
- </span>
- </nav>
- </details>
- {props.onGuidanceChange !== undefined && (
- <select className="atlas-guidance" aria-label={workspaceStrings.guidance}
- value={props.guidance ?? 'brief'}
- onChange={(event) => props.onGuidanceChange?.(event.target.value as Guidance)}>
- <option value={workspaceStrings.briefValue}>{workspaceStrings.brief}</option>
- <option value={workspaceStrings.explainedValue}>{workspaceStrings.explained}</option>
- </select>
- )}
+ <GraphEdgeControls />
<div className="atlas-chips">
{props.chips.filter(chip => props.projectSwitcher === undefined || chip.label !== messages.statusbar.chipProject).map((chip) => (
<ChipView key={chip.label} chip={chip} />
@@ -842,6 +774,7 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
)}
{props.readerActions !== undefined && <div className="atlas-reader-actions">{props.readerActions}</div>}
</div>
+ {props.readerDetails && <section className="atlas-reader-details" aria-label={workspaceStrings.codeDetails}>{props.readerDetails}</section>}
{props.coverageNote !== undefined && (
<p
className="atlas-coverage-note"
@@ -883,15 +816,15 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
</div>
<main className="atlas-alternate-workspace" hidden={props.workspace === undefined || props.workspace === 'explore' || props.workspace === 'galaxy'}>{props.workspacePanel}</main>
</div>
- {props.chatOpen === true && <Splitter testId="atlas-split-chat" orientation="vertical" label={workspaceStrings.chatWidth} value={chatWidth}
+ {showChatColumn && <Splitter testId="atlas-split-chat" orientation="vertical" label={workspaceStrings.chatWidth} value={chatWidth}
min={300} max={600} invert onChange={setChatWidth} onReset={() => setChatWidth(420)} />}
- <div className="atlas-chat-column" hidden={props.chatOpen !== true} data-graph={graphBelowChat} data-selection-inspector={inspectorAboveChat}
- style={{ '--atlas-chat-graph-height': `${graphHeight}px` } as CSSProperties}>
+ <div ref={chatColumn} className="atlas-chat-column" hidden={!showChatColumn} data-graph={graphBelowChat} data-selection-inspector={inspectorAboveChat} data-chat-expanded={props.chatOpen === true}
+ style={{ '--atlas-chat-graph-height': `${graphHeight}px`, '--atlas-chat-fraction': `${1 - graphShare}fr`, '--atlas-graph-fraction': `${graphShare}fr` } as CSSProperties}>
<div ref={chatInspectorHost} className="atlas-selection-host" hidden={!inspectorAboveChat} />
{props.chatDock}
- {graphBelowChat && <Splitter testId="atlas-split-chat-graph" orientation="horizontal"
- label={workspaceStrings.chatGraphHeight} value={graphHeight} min={320} max={640} invert
- onChange={setGraphHeight} onReset={() => setGraphHeight(380)} />}
+ {graphBelowChat && props.chatOpen === true && <Splitter testId="atlas-split-chat-graph" orientation="horizontal"
+ label={workspaceStrings.chatGraphHeight} value={graphHeight} min={graphSpace / 3} max={graphSpace * 0.85} invert
+ onChange={value => setGraphShare(Math.min(0.85, Math.max(1 / 3, value / graphSpace)))} onReset={() => setGraphShare(1 / 3)} />}
<div ref={chatGalaxyHost} className="atlas-galaxy-host" hidden={!graphBelowChat} />
</div>
{galaxyMount !== null && createPortal(props.galaxy, galaxyMount)}
@@ -988,6 +921,76 @@ export default function AtlasChrome(props: AtlasChromeProps): JSX.Element {
<span className="atlas-command-hint">{props.commandHint}</span>
</div>
+ <nav className="atlas-menu" data-testid="atlas-menu" onClick={event => { if ((event.target as HTMLElement).closest('button')) closeSearch(); }} aria-label={messages.menu.ariaLabel}>
+ {MENU_ITEMS.map((item) => {
+ const wiring = props.menus?.[item.key];
+ return wiring === undefined ? null : (
+ <span className="atlas-menu-group" key={item.key}>
+ <Hint name={`menu-${item.key}`} text={wiring.title}>
+ <button
+ type="button"
+ className="atlas-menu-item"
+ data-state={wiring.state}
+ data-menu={item.key}
+ data-testid="atlas-menu-item"
+ aria-pressed={wiring.state === 'on'}
+ onClick={wiring.onSelect}
+ >
+ <span className="atlas-menu-key">[{item.key}]</span>
+ {item.rest}
+ </button>
+ </Hint>
+ {(wiring.extras ?? [])
+ .filter((extra) => extra.key !== 'bug' && extra.key !== 'impact')
+ .map((extra) => {
+ const parts = splitMenuLabel(extra.label);
+ return (
+ <Hint
+ key={extra.key}
+ name={`menu-${item.key}-${extra.key}`}
+ text={extra.title}
+ >
+ <button
+ type="button"
+ className="atlas-menu-item"
+ /*
+ * `off` und nicht ein dritter
+ * Wert: ein Eintrag der
+ * Atlas-Zeile schaltet eine
+ * Flaeche auf, die beim Zeichnen
+ * der Zeile noch zu ist. `on`
+ * waere die Behauptung, sie
+ * stuende schon da.
+ */
+ data-state="off"
+ data-menu={`${item.key}-${extra.key}`}
+ data-testid="atlas-menu-item"
+ onClick={extra.onSelect}
+ >
+ {parts.key.length > 0 && (
+ <span className="atlas-menu-key">[{parts.key}]</span>
+ )}
+ {parts.rest}
+ </button>
+ </Hint>
+ );
+ })}
+ </span>
+ );
+ })}
+ {/*
+ * Was die Klammer bedeutet, in der Zeile selbst.
+ *
+ * Seit dem 2026-08-29 gilt ein Menuebuchstabe nur mit
+ * Alt/Option (src/app/keyboard.ts nennt den Grund: blanke
+ * Buchstaben gehoeren dem Tippen). Ein `[a]` ohne diese
+ * Angabe waere genau die Sorte Versprechen, die dieser
+ * Zyklus aus der Zeile entfernt hat.
+ */}
+ <span className="atlas-menu-legend" data-testid="atlas-menu-legend">
+ {messages.menu.legend}
+ </span>
+ </nav>
</dialog>
<div className="atlas-statusbar" data-testid="atlas-statusbar">
diff --git a/graph-ui/src/app/AtlasTree.test.tsx b/graph-ui/src/app/AtlasTree.test.tsx
index 2b85f45ec..acb4915fd 100644
--- a/graph-ui/src/app/AtlasTree.test.tsx
+++ b/graph-ui/src/app/AtlasTree.test.tsx
@@ -9,12 +9,15 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import AtlasTree, { twistyFor } from './AtlasTree';
+import AtlasTree, { AtlasTreeIndexDetails, twistyFor } from './AtlasTree';
import type { AtlasTreeProps } from './AtlasTree';
import type { TreeRow } from './tree-model';
let container: HTMLDivElement;
let root: Root;
+async function renderIndexDetails(details: AtlasTreeProps) {
+ await act(async () => root.render(<AtlasTreeIndexDetails {...details} />));
+}
beforeEach(() => {
(globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
@@ -142,9 +145,9 @@ describe('AtlasTree', () => {
});
it('zeigt die Herkunftszeile des Baums und faerbt eine Abwesenheit', async () => {
- await render(props());
+ await renderIndexDetails(props());
expect(container.querySelector('.atlas-tree-note')?.textContent).toContain('/api/tree');
- await render(props({ note: 'tree unavailable: HTTP 404', noteIsAbsence: true }));
+ await renderIndexDetails(props({ note: 'tree unavailable: HTTP 404', noteIsAbsence: true }));
expect(container.querySelector('.atlas-tree-note')?.getAttribute('data-state')).toBe('absent');
});
});
@@ -231,7 +234,7 @@ describe('AtlasTree und die Coverage-Stufen', () => {
});
it('erklaert in der Legende auch den Gutfall, mit seinem Punkt', async () => {
- await render(props({ rows: coveredRows }));
+ await renderIndexDetails(props({ rows: coveredRows }));
const good = container.querySelector('[data-testid="atlas-tree-legend-entry"][data-coverage="indexed"]');
expect(good).not.toBeNull();
expect(good?.querySelector('[data-testid="atlas-tree-legend-dot"]')?.getAttribute('data-tone'))
@@ -264,7 +267,7 @@ describe('AtlasTree und die Coverage-Stufen', () => {
});
it('zeigt eine Legende mit den vorkommenden Stufen und dem Quellensatz', async () => {
- await render(props({ rows: coveredRows }));
+ await renderIndexDetails(props({ rows: coveredRows }));
const legend = container.querySelector('[data-testid="atlas-tree-legend"]');
expect(legend).not.toBeNull();
const entries = [...container.querySelectorAll('[data-testid="atlas-tree-legend-entry"]')]
@@ -275,14 +278,14 @@ describe('AtlasTree und die Coverage-Stufen', () => {
});
it('erklaert keine Stufe, die im Baum nicht vorkommt', async () => {
- await render(props({ rows: [withCoverage(file('a.ts'), 'indexed')] }));
+ await renderIndexDetails(props({ rows: [withCoverage(file('a.ts'), 'indexed')] }));
const entries = [...container.querySelectorAll('[data-testid="atlas-tree-legend-entry"]')]
.map((entry) => entry.getAttribute('data-coverage'));
expect(entries).toEqual(['indexed']);
});
it('zeigt jede gekappte Liste als eigene ehrliche Zeile', async () => {
- await render(props({
+ await renderIndexDetails(props({
rows: coveredRows,
truncations: ['the server cut the skipped list: 812 recorded, fewer listed'],
}));
diff --git a/graph-ui/src/app/AtlasTree.tsx b/graph-ui/src/app/AtlasTree.tsx
index ed7554975..ae9d7eeb7 100644
--- a/graph-ui/src/app/AtlasTree.tsx
+++ b/graph-ui/src/app/AtlasTree.tsx
@@ -160,9 +160,6 @@ export default function AtlasTree(props: AtlasTreeProps): JSX.Element {
}
}, [props.cursor, props.rows.length]);
- const states = shownStates(props.rows);
- const markedFolders = props.rows.some((row) => row.kind === 'dir' && coverageOf(row) !== 'indexed');
-
return (
<aside className="atlas-tree" data-testid="atlas-tree">
<h2 className="atlas-tree-title">{messages.explorer.title}</h2>
@@ -249,20 +246,26 @@ export default function AtlasTree(props: AtlasTreeProps): JSX.Element {
);
})}
</ul>
+ </aside>
+ );
+}
+
+/** Coverage metadata belongs in the Coverage workspace, separate from file navigation. */
+export function AtlasTreeIndexDetails(props: Pick<AtlasTreeProps, 'rows' | 'note' | 'noteIsAbsence' | 'truncations'>): JSX.Element {
+ const states = shownStates(props.rows);
+ const markedFolders = props.rows.some((row) => row.kind === 'dir' && coverageOf(row) !== 'indexed');
+ return <section aria-label={workspaceStrings.indexInventory}>
{props.note.length > 0 && (
- <details className="atlas-evidence-details" open={props.explained || props.noteIsAbsence}>
- <summary>{workspaceStrings.coverage}</summary>
<p className="atlas-tree-note" data-state={props.noteIsAbsence === true ? 'absent' : 'present'}>
{props.note}
</p>
- </details>
)}
{(props.truncations ?? []).map((line) => (
<p className="atlas-tree-note" data-state="absent" data-testid="atlas-tree-truncation" key={line}>
{line}
</p>
))}
- <div className="atlas-tree-legend atlas-guidance-note" data-testid="atlas-tree-legend">
+ <div className="atlas-tree-legend" data-testid="atlas-tree-legend">
{/*
* Die Legende erklaert auch den Gutfall.
*
@@ -298,6 +301,5 @@ export default function AtlasTree(props: AtlasTreeProps): JSX.Element {
{COVERAGE_SOURCE_NOTE}
</span>
</div>
- </aside>
- );
+ </section>;
}
diff --git a/graph-ui/src/app/WelcomePanel.test.tsx b/graph-ui/src/app/WelcomePanel.test.tsx
index 83dc16a1d..f5b2cb307 100644
--- a/graph-ui/src/app/WelcomePanel.test.tsx
+++ b/graph-ui/src/app/WelcomePanel.test.tsx
@@ -10,8 +10,8 @@ it('allows first use without starting or setting up browser AI', async () => {
const root = createRoot(host);
const onContinue = vi.fn(), onLocalAi = vi.fn();
try {
- await act(async () => root.render(<WelcomePanel workspace="architecture" guidance="brief"
- onWorkspace={vi.fn()} onGuidance={vi.fn()} onContinue={onContinue} onLocalAi={onLocalAi} />));
+ await act(async () => root.render(<WelcomePanel workspace="architecture"
+ onWorkspace={vi.fn()} onContinue={onContinue} onLocalAi={onLocalAi} />));
expect(onLocalAi).not.toHaveBeenCalled();
expect(document.activeElement).toBe(host.querySelector('.cbm-primary'));
await act(async () => host.querySelector<HTMLButtonElement>('.cbm-primary')!.click());
diff --git a/graph-ui/src/app/WelcomePanel.tsx b/graph-ui/src/app/WelcomePanel.tsx
index 4d968f9a0..5b3e41e43 100644
--- a/graph-ui/src/app/WelcomePanel.tsx
+++ b/graph-ui/src/app/WelcomePanel.tsx
@@ -1,11 +1,11 @@
import { useEffect, useRef } from 'react';
import type { JSX } from 'react';
-import type { Workspace, Guidance } from './workspace-strings';
+import type { Workspace } from './workspace-strings';
import { workspaceStrings as s } from './workspace-strings';
interface Props {
- workspace: Workspace; guidance: Guidance;
- onWorkspace: (workspace: Workspace) => void; onGuidance: (guidance: Guidance) => void;
+ workspace: Workspace;
+ onWorkspace: (workspace: Workspace) => void;
onContinue: () => void; onLocalAi: () => void;
}
export default function WelcomePanel(props: Props): JSX.Element {
@@ -33,11 +33,6 @@ export default function WelcomePanel(props: Props): JSX.Element {
<strong>{item.label}</strong><span>{s.descriptions[item.id]}</span>
</button>)}
</div>
- <label className="cbm-welcome-guidance">{s.guidance}
- <select value={props.guidance} onChange={(event) => props.onGuidance(event.target.value as Guidance)}>
- <option value="brief">{s.brief}</option><option value="explained">{s.explained}</option>
- </select>
- </label>
<p className="cbm-welcome-note">{s.changeLater}</p>
<footer><button type="button" onClick={props.onLocalAi}>{s.localAi}</button>
<button type="button" className="cbm-primary" autoFocus onClick={props.onContinue}>{s.start}</button></footer>
diff --git a/graph-ui/src/app/workspace-navigation.test.tsx b/graph-ui/src/app/workspace-navigation.test.tsx
index 6a583e600..aed17a191 100644
--- a/graph-ui/src/app/workspace-navigation.test.tsx
+++ b/graph-ui/src/app/workspace-navigation.test.tsx
@@ -29,7 +29,7 @@ it('offers the Galaxy workspace and reports the selected task', async () => {
workspace: 'explore', onWorkspaceChange,
}} />));
const tabs = [...host.querySelectorAll<HTMLButtonElement>('[data-workspace-tab]')];
- expect(tabs.map(tab => tab.textContent?.trim())).toEqual(['Explore', 'Galaxy', 'Architecture', 'Agents', 'System']);
+ expect(tabs.map(tab => tab.textContent?.trim())).toEqual(['Explore', 'Galaxy', 'Architecture', 'Agents', 'Coverage', 'System']);
expect(tabs[0].getAttribute('aria-selected')).toBe('true');
await act(async () => tabs[1].click());
expect(onWorkspaceChange).toHaveBeenCalledWith('galaxy');
@@ -121,7 +121,7 @@ it('hides selected-code context outside Explore without losing its state', async
const inspector = <input aria-label="Pinned code context" defaultValue="keep context" />;
await act(async () => root.render(<AtlasChrome {...props} selectionInspector={inspector} chatOpen workspace="explore" />));
const panel = host.querySelector('[aria-label="Pinned code context"]');
- for (const workspace of ['galaxy', 'architecture', 'agents', 'system'] as const) {
+ for (const workspace of ['galaxy', 'architecture', 'agents', 'coverage', 'system'] as const) {
await act(async () => root.render(<AtlasChrome {...props} selectionInspector={inspector} chatOpen workspace={workspace} />));
expect(host.querySelector('[aria-label="Pinned code context"]')).toBe(panel);
expect(panel?.closest('[hidden]')).not.toBeNull();
@@ -201,18 +201,11 @@ it('keeps the reader mounted while showing a different workspace', async () => {
expect(host.querySelector('[data-testid="atlas-exploration-workspace"]')?.hasAttribute('hidden')).toBe(true);
});
-it('changes explanation depth separately from the workspace', async () => {
- const onGuidanceChange = vi.fn();
- await act(async () => root.render(<AtlasChrome {...makeProps()} {...{
- workspace: 'explore', onWorkspaceChange: vi.fn(), guidance: 'brief', onGuidanceChange,
- }} />));
- const choice = host.querySelector<HTMLSelectElement>('[aria-label="Explanation depth"]');
- expect(choice).not.toBeNull();
- await act(async () => {
- choice!.value = 'explained';
- choice!.dispatchEvent(new Event('change', { bubbles: true }));
- });
- expect(onGuidanceChange).toHaveBeenCalledWith('explained');
+it('keeps tools and explanation-depth controls out of the header', async () => {
+ await act(async () => root.render(<AtlasChrome {...makeProps()} workspace="explore" />));
+ const header = host.querySelector('[data-testid="atlas-header"]')!;
+ expect(header.querySelector('.atlas-tools-menu')).toBeNull();
+ expect(header.querySelector('[aria-label="Explanation depth"]')).toBeNull();
});
it('keeps pending results visible until activation succeeds and refocuses an open search', async () => {
@@ -229,3 +222,24 @@ it('keeps pending results visible until activation succeeds and refocuses an ope
await act(async () => window.dispatchEvent(new Event('cbm:close-command-search')));
expect(dialog.open).toBe(false);
});
+
+
+it('keeps Explorer graph and chat draft mounted when chat folds', async () => {
+ const props = makeProps();
+ const galaxy = <section className="atlas-galaxy"><canvas /></section>;
+ const chat = <input aria-label="Folded chat draft" defaultValue="keep my question" />;
+ const render = (chatOpen: boolean) => root.render(<AtlasChrome {...props} workspace="explore" galaxy={galaxy} chatDock={chat} chatOpen={chatOpen} />);
+ await act(async () => render(false));
+ const canvas = host.querySelector('canvas');
+ const draft = host.querySelector('[aria-label="Folded chat draft"]');
+ expect(canvas?.closest('.atlas-chat-column')?.hasAttribute('hidden')).toBe(false);
+ expect(canvas?.closest('[hidden]')).toBeNull();
+ expect(host.querySelector('[data-testid="atlas-split-chat-graph"]')).toBeNull();
+ await act(async () => render(true));
+ expect(host.querySelector('canvas')).toBe(canvas);
+ expect(host.querySelector('[data-testid="atlas-split-chat-graph"]')).not.toBeNull();
+ await act(async () => render(false));
+ expect(host.querySelector('canvas')).toBe(canvas);
+ expect(host.querySelector('[aria-label="Folded chat draft"]')).toBe(draft);
+ expect(canvas?.closest('[hidden]')).toBeNull();
+});
diff --git a/graph-ui/src/app/workspace-strings.ts b/graph-ui/src/app/workspace-strings.ts
index 2446c7a32..2e35003fc 100644
--- a/graph-ui/src/app/workspace-strings.ts
+++ b/graph-ui/src/app/workspace-strings.ts
@@ -1,4 +1,4 @@
-export type Workspace = 'explore' | 'galaxy' | 'architecture' | 'agents' | 'system';
+export type Workspace = 'explore' | 'galaxy' | 'architecture' | 'agents' | 'coverage' | 'system';
export type Guidance = 'brief' | 'explained';
export const workspaceStrings = {
@@ -8,6 +8,7 @@ export const workspaceStrings = {
{ id: 'galaxy' as const, label: 'Galaxy' },
{ id: 'architecture' as const, label: 'Architecture' },
{ id: 'agents' as const, label: 'Agents' },
+ { id: 'coverage' as const, label: 'Coverage' },
{ id: 'system' as const, label: 'System' },
],
tools: 'Tools',
@@ -37,15 +38,19 @@ export const workspaceStrings = {
galaxy: 'Explore the whole graph and its coverage shadow.',
architecture: 'See modules, dependencies, and entry points.',
agents: 'Inspect recorded activity and touched code.',
+ coverage: 'Inspect indexed paths, exclusions, and parser gaps.',
system: 'Monitor the daemon, indexes, and logs.',
},
- changeLater: 'Switch workspaces and explanation depth at any time. Every feature stays available.',
+ changeLater: 'Switch workspaces at any time.',
localAi: 'Set up browser AI',
browserAi: 'Chat',
daemon: 'Daemon',
daemonNavigation: (state: string) => `Open System: daemon ${state}`,
chatWidth: 'Width of local chat',
askSelection: 'Ask about selection',
+ assessImpact: 'Assess impact',
+ codeDetails: 'Code details',
+ indexInventory: 'Index inventory and legend',
selectionImpact: 'Assess change impact',
changeAnalysis: 'Change analysis',
sourceOutsideSnapshot: 'This file is outside the loaded index snapshot.',
diff --git a/graph-ui/src/architecture/ArchitecturePanel.test.tsx b/graph-ui/src/architecture/ArchitecturePanel.test.tsx
index 52419d729..b198a0ed5 100644
--- a/graph-ui/src/architecture/ArchitecturePanel.test.tsx
+++ b/graph-ui/src/architecture/ArchitecturePanel.test.tsx
@@ -6,6 +6,8 @@ import ArchitecturePanel from './ArchitecturePanel';
import type { ArchitecturePanelProps } from './ArchitecturePanel';
import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
import { architectureText as text } from './strings';
+vi.mock('./ArchitectureScene', () => ({ ArchitectureScene: () => <div data-testid="scene" /> }));
+vi.mock('./ContainerMap', () => ({ default: () => <div data-testid="container-map" /> }));
let container: HTMLDivElement;
let root: Root;
@@ -64,15 +66,41 @@ async function filter(value: string): Promise<void> {
}
describe('architecture workspace', () => {
- it('keeps a spatial exploration surface across architecture, dependencies, routes and entry points', async () => {
+ it('loads system structure independently when the legacy summary is unavailable', async () => {
+ const loader = vi.fn().mockResolvedValue({ status: 'failed', generation: 'g1', error: 'System analysis service unavailable.' });
+ await render({ overview: undefined, loading: true, error: 'Legacy summary failed.', systemArchitectureLoader: loader });
+ await click('[data-view="structure"]');
+ await act(async () => { await vi.dynamicImportSettled(); });
+ expect(loader).toHaveBeenCalledWith({ project: 'sample', entryNodeId: undefined }, expect.any(AbortSignal));
+ expect(container.textContent).not.toContain('Legacy summary failed.');
+ expect(container.textContent).not.toContain(text.loading);
+ expect(container.querySelector('[data-testid="atlas-architecture"]')?.getAttribute('aria-busy')).toBe('false');
+ expect(container.textContent).toContain('System analysis service unavailable.');
+ });
+
+ it('adds system views while retaining the repository views and entry points inside Overview', 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']) {
+ expect([...container.querySelectorAll('[data-view]')].map(node => node.getAttribute('data-view'))).toEqual(['overview', 'routes', 'hotspots', 'structure', 'behavior']);
+ for (const view of ['hotspots', 'overview']) {
await click(`[data-view="${view}"]`);
expect(container.querySelector('[data-testid="spatial-architecture"]')).toBe(surface);
expect(container.querySelector('[aria-label="Architecture relationships"]')).not.toBeNull();
}
+ await click('[data-view="routes"]');
+ await act(async () => { await vi.dynamicImportSettled(); });
+ expect(container.querySelector('[data-testid="container-map"]')).not.toBeNull();
+ const endpoints = [...container.querySelectorAll('[aria-label="Routes perspective"] button')].find(button => button.textContent === 'Endpoints')!;
+ await act(async () => (endpoints as HTMLButtonElement).click());
+ expect(container.querySelector('[data-testid="container-map"]')).toBeNull();
+ expect(container.querySelector('[data-testid="spatial-architecture"]')).not.toBeNull();
+ expect(container.querySelector('[aria-label="Architecture relationships"]')).not.toBeNull();
+ await click('[data-view="overview"]');
+ const entry = [...container.querySelectorAll('[aria-label="Overview mode"] button')].find(button => button.textContent === 'Entry points')!;
+ await act(async () => (entry as HTMLButtonElement).click());
+ expect(container.querySelector('[data-view="overview"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(container.querySelector('select[aria-label="Entry point"]')).not.toBeNull();
});
it('keeps module, layer, community and indexed-file evidence available in Overview', async () => {
@@ -88,7 +116,6 @@ describe('architecture workspace', () => {
it('opens a source location at the exact provider line and leaves unknown locations unlinked', async () => {
const onNavigate = vi.fn();
await render({ onNavigate });
- await click('[data-view="entryPoints"]');
await click('button[aria-label="Open source: start"]');
expect(onNavigate).toHaveBeenCalledWith('src/api.ts', 9, 'start');
const missing = [...container.querySelectorAll('tbody tr')].find(row => row.textContent?.includes('noLocation'));
@@ -126,25 +153,24 @@ describe('architecture workspace', () => {
it('links the module card and keyboard-accessible dependency map to the same filter', async () => {
await render();
await click('button[aria-label="Show relationships for api"]');
- expect(container.querySelector('[data-view="dependencies"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(container.querySelector('[data-view="overview"]')?.getAttribute('aria-pressed')).toBe('true');
const target = container.querySelector<SVGGElement>('g[aria-label="Show relationships for storage"]')!;
expect(target.getAttribute('tabindex')).toBe('0');
await act(async () => target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
expect(container.querySelector<HTMLInputElement>('input')?.value).toBe('storage');
- expect(container.querySelectorAll('tbody tr')).toHaveLength(1);
+ expect(container.querySelectorAll('[data-testid="architecture-dependency-details"] tbody tr')).toHaveLength(1);
});
it('bounds the diagram while keeping every reported relationship reachable', async () => {
const data = overview();
data.boundaries = Array.from({ length: 30 }, (_, index) => ({ from: `module-${index}`, to: 'core', callCount: index + 1 }));
await render({ overview: data });
- await click('[data-view="dependencies"]');
- expect(container.querySelectorAll('svg g[role="button"]')).toHaveLength(8);
+ expect(container.querySelectorAll('[data-testid="architecture-dependency-details"] svg g[role="button"]')).toHaveLength(8);
expect(container.textContent).toContain(text.mapLimit(8, 23));
- expect(container.querySelectorAll('tbody tr')).toHaveLength(24);
- const more = [...container.querySelectorAll('button')].find(button => button.textContent === text.showMore)!;
+ expect(container.querySelectorAll('[data-testid="architecture-dependency-details"] tbody tr')).toHaveLength(24);
+ const more = [...container.querySelectorAll<HTMLButtonElement>('[data-testid="architecture-dependency-details"] button')].find(button => button.textContent === text.showMore)!;
await act(async () => more.click());
- expect(container.querySelectorAll('tbody tr')).toHaveLength(30);
+ expect(container.querySelectorAll('[data-testid="architecture-dependency-details"] tbody tr')).toHaveLength(30);
});
it('distinguishes missing hotspot measurements from a measured zero', async () => {
diff --git a/graph-ui/src/architecture/ArchitecturePanel.tsx b/graph-ui/src/architecture/ArchitecturePanel.tsx
index d52f82593..dbeb4c24f 100644
--- a/graph-ui/src/architecture/ArchitecturePanel.tsx
+++ b/graph-ui/src/architecture/ArchitecturePanel.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useId, useMemo, useState } from 'react';
+import { lazy, Suspense, useEffect, useId, useMemo, useState } from 'react';
import type { JSX, ReactNode } from 'react';
import type { ArchitectureBoundary, ArchitectureHotspot, ArchitectureOverviewDto } from '../core/intelligence-provider';
import {
@@ -12,16 +12,24 @@ import RepositoryMapView, { RelationshipEvidence } from './RepositoryMap';
import type { RepositoryMapProps } from './RepositoryMap';
import { repositoryMap } from './repository-map';
import SpatialArchitecture from './SpatialArchitecture';
+import RoutesArchitecture from './RoutesArchitecture';
+import type { CoverageIndex } from '../app/tree-model';
+import type { SystemArchitectureLoader } from './system-architecture-source';
+
+const SystemArchitecture = lazy(() => import('./SystemArchitecture'));
export interface ArchitecturePanelProps extends Pick<RepositoryMapProps, 'graph' | 'selection' | 'selectionPanel' | 'onSelect' | 'graphNote' | 'readSource'> {
projectName: string;
graphGeneration?: string;
active?: boolean;
+ coverage?: CoverageIndex;
overview?: ArchitectureOverviewDto;
loading?: boolean;
error?: string;
onRefresh?: () => void;
+ onClearSelection?: () => void;
onProjectWalk?: () => void;
+ systemArchitectureLoader?: SystemArchitectureLoader;
/** The declaration line is 1-based, as returned by the provider. */
onNavigate: (filePath: string, line?: number, name?: string) => void;
}
@@ -238,7 +246,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, active = true }: ArchitecturePanelProps): JSX.Element {
+function ArchitectureWorkspace({ projectName, overview, loading = false, error, onRefresh, onProjectWalk, onNavigate, graph, selection, selectionPanel, onSelect, onClearSelection, graphNote, graphGeneration, readSource, active = true, coverage, systemArchitectureLoader }: ArchitecturePanelProps): JSX.Element {
const storage = useMemo(browserStorage, []);
const [config, setConfig] = useState(() => readArchitectureConfig(storage, projectName));
const [saved, setSaved] = useState(true);
@@ -246,17 +254,18 @@ function ArchitectureWorkspace({ projectName, overview, loading = false, error,
// A cached summary from another project must never appear here.
const data = overview?.projectName && overview.projectName !== projectName ? undefined : overview;
const filtered = useMemo(() => data ? matchingArchitecture(data, config.filter) : undefined, [data, config.filter]);
- const onGroup = (group: string) => setConfig({ view: 'dependencies', filter: group });
+ const onGroup = (group: string) => setConfig({ view: 'overview', filter: group });
const empty = config.filter.trim() ? text.noMatches : text.noData;
const ready = Boolean(data && filtered && !loading && !error && projectName);
- return <section className="atlas-architecture" data-testid="atlas-architecture" aria-label={text.title} aria-busy={loading}>
- <header className="atlas-arch-heading"><div><span className="atlas-arch-project">{projectName}</span>
- <h1>{text.title}</h1><p>{text.subtitle}</p></div>
+ const systemView = config.view === 'structure' || config.view === 'behavior' ? config.view : undefined;
+ const SpatialView = config.view === 'routes' ? RoutesArchitecture : SpatialArchitecture;
+ return <section className="atlas-architecture" data-testid="atlas-architecture" data-system-view={systemView} aria-label={text.title} aria-busy={!systemView && loading}>
+ <header className="atlas-arch-heading"><span className="atlas-arch-project">{projectName}</span>
<div className="repo-map-directions">{onProjectWalk && <button onClick={onProjectWalk} disabled={!projectName}>{text.importWalk}</button>}
- {onRefresh && <button className="atlas-arch-action" onClick={onRefresh} disabled={loading || !projectName}>{text.refresh}</button>}</div>
+ {onRefresh && !systemView && <button className="atlas-arch-action" onClick={onRefresh} disabled={loading || !projectName}>{text.refresh}</button>}</div>
</header>
<nav className="atlas-arch-tabs" aria-label={text.navigation}>{ARCHITECTURE_VIEWS.map(view =>
- <button className="atlas-arch-tab" key={view} aria-pressed={config.view === view} data-view={view}
+ <button className="atlas-arch-tab" key={view} aria-pressed={config.view === view || (view === 'overview' && ['dependencies', 'entryPoints'].includes(config.view))} data-view={view}
onClick={() => setConfig(current => ({ ...current, view }))}>{text.views[view]}</button>)}</nav>
<div className="atlas-arch-toolbar">
<label className="atlas-arch-filter"><svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><circle cx="6.5" cy="6.5" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.4" /><path d="m10 10 4 4" stroke="currentColor" strokeWidth="1.4" /></svg>
@@ -265,22 +274,28 @@ function ArchitectureWorkspace({ projectName, overview, loading = false, error,
</label><span className="atlas-arch-saved">{saved ? text.saved : text.sessionOnly}</span>
<button className="atlas-arch-action" onClick={() => setConfig({ ...DEFAULT_ARCHITECTURE_CONFIG })}>{text.reset}</button>
</div>
- {!projectName ? <Empty>{text.chooseProject}</Empty> : loading ? <div role="status"><Empty>{text.loading}</Empty></div>
+ {systemView && projectName ? <Suspense fallback={<div role="status"><Empty>Preparing system analysis…</Empty></div>}><SystemArchitecture
+ project={projectName} generation={graphGeneration} view={systemView} filter={config.filter} active={active}
+ graph={graph} onSelect={onSelect} onClearSelection={onClearSelection} onNavigate={onNavigate} loader={systemArchitectureLoader} /></Suspense> : null}
+ {!systemView && (!projectName ? <Empty>{text.chooseProject}</Empty> : loading ? <div role="status"><Empty>{text.loading}</Empty></div>
: 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>
+ : !data ? <Empty>{text.unavailable}</Empty> : null)}
+ {systemView && !projectName && <Empty>{text.chooseProject}</Empty>}
+ {!systemView && ready && data && graph && <SpatialView project={projectName} generation={graphGeneration} graph={graph} overview={data}
+ view={config.view === 'dependencies' || config.view === 'structure' || config.view === 'behavior' ? 'overview' : config.view} filter={config.filter} active={active}
+ graphNote={graphNote} coverage={coverage} onSelect={onSelect} onClearSelection={onClearSelection} selectionPanel={selectionPanel} onNavigate={onNavigate} onView={view => setConfig(current => ({ ...current, view: view === 'dependencies' ? 'overview' : view }))} />}
+ {!systemView && ready && data && filtered && <div className="atlas-arch-content" key={`${config.view}:${config.filter}:${graphGeneration ?? ""}`} data-testid="atlas-architecture-content">
+ <details open={!graph}><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 data-testid="architecture-dependency-details"><summary>Dependency details</summary><Dependencies data={filtered} empty={empty} onGroup={onGroup} graph={graph} onNavigate={onNavigate} /></details>
+ <details data-testid="architecture-entry-details"><summary>Entry-point source evidence</summary><Findings view="entryPoints" data={filtered} empty={empty} onNavigate={onNavigate} /></details>
<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>}
+ {!systemView && 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
index b54dc2eb3..4c7f9f27b 100644
--- a/graph-ui/src/architecture/ArchitectureScene.tsx
+++ b/graph-ui/src/architecture/ArchitectureScene.tsx
@@ -1,10 +1,15 @@
import { useEffect, useMemo, useRef, useState, type RefObject } from 'react';
-import { Canvas, useThree } from '@react-three/fiber';
+import { Canvas, useFrame, 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 { Box3, Color, CubicBezierCurve3, MOUSE, TOUCH, OrthographicCamera as ThreeOrthographicCamera, Quaternion, QuadraticBezierCurve3, Vector2, Vector3 } from 'three';
import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib';
-import type { SemanticEdge, SemanticGraph, SemanticNode } from './semantic-graph';
+import type { SemanticEdge, SemanticGraph, SemanticNode, SemanticPlatform } from './semantic-graph';
+import { languageColor, measureSourceNode, sourceBrickHeight, sourceLanguage, sourceNodeSizePercent, type SourceCatalog, type SourceMeasure } from './source-metrics';
+import { gravityPercent, gravityStrength, hotspotsForNode, type HotspotCatalog, type HotspotGroup } from './hotspot-map';
+import { edgeColor, isDirectedEdge } from '../graph/edge-style';
+import { EdgePulseLayer } from '../graph/EdgePulseLayer';
import './architecture-scene.css';
+import { useGraphBackgroundReset } from '../graph/useGraphBackgroundReset';
export interface ArchitectureSceneProps {
model: SemanticGraph;
@@ -12,58 +17,91 @@ export interface ArchitectureSceneProps {
selectedEdgeId?: string;
onSelect: (id: string) => void;
onSelectEdge: (id: string) => void;
+ onOpen?: (id: string) => void;
+ onClearSelection?: () => void;
active?: boolean;
planar?: boolean;
resetKey?: number;
+ catalog?: SourceCatalog;
+ heightMetric?: 'lines' | 'uniform';
+ colorMetric?: 'language' | 'kind';
+ hotspots?: HotspotCatalog;
+ showHotspots?: boolean;
+ adaptiveLabels?: boolean;
}
+interface RenderNode extends SemanticNode { height?: number; tint?: string; measure?: SourceMeasure; hotspot?: HotspotGroup; gravity?: number; sizePercent?: number; gravityPercent?: number }
+type RenderGraph = Omit<SemanticGraph, 'nodes'> & { nodes: RenderNode[] };
+
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];
+function dimensions(node: RenderNode): [number, number, number] {
+ if (node.footprint) return [node.footprint[0], node.height ?? 1.1, node.footprint[1]];
+ if (node.kind === 'area') return [12, node.height ?? 0.9, 8];
+ if (node.kind === 'file') return [5.5, node.height ?? 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 {
+function centerOf(node: RenderNode): 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;
+/** Folder containment is scenery, never an extra dependency or selectable symbol. */
+function FolderPlatform({ platform }: { platform: SemanticPlatform }) {
+ return <group position={platform.position}>
+ <mesh position={[0, -0.225, 0]} raycast={() => null}>
+ <boxGeometry args={[platform.width, 0.45, platform.depth]} />
+ <meshStandardMaterial color="#536977" roughness={0.95} transparent opacity={0.11 + platform.level * 0.015} depthWrite={false} />
+ <Edges color="#6e8a98" transparent opacity={0.3} />
+ </mesh>
+ <Html position={[-platform.width / 2 + 3, 0.12, platform.depth / 2 - 2]} zIndexRange={[5, 1]} style={{ pointerEvents: 'none' }}>
+ <span className="architecture-folder-label" data-folder-path={platform.path} data-level={platform.level}
+ data-position={platform.position.join(',')} data-width={platform.width} data-depth={platform.depth}
+ title={platform.path}>{platform.path ? platform.path.split('/').at(-1) : platform.label}</span>
+ </Html>
+ </group>;
+}
+
+function GravityWell({ node, floorY, dimmed }: { node: RenderNode; floorY: number; dimmed: boolean }) {
+ const strength = node.gravity ?? 0;
+ const radius = 1.2 + strength * 8.3;
+ const depth = 0.35 + strength * 6.65;
+ const profile = useMemo(() => [new Vector2(0.25, -depth), new Vector2(radius * 0.2, -depth * 0.85),
+ new Vector2(radius * 0.45, -depth * 0.35), new Vector2(radius * 0.7, -depth * 0.08), new Vector2(radius, 0)], [depth, radius]);
+ return <group position={[node.position[0], floorY - 0.1, node.position[2]]}>
+ <mesh raycast={() => null}><latheGeometry args={[profile, 24]} /><meshBasicMaterial color="#8e8270" wireframe transparent opacity={dimmed ? 0.025 : 0.1 + strength * 0.12} depthWrite={false} /></mesh>
+ {[0.45, 0.7, 1].map((fraction, index) => <mesh key={fraction} position={[0, -depth * [0.35, 0.08, 0][index], 0]} rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>
+ <ringGeometry args={[radius * fraction - 0.04, radius * fraction + 0.04, 48]} /><meshBasicMaterial color="#aea08b" transparent opacity={dimmed ? 0.06 : 0.2 + strength * 0.3} depthWrite={false} />
+ </mesh>)}
+ </group>;
+}
+
+/** Base edges and the batched pulses share a single source-to-target curve. */
+function relationshipGeometry(source: RenderNode, target: RenderNode, laneOffset: number) {
+ const start = centerOf(source), end = centerOf(target), delta = end.clone().sub(start), distance = delta.length();
+ // 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 = source.id === target.id
+ ? 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, points: curve.getPoints(32), arrowPosition: curve.getPoint(arrowAt),
+ arrowRotation: new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), curve.getTangent(arrowAt).normalize()),
+ labelPosition: curve.getPoint(0.5) };
+}
+
+/** Direction comes from relationship semantics, never navigation or selection. */
+function Relationship({ edge, geometry, selected, emphasized, dimmed, showLabel, onSelect, onHover }: {
+ edge: SemanticEdge; geometry: ReturnType<typeof relationshipGeometry>;
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 { curve, arrowPosition, arrowRotation, labelPosition } = geometry;
+ const color = edgeColor(edge.type);
const opacity = dimmed ? 0.06 : selected ? 1 : emphasized ? 0.95 : 0.55;
return <group>
<mesh onClick={event => { event.stopPropagation(); onSelect(); }}
@@ -76,11 +114,11 @@ function Relationship({ edge, source, target, selected, emphasized, dimmed, show
<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}
+ {isDirectedEdge(edge.type) && <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>
+ </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`}>
@@ -90,60 +128,114 @@ function Relationship({ edge, source, target, selected, emphasized, dimmed, show
</group>;
}
-function ArchitectureNode({ node, selected, highlighted, dimmed, onSelect, onHover }: {
- node: SemanticNode; selected: boolean; highlighted: boolean; dimmed: boolean;
+function ArchitectureNode({ node, selected, highlighted, dimmed, labelVisible = true, onSelect, onOpen, onHover }: {
+ node: RenderNode; selected: boolean; highlighted: boolean; dimmed: boolean;
+ labelVisible?: boolean;
onSelect: () => void; onHover: (id?: string) => void;
+ onOpen?: () => void;
}) {
- const color = PALETTE[node.kind];
+ const color = node.tint ?? PALETTE[node.kind];
+ const fill = useMemo(() => new Color('#27333e').lerp(new Color(color), selected ? 0.34 : highlighted ? 0.25 : 0.18), [color, selected, highlighted]);
const size = dimensions(node);
const labelY = size[1] + 7;
+ const measure = node.measure;
+ const lineText = measure?.lines === undefined ? 'Lines unavailable'
+ : `${measure.measuredFiles < measure.files ? '≥ ' : ''}${measure.lines.toLocaleString()} indexed lines`;
+ const mixed = Boolean(measure && measure.languages.length > 1);
+ const roofLanguages = node.tint && mixed ? measure!.languages.slice(0, 4) : [];
+ const roofTotal = measure?.lines || measure?.files || 1;
+ let roofOffset = -size[0] / 2;
return <group position={node.position}>
<mesh position={[0, size[1] / 2, 0]}
onClick={event => { event.stopPropagation(); onSelect(); }}
+ onDoubleClick={event => { event.stopPropagation(); onOpen?.(); }}
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} />
+ <meshStandardMaterial color={fill} roughness={0.85} metalness={0.05}
+ emissive={color} emissiveIntensity={selected ? 0.08 : highlighted ? 0.035 : 0.008}
+ transparent opacity={dimmed ? 0.14 : selected ? 0.65 : highlighted ? 0.55 : 0.42} depthWrite={false} />
+ <Edges color={selected ? '#f0fff9' : color} transparent opacity={dimmed ? 0.12 : selected ? 1 : highlighted ? 0.85 : 0.48} />
</mesh>
+ {roofLanguages.map(language => {
+ const width = size[0] * (measure?.lines ? language.lines : language.files) / roofTotal;
+ const x = roofOffset + width / 2; roofOffset += width;
+ return width > 0 ? <mesh key={language.name} position={[x, size[1] + 0.025, size[2] / 2 - 0.45]} raycast={() => null}>
+ <boxGeometry args={[width, 0.06, 0.9]} /><meshBasicMaterial color={language.color} transparent opacity={dimmed ? 0.1 : selected ? 0.6 : 0.38} depthWrite={false} />
+ </mesh> : null;
+ })}
{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} />
+ <meshBasicMaterial color="#ecfff7" transparent opacity={0.85} 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}
+ <button type="button" className={`architecture-node-label${selected ? ' is-selected' : ''}${dimmed ? ' is-dimmed' : ''}${labelVisible ? '' : ' is-hidden'}`}
+ data-kind={node.kind} aria-pressed={selected} onClick={onSelect} onDoubleClick={onOpen}
+ data-node-id={node.id} data-position={node.position.join(',')} data-label-visible={labelVisible}
+ data-lines={measure?.lines} data-height={size[1]} data-language={measure?.languages[0]?.name} data-gravity={node.gravity ?? 0} data-size-percent={node.sizePercent} data-gravity-percent={node.gravityPercent}
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>
+ title={`${node.label}\n${node.detail}${measure ? `\n${lineText}\n${measure.languages.map(language => language.name).join(', ')} (from file types)` : ''}`}>
+ {selected && <span className="architecture-node-kind"><i style={{ background: color }} />{node.kindLabel ?? (node.kind === 'area' ? 'Source area' : node.kind)}</span>}
+ <span className="architecture-node-title"><strong>{node.hotspot && <span className="architecture-hotspot-mark" title={`${node.hotspot.findings.length} ranked hotspots; strongest measured fan-in ${node.hotspot.maxFanIn ?? 'unavailable'}${node.gravityPercent === undefined ? '' : `; gravity ${Number(node.gravityPercent.toFixed(1))}%`}`}>◉ </span>}{node.label}</strong>{!measure && node.gravityPercent !== undefined && <small className="architecture-node-size" title="Gravity relative to strongest hotspot">{node.gravityPercent > 0 && node.gravityPercent < 0.1 ? '<0.1' : Number(node.gravityPercent.toFixed(1))}%</small>}</span>
+ {selected && measure && <span className="architecture-node-metric"><i style={{ background: color }} />{measure.lines === undefined ? '?' : `${measure.measuredFiles < measure.files ? '≥' : ''}${Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }).format(measure.lines)}`} lines{mixed ? ' · mixed' : ''}</span>}
{selected && <span className="architecture-node-detail">{node.detail}</span>}
</button>
</Html>
</group>;
}
+/** Screen-space label density changes with zoom; source positions never do. */
+function HotspotLabels({ model, priorityId, onVisible }: { model: RenderGraph; priorityId?: string; onVisible: (ids: Set<string>) => void }) {
+ const { camera, size } = useThree();
+ const previous = useRef('');
+ useFrame(() => {
+ const occupied: { left: number; right: number; top: number; bottom: number }[] = [];
+ const ids = new Set<string>();
+ const ordered = [...model.nodes].sort((a, b) => Number(b.id === priorityId) - Number(a.id === priorityId));
+ for (const node of ordered) {
+ const point = new Vector3(...node.position).add(new Vector3(0, dimensions(node)[1] + 7, 0)).project(camera);
+ const x = (point.x + 1) * size.width / 2; const y = (1 - point.y) * size.height / 2;
+ const width = Math.min(178, Math.max(78, node.label.length * 7 + (node.gravityPercent === undefined ? 26 : 68)));
+ const halfHeight = node.id === priorityId ? 48 : 19;
+ const rect = { left: x - width / 2 - 5, right: x + width / 2 + 5, top: y - halfHeight, bottom: y + halfHeight };
+ if (node.id !== priorityId && (rect.right < 0 || rect.left > size.width || rect.bottom < 0 || rect.top > size.height
+ || occupied.some(other => rect.left < other.right && rect.right > other.left && rect.top < other.bottom && rect.bottom > other.top))) continue;
+ ids.add(node.id); occupied.push(rect);
+ }
+ const key = [...ids].sort().join('|');
+ if (previous.current !== key) { previous.current = key; onVisible(ids); }
+ });
+ return null;
+}
+
function FitArchitecture({ model, planar, resetKey, controls, active }: {
- model: SemanticGraph; planar: boolean; resetKey: number;
+ model: RenderGraph; 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 layoutKey = model.nodes.map(node => `${node.id}:${node.position.join(',')}:${dimensions(node)[1]}:${node.gravity ?? 0}`).join('|')
+ + (model.platforms ?? []).map(platform => `${platform.id}:${platform.position.join(',')}:${platform.width}:${platform.depth}`).join('|');
const nodesRef = useRef(model.nodes);
nodesRef.current = model.nodes;
+ const platformsRef = useRef(model.platforms);
+ platformsRef.current = model.platforms;
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);
+ if (node.gravity) { half.x = Math.max(half.x, 10); half.z = Math.max(half.z, 10); bounds.expandByPoint(new Vector3(node.position[0], -8, node.position[2])); }
bounds.expandByPoint(center.clone().sub(half));
bounds.expandByPoint(center.clone().add(half));
}
+ for (const platform of platformsRef.current ?? []) {
+ const [x, y, z] = platform.position;
+ bounds.expandByPoint(new Vector3(x - platform.width / 2 - 2, y - 0.45, z - platform.depth / 2 - 2));
+ bounds.expandByPoint(new Vector3(x + platform.width / 2 + 2, y + 1, z + platform.depth / 2 + 2));
+ }
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());
@@ -171,9 +263,21 @@ function FitArchitecture({ model, planar, resetKey, controls, active }: {
return null;
}
-export function ArchitectureScene({ model, selectedId, selectedEdgeId, onSelect, onSelectEdge, active = true, planar = false, resetKey = 0 }: ArchitectureSceneProps) {
+export function ArchitectureScene({ model: graphModel, selectedId, selectedEdgeId, onSelect, onSelectEdge, onOpen, onClearSelection, active = true, planar = false, resetKey = 0, catalog, heightMetric = 'uniform', colorMetric = 'kind', hotspots, showHotspots = true, adaptiveLabels = false }: ArchitectureSceneProps) {
+ const model: RenderGraph = useMemo(() => ({ ...graphModel, nodes: graphModel.nodes.map(node => {
+ const measure = catalog ? measureSourceNode(node, catalog) : undefined;
+ const sizePercent = catalog ? sourceNodeSizePercent(node, catalog) : undefined;
+ const language = measure?.languages[0]?.name ?? (node.filePath ? sourceLanguage(node.filePath) : undefined);
+ const hotspot = showHotspots && hotspots ? hotspotsForNode(node, hotspots) : undefined;
+ return { ...node, measure, sizePercent, hotspot, gravity: hotspot && hotspots ? gravityStrength(hotspot.maxFanIn, hotspots.maxFanIn) : 0,
+ gravityPercent: hotspot && hotspots ? gravityPercent(hotspot.maxFanIn, hotspots.maxFanIn) : undefined,
+ height: catalog && heightMetric === 'lines' && ['area', 'file'].includes(node.kind) ? node.kind === 'area' && node.areaPath === '(root)' ? 0.35 : sourceBrickHeight(sizePercent, 100) : undefined,
+ tint: node.tint ?? (colorMetric === 'language' && node.kind !== 'route' ? languageColor(language ?? 'Unknown') : undefined) };
+ }) }), [graphModel, catalog, heightMetric, colorMetric, hotspots, showHotspots]);
const [hoveredId, setHoveredId] = useState<string>();
const [hoveredEdgeId, setHoveredEdgeId] = useState<string>();
+ const [visibleHotspotLabels, setVisibleHotspotLabels] = useState<Set<string>>();
+ const background = useGraphBackgroundReset(() => { setHoveredId(undefined); setHoveredEdgeId(undefined); onClearSelection?.(); });
const controls = useRef<OrbitControlsImpl | null>(null);
const nodesById = useMemo(() => new Map(model.nodes.map(node => [node.id, node])), [model.nodes]);
const edgeOffsets = useMemo(() => {
@@ -184,6 +288,14 @@ export function ArchitectureScene({ model, selectedId, selectedEdgeId, onSelect,
}
return offsets;
}, [model.edges]);
+ const edgeGeometry = useMemo(() => {
+ const result = new Map<string, ReturnType<typeof relationshipGeometry>>();
+ for (const edge of model.edges) {
+ const source = nodesById.get(edge.source), target = nodesById.get(edge.target);
+ if (source && target) result.set(edge.id, relationshipGeometry(source, target, edgeOffsets.get(edge.id) ?? 0));
+ }
+ return result;
+ }, [model.edges, nodesById, edgeOffsets]);
const candidateId = hoveredId ?? selectedId;
const focusId = candidateId && nodesById.has(candidateId) ? candidateId : undefined;
const candidateEdgeId = hoveredEdgeId ?? selectedEdgeId;
@@ -198,11 +310,18 @@ export function ArchitectureScene({ model, selectedId, selectedEdgeId, onSelect,
}
return ids;
}, [model.edges, focusId, focusEdgeId]);
+ const pulsePaths = useMemo(() => model.edges.flatMap(edge => {
+ const geometry = edgeGeometry.get(edge.id);
+ if (!geometry || !isDirectedEdge(edge.type)) return [];
+ const emphasized = edge.id === focusEdgeId || edge.source === focusId || edge.target === focusId;
+ return [{ id: edge.id, type: edge.type, points: geometry.points,
+ opacity: related.size > 0 && !emphasized ? 0.04 : edge.id === selectedEdgeId ? 0.95 : emphasized ? 0.8 : 0.65 }];
+ }), [model.edges, edgeGeometry, focusEdgeId, focusId, related, selectedEdgeId]);
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]}
+ <Canvas {...background} 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']} />
@@ -211,24 +330,27 @@ export function ArchitectureScene({ model, selectedId, selectedEdgeId, onSelect,
<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.platforms?.map(platform => <FolderPlatform key={platform.id} platform={platform} />)}
+ {model.nodes.filter(node => node.gravity).map(node => <GravityWell key={`gravity:${node.id}`} node={node} floorY={floorY} dimmed={related.size > 0 && !related.has(node.id)} />)}
{model.edges.map(edge => {
- const source = nodesById.get(edge.source);
- const target = nodesById.get(edge.target);
- if (!source || !target) return null;
+ const geometry = edgeGeometry.get(edge.id);
+ if (!geometry) 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}
+ return <Relationship key={edge.id} edge={edge} geometry={geometry}
selected={edge.id === selectedEdgeId} emphasized={emphasized} showLabel={edge.id === focusEdgeId}
dimmed={related.size > 0 && !emphasized} onSelect={() => onSelectEdge(edge.id)} onHover={setHoveredEdgeId} />;
})}
+ <EdgePulseLayer paths={pulsePaths} active={active} />
{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} />)}
+ labelVisible={(!adaptiveLabels && model.view !== 'hotspots') || visibleHotspotLabels === undefined || visibleHotspotLabels.has(node.id) || node.id === selectedId || (adaptiveLabels && node.id === hoveredId)}
+ onSelect={() => onSelect(node.id)} onOpen={onOpen ? () => onOpen(node.id) : undefined} 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} />
+ {(adaptiveLabels || model.view === 'hotspots') && <HotspotLabels model={model} priorityId={selectedId ?? hoveredId} onVisible={setVisibleHotspotLabels} />}
</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/BehaviorJourney.test.tsx b/graph-ui/src/architecture/BehaviorJourney.test.tsx
new file mode 100644
index 000000000..feb3f0dcc
--- /dev/null
+++ b/graph-ui/src/architecture/BehaviorJourney.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import BehaviorJourney, { journeyPage, type BehaviorJourneyProps } from './BehaviorJourney';
+import { behaviorJourney } from './behavior-journey-model';
+import type { SystemSceneModel } from './system-architecture-model';
+import type { SystemProjection, SystemSymbol } from './system-architecture-source';
+
+vi.mock('./BehaviorSourceEvidence', () => ({ default: () => <div data-source-evidence /> }));
+vi.mock('./SystemArchitectureScene', () => ({ default: ({ model, onSelectNode, onExpandNode, onClearSelection, selectedNode, presentation }: {
+ model: SystemSceneModel; onSelectNode: (id: string) => void; onExpandNode: (id: string) => void; presentation: string; onClearSelection?: () => void; selectedNode?: string;
+}) => <div data-scene={presentation} data-selected={selectedNode}><button onClick={onClearSelection}>Empty background</button>{model.nodes.map(node => <button key={node.id} data-node={node.id} onClick={() => onSelectNode(node.id)} onDoubleClick={() => onExpandNode(node.id)}>{node.label}</button>)}
+ {model.edges.map(edge => <span key={edge.id} data-edge={edge.pathEdge?.id} />)}</div> }));
+const symbol = (id: number): SystemSymbol => ({ id, name: `operation${id}`, qualified_name: `sample.operation${id}`, label: 'Function',
+ component_id: `component${id % 2}`, file_path: `src/part${id % 2}.ts`, start_line: id });
+function fixture(): SystemProjection {
+ const nodes = Array.from({ length: 9 }, (_, index) => symbol(index + 1));
+ return { schema_version: 1, status: 'ready', kind: 'static_projection', complete: true, components: [], dependencies: [], cycles: [],
+ entrypoints: [nodes[0]], paths: [{ entrypoint_id: 1, nodes, edges: nodes.slice(1).map((node, index) => ({
+ id: 10 + index, source_id: nodes[index].id, target_id: node.id, type: 'CALLS', callsite: { file_path: nodes[index].file_path!, line: 20 + index },
+ })) }], totals: {}, limits: {}, warnings: [] };
+}
+let container: HTMLDivElement, root: Root;
+beforeEach(() => { (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true; container = document.createElement('div'); document.body.append(container); root = createRoot(container); });
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
+async function render(data: SystemProjection, changes: Partial<BehaviorJourneyProps> = {}) {
+ const props: BehaviorJourneyProps = { project: 'sample', generation: 'g1', data, entries: data.entrypoints,
+ targets: data.paths[0].nodes.slice(1).map((node, index) => ({ ...node, distance: index + 1 })), entryId: 1,
+ active: true, pending: false, filter: '', onRequest: vi.fn(), onRefresh: vi.fn(), onNavigate: vi.fn(), onSelectSymbol: vi.fn(), ...changes };
+ await act(async () => root.render(<BehaviorJourney {...props} />)); return props;
+}
+async function click(text: string) { const button = [...container.querySelectorAll('button')].find(button => button.textContent === text); expect(button).toBeDefined(); await act(async () => button!.click()); }
+
+describe('behavior journeys', () => {
+ it('opens with unordered immediate calls rather than the system overview or a fabricated full journey', async () => {
+ await render(fixture());
+ expect(container.querySelector('[data-scene]')?.getAttribute('data-scene')).toBe('journey');
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(2);
+ expect(container.querySelectorAll('[data-edge]')).toHaveLength(1);
+ expect(container.textContent).toContain('DIRECT CALLS · UNORDERED');
+ expect(container.querySelector('[aria-label="Walk the call chain"]')).toBeNull();
+ });
+ it('walks a long path through readable windows while retaining access to every operation', async () => {
+ await render(fixture(), { targetId: 9 });
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(5);
+ expect(container.querySelectorAll('[aria-label="All operations in this call chain"] li')).toHaveLength(9);
+ for (let i = 0; i < 5; i++) await click('Next →');
+ expect(container.textContent).toContain('Showing operations 5 to 9 of 9');
+ expect([...container.querySelectorAll('[data-edge]')].map(item => item.getAttribute('data-edge'))).toEqual(['14', '15', '16', '17']);
+ expect(container.querySelector('[aria-label="Call-chain position"]')?.getAttribute('value')).toBe('5');
+ });
+ it('double-clicking an operation requests its actual symbol and Back restores the previous scope', async () => {
+ const props = await render(fixture());
+ const button = container.querySelector('[data-node="journey-choice:2"]')!;
+ await act(async () => button.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 2 }), undefined);
+ await click('← Back');
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }), undefined);
+ });
+ it('clears inspection and returns from a followed operation to the original entry on empty background', async () => {
+ const clear = vi.fn(); const props = await render(fixture(), { onClearSelection: clear });
+ await act(async () => container.querySelector('[data-node="journey-choice:2"]')!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
+ const next = fixture(); next.entrypoints = [next.paths[0].nodes[1]];
+ next.paths = [{ ...next.paths[0], entrypoint_id: 2, nodes: next.paths[0].nodes.slice(1), edges: next.paths[0].edges.slice(1) }];
+ await render(next, { ...props, data: next, entryId: 2 });
+ await click('Empty background');
+ expect(props.onRequest).toHaveBeenLastCalledWith(expect.objectContaining({ id: 1 }));
+ expect(container.querySelector('[data-scene]')?.getAttribute('data-selected')).toBeNull();
+ expect(container.querySelector('[aria-label="Behavior evidence inspector"]')?.textContent).toContain('Select an operation or a call');
+ expect(clear).toHaveBeenCalledOnce();
+ expect([...container.querySelectorAll('button')].find(item => item.textContent === '← Back')?.disabled).toBe(true);
+ });
+ it('shows exact argument expressions and declaration facts without inventing argument-to-parameter bindings', async () => {
+ const data = fixture();
+ data.paths[0].nodes[1].signature = 'operation2(options: Options): Result';
+ data.paths[0].nodes[1].parameters = { names: ['options'], types: ['Options'], count: 1 };
+ data.paths[0].nodes[1].return_type = 'Result';
+ Object.assign(data.paths[0].edges[0], { arguments: [{ i: 0, e: '...settings' }], argument_limit: 8, arguments_complete: false });
+ await render(data, { targetId: 9 });
+ const contract = container.querySelector('[aria-label="Indexed call contract"]')!;
+ expect(contract.textContent).toContain('...settings'); expect(contract.textContent).toContain('options: Options');
+ expect(contract.textContent).toContain('Declared return typeResult');
+ expect(contract.textContent).toContain('Parameter binding is not established.');
+ });
+ it('never keeps an old scene under a pending or failed new request', async () => {
+ const data = fixture(); await render(data, { targetId: 9 }); expect(container.querySelector('[data-scene]')).not.toBeNull();
+ await render(data, { data: undefined, pending: true, targetId: 8 });
+ expect(container.querySelector('[data-scene]')).toBeNull(); expect(container.textContent).toContain('Preparing the selected operation');
+ await render(data, { data: undefined, pending: false, error: 'Snapshot changed.' });
+ expect(container.querySelector('[data-scene]')).toBeNull(); expect(container.textContent).toContain('Snapshot changed.');
+ });
+ it('pages only real edges and component lanes within the selected path window', () => {
+ const scene = behaviorJourney(fixture(), { entryId: 1, targetId: 9 }).scene;
+ const page = journeyPage(scene, 6), ids = new Set(page.nodes.map(node => node.id));
+ expect(page.nodes).toHaveLength(5); expect(page.edges).toHaveLength(4);
+ expect(page.edges.every(edge => ids.has(edge.source) && ids.has(edge.target))).toBe(true);
+ expect(page.edges.map(edge => edge.pathEdge!.id)).toEqual([14, 15, 16, 17]);
+ expect(scene.nodes).toHaveLength(9);
+ const compact = journeyPage(scene, 5, false, 3);
+ expect(compact.nodes.map(node => node.symbol!.id)).toEqual([5, 6, 7]);
+ expect(compact.edges.map(edge => edge.pathEdge!.id)).toEqual([14, 15]);
+ });
+});
diff --git a/graph-ui/src/architecture/BehaviorJourney.tsx b/graph-ui/src/architecture/BehaviorJourney.tsx
new file mode 100644
index 000000000..700eb2495
--- /dev/null
+++ b/graph-ui/src/architecture/BehaviorJourney.tsx
@@ -0,0 +1,194 @@
+import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
+import { behaviorJourney } from './behavior-journey-model';
+import type { SystemSceneModel } from './system-architecture-model';
+import type { SystemProjection, SystemSymbol } from './system-architecture-source';
+import BehaviorSourceEvidence from './BehaviorSourceEvidence';
+import './behavior-journey.css';
+
+const Scene = lazy(() => import('./SystemArchitectureScene'));
+export interface BehaviorJourneyProps {
+ project: string; generation?: string; data?: SystemProjection; entries: SystemSymbol[];
+ targets: (SystemSymbol & { distance: number })[]; entryId?: number; targetId?: number;
+ active: boolean; pending: boolean; error?: string; filter: string;
+ onRequest: (entry: SystemSymbol | undefined, targetId?: number) => void;
+ onClearSelection?: () => void;
+ onRefresh: () => void; onSelectSymbol: (symbol: SystemSymbol) => void;
+ onNavigate: (path: string, line?: number, name?: string) => void;
+}
+
+/** Overlapping windows keep every operation legible and retain actual call adjacency. */
+export function journeyPage(scene: SystemSceneModel, step: number, choices = false, pathWindow = 5): SystemSceneModel {
+ const size = choices ? 5 : Math.max(2, Math.min(5, pathWindow));
+ if (scene.nodes.length <= size) return scene;
+ const start = choices ? step * 4 + 1 : Math.min(Math.floor(step / (size - 1)) * (size - 1), Math.max(0, scene.nodes.length - size));
+ const window = choices ? [scene.nodes[0], ...scene.nodes.slice(start, start + 4)] : scene.nodes.slice(start, start + size);
+ const nodes = choices ? window.map((node, index) => ({ ...node, position: (index === 0 ? [0, 0, 0] : [88, ((window.length - 2) / 2 - index + 1) * 30, 0]) as [number, number, number] })) : window;
+ const ids = new Set(nodes.map(node => node.id));
+ const lanes = scene.lanes.flatMap(lane => {
+ const members = nodes.filter(node => `journey-component:${node.symbol?.component_id}` === lane.id);
+ if (!members.length) return [];
+ const xs = members.map(node => node.position[0]), ys = members.map(node => node.position[1]);
+ return [{ ...lane, position: [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2, -2] as [number, number, number],
+ width: Math.max(...xs) - Math.min(...xs) + 62, height: Math.max(...ys) - Math.min(...ys) + 32 }];
+ });
+ return { ...scene, nodes, lanes, edges: scene.edges.filter(edge => ids.has(edge.source) && ids.has(edge.target)), scopeKey: `${scene.scopeKey}:page:${start}` };
+}
+
+export default function BehaviorJourney({ project, generation, data, entries, targets, entryId, targetId, active, pending, error, filter,
+ onRequest, onRefresh, onSelectSymbol, onNavigate, onClearSelection }: BehaviorJourneyProps) {
+ const [pathIndex, setPathIndex] = useState(0), [step, setStep] = useState(0);
+ const [branchPage, setBranchPage] = useState(0);
+ const [overview, setOverview] = useState(false);
+ const [selection, setSelection] = useState<{ node?: string; edge?: string }>();
+ const [planar, setPlanar] = useState(false), [resetKey, setResetKey] = useState(0);
+ const [history, setHistory] = useState<{ entry: SystemSymbol; targetId?: number }[]>([]);
+ const [targetSearch, setTargetSearch] = useState('');
+ const visual = useRef<HTMLDivElement>(null);
+ const [pathWindow, setPathWindow] = useState(5);
+ useEffect(() => { setSelection(undefined); setPathIndex(0); setStep(0); setBranchPage(0); }, [project, generation, entryId, targetId, filter]);
+ useEffect(() => { setHistory([]); setTargetSearch(''); }, [project, generation]);
+ const journey = useMemo(() => data ? behaviorJourney(data, { entryId, targetId, pathIndex, filter }) : undefined,
+ [data, entryId, targetId, pathIndex, filter]);
+ const path = journey?.path;
+ const activeStep = Math.min(step, Math.max(0, (path?.nodes.length ?? 1) - 1));
+ const scene = useMemo(() => journey ? journeyPage(journey.scene, path ? activeStep : branchPage, !path, pathWindow) : undefined, [journey, path, activeStep, branchPage, pathWindow]);
+ const hasScene = Boolean(scene);
+ useEffect(() => {
+ const element = visual.current;
+ if (!element) return;
+ const resize = () => { const width = element.getBoundingClientRect().width; if (width > 0) setPathWindow(width < 800 ? 3 : 5); };
+ resize();
+ if (typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(resize); observer.observe(element);
+ return () => observer.disconnect();
+ }, [pending, hasScene]);
+ const allNodes = journey?.scene.nodes ?? [];
+ const selectedEdge = journey?.scene.edges.find(edge => edge.id === selection?.edge);
+ const selectedNode = overview ? undefined : allNodes.find(node => node.id === selection?.node) ?? (path ? allNodes[activeStep] : allNodes[0]);
+ const symbol = overview ? undefined : selectedNode?.symbol ?? journey?.entry;
+ const call = selectedEdge?.pathEdge ?? (path && !overview && !selection?.edge ? path.edges[activeStep] : undefined);
+ const caller = call ? allNodes.find(node => node.symbol?.id === call.source_id)?.symbol : symbol;
+ const callee = call ? allNodes.find(node => node.symbol?.id === call.target_id)?.symbol : undefined;
+ const components = new Map([...(data?.components ?? []), ...(data?.overview?.components ?? [])].map(component => [component.id, component]));
+ const related = symbol ? journey?.scene.edges.filter(edge => edge.pathEdge?.source_id === symbol.id) ?? [] : [];
+ const targetOptions = [...new Map([...targets, ...(journey?.choices ?? []).map(item => ({ ...item, distance: item.distance ?? 1 }))]
+ .filter(item => item.id !== (entryId ?? journey?.entry?.id)).map(item => [item.id, item])).values()];
+ const matchingTargets = targetOptions.filter(item => item.id === targetId || !targetSearch.trim()
+ || `${item.name} ${item.file_path ?? ''}`.toLocaleLowerCase().includes(targetSearch.trim().toLocaleLowerCase()));
+ const entry = journey?.entry ?? entries.find(item => item.id === entryId);
+ const availableEntries = entry && !entries.some(item => item.id === entry.id) ? [entry, ...entries] : entries;
+ const selectedTarget = targetOptions.find(item => item.id === targetId) ?? path?.nodes.at(-1);
+ function clearSelection() {
+ const origin = history[0]?.entry ?? entry;
+ setOverview(true); setSelection(undefined); setStep(0); setBranchPage(0); setPathIndex(0); setHistory([]);
+ setResetKey(value => value + 1); onClearSelection?.();
+ if (history.length || targetId !== undefined) onRequest(origin);
+ }
+ function request(next: SystemSymbol | undefined, destination?: number, remember = true) {
+ setOverview(false);
+ if (remember && entry) setHistory(items => [...items.slice(-19), { entry, targetId }]);
+ setSelection(undefined); setStep(0); setPathIndex(0); setTargetSearch(''); onRequest(next, destination);
+ }
+ function selectNode(id: string) {
+ setOverview(false);
+ const node = allNodes.find(item => item.id === id);
+ setSelection({ node: id });
+ if (path && node?.depth !== undefined) setStep(node.depth);
+ if (!path && node) setBranchPage(Math.max(0, Math.floor((allNodes.indexOf(node) - 1) / 4)));
+ if (node?.symbol) onSelectSymbol(node.symbol);
+ }
+ function selectEdge(id: string) {
+ setOverview(false);
+ const edge = journey?.scene.edges.find(item => item.id === id);
+ setSelection({ edge: id });
+ if (path && edge?.depth) setStep(edge.depth - 1);
+ if (!path && edge) setBranchPage(Math.max(0, Math.floor((allNodes.findIndex(node => node.id === edge.target) - 1) / 4)));
+ }
+ function selectStep(index: number) {
+ setOverview(false);
+ const node = allNodes[index];
+ if (!node || !path) return;
+ setStep(index); setSelection({ node: node.id }); if (node.symbol) onSelectSymbol(node.symbol);
+ }
+ function follow(id: string) {
+ const operation = allNodes.find(node => node.id === id)?.symbol;
+ if (operation && operation.id !== entryId) request(operation);
+ }
+ return <section className="system-architecture behavior-journey" aria-label="Behavior" data-testid="behavior-journey" aria-busy={pending}>
+ <header className="behavior-heading"><div><span className="system-eyebrow">Behavior · source-guided exploration</span>
+ <h2>{targetId !== undefined ? `${entry?.name ?? 'Operation'} → ${selectedTarget?.name ?? 'destination'}` : `What can ${entry?.name ?? 'this operation'} call?`}</h2>
+ <p>{path ? 'Follow one recorded call chain across the parts it touches.' : 'Choose a starting operation. Explore its calls, or follow a path to a destination.'}</p></div>
+ <button onClick={onRefresh}>Refresh</button></header>
+ <div className="behavior-requests">
+ <label>Start <select aria-label="Behavior entry point" value={entryId ?? ''} onChange={event => request(availableEntries.find(item => item.id === Number(event.target.value)))}>
+ <option value="">Choose an operation…</option>{availableEntries.map(item => <option key={item.id} value={item.id}>{item.name} · {item.file_path ?? item.qualified_name}</option>)}
+ </select></label>
+ <label>Reach <select aria-label="Behavior destination" value={targetId ?? ''} disabled={!entry || pending} onChange={event => request(entry, event.target.value ? Number(event.target.value) : undefined)}>
+ <option value="">Explore immediate calls</option>{matchingTargets.map(item => <option key={item.id} value={item.id}>{item.name} · {item.file_path ?? ''}</option>)}
+ </select></label>
+ {targetOptions.length > 15 && <input aria-label="Find a destination" placeholder="Find a destination…" value={targetSearch} onChange={event => setTargetSearch(event.target.value)} />}
+ </div>
+ <div className="behavior-navigation"><button disabled={!history.length} onClick={() => { const previous = history.at(-1)!; setHistory(items => items.slice(0, -1)); request(previous.entry, previous.targetId, false); }}>← Back</button>
+ {targetId !== undefined && <button onClick={() => request(entry)}>Immediate calls</button>}
+ <span>{pending ? 'Updating this journey…' : path ? `${path.edges.length} call-chain hops · ${new Set(path.nodes.map(item => item.component_id)).size} components`
+ : `${journey?.counts.directChoices ?? 0} direct callees with returned evidence`}</span>
+ <span className="behavior-static-badge" title="Graph relationships describe possible calls. They do not prove execution order, path feasibility or actual runtime values.">Static evidence</span>
+ </div>
+ {error && <p role="alert">{error} <button onClick={onRefresh}>Try again</button></p>}
+ {pending ? <div className="behavior-loading" role="status">Preparing the selected operation…</div> : !scene || !journey ? <div className="behavior-loading">Choose an operation to explore.</div> : <>
+ {journey.paths.length > 1 && <div className="behavior-paths" role="group" aria-label="Indexed paths">{journey.paths.map((item, index) => <button key={index} aria-pressed={pathIndex === index} onClick={() => { setPathIndex(index); setStep(0); setSelection(undefined); }}>
+ Path {index + 1}<small>{item.edges.length} hops{new Set(item.nodes.map(node => node.id)).size < item.nodes.length ? ' · revisits a symbol' : ''}</small></button>)}</div>}
+ <div className="behavior-stage"><div className="behavior-visual" ref={visual}>
+ <div className="behavior-visual-toolbar"><span>{path ? 'CALL CHAIN →' : 'DIRECT CALLS · UNORDERED'}</span>
+ <div className="system-view-switch" role="group" aria-label="Behavior camera"><button aria-pressed={!planar} onClick={() => setPlanar(false)}>3D</button><button aria-pressed={planar} onClick={() => setPlanar(true)}>Plan</button></div>
+ <button onClick={() => setResetKey(value => value + 1)}>Fit</button></div>
+ <div className="system-map behavior-map">
+ {scene.nodes.length ? <Suspense fallback={<div className="behavior-loading">Preparing the journey…</div>}><Scene model={scene}
+ selectedNode={selectedEdge ? undefined : selectedNode?.id} selectedEdge={selectedEdge?.id}
+ onSelectNode={selectNode} onSelectEdge={selectEdge} onExpandNode={follow} onClearSelection={clearSelection}
+ resetKey={resetKey} planar={planar} active={active} showConnectionLoad={false} presentation="journey" /></Suspense>
+ : <div className="behavior-loading">{filter ? 'No connected path matches this filter.' : targetId !== undefined ? 'No connected call-chain witness was returned for this destination.' : 'No direct call witnesses were returned for this operation.'}</div>}
+ <div className="system-map-caption"><span>{path ? `Showing operations ${(scene.nodes[0]?.depth ?? 0) + 1} to ${(scene.nodes.at(-1)?.depth ?? 0) + 1} of ${path.nodes.length}` : 'Branches are possible calls, not an execution sequence.'}</span>
+ <span>Double-click an operation to follow its calls</span></div>
+ </div>
+ {path && <nav className="behavior-walk" aria-label="Walk the call chain"><button disabled={activeStep === 0} onClick={() => selectStep(activeStep - 1)}>← Previous</button>
+ <input type="range" aria-label="Call-chain position" min={0} max={path.nodes.length - 1} value={activeStep} onChange={event => selectStep(Number(event.target.value))} />
+ <span>{activeStep + 1} / {path.nodes.length}</span><button disabled={activeStep >= path.nodes.length - 1} onClick={() => selectStep(activeStep + 1)}>Next →</button></nav>}
+ {!path && journey.scene.nodes.length > 5 && <nav className="behavior-walk" aria-label="Direct call pages"><button disabled={branchPage === 0} onClick={() => { setBranchPage(page => page - 1); setSelection(undefined); }}>← Earlier calls</button>
+ <span>Calls {branchPage * 4 + 1} to {Math.min(branchPage * 4 + 4, journey.scene.nodes.length - 1)} of {journey.scene.nodes.length - 1} shown</span>
+ <button disabled={(branchPage + 1) * 4 >= journey.scene.nodes.length - 1} onClick={() => { setBranchPage(page => page + 1); setSelection(undefined); }}>More calls →</button></nav>}
+ </div><aside className="behavior-inspector" aria-label="Behavior evidence inspector">
+ {caller ? <><span className="system-eyebrow">{call ? call.type.replaceAll('_', ' ') : path ? `Operation ${activeStep + 1}` : 'Starting operation'}</span>
+ <h3>{caller.name}{callee && <><span className="behavior-call-arrow">↓</span>{callee.name}</>}</h3>
+ <p>{call && callee ? caller.component_id === callee.component_id ? 'A call within the same component.' : `Crosses from ${components.get(caller.component_id)?.label ?? caller.component_id} into ${components.get(callee.component_id)?.label ?? callee.component_id}.`
+ : components.get(caller.component_id)?.label ?? caller.file_path}</p>
+ {call?.resolution && <p className="behavior-resolution">{call.resolution.strategy?.replaceAll('_', ' ') ?? 'Indexed resolution'}{call.resolution.candidates && call.resolution.candidates > 1 ? ` · ${call.resolution.candidates} candidate targets` : ''}</p>}
+ <div className="behavior-inspector-actions">{symbol && symbol.id !== entryId && <button onClick={() => request(symbol)}>Follow calls from here</button>}
+ {symbol?.file_path && <button onClick={() => onNavigate(symbol.file_path!, symbol.start_line, symbol.name)}>Open definition ↗</button>}</div>
+ <div className="behavior-contract" aria-label="Indexed call contract">
+ {call?.arguments && <section><h4>Passed expressions</h4>{call.arguments.length ? <ol>{call.arguments.map((argument, index) => <li key={`${argument.i}:${index}`}><code>{argument.e}</code>
+ {argument.v !== undefined && <small>Resolved string: <code>{JSON.stringify(argument.v)}</code></small>}</li>)}</ol> : <p>No argument expressions were captured.</p>}
+ <small>Indexed expressions{call.argument_limit ? ` · up to ${call.argument_limit}` : ''}. Parameter binding is not established.</small></section>}
+ {(callee ?? symbol)?.signature && <section><h4>{callee ? 'Called declaration' : 'Declaration'}</h4><code className="behavior-signature">{(callee ?? symbol)!.signature}</code></section>}
+ {(callee ?? symbol)?.parameters && <section><h4>Declared parameters</h4><ul>{(callee ?? symbol)!.parameters!.names.map((name, index) => <li key={`${index}:${name}`}><code>{name}{(callee ?? symbol)!.parameters!.types[index] ? `: ${(callee ?? symbol)!.parameters!.types[index]}` : ''}</code></li>)}</ul>
+ <small>{(callee ?? symbol)!.parameters!.count} reported parameters</small></section>}
+ {(callee ?? symbol)?.return_type && <section><h4>Declared return type</h4><code>{(callee ?? symbol)!.return_type}</code></section>}
+ </div>
+ <BehaviorSourceEvidence project={project} generation={generation} symbol={caller} call={call} active={active} onNavigate={onNavigate} />
+ {callee && <div className="behavior-next-operation"><span>Continues into</span><button onClick={() => { const node = allNodes.find(node => node.symbol?.id === callee.id && (node.depth ?? 0) > activeStep) ?? allNodes.find(node => node.symbol?.id === callee.id); if (node) selectNode(node.id); }}>{callee.name} →</button></div>}
+ {!path && related.length > 0 && <div className="behavior-immediate-list"><h4>Calls from this operation</h4>{related.map(edge => <button key={edge.id} onClick={() => selectEdge(edge.id)}>
+ {allNodes.find(node => node.id === edge.target)?.symbol?.name ?? edge.target}<small>{edge.pathEdge?.callsite ? `line ${edge.pathEdge.callsite.line}` : edge.type.toLowerCase().replaceAll('_', ' ')}</small></button>)}</div>}
+ </> : <p>Select an operation or a call to inspect its evidence.</p>}
+ </aside></div>
+ {path && <ol className="behavior-operation-strip" aria-label="All operations in this call chain">{path.nodes.map((item, index) => <li key={`${index}:${item.id}`}>
+ <button aria-label={`Select step ${index + 1}: ${item.name}`} aria-pressed={!overview && activeStep === index} onClick={() => selectStep(index)}><span>{index + 1}</span><strong>{item.name}</strong><small>{item.file_path}</small></button></li>)}</ol>}
+ <details className="behavior-limits"><summary>Evidence and limits{journey.limits.sampled ? ' · partial analysis' : ''}</summary>
+ <p>Each arrow is a recorded invocation. Component lanes provide orientation; numbered operations follow call-chain depth. Neither proves execution order, branch feasibility, data transformation or runtime values. Opening a call reads its current local source.</p>
+ <p>{journey.counts.omittedChoices} choices, {journey.counts.omittedNodes} nodes and {journey.counts.omittedEdges} edges omitted by display limits. {journey.counts.invalidPaths} disconnected or unsupported paths excluded.</p>
+ {(data?.behavior?.totals.omitted_targets ?? 0) > 0 && <p>{data!.behavior!.totals.omitted_targets} reachable destinations are outside the returned catalog.</p>}
+ {journey.limits.hit.length > 0 && <p>{journey.limits.hit.join(' · ')}</p>}
+ {data?.warnings.map((warning, index) => <p key={index}>{warning}</p>)}
+ </details>
+ </>}
+ </section>;
+}
diff --git a/graph-ui/src/architecture/BehaviorSourceEvidence.test.tsx b/graph-ui/src/architecture/BehaviorSourceEvidence.test.tsx
new file mode 100644
index 000000000..ab9da51ae
--- /dev/null
+++ b/graph-ui/src/architecture/BehaviorSourceEvidence.test.tsx
@@ -0,0 +1,35 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import BehaviorSourceEvidence from './BehaviorSourceEvidence';
+import { callToolJson } from '../provider/rpc-transport';
+import type { SystemSymbol } from './system-architecture-source';
+vi.mock('../provider/rpc-transport', () => ({ callToolJson: vi.fn() }));
+const symbol: SystemSymbol = { id: 1, name: 'start', qualified_name: 'sample.start', label: 'Function', component_id: 'api', file_path: 'src/api.ts', start_line: 10 };
+const snippet = { qualified_name: 'sample.start', file_path: '/repo/src/api.ts', source_mode: 'full', source: 'start()\nnext()\n', start_line: 10, end_line: 11 };
+let container: HTMLDivElement, root: Root;
+beforeEach(() => { (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true; vi.clearAllMocks(); container = document.createElement('div'); document.body.append(container); root = createRoot(container); });
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); });
+async function render(project = 'sample', active = true) { await act(async () => root.render(<BehaviorSourceEvidence project={project} generation="g1" symbol={symbol} active={active} onNavigate={vi.fn()} />)); }
+describe('behavior source evidence', () => {
+ it('requests bounded JSON source and highlights only a verified line', async () => {
+ vi.mocked(callToolJson).mockResolvedValue(snippet); await render();
+ expect(callToolJson).toHaveBeenCalledWith('get_code_snippet', expect.objectContaining({ format: 'json', source_mode: 'full', max_lines: 32 }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ expect(container.querySelector('[data-selected="true"]')?.textContent).toContain('start()');
+ });
+ it('rejects source identity/range mismatches instead of attaching it to the selected call', async () => {
+ vi.mocked(callToolJson).mockResolvedValue({ ...snippet, qualified_name: 'other.start' }); await render();
+ expect(container.querySelector('pre')).toBeNull(); expect(container.textContent).toContain('Source identity changed');
+ vi.mocked(callToolJson).mockResolvedValue({ ...snippet, end_line: 15 }); await render('another');
+ expect(container.querySelector('pre')).toBeNull(); expect(container.textContent).toContain('Source line range could not be verified');
+ });
+ it('aborts and ignores a source reply after the project changes', async () => {
+ let finish!: (value: unknown) => void;
+ vi.mocked(callToolJson).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })).mockResolvedValue({ ...snippet, source: 'new()\nnext()' });
+ await render(); const signal = vi.mocked(callToolJson).mock.calls[0][2]?.signal;
+ await render('other'); expect(signal?.aborted).toBe(true);
+ await act(async () => finish(snippet)); expect(container.textContent).toContain('new()'); expect(container.textContent).not.toContain('start()');
+ });
+ it('does not request source for an inactive workspace', async () => { await render('sample', false); expect(callToolJson).not.toHaveBeenCalled(); });
+});
diff --git a/graph-ui/src/architecture/BehaviorSourceEvidence.tsx b/graph-ui/src/architecture/BehaviorSourceEvidence.tsx
new file mode 100644
index 000000000..cd6c904c6
--- /dev/null
+++ b/graph-ui/src/architecture/BehaviorSourceEvidence.tsx
@@ -0,0 +1,60 @@
+import { useEffect, useState } from 'react';
+import { callToolJson } from '../provider/rpc-transport';
+import { readCodeSnippet, type CodeSnippetResult } from '../provider/rpc-schemas';
+import type { SystemPathEdge, SystemSymbol } from './system-architecture-source';
+
+/** A small, current-source window. It never turns nearby syntax into an inferred guard. */
+export default function BehaviorSourceEvidence({ project, generation, symbol, call, active, onNavigate }: {
+ project: string; generation?: string; symbol: SystemSymbol; call?: SystemPathEdge; active: boolean;
+ onNavigate: (path: string, line?: number, name?: string) => void;
+}) {
+ const line = call?.callsite?.line ?? symbol.start_line;
+ const file = call?.callsite?.file_path ?? symbol.file_path;
+ const key = JSON.stringify([project, generation, symbol.qualified_name, file, line]);
+ const [reading, setReading] = useState<{ key: string; source?: CodeSnippetResult; error?: string }>();
+ const current = reading?.key === key ? reading : undefined;
+ useEffect(() => {
+ if (!active || !file || !symbol.qualified_name) return;
+ const controller = new AbortController();
+ setReading({ key });
+ void (async () => {
+ try {
+ const source = readCodeSnippet(await callToolJson('get_code_snippet', {
+ project, qualified_name: symbol.qualified_name, source_mode: 'full', format: 'json',
+ start_line: Math.max(1, (line ?? 1) - 8), max_lines: 32,
+ }, { signal: controller.signal }));
+ if (controller.signal.aborted) return;
+ const path = source.file_path?.replaceAll('\\', '/');
+ if (source.qualified_name && source.qualified_name !== symbol.qualified_name)
+ throw new Error('Source identity changed. Refresh the analysis before following this call.');
+ if (!path || (path !== file && !path.endsWith(`/${file}`)))
+ throw new Error('The returned source does not match this call location.');
+ if (source.source_mode && source.source_mode !== 'full') throw new Error('Full source is unavailable for this operation.');
+ const lines = source.source.split('\n');
+ const count = source.end_line !== undefined && source.start_line !== undefined ? source.end_line - source.start_line + 1 : 0;
+ if (lines.at(-1) === '' && lines.length - 1 === count) lines.pop();
+ if (!source.start_line || !source.end_line || count < 1 || lines.length !== count)
+ throw new Error('Source line range could not be verified. Open the definition to inspect it.');
+ if (line && (line < source.start_line || line > source.end_line))
+ throw new Error('The indexed location is outside the current source window. The file may have changed.');
+ setReading({ key, source: { ...source, source: lines.join('\n') } });
+ } catch (error) {
+ if (!controller.signal.aborted) setReading({ key, error: error instanceof Error ? error.message : 'Could not read this source.' });
+ }
+ })();
+ return () => controller.abort();
+ }, [project, generation, symbol.qualified_name, file, line, key, active]);
+ return <section className="behavior-source" aria-label="Behavior source evidence">
+ <div className="behavior-source-heading"><h4>{call?.callsite ? 'Code at this call' : 'Operation source'}</h4>
+ {file && <button onClick={() => onNavigate(file, line, symbol.name)}>Open source ↗</button>}</div>
+ {!file ? <p>Source location unavailable.</p> : <>
+ <p className="behavior-source-location">{file}{line ? `:${line}` : ''}</p>
+ {current?.error ? <p role="status">{current.error}</p> : !current?.source ? <p role="status">{active ? 'Reading source…' : 'Source reading paused.'}</p>
+ : <pre aria-label="Code at selected operation"><code>{current.source.source.split('\n').map((text, index) => {
+ const number = current.source!.start_line! + index;
+ return <span key={number} data-selected={number === line}><i aria-hidden="true">{number}</i>{text || ' '}{'\n'}</span>;
+ })}</code></pre>}
+ <small>Current local source · may differ from the indexed snapshot.</small>
+ </>}
+ </section>;
+}
diff --git a/graph-ui/src/architecture/ContainerMap.test.tsx b/graph-ui/src/architecture/ContainerMap.test.tsx
new file mode 100644
index 000000000..9e2c90c52
--- /dev/null
+++ b/graph-ui/src/architecture/ContainerMap.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import ContainerMap from './ContainerMap';
+import { loadContainerInventory, loadContainerTopology } from './container-source';
+import type { ContainerReading } from './container-source';
+vi.mock('./ArchitectureScene', () => ({ ArchitectureScene: ({ onOpen, onClearSelection }: { onOpen: (id: string) => void; onClearSelection?: () => void }) => <div><button data-testid="open-service" onDoubleClick={() => onOpen('web')}>3D scene</button><button onClick={onClearSelection}>Empty background</button></div> }));
+vi.mock('../provider/rpc-client', () => ({ RpcIntelligenceClient: class { listProjects = async () => ({ projects: [{ name: 'p', root_path: '/p' }] }); } }));
+vi.mock('./container-source', () => ({ loadContainerInventory: vi.fn(), loadContainerTopology: vi.fn() }));
+let container: HTMLDivElement, root: Root;
+const sample = (): ContainerReading => ({ projects: [], warnings: [], filesRead: 3, topology: {
+ services: ['web', 'db', 'isolated'].map(id => ({ id, name: id, project: 'p', manifest: 'compose.yml', line: id === 'web' ? 2 : 5,
+ sourcePaths: [], networks: ['p:default'], ports: [], image: 'fixture:1' })),
+ connections: [{ id: 'call', source: 'web', target: 'db', kind: 'call', protocol: 'postgres', evidence: [{ project: 'p', path: 'api.ts', line: 7, summary: 'Connects to db' }] },
+ { id: 'startup', source: 'web', target: 'db', kind: 'startup', protocol: 'depends_on', evidence: [{ project: 'p', path: 'compose.yml', line: 4, summary: 'Depends on db' }] }],
+ warnings: [], unresolved: [],
+} });
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);
+ vi.mocked(loadContainerInventory).mockResolvedValue({ project: 'p', rootPath: '/p', files: new Map(), manifests: ['compose.yml'], warnings: [] });
+ vi.mocked(loadContainerTopology).mockResolvedValue(sample());
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.clearAllMocks(); });
+const button = (text: string) => [...container.querySelectorAll('button')].find(element => element.textContent === text)!;
+describe('service map interactions', () => {
+ it('keeps isolated services visible and distinguishes calls from optional startup edges', async () => {
+ await act(async () => root.render(<ContainerMap project="p" active filter="" onNavigate={vi.fn()} />));
+ expect(container.textContent).toContain('3 / 3 services · 1 connections shown');
+ expect(container.querySelector('[aria-label="All declared services"]')?.textContent).toContain('isolated');
+ const startup = [...container.querySelectorAll('label')].find(label => label.textContent === 'Startup dependencies')!.querySelector('input')!;
+ await act(async () => startup.click());
+ expect(container.textContent).toContain('3 / 3 services · 2 connections shown');
+ });
+ it('opens exact evidence locations and focuses a service with its neighbors', async () => {
+ const navigate = vi.fn();
+ await act(async () => root.render(<ContainerMap project="p" active filter="" onNavigate={navigate} />));
+ const web = container.querySelector('[aria-label="All declared services"] button')!;
+ await act(async () => (web as HTMLButtonElement).click());
+ await act(async () => button('Open declaration').click()); expect(navigate).toHaveBeenCalledWith('compose.yml', 2);
+ await act(async () => button('Focus service').click()); expect(container.textContent).toContain('2 / 3 services');
+ await act(async () => button('All services').click()); expect(container.textContent).toContain('3 / 3 services');
+ });
+ it('returns from a focused neighborhood to all services and clears the inspector on empty background', async () => {
+ const clear = vi.fn();
+ await act(async () => root.render(<ContainerMap project="p" active filter="" onNavigate={vi.fn()} onClearSelection={clear} />));
+ await act(async () => container.querySelector('[data-testid="open-service"]')!.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));
+ expect(container.textContent).toContain('2 / 3 services');
+ expect(button('Open declaration')).toBeDefined();
+ await act(async () => button('Empty background').click());
+ expect(container.textContent).toContain('3 / 3 services');
+ expect(button('Open declaration')).toBeUndefined();
+ expect(clear).toHaveBeenCalledOnce();
+ });
+ it('does not request deployment source while the workspace is inactive', async () => {
+ await act(async () => root.render(<ContainerMap project="p" active={false} filter="" onNavigate={vi.fn()} />));
+ expect(loadContainerTopology).not.toHaveBeenCalled(); expect(loadContainerInventory).not.toHaveBeenCalled();
+ });
+});
diff --git a/graph-ui/src/architecture/ContainerMap.tsx b/graph-ui/src/architecture/ContainerMap.tsx
new file mode 100644
index 000000000..a10716c64
--- /dev/null
+++ b/graph-ui/src/architecture/ContainerMap.tsx
@@ -0,0 +1,169 @@
+import { Component, useEffect, useMemo, useState, type ReactNode } from 'react';
+import { RpcIntelligenceClient } from '../provider/rpc-client';
+import type { ProjectEntry } from '../provider/rpc-schemas';
+import { ArchitectureScene } from './ArchitectureScene';
+import { layoutContainers } from './container-layout';
+import { loadContainerInventory, loadContainerTopology, type ContainerReading, type ContainerSelection } from './container-source';
+import type { ServiceEvidence } from './container-topology';
+import './spatial-architecture.css';
+import './container-map.css';
+
+interface Props { project: string; generation?: string; active: boolean; filter: string; onNavigate: (path: string, line?: number) => void; onClearSelection?: () => void }
+class ContainerSceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() { return { failed: true }; }
+ render() { return this.state.failed ? <p className="spatial-unavailable">3D is unavailable. Use the service and connection lists to inspect the same evidence.</p> : this.props.children; }
+}
+const evidenceLabel = (kind: string) => kind === 'startup' ? 'Startup dependency' : kind === 'configuration' ? 'Configured destination' : 'Call found in source';
+const relativeSource = (absolute: string, selection: ContainerSelection) => {
+ const prefix = selection.inventory.rootPath.replaceAll('\\', '/').replace(/\/$/, '') + '/';
+ return absolute.startsWith(prefix) ? absolute.slice(prefix.length) : undefined;
+};
+
+export default function ContainerMap({ project, generation, active, filter, onNavigate, onClearSelection }: Props) {
+ const [available, setAvailable] = useState<ProjectEntry[]>([]);
+ const [selections, setSelections] = useState<ContainerSelection[]>([]);
+ const [discovery, setDiscovery] = useState('Finding indexed Compose definitions…');
+ const [reading, setReading] = useState<{ key: string; result?: ContainerReading; error?: string }>();
+ const [revision, setRevision] = useState(0);
+ const [discoveryRevision, setDiscoveryRevision] = useState(0);
+ const [startup, setStartup] = useState(false);
+ const [configured, setConfigured] = useState(true);
+ const [planar, setPlanar] = useState(false);
+ const [resetKey, setResetKey] = useState(0);
+ const [selected, setSelected] = useState<{ key: string; node?: string; edge?: string }>();
+ const [focus, setFocus] = useState<string>();
+ const [adding, setAdding] = useState(false);
+ const [source, setSource] = useState<{ key: string; evidence: ServiceEvidence; text?: string; error?: string }>();
+ const [memberLimit, setMemberLimit] = useState(12);
+ useEffect(() => {
+ if (!active) return;
+ const controller = new AbortController(), client = new RpcIntelligenceClient({ signal: controller.signal });
+ setDiscovery('Finding indexed Compose definitions…');
+ void client.listProjects().then(async response => {
+ const projects = response.projects;
+ const current = projects.find(entry => entry.name === project);
+ if (!current) throw new Error('Project is no longer indexed.');
+ const inventory = await loadContainerInventory(current, client);
+ if (controller.signal.aborted) return;
+ setAvailable(projects); setSelections([{ inventory, manifest: inventory.manifests[0] ?? '' }]);
+ setDiscovery(inventory.manifests.length ? '' : 'No indexed Compose file was found. The Endpoints view is still available.');
+ }).catch(() => { if (!controller.signal.aborted) setDiscovery('Could not read the indexed deployment files. Refresh to try again.'); });
+ return () => controller.abort();
+ }, [project, active, generation, discoveryRevision]);
+ const selectionKey = JSON.stringify(selections.map(item => [item.inventory.project, item.manifest]));
+ const key = `${project}:${generation ?? ''}:${selectionKey}:${revision}`;
+ useEffect(() => {
+ if (!active || !selections.length || selections[0].inventory.project !== project || !selections.some(item => item.manifest)) return;
+ const controller = new AbortController(), client = new RpcIntelligenceClient({ signal: controller.signal });
+ setReading({ key }); setFocus(undefined); setSource(undefined);
+ void loadContainerTopology(selections, client, controller.signal).then(result => {
+ if (!controller.signal.aborted) setReading({ key, result });
+ }).catch(() => { if (!controller.signal.aborted) setReading({ key, error: 'Could not complete service inspection. Refresh to try again.' }); });
+ return () => controller.abort();
+ }, [active, project, key, selections]);
+ const result = reading?.key === key ? reading.result : undefined;
+ const topology = result?.topology;
+ const layout = useMemo(() => topology ? layoutContainers(topology) : undefined, [topology]);
+ const selectedService = selected?.key === key ? topology?.services.find(service => service.id === selected.node) : undefined;
+ const selectedEdge = selected?.key === key ? topology?.connections.find(edge => edge.id === selected.edge) : undefined;
+ const shownEdges = useMemo(() => topology?.connections.filter(edge => (startup || edge.kind !== 'startup') && (configured || edge.kind !== 'configuration')) ?? [], [topology, startup, configured]);
+ const graph = useMemo(() => {
+ if (!layout || !topology) return undefined;
+ const connected = new Set<string>(focus ? [focus] : []);
+ if (focus) shownEdges.forEach(edge => { if (edge.source === focus || edge.target === focus) { connected.add(edge.source); connected.add(edge.target); } });
+ const query = filter.trim().toLowerCase();
+ const ids = new Set(topology.services.filter(service => (!focus || connected.has(service.id))
+ && (!query || `${service.name} ${service.project} ${service.image ?? ''}`.toLowerCase().includes(query))).map(service => service.id));
+ const edges = new Set(shownEdges.filter(edge => ids.has(edge.source) && ids.has(edge.target)).map(edge => edge.id));
+ return { ...layout.graph, scopeKey: `${layout.graph.scopeKey}:${focus ?? ''}`,
+ nodes: layout.graph.nodes.filter(node => ids.has(node.id)), edges: layout.graph.edges.filter(edge => edges.has(edge.id)),
+ omittedNodes: layout.graph.nodes.length - ids.size, omittedEdges: layout.graph.edges.length - edges.size };
+ }, [layout, topology, filter, focus, shownEdges]);
+ const servicesById = useMemo(() => new Map(topology?.services.map(service => [service.id, service]) ?? []), [topology]);
+ const clearSelection = () => { setSelected(undefined); setFocus(undefined); setSource(undefined); setResetKey(value => value + 1); onClearSelection?.(); };
+ const selectService = (id: string) => { setSelected({ key, node: id }); setMemberLimit(12); setSource(undefined); };
+ const inspect = (evidence: ServiceEvidence) => {
+ if (evidence.project === project) { onNavigate(evidence.path, evidence.line); return; }
+ setSource({ key, evidence });
+ };
+ const sourceEvidence = source?.key === key ? source.evidence : undefined;
+ useEffect(() => {
+ if (!sourceEvidence) return;
+ const inventory = selections.find(selection => selection.inventory.project === sourceEvidence.project)?.inventory;
+ const qn = inventory?.files.get(sourceEvidence.path);
+ if (!qn) { setSource({ key, evidence: sourceEvidence, error: 'This source location is not in the selected project inventory.' }); return; }
+ const controller = new AbortController(), client = new RpcIntelligenceClient({ signal: controller.signal });
+ void client.getCodeSnippet(sourceEvidence.project, qn, { startLine: Math.max(1, sourceEvidence.line - 2), maxLines: 12 }).then(snippet => {
+ if (!controller.signal.aborted) setSource({ key, evidence: sourceEvidence, text: snippet.source });
+ }).catch(() => { if (!controller.signal.aborted) setSource({ key, evidence: sourceEvidence, error: 'Source evidence is unavailable.' }); });
+ return () => controller.abort();
+ }, [sourceEvidence, key, selections]);
+ const addProject = async (name: string) => {
+ const entry = available.find(item => item.name === name);
+ if (!entry || adding || selections.length >= 4) return;
+ setAdding(true);
+ try {
+ const inventory = await loadContainerInventory(entry, new RpcIntelligenceClient());
+ setSelections(current => current.some(item => item.inventory.project === name) ? current : [...current, { inventory, manifest: inventory.manifests[0] ?? '' }]);
+ } catch { setDiscovery('Could not read that project. Its index may be unavailable.'); }
+ finally { setAdding(false); }
+ };
+ const evidenceButton = (evidence: ServiceEvidence, index: number) => <button key={`${evidence.project}:${evidence.path}:${evidence.line}:${index}`} onClick={() => inspect(evidence)}>
+ {evidence.summary}<small>{evidence.project} / {evidence.path}:{evidence.line}</small></button>;
+ const incident = selectedService ? shownEdges.filter(edge => edge.source === selectedService.id || edge.target === selectedService.id) : [];
+ const warnings = [...new Set([...(topology?.warnings ?? []), ...(result?.warnings ?? [])])];
+ return <section className="spatial-architecture container-map" aria-label="Container service map">
+ <header className="spatial-heading"><div><span className="spatial-eyebrow">Routes / Services</span><h2>How the services connect</h2>
+ <p>One square per declared service. Follow a connection to see the configuration and code behind it.</p></div>
+ <div className="spatial-camera-controls"><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><button onClick={() => {
+ setRevision(value => value + 1);
+ if (!selections.length || !selections[0].inventory.manifests.length) setDiscoveryRevision(value => value + 1);
+ }}>Refresh</button></div></header>
+ <div className="container-projects" aria-label="Deployment sources">{selections.map((selection, index) => <label key={selection.inventory.project}><span>{selection.inventory.project}</span>
+ <select aria-label={`Compose file for ${selection.inventory.project}`} value={selection.manifest} onChange={event => setSelections(current => current.map((item, i) => i === index ? { ...item, manifest: event.target.value } : item))}>
+ <option value="">Source only</option>{selection.inventory.manifests.map(path => <option key={path}>{path}</option>)}</select>
+ {index > 0 && <button aria-label={`Remove ${selection.inventory.project}`} onClick={() => setSelections(current => current.filter((_, i) => i !== index))}>×</button>}</label>)}
+ {selections.length < 4 && <select aria-label="Compare indexed project" value="" disabled={adding} onChange={event => { void addProject(event.target.value); }}><option value="">{adding ? 'Reading project…' : '+ Compare project'}</option>
+ {available.filter(entry => !selections.some(selection => selection.inventory.project === entry.name)).map(entry => <option key={entry.name} value={entry.name}>{entry.name}</option>)}</select>}</div>
+ <div className="spatial-controls"><nav aria-label="Service navigation"><button onClick={clearSelection}>All services</button>{focus && <span> / {servicesById.get(focus)?.name} and neighbors</span>}</nav>
+ <div className="container-edge-key"><span><i className="container-call-key" />Calls</span><label><input type="checkbox" checked={configured} onChange={event => setConfigured(event.target.checked)} />Configured destinations</label>
+ <label><input type="checkbox" checked={startup} onChange={event => setStartup(event.target.checked)} />Startup dependencies</label></div></div>
+ {discovery && <p role="status" className="spatial-notice">{discovery}</p>}
+ {!discovery && selections.length > 0 && !selections.some(selection => selection.manifest) && <p className="spatial-notice">Select a Compose file to show its declared services.</p>}
+ {reading?.key === key && !result && <p role="status" className="spatial-notice">{reading.error ?? 'Reading deployment definitions and bounded source evidence…'}</p>}
+ {graph && topology && <><div className="spatial-map-layout"><div className="spatial-map">
+ {graph.nodes.length ? <ContainerSceneBoundary key={key}><ArchitectureScene model={graph} active={active} planar={planar} resetKey={resetKey} adaptiveLabels={graph.nodes.length > 16}
+ selectedId={selectedService?.id} selectedEdgeId={selectedEdge?.id} onSelect={selectService} onSelectEdge={id => { setSelected({ key, edge: id }); setSource(undefined); }}
+ onClearSelection={clearSelection} onOpen={id => { selectService(id); setFocus(id); }} /></ContainerSceneBoundary> : <p className="spatial-unavailable">No matching service declarations in the selected files.</p>}
+ <div className="spatial-map-caption"><span>Static declarations · not live containers</span><span>Double-click a square to focus · select an arrow for evidence</span></div></div>
+ <aside className="spatial-inspector" aria-label="Service inspector">
+ {selectedService ? <><span className="spatial-eyebrow">Declared service</span><h3>{selectedService.name}</h3><p className="spatial-muted">{selectedService.project}</p>
+ <button className="spatial-primary" onClick={() => setFocus(selectedService.id)}>Focus service</button>
+ <button onClick={() => inspect({ project: selectedService.project, path: selectedService.manifest, line: selectedService.line, summary: 'Service declaration' })}>Open declaration</button>
+ <dl className="container-facts"><dt>Image</dt><dd>{selectedService.image ?? 'Built locally'}</dd><dt>Networks</dt><dd>{selectedService.networks.map(network => network.split(':').at(-1)).join(', ') || 'No resolved network'}</dd>
+ <dt>Ports</dt><dd>{selectedService.ports.join(', ') || 'Not declared'}</dd>{Boolean(selectedService.profiles?.length) && <><dt>Profiles</dt><dd>{selectedService.profiles!.join(', ')} · optional</dd></>}
+ <dt>Source</dt><dd>{selectedService.sourcePaths.length ? `${selectedService.sourcePaths.length} candidate files` : 'Image-only or unresolved ownership'}</dd></dl>
+ <div className="spatial-members"><h4>Connections</h4>{incident.length ? incident.map(edge => <button key={edge.id} onClick={() => setSelected({ key, edge: edge.id })}>{servicesById.get(edge.source)?.name} → {servicesById.get(edge.target)?.name}<small>{evidenceLabel(edge.kind)} · {edge.protocol}</small></button>) : <p>No detected connections with the current filters.</p>}
+ <h4>Source files</h4>{selectedService.sourcePaths.slice(0, memberLimit).map(absolute => {
+ const owner = selections.find(selection => { const path = relativeSource(absolute, selection); return path !== undefined && selection.inventory.files.has(path); });
+ const path = owner && relativeSource(absolute, owner);
+ return path && owner ? <button key={absolute} onClick={() => inspect({ project: owner.inventory.project, path, line: 1, summary: 'Candidate source file' })}>{path}<small>{owner.inventory.project}</small></button> : <span key={absolute}>{absolute}</span>;
+ })}{selectedService.sourcePaths.length > memberLimit && <button onClick={() => setMemberLimit(value => value + 24)}>Show more files</button>}</div></>
+ : selectedEdge ? <><span className="spatial-eyebrow">{evidenceLabel(selectedEdge.kind)}</span><h3>{servicesById.get(selectedEdge.source)?.name} → {servicesById.get(selectedEdge.target)?.name}</h3><p>{selectedEdge.protocol}</p>
+ <p className="spatial-muted">{selectedEdge.kind === 'startup' ? 'The deployment declares a startup dependency. This does not establish a network call.' : selectedEdge.kind === 'configuration' ? 'Configuration names this destination. An executed call has not been established.' : 'Static source identifies this destination. The arrow shows the caller, not the direction of every payload.'}</p>
+ <div className="spatial-members">{selectedEdge.evidence.map(evidenceButton)}</div></>
+ : <><span className="spatial-eyebrow">Read the map</span><h3>Services, with evidence.</h3><p>Blue squares have candidate source files. Warm squares have an image declaration or unresolved source ownership.</p><p className="spatial-muted">Compare another indexed project to find connections over explicitly shared networks. Unresolved hosts remain findings, not guessed arrows.</p></>}
+ {source?.key === key && <div className="container-source"><h4>{source.evidence.project} / {source.evidence.path}:{source.evidence.line}</h4><button onClick={() => setSource(undefined)}>Close source</button><pre>{source.error ?? source.text ?? 'Reading source…'}</pre></div>}
+ </aside></div>
+ <div className="spatial-bottom"><span>{graph.nodes.length} / {topology.services.length} services · {graph.edges.length} connections shown</span><span>{result?.filesRead} source files inspected · {topology.unresolved.length} unresolved findings</span></div>
+ <div className="container-service-list" aria-label="All declared services">{topology.services.map(service => <button key={service.id} aria-pressed={selectedService?.id === service.id} onClick={() => selectService(service.id)} onDoubleClick={() => { selectService(service.id); setFocus(service.id); }}>{service.name}<small>{service.project}{service.profiles?.length ? ' · optional' : ''}</small></button>)}</div>
+ {!!layout?.cycles.length && <details className="spatial-coverage"><summary>Dependency cycles · {layout.cycles.length}</summary>{layout.cycles.map(cycle => <p key={cycle.join('|')}>{cycle.map(id => servicesById.get(id)?.name).join(' ↔ ')} · mutually reachable through detected calls or configured destinations</p>)}</details>}
+ <details className="spatial-relationship-list"><summary>All connections · {shownEdges.length}</summary><div>{shownEdges.map(edge => <button key={edge.id} onClick={() => setSelected({ key, edge: edge.id })}>{servicesById.get(edge.source)?.name} → {servicesById.get(edge.target)?.name}<small>{evidenceLabel(edge.kind)} · {edge.protocol}</small></button>)}</div></details>
+ {!!topology.unresolved.length && <details className="spatial-coverage"><summary>Unresolved destinations · {topology.unresolved.length}</summary><div className="spatial-members">{topology.unresolved.map(evidenceButton)}</div></details>}
+ </>}
+ <details className="spatial-coverage"><summary>Coverage and interpretation{warnings.length ? ` · ${warnings.length} notes` : ''}</summary><p>One selected Compose file per project. Overrides, includes, host environment values, and running-container state are not evaluated. Source grouping is inferred from build inputs, not guaranteed exclusive ownership.</p>
+ {warnings.map(warning => <p key={warning}>{warning}</p>)}</details>
+ </section>;
+}
diff --git a/graph-ui/src/architecture/RoutesArchitecture.tsx b/graph-ui/src/architecture/RoutesArchitecture.tsx
new file mode 100644
index 000000000..c8891486b
--- /dev/null
+++ b/graph-ui/src/architecture/RoutesArchitecture.tsx
@@ -0,0 +1,15 @@
+import { lazy, Suspense, useState, type ComponentProps } from 'react';
+import SpatialArchitecture from './SpatialArchitecture';
+import './container-map.css';
+const ContainerMap = lazy(() => import('./ContainerMap'));
+
+/** The endpoint graph remains available independently of deployment metadata. */
+export default function RoutesArchitecture(props: ComponentProps<typeof SpatialArchitecture>) {
+ const [mode, setMode] = useState<'services' | 'endpoints'>('services');
+ return <><nav className="container-mode" aria-label="Routes perspective">
+ <button aria-pressed={mode === 'services'} onClick={() => setMode('services')}>Service map</button>
+ <button aria-pressed={mode === 'endpoints'} onClick={() => setMode('endpoints')}>Endpoints</button>
+ </nav>{mode === 'services' ? <Suspense fallback={<p role="status">Preparing service map…</p>}><ContainerMap
+ project={props.project} generation={props.generation} active={props.active} filter={props.filter} onNavigate={props.onNavigate} onClearSelection={props.onClearSelection} /></Suspense>
+ : <SpatialArchitecture {...props} />}</>;
+}
diff --git a/graph-ui/src/architecture/SourceMetricsDetails.tsx b/graph-ui/src/architecture/SourceMetricsDetails.tsx
new file mode 100644
index 000000000..89dba9733
--- /dev/null
+++ b/graph-ui/src/architecture/SourceMetricsDetails.tsx
@@ -0,0 +1,16 @@
+import type { SourceCatalog, SourceMeasure } from './source-metrics';
+
+export default function SourceMetricsDetails({ measure, catalog }: { measure: SourceMeasure; catalog: SourceCatalog }) {
+ const share = measure.lines !== undefined && catalog.total.lines ? Math.min(100, measure.lines / catalog.total.lines * 100) : undefined;
+ const denominator = measure.lines || measure.files || 1;
+ return <div className="spatial-source-metrics" aria-label="Source size and languages">
+ <div className="spatial-source-total"><strong>{measure.lines === undefined ? 'Unknown' : `${measure.measuredFiles < measure.files ? '≥ ' : ''}${measure.lines.toLocaleString()}`}</strong><span>indexed source lines</span></div>
+ <small>Includes comments and blank lines. Each measured file counts once.</small>
+ {share !== undefined && <div className="spatial-source-share"><span>{share.toFixed(1)}% of measured project lines</span><div role="meter" aria-label="Share of measured project lines" aria-valuenow={share} aria-valuemin={0} aria-valuemax={100}><i style={{ width: `${share}%` }} /></div></div>}
+ <small>{measure.measuredFiles} / {measure.files} files measured{measure.measuredFiles < measure.files ? ' · remaining sizes unknown' : ''}</small>
+ <h4>Language mix <span>· {measure.lines ? 'measured lines' : 'files'}</span></h4>
+ <div className="spatial-language-bar" aria-hidden="true">{measure.languages.map(language => <i key={language.name} style={{ background: language.color, flex: measure.lines ? language.lines : language.files }} />)}</div>
+ <ul className="spatial-language-breakdown">{measure.languages.map(language => <li key={language.name}><i style={{ background: language.color }} /><span>{language.name}</span><span>{((measure.lines ? language.lines : language.files) / denominator * 100).toFixed(1)}%</span></li>)}</ul>
+ <small>Language inferred from file type. A mixed file may contain other languages.</small>
+ </div>;
+}
diff --git a/graph-ui/src/architecture/SpatialArchitecture.test.tsx b/graph-ui/src/architecture/SpatialArchitecture.test.tsx
index 045105207..78dea4856 100644
--- a/graph-ui/src/architecture/SpatialArchitecture.test.tsx
+++ b/graph-ui/src/architecture/SpatialArchitecture.test.tsx
@@ -8,7 +8,7 @@ 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('./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>)}<button aria-label="Empty background" onClick={props.onClearSelection} /></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: '' };
@@ -37,6 +37,16 @@ it('drills inferred areas to files and symbols before enabling real-node impact
expect(host.textContent).toContain('Analyze selected symbol');
await click('Open source'); expect(onNavigate).toHaveBeenCalledWith('src/api/main.ts', 12, 'start');
});
+it('returns from a file symbol to the repository map on empty background', async () => {
+ const clear = vi.fn();
+ await act(async () => root.render(<SpatialArchitecture project="sample" graph={graph} overview={overview} view="overview" filter="" active onSelect={vi.fn()} onClearSelection={clear} onNavigate={vi.fn()} onView={vi.fn()} selectionPanel={<button>Analyze selected symbol</button>} />));
+ await click('src/api'); await click('Open area →'); await click('src/api/main.ts'); await click('Open file symbols →'); await click('start');
+ expect(host.textContent).toContain('Analyze selected symbol');
+ await act(async () => host.querySelector<HTMLButtonElement>('[aria-label="Empty background"]')!.click());
+ expect(host.querySelector('[data-testid="scene"]')?.textContent).toContain('src/api');
+ expect(host.textContent).not.toContain('Analyze selected symbol');
+ expect(clear).toHaveBeenCalledOnce();
+});
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 />));
@@ -61,6 +71,32 @@ 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('explains the brick encodings and allows a uniform-height structural view', async () => {
+ await act(async () => root.render(<SpatialArchitecture project="sample" graph={graph} overview={overview} view="overview" filter="" active onNavigate={vi.fn()} onView={vi.fn()} />));
+ const height = host.querySelector<HTMLSelectElement>('select[aria-label="Brick height"]');
+ expect(height).not.toBeNull();
+ expect(height?.value).toBe('lines');
+ expect(height?.selectedOptions[0].textContent).toBe('Source size');
+ expect(host.querySelector('select[aria-label="Brick color"]')).not.toBeNull();
+ await act(async () => { height!.value = 'uniform'; height!.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(height?.value).toBe('uniform');
+ expect(height?.selectedOptions[0].textContent).toBe('Uniform');
+});
+it('keeps isolated and coverage-only files reachable through the inventory and visibility filter', async () => {
+ const coverage = { records: new Map([['assets/logo.svg', { path: 'assets/logo.svg', kind: 'file' as const, state: 'not-indexed' as const, reason: 'excluded type', sources: ['coverage'] }]]),
+ truncations: [], counts: { partial: 0, skipped: 0, notIndexedDirs: 0, notIndexedFiles: 1, scopeEntries: 1 } };
+ const onNavigate = vi.fn();
+ await act(async () => root.render(<SpatialArchitecture project="sample" graph={graph} overview={{ ...overview, files: ['src/api/main.ts', 'empty/unused.ts'] }} coverage={coverage} view="overview" filter="" active onNavigate={onNavigate} onView={vi.fn()} />));
+ expect(host.textContent).toContain('File inventory · 3 known files');
+ expect(host.textContent).toContain('assets/logo.svg');
+ const files = host.querySelector<HTMLSelectElement>('select[aria-label="File visibility"]')!;
+ await act(async () => { files.value = 'connected'; files.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(host.querySelector('.spatial-inventory-list')?.textContent).toBe('');
+ await act(async () => { files.value = 'all'; files.dispatchEvent(new Event('change', { bubbles: true })); });
+ const read = host.querySelector<HTMLButtonElement>('button[aria-label="Read assets/logo.svg"]')!;
+ await act(async () => read.click());
+ expect(onNavigate).toHaveBeenCalledWith('assets/logo.svg', 1);
+});
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() };
diff --git a/graph-ui/src/architecture/SpatialArchitecture.tsx b/graph-ui/src/architecture/SpatialArchitecture.tsx
index fe266746c..9c0153838 100644
--- a/graph-ui/src/architecture/SpatialArchitecture.tsx
+++ b/graph-ui/src/architecture/SpatialArchitecture.tsx
@@ -4,14 +4,19 @@ 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 { collectSourceMetrics, measureSourceNode } from './source-metrics';
+import SourceMetricsDetails from './SourceMetricsDetails';
+import type { CoverageIndex } from '../app/tree-model';
+import { buildHotspotGraph, collectHotspots, hotspotsForNode, hotspotSignals, hotspotIdentity, gravityPercent } from './hotspot-map';
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;
+ onSelect?: (node: GraphNode) => void; onClearSelection?: () => void; selectionPanel?: ReactNode;
onView: (view: SemanticView) => void;
onNavigate: (path: string, line?: number, name?: string) => void;
+ coverage?: CoverageIndex;
}
class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
@@ -27,16 +32,23 @@ const viewNotes: Record<SemanticView, string> = {
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.',
+ hotspots: 'Inspect ranked symbols and their connections. Gravity wells grow with static fan-in; select a finding to read its measured signals.',
};
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) {
+export default function SpatialArchitecture({ project, generation, graph, overview, view, filter, active, graphNote, onSelect, onClearSelection, selectionPanel, onNavigate, onView, coverage }: 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 [heightMetric, setHeightMetric] = useState<'lines' | 'uniform'>('lines');
+ const [colorMetric, setColorMetric] = useState<'language' | 'kind'>('language');
+ const [fileVisibility, setFileVisibility] = useState<'all' | 'connected' | 'unconnected'>('all');
+ const [inventoryFilter, setInventoryFilter] = useState('');
+ const [inventoryLimit, setInventoryLimit] = useState(24);
+ const [showHotspots, setShowHotspots] = useState(true);
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 }>();
@@ -59,13 +71,23 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
? 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, {
+ const knownFiles = useMemo(() => [...new Set([...overview.files, ...[...(coverage?.records.values() ?? [])].filter(record => record.kind === 'file').map(record => record.path)])], [overview.files, coverage]);
+ const catalog = useMemo(() => collectSourceMetrics(graph, knownFiles), [graph, knownFiles]);
+ const hotspotCatalog = useMemo(() => collectHotspots(overview.hotspots, graph), [overview.hotspots, graph]);
+ const visibleFiles = useMemo(() => fileVisibility === 'all' || !['overview', 'dependencies'].includes(view) ? undefined : new Set([...catalog.files.values()]
+ .filter(file => fileVisibility === 'connected' ? file.connection === 'connected' : file.connection !== 'connected').map(file => file.path)), [catalog, fileVisibility, view]);
+ const inventoryFiles = useMemo(() => [...catalog.files.values()].filter(file => (!visibleFiles || visibleFiles.has(file.path))
+ && file.path.toLowerCase().includes(inventoryFilter.trim().toLowerCase())).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0), [catalog, visibleFiles, inventoryFilter]);
+ const model = useMemo(() => view === 'hotspots' ? buildHotspotGraph(graph, hotspotCatalog, filter) : 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]);
+ routes: overview.routes, routeSnapshot, knownFiles: [...catalog.files.keys()], visibleFiles,
+ }), [graph, view, areaPath, filePath, currentEntry?.id, depth, filter, relations, overview.routes, overview.entryPoints, routeSnapshot, catalog, visibleFiles, hotspotCatalog]);
+ const hasSourceBricks = model.nodes.some(node => node.kind === 'area' || node.kind === 'file');
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 selectedMeasure = selectedNode ? measureSourceNode(selectedNode, catalog) : undefined;
+ const selectedHotspots = selectedNode ? hotspotsForNode(selectedNode, hotspotCatalog) : 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) => {
@@ -76,10 +98,10 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
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');
+ if (view === 'routes' || view === 'hotspots') onView('overview');
setSelection(undefined);
};
- const clearScope = () => { setAreaPath(undefined); setFilePath(undefined); setSelection(undefined); };
+ const clearScope = () => { setAreaPath(undefined); setFilePath(undefined); setSelection(undefined); setResetKey(value => value + 1); onClearSelection?.(); };
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);
@@ -94,6 +116,7 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
</div>
</div>
<div className="spatial-controls">
+ {['overview', 'dependencies', 'entryPoints'].includes(view) && <div className="spatial-projection-modes" role="group" aria-label="Overview mode"><button aria-pressed={view !== 'entryPoints'} onClick={() => onView('overview')}>Structure</button><button aria-pressed={view === 'entryPoints'} onClick={() => onView('entryPoints')}>Entry points</button></div>}
{(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>}
@@ -106,11 +129,18 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
<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-encoding-controls" aria-label="Map appearance">
+ {hasSourceBricks && <label>Height <select aria-label="Brick height" value={heightMetric} onChange={event => setHeightMetric(event.target.value as 'lines' | 'uniform')}><option value="lines">Source size</option><option value="uniform">Uniform</option></select></label>}
+ <label>Color <select aria-label="Brick color" value={colorMetric} onChange={event => setColorMetric(event.target.value as 'language' | 'kind')}><option value="language">Language</option><option value="kind">Node kind</option></select></label>
+ <label className="spatial-gravity-toggle"><input aria-label="Hotspot gravity" type="checkbox" checked={showHotspots} onChange={event => setShowHotspots(event.target.checked)} />Hotspot gravity</label>
+ {(view === 'overview' || view === 'dependencies') && <label>Files <select aria-label="File visibility" value={fileVisibility} onChange={event => { setFileVisibility(event.target.value as typeof fileVisibility); setSelection(undefined); setInventoryLimit(24); }}><option value="all">All known files</option><option value="connected">With connections</option><option value="unconnected">Without known connections</option></select></label>}
+ {colorMetric === 'language' && <div className="spatial-language-legend" aria-label="Language colors">{catalog.total.languages.slice(0, 5).map(language => <span key={language.name}><i style={{ background: language.color }} />{language.name}</span>)}{catalog.total.languages.length > 5 && <span>+{catalog.total.languages.length - 5} types</span>}</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>}
+ onSelectEdge={id => setSelection({ scope, edge: id })} onClearSelection={clearScope} active={active} planar={planar} resetKey={resetKey} catalog={catalog} heightMetric={heightMetric} colorMetric={colorMetric} hotspots={hotspotCatalog} showHotspots={showHotspots} />
+ : <div className="spatial-unavailable">{filter ? 'No matching graph evidence. Try a broader filter.' : view === 'hotspots' ? 'No ranked hotspot measurements are available in this snapshot.' : 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>
@@ -122,16 +152,27 @@ export default function SpatialArchitecture({ project, generation, graph, overvi
<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>
+ {selectedMeasure && <SourceMetricsDetails measure={selectedMeasure} catalog={catalog} />}
+ {selectedHotspots && <div className="spatial-hotspot-details" aria-label="Hotspot measurements"><h4>Hotspots · {selectedHotspots.findings.length}</h4>{selectedHotspots.maxFanIn !== undefined && <p>Gravity · {Number(gravityPercent(selectedHotspots.maxFanIn, hotspotCatalog.maxFanIn)!.toFixed(1))}% of the strongest measured hotspot.</p>}<p>Strongest measured fan-in: {selectedHotspots.maxFanIn ?? 'unavailable'}. This is an indexed reference count, not runtime frequency.</p>{selectedHotspots.findings.slice(0, memberLimit).map(finding => <article key={hotspotIdentity(finding)}><button disabled={!finding.filePath} onClick={() => onNavigate(finding.filePath!, finding.line, finding.name)}>{finding.name}</button><div>{hotspotSignals(finding).map(signal => <span key={signal}>{signal}</span>)}</div></article>)}{selectedHotspots.findings.length > memberLimit && <button onClick={() => setMemberLimit(value => value + 16)}>More hotspot findings</button>}</div>}
{(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></>}
+ </> : <><span className="spatial-eyebrow">Read the map</span><h3>{view === 'hotspots' ? 'Inspect a gravity well.' : 'Follow a connection.'}</h3><p>Select a node to inspect its source members. Select an arrow to see what connects the two parts.</p>{showHotspots && <p className="spatial-hotspot-key">◉ Gravity: square-root scale · strongest hotspot = 100%{hotspotCatalog.maxFanIn > 0 ? ` · maximum ${hotspotCatalog.maxFanIn.toLocaleString()} references` : ` · no measured references`}. Folder fields use their strongest measured hotspot.</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>
+ <p className="spatial-measure-note">{hasSourceBricks ? 'Source lines include comments and blank lines.' : 'Gravity represents static fan-in.'} Color is inferred from file type. {catalog.total.measuredFiles.toLocaleString()} / {catalog.total.files.toLocaleString()} known files have a line measurement{catalog.partial ? '; totals cover measured files only' : ''}.</p>
+ <details className="spatial-file-inventory"><summary>File inventory · {catalog.files.size.toLocaleString()} known files</summary>
+ <p>Every returned file remains reachable here, even without connections or outside the 3D display limit. Unindexed folders may contain additional files that the index has not listed.</p>
+ <label>Find a file <input aria-label="Find an architecture file" type="search" value={inventoryFilter} onChange={event => { setInventoryFilter(event.target.value); setInventoryLimit(24); }} /></label>
+ <div className="spatial-inventory-list">{inventoryFiles.slice(0, inventoryLimit).map(file => <article key={file.path}><button onClick={() => { setAreaPath(undefined); setFilePath(file.path); setSelection(undefined); onView('overview'); }}>{file.path}</button><small>{file.language} · {file.lines === undefined ? 'size unknown' : `${file.lines.toLocaleString()} indexed lines`} · {file.connection === 'connected' ? 'connected' : file.connection === 'none' ? 'no indexed connections' : 'connections unknown'}{coverage?.records.get(file.path) ? ` · ${coverage.records.get(file.path)!.state}` : ''}</small><button aria-label={`Read ${file.path}`} onClick={() => onNavigate(file.path, 1)}>Read source</button></article>)}</div>
+ <small>{Math.min(inventoryLimit, inventoryFiles.length)} / {inventoryFiles.length} matching files</small>{inventoryLimit < inventoryFiles.length && <button onClick={() => setInventoryLimit(value => value + 24)}>More files</button>}
+ {(overview.symbolKinds.find(kind => kind.kind === 'File')?.count ?? 0) > overview.files.length && <p className="spatial-notice">The file inventory query is limited. Additional files are available through the explorer tree.</p>}
+ {coverage?.truncations.map(note => <p key={note} className="spatial-notice">{note}</p>)}
+ </details>
{!!(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>)}
diff --git a/graph-ui/src/architecture/SystemArchitecture.test.tsx b/graph-ui/src/architecture/SystemArchitecture.test.tsx
new file mode 100644
index 000000000..735235913
--- /dev/null
+++ b/graph-ui/src/architecture/SystemArchitecture.test.tsx
@@ -0,0 +1,500 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import SystemArchitecture, { suggestedBehaviorEntry, type SystemArchitectureProps } from './SystemArchitecture';
+import { isContiguousPath, systemBehaviorGraph, systemComponentGraph, systemComponents, type SystemSceneModel } from './system-architecture-model';
+import { loadSystemArchitecture, readSystemArchitecture, type SystemArchitectureLoader, type SystemArchitectureResponse, type SystemProjection, type SystemSymbol } from './system-architecture-source';
+import { callToolJson } from '../provider/rpc-transport';
+
+vi.mock('../provider/rpc-transport', () => ({ callToolJson: vi.fn() }));
+vi.mock('./BehaviorSourceEvidence', () => ({ default: ({ symbol, call }: { symbol: SystemSymbol; call?: { id: number } }) =>
+ <div data-testid="behavior-source-evidence" data-symbol={symbol.id} data-call={call?.id} /> }));
+vi.mock('./SystemArchitectureScene', () => ({ default: ({ model, onSelectNode, onSelectEdge, onClearSelection, selectedNode, highlightedPathIndex, planar }: {
+ model: SystemSceneModel; onSelectNode: (id: string) => void; onSelectEdge: (id: string) => void; highlightedPathIndex?: number; planar?: boolean; onClearSelection?: () => void; selectedNode?: string;
+}) => <div data-testid="system-scene" data-selected={selectedNode} data-planar={planar} data-positions={JSON.stringify(model.nodes.map(node => node.position))} data-focus={model.focusId ?? ''} data-highlighted-path={highlightedPathIndex ?? 'all'} data-preferred-path={model.preferredPathIndex ?? 'all'}>
+ <button onClick={onClearSelection}>Empty background</button>{model.nodes.map(node => <button key={node.id} data-node={node.id} onClick={() => onSelectNode(node.id)}>{node.label}</button>)}
+ {model.edges.map(edge => <button key={edge.id} data-edge={edge.id} data-corridor={edge.inCorridor || undefined} onClick={() => onSelectEdge(edge.id)}>{edge.type}</button>)}</div> }));
+
+const symbol = (id: number, component: string, name = `symbol${id}`): SystemSymbol => ({
+ id, name, qualified_name: `sample.${name}`, label: 'Function', file_path: `src/${component}.ts`, start_line: id * 10, component_id: component,
+});
+function fixture(): SystemProjection {
+ const first = symbol(1, 'api', 'start'), next = symbol(2, 'service', 'handle'), last = symbol(3, 'store', 'save');
+ return {
+ schema_version: 1, status: 'ready', kind: 'static_projection', complete: true,
+ components: [first, next, last].map(item => ({ id: item.component_id, label: item.component_id, basis: 'interaction_community', member_count: 10, file_count: 2, representatives: [item] })),
+ dependencies: [{ source: 'api', target: 'service', type: 'CALLS', count: 8, witnesses: [{ edge_id: 10, source: first, target: next }] },
+ { source: 'service', target: 'store', type: 'CALLS', count: 5, witnesses: [{ edge_id: 11, source: next, target: last }] }],
+ cycles: [], entrypoints: [first, next], paths: [{ entrypoint_id: 1, nodes: [first, next, last], edges: [
+ { id: 10, source_id: 1, target_id: 2, type: 'CALLS' }, { id: 11, source_id: 2, target_id: 3, type: 'CALLS' },
+ ] }], totals: { nodes: 30, files: 6, edges: 15, accounted_nodes: 30, structural_nodes: 6 },
+ limits: { omitted_components: 0, paths_truncated: false }, warnings: [],
+ };
+}
+const response = (result = fixture()): SystemArchitectureResponse => ({ status: 'ready', generation: 'g1', result });
+function overviewFixture(): SystemProjection {
+ const data = fixture();
+ const enrich = (item: SystemSymbol) => ({ ...item, group_id: `g:${item.component_id}` });
+ data.components = data.components.map(item => ({ ...item, group_id: `g:${item.id}`, representatives: item.representatives.map(enrich) }));
+ data.paths = data.paths.map(path => ({ ...path, nodes: path.nodes.map(enrich) }));
+ data.entrypoints = data.entrypoints.map(enrich);
+ data.overview = { complete: true, grouping_basis: 'common_source_directory_aggregate',
+ groups: data.components.map(item => ({ id: `g:${item.id}`, label: item.label, component_count: 1, member_count: item.member_count, file_count: item.file_count,
+ component_ids: [item.id], representatives: item.representatives })), components: data.components,
+ connections: data.dependencies.map(edge => ({ ...edge, source: `g:${edge.source}`, target: `g:${edge.target}`, witnesses: edge.witnesses.map(witness => ({ ...witness, source: enrich(witness.source), target: enrich(witness.target), callsite: { file_path: 'src/call-site.ts', line: 91 }, resolution: { strategy: 'lsp_direct', candidates: 1 } })) })),
+ totals: { groups: 3, components: 3 }, limits: { omitted_connections: 0 } };
+ data.behavior = { mode: 'targets', source_id: 1, complete: true, max_hops: 10, limits_hit: [],
+ reachable_targets: data.paths[0].nodes.slice(1).map((item, index) => ({ ...item, distance: index + 1 })), totals: { reachable_nodes: 3 }, nodes: [], edges: [], cycles: [] };
+ return data;
+}
+function corridorFixture(): SystemProjection {
+ const data = overviewFixture();
+ data.behavior = { ...data.behavior!, mode: 'corridor', target_id: 3, nodes: data.paths[0].nodes, edges: data.paths[0].edges };
+ return data;
+}
+function addOverviewContext(data: SystemProjection) {
+ const extra = { id: 'context', label: 'context', basis: 'declared_module', member_count: 1, file_count: 1, representatives: [], group_id: 'g:context' };
+ data.components.push(extra);
+ data.overview!.groups.push({ id: 'g:context', label: 'context', component_count: 1, member_count: 1, file_count: 1, component_ids: ['context'], representatives: [] });
+}
+let container: HTMLDivElement;
+let root: Root;
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);
+ vi.clearAllMocks();
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.useRealTimers(); });
+async function render(loader: SystemArchitectureLoader, props: Partial<SystemArchitectureProps> = {}) {
+ await act(async () => { root.render(<SystemArchitecture project="sample" view="structure" filter="" active onNavigate={vi.fn()} loader={loader} {...props} />); });
+}
+async function click(selector: string) { const button = container.querySelector<HTMLButtonElement>(selector); expect(button).not.toBeNull(); await act(async () => button!.click()); }
+async function choose(label: string, value: string) {
+ const select = container.querySelector<HTMLSelectElement>(`[aria-label="${label}"]`); expect(select).not.toBeNull();
+ await act(async () => { select!.value = value; select!.dispatchEvent(new Event('change', { bubbles: true })); });
+}
+async function clickText(text: string) {
+ const button = [...container.querySelectorAll('button')].find(item => item.textContent === text); expect(button).toBeDefined();
+ await act(async () => button!.click());
+}
+
+describe('system architecture evidence', () => {
+ it('changes camera locally without refetching or rearranging the graph', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response(overviewFixture()));
+ await render(loader);
+ const scene = () => container.querySelector('[data-testid="system-scene"]')!;
+ const positions = scene().getAttribute('data-positions');
+ const requests = loader.mock.calls.length;
+ expect(scene().getAttribute('data-planar')).toBe('false');
+ await clickText('Plan');
+ expect(scene().getAttribute('data-planar')).toBe('true');
+ expect(scene().getAttribute('data-positions')).toBe(positions);
+ expect(loader).toHaveBeenCalledTimes(requests);
+ await clickText('3D');
+ expect(scene().getAttribute('data-planar')).toBe('false');
+ });
+ it('clears component focus and inspection while retaining the projection on empty background', async () => {
+ const clear = vi.fn(); await render(vi.fn().mockResolvedValue(response(overviewFixture())), { onClearSelection: clear });
+ await clickText('Plan'); await click('[data-node="g:api"]'); await clickText('Focus here');
+ expect(container.querySelector('[data-testid="system-scene"]')?.getAttribute('data-focus')).toBe('g:api');
+ await clickText('Empty background');
+ const scene = container.querySelector('[data-testid="system-scene"]')!;
+ expect(scene.getAttribute('data-focus')).toBe(''); expect(scene.getAttribute('data-selected')).toBeNull();
+ expect(scene.getAttribute('data-planar')).toBe('true');
+ expect(scene.querySelectorAll('[data-node]')).toHaveLength(3);
+ expect(clear).toHaveBeenCalledOnce();
+ });
+ it('opens aggregate connection evidence from an accessible inspector control', async () => {
+ await render(vi.fn().mockResolvedValue(response(overviewFixture())));
+ await click('[data-node="g:api"]');
+ await click('[aria-label="Inspect outgoing connection to service"]');
+ const inspector = container.querySelector('[aria-label="System evidence inspector"]')!;
+ expect(inspector.textContent).toContain('api → service');
+ expect(inspector.textContent).toContain('Open call site · src/call-site.ts:91');
+ expect(inspector.textContent).toContain('Resolved by lsp direct');
+ });
+ it('offers deeper destinations from contiguous same-source witnesses beyond the target catalog', async () => {
+ const data = overviewFixture();
+ data.behavior!.reachable_targets = data.behavior!.reachable_targets.slice(0, 1);
+ data.behavior!.totals.omitted_targets = 1;
+ const foreign = symbol(99, 'other', 'foreign');
+ data.paths.push({ entrypoint_id: 2, nodes: [symbol(2, 'service'), foreign], edges: [{ id: 99, source_id: 2, target_id: 99, type: 'CALLS' }] });
+ const broken = symbol(98, 'other', 'broken');
+ data.paths.push({ entrypoint_id: 1, nodes: [data.entrypoints[0], broken], edges: [{ id: 98, source_id: 77, target_id: 98, type: 'CALLS' }] });
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response(data));
+ await render(loader, { view: 'behavior' });
+ await choose('Behavior entry point', '1');
+ const values = [...container.querySelectorAll<HTMLOptionElement>('[aria-label="Behavior destination"] option')].map(option => option.value);
+ expect(values).toContain('3'); expect(values).not.toContain('99'); expect(values).not.toContain('98');
+ await choose('Behavior destination', '3');
+ expect(loader.mock.calls.at(-1)?.[0]).toMatchObject({ entryNodeId: 1, targetNodeId: 3, expectedGeneration: 'g1' });
+ });
+ it('validates additive overview and call-site evidence and rejects broken corridor endpoints', () => {
+ const data = overviewFixture();
+ expect(readSystemArchitecture(response(data)).result?.overview?.groups).toHaveLength(3);
+ data.behavior = { ...data.behavior!, mode: 'corridor', target_id: 3, nodes: data.paths[0].nodes, edges: [{ id: 42, source_id: 1, target_id: 99, type: 'CALLS' }] };
+ expect(() => readSystemArchitecture(response(data))).toThrow('invalid shape');
+ });
+ it('passes the exact target and snapshot through the RPC boundary', async () => {
+ vi.mocked(callToolJson).mockResolvedValue(response());
+ const controller = new AbortController();
+ await loadSystemArchitecture({ project: 'sample', entryNodeId: 1, targetNodeId: 3, expectedGeneration: 'g1' }, controller.signal);
+ expect(vi.mocked(callToolJson).mock.calls[0][1]).toMatchObject({ entry_node_id: 1, target_node_id: 3, expected_generation: 'g1' });
+ });
+ it('requests the shared MCP projection and propagates cancellation', async () => {
+ vi.mocked(callToolJson).mockResolvedValue(response());
+ const controller = new AbortController();
+ const result = await loadSystemArchitecture({ project: 'sample', entryNodeId: 2, expectedGeneration: 'projection-g1' }, controller.signal);
+ expect(result.status).toBe('ready');
+ expect(callToolJson).toHaveBeenCalledWith('get_architecture', { project: 'sample', aspects: ['system_structure'], format: 'json', entry_node_id: 2, expected_generation: 'projection-g1' }, { signal: controller.signal });
+ });
+ it('rejects malformed source locations before they can drive navigation', () => {
+ const value = response();
+ (value.result!.components[0].representatives[0] as unknown as Record<string, unknown>).file_path = { path: 'bad' };
+ expect(() => readSystemArchitecture(value)).toThrow('invalid shape');
+ });
+ it('accepts limited projections without inventing complete coverage', () => {
+ const data = fixture(); data.status = 'limited'; data.complete = false; data.warnings = ['Node budget reached.'];
+ expect(readSystemArchitecture(response(data)).result?.complete).toBe(false);
+ });
+ it('rejects projected paths whose underlying symbols do not join', () => {
+ const data = fixture(); data.paths[0].edges[1].source_id = 99;
+ expect(isContiguousPath(data.paths[0])).toBe(false);
+ expect(systemBehaviorGraph(data, data.paths[0]).nodes).toHaveLength(0);
+ });
+ it('preserves repeated symbols as distinct path steps without manufacturing a self-edge', () => {
+ const data = fixture(), path = data.paths[0];
+ path.nodes[2] = path.nodes[0]; path.edges[1].target_id = 1;
+ const model = systemBehaviorGraph(data, path);
+ expect(model.nodes.map(node => node.id)).toEqual(['step:0', 'step:1', 'step:2']);
+ expect(model.edges.map(edge => [edge.source, edge.target])).toEqual([['step:0', 'step:1'], ['step:1', 'step:2']]);
+ });
+ it('limits cycle filtering to relationships inside the same reported component cycle', () => {
+ const data = fixture(); data.cycles = [{ component_ids: ['api', 'service'] }, { component_ids: ['store'] }];
+ expect(systemComponentGraph(data, '', true).edges.map(edge => edge.source)).toEqual(['api']);
+ });
+ it('bounds the 3D scene without discarding returned component membership', () => {
+ const data = fixture(); data.components = Array.from({ length: 100 }, (_, index) => ({ id: `c${index}`, label: `C${index}`, basis: 'declared_module', member_count: 100, file_count: 10, representatives: [] }));
+ const scene = systemComponentGraph(data, '', false, true);
+ expect(scene.nodes.length).toBeLessThanOrEqual(16); expect(scene.omittedNodes + scene.nodes.length).toBe(100); expect(data.components).toHaveLength(100);
+ });
+ it('leads with connected collaboration groups and keeps isolated modules available by opt-in', () => {
+ const data = fixture(); data.components.unshift({ id: 'aaa', label: 'README.md', basis: 'declared_module', member_count: 1000, file_count: 1, representatives: [] });
+ expect(systemComponents(data, '', false).map(component => component.id)).toEqual(['service', 'api', 'store']);
+ expect(systemComponentGraph(data, '', false).nodes.some(node => node.label === 'README.md')).toBe(false);
+ expect(systemComponents(data, '', false, true).at(-1)?.label).toBe('README.md');
+ });
+ it('filters explicit test roles without guessing missing roles or inflating ranking with hidden test callers', () => {
+ const data = fixture(); data.components[2].role = 'test'; data.components[2].role_basis = 'indexed_is_test_or_test_path';
+ expect(systemComponents(data, '', false).map(component => component.id)).toEqual(['api', 'service']);
+ expect(systemComponents(data, '', false, false, true).map(component => component.id)).toEqual(['service', 'api', 'store']);
+ expect(data.components).toHaveLength(3);
+ });
+});
+
+describe('system architecture workspace', () => {
+ it('keeps the selected path when inspecting an operation and excludes unrelated overview context', async () => {
+ const targets = overviewFixture(), corridor = corridorFixture(); addOverviewContext(targets); addOverviewContext(corridor);
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridor : targets)));
+ await render(loader, { view: 'behavior' }); await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
+ const scene = container.querySelector('[data-testid="system-scene"]')!;
+ const positions = scene.getAttribute('data-positions'), requests = loader.mock.calls.length;
+ expect(scene.querySelectorAll('[data-node]')).toHaveLength(3);
+ expect(scene.textContent).not.toContain('context');
+ await click('[data-node="journey:1:2:3"]');
+ expect(scene.getAttribute('data-positions')).toBe(positions);
+ expect(scene.getAttribute('data-focus')).toBe('');
+ expect(loader).toHaveBeenCalledTimes(requests);
+ expect(container.querySelector('[aria-label="Select step 3: save"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(container.querySelector<HTMLInputElement>('[aria-label="Call-chain position"]')?.value).toBe('2');
+ });
+ it('uses an explicit Behavior call context independently of hidden Structure filters', async () => {
+ const targets = overviewFixture(), corridor = corridorFixture();
+ for (const data of [targets, corridor]) {
+ addOverviewContext(data); data.components.find(item => item.id === 'store')!.role = 'test';
+ data.overview!.groups.find(item => item.id === 'g:store')!.role = 'test';
+ }
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridor : targets)));
+ await render(loader); await choose('Connection view', 'types');
+ await render(loader, { view: 'behavior' }); await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
+ expect(container.textContent).toContain('CALL CHAIN');
+ expect(container.querySelector('[data-node="journey:1:2:3"]')).not.toBeNull();
+ expect(container.querySelector('[data-node="g:context"]')).toBeNull();
+ expect(container.querySelectorAll('[data-edge]')).toHaveLength(2);
+ await render(loader);
+ expect(container.querySelector<HTMLSelectElement>('[aria-label="Connection view"]')?.value).toBe('types');
+ expect(container.querySelector('[data-node="g:store"]')).toBeNull();
+ expect(container.querySelector('[data-node="g:context"]')).toBeNull();
+ });
+ it('returns to immediate calls and restores the selected destination with Back', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridorFixture() : overviewFixture())));
+ await render(loader, { view: 'behavior' });
+ await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
+ await clickText('Immediate calls');
+ expect(container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')?.value).toBe('');
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(2);
+ expect(container.textContent).toContain('DIRECT CALLS · UNORDERED');
+ await clickText('← Back');
+ expect(container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')?.value).toBe('3');
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(3);
+ expect(container.querySelector('[data-testid="system-scene"]')?.getAttribute('data-focus')).toBe('');
+ });
+ it('filters whole paths without drawing disconnected remnants and restores the path without refetching', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => Promise.resolve(response(request.targetNodeId === 3 ? corridorFixture() : overviewFixture())));
+ await render(loader, { view: 'behavior' }); await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
+ const requests = loader.mock.calls.length;
+ await render(loader, { view: 'behavior', filter: 'no-such-symbol' });
+ expect(container.querySelector('[data-testid="system-scene"]')).toBeNull();
+ expect(container.querySelectorAll('[data-edge]')).toHaveLength(0);
+ expect(container.textContent).toContain('No connected path matches this filter.');
+ expect(container.querySelector('[aria-label="Walk the call chain"]')).toBeNull();
+ await render(loader, { view: 'behavior' });
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(3);
+ expect(container.querySelector('[aria-label="Select step 1: start"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(loader).toHaveBeenCalledTimes(requests);
+ });
+ it('discards stale destination catalogs when the analysis snapshot changes within the same project generation', async () => {
+ let phase: 'initial' | 'updated' = 'initial';
+ let finishCatalog!: (value: SystemArchitectureResponse) => void;
+ const updated = overviewFixture(); updated.behavior = undefined; updated.paths = [];
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => {
+ if (phase === 'initial') return Promise.resolve(response(overviewFixture()));
+ if (request.entryNodeId === undefined) return Promise.resolve({ status: 'ready', generation: 'g2', result: updated });
+ if (request.expectedGeneration === 'g2' && request.targetNodeId === undefined) return new Promise(resolve => { finishCatalog = resolve; });
+ return new Promise(() => {});
+ });
+ await render(loader, { view: 'behavior', generation: 'outer' }); await choose('Behavior entry point', '1');
+ expect(container.querySelector('[aria-label="Behavior destination"]')?.textContent).toContain('save');
+ phase = 'updated'; await render(loader, { generation: 'outer' }); await render(loader, { view: 'behavior', generation: 'outer' });
+ expect(container.querySelector('[aria-label="Behavior destination"]')?.textContent).not.toContain('save');
+ await choose('Behavior entry point', '1');
+ const destination = container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')!;
+ expect(destination.disabled).toBe(true); expect(destination.textContent).not.toContain('save');
+ expect(loader.mock.calls.at(-1)?.[0]).toMatchObject({ entryNodeId: 1, expectedGeneration: 'g2' });
+ const fresh = overviewFixture(); fresh.paths = []; fresh.behavior!.reachable_targets = [{ ...symbol(4, 'store', 'newSave'), group_id: 'g:store', distance: 2 }];
+ await act(async () => finishCatalog({ status: 'ready', generation: 'g2', result: fresh }));
+ expect(destination.disabled).toBe(false); expect(destination.textContent).toContain('newSave'); expect(destination.textContent).not.toContain('save');
+ await choose('Behavior destination', '4');
+ expect(loader.mock.calls.at(-1)?.[0]).toMatchObject({ entryNodeId: 1, targetNodeId: 4, expectedGeneration: 'g2' });
+ });
+ it('discloses destinations omitted from the bounded reachable-target list', async () => {
+ const data = overviewFixture(); data.behavior!.totals.omitted_targets = 27;
+ await render(vi.fn().mockResolvedValue(response(data)), { view: 'behavior' });
+ expect(container.textContent).toContain('27 reachable destinations are outside the returned catalog.');
+ });
+ it('hides the previous journey while querying a chosen destination', async () => {
+ const data = overviewFixture();
+ let finish!: (value: SystemArchitectureResponse) => void;
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementation(request => request.targetNodeId === 3 ? new Promise(resolve => { finish = resolve; }) : Promise.resolve(response(data)));
+ await render(loader, { view: 'behavior' });
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '1'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(2);
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior destination"]')!; select.value = '3'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(loader.mock.calls.at(-1)?.[0]).toEqual({ project: 'sample', entryNodeId: 1, targetNodeId: 3, expectedGeneration: 'g1', includeBehaviorEvidence: true });
+ expect(container.querySelector('[data-testid="system-scene"]')).toBeNull();
+ expect(container.textContent).toContain('Updating this journey');
+ expect(container.querySelector('[aria-label="Walk the call chain"]')).toBeNull();
+ const corridor = overviewFixture(); corridor.behavior = { ...corridor.behavior!, mode: 'corridor', target_id: 3, nodes: corridor.paths[0].nodes, edges: corridor.paths[0].edges };
+ await act(async () => finish(response(corridor)));
+ expect(container.querySelectorAll('[data-node]')).toHaveLength(3);
+ expect(container.querySelector('[aria-label="Select step 1: start"]')?.getAttribute('aria-pressed')).toBe('true');
+ });
+ it('opens a recorded call site separately from its caller definition', async () => {
+ const onNavigate = vi.fn();
+ await render(vi.fn().mockResolvedValue(response(overviewFixture())), { onNavigate });
+ await click('[data-edge]');
+ const inspector = container.querySelector('[aria-label="System evidence inspector"]')!;
+ await act(async () => [...inspector.querySelectorAll('button')].find(item => item.textContent?.startsWith('Open call site'))!.click());
+ expect(onNavigate).toHaveBeenCalledWith('src/call-site.ts', 91, 'start');
+ expect(inspector.textContent).toContain('Resolved by lsp direct');
+ expect(inspector.textContent).not.toContain('95%');
+ });
+ it('keeps the same topology when a component is selected for inspection', async () => {
+ await render(vi.fn().mockResolvedValue(response()));
+ const topology = () => [...container.querySelectorAll('[data-node], [data-edge]')].map(item => item.getAttribute('data-node') ?? item.getAttribute('data-edge'));
+ const before = topology();
+ await click('[data-node="api"]');
+ expect(topology()).toEqual(before);
+ expect(container.querySelector('[aria-label="System evidence inspector"] h3')?.textContent).toBe('api');
+ });
+ it('prefers a conventional executable entry over test runners and install helpers', () => {
+ const entries = [
+ { ...symbol(1, 'install', 'main'), file_path: 'install.sh' },
+ { ...symbol(2, 'test', 'main'), file_path: 'tests/test_main.c' },
+ { ...symbol(3, 'go', 'main'), file_path: 'pkg/go/cmd/tool/main.go' },
+ { ...symbol(4, 'core', 'main'), file_path: 'src/main.c' },
+ ];
+ expect(suggestedBehaviorEntry(entries)?.id).toBe(4);
+ expect(suggestedBehaviorEntry([symbol(5, 'helper', 'format')])).toBeUndefined();
+ });
+ it('automatically requests the executable entry once and leaves manual selection authoritative', async () => {
+ const data = fixture(); data.entrypoints[0] = { ...data.entrypoints[0], name: 'main', file_path: 'src/main.c' };
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response(data));
+ await render(loader, { view: 'behavior' });
+ expect(loader).toHaveBeenCalledTimes(2); expect(loader.mock.calls[1][0].entryNodeId).toBe(1);
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '2'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(loader).toHaveBeenCalledTimes(3); expect(loader.mock.calls[2][0].entryNodeId).toBe(2);
+ });
+ it('shows direct calls before narrowing to one branch and synchronizes its selected operation with source', async () => {
+ const data = fixture(), fork = symbol(4, 'queue', 'publish'), unrelated = symbol(8, 'other', 'elsewhere');
+ data.paths.push({ entrypoint_id: 1, nodes: [data.paths[0].nodes[0], data.paths[0].nodes[1], fork], edges: [data.paths[0].edges[0], { id: 12, source_id: 2, target_id: 4, type: 'ASYNC_CALLS' }] });
+ data.paths.push({ entrypoint_id: 8, nodes: [unrelated], edges: [] });
+ const onNavigate = vi.fn();
+ await render(vi.fn().mockResolvedValue(response(data)), { view: 'behavior', onNavigate });
+ expect(container.querySelector('[data-testid="system-scene"]')?.textContent).toContain('handle');
+ expect(container.querySelector('[data-testid="system-scene"]')?.textContent).not.toContain('save');
+ expect(container.querySelector('[data-testid="system-scene"]')?.textContent).not.toContain('publish');
+ await choose('Behavior entry point', '1'); await choose('Behavior destination', '4');
+ const scene = container.querySelector('[data-testid="system-scene"]')!;
+ expect(scene.textContent).toContain('publish'); expect(scene.textContent).not.toContain('save'); expect(scene.textContent).not.toContain('elsewhere');
+ await click('[aria-label="Select step 3: publish"]');
+ const inspector = container.querySelector('[aria-label="Behavior evidence inspector"]')!;
+ expect(inspector.textContent).toContain('Operation 3'); expect(inspector.textContent).toContain('publish');
+ expect(inspector.querySelector('[data-testid="behavior-source-evidence"]')?.getAttribute('data-symbol')).toBe('4');
+ await clickText('Open definition ↗');
+ expect(onNavigate).toHaveBeenCalledWith('src/queue.ts', 40, 'publish');
+ });
+ it('includes a component beyond the former immediate neighborhood for inspection', async () => {
+ const data = fixture();
+ data.components.push({ id: 'far', label: 'far', basis: 'declared_module', member_count: 1, file_count: 1, representatives: [symbol(7, 'far')] });
+ data.dependencies.push({ source: 'store', target: 'far', type: 'IMPORTS', count: 1, witnesses: [] });
+ await render(vi.fn().mockResolvedValue(response(data)));
+ await click('[data-node="far"]');
+ expect(container.querySelector('[data-node="far"]')).not.toBeNull();
+ expect(container.querySelector('[aria-label="System evidence inspector"] h3')?.textContent).toBe('far');
+ });
+ it('keeps the inspector aligned when filtering removes the previous focus', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response());
+ await render(loader); await click('[data-node="api"]');
+ await render(loader, { filter: 'store' });
+ expect(container.querySelector('[aria-label="System evidence inspector"] h3')?.textContent).toBe('store');
+ });
+ it('keeps generic references available without letting them dominate the initial call map', async () => {
+ const data = fixture();
+ data.components.push({ id: 'referenceHub', label: 'referenceHub', basis: 'declared_module', member_count: 1, file_count: 1, representatives: [] });
+ data.dependencies.push(...['api', 'service', 'store'].map(target => ({ source: 'referenceHub', target, type: 'USAGE', count: 1000, witnesses: [] })));
+ await render(vi.fn().mockResolvedValue(response(data)));
+ expect(container.querySelector('[data-node="referenceHub"]')).toBeNull();
+ expect(container.textContent).toContain('2 of 5 returned connections');
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Connection view"]')!; select.value = 'all'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(container.querySelector('[data-node="referenceHub"]')).not.toBeNull();
+ await click('[data-node="referenceHub"]');
+ expect(container.querySelector('[aria-label="System evidence inspector"] h3')?.textContent).toBe('referenceHub');
+ });
+ it('resets step navigation for a filtered branch and distinguishes a filter miss from absent evidence', async () => {
+ const data = fixture(), branch = symbol(4, 'queue', 'publish');
+ data.paths.push({ entrypoint_id: 1, nodes: [data.paths[0].nodes[0], branch, data.paths[0].nodes[2]], edges: [
+ { id: 12, source_id: 1, target_id: 4, type: 'CALLS' }, { id: 13, source_id: 4, target_id: 3, type: 'CALLS' },
+ ] });
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response(data));
+ await render(loader, { view: 'behavior' }); await choose('Behavior entry point', '1'); await choose('Behavior destination', '3');
+ await click('[aria-label="Select step 3: save"]');
+ await render(loader, { view: 'behavior', filter: 'publish' });
+ const inspector = container.querySelector('[aria-label="Behavior evidence inspector"]')!;
+ expect(container.querySelector('[aria-label="Select step 1: start"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(container.querySelector('[data-testid="system-scene"]')?.textContent).toContain('publish');
+ expect(container.querySelector('[data-testid="system-scene"]')?.textContent).not.toContain('handle');
+ await clickText('Next →');
+ expect(container.querySelector('[aria-label="Select step 2: publish"]')?.getAttribute('aria-pressed')).toBe('true');
+ expect(inspector.textContent).toContain('publish');
+ await render(loader, { view: 'behavior', filter: 'no-such-symbol' });
+ expect(container.textContent).toContain('No connected path matches this filter.');
+ });
+ it('shows progress on first paint and polls pending work without overlapping requests', async () => {
+ vi.useFakeTimers();
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValueOnce({ status: 'pending', generation: 'g1', retry_after_ms: 1 }).mockResolvedValue(response());
+ await render(loader);
+ expect(container.textContent).toContain('Analyzing interactions'); expect(loader).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(499); }); expect(loader).toHaveBeenCalledTimes(1);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(loader).toHaveBeenCalledTimes(2); expect(container.textContent).toContain('3 components');
+ await act(async () => { await vi.advanceTimersByTimeAsync(5000); }); expect(loader).toHaveBeenCalledTimes(2);
+ });
+ it('aborts pending work when the view becomes inactive and starts no further poll', async () => {
+ vi.useFakeTimers();
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue({ status: 'pending', generation: 'g1' });
+ await render(loader); const signal = loader.mock.calls[0][1];
+ await render(loader, { active: false }); expect(signal.aborted).toBe(true);
+ await act(async () => { await vi.advanceTimersByTimeAsync(5000); }); expect(loader).toHaveBeenCalledTimes(1);
+ });
+ it('ignores a previous project response after project navigation', async () => {
+ let finish!: (value: SystemArchitectureResponse) => void;
+ const loader = vi.fn<SystemArchitectureLoader>().mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })).mockResolvedValue(response());
+ await render(loader); const oldSignal = loader.mock.calls[0][1];
+ await render(loader, { project: 'other' }); expect(oldSignal.aborted).toBe(true);
+ const obsolete = fixture(); obsolete.components[0].label = 'OBSOLETE PROJECT';
+ await act(async () => finish(response(obsolete)));
+ expect(container.textContent).not.toContain('OBSOLETE PROJECT');
+ expect(loader.mock.calls[1][0].project).toBe('other');
+ });
+ it('requests the selected behavior entry and does not reuse it for another project', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response());
+ await render(loader, { view: 'behavior' });
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '2'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(loader.mock.calls.at(-1)?.[0]).toEqual({ project: 'sample', entryNodeId: 2, expectedGeneration: 'g1', includeBehaviorEvidence: true });
+ await render(loader, { view: 'behavior', project: 'other' });
+ expect(loader.mock.calls.at(-1)?.[0]).toEqual({ project: 'other', entryNodeId: undefined, includeBehaviorEvidence: true });
+ });
+ it('discards numeric entry identities after the indexed generation changes', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue(response());
+ await render(loader, { view: 'behavior', generation: 'g1' });
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '2'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(loader.mock.calls.at(-1)?.[0].entryNodeId).toBe(2);
+ await render(loader, { view: 'behavior', generation: 'g2' });
+ expect(loader.mock.calls.at(-1)?.[0].entryNodeId).toBeUndefined();
+ });
+ it('guards entry identities with the analysis generation and resets a stale selection once', async () => {
+ const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValueOnce({ ...response(), generation: 'analysis-g1' })
+ .mockResolvedValueOnce({ status: 'failed', generation: 'analysis-g2', error: 'Entry snapshot changed.' })
+ .mockResolvedValue({ ...response(), generation: 'analysis-g2' });
+ await render(loader, { view: 'behavior', generation: 'different-parent-generation' });
+ await act(async () => { const select = container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')!; select.value = '2'; select.dispatchEvent(new Event('change', { bubbles: true })); });
+ expect(loader.mock.calls[1][0]).toEqual({ project: 'sample', entryNodeId: 2, expectedGeneration: 'analysis-g1', includeBehaviorEvidence: true });
+ expect(loader.mock.calls[2][0]).toEqual({ project: 'sample', entryNodeId: undefined, includeBehaviorEvidence: true });
+ expect(loader).toHaveBeenCalledTimes(3);
+ expect(container.querySelector<HTMLSelectElement>('[aria-label="Behavior entry point"]')?.value).toBe('');
+ expect(container.textContent).not.toContain('Entry snapshot changed.');
+ });
+ it('opens exact source witnesses and synchronizes selection by qualified name', async () => {
+ const data = fixture(), onNavigate = vi.fn(), onSelect = vi.fn();
+ const graphNode = { id: 999, name: 'start', qualified_name: 'sample.start', file_path: 'src/api.ts', label: 'Function', x: 0, y: 0, z: 0, size: 1, color: '' };
+ await render(vi.fn().mockResolvedValue(response(data)), { onNavigate, onSelect, graph: { nodes: [graphNode], edges: [], total_nodes: 1 } });
+ await click('[data-edge]');
+ const inspector = container.querySelector('[aria-label="System evidence inspector"]')!;
+ const source = [...inspector.querySelectorAll('button')].find(button => button.textContent === 'start')!;
+ await act(async () => source.click());
+ expect(onNavigate).toHaveBeenCalledWith('src/api.ts', 10, 'start'); expect(onSelect).toHaveBeenCalledWith(graphNode);
+ expect(inspector.textContent).toContain('8 indexed relationships · 1 source examples.');
+ });
+ it('excludes a disconnected behavior path while retaining only supported direct calls', async () => {
+ const data = fixture(); data.paths[0].edges[1].source_id = 999;
+ await render(vi.fn().mockResolvedValue(response(data)), { view: 'behavior' });
+ expect([...container.querySelectorAll('[data-node]')].map(node => node.textContent)).toEqual(['start', 'handle']);
+ expect(container.querySelectorAll('[data-edge]')).toHaveLength(1);
+ expect(container.querySelector('[aria-label="All operations in this call chain"]')).toBeNull();
+ expect(container.textContent).toContain('1 disconnected or unsupported paths excluded.');
+ });
+ it('renders limited-analysis warnings and accurate representative membership counts', async () => {
+ const data = fixture(); data.complete = false; data.status = 'limited'; data.warnings = ['Some callback targets are unresolved.'];
+ await render(vi.fn().mockResolvedValue(response(data))); await click('[data-node="api"]');
+ const inspector = container.querySelector('[aria-label="System evidence inspector"]')!;
+ expect(inspector.textContent).toContain('10 symbols across 2 files'); expect(inspector.textContent).toContain('Representative sources');
+ expect(container.textContent).toContain('Partial analysis'); expect(container.textContent).toContain('Some callback targets are unresolved.');
+ });
+ it('lets users include test components while preserving total and filtered counts', async () => {
+ const data = fixture(); data.components[2].role = 'test'; data.components[2].role_basis = 'indexed_is_test_or_test_path';
+ await render(vi.fn().mockResolvedValue(response(data)));
+ expect(container.querySelector('[data-node="store"]')).toBeNull();
+ expect(container.textContent).toContain('3 components returned · 2 shown');
+ const toggle = [...container.querySelectorAll('label')].find(label => label.textContent?.includes('Include test components'))!.querySelector('input')!;
+ await act(async () => toggle.click());
+ expect(container.querySelector('[data-node="store"]')).not.toBeNull();
+ expect(container.textContent).toContain('Test code'); expect(container.textContent).toContain('3 components returned');
+ });
+ it('shows failures without retrying continuously', async () => {
+ vi.useFakeTimers(); const loader = vi.fn<SystemArchitectureLoader>().mockResolvedValue({ status: 'failed', generation: 'g1', error: 'Analysis budget exceeded.' });
+ await render(loader); await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain('Analysis budget exceeded'); expect(loader).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/graph-ui/src/architecture/SystemArchitecture.tsx b/graph-ui/src/architecture/SystemArchitecture.tsx
new file mode 100644
index 000000000..b4974d9ac
--- /dev/null
+++ b/graph-ui/src/architecture/SystemArchitecture.tsx
@@ -0,0 +1,378 @@
+import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import { loadSystemArchitecture, type SystemArchitectureLoader, type SystemArchitectureResponse, type SystemProjection, type SystemSymbol, type SystemWitness, type SystemCallEvidence } from './system-architecture-source';
+import { componentBasis, isContiguousPath, systemOverviewGraph, systemComponents, type SystemSceneEdge, type SystemSceneModel } from './system-architecture-model';
+import { connectionLoad } from '../graph/connection-load';
+import BehaviorJourney from './BehaviorJourney';
+import './system-architecture.css';
+
+const Scene = lazy(() => import('./SystemArchitectureScene'));
+export interface SystemArchitectureProps {
+ project: string; generation?: string; view: 'structure' | 'behavior'; filter: string; active: boolean;
+ graph?: GraphData; onSelect?: (node: GraphNode) => void; onClearSelection?: () => void;
+ onNavigate: (path: string, line?: number, name?: string) => void;
+ loader?: SystemArchitectureLoader;
+}
+
+function EvidenceSource({ symbol, onOpen }: { symbol: SystemSymbol; onOpen: (symbol: SystemSymbol) => void }) {
+ return <div className="system-source"><button disabled={!symbol.file_path} onClick={() => onOpen(symbol)} title={symbol.qualified_name}>{symbol.name}</button>
+ <small>{symbol.file_path ? `${symbol.file_path}${symbol.start_line ? `:${symbol.start_line}` : ''}` : 'Source location unavailable'}</small></div>;
+}
+
+/** Prefer a conventional executable entry when one exists; keep every indexed entry selectable. */
+export function suggestedBehaviorEntry(entries: SystemSymbol[]): SystemSymbol | undefined {
+ return entries.filter(entry => /^(main|Main)$/.test(entry.name)
+ && entry.file_path && !/(^|\/)(tests?|__tests__|examples?|fixtures?|vendor|node_modules)(\/|$)/i.test(entry.file_path)
+ && /\.(c|cc|cpp|go|rs|py|java|cs|js|ts)$/.test(entry.file_path))
+ .sort((a, b) => Number(!/^src\/main\./.test(a.file_path!)) - Number(!/^src\/main\./.test(b.file_path!))
+ || a.file_path!.split('/').length - b.file_path!.split('/').length || a.file_path!.localeCompare(b.file_path!))[0];
+}
+
+const handoffs = (symbols: SystemSymbol[]) => symbols.slice(1).filter((symbol, index) => symbol.component_id !== symbols[index].component_id).length;
+type ConnectionView = 'calls' | 'types' | 'all';
+const connectionAllowed = (type: string, view: ConnectionView) => view === 'all'
+ || (view === 'calls' ? ['CALLS', 'IMPORTS', 'HTTP_CALLS', 'ASYNC_CALLS'] : ['INHERITS', 'IMPLEMENTS']).includes(type);
+
+/** Poll only while this view is active. A new request key hides stale results before its effect runs. */
+export default function SystemArchitecture({ project, generation, view, filter, active, graph, onSelect, onClearSelection, onNavigate, loader = loadSystemArchitecture }: SystemArchitectureProps) {
+ const [entryChoice, setEntryChoice] = useState<{ project: string; generation?: string; expectedGeneration?: string; id?: number; targetId?: number }>();
+ const [entryChoices, setEntryChoices] = useState<{ project: string; generation?: string; analysisGeneration: string; entries: SystemSymbol[] }>();
+ const [snapshot, setSnapshot] = useState<{ project: string; generation?: string; analysisGeneration: string; data: SystemProjection }>();
+ const [targetCatalog, setTargetCatalog] = useState<{ project: string; generation?: string; source: number; analysisGeneration: string; targets: (SystemSymbol & { distance: number })[] }>();
+ const [expandedGroups, setExpandedGroups] = useState<string[]>([]);
+ const [scopeHistory, setScopeHistory] = useState<(string | undefined)[]>([]);
+ const [revision, setRevision] = useState(0);
+ const [reading, setReading] = useState<{ key: string; response?: SystemArchitectureResponse; error?: string }>();
+ const [cyclesOnly, setCyclesOnly] = useState(false);
+ const [includeUnconnected, setIncludeUnconnected] = useState(false);
+ const [includeTests, setIncludeTests] = useState(false);
+ const [connectionView, setConnectionView] = useState<ConnectionView>('calls');
+ const [pathIndex, setPathIndex] = useState(0);
+ const [selection, setSelection] = useState<{ node?: string; edge?: string; dependencyIndex?: number }>();
+ const [listLimit, setListLimit] = useState(20);
+ const [resetKey, setResetKey] = useState(0);
+ const [planar, setPlanar] = useState(false);
+ const [focusId, setFocusId] = useState<string>();
+ const [stepIndex, setStepIndex] = useState(0);
+ const [showConnectionLoad, setShowConnectionLoad] = useState(true);
+ useEffect(() => { setSelection(undefined); setPathIndex(0); setStepIndex(0); }, [filter, cyclesOnly, includeUnconnected, includeTests, connectionView]);
+ const requestedEntry = view === 'behavior' && entryChoice?.project === project && entryChoice.generation === generation ? entryChoice.id : undefined;
+ const requestedTarget = requestedEntry === undefined ? undefined : entryChoice?.targetId;
+ const expectedGeneration = requestedEntry === undefined ? undefined : entryChoice?.expectedGeneration;
+ const requestKey = JSON.stringify([project, generation, view, requestedEntry, requestedTarget, expectedGeneration, revision]);
+ useEffect(() => {
+ if (!active || !project) return;
+ const controller = new AbortController();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ setReading({ key: requestKey }); setSelection(undefined); setPathIndex(0); setStepIndex(0); setListLimit(20);
+ const poll = async () => {
+ try {
+ const response = await loader({ project, entryNodeId: requestedEntry, ...(requestedTarget === undefined ? {} : { targetNodeId: requestedTarget }), ...(expectedGeneration === undefined ? {} : { expectedGeneration }), ...(view === 'behavior' ? { includeBehaviorEvidence: true } : {}) }, controller.signal);
+ if (controller.signal.aborted) return;
+ // The numeric identity belongs to the projection that supplied the dropdown.
+ // A stale-entry rejection reopens the overview once, rather than reusing that ID.
+ if (response.status === 'failed' && requestedEntry !== undefined && expectedGeneration !== undefined && response.generation !== expectedGeneration) {
+ setEntryChoice({ project, generation }); setEntryChoices(undefined); setTargetCatalog(undefined); setSnapshot(undefined); return;
+ }
+ setReading({ key: requestKey, response });
+ if (response.status === 'pending') timer = setTimeout(() => { void poll(); }, Math.min(5000, Math.max(500, response.retry_after_ms ?? 500)));
+ else if (response.status === 'ready' && response.result) {
+ setSnapshot({ project, generation, analysisGeneration: response.generation, data: response.result });
+ if (response.result.behavior?.mode === 'targets') {
+ const behavior = response.result.behavior;
+ const reachable = new Map(behavior.reachable_targets.map(target => [target.id, target]));
+ // Bounded source witnesses also expose useful deeper destinations beyond the catalog page.
+ for (const path of response.result.paths) {
+ if (path.entrypoint_id !== behavior.source_id || !isContiguousPath(path)) continue;
+ path.nodes.forEach((symbol, hop) => {
+ if (hop > 0 && hop <= behavior.max_hops && !reachable.has(symbol.id)) reachable.set(symbol.id, { ...symbol, distance: hop });
+ });
+ }
+ setTargetCatalog({ project, generation, source: behavior.source_id, analysisGeneration: response.generation, targets: [...reachable.values()] });
+ }
+ setEntryChoices(current => requestedEntry !== undefined && current?.project === project && current.generation === generation ? current : { project, generation, analysisGeneration: response.generation, entries: response.result!.entrypoints });
+ }
+ } catch (error) {
+ if (!controller.signal.aborted) setReading({ key: requestKey, error: error instanceof Error ? error.message : 'Architecture analysis failed.' });
+ }
+ };
+ void poll();
+ return () => { controller.abort(); if (timer !== undefined) clearTimeout(timer); };
+ }, [project, generation, active, view, requestedEntry, requestedTarget, expectedGeneration, revision, requestKey, loader]);
+ const current = reading?.key === requestKey ? reading : undefined;
+ const queryData = current?.response?.status === 'ready' ? current.response.result : undefined;
+ const matchingSnapshot = snapshot?.project === project && snapshot.generation === generation ? snapshot : undefined;
+ const data = queryData ?? matchingSnapshot?.data;
+ const projectionGeneration = queryData ? current?.response?.generation : matchingSnapshot?.analysisGeneration;
+ const sourceGeneration = expectedGeneration ?? projectionGeneration;
+ const matchesSourceGeneration = (analysisGeneration: string | undefined) => analysisGeneration === sourceGeneration
+ && (projectionGeneration === undefined || analysisGeneration === projectionGeneration);
+ const matchingTargetCatalog = targetCatalog?.project === project && targetCatalog.generation === generation
+ && targetCatalog.source === requestedEntry && matchesSourceGeneration(targetCatalog.analysisGeneration) ? targetCatalog : undefined;
+ const currentTargets = requestedEntry !== undefined && queryData?.behavior?.source_id === requestedEntry && matchesSourceGeneration(current?.response?.generation)
+ ? queryData.behavior.reachable_targets : [];
+ const targets = matchingTargetCatalog?.targets ?? currentTargets;
+ const queryPending = !current?.error && current?.response?.status !== 'failed' && !queryData;
+ useEffect(() => { setFocusId(undefined); setExpandedGroups([]); setScopeHistory([]); setSelection(undefined); }, [project, generation]);
+ const structureData = useMemo(() => data ? { ...data, dependencies: data.dependencies.filter(edge => connectionAllowed(edge.type, connectionView)) } : undefined, [data, connectionView]);
+ const error = current?.error ?? (current?.response?.status === 'failed' ? current.response.error ?? 'Architecture analysis failed.' : undefined);
+ const entries = entryChoices?.project === project && entryChoices.generation === generation ? entryChoices.entries : data?.entrypoints ?? [];
+ useEffect(() => {
+ if (view !== 'behavior' || !data || (entryChoice?.project === project && entryChoice.generation === generation)) return;
+ const suggested = suggestedBehaviorEntry(data.entrypoints);
+ if (suggested) setEntryChoice({ project, generation, expectedGeneration: current?.response?.generation ?? snapshot?.analysisGeneration, id: suggested.id });
+ }, [view, data, project, generation, entryChoice, current?.response?.generation, snapshot?.analysisGeneration]);
+ const returnedPaths = useMemo(() => {
+ const valid = queryData?.paths.filter(path => isContiguousPath(path)) ?? [];
+ if (queryData?.behavior && requestedTarget === undefined) return [];
+ const entry = requestedEntry ?? valid[0]?.entrypoint_id;
+ return valid.filter(path => path.entrypoint_id === entry)
+ .sort((a, b) => requestedTarget !== undefined ? a.edges.length - b.edges.length : b.edges.length - a.edges.length || handoffs(b.nodes) - handoffs(a.nodes));
+ }, [queryData, requestedEntry, requestedTarget]);
+ const paths = useMemo(() => {
+ const query = filter.trim().toLocaleLowerCase();
+ return returnedPaths.filter(path => !query || path.nodes.some(symbol => [symbol.name, symbol.file_path ?? ''].some(value => value.toLocaleLowerCase().includes(query))));
+ }, [returnedPaths, filter]);
+ const activePathIndex = Math.min(pathIndex, Math.max(0, paths.length - 1));
+ const highlightedPathIndex = paths.length ? activePathIndex : undefined;
+ const path = paths[activePathIndex];
+ const activeStep = Math.min(stepIndex, Math.max(0, (path?.nodes.length ?? 1) - 1));
+ const relationshipTypes = view === 'behavior' || connectionView === 'calls' ? ['CALLS', 'IMPORTS', 'HTTP_CALLS', 'ASYNC_CALLS']
+ : connectionView === 'all' ? undefined : ['INHERITS', 'IMPLEMENTS'];
+ const layoutKey = JSON.stringify([project, current?.response?.generation ?? snapshot?.analysisGeneration ?? generation]);
+ const overviewModel = useMemo(() => data && view === 'structure' ? systemOverviewGraph(data, {
+ filter, cyclesOnly, includeTests, includeUnconnected,
+ relationshipTypes, expandedGroupIds: expandedGroups, focusId, layoutKey,
+ }) : { nodes: [], edges: [], lanes: [], omittedNodes: 0, omittedEdges: 0 } as SystemSceneModel,
+ [data, filter, view, cyclesOnly, includeTests, includeUnconnected, connectionView, expandedGroups, focusId, layoutKey]);
+ const model = overviewModel;
+ const loads = useMemo(() => connectionLoad(model.nodes, model.edges), [model]);
+ const node = model.nodes.find(candidate => candidate.id === selection?.node);
+ const listedDependency = selection?.dependencyIndex === undefined ? undefined : data?.dependencies[selection.dependencyIndex];
+ const edge: SystemSceneEdge | undefined = model.edges.find(candidate => candidate.id === selection?.edge)
+ ?? (listedDependency ? { ...listedDependency, id: `listed:${selection?.dependencyIndex}`, dependency: listedDependency } : undefined);
+ const component = node?.component;
+ const selectedSymbol = node?.symbol ?? (view === 'behavior' && !edge && (!selection?.node || selection?.node.startsWith('step:')) ? path?.nodes[activeStep] : undefined);
+ const allComponents = useMemo(() => structureData && view === 'structure' ? systemComponents(structureData, filter, cyclesOnly, includeUnconnected, includeTests) : [], [structureData, view, filter, cyclesOnly, includeUnconnected, includeTests]);
+ const listedDependencies = useMemo(() => {
+ const ids = new Set(allComponents.map(item => item.id));
+ return data?.dependencies.map((dependency, index) => ({ dependency, index })).filter(item => connectionAllowed(item.dependency.type, connectionView) && ids.has(item.dependency.source) && ids.has(item.dependency.target)) ?? [];
+ }, [data, allComponents, connectionView]);
+ const sceneComponents = model.nodes.flatMap(item => item.component ? [item.component] : []);
+ const selectedComponent = component ?? sceneComponents.find(item => item.id === selection?.node) ?? allComponents.find(candidate => candidate.id === (selection?.node ?? model.focusId))
+ ?? allComponents.find(candidate => candidate.id === model.focusId) ?? (filter.trim() && sceneComponents.length === 1 ? sceneComponents[0] : undefined);
+ const neighbors = useMemo(() => {
+ const eligible = new Set(sceneComponents.map(item => item.id));
+ const incoming = new Map<string, Set<string>>(), outgoing = new Map<string, Set<string>>();
+ for (const dependency of model.edges) {
+ if (dependency.source === dependency.target) continue;
+ const target = dependency.target === selectedComponent?.id ? incoming : dependency.source === selectedComponent?.id ? outgoing : undefined;
+ const id = target === incoming ? dependency.source : dependency.target;
+ if (target && eligible.has(id)) {
+ if (!target.has(id)) target.set(id, new Set());
+ for (const type of dependency.types ?? [dependency.type]) target.get(id)!.add(type);
+ }
+ }
+ return { incoming, outgoing };
+ }, [model, selectedComponent]);
+ function selectSymbol(symbol: SystemSymbol, open = false) {
+ // The response can come from a newer graph snapshot; numeric IDs are not portable between snapshots.
+ const existing = symbol.qualified_name ? graph?.nodes.find(candidate => candidate.qualified_name === symbol.qualified_name) : undefined;
+ if (existing) onSelect?.(existing);
+ if (open && symbol.file_path) onNavigate(symbol.file_path, symbol.start_line || undefined, symbol.name);
+ }
+ function selectNode(id: string) {
+ setSelection({ node: id });
+ const found = model.nodes.find(candidate => candidate.id === id);
+ // Inspection deliberately leaves topology and camera unchanged.
+ if (found?.pathIndices?.length && !found.pathIndices.includes(activePathIndex)) setPathIndex(found.pathIndices[0]);
+ if (found?.depth !== undefined) setStepIndex(found.depth);
+ const symbol = found?.symbol;
+ if (symbol) selectSymbol(symbol);
+ }
+ function selectPath(index: number) { setPathIndex(index); setStepIndex(0); setSelection(undefined); }
+ function selectStep(index: number) {
+ if (!path?.nodes[index]) return;
+ setStepIndex(index);
+ const found = model.nodes.find(item => item.depth === index && item.pathIndices?.includes(activePathIndex))
+ ?? model.nodes.find(item => item.componentIds?.includes(path.nodes[index].component_id) || item.id === path.nodes[index].group_id);
+ setSelection(data?.overview ? undefined : found ? { node: found.id } : undefined); selectSymbol(path.nodes[index]);
+ }
+ function selectEdge(id: string) {
+ const found = model.edges.find(item => item.id === id);
+ const nextPath = found?.pathIndices?.includes(activePathIndex) ? activePathIndex : found?.pathIndices?.[0] ?? activePathIndex;
+ setPathIndex(nextPath);
+ setStepIndex(Math.max(0, paths[nextPath]?.edges.findIndex(item => item.id === found?.pathEdge?.id) ?? 0));
+ setSelection({ edge: id });
+ }
+ function open(symbol: SystemSymbol) { selectSymbol(symbol, true); }
+ function revealEvidence() {
+ const details = document.getElementById(`system-evidence-${view}`) as HTMLDetailsElement | null;
+ if (details) { details.open = true; details.scrollIntoView({ block: 'nearest' }); }
+ }
+ const pathSource = edge?.pathEdge && path?.nodes.find(symbol => symbol.id === edge.pathEdge!.source_id);
+ const pathTarget = edge?.pathEdge && path?.nodes.find(symbol => symbol.id === edge.pathEdge!.target_id);
+ const pending = !error && !data;
+ function clearSelection() {
+ setSelection(undefined); setFocusId(undefined); setScopeHistory([]); setExpandedGroups([]);
+ setResetKey(value => value + 1); onClearSelection?.();
+ }
+ function focus(id: string | undefined) { setScopeHistory(previous => [...previous, focusId]); setFocusId(id); }
+ function toggleGroup(id: string) { setExpandedGroups(previous => previous.includes(id) ? previous.filter(value => value !== id) : [...previous, id]); }
+ const selectedGroup = node?.group;
+ const corridorWitnesses: SystemWitness[] = view === 'behavior' ? (edge?.behaviorEdges ?? []).flatMap(evidence => {
+ const source = queryData?.behavior?.nodes.find(symbol => symbol.id === evidence.source_id);
+ const target = queryData?.behavior?.nodes.find(symbol => symbol.id === evidence.target_id);
+ return source && target ? [{ ...evidence, edge_id: evidence.id, source, target }] : [];
+ }) : [];
+ const selectedDependencies = corridorWitnesses.length ? [] : edge?.dependencies ?? (edge?.dependency ? [edge.dependency] : []);
+ const selectedSceneNode = selection?.node ?? (selectedSymbol ? model.nodes.find(item => item.symbol?.id === selectedSymbol.id
+ || item.id === selectedSymbol.group_id || item.componentIds?.includes(selectedSymbol.component_id))?.id : undefined);
+ const behavior = queryData?.behavior;
+ const completeOverview = data?.overview?.complete;
+ const limitationCount = data ? Object.entries(data.limits).filter(([key, value]) => (key.startsWith('omitted_') || key.endsWith('_truncated')) && Boolean(value)).length : 0;
+ const behaviorPage = view === 'behavior' ? <BehaviorJourney project={project} generation={projectionGeneration} data={queryData}
+ entries={entries} targets={targets} entryId={requestedEntry} targetId={requestedTarget} active={active} pending={queryPending}
+ error={error} filter={filter} onRefresh={() => setRevision(value => value + 1)} onNavigate={onNavigate} onSelectSymbol={selectSymbol} onClearSelection={onClearSelection}
+ onRequest={(entry, targetId) => {
+ const analysisGeneration = projectionGeneration ?? sourceGeneration;
+ if (entry && analysisGeneration) setEntryChoices(previous => ({ project, generation, analysisGeneration,
+ entries: [...new Map([...(previous?.project === project && previous.generation === generation ? previous.entries : entries), entry].map(item => [item.id, item])).values()] }));
+ setEntryChoice({ project, generation, id: entry?.id, targetId, expectedGeneration: analysisGeneration });
+ }} /> : undefined;
+ if (behaviorPage) return behaviorPage;
+ return <section className="system-architecture" data-testid="system-architecture" aria-label={view === 'structure' ? 'System structure' : 'Behavior'} aria-busy={active && pending}>
+ <div className="system-toolbar">
+ <p>{view === 'structure' ? 'Inspect the parts and the code that connects them.' : 'Follow a question through the same system map.'}</p>
+ <button className="atlas-arch-action system-refresh" onClick={() => { setRevision(value => value + 1); setResetKey(value => value + 1); }}>Refresh analysis</button>
+ </div><div className="system-controls">
+ <div className="system-scope-actions"><button disabled={!scopeHistory.length} onClick={() => { setFocusId(scopeHistory.at(-1)); setScopeHistory(previous => previous.slice(0, -1)); }}>← Back</button>
+ <button disabled={!focusId} onClick={clearSelection}>Whole system</button></div>
+ {view === 'structure' && <label>Connections <select aria-label="Connection view" value={connectionView} onChange={event => { setConnectionView(event.target.value as ConnectionView); setCyclesOnly(false); }}>
+ <option value="calls">Calls &amp; imports</option><option value="types">Type relationships</option><option value="all">All relationships</option>
+ </select></label>}
+ {view === 'structure' && <label title="Cycles in the displayed relationship lens; aggregate cycles do not establish symbol recursion."><input type="checkbox" checked={cyclesOnly} onChange={event => { setCyclesOnly(event.target.checked); setSelection(undefined); }} />{data?.overview ? 'Group cycles' : 'Component cycles'}</label>}
+ {view === 'structure' && <label title="Include components with no connection in the returned projection. Analysis limits can hide relationships."><input type="checkbox" checked={includeUnconnected} onChange={event => setIncludeUnconnected(event.target.checked)} />Include unconnected</label>}
+ {view === 'structure' && <label><input type="checkbox" checked={includeTests} onChange={event => { setIncludeTests(event.target.checked); setSelection(undefined); }} />Include test components</label>}
+ {view === 'behavior' && <span className="system-small">Calls &amp; imports · all code groups</span>}
+ {view === 'behavior' && <label>From <select aria-label="Behavior entry point" value={requestedEntry ?? ''} onChange={event => setEntryChoice({ project, generation,
+ expectedGeneration: entryChoices?.analysisGeneration ?? current?.response?.generation, id: event.target.value ? Number(event.target.value) : undefined })}>
+ <option value="">{path ? `Suggested · ${path.nodes[0].name}${path.nodes[0].file_path ? ` · ${path.nodes[0].file_path}` : ''}` : 'Choose an entry point'}</option>{entries.map(entry => <option key={entry.id} value={entry.id}>{entry.name}{entry.file_path ? ` · ${entry.file_path}` : ''}</option>)}
+ </select></label>}
+ {view === 'behavior' && (data?.behavior || requestedEntry !== undefined) && <label>To <select aria-label="Behavior destination" disabled={requestedEntry === undefined || (!targets.length && queryPending)} value={requestedTarget ?? ''}
+ onChange={event => setEntryChoice({ project, generation, id: requestedEntry, targetId: event.target.value ? Number(event.target.value) : undefined,
+ expectedGeneration: matchingTargetCatalog?.analysisGeneration ?? sourceGeneration })}>
+ <option value="">Choose a reachable operation…</option>{targets.map(target => <option key={target.id} value={target.id}>{target.name} · {target.file_path}</option>)}
+ </select></label>}
+ </div>
+ {error && !data ? <div className="system-analysis-state" role="alert"><strong>Could not analyze this project.</strong><p>{error}</p><button className="atlas-arch-action" onClick={() => setRevision(value => value + 1)}>Try again</button></div>
+ : pending ? <div className="system-analysis-state" role="status"><span className="system-progress" /><strong>{active ? 'Analyzing interactions…' : 'Analysis paused'}</strong><p>The workspace stays available while the server prepares this view.</p></div>
+ : data && <>
+ {error && <p className="system-small" role="alert">{error} <button onClick={() => setRevision(value => value + 1)}>Try again</button></p>}
+ <div className="system-reading-status"><span>{queryPending ? 'Updating path…' : view === 'structure'
+ ? data.overview ? `${data.overview.groups.length} groups · ${model.nodes.filter(item => !item.parentId).length} shown · ${data.overview.totals.components ?? data.overview.components.length} components accounted for`
+ : `${data.components.length} components returned · ${model.nodes.length} shown · ${structureData?.dependencies.length} of ${data.dependencies.length} returned connections`
+ : behavior?.mode === 'corridor' ? `${behavior.nodes.length} symbols · ${behavior.edges.length} calls in this corridor`
+ : data.behavior ? 'Choose a destination to reveal its call paths' : `${paths.length} indexed paths`}</span>
+ <span>{(view === 'structure' && completeOverview === true) || (view === 'behavior' && (behavior?.mode === 'corridor' ? behavior.corridor_complete ?? behavior.complete : behavior?.complete)) || (!data.overview && data.complete && !limitationCount) ? 'Indexed snapshot' : 'Partial analysis'} · <button onClick={revealEvidence}>Evidence and limits</button></span></div>
+ <div className="system-display-controls">
+ <span className="system-layout-hint" title="Directory ancestry determines placement. Connections still come from the indexed graph. Representatives provide location hints when no directory group is reported.">{data.overview || view === 'structure' ? 'Grouped by source location' : 'Ordered by call paths'}</span>
+ <label title="Ring area follows log(1 + visible links), relative to the busiest item in this view. Each directed relationship type counts once; this is visual load, not runtime activity."><input type="checkbox" checked={showConnectionLoad} onChange={event => setShowConnectionLoad(event.target.checked)} />Connection load</label>
+ <div className="system-view-switch" role="group" aria-label="System camera"><button aria-pressed={!planar} onClick={() => setPlanar(false)}>3D</button><button aria-pressed={planar} onClick={() => setPlanar(true)}>Plan</button></div>
+ </div>
+ <div className="system-workspace"><div className="system-map">
+ {model.nodes.length ? <Suspense fallback={<div className="system-scene-empty">Preparing 3D view…</div>}><Scene model={model} selectedNode={selectedSceneNode} selectedEdge={selection?.edge}
+ onSelectNode={selectNode} onSelectEdge={selectEdge} onExpandNode={id => { toggleGroup(id); focus(id); }} onClearSelection={clearSelection} highlightedPathIndex={view === 'behavior' ? highlightedPathIndex : undefined} resetKey={resetKey} planar={planar} active={active} showConnectionLoad={showConnectionLoad} /></Suspense>
+ : <div className="system-scene-empty">{view === 'behavior' ? filter ? 'No source paths match this filter. Clear it to see the entry point’s returned paths.' : 'No connected source path is available for this entry point.' : cyclesOnly ? 'No component cycles match the current filters in the returned analysis.' : filter ? 'No matching components. Try a broader filter or include unconnected components.' : data.components.length && !includeUnconnected ? 'No connected components match the current view. Change the connection filter or include unconnected components.' : 'No component projection is available within this analysis budget.'}</div>}
+ <div className="system-map-caption"><span>{view === 'behavior' ? 'Arrows are indexed calls, not an execution timeline.' : 'Select to inspect · expand a group for its members'}{showConnectionLoad ? ' · rings show link load' : ''}</span>
+ <button onClick={() => setResetKey(value => value + 1)}>Fit view</button></div>
+ </div><aside className="system-inspector" aria-label="System evidence inspector">
+ {edge ? <><span className="system-eyebrow">{edge.type.replaceAll('_', ' ')}</span><h3>{model.nodes.find(item => item.id === edge.source)?.label ?? data.components.find(item => item.id === edge.source)?.label ?? edge.source} → {model.nodes.find(item => item.id === edge.target)?.label ?? data.components.find(item => item.id === edge.target)?.label ?? edge.target}</h3>
+ {corridorWitnesses.length > 0 && <><p>{corridorWitnesses.length} calls in the selected corridor.</p>{corridorWitnesses.slice(0, listLimit).map(witness => <CallWitness key={witness.edge_id} witness={witness} type={edge.behaviorEdges?.find(item => item.id === witness.edge_id)?.type ?? edge.type} onOpen={open} onNavigate={onNavigate} />)}
+ {corridorWitnesses.length > listLimit && <button onClick={() => setListLimit(value => value + 20)}>More call sites</button>}</>}
+ {selectedDependencies.length > 0 && <><p>{selectedDependencies.reduce((sum, item) => sum + item.count, 0).toLocaleString()} indexed relationships · {selectedDependencies.reduce((sum, item) => sum + item.witnesses.length, 0)} source examples.</p>
+ {selectedDependencies.map(dependency => <div key={`${dependency.source}:${dependency.target}:${dependency.type}`} className="system-connection-evidence"><h4>{dependency.type.replaceAll('_', ' ')} <span>{dependency.count}</span></h4>
+ {dependency.witnesses.map(witness => <CallWitness key={witness.edge_id} witness={witness} type={dependency.type} onOpen={open} onNavigate={onNavigate} />)}
+ {!dependency.witnesses.length && <p className="system-small">No source example returned for this relationship.</p>}
+ </div>)}<p className="system-small">Counts describe indexed relationships. Examples may be a sample.</p></>}
+ {pathSource && pathTarget && edge.pathEdge && <CallWitness witness={{ ...edge.pathEdge, edge_id: edge.pathEdge.id, source: pathSource, target: pathTarget }} type={edge.type} onOpen={open} onNavigate={onNavigate} />}
+ {edge.type === 'CALL_REFERENCE' && <p>A callable reference does not establish invocation.</p>}
+ </> : selectedSymbol ? <><span className="system-eyebrow">Step {activeStep + 1} of {path?.nodes.length} · selected path</span><h3>{selectedSymbol.name}</h3><EvidenceSource symbol={selectedSymbol} onOpen={open} />
+ <p>{data.components.find(item => item.id === selectedSymbol.component_id)?.label ?? selectedSymbol.file_path ?? 'Component outside returned summary'}</p>
+ {path?.edges[activeStep] && <CallEvidence evidence={path.edges[activeStep]} caller={selectedSymbol} onNavigate={onNavigate} />}
+ <div className="system-step-controls"><button disabled={activeStep <= 0} onClick={() => selectStep(activeStep - 1)}>← Previous step</button><button disabled={!path || activeStep >= path.nodes.length - 1} onClick={() => selectStep(activeStep + 1)}>Next step →</button></div>
+ {path && <p className="system-small">{handoffs(path.nodes)} component handoffs. This is a connected static witness; execution conditions are not established.</p>}</>
+ : selectedComponent ? <><span className="system-eyebrow">{componentBasis(selectedComponent.basis)}</span><h3>{selectedComponent.label}</h3>
+ {selectedComponent.role === 'test' && <span className="system-test-badge" title={selectedComponent.role_basis}>Test code</span>}
+ <div className="system-selection-actions">{selectedGroup && <button onClick={() => toggleGroup(selectedGroup.id)}>{expandedGroups.includes(selectedGroup.id) ? 'Collapse group' : 'Expand group'}</button>}
+ <button onClick={() => focus(selectedComponent.id)}>Focus here</button></div>
+ {showConnectionLoad && node && <p className="system-small">{loads.get(node.id)?.links ?? 0} visible links · {loads.get(node.id)?.neighbors ?? 0} connected items in this view.</p>}
+ {selectedGroup && <p className="system-small">{selectedGroup.component_count} code groups share this boundary. Grouping follows source organization; functional responsibilities are not inferred from its name.</p>}
+ {selectedGroup && <label className="system-member-picker">Browse members <select aria-label="Group member" value="" onChange={event => {
+ const id = event.target.value; if (!id) return;
+ setExpandedGroups(previous => previous.includes(selectedGroup.id) ? previous : [...previous, selectedGroup.id]);
+ focus(id); setSelection({ node: `member:${selectedGroup.id}:${id}` });
+ }}><option value="">Choose a component…</option>{(data.overview?.components ?? []).filter(item => selectedGroup.component_ids.includes(item.id)).map(item => <option key={item.id} value={item.id}>{item.label}</option>)}</select></label>}
+ <p>{selectedComponent.member_count.toLocaleString()} symbols across {selectedComponent.file_count.toLocaleString()} files.</p>
+ {(['incoming', 'outgoing'] as const).map(direction => <div className="system-neighbors" key={direction}><h4>{direction === 'incoming' ? 'Used by' : 'Uses'} <span>{neighbors[direction].size}</span></h4>
+ {neighbors[direction].size ? [...neighbors[direction]].slice(0, 8).map(([id, types]) => <div className="system-neighbor-row" key={id}>
+ <button onClick={() => selectNode(id)} title={model.nodes.find(item => item.id === id)?.label}><strong>{model.nodes.find(item => item.id === id)?.label ?? id}</strong><small>{[...types].map(type => type.toLowerCase().replaceAll('_', ' ')).join(' · ')}</small></button>
+ <button className="system-neighbor-evidence" aria-label={`Inspect ${direction} connection ${direction === 'incoming' ? 'from' : 'to'} ${model.nodes.find(item => item.id === id)?.label ?? id}`} onClick={() => {
+ const connection = model.edges.find(item => direction === 'incoming' ? item.source === id && item.target === selectedComponent.id : item.source === selectedComponent.id && item.target === id);
+ if (connection) selectEdge(connection.id);
+ }}>Evidence</button>
+ </div>) : <p className="system-small">None in the current view.</p>}
+ {neighbors[direction].size > 8 && <small>{neighbors[direction].size - 8} more in the dependency list below.</small>}
+ </div>)}
+ <details className="system-representatives"><summary>Representative sources</summary>{selectedComponent.representatives.map(symbol => <EvidenceSource key={symbol.id} symbol={symbol} onOpen={open} />)}
+ <p className="system-small">Sources shown are examples; the membership count includes the whole returned group.</p></details>
+ </> : <><span className="system-eyebrow">Inspect the evidence</span><h3>{view === 'structure' ? 'How the parts connect' : 'A path through the system'}</h3>
+ <p>Select a component, symbol or connection to inspect its source evidence.</p><p>{view === 'structure' ? 'Collaboration groups are inferred from indexed interactions. They do not establish deployment boundaries.' : 'Each arrow follows a recorded relationship. Static paths describe possible interactions, not observed execution.'}</p></>}
+ </aside></div>
+ {(model.omittedNodes > 0 || model.omittedEdges > 0) && <p className="system-limit">{view === 'structure' ? 'This scope has additional detail.' : 'Additional detail is outside this scene.'} {model.omittedNodes} nodes and {model.omittedEdges} connections are outside this scene. Returned findings remain available below.</p>}
+ {view === 'structure' && !data.overview ? <details className="system-findings"><summary>Browse components · {allComponents.length}</summary>
+ <div className="system-component-list">{allComponents.slice(0, listLimit).map(item => <button key={item.id} aria-pressed={model.focusId === item.id} onClick={() => selectNode(item.id)}>
+ <strong>{item.label}</strong><span>{componentBasis(item.basis)}{item.role === 'test' && <> · <span title={item.role_basis}>Test code</span></>}</span><small>{item.member_count.toLocaleString()} symbols · {item.file_count.toLocaleString()} files</small></button>)}</div>
+ {allComponents.length > listLimit && <button className="atlas-arch-action" onClick={() => setListLimit(value => value + 20)}>More components</button>}
+ <details><summary>Directed dependencies · {listedDependencies.length}</summary><div className="system-dependency-list">{listedDependencies.slice(0, listLimit).map(({ dependency: item, index }) => <button key={index} onClick={() => {
+ const visible = model.edges.find(candidate => candidate.dependency === item);
+ if (visible) setSelection({ edge: visible.id }); else setSelection({ dependencyIndex: index });
+ }}>{model.nodes.find(component => component.id === item.source)?.label ?? item.source} → {model.nodes.find(component => component.id === item.target)?.label ?? item.target}<small>{item.type} · {item.count}</small></button>)}</div>
+ {listedDependencies.length > listLimit && <button className="atlas-arch-action" onClick={() => setListLimit(value => value + 20)}>More dependencies</button>}
+ </details>
+ </details> : view === 'behavior' && path && <><div className="system-branch-list" role="group" aria-label="Indexed paths">{paths.map((item, index) => <button key={index} aria-pressed={activePathIndex === index} onClick={() => selectPath(index)}>
+ <span>Path {index + 1}</span><strong>{item.nodes.at(-1)?.name}</strong><small>{item.edges.length} calls · {handoffs(item.nodes)} handoffs</small>
+ </button>)}</div><details className="system-findings"><summary>Connected source path · {path.nodes.length} symbols</summary><ol className="system-path-list">{path.nodes.map((symbol, index) => <li key={`${symbol.id}:${index}`} data-selected={activeStep === index}>
+ <button className="system-step-select" aria-label={`Select step ${index + 1}: ${symbol.name}`} aria-pressed={activeStep === index} onClick={() => selectStep(index)}>{index + 1}</button>
+ <EvidenceSource symbol={symbol} onOpen={open} />{path.edges[index] && <span>↓ {path.edges[index].type.replaceAll('_', ' ')}{symbol.component_id !== path.nodes[index + 1].component_id ? ' · component handoff' : ''}</span>}</li>)}</ol></details></>}
+ {view === 'behavior' && data.behavior && !queryPending && !requestedTarget && <p className="system-small">The destination list shows reachable indexed symbols within {data.behavior.max_hops} calls.
+ {(data.behavior.totals.omitted_targets ?? 0) > 0 && <> This bounded list omits {data.behavior.totals.omitted_targets.toLocaleString()} reachable targets.</>} Select an operation to see its connecting paths and source evidence.</p>}
+ {view === 'behavior' && behavior?.mode === 'corridor' && !paths.length && <p className="system-small" role="status">{returnedPaths.length
+ ? 'No source paths match this filter. The returned call corridor remains visible; clear the filter to inspect its witnesses.'
+ : 'No connected witness was returned within this query’s limits. This does not establish that the operation is unreachable.'}</p>}
+ <EvidenceDetails data={data} view={view} invalidPaths={data.paths.filter(item => !isContiguousPath(item)).length} />
+ </>}
+ </section>;
+}
+
+function EvidenceDetails({ data, view, invalidPaths }: { data: SystemProjection; view: string; invalidPaths: number }) {
+ const omitted = Object.entries(data.limits).filter(([key, value]) => (key.startsWith('omitted_') || key.endsWith('_truncated')) && Boolean(value));
+ return <details className="system-findings" id={`system-evidence-${view}`} open={invalidPaths > 0}>
+ <summary>Evidence and limits</summary><p>This view uses indexed source relationships. Definition links point to indexed declarations; call-site links use recorded invocation locations where available. Changes since indexing are not included. Group boundaries may follow declared modules, inferred interactions or common source directories; the inspector identifies their basis. Component dependency cycles can involve different symbols at each boundary; they do not establish function recursion, runtime loops or a design defect. Behavior paths separately require connected source relationships. Missing relationships can reflect indexing coverage or unresolved bindings.</p>
+ <p>{data.totals.accounted_nodes?.toLocaleString() ?? 'Unknown'} nodes assigned to components; {data.totals.structural_nodes?.toLocaleString() ?? 'Unknown'} structural nodes reported separately.</p>
+ {omitted.map(([key, value]) => <p key={key}>{key.replaceAll('_', ' ')}: {String(value)}</p>)}
+ {data.overview && <p>Overview: {data.overview.totals.components ?? data.overview.components.length} components across {data.overview.groups.length} groups. {data.overview.complete ? 'All analyzed components are represented at this level.' : 'This overview is limited.'} {Object.entries(data.overview.limits).filter(([, value]) => Boolean(value)).map(([key, value]) => `${key.replaceAll('_', ' ')}: ${value}`).join(' · ')}</p>}
+ {data.behavior && <p>Static query limited to {data.behavior.max_hops} calls. {data.behavior.limits_hit.join(' · ')}</p>}
+ {data.warnings.map((warning, index) => <p key={index}>{warning}</p>)}
+ {invalidPaths > 0 && <p>{invalidPaths} disconnected path responses were excluded because their source relationships did not join.</p>}
+ </details>;
+}
+
+function CallEvidence({ evidence, caller, onNavigate }: { evidence: SystemCallEvidence; caller: SystemSymbol; onNavigate: SystemArchitectureProps['onNavigate'] }) {
+ return <div className="system-call-evidence">{evidence.callsite ? <button onClick={() => onNavigate(evidence.callsite!.file_path, evidence.callsite!.line, caller.name)}>Open call site · {evidence.callsite.file_path}:{evidence.callsite.line}</button>
+ : <span>Call site unavailable · definition links below</span>}
+ {evidence.resolution?.strategy && <small>Resolved by {evidence.resolution.strategy.replaceAll('_', ' ')}{evidence.resolution.candidates !== undefined ? ` · ${evidence.resolution.candidates} candidate${evidence.resolution.candidates === 1 ? '' : 's'}` : ''}</small>}</div>;
+}
+function CallWitness({ witness, type, onOpen, onNavigate }: { witness: SystemWitness; type: string; onOpen: (symbol: SystemSymbol) => void; onNavigate: SystemArchitectureProps['onNavigate'] }) {
+ return <article className="system-witness"><CallEvidence evidence={witness} caller={witness.source} onNavigate={onNavigate} /><EvidenceSource symbol={witness.source} onOpen={onOpen} /><span>→ {type.replaceAll('_', ' ')}</span><EvidenceSource symbol={witness.target} onOpen={onOpen} /></article>;
+}
diff --git a/graph-ui/src/architecture/SystemArchitectureScene.tsx b/graph-ui/src/architecture/SystemArchitectureScene.tsx
new file mode 100644
index 000000000..6214e69bf
--- /dev/null
+++ b/graph-ui/src/architecture/SystemArchitectureScene.tsx
@@ -0,0 +1,297 @@
+import { Component, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
+import { Canvas, useFrame, useThree } from '@react-three/fiber';
+import { Edges, Html, Line, OrbitControls, OrthographicCamera } from '@react-three/drei';
+import { Box3, Color, MOUSE, TOUCH, OrthographicCamera as ThreeOrthographicCamera, QuadraticBezierCurve3, Quaternion, Vector3 } from 'three';
+import type { SystemSceneEdge, SystemSceneLane, SystemSceneModel, SystemSceneNode } from './system-architecture-model';
+import { edgeColor, isDirectedEdge, normalizeEdgeType } from '../graph/edge-style';
+import { EdgePulseLayer } from '../graph/EdgePulseLayer';
+import { useGraphBackgroundReset } from '../graph/useGraphBackgroundReset';
+import { connectionLoad, type ConnectionLoad } from '../graph/connection-load';
+
+/** The model keeps its stable XY layout; rendering places that footprint on XZ. */
+const groundPosition = ([x, y, z]: [number, number, number]): Vector3 => new Vector3(x, z, -y);
+const dimensions = (node: SystemSceneNode): [number, number, number] => {
+ const [width, height, depth] = node.size ?? (node.component ? [11, 8, 3.6] : [3, 3, 1.8]);
+ return [width, depth, height];
+};
+const center = (node: SystemSceneNode): Vector3 => groundPosition(node.position).add(new Vector3(0, node.size ? 0 : dimensions(node)[1] / 2, 0));
+const activeNode = (model: SystemSceneModel, node: SystemSceneNode, path?: number) => !model.highlightActive
+ || (path === undefined ? node.inCorridor : node.pathIndices?.includes(path));
+const activeEdge = (model: SystemSceneModel, edge: SystemSceneEdge, path?: number) => !model.highlightActive
+ || (path === undefined ? edge.inCorridor : edge.pathIndices?.includes(path));
+
+interface CameraSnapshot { position: [number, number, number]; target: [number, number, number]; zoom: number; far: number; width: number; height: number }
+const cameraViews = new Map<string, CameraSnapshot>();
+
+/** Only explicit scope changes or resizing fit the camera; selection is deliberately absent. */
+function ScopeCamera({ model, resetKey, planar, presentation }: { model: SystemSceneModel; resetKey: number; planar: boolean; presentation?: 'system' | 'journey' }) {
+ const { camera, controls, size, invalidate } = useThree();
+ const currentModel = useRef(model); currentModel.current = model;
+ const previous = useRef<{ key: string; reset: number; width: number; height: number } | undefined>(undefined);
+ const key = `${model.scopeKey ?? 'legacy'}:focus:${model.focusId ?? ''}:projection:${planar ? 'plan' : '3d'}`;
+ useLayoutEffect(() => {
+ const orbit = controls as unknown as { target: Vector3; update: () => void } | undefined;
+ if (!orbit || !(camera instanceof ThreeOrthographicCamera) || size.width < 1 || size.height < 1) return;
+ const last = previous.current;
+ if (last && last.key !== key) {
+ cameraViews.set(last.key, { position: camera.position.toArray() as [number, number, number], target: orbit.target.toArray() as [number, number, number], zoom: camera.zoom, far: camera.far, width: last.width, height: last.height });
+ if (cameraViews.size > 24) cameraViews.delete(cameraViews.keys().next().value!);
+ }
+ const stored = last?.reset === resetKey ? cameraViews.get(key) : undefined;
+ previous.current = { key, reset: resetKey, width: size.width, height: size.height };
+ camera.up.set(0, planar ? 0 : 1, planar ? -1 : 0);
+ if (stored && last?.key !== key && stored.width === size.width && stored.height === size.height) {
+ camera.position.fromArray(stored.position); camera.zoom = stored.zoom; camera.far = stored.far; camera.updateProjectionMatrix();
+ orbit.target.fromArray(stored.target); orbit.update(); invalidate(); return;
+ }
+ const scope = currentModel.current;
+ const focus = scope.nodes.find(node => node.id === scope.focusId);
+ const targets = focus ? scope.nodes.filter(node => node.id === focus.id || node.parentId === focus.id) : scope.nodes;
+ const box = new Box3();
+ for (const node of targets) {
+ const location = center(node), half = new Vector3(...dimensions(node)).multiplyScalar(0.5).add(new Vector3(6, 6, 6));
+ box.expandByPoint(location.clone().sub(half));
+ box.expandByPoint(location.clone().add(half));
+ box.expandByPoint(new Vector3(...labelPosition(node)));
+ }
+ if (!focus) for (const lane of scope.lanes ?? []) {
+ const location = groundPosition(lane.position), half = new Vector3(lane.width / 2 + 2, lane.depth / 2 + 1, (lane.height ?? 24) / 2 + 2);
+ box.expandByPoint(location.clone().sub(half));
+ box.expandByPoint(location.clone().add(half));
+ }
+ if (box.isEmpty()) box.set(new Vector3(-12, -2, -12), new Vector3(12, 5, 12));
+ const target = box.getCenter(new Vector3()), reach = Math.max(30, box.getSize(new Vector3()).length());
+ camera.position.copy(target).addScaledVector(new Vector3(...(planar ? [0, 1, 0] : presentation === 'journey' ? [0.1, 1.6, 0.9] : [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 [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) {
+ projected.expandByPoint(new Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse));
+ }
+ const span = projected.getSize(new Vector3());
+ // Labels use CSS pixels, so reserve margins after projecting the scene bounds.
+ camera.zoom = Math.max(0.15, Math.min(90, Math.max(60, size.width - 160) / Math.max(1, span.x), Math.max(60, size.height - 120) / Math.max(1, span.y)));
+ camera.updateProjectionMatrix(); orbit.target.copy(target); orbit.update(); invalidate();
+ }, [camera, controls, invalidate, key, planar, resetKey, size.width, size.height, presentation]);
+ return null;
+}
+
+/** Folder backplates are visual containment, never selectable nodes or relationships. */
+function FolderBackplate({ lane }: { lane: SystemSceneLane }) {
+ const height = lane.height ?? 24;
+ return <group position={groundPosition(lane.position)}>
+ <mesh raycast={() => null}>
+ <boxGeometry args={[lane.width, lane.depth, height]} />
+ <meshStandardMaterial color="#536977" roughness={0.95} transparent opacity={0.09} depthWrite={false} />
+ <Edges color="#6e8a98" transparent opacity={0.24} />
+ </mesh>
+ <Html position={[-lane.width / 2 + 3, lane.depth / 2 + 0.2, -height / 2 + 3]} zIndexRange={[5, 1]} style={{ pointerEvents: 'none' }}>
+ <span className="system-scene-lane-label" data-folder-id={lane.id} title={lane.label}>{lane.label}</span>
+ </Html>
+ </group>;
+}
+
+/** Source-to-target geometry is shared by the base edge and the GPU pulse batch. */
+function connectionGeometry(source: SystemSceneNode, target: SystemSceneNode, offset: number) {
+ const start = center(source), end = center(target), sourceSize = dimensions(source);
+ start.y += sourceSize[1] / 2 + 0.4;
+ end.y += dimensions(target)[1] / 2 + 0.4;
+ let control: Vector3;
+ if (source.id === target.id) {
+ start.add(new Vector3(sourceSize[0] / 2 + 0.3, 0, sourceSize[2] / 4));
+ end.add(new Vector3(sourceSize[0] / 4, 0, sourceSize[2] / 2 + 0.3));
+ control = center(source).add(new Vector3(sourceSize[0] / 2 + 13, sourceSize[1] / 2 + 8, sourceSize[2] / 2 + 13))
+ .addScaledVector(new Vector3(1, 0.3, 1).normalize(), offset);
+ } else {
+ const direction = end.clone().sub(start).setY(0), normal = direction.clone().normalize();
+ const reach = (node: SystemSceneNode) => Math.min(dimensions(node)[0] / 2 / Math.max(1e-6, Math.abs(normal.x)), dimensions(node)[2] / 2 / Math.max(1e-6, Math.abs(normal.z))) + 0.5;
+ const from = reach(source), to = reach(target), factor = Math.min(1, Math.max(0, direction.length() - 1) / (from + to));
+ start.addScaledVector(normal, from * factor); end.addScaledVector(normal, -to * factor);
+ const side = new Vector3(-direction.z, 0, direction.x).normalize().multiplyScalar(offset * (source.id < target.id ? 1 : -1));
+ control = start.clone().lerp(end, 0.5).add(side).add(new Vector3(0, Math.min(10, 3.5 + direction.length() * 0.035), 0));
+ }
+ const curve = new QuadraticBezierCurve3(start, control, end);
+ return { curve, points: curve.getPoints(32), arrow: curve.getPoint(0.76), rotation: new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), curve.getTangent(0.76).normalize()) };
+}
+
+interface ConnectionStrand { type: string; geometry: ReturnType<typeof connectionGeometry> }
+
+function Connection({ edge, strands, selected, dimmed, emphasized, onSelect }: {
+ edge: SystemSceneEdge; strands: ConnectionStrand[]; selected: boolean;
+ dimmed: boolean; emphasized: boolean; onSelect: () => void;
+}) {
+ const internal = edge.source === edge.target;
+ const opacity = selected ? 0.98 : dimmed ? 0.065 : emphasized ? 0.86 : internal ? 0.15 : 0.34;
+ return <group onClick={event => { event.stopPropagation(); onSelect(); }}>
+ {strands.map(({ type, geometry }) => <group key={type}>
+ <Line points={geometry.points} color={edgeColor(type)} lineWidth={selected ? 2 : emphasized ? 1.6 : 0.7}
+ transparent opacity={opacity} depthWrite={false} />
+ {isDirectedEdge(type) && <mesh position={geometry.arrow} quaternion={geometry.rotation}>
+ <coneGeometry args={[selected || emphasized ? 0.85 : 0.62, 2.2, 7]} />
+ <meshBasicMaterial color={edgeColor(type)} transparent opacity={opacity} depthWrite={false} />
+ </mesh>}
+ </group>)}
+ {selected && <Html position={strands[0].geometry.curve.getPoint(0.5).lerp(strands.at(-1)!.geometry.curve.getPoint(0.5), 0.5)} center zIndexRange={[15, 10]} style={{ pointerEvents: 'none' }}>
+ <span className="system-scene-edge-label" style={{ borderColor: edgeColor(edge.type, edge.types) }}>{internal ? 'Within group · ' : ''}{edge.types?.length ? edge.types.join(' · ').replaceAll('_', ' ') : edge.type.replaceAll('_', ' ')} · {edge.count}</span>
+ </Html>}
+ </group>;
+}
+
+const labelPosition = (node: SystemSceneNode): [number, number, number] => {
+ const point = center(node), size = dimensions(node);
+ return [point.x, point.y + size[1] / 2 + (node.parentId ? 2.6 : 4), point.z - (node.expanded ? size[2] / 2 + 2 : 0)];
+};
+
+/** Corridor labels take priority; neither hovering nor ordinary selection changes membership. */
+function NodeLabels({ model, selectedNode, highlightedPathIndex, onSelect, onExpand, loads, presentation }: {
+ model: SystemSceneModel; selectedNode?: string; highlightedPathIndex?: number;
+ onSelect: (id: string) => void; onExpand?: (id: string) => void;
+ loads?: Map<string, ConnectionLoad>; presentation?: 'system' | 'journey';
+}) {
+ const { camera, size, gl } = useThree(), previous = useRef('');
+ const [visible, setVisible] = useState<Set<string>>(new Set());
+ const [captionHeight, setCaptionHeight] = useState(36);
+ const ordered = useMemo(() => [...model.nodes].sort((a, b) => (model.highlightActive
+ ? Number(Boolean(activeNode(model, b, highlightedPathIndex))) - Number(Boolean(activeNode(model, a, highlightedPathIndex))) : 0)
+ || Number(Boolean(a.parentId)) - Number(Boolean(b.parentId)) || a.id.localeCompare(b.id)), [model, highlightedPathIndex]);
+ useLayoutEffect(() => {
+ const caption = gl.domElement.closest('.system-map')?.querySelector<HTMLElement>('.system-map-caption');
+ if (!caption) return;
+ const measure = () => setCaptionHeight(Math.ceil(caption.getBoundingClientRect().height) + 4);
+ measure();
+ const observer = new ResizeObserver(measure); observer.observe(caption);
+ return () => observer.disconnect();
+ }, [gl]);
+ useFrame(() => {
+ const boxes: { left: number; right: number; top: number; bottom: number }[] = [], ids: string[] = [];
+ const zoom = 'zoom' in camera ? Number(camera.zoom) : 1;
+ for (const node of ordered) {
+ if (node.parentId && zoom < 5) continue;
+ const projected = new Vector3(...labelPosition(node)).project(camera);
+ if (projected.z < -1 || projected.z > 1) continue;
+ const x = (projected.x + 1) * size.width / 2, y = (1 - projected.y) * size.height / 2;
+ const compact = node.kind === 'group' && !node.expanded;
+ const width = presentation === 'journey' ? 116 : compact ? 76 : node.parentId ? 110 : node.expanded ? 126 : 96, height = presentation === 'journey' ? 58 : compact ? 24 : 28;
+ const box = { left: x - width / 2, right: x + width / 2, top: y - height / 2, bottom: y + height / 2 };
+ if (box.left < 2 || box.right > size.width - 2 || box.top < 2 || box.bottom > size.height - captionHeight) continue;
+ if (boxes.some(other => box.left < other.right && box.right > other.left && box.top < other.bottom && box.bottom > other.top)) continue;
+ boxes.push(box); ids.push(node.id);
+ }
+ const key = ids.join('|');
+ if (key !== previous.current) { previous.current = key; setVisible(new Set(ids)); }
+ });
+ return <>{ordered.filter(node => visible.has(node.id)).map(node => <Html key={node.id}
+ position={labelPosition(node)} center zIndexRange={[10, 6]}>
+ <button className="system-scene-node-label" data-presentation={presentation} data-kind={node.kind} data-expanded={node.expanded} data-child={Boolean(node.parentId)}
+ data-selected={selectedNode === node.id} data-focus={model.focusId === node.id}
+ data-node-id={node.id} data-position={center(node).toArray().join(',')} data-size={dimensions(node).join(',')}
+ data-color={node.visual?.color} data-color-label={node.visual?.label}
+ data-connection-load={loads?.get(node.id)?.links}
+ style={{ '--system-node-tint': node.visual?.color ?? '#91a6b4' } as CSSProperties}
+ data-muted={!activeNode(model, node, highlightedPathIndex)} title={`${node.label} · ${node.detail}${loads ? ` · ${loads.get(node.id)?.links ?? 0} visible links · ${loads.get(node.id)?.neighbors ?? 0} connected items` : ''}${node.visual ? ` · ${node.visual.label}${node.visual.basis ? ` (${node.visual.basis})` : ''}` : ''}`}
+ type="button" aria-label={`${node.label} · ${node.detail}`} aria-pressed={selectedNode === node.id}
+ onClick={() => onSelect(node.id)} onDoubleClick={onExpand && (node.group || presentation === 'journey') ? () => onExpand(node.id) : undefined}>
+ {presentation === 'journey' && <small>{node.depth === 0 ? 'START' : node.pathIndices?.length ? `HOP ${node.depth}` : 'POSSIBLE CALL'}</small>}
+ <strong>{node.label}</strong>
+ {presentation === 'journey' && <small>{node.symbol?.file_path?.split('/').at(-1) ?? 'Source unavailable'}</small>}
+ </button>
+ </Html>)}</>;
+}
+
+class SceneBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false };
+ static getDerivedStateFromError() { return { failed: true }; }
+ render() { return this.state.failed ? <div className="system-scene-empty" role="status">3D is unavailable. Components and source evidence remain accessible below.</div> : this.props.children; }
+}
+
+export default function SystemArchitectureScene({ model, selectedNode, selectedEdge, highlightedPathIndex, onSelectNode, onSelectEdge, onExpandNode, onClearSelection, resetKey, planar = false, active = true, showConnectionLoad = true, presentation = 'system' }: {
+ model: SystemSceneModel; selectedNode?: string; selectedEdge?: string; highlightedPathIndex?: number;
+ onSelectNode: (id: string) => void; onSelectEdge: (id: string) => void; onExpandNode?: (id: string) => void; onClearSelection?: () => void; resetKey: number; planar?: boolean; active?: boolean; showConnectionLoad?: boolean; presentation?: 'system' | 'journey';
+}) {
+ const nodes = useMemo(() => new Map(model.nodes.map(node => [node.id, node])), [model.nodes]);
+ const activePath = highlightedPathIndex ?? model.preferredPathIndex;
+ const loads = useMemo(() => connectionLoad(model.nodes, model.edges), [model.nodes, model.edges]);
+ const neighborhood = useMemo(() => {
+ const ids = new Set<string>();
+ if (selectedNode && nodes.has(selectedNode)) ids.add(selectedNode);
+ for (const edge of model.edges) if (edge.id === selectedEdge || edge.source === selectedNode || edge.target === selectedNode) {
+ ids.add(edge.source); ids.add(edge.target);
+ }
+ return ids;
+ }, [model.edges, nodes, selectedNode, selectedEdge]);
+ const focusedEdge = (edge: SystemSceneEdge) => !neighborhood.size || edge.id === selectedEdge || edge.source === selectedNode || edge.target === selectedNode;
+ const offsets = useMemo(() => {
+ const pairs = new Map<string, SystemSceneEdge[]>(), result = new Map<string, number>();
+ model.edges.forEach(edge => { const key = JSON.stringify([edge.source, edge.target].sort()); pairs.set(key, [...(pairs.get(key) ?? []), edge]); });
+ pairs.forEach(edges => edges.sort((a, b) => a.id.localeCompare(b.id)).forEach((edge, index) => result.set(edge.id, (index - (edges.length - 1) / 2) * 7)));
+ return result;
+ }, [model.edges]);
+ const edgeStrands = useMemo(() => {
+ const result = new Map<string, ConnectionStrand[]>();
+ for (const edge of model.edges) {
+ const source = nodes.get(edge.source), target = nodes.get(edge.target);
+ if (!source || !target) continue;
+ const types = [...new Set((edge.types?.length ? edge.types : [edge.type]).map(normalizeEdgeType).filter(Boolean))].sort();
+ if (!types.length) types.push(normalizeEdgeType(edge.type));
+ result.set(edge.id, types.map((type, index) => ({ type,
+ geometry: connectionGeometry(source, target, (offsets.get(edge.id) ?? 0) + (index - (types.length - 1) / 2) * 4.5) })));
+ }
+ return result;
+ }, [model.edges, nodes, offsets]);
+ const pulsePaths = useMemo(() => model.edges.flatMap(edge => {
+ const dimmed = !activeEdge(model, edge, activePath) || !focusedEdge(edge), emphasized = (model.highlightActive || neighborhood.size > 0) && !dimmed;
+ return (edgeStrands.get(edge.id) ?? []).filter(strand => isDirectedEdge(strand.type)).map(({ type, geometry }) => ({ id: `${edge.id}:${type}`, type, points: geometry.points,
+ opacity: edge.id === selectedEdge ? 0.95 : dimmed ? 0.04 : emphasized ? 0.8 : edge.source === edge.target ? 0.22 : 0.65 }));
+ }), [model, edgeStrands, activePath, selectedEdge, selectedNode, neighborhood]);
+ const background = useGraphBackgroundReset(onClearSelection);
+ const floorY = Math.min(0, ...model.nodes.map(node => center(node).y - dimensions(node)[1] / 2), ...(model.lanes ?? []).map(lane => lane.position[2] - lane.depth / 2)) - 0.2;
+ const extent = Math.max(120, ...model.nodes.map(node => Math.max(Math.abs(node.position[0]) + dimensions(node)[0] / 2, Math.abs(node.position[1]) + dimensions(node)[2] / 2) * 2 + 40));
+ return <SceneBoundary><div className="system-scene" data-testid="system-scene" data-projection={planar ? 'plan' : '3d'}>
+ <Canvas {...background} frameloop={active ? 'demand' : 'never'} dpr={[1, 1.5]} gl={{ antialias: true, alpha: false, powerPreference: 'low-power' }}
+ role="img" aria-label={presentation === 'journey' ? 'Behavior call journey. Follow recorded invocations across component lanes. Double-click an operation to explore its calls.' : `System ${planar ? 'plan' : '3D map'}. Groups lie on a ground plane; expanded members sit above their group. Use the adjacent list to inspect source evidence.`}>
+ <color attach="background" args={['#0b1118']} />
+ <OrthographicCamera makeDefault position={[80, 115, 105]} zoom={4} near={0.1} far={10000} />
+ <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]} raycast={() => null} />
+ {(model.lanes ?? []).map(lane => <FolderBackplate key={lane.id} lane={lane} />)}
+ {showConnectionLoad && model.nodes.map(node => {
+ const load = loads.get(node.id)!;
+ if (!load.links || node.expanded) return null;
+ const position = center(node), size = dimensions(node);
+ const muted = !activeNode(model, node, activePath) || (neighborhood.size > 0 && !neighborhood.has(node.id));
+ return <mesh key={`load:${node.id}`} position={[position.x, position.y - size[1] / 2 - 0.1, position.z]}
+ rotation={[-Math.PI / 2, 0, 0]} scale={[size[0] * 0.56, size[2] * 0.62, 1]} raycast={() => null}>
+ <ringGeometry args={[1, Math.sqrt(1 + load.strength * 1.1), 48]} />
+ <meshBasicMaterial color="#91a6b4" transparent opacity={muted ? 0.025 : 0.08 + load.strength * 0.12} depthWrite={false} />
+ </mesh>;
+ })}
+ {model.edges.map(edge => {
+ const strands = edgeStrands.get(edge.id);
+ return strands ? <Connection key={edge.id} edge={edge} strands={strands}
+ selected={selectedEdge === edge.id} dimmed={!activeEdge(model, edge, activePath) || !focusedEdge(edge)}
+ emphasized={Boolean((model.highlightActive || neighborhood.size > 0) && activeEdge(model, edge, activePath) && focusedEdge(edge))}
+ onSelect={() => onSelectEdge(edge.id)} /> : null;
+ })}
+ <EdgePulseLayer paths={pulsePaths} active={active} />
+ {model.nodes.map(node => {
+ const selected = selectedNode === node.id, active = activeNode(model, node, activePath) && (!neighborhood.size || neighborhood.has(node.id)), size = dimensions(node);
+ const color = node.visual?.color ?? (node.kind === 'remainder' ? '#9c9a8b' : '#91a6b4');
+ const fill = new Color('#27333e').lerp(new Color(color), selected ? 0.34 : 0.2);
+ return <mesh key={node.id} position={center(node)} onClick={event => { event.stopPropagation(); onSelectNode(node.id); }}
+ onDoubleClick={onExpandNode && (node.group || presentation === 'journey') ? event => { event.stopPropagation(); onExpandNode(node.id); } : undefined}>
+ <boxGeometry args={size} />
+ <meshStandardMaterial color={fill} roughness={0.85} metalness={0.05} emissive={color} emissiveIntensity={selected ? 0.05 : 0.008}
+ transparent opacity={selected ? 0.6 : !active ? 0.045 : node.expanded ? 0.065 : node.parentId ? 0.36 : 0.28} depthWrite={false} />
+ <Edges color={selected ? '#f0f6fa' : color} transparent opacity={selected ? 0.95 : !active ? 0.12 : node.expanded ? 0.36 : 0.46} />
+ </mesh>;
+ })}
+ <NodeLabels model={model} selectedNode={selectedNode} highlightedPathIndex={activePath} onSelect={onSelectNode} onExpand={onExpandNode} loads={showConnectionLoad ? loads : undefined} presentation={presentation} />
+ <OrbitControls 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={90} rotateSpeed={0.5} zoomSpeed={0.8} maxPolarAngle={Math.PI / 2.05} />
+ <ScopeCamera model={model} resetKey={resetKey} planar={planar} presentation={presentation} />
+ </Canvas>
+ </div></SceneBoundary>;
+}
diff --git a/graph-ui/src/architecture/architecture-model.test.ts b/graph-ui/src/architecture/architecture-model.test.ts
index e1390e3bb..727d9d04d 100644
--- a/graph-ui/src/architecture/architecture-model.test.ts
+++ b/graph-ui/src/architecture/architecture-model.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import type { ArchitectureOverviewDto } from '../core/intelligence-provider';
import {
- boundaryMap, DEFAULT_ARCHITECTURE_CONFIG, matchingArchitecture,
+ ARCHITECTURE_VIEWS, boundaryMap, DEFAULT_ARCHITECTURE_CONFIG, matchingArchitecture,
readArchitectureConfig, saveArchitectureConfig,
} from './architecture-model';
@@ -30,6 +30,10 @@ function memoryStorage() {
}
describe('architecture workspace configuration', () => {
+ it('retains the repository views and adds separate system and behavior views', () => {
+ expect(ARCHITECTURE_VIEWS).toEqual(['overview', 'routes', 'hotspots', 'structure', 'behavior']);
+ });
+
it('restores the chosen view and filter for each project independently', () => {
const store = memoryStorage();
const config = { view: 'routes' as const, filter: '/users' };
@@ -38,8 +42,38 @@ describe('architecture workspace configuration', () => {
expect(readArchitectureConfig(store, 'other')).toEqual(DEFAULT_ARCHITECTURE_CONFIG);
});
+ it('restores legacy Dependencies preferences as Overview without losing the project filter', () => {
+ const store = memoryStorage();
+ store.setItem('atlas.architecture.v1:sample', JSON.stringify({
+ version: 1, view: 'dependencies', filter: 'src/api',
+ }));
+ expect(readArchitectureConfig(store, 'sample')).toEqual({ view: 'overview', filter: 'src/api' });
+ expect(readArchitectureConfig(store, 'other')).toEqual(DEFAULT_ARCHITECTURE_CONFIG);
+ });
+
+ it('writes the canonical view even when an older caller saves Dependencies', () => {
+ const store = memoryStorage();
+ expect(saveArchitectureConfig(store, 'sample', { view: 'dependencies', filter: 'storage' })).toBe(true);
+ expect(JSON.parse(store.getItem('atlas.architecture.v1:sample')!)).toEqual({
+ version: 1, view: 'overview', filter: 'storage',
+ });
+ expect(readArchitectureConfig(store, 'sample')).toEqual({ view: 'overview', filter: 'storage' });
+ });
+
+ it('preserves a saved Entry points mode and filter within Overview', () => {
+ const store = memoryStorage();
+ store.setItem('atlas.architecture.v1:sample', JSON.stringify({
+ version: 1, view: 'entryPoints', filter: 'start',
+ }));
+ const config = readArchitectureConfig(store, 'sample');
+ expect(config).toEqual({ view: 'entryPoints', filter: 'start' });
+ expect(saveArchitectureConfig(store, 'sample', config)).toBe(true);
+ expect(readArchitectureConfig(store, 'sample')).toEqual(config);
+ });
+
it('ignores malformed or unknown saved versions and never breaks exploration when storage is blocked', () => {
- for (const raw of ['{', 'null', '{"view":"admin","filter":true}', '{"version":2,"view":"routes","filter":"x"}']) {
+ for (const raw of ['{', 'null', '{"view":"admin","filter":true}', '{"version":2,"view":"routes","filter":"x"}',
+ '{"version":2,"view":"dependencies","filter":"x"}', '{"version":1,"view":"dependencies","filter":true}']) {
expect(readArchitectureConfig({ getItem: () => raw, setItem() {} }, 'sample')).toEqual(DEFAULT_ARCHITECTURE_CONFIG);
}
const blocked = { getItem(): never { throw new Error('blocked'); }, setItem(): never { throw new Error('blocked'); } };
diff --git a/graph-ui/src/architecture/architecture-model.ts b/graph-ui/src/architecture/architecture-model.ts
index b2dda7e61..d1f0c5c21 100644
--- a/graph-ui/src/architecture/architecture-model.ts
+++ b/graph-ui/src/architecture/architecture-model.ts
@@ -1,7 +1,8 @@
import type { ArchitectureBoundary, ArchitectureOverviewDto } from '../core/intelligence-provider';
-export const ARCHITECTURE_VIEWS = ['overview', 'dependencies', 'entryPoints', 'routes', 'hotspots'] as const;
-export type ArchitectureView = typeof ARCHITECTURE_VIEWS[number];
+export const ARCHITECTURE_VIEWS = ['overview', 'routes', 'hotspots', 'structure', 'behavior'] as const;
+/** Legacy Dependencies migrates to Overview; Entry points remains a mode within Overview. */
+export type ArchitectureView = typeof ARCHITECTURE_VIEWS[number] | 'dependencies' | 'entryPoints';
export interface ArchitectureConfig { view: ArchitectureView; filter: string }
export interface ConfigStorage { getItem(key: string): string | null; setItem(key: string, value: string): void }
export interface BoundaryMap { groups: string[]; boundaries: ArchitectureBoundary[]; omittedGroups: number }
@@ -18,11 +19,12 @@ export function readArchitectureConfig(storage: ConfigStorage | undefined, proje
const value: unknown = JSON.parse(raw);
if (value === null || typeof value !== 'object') return { ...DEFAULT_ARCHITECTURE_CONFIG };
const candidate = value as Record<string, unknown>;
+ const view = candidate.view === 'dependencies' ? 'overview' : candidate.view;
if (candidate.version !== 1 || typeof candidate.filter !== 'string'
- || !ARCHITECTURE_VIEWS.includes(candidate.view as ArchitectureView)) {
+ || (view !== 'entryPoints' && !ARCHITECTURE_VIEWS.includes(view as typeof ARCHITECTURE_VIEWS[number]))) {
return { ...DEFAULT_ARCHITECTURE_CONFIG };
}
- return { view: candidate.view as ArchitectureView, filter: candidate.filter };
+ return { view: view as ArchitectureView, filter: candidate.filter };
} catch {
return { ...DEFAULT_ARCHITECTURE_CONFIG };
}
@@ -31,7 +33,9 @@ export function readArchitectureConfig(storage: ConfigStorage | undefined, proje
export function saveArchitectureConfig(storage: ConfigStorage | undefined, project: string, config: ArchitectureConfig): boolean {
if (!storage || !project) return false;
try {
- storage.setItem(configKey(project), JSON.stringify({ version: 1, ...config }));
+ storage.setItem(configKey(project), JSON.stringify({
+ version: 1, ...config, view: config.view === 'dependencies' ? 'overview' : config.view,
+ }));
return true;
} catch {
return false;
diff --git a/graph-ui/src/architecture/architecture-scene.css b/graph-ui/src/architecture/architecture-scene.css
index 114f692da..3b96b51ed 100644
--- a/graph-ui/src/architecture/architecture-scene.css
+++ b/graph-ui/src/architecture/architecture-scene.css
@@ -11,6 +11,7 @@
.architecture-scene canvas { display: block; outline: none; touch-action: none; }
.architecture-scene button { font-family: inherit; }
+.architecture-folder-label { display: block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #91a4af; font: 10px/1.4 var(--atlas-mono, monospace); letter-spacing: 0.02em; text-shadow: 0 1px 5px #0b1118; }
.architecture-node-label {
display: flex;
@@ -34,10 +35,16 @@
.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.is-hidden { visibility: hidden; pointer-events: none; }
.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-title { display:flex; align-items:center; gap:7px; min-width:0; }
+.architecture-node-title strong { min-width:0; }
+.architecture-node-size { flex-shrink:0; color:#a5b5bf; font:9px/1.35 var(--atlas-mono, monospace); font-variant-numeric:tabular-nums; }
.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-metric { display:flex; align-items:center; gap:5px; color:#b4c5ce; font:10px/1.3 var(--atlas-mono, monospace); white-space:nowrap; }
+.architecture-node-metric i { width:6px; height:6px; border-radius:2px; flex-shrink:0; }
.architecture-node-label[data-kind="route"] { border-color: #735d40; }
.architecture-node-label[data-kind="symbol"] { border-color: #554d70; }
diff --git a/graph-ui/src/architecture/behavior-journey-model.test.ts b/graph-ui/src/architecture/behavior-journey-model.test.ts
new file mode 100644
index 000000000..24f511c4d
--- /dev/null
+++ b/graph-ui/src/architecture/behavior-journey-model.test.ts
@@ -0,0 +1,169 @@
+import { describe, expect, it } from 'vitest';
+import { behaviorJourney } from './behavior-journey-model';
+import type { SystemBehavior, SystemPath, SystemPathEdge, SystemProjection, SystemSymbol } from './system-architecture-source';
+
+const symbol = (id: number, component = 'app'): SystemSymbol => ({ id, name: `f${id}`, qualified_name: `app.f${id}`,
+ label: 'Function', component_id: component, file_path: `src/${component}.ts`, start_line: id + 1 });
+const edge = (id: number, source: number, target: number, type = 'CALLS'): SystemPathEdge => ({ id, source_id: source, target_id: target, type });
+const path = (ids: number[], base = 100): SystemPath => ({ entrypoint_id: ids[0], nodes: ids.map(id => symbol(id)),
+ edges: ids.slice(1).map((id, index) => edge(base + index, ids[index], id)) });
+const projection = (changes: Partial<SystemProjection> = {}): SystemProjection => ({ schema_version: 1, status: 'ready',
+ kind: 'static_projection', complete: true, components: [], dependencies: [], cycles: [], entrypoints: [symbol(1)],
+ paths: [], totals: {}, limits: {}, warnings: [], ...changes });
+const behavior = (nodes: SystemSymbol[], edges: SystemPathEdge[], changes: Partial<SystemBehavior> = {}): SystemBehavior => ({
+ mode: 'targets', source_id: 1, complete: true, limits_hit: [], reachable_targets: [], totals: {}, nodes, edges,
+ cycles: [], max_hops: 20, ...changes,
+});
+const drawnPairs = (data: ReturnType<typeof behaviorJourney>) => data.scene.edges.map(item => {
+ const nodes = new Map(data.scene.nodes.map(node => [node.id, node.symbol!.id]));
+ return [nodes.get(item.source), nodes.get(item.target)];
+});
+
+describe('focused Behavior journeys', () => {
+ it('shows direct branches at the same depth instead of connecting siblings in catalog order', () => {
+ const data = projection({ behavior: behavior([symbol(1), symbol(2), symbol(3)], [edge(10, 1, 2), edge(11, 1, 3)], {
+ reachable_targets: [{ ...symbol(3), distance: 1 }, { ...symbol(2), distance: 1 }, { ...symbol(9), distance: 4 }],
+ }) });
+ const result = behaviorJourney(data);
+ expect(result.mode).toBe('choices');
+ expect(drawnPairs(result)).toEqual([[1, 2], [1, 3]]);
+ expect(result.scene.nodes.slice(1).map(node => node.depth)).toEqual([1, 1]);
+ expect(result.scene.nodes.slice(1).map(node => node.position[0])).toEqual([88, 88]);
+ expect(result.scene.nodes.map(node => node.symbol!.id)).not.toContain(9);
+ expect(result.choices.find(choice => choice.id === 9)).toMatchObject({ direct: false, distance: 4 });
+ expect(result.scene.focusId).toBeUndefined();
+ });
+
+ it('uses exact-source witnesses and valid first hops but never aggregate counts or references', () => {
+ const data = projection({ paths: [path([1, 2, 8])], dependencies: [
+ { source: 'app', target: 'other', type: 'CALLS', count: 500, witnesses: [] },
+ { source: 'app', target: 'other', type: 'CALLS', count: 2, witnesses: [
+ { edge_id: 20, source: symbol(1), target: symbol(3), callsite: { file_path: 'src/app.ts', line: 8 } },
+ { edge_id: 21, source: symbol(99), target: symbol(4) },
+ ] },
+ { source: 'app', target: 'other', type: 'CALL_REFERENCE', count: 1, witnesses: [{ edge_id: 22, source: symbol(1), target: symbol(5) }] },
+ { source: 'app', target: 'other', type: 'IMPORTS', count: 1, witnesses: [{ edge_id: 23, source: symbol(1), target: symbol(6) }] },
+ ] });
+ const result = behaviorJourney(data);
+ expect(drawnPairs(result)).toEqual([[1, 2], [1, 3]]);
+ expect(result.scene.edges[1].pathEdge?.callsite).toEqual({ file_path: 'src/app.ts', line: 8 });
+ expect(result.scene.nodes.map(node => node.symbol!.id)).toEqual([1, 2, 3]);
+ });
+
+ it('admits only exact-source invocation witnesses from overview connections and keeps the fan stable', () => {
+ const connections = [
+ { source: 'aggregate-a', target: 'aggregate-b', type: 'ASYNC_CALLS', count: 50, witnesses: [
+ { edge_id: 20, source: symbol(1), target: symbol(3, 'worker') },
+ { edge_id: 21, source: symbol(7), target: symbol(8, 'worker') },
+ ] },
+ { source: 'aggregate-a', target: 'aggregate-c', type: 'CALLS', count: 20, witnesses: [
+ { edge_id: 22, source: symbol(1), target: symbol(2, 'store') },
+ ] },
+ ];
+ const data = projection({ overview: { complete: false, grouping_basis: 'common_source_directory_aggregate',
+ groups: [], components: [], connections, totals: {}, limits: {} } });
+ const result = behaviorJourney(data);
+ expect(result.scene.nodes.map(node => node.symbol!.id)).toEqual([1, 2, 3]);
+ expect(result.scene.edges.map(item => item.type)).toEqual(['ASYNC_CALLS', 'CALLS']);
+ expect(result.scene.nodes.some(node => node.symbol!.id === 8)).toBe(false);
+ expect(result.limits.sampled).toBe(true);
+ const reordered = behaviorJourney({ ...data, overview: { ...data.overview!, connections: [...connections].reverse() } });
+ expect(reordered.scene.nodes).toEqual(result.scene.nodes);
+ expect(reordered.scene.scopeKey).toBe(result.scene.scopeKey);
+ });
+
+ it('selects one complete path for the exact entry and target while preserving input order', () => {
+ const first = path([1, 2, 5]), second = path([1, 3, 5], 200);
+ second.nodes[1] = symbol(3, 'store');
+ const data = projection({ paths: [first, path([7, 3, 5]), path([1, 3, 6]), second],
+ components: [{ id: 'store', label: 'Storage', basis: 'declared_module', member_count: 10, file_count: 2, representatives: [] }] });
+ const result = behaviorJourney(data, { entryId: 1, targetId: 5, pathIndex: 1 });
+ expect(result.paths).toEqual([first, second]); expect(result.path).toBe(second); expect(result.mode).toBe('path');
+ expect(drawnPairs(result)).toEqual([[1, 3], [3, 5]]);
+ expect(result.scene.nodes.map(node => node.depth)).toEqual([0, 1, 2]);
+ expect(result.scene.nodes.map(node => node.label)).toEqual(['1. f1', '2. f3', '3. f5']);
+ expect(result.scene.nodes.map(node => node.position[0])).toEqual([0, 72, 144]);
+ expect(result.scene.nodes.every(node => Math.abs(node.position[2]) < 2)).toBe(true);
+ expect(result.scene.lanes.map(lane => lane.label)).toContain('Storage');
+ expect(result.scene.edges.map(item => item.pathEdge)).toEqual(second.edges);
+ expect(result.scene.focusId).toBeUndefined();
+ });
+
+ it('rejects jumps, missing hops, mismatched entry IDs and non-invocation path edges', () => {
+ const jump = path([1, 2, 3]); jump.edges[1] = edge(101, 9, 3);
+ const missing = path([1, 3]); missing.edges = [];
+ const wrongEntry = path([2, 3]); wrongEntry.entrypoint_id = 1;
+ const reference = path([1, 3]); reference.edges[0].type = 'CALL_REFERENCE';
+ const result = behaviorJourney(projection({ paths: [jump, missing, wrongEntry, reference] }), { entryId: 1, targetId: 3 });
+ expect(result.mode).toBe('empty'); expect(result.path).toBeUndefined();
+ expect(result.scene.edges).toEqual([]); expect(result.counts.invalidPaths).toBe(4);
+ });
+
+ it('finds a shortest corridor path with stable evidence-order ties and terminates on cycles', () => {
+ const edges = [edge(1, 1, 2), edge(2, 1, 3), edge(3, 2, 1), edge(4, 2, 5), edge(5, 3, 5)];
+ const data = projection({ behavior: behavior([1, 2, 3, 5].map(id => symbol(id)), edges, { mode: 'corridor', target_id: 5 }) });
+ const result = behaviorJourney(data, { entryId: 1, targetId: 5 });
+ expect(result.mode).toBe('corridor'); expect(drawnPairs(result)).toEqual([[1, 2], [2, 5]]);
+ expect(result.path?.edges.map(item => item.id)).toEqual([1, 4]);
+ expect(behaviorJourney({ ...data, behavior: { ...data.behavior!, edges: [...edges].reverse() } }, { targetId: 5 }).path).toEqual(result.path);
+ expect(behaviorJourney(data, { entryId: 1, targetId: 99 }).mode).toBe('empty');
+ expect(behaviorJourney(data, { entryId: 2, targetId: 5 }).mode).toBe('empty');
+ });
+
+ it('does not bridge two witnesses that merely share a component or a catalog distance', () => {
+ const data = projection({ behavior: behavior([1, 2, 3, 4].map(id => symbol(id)), [edge(1, 1, 2), edge(2, 3, 4)], {
+ mode: 'corridor', target_id: 4, reachable_targets: [{ ...symbol(4), distance: 2 }],
+ }) });
+ const result = behaviorJourney(data, { targetId: 4 });
+ expect(result.mode).toBe('empty'); expect(result.paths).toEqual([]); expect(result.scene.edges).toEqual([]);
+ });
+
+ it('keeps separate numbered occurrences when an explicit recorded path revisits a symbol', () => {
+ const result = behaviorJourney(projection({ paths: [path([1, 2, 1, 3])] }), { targetId: 3 });
+ expect(result.scene.nodes.map(node => node.symbol!.id)).toEqual([1, 2, 1, 3]);
+ expect(new Set(result.scene.nodes.map(node => node.id)).size).toBe(4);
+ expect(drawnPairs(result)).toEqual([[1, 2], [2, 1], [1, 3]]);
+ });
+
+ it('filters complete paths while retaining every connecting hop', () => {
+ const result = behaviorJourney(projection({ paths: [path([1, 2, 5]), path([1, 3, 5], 200)] }), { targetId: 5, filter: 'f2' });
+ expect(result.paths).toHaveLength(1); expect(result.counts.filteredPaths).toBe(1);
+ expect(result.scene.nodes.map(node => node.symbol!.id)).toEqual([1, 2, 5]);
+ expect(drawnPairs(result)).toEqual([[1, 2], [2, 5]]);
+ expect(behaviorJourney(projection({ paths: [path([1, 2, 5])] }), { targetId: 5, filter: 'absent' }).mode).toBe('empty');
+ });
+
+ it('bounds a direct fan while reserving a real edge for every displayed callee', () => {
+ const targets = Array.from({ length: 20 }, (_, index) => ({ ...symbol(index + 2), name: `target${String(index).padStart(2, '0')}` }));
+ const edges = [...Array.from({ length: 130 }, (_, index) => edge(index, 1, 2)),
+ ...targets.slice(1).map((target, index) => edge(200 + index, 1, target.id))];
+ const data = projection({ behavior: behavior([symbol(1), ...targets], edges, {
+ complete: false, limits_hit: ['server-node-cap'], reachable_targets: targets.map(target => ({ ...target, distance: 1 })),
+ }) });
+ const result = behaviorJourney(data);
+ expect(result.scene.nodes).toHaveLength(13); expect(result.scene.edges).toHaveLength(120);
+ expect(result.choices.filter(choice => choice.direct)).toHaveLength(12);
+ const connected = new Set(result.scene.edges.map(item => item.target));
+ expect(result.scene.nodes.slice(1).every(node => connected.has(node.id))).toBe(true);
+ expect(result.counts.omittedNodes).toBe(8); expect(result.counts.omittedChoices).toBe(8);
+ expect(result.counts.omittedEdges).toBe(edges.length - 120);
+ expect(result.limits.sampled).toBe(true);
+ expect(result.limits.hit).toEqual(expect.arrayContaining(['server-node-cap', 'direct-choices', 'direct-edges']));
+ });
+
+ it('omits an oversized whole path instead of truncating it into a claim that reaches the target', () => {
+ const large = path(Array.from({ length: 61 }, (_, index) => index + 1));
+ const result = behaviorJourney(projection({ paths: [large] }), { targetId: 61 });
+ expect(result.mode).toBe('empty'); expect(result.path).toBeUndefined(); expect(result.scene.nodes).toEqual([]);
+ expect(result.counts.omittedNodes).toBe(61); expect(result.counts.omittedEdges).toBe(60);
+ expect(result.limits.hit).toContain('whole-path-size');
+ });
+
+ it('caps corridor exploration without deriving shortcuts from unreachable catalog rows', () => {
+ const nodes = Array.from({ length: 70 }, (_, index) => symbol(index + 1));
+ const edges = nodes.slice(1).map((target, index) => edge(index, nodes[index].id, target.id));
+ const result = behaviorJourney(projection({ behavior: behavior(nodes, edges, { mode: 'corridor', target_id: 70 }) }), { targetId: 70 });
+ expect(result.mode).toBe('empty'); expect(result.scene.nodes.length).toBeLessThanOrEqual(60);
+ expect(result.limits.hit).toContain('corridor-node-search'); expect(result.limits.sampled).toBe(true);
+ });
+});
diff --git a/graph-ui/src/architecture/behavior-journey-model.ts b/graph-ui/src/architecture/behavior-journey-model.ts
new file mode 100644
index 000000000..1597a8787
--- /dev/null
+++ b/graph-ui/src/architecture/behavior-journey-model.ts
@@ -0,0 +1,222 @@
+import type { SystemSceneModel, SystemSceneNode } from './system-architecture-model';
+import type { SystemPath, SystemPathEdge, SystemProjection, SystemSymbol } from './system-architecture-source';
+
+export interface BehaviorJourneyOptions {
+ entryId?: number; targetId?: number; pathIndex?: number; filter?: string;
+}
+export interface BehaviorJourneyChoice extends SystemSymbol { distance?: number; direct: boolean }
+export interface BehaviorJourney {
+ scene: SystemSceneModel; paths: SystemPath[]; path?: SystemPath; entry?: SystemSymbol;
+ mode: 'choices' | 'path' | 'corridor' | 'empty'; choices: BehaviorJourneyChoice[];
+ counts: {
+ directChoices: number; reachableTargets: number; validPaths: number; invalidPaths: number;
+ filteredPaths: number; omittedChoices: number; omittedNodes: number; omittedEdges: number;
+ };
+ limits: { maxChoices: number; maxNodes: number; maxEdges: number; hit: string[]; sampled: boolean };
+}
+
+const MAX_CHOICES = 12, MAX_NODES = 60, MAX_EDGES = 120;
+const INVOCATIONS = new Set(['CALLS', 'HTTP_CALLS', 'ASYNC_CALLS', 'GRPC_CALLS', 'GRAPHQL_CALLS', 'TRPC_CALLS',
+ 'CROSS_HTTP_CALLS', 'CROSS_ASYNC_CALLS', 'CROSS_GRPC_CALLS', 'CROSS_GRAPHQL_CALLS', 'CROSS_TRPC_CALLS']);
+const invocation = (edge: { type: string }) => INVOCATIONS.has(edge.type.trim().replaceAll('-', '_').toUpperCase());
+const edgeKey = (edge: SystemPathEdge) => JSON.stringify([edge.id, edge.source_id, edge.target_id, edge.type]);
+const compareText = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
+
+/** Every consecutive hop must have its own invocation witness, including repeated symbols. */
+function validPath(path: SystemPath): boolean {
+ return path.nodes.length > 0 && path.entrypoint_id === path.nodes[0].id && path.edges.length === path.nodes.length - 1
+ && path.edges.every((edge, index) => invocation(edge)
+ && edge.source_id === path.nodes[index].id && edge.target_id === path.nodes[index + 1].id);
+}
+
+function laneLayout(data: SystemProjection, nodes: SystemSceneNode[]): SystemSceneModel['lanes'] {
+ const labels = new Map([...data.components, ...(data.overview?.components ?? [])].map(component => [component.id, component.label]));
+ const groups = new Map<string, SystemSceneNode[]>();
+ for (const node of nodes) {
+ const component = node.symbol!.component_id;
+ if (!groups.has(component)) groups.set(component, []);
+ groups.get(component)!.push(node);
+ }
+ return [...groups].map(([id, members]) => {
+ const xs = members.map(node => node.position[0]), ys = members.map(node => node.position[1]);
+ const left = Math.min(...xs), right = Math.max(...xs), bottom = Math.min(...ys), top = Math.max(...ys);
+ return { id: `journey-component:${id}`, label: labels.get(id) ?? id,
+ position: [(left + right) / 2, (bottom + top) / 2, -2] as [number, number, number],
+ width: right - left + 62, height: top - bottom + 32, depth: 0.4 };
+ });
+}
+
+function pathScene(data: SystemProjection, path: SystemPath, index: number): SystemSceneModel {
+ const components = [...new Set(path.nodes.map(symbol => symbol.component_id))];
+ const nodes: SystemSceneNode[] = path.nodes.map((symbol, depth) => {
+ const lane = components.indexOf(symbol.component_id);
+ return { id: `journey:${path.entrypoint_id}:${depth}:${symbol.id}`, label: `${depth + 1}. ${symbol.name}`,
+ symbol, detail: symbol.file_path ?? symbol.qualified_name, depth, pathIndices: [index],
+ handoff: depth > 0 && path.nodes[depth - 1].component_id !== symbol.component_id,
+ size: [48, 18, 3], position: [depth * 72, (lane - (components.length - 1) / 2) * 34, lane % 3 * 0.45] };
+ });
+ const edges = path.edges.map((edge, depth) => ({ id: `journey-edge:${depth}:${edgeKey(edge)}`,
+ source: nodes[depth].id, target: nodes[depth + 1].id, type: edge.type, count: 1,
+ pathEdge: edge, pathIndices: [index], depth: depth + 1, handoff: nodes[depth + 1].handoff }));
+ return { nodes, edges, lanes: laneLayout(data, nodes), omittedNodes: 0, omittedEdges: 0,
+ preferredPathIndex: index, scopeKey: `journey:path:${path.entrypoint_id}:${path.edges.map(edgeKey).join('|')}` };
+}
+
+/** Breadth-first traversal visits each symbol once and never joins component representatives. */
+function corridorPath(data: SystemProjection, source: number, target: number, hit: Set<string>): SystemPath | undefined {
+ const behavior = data.behavior;
+ if (!behavior || behavior.mode !== 'corridor' || behavior.source_id !== source || behavior.target_id !== target) return undefined;
+ const symbols = new Map(behavior.nodes.map(symbol => [symbol.id, symbol]));
+ if (!symbols.has(source) || !symbols.has(target)) return undefined;
+ const adjacent = new Map<number, SystemPathEdge[]>();
+ for (const edge of behavior.edges) if (invocation(edge) && symbols.has(edge.source_id) && symbols.has(edge.target_id)) {
+ if (!adjacent.has(edge.source_id)) adjacent.set(edge.source_id, []);
+ adjacent.get(edge.source_id)!.push(edge);
+ }
+ for (const outgoing of adjacent.values()) outgoing.sort((a, b) => compareText(a.callsite?.file_path ?? '', b.callsite?.file_path ?? '')
+ || (a.callsite?.line ?? 0) - (b.callsite?.line ?? 0) || a.id - b.id
+ || a.target_id - b.target_id || compareText(a.type, b.type));
+ const queue = [source], seen = new Set(queue), previous = new Map<number, SystemPathEdge>();
+ let visitedEdges = 0;
+ for (let at = 0; at < queue.length && !seen.has(target); at++) {
+ for (const edge of adjacent.get(queue[at]) ?? []) {
+ if (visitedEdges >= MAX_EDGES) { hit.add('corridor-edge-search'); break; }
+ visitedEdges++;
+ if (seen.has(edge.target_id)) continue;
+ if (seen.size >= MAX_NODES) { hit.add('corridor-node-search'); continue; }
+ seen.add(edge.target_id); previous.set(edge.target_id, edge); queue.push(edge.target_id);
+ if (edge.target_id === target) break;
+ }
+ if (visitedEdges >= MAX_EDGES) break;
+ }
+ if (!seen.has(target)) return undefined;
+ const nodes = [symbols.get(target)!], edges: SystemPathEdge[] = [];
+ let current = target;
+ while (current !== source) {
+ const edge = previous.get(current)!;
+ edges.push(edge); current = edge.source_id; nodes.push(symbols.get(current)!);
+ }
+ return { entrypoint_id: source, nodes: nodes.reverse(), edges: edges.reverse() };
+}
+
+/** A focused static journey: positions describe hops, never catalog distance or runtime order. */
+export function behaviorJourney(data: SystemProjection, options: BehaviorJourneyOptions = {}): BehaviorJourney {
+ const entryId = options.entryId ?? data.behavior?.source_id ?? data.entrypoints[0]?.id
+ ?? data.paths.find(validPath)?.entrypoint_id;
+ const scopedBehavior = data.behavior?.source_id === entryId ? data.behavior : undefined;
+ const dependencies = [...data.dependencies, ...(data.overview?.connections ?? [])];
+ const symbols = new Map<number, SystemSymbol>();
+ const add = (symbol: SystemSymbol) => { if (!symbols.has(symbol.id)) symbols.set(symbol.id, symbol); };
+ data.entrypoints.forEach(add);
+ scopedBehavior?.nodes.forEach(add);
+ const scopedPaths = data.paths.filter(path => path.entrypoint_id === entryId);
+ const valid = scopedPaths.filter(validPath);
+ valid.forEach(path => path.nodes.forEach(add));
+ let sampledWitnesses = false;
+ for (const dependency of dependencies) for (const witness of dependency.witnesses) {
+ if (invocation(dependency) && witness.source.id === entryId) {
+ add(witness.source); add(witness.target);
+ sampledWitnesses ||= dependency.count > dependency.witnesses.length;
+ }
+ }
+ const entry = entryId === undefined ? undefined : symbols.get(entryId);
+ const hit = new Set(scopedBehavior?.limits_hit ?? []);
+ const result: BehaviorJourney = {
+ scene: { nodes: [], edges: [], lanes: [], omittedNodes: 0, omittedEdges: 0, scopeKey: `journey:empty:${entryId ?? ''}:${options.targetId ?? ''}` },
+ paths: [], entry, mode: 'empty', choices: [],
+ counts: { directChoices: 0, reachableTargets: scopedBehavior?.reachable_targets.length ?? 0,
+ validPaths: 0, invalidPaths: scopedPaths.length - valid.length, filteredPaths: 0,
+ omittedChoices: 0, omittedNodes: 0, omittedEdges: 0 },
+ limits: { maxChoices: MAX_CHOICES, maxNodes: MAX_NODES, maxEdges: MAX_EDGES,
+ hit: [], sampled: !data.complete || data.status === 'limited' || scopedBehavior?.complete === false
+ || scopedBehavior?.corridor_complete === false || (options.targetId === undefined && (sampledWitnesses || data.overview?.complete === false)) },
+ };
+ const finish = (): BehaviorJourney => {
+ result.limits.hit = [...hit];
+ result.limits.sampled ||= hit.size > 0 || result.counts.omittedNodes > 0 || result.counts.omittedEdges > 0 || result.counts.omittedChoices > 0;
+ result.scene.omittedNodes = result.counts.omittedNodes;
+ result.scene.omittedEdges = result.counts.omittedEdges;
+ return result;
+ };
+ if (!entry) return finish();
+ const query = options.filter?.trim().toLocaleLowerCase() ?? '';
+ const labels = new Map([...data.components, ...(data.overview?.components ?? [])].map(component => [component.id, component.label]));
+ const matches = (symbol: SystemSymbol) => !query || [symbol.name, symbol.qualified_name, symbol.file_path ?? '', labels.get(symbol.component_id) ?? '']
+ .some(value => value.toLocaleLowerCase().includes(query));
+
+ if (options.targetId !== undefined) {
+ let paths = valid.filter(path => path.nodes.at(-1)!.id === options.targetId);
+ let derived = false;
+ if (!paths.length) {
+ const path = corridorPath(data, entry.id, options.targetId, hit);
+ if (path) { paths = [path]; derived = true; }
+ }
+ result.counts.validPaths = paths.length;
+ for (const path of paths) {
+ if (!path.nodes.some(matches)) { result.counts.filteredPaths++; continue; }
+ if (path.nodes.length > MAX_NODES || path.edges.length > MAX_EDGES) {
+ result.counts.omittedNodes += path.nodes.length; result.counts.omittedEdges += path.edges.length;
+ hit.add('whole-path-size'); continue;
+ }
+ result.paths.push(path);
+ }
+ const index = options.pathIndex !== undefined && Number.isInteger(options.pathIndex) && options.pathIndex >= 0 && options.pathIndex < result.paths.length ? options.pathIndex : 0;
+ result.path = result.paths[index];
+ if (result.path) { result.mode = derived ? 'corridor' : 'path'; result.scene = pathScene(data, result.path, index); }
+ return finish();
+ }
+
+ const direct = new Map<string, SystemPathEdge>();
+ const recordDirect = (edge: SystemPathEdge) => {
+ if (edge.source_id === entry.id && invocation(edge) && symbols.has(edge.target_id)) direct.set(edgeKey(edge), edge);
+ };
+ scopedBehavior?.edges.forEach(recordDirect);
+ valid.forEach(path => { if (path.edges[0]) recordDirect(path.edges[0]); });
+ for (const dependency of dependencies) if (invocation(dependency)) {
+ for (const witness of dependency.witnesses) if (witness.source.id === entry.id) recordDirect({
+ ...witness, id: witness.edge_id, source_id: witness.source.id, target_id: witness.target.id, type: dependency.type,
+ callsite: witness.callsite, resolution: witness.resolution,
+ });
+ }
+ const callees = [...new Set([...direct.values()].map(edge => edge.target_id))].map(id => symbols.get(id)!)
+ .sort((a, b) => compareText(a.file_path ?? '', b.file_path ?? '') || compareText(a.name, b.name) || a.id - b.id);
+ result.counts.directChoices = callees.length;
+ const candidates = callees.filter(symbol => matches(entry) || matches(symbol));
+ const shown = candidates.slice(0, MAX_CHOICES), shownIds = new Set(shown.map(symbol => symbol.id));
+ if (candidates.length > shown.length) hit.add('direct-choices');
+ result.choices = shown.map(symbol => ({ ...symbol, distance: 1, direct: true }));
+ const calleeIds = new Set(callees.map(symbol => symbol.id));
+ const catalog = new Map<number, BehaviorJourneyChoice>();
+ for (const target of scopedBehavior?.reachable_targets ?? []) if (matches(target) && !calleeIds.has(target.id)) {
+ catalog.set(target.id, { ...target, direct: false });
+ }
+ // Older projections expose sampled paths without a separate destination catalog.
+ if (!scopedBehavior) for (const path of valid) for (let depth = 1; depth < path.nodes.length; depth++) {
+ const target = path.nodes[depth];
+ if (target.id !== entry.id && !calleeIds.has(target.id) && matches(target) && !catalog.has(target.id))
+ catalog.set(target.id, { ...target, distance: depth, direct: false });
+ }
+ result.choices.push(...[...catalog.values()].slice(0, MAX_NODES - result.choices.length));
+ result.counts.omittedChoices = new Set([...candidates.map(symbol => symbol.id), ...catalog.keys()]).size - result.choices.length;
+ if (result.counts.omittedChoices > 0) hit.add('target-choices');
+ const visible = [entry, ...shown.filter(symbol => symbol.id !== entry.id)];
+ const nodes: SystemSceneNode[] = visible.map((symbol, index) => ({ id: `journey-choice:${symbol.id}`, label: symbol.name,
+ symbol, detail: symbol.file_path ?? symbol.qualified_name, depth: index === 0 ? 0 : 1,
+ size: [48, 18, 3], position: index === 0 ? [0, 0, 0] : [88, (index - 1 - (visible.length - 2) / 2) * 28, 0] }));
+ const ids = new Set(visible.map(symbol => symbol.id));
+ const eligibleEdges = [...direct.values()].filter(edge => ids.has(edge.target_id));
+ // Reserve one witness per visible branch before admitting parallel callsites.
+ const admitted = new Set<string>(), connected = new Set<number>();
+ for (const edge of eligibleEdges) if (!connected.has(edge.target_id)) { admitted.add(edgeKey(edge)); connected.add(edge.target_id); }
+ for (const edge of eligibleEdges) { if (admitted.size >= MAX_EDGES) break; admitted.add(edgeKey(edge)); }
+ const edges = eligibleEdges.filter(edge => admitted.has(edgeKey(edge))).map(edge => ({ id: `journey-choice-edge:${edgeKey(edge)}`,
+ source: `journey-choice:${entry.id}`, target: `journey-choice:${edge.target_id}`, type: edge.type, count: 1,
+ pathEdge: edge, depth: 1, handoff: symbols.get(edge.target_id)!.component_id !== entry.component_id }));
+ result.counts.omittedNodes = candidates.filter(symbol => symbol.id !== entry.id && !shownIds.has(symbol.id)).length;
+ result.counts.omittedEdges = [...direct.values()].filter(edge => matches(entry) || matches(symbols.get(edge.target_id)!)).length - edges.length;
+ if (eligibleEdges.length > edges.length) hit.add('direct-edges');
+ result.mode = 'choices';
+ result.scene = { nodes, edges, lanes: laneLayout(data, nodes), omittedNodes: 0, omittedEdges: 0,
+ scopeKey: `journey:choices:${entry.id}:${nodes.map(node => node.id).join('|')}` };
+ return finish();
+}
diff --git a/graph-ui/src/architecture/behavior-journey.css b/graph-ui/src/architecture/behavior-journey.css
new file mode 100644
index 000000000..4b5fce2e1
--- /dev/null
+++ b/graph-ui/src/architecture/behavior-journey.css
@@ -0,0 +1,72 @@
+.behavior-journey { --journey-line: #8ca5bc29; font-family: var(--atlas-ui-font, system-ui, sans-serif); }
+.behavior-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 20px; margin: 18px 0; }
+.behavior-heading h2 { font-size: 25px; font-weight: 500; letter-spacing: -.6px; margin: 7px 0; overflow-wrap: anywhere; }
+.behavior-heading p { color: var(--atlas-dim); font-size: 12px; margin: 0; }
+.behavior-journey button { cursor: pointer; }
+.behavior-heading > button, .behavior-navigation > button, .behavior-inspector-actions button, .behavior-walk button, .behavior-visual-toolbar > button, .behavior-source-heading button { background: #9bb5ca09; color: #becbd7; border: 1px solid var(--journey-line); border-radius: 6px; padding: 6px 10px; font: inherit; font-size: 11px; }
+.behavior-journey button:disabled { opacity: .35; cursor: default; }
+.behavior-journey button:focus-visible { outline: 2px solid #8eadce; outline-offset: 3px; }
+.behavior-requests { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 12px; border: 1px solid var(--journey-line); border-radius: 10px; background: #91a8c106; }
+.behavior-requests label { display: flex; align-items: center; gap: 10px; font-size: 11px; color: var(--atlas-dim); flex: 1 1 270px; min-width: 0; }
+.behavior-requests select { min-width: 0; width: 100%; max-width: 100%; }
+.behavior-requests input { flex: 1 1 150px; min-width: 120px; background: transparent; color: var(--atlas-fg); border: 1px solid var(--journey-line); border-radius: 5px; padding: 6px 9px; font: inherit; font-size: 11px; }
+.behavior-navigation { display: flex; align-items: center; flex-wrap: wrap; gap: 9px; margin: 12px 0; font-size: 11px; color: var(--atlas-dim); }
+.behavior-navigation > span:first-of-type { margin-left: 4px; }
+.behavior-static-badge { margin-left: auto; border: 1px solid #91a6bb25; border-radius: 20px; padding: 4px 9px; font-size: 10px; }
+.behavior-stage { display: grid; grid-template-columns: minmax(0, 1fr) 310px; border: 1px solid var(--journey-line); border-radius: 12px; overflow: hidden; background: #0b1118; }
+.behavior-visual { min-width: 0; }
+.behavior-visual-toolbar { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-bottom: 1px solid var(--journey-line); color: #9baec1; font-size: 10px; }
+.behavior-visual-toolbar > span { margin-right: auto; letter-spacing: 1.4px; }
+.system-architecture.behavior-journey .behavior-map { height: clamp(410px, calc(100dvh - 400px), 680px); }
+.behavior-journey .system-map-caption { gap: 5px; font-size: 10px; }
+.behavior-inspector { min-width: 0; border-left: 1px solid var(--journey-line); padding: 18px; max-height: clamp(500px, calc(100dvh - 320px), 790px); overflow: auto; background: #101820; }
+.behavior-inspector h3 { overflow-wrap: anywhere; font-size: 19px; font-weight: 500; line-height: 1.25; margin: 12px 0; }
+.behavior-inspector > p { color: #99aabd; font-size: 11px; overflow-wrap: anywhere; line-height: 1.6; }
+.behavior-call-arrow { display: block; color: #7399b1; font-size: 16px; margin: 6px 0; }
+.behavior-inspector-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 16px 0; }
+.behavior-resolution { font-size: 10px !important; }
+.behavior-contract section { padding: 12px 0; border-top: 1px solid var(--journey-line); }
+.behavior-contract h4 { margin: 0 0 8px; font-size: 11px; font-weight: 500; color: #b4c9dc; }
+.behavior-contract code { font-size: 10px; white-space: pre-wrap; overflow-wrap: anywhere; color: #d0deeb; }
+.behavior-contract ol, .behavior-contract ul { padding-left: 18px; margin: 6px 0; }
+.behavior-contract li { margin: 6px 0; color: #8298ac; font-size: 10px; }
+.behavior-contract small { display: block; margin-top: 5px; font-size: 9px; line-height: 1.5; color: #7e96ac; }
+.behavior-signature { display: block; padding: 8px; border-radius: 5px; background: #0b1219; }
+.behavior-source { border-top: 1px solid var(--journey-line); padding-top: 14px; margin-top: 16px; }
+.behavior-source-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
+.behavior-source h4, .behavior-immediate-list h4 { font-size: 11px; font-weight: 500; margin: 0; }
+.behavior-source-heading button { padding: 4px 6px; font-size: 10px; }
+.behavior-source-location { color: #91a5b9; font-size: 10px; overflow-wrap: anywhere; margin: 8px 0; }
+.behavior-source pre { max-height: 255px; overflow: auto; background: #080f17; border-radius: 7px; padding: 10px 0; font-size: 10px; line-height: 1.7; color: #bdcbd9; tab-size: 4; }
+.behavior-source code > span { display: block; white-space: pre; min-width: max-content; padding-right: 12px; }
+.behavior-source code i { display: inline-block; width: 34px; padding-right: 8px; font-style: normal; color: #5f758b; text-align: right; user-select: none; }
+.behavior-source code > span[data-selected=true] { background: #638db328; box-shadow: inset 2px 0 #7ca1bf; color: #ecf3fa; }
+.behavior-source > small { font-size: 9px; color: #8b9db0; line-height: 1.5; display: block; }
+.behavior-source > p[role=status] { font-size: 11px; color: #b4a999; }
+.behavior-walk { display: flex; align-items: center; gap: 12px; border-top: 1px solid var(--journey-line); padding: 12px 14px; color: #9baec1; font-size: 11px; }
+.behavior-walk input { min-width: 40px; flex: 1; accent-color: #8caec7; }
+.behavior-paths { display: flex; overflow-x: auto; gap: 7px; margin: 12px 0; }
+.behavior-paths button { display: grid; gap: 4px; background: #94b6d20a; border: 1px solid var(--journey-line); border-radius: 7px; padding: 8px 12px; color: #b8cadb; font: inherit; font-size: 11px; white-space: nowrap; }
+.behavior-paths button small { color: #8198ae; font-size: 10px; }
+.behavior-paths button[aria-pressed=true] { border-color: #8bacce94; background: #719ec51a; }
+.behavior-operation-strip { display: flex; gap: 7px; overflow-x: auto; list-style: none; padding: 14px 0; margin: 0; }
+.behavior-operation-strip li { flex: 0 0 170px; }
+.behavior-operation-strip button { display: grid; width: 100%; grid-template-columns: 20px minmax(0, 1fr); gap: 5px 8px; text-align: left; border: 1px solid var(--journey-line); border-radius: 8px; padding: 10px; background: #91a9c006; color: #a8bace; font: inherit; font-size: 11px; }
+.behavior-operation-strip button > span { grid-row: span 2; color: #6e95b7; }
+.behavior-operation-strip strong { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.behavior-operation-strip small { font-size: 9px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #7d96ae; }
+.behavior-operation-strip button[aria-pressed=true] { border-color: #88abc780; background: #719ec51a; color: #e0ebf7; }
+.behavior-limits { border-top: 1px solid var(--journey-line); padding: 14px 0; color: #91a5b9; font-size: 11px; }
+.behavior-limits summary { cursor: pointer; }
+.behavior-limits p { max-width: 950px; }
+.behavior-next-operation, .behavior-immediate-list { margin-top: 18px; border-top: 1px solid var(--journey-line); padding-top: 14px; }
+.behavior-next-operation > span { color: #839eb8; font-size: 10px; display: block; margin-bottom: 6px; }
+.behavior-next-operation button, .behavior-immediate-list button { background: transparent; border: 0; color: #b5cee4; padding: 6px 0; text-align: left; font: inherit; font-size: 11px; overflow-wrap: anywhere; }
+.behavior-immediate-list button { display: flex; align-items: center; gap: 12px; width: 100%; border-bottom: 1px solid #91a6bb12; }
+.behavior-immediate-list small { margin-left: auto; color: #849aaf; font-size: 9px; white-space: nowrap; }
+.behavior-loading { min-height: 310px; display: flex; align-items: center; justify-content: center; color: #829bb2; font-size: 12px; padding: 25px; text-align: center; }
+.system-architecture .system-scene .system-scene-node-label[data-presentation=journey] { width: 116px; height: 58px; gap: 3px; padding: 7px; background: #14212ef2; border-radius: 8px; }
+.system-architecture .system-scene .system-scene-node-label[data-presentation=journey] small { font-size: 8px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
+.system-architecture .system-scene .system-scene-node-label[data-presentation=journey] strong { font-size: 10px; }
+@media (max-width: 1000px) { .behavior-stage { grid-template-columns: minmax(0, 1fr) 280px; } .behavior-inspector { padding: 14px; } }
+@media (max-width: 760px) { .behavior-stage { grid-template-columns: minmax(0, 1fr); } .behavior-inspector { border-left: 0; border-top: 1px solid var(--journey-line); max-height: 420px; } .behavior-heading h2 { font-size: 20px; } .behavior-requests label { flex-basis: 100%; } .behavior-walk { gap: 8px; } }
diff --git a/graph-ui/src/architecture/container-layout.test.ts b/graph-ui/src/architecture/container-layout.test.ts
new file mode 100644
index 000000000..cdcf6e86a
--- /dev/null
+++ b/graph-ui/src/architecture/container-layout.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest';
+import { layoutContainers } from './container-layout';
+import type { ContainerTopology } from './container-topology';
+import type { SemanticGraph } from './semantic-graph';
+const topology = (): ContainerTopology => ({ services: ['frontend', 'worker', 'db', 'isolated'].map(id => ({
+ id, name: id, project: 'p', manifest: 'compose.yml', line: 1, sourcePaths: [], networks: [], ports: [],
+})), connections: [
+ { id: '1', source: 'frontend', target: 'worker', kind: 'call', protocol: 'http', evidence: [] },
+ { id: '2', source: 'worker', target: 'db', kind: 'call', protocol: 'postgres', evidence: [] },
+], warnings: [], unresolved: [] });
+const serviceMap = (count: number): ContainerTopology => ({ ...topology(), connections: [],
+ services: Array.from({ length: count }, (_, index) => {
+ const id = `service-${String(index).padStart(3, '0')}`;
+ return { ...topology().services[0], id, name: id };
+ }),
+});
+const connect = (source: string, target: string): ContainerTopology['connections'][number] => ({
+ id: `${source}->${target}`, source, target, kind: 'call', protocol: 'http', evidence: [],
+});
+function expectSeparatedSquares(graph: SemanticGraph) {
+ for (const [index, node] of graph.nodes.entries()) {
+ expect(node.position.every(Number.isFinite)).toBe(true);
+ expect(node.footprint).toEqual([18, 18]);
+ for (const other of graph.nodes.slice(index + 1)) {
+ const apartX = Math.abs(node.position[0] - other.position[0]);
+ const apartZ = Math.abs(node.position[2] - other.position[2]);
+ expect(apartX >= 18 || apartZ >= 18, `${node.id} overlaps ${other.id}`).toBe(true);
+ }
+ }
+}
+function expectCompact(graph: SemanticGraph, maxExtent: number) {
+ for (const axis of [0, 2]) {
+ const coordinates = graph.nodes.map(node => node.position[axis]);
+ expect(Math.max(...coordinates) - Math.min(...coordinates) + 18).toBeLessThanOrEqual(maxExtent);
+ expect(new Set(coordinates).size).toBeGreaterThan(1);
+ }
+}
+describe('service map layout', () => {
+ it('retains isolated services and layers callers before their dependencies', () => {
+ const result = layoutContainers(topology()), nodes = new Map(result.graph.nodes.map(node => [node.id, node]));
+ expect(nodes.size).toBe(4); expect(nodes.get('frontend')!.position[0]).toBeLessThan(nodes.get('worker')!.position[0]);
+ expect(nodes.get('worker')!.position[0]).toBeLessThan(nodes.get('db')!.position[0]);
+ expect(nodes.get('isolated')!.footprint).toEqual([18, 18]);
+ });
+ it('condenses dependency cycles and remains deterministic across input order', () => {
+ const input = topology(); input.connections.push({ id: '3', source: 'db', target: 'worker', kind: 'call', protocol: 'http', evidence: [] });
+ const result = layoutContainers(input);
+ expect(result.cycles).toEqual([['db', 'worker']]);
+ expect(result.graph.nodes.every(node => node.position.every(Number.isFinite))).toBe(true);
+ expect(layoutContainers({ ...input, services: [...input.services].reverse(), connections: [...input.connections].reverse() }).graph).toEqual(result.graph);
+ });
+ it('does not treat startup order as a communication layer', () => {
+ const input = topology(); input.connections = [{ id: 'start', source: 'isolated', target: 'db', kind: 'startup', protocol: 'depends_on', evidence: [] }];
+ expect(layoutContainers(input).graph.nodes).toEqual(layoutContainers({ ...input, connections: [] }).graph.nodes);
+ });
+ it.each([68, 128])('packs %i unconnected services into a compact map without inventing edges', count => {
+ const input = serviceMap(count), result = layoutContainers(input);
+ expect(result.graph.nodes).toHaveLength(count);
+ expect(result.graph.edges).toEqual([]);
+ expectCompact(result.graph, 350);
+ expectSeparatedSquares(result.graph);
+ expect(layoutContainers({ ...input, services: [...input.services].reverse() })).toEqual(result);
+ });
+ it('keeps a sparse 68-service map compact while preserving connected dependency order', () => {
+ const input = serviceMap(68);
+ input.connections = [connect('service-000', 'service-001'), connect('service-001', 'service-002')];
+ const result = layoutContainers(input), nodes = new Map(result.graph.nodes.map(node => [node.id, node]));
+ expectCompact(result.graph, 350);
+ expectSeparatedSquares(result.graph);
+ for (const edge of input.connections) expect(nodes.get(edge.source)!.position[0]).toBeLessThan(nodes.get(edge.target)!.position[0]);
+ expect(result.graph.edges).toHaveLength(2);
+ });
+ it('packs a wide dependency layer after its callers and before its shared dependency', () => {
+ const input = serviceMap(68), peers = input.services.slice(1, -1);
+ input.connections = peers.flatMap(service => [connect('service-000', service.id), connect(service.id, 'service-067')]);
+ const result = layoutContainers(input), nodes = new Map(result.graph.nodes.map(node => [node.id, node]));
+ expectCompact(result.graph, 350);
+ expectSeparatedSquares(result.graph);
+ for (const service of peers) {
+ expect(nodes.get('service-000')!.position[0]).toBeLessThan(nodes.get(service.id)!.position[0]);
+ expect(nodes.get(service.id)!.position[0]).toBeLessThan(nodes.get('service-067')!.position[0]);
+ }
+ expect(layoutContainers({ ...input, services: [...input.services].reverse(), connections: [...input.connections].reverse() })).toEqual(result);
+ });
+ it('keeps cycle membership and layout stable across traversal order in a large graph', () => {
+ const input = serviceMap(68);
+ input.connections = [connect('service-000', 'service-001'), connect('service-000', 'service-003'),
+ connect('service-001', 'service-002'), connect('service-002', 'service-001'),
+ connect('service-003', 'service-004'), connect('service-004', 'service-003'),
+ connect('service-002', 'service-005'), connect('service-004', 'service-005')];
+ const result = layoutContainers(input), nodes = new Map(result.graph.nodes.map(node => [node.id, node]));
+ expect(result.cycles).toEqual([['service-001', 'service-002'], ['service-003', 'service-004']]);
+ for (const id of ['service-001', 'service-002', 'service-003', 'service-004']) {
+ expect(nodes.get('service-000')!.position[0]).toBeLessThan(nodes.get(id)!.position[0]);
+ expect(nodes.get(id)!.position[0]).toBeLessThan(nodes.get('service-005')!.position[0]);
+ }
+ expectSeparatedSquares(result.graph);
+ expectCompact(result.graph, 400);
+ expect(layoutContainers({ ...input, services: [...input.services].reverse(), connections: [...input.connections].reverse() })).toEqual(result);
+ });
+});
diff --git a/graph-ui/src/architecture/container-layout.ts b/graph-ui/src/architecture/container-layout.ts
new file mode 100644
index 000000000..4de35f765
--- /dev/null
+++ b/graph-ui/src/architecture/container-layout.ts
@@ -0,0 +1,63 @@
+import type { ContainerTopology } from './container-topology';
+import type { SemanticGraph } from './semantic-graph';
+
+/** Condense cycles before layering. Direction describes callers, not data movement. */
+export function layoutContainers(topology: ContainerTopology): { graph: SemanticGraph; cycles: string[][] } {
+ const services = [...topology.services].sort((a, b) => a.id.localeCompare(b.id));
+ const ids = new Set(services.map(service => service.id));
+ const adjacent = new Map(services.map(service => [service.id, new Set<string>()]));
+ for (const edge of topology.connections) if (edge.kind !== 'startup' && ids.has(edge.source) && ids.has(edge.target)) adjacent.get(edge.source)!.add(edge.target);
+ const numbers = new Map<string, number>(), low = new Map<string, number>();
+ const stack: string[] = [], active = new Set<string>(), groups: string[][] = [];
+ const visit = (id: string) => {
+ numbers.set(id, numbers.size); low.set(id, numbers.get(id)!); stack.push(id); active.add(id);
+ for (const target of [...adjacent.get(id)!].sort()) {
+ if (!numbers.has(target)) { visit(target); low.set(id, Math.min(low.get(id)!, low.get(target)!)); }
+ else if (active.has(target)) low.set(id, Math.min(low.get(id)!, numbers.get(target)!));
+ }
+ if (low.get(id) === numbers.get(id)) {
+ const group: string[] = []; let next: string;
+ do { next = stack.pop()!; active.delete(next); group.push(next); } while (next !== id);
+ groups.push(group.sort());
+ }
+ };
+ services.forEach(service => { if (!numbers.has(service.id)) visit(service.id); });
+ const membership = new Map(groups.flatMap((group, index) => group.map(id => [id, index] as const)));
+ const outgoing = groups.map(() => new Set<number>()), incoming = groups.map(() => 0), layers = groups.map(() => 0);
+ for (const [source, targets] of adjacent) for (const target of targets) {
+ const a = membership.get(source)!, b = membership.get(target)!;
+ if (a !== b && !outgoing[a].has(b)) { outgoing[a].add(b); incoming[b]++; }
+ }
+ const queue = incoming.flatMap((count, index) => count ? [] : [index]);
+ for (let index = 0; index < queue.length; index++) for (const next of outgoing[queue[index]]) {
+ layers[next] = Math.max(layers[next], layers[queue[index]] + 1);
+ if (--incoming[next] === 0) queue.push(next);
+ }
+ const rows = new Map<number, typeof services>();
+ services.forEach(service => { const layer = layers[membership.get(service.id)!]; rows.set(layer, [...(rows.get(layer) ?? []), service]); });
+ const positions = new Map<string, [number, number, number]>();
+ let offsetX = 0;
+ for (const [, row] of [...rows].sort(([a], [b]) => a - b)) {
+ const columns = Math.ceil(Math.sqrt(row.length)), rowCount = Math.ceil(row.length / columns);
+ // Pack peers in two dimensions, reserving the whole region before the next
+ // layer so every dependency between condensed cycles still points right.
+ row.forEach((service, index) => positions.set(service.id, [offsetX + (index % columns) * 28, 0,
+ (Math.floor(index / columns) - (rowCount - 1) / 2) * 28]));
+ offsetX += (columns - 1) * 28 + 34;
+ }
+ const graph: SemanticGraph = {
+ view: 'routes', scopeKey: services.map(service => service.id).join('|'), title: 'Container service map',
+ positionMeaning: 'Squares represent declared services. Dependency layers advance left to right; peers and cycles share compact regions.',
+ nodes: services.map(service => ({ id: service.id, kind: 'area', label: service.name,
+ detail: `${service.project} · ${service.image ?? 'built from source'}`, position: positions.get(service.id)!,
+ count: service.sourcePaths.length, members: [], footprint: [18, 18],
+ tint: service.sourcePaths.length ? '#85b4c5' : '#b6a087', kindLabel: 'Declared service' })),
+ edges: [...topology.connections].sort((a, b) => a.id.localeCompare(b.id)).map(edge => ({ id: edge.id, source: edge.source, target: edge.target,
+ type: edge.kind === 'startup' ? 'STARTUP_DEPENDENCY' : edge.kind === 'configuration' ? 'CONFIGURES'
+ : /redis|postgres|mysql|database|sql/i.test(edge.protocol) ? 'SERVICE_CALLS'
+ : /grpc/i.test(edge.protocol) ? 'GRPC_CALLS' : /http/i.test(edge.protocol) ? 'HTTP_CALLS' : 'SERVICE_CALLS',
+ count: edge.evidence.length, evidence: [] })),
+ totalNodes: services.length, totalEdges: topology.connections.length, omittedNodes: 0, omittedEdges: 0, warnings: [],
+ };
+ return { graph, cycles: groups.filter(group => group.length > 1 || adjacent.get(group[0])!.has(group[0])) };
+}
diff --git a/graph-ui/src/architecture/container-map.css b/graph-ui/src/architecture/container-map.css
new file mode 100644
index 000000000..e70dfb1c9
--- /dev/null
+++ b/graph-ui/src/architecture/container-map.css
@@ -0,0 +1,22 @@
+.container-projects { display:flex; flex-wrap:wrap; gap:10px 20px; padding:12px 20px; border-top:1px solid var(--spatial-line); }
+.container-projects label { display:flex; flex-wrap:wrap; align-items:center; gap:8px; font-size:12px; min-width:0; }
+.container-projects select { max-width:260px; }
+.container-edge-key { display:flex; flex-wrap:wrap; gap:14px; font-size:11px; align-items:center; color:var(--spatial-muted); }
+.container-edge-key label, .container-edge-key span { display:flex; align-items:center; gap:6px; }
+.container-edge-key input { accent-color:#a9b8b1; }
+.container-call-key { width:18px; height:2px; background:#7da4ba; }
+.container-map .spatial-map { height:clamp(540px,64vh,820px); }
+.container-map .spatial-inspector { max-height:clamp(540px,64vh,820px); }
+.container-map .architecture-node-label:not(.is-selected) { max-width:145px; background:#101b23db; border-color:#63889380; border-radius:6px; padding:7px 12px; }
+.container-map .architecture-node-label:not(.is-selected) strong { font-size:12px; }
+.container-facts { display:grid; grid-template-columns:auto minmax(0,1fr); gap:10px; font-size:11px; line-height:1.6; }
+.container-facts dt { color:var(--spatial-muted); }
+.container-facts dd { margin:0; overflow-wrap:anywhere; }
+.container-service-list { display:flex; flex-wrap:wrap; gap:8px; padding:8px 20px 16px; }
+.container-service-list button { text-align:left; flex:1 1 120px; max-width:240px; }
+.container-source pre { white-space:pre-wrap; overflow-wrap:anywhere; font-size:11px; padding:12px; border:1px solid var(--spatial-line); }
+.container-mode { display:flex; gap:6px; margin:16px 0; }
+.container-mode button { color:#aebeb7; border:1px solid #314c43; border-radius:6px; padding:8px 14px; background:#101b19; font:inherit; font-size:12px; cursor:pointer; }
+.container-mode button[aria-pressed=true] { color:#d9ece5; background:#243d35; border-color:#638d7b; }
+.container-mode button:focus-visible { outline:2px solid #8ce9f7; outline-offset:3px; }
+@media(max-width:760px) { .container-projects { padding:12px; } .container-map .spatial-map { height:540px; } }
diff --git a/graph-ui/src/architecture/container-source.test.ts b/graph-ui/src/architecture/container-source.test.ts
new file mode 100644
index 000000000..0152c478c
--- /dev/null
+++ b/graph-ui/src/architecture/container-source.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from 'vitest';
+import { isComposePath, loadContainerInventory, loadContainerTopology, readContainerSource, type ContainerInventory } from './container-source';
+import type { RpcIntelligenceClient } from '../provider/rpc-client';
+
+const inventory: ContainerInventory = { project: 'demo', rootPath: '/demo', files: new Map([
+ ['compose.yml', 'demo.compose'], ['api/Dockerfile', 'demo.docker'], ['api/main.py', 'demo.main'], ['.env', 'demo.env'],
+]), manifests: ['compose.yml'], warnings: [] };
+const signal = () => new AbortController().signal;
+const client = (methods: object) => methods as RpcIntelligenceClient;
+
+describe('container source inspection', () => {
+ it('recognizes Compose variants while requiring explicit selection', () => {
+ expect(isComposePath('deploy/docker-compose.dev.yaml')).toBe(true);
+ expect(isComposePath('compose.yml')).toBe(true);
+ expect(isComposePath('package.json')).toBe(false);
+ expect(isComposePath('somecompose.yml')).toBe(false);
+ });
+ it('uses indexed qualified identities and reports the file discovery bound', async () => {
+ const queryRows = vi.fn(async (_project: string, _query: string) => Array.from({ length: 4001 }, (_, i) => ({ path: i ? `src/${i}.ts` : 'compose.yml', qn: `qn${i}` })));
+ const result = await loadContainerInventory({ name: 'p', root_path: '/p' }, client({ queryRows }));
+ expect(result.files.size).toBe(4000); expect(result.manifests).toEqual(['compose.yml']);
+ expect(result.warnings).toHaveLength(1); expect(queryRows.mock.calls[0][0]).toBe('p');
+ });
+ it('rejects incomplete YAML instead of constructing a partial service declaration', async () => {
+ const getCodeSnippet = vi.fn(async () => ({ source: 'services:\n web:', start_line: 1, source_truncated: true }));
+ await expect(readContainerSource(inventory, 'compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow('incomplete');
+ });
+ it('reads a verified module span rather than accepting an unflagged 51-line File preview', async () => {
+ const queryRows = vi.fn(async (_project: string, query: string) => query.includes('f:Module')
+ ? [{ path: 'compose.yml', qn: 'module', first_line: '1', last_line: '97' }]
+ : [{ path: 'compose.yml', qn: 'file' }]);
+ const result = await loadContainerInventory({ name: 'p', root_path: '/p' }, client({ queryRows }));
+ expect(result.files.get('compose.yml')).toBe('module');
+ const getCodeSnippet = vi.fn(async () => ({ source: 'services:', start_line: 1, end_line: 51 }));
+ await expect(readContainerSource(result, 'compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow('incomplete');
+ const withoutSpan = { ...result, sourceEnds: new Map<string, number>() };
+ await expect(readContainerSource(withoutSpan, 'compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow('module span');
+ });
+ it('rejects a repeated source page and unknown source paths', async () => {
+ const getCodeSnippet = vi.fn(async () => ({ source: 'services:', start_line: 1, end_line: 1, next_start_line: 1 }));
+ await expect(readContainerSource(inventory, 'compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow('changed');
+ await expect(readContainerSource(inventory, '../other/compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow('outside');
+ expect(getCodeSnippet).toHaveBeenCalledTimes(1);
+ });
+ it('reads complete indexed class ranges when a whole-file module is unavailable, preserving source lines', async () => {
+ const queryRows = vi.fn(async (_project: string, query: string) => query.includes('f:File')
+ ? [{ path: 'api/Client.java', qn: 'file' }]
+ : query.includes('f:Class') ? [
+ { path: 'api/Client.java', qn: 'outer', first_line: '5', last_line: '8' },
+ { path: 'api/Client.java', qn: 'inner', first_line: '6', last_line: '7' },
+ ] : []);
+ const result = await loadContainerInventory({ name: 'p', root_path: '/p' }, client({ queryRows }));
+ const getCodeSnippet = vi.fn(async () => ({ source: 'class Client {\n String host = "cache";\n void send() {}\n}', start_line: 5, end_line: 8 }));
+ const source = await readContainerSource(result, 'api/Client.java', client({ getCodeSnippet }), signal());
+ expect(source.split('\n')[4]).toBe('class Client {');
+ expect(source.split('\n')[5]).toContain('"cache"');
+ expect(getCodeSnippet).toHaveBeenCalledTimes(1);
+ expect(getCodeSnippet).toHaveBeenCalledWith('p', 'outer', { startLine: 5, maxLines: 500 });
+ expect(result.sourceEnds?.has('api/Client.java')).toBe(false);
+ });
+ it('never uses a class-range fallback to accept an incomplete Compose document', async () => {
+ const queryRows = vi.fn(async (_project: string, query: string) => query.includes('f:File')
+ ? [{ path: 'compose.yml', qn: 'file' }]
+ : query.includes('f:Class') ? [{ path: 'compose.yml', qn: 'misclassified', first_line: '5', last_line: '8' }] : []);
+ const result = await loadContainerInventory({ name: 'p', root_path: '/p' }, client({ queryRows }));
+ const getCodeSnippet = vi.fn();
+ await expect(readContainerSource(result, 'compose.yml', client({ getCodeSnippet }), signal())).rejects.toThrow();
+ expect(getCodeSnippet).not.toHaveBeenCalled();
+ });
+ it('shares the bounded source budget across services instead of starving later build contexts', async () => {
+ const files = new Map<string, string>([['compose.yml', 'compose']]);
+ for (const name of ['a', 'b', 'c']) for (let i = 0; i < (name === 'a' ? 80 : 2); i++) files.set(`${name}/${i}.py`, `${name}/${i}`);
+ const getCodeSnippet = vi.fn(async (_project: string, qn: string) => ({
+ source: qn === 'compose' ? 'services:\n a:\n build: ./a\n b:\n build: ./b\n c:\n build: ./c\n' : 'pass', start_line: 1,
+ }));
+ const queryGraph = vi.fn(async () => ({ columns: [], rows: [], total: 0 }));
+ const result = await loadContainerTopology([{ inventory: { project: 'p', rootPath: '/p', files, manifests: ['compose.yml'], warnings: [] }, manifest: 'compose.yml' }], client({ getCodeSnippet, queryGraph }), signal());
+ const inspected = getCodeSnippet.mock.calls.map(call => call[1]);
+ expect(inspected).toContain('b/0'); expect(inspected).toContain('b/1');
+ expect(inspected).toContain('c/0'); expect(inspected).toContain('c/1');
+ expect(result.filesRead).toBe(81);
+ expect(result.warnings.some(warning => warning.includes('80 of 84'))).toBe(true);
+ });
+ it('does not read host environment files and only reads code within mapped build inputs', async () => {
+ const content: Record<string, string> = { 'demo.compose': 'services:\n web:\n build: ./api\n cache:\n image: redis:alpine\n', 'demo.docker': 'FROM python:3\nCOPY . /app', 'demo.main': 'import redis\nr = redis.Redis(host="cache")' };
+ const getCodeSnippet = vi.fn(async (_project: string, qn: string) => ({ source: content[qn], start_line: 1 }));
+ const queryGraph = vi.fn(async () => ({ columns: [], rows: [], total: 0 }));
+ const result = await loadContainerTopology([{ inventory, manifest: 'compose.yml' }], client({ getCodeSnippet, queryGraph }), signal());
+ expect(getCodeSnippet.mock.calls.map(call => call[1])).toEqual(['demo.compose', 'demo.docker', 'demo.main']);
+ expect(result.topology.services).toHaveLength(2); expect(result.filesRead).toBe(3);
+ });
+ it('stops before requesting source after cancellation', async () => {
+ const controller = new AbortController(); controller.abort(); const getCodeSnippet = vi.fn();
+ await expect(readContainerSource(inventory, 'compose.yml', client({ getCodeSnippet }), controller.signal)).rejects.toMatchObject({ name: 'AbortError' });
+ expect(getCodeSnippet).not.toHaveBeenCalled();
+ });
+});
diff --git a/graph-ui/src/architecture/container-source.ts b/graph-ui/src/architecture/container-source.ts
new file mode 100644
index 000000000..cacb490a1
--- /dev/null
+++ b/graph-ui/src/architecture/container-source.ts
@@ -0,0 +1,176 @@
+import { RpcIntelligenceClient } from '../provider/rpc-client';
+import type { ProjectEntry } from '../provider/rpc-schemas';
+import { loadRouteGraph } from './route-graph-source';
+import { buildContainerTopology, normalizeSourcePath, type ContainerTopology, type ServiceProject } from './container-topology';
+
+interface SourceSpan { qn: string; first: number; last: number }
+export interface ContainerInventory {
+ project: string; rootPath: string; files: Map<string, string>; manifests: string[]; warnings: string[];
+ sourceEnds?: Map<string, number>;
+ sourceSpans?: Map<string, SourceSpan[]>;
+}
+export interface ContainerSelection { inventory: ContainerInventory; manifest: string }
+export interface ContainerReading { topology: ContainerTopology; projects: ServiceProject[]; warnings: string[]; filesRead: number }
+export const isComposePath = (path: string) => /(^|\/)(?:docker-)?compose(?:[.-][\w.-]+)?\.ya?ml$/i.test(path);
+const isDockerfile = (path: string) => /(^|\/)(?:Dockerfile(?:[.][\w.-]+)?|[\w.-]+\.Dockerfile)$/i.test(path);
+const isCode = (path: string) => /\.(?:py|js|jsx|ts|tsx|cs|go|java|kt|rs|rb|php|c|cc|cpp|ex|exs)$/i.test(path)
+ && !/(^|\/)(?:node_modules|vendor|vendored|test|tests|fixtures|dist|build)\//.test(path)
+ && !/\.(?:min|test|spec)\.[^.]+$/.test(path);
+const checkAbort = (signal: AbortSignal) => { if (signal.aborted) throw new DOMException('Aborted', 'AbortError'); };
+
+/** Queries only indexed files. The caller explicitly selects each additional project. */
+export async function loadContainerInventory(project: ProjectEntry, client: RpcIntelligenceClient): Promise<ContainerInventory> {
+ const [rows, modules, classes, interfaces] = await Promise.all([
+ client.queryRows(project.name, 'MATCH (f:File) RETURN f.file_path AS path, f.qualified_name AS qn ORDER BY f.file_path LIMIT 4001'),
+ client.queryRows(project.name, 'MATCH (f:Module) RETURN f.file_path AS path, f.qualified_name AS qn, f.start_line AS first_line, f.end_line AS last_line ORDER BY f.file_path LIMIT 4001'),
+ client.queryRows(project.name, 'MATCH (f:Class) RETURN f.file_path AS path, f.qualified_name AS qn, f.start_line AS first_line, f.end_line AS last_line ORDER BY f.file_path LIMIT 4001'),
+ client.queryRows(project.name, 'MATCH (f:Interface) RETURN f.file_path AS path, f.qualified_name AS qn, f.start_line AS first_line, f.end_line AS last_line ORDER BY f.file_path LIMIT 4001'),
+ ]);
+ const files = new Map<string, string>();
+ for (const row of rows.slice(0, 4000)) if (row.path && row.path !== '{}' && row.qn) files.set(row.path, row.qn);
+ const sourceEnds = new Map<string, number>();
+ for (const row of modules.slice(0, 4000)) if (files.has(row.path) && row.qn && Number(row.first_line) === 1
+ && Number.isSafeInteger(Number(row.last_line)) && Number(row.last_line) >= 1) {
+ files.set(row.path, row.qn); sourceEnds.set(row.path, Number(row.last_line));
+ }
+ // Java and some other languages expose class/interface ranges without a file-wide Module.
+ // Keep exact ranges rather than claiming that a default File preview contains the whole file.
+ const sourceSpans = new Map<string, SourceSpan[]>();
+ for (const row of [...classes.slice(0, 4000), ...interfaces.slice(0, 4000)]) {
+ const first = Number(row.first_line), last = Number(row.last_line);
+ if (!files.has(row.path) || sourceEnds.has(row.path) || !isCode(row.path) || !row.qn
+ || !Number.isSafeInteger(first) || !Number.isSafeInteger(last) || first < 1 || last < first) continue;
+ const spans = sourceSpans.get(row.path) ?? [];
+ spans.push({ qn: row.qn, first, last }); sourceSpans.set(row.path, spans);
+ }
+ for (const [path, spans] of sourceSpans) {
+ const outer: SourceSpan[] = [];
+ for (const span of spans.sort((a, b) => a.first - b.first || b.last - a.last || a.qn.localeCompare(b.qn))) {
+ if (!outer.length || span.first > outer[outer.length - 1].last) outer.push(span);
+ }
+ sourceSpans.set(path, outer);
+ }
+ const manifests = [...files.keys()].filter(isComposePath).sort((a, b) =>
+ Number(!/^(?:docker-)?compose\.ya?ml$/.test(a)) - Number(!/^(?:docker-)?compose\.ya?ml$/.test(b)) || a.localeCompare(b));
+ return { project: project.name, rootPath: project.root_path ?? '', files, manifests, sourceEnds, sourceSpans,
+ warnings: [rows, modules, classes, interfaces].some(result => result.length > 4000)
+ ? ['File and symbol discovery is limited to 4,000 rows per kind for this project.'] : [] };
+}
+
+/** A partial YAML document must never masquerade as a complete deployment. */
+export async function readContainerSource(inventory: ContainerInventory, path: string, client: RpcIntelligenceClient, signal: AbortSignal): Promise<string> {
+ const qn = inventory.files.get(path);
+ if (!qn) throw new Error('File is outside the indexed inventory.');
+ // File nodes without a Module span can return a 51-line preview with no truncation flag.
+ if (inventory.sourceEnds && !inventory.sourceEnds.has(path)) {
+ const spans = isCode(path) ? inventory.sourceSpans?.get(path) : undefined;
+ if (!spans?.length) throw new Error('No complete module span or indexed code range is available.');
+ if (spans.length > 8 || spans[spans.length - 1].last > 20_000
+ || spans.reduce((total, span) => total + span.last - span.first + 1, 0) > 2000) throw new Error('Indexed code exceeds the source limit.');
+ const lines: string[] = [];
+ for (const span of spans) {
+ const code = await readSourceRange(inventory.project, span.qn, span.first, span.last, client, signal);
+ const part = code.split('\n');
+ if (part[part.length - 1] === '') part.pop();
+ if (part.length !== span.last - span.first + 1) throw new Error('Indexed code range changed while reading.');
+ while (lines.length < span.first - 1) lines.push('');
+ lines.push(...part);
+ if (lines.reduce((total, line) => total + line.length + 1, 0) > 160_000) throw new Error('Source exceeds the inspection limit.');
+ }
+ return lines.join('\n');
+ }
+ return readSourceRange(inventory.project, qn, 1, inventory.sourceEnds?.get(path), client, signal);
+}
+
+async function readSourceRange(project: string, qn: string, first: number, last: number | undefined, client: RpcIntelligenceClient, signal: AbortSignal): Promise<string> {
+ let source = '', next = first;
+ for (let page = 0; page < 4; page++) {
+ checkAbort(signal);
+ const snippet = await client.getCodeSnippet(project, qn, { startLine: next, maxLines: 500 });
+ checkAbort(signal);
+ if ((snippet.start_line ?? 1) !== next || snippet.source_mode === 'outline'
+ || !snippet.source || snippet.source === '(source not available)') throw new Error('Source page is unavailable.');
+ source += (page && !source.endsWith('\n') ? '\n' : '') + snippet.source;
+ if (source.length > 160_000) throw new Error('Source exceeds the inspection limit.');
+ if (snippet.next_start_line === undefined) {
+ if (snippet.source_clipped || snippet.source_truncated
+ || (last !== undefined && (snippet.end_line ?? 0) < last)) throw new Error('Source is incomplete.');
+ return source;
+ }
+ if (snippet.next_start_line <= next || snippet.next_start_line !== (snippet.end_line ?? 0) + 1) throw new Error('Source pages changed while reading.');
+ next = snippet.next_start_line;
+ }
+ throw new Error('Source exceeds the 2,000-line inspection limit.');
+}
+
+/** Round-robin build scopes so one large service cannot consume every inspected file. */
+function fairSourcePaths(paths: string[], project: ServiceProject, services: ContainerTopology['services']): string[] {
+ const available = new Map(paths.map(path => [normalizeSourcePath(project.rootPath, path), path]));
+ const priority = (path: string) => {
+ const name = path.split('/').at(-1) ?? '';
+ if (/(?:impl|client|gateway|transport)\.[^.]+$/i.test(name)) return 0;
+ return /(?:service|controller|repository)/i.test(name) ? 1 : 2;
+ };
+ const queues = [...services].sort((a, b) => a.id.localeCompare(b.id)).map(service => service.sourcePaths
+ .flatMap(path => available.has(path) ? [available.get(path)!] : [])
+ .sort((a, b) => priority(a) - priority(b) || a.localeCompare(b))).filter(queue => queue.length);
+ const ordered = new Set<string>();
+ for (let index = 0; queues.some(queue => index < queue.length); index++) {
+ for (const queue of queues) if (queue[index]) ordered.add(queue[index]);
+ }
+ paths.forEach(path => ordered.add(path));
+ return [...ordered];
+}
+
+/** Per-request lifetime; no ambient environment, shell, deployment, or external URL access. */
+export async function loadContainerTopology(selections: readonly ContainerSelection[], client: RpcIntelligenceClient, signal: AbortSignal): Promise<ContainerReading> {
+ const warnings: string[] = [];
+ let filesRead = 0;
+ const rangeFiles = new Set<string>();
+ let sourceChars = 0;
+ const projects: ServiceProject[] = selections.slice(0, 4).map(({ inventory, manifest }) => ({
+ project: inventory.project, rootPath: inventory.rootPath, manifest, files: [...inventory.files.keys()], sources: new Map<string, string>(),
+ }));
+ if (selections.length > 4) warnings.push('Compare at most four indexed projects at once.');
+ const read = async (index: number, paths: string[]) => {
+ const inventory = selections[index].inventory;
+ // Four requests at a time keep a large repo from monopolizing the daemon.
+ for (let offset = 0; offset < paths.length; offset += 4) {
+ checkAbort(signal);
+ if (sourceChars >= 4_000_000) { warnings.push('Source inspection reached the four-million-character budget.'); break; }
+ await Promise.all(paths.slice(offset, offset + 4).map(async path => {
+ try {
+ const source = await readContainerSource(inventory, path, client, signal);
+ if (sourceChars + source.length > 4_000_000) { sourceChars = 4_000_000; warnings.push('Source inspection reached the four-million-character budget.'); return; }
+ sourceChars += source.length;
+ (projects[index].sources as Map<string, string>).set(path, source); filesRead++;
+ if (inventory.sourceSpans?.has(path) && !inventory.sourceEnds?.has(path)) rangeFiles.add(`${inventory.project}:${path}`);
+ } catch {
+ checkAbort(signal);
+ warnings.push(`${inventory.project}: ${path} was unavailable, incomplete, or exceeded the source limit.`);
+ }
+ }));
+ }
+ };
+ for (let index = 0; index < projects.length; index++) {
+ warnings.push(...selections[index].inventory.warnings);
+ if (projects[index].manifest) await read(index, [projects[index].manifest]);
+ const dockerfiles = projects[index].files.filter(isDockerfile);
+ if (dockerfiles.length > 32) warnings.push(`${projects[index].project}: Dockerfile inspection is limited to 32 files.`);
+ await read(index, dockerfiles.slice(0, 32));
+ }
+ const declarations = buildContainerTopology(projects);
+ for (let index = 0; index < projects.length; index++) {
+ // Candidate ownership is established from declarations before reading application code.
+ const candidates = new Set(declarations.services.flatMap(service => service.sourcePaths));
+ const paths = fairSourcePaths(projects[index].files.filter(path => candidates.has(normalizeSourcePath(projects[index].rootPath, path)) && isCode(path)), projects[index], declarations.services);
+ if (paths.length > 80) warnings.push(`${projects[index].project}: inspected 80 of ${paths.length} candidate source files.`);
+ await read(index, paths.slice(0, 80));
+ checkAbort(signal);
+ projects[index].routeGraph = await loadRouteGraph(projects[index].project, { client, signal });
+ warnings.push(...projects[index].routeGraph!.warnings);
+ }
+ checkAbort(signal);
+ if (rangeFiles.size) warnings.push(`${rangeFiles.size} files were inspected through indexed class/interface ranges; imports and code outside those ranges were not analyzed.`);
+ return { topology: buildContainerTopology(projects), projects, warnings: [...new Set(warnings)], filesRead };
+}
diff --git a/graph-ui/src/architecture/container-topology.test.ts b/graph-ui/src/architecture/container-topology.test.ts
new file mode 100644
index 000000000..3cfa2db5f
--- /dev/null
+++ b/graph-ui/src/architecture/container-topology.test.ts
@@ -0,0 +1,345 @@
+import { describe, expect, it } from 'vitest';
+import { buildContainerTopology, normalizeSourcePath } from './container-topology';
+import type { ContainerTopology, ServiceProject } from './container-topology';
+import type { RouteGraphSnapshot } from './route-graph-source';
+
+function project(compose: string, sources: Record<string, string> = {}, overrides: Partial<ServiceProject> = {}): ServiceProject {
+ return { project: 'sample', rootPath: '/repos/sample', manifest: 'compose.yaml',
+ files: Object.keys(sources), sources: new Map(Object.entries({ 'compose.yaml': compose, ...sources })), ...overrides };
+}
+function links(topology: ContainerTopology, kind: 'call' | 'configuration' | 'startup' = 'call'): string[] {
+ const names = new Map(topology.services.map(service => [service.id, service.name]));
+ return topology.connections.filter(edge => edge.kind === kind).map(edge => `${names.get(edge.source)}>${names.get(edge.target)}:${edge.protocol}`).sort();
+}
+
+const voting = `services:
+ vote:
+ build: ./vote
+ networks: [front, back]
+ depends_on: [redis]
+ result:
+ build: ./result
+ networks: [front, back]
+ worker:
+ build: ./worker
+ networks: [back]
+ redis:
+ image: redis:alpine
+ networks: [back]
+ db:
+ image: postgres:15
+ networks: [back]
+ environment:
+ POSTGRES_PASSWORD: top-secret
+ seed:
+ build: ./seed
+ profiles: [seed]
+ networks: [front]
+networks:
+ front:
+ back:
+`;
+const votingSources = {
+ 'vote/app.py': 'from redis import Redis\nclient = Redis(host="redis", db=0)\n',
+ 'result/server.js': "const pool = new Pool({\n connectionString: 'postgres://user:credential@db/votes'\n});\n",
+ 'worker/Program.cs': `class Worker {
+ static void Main() {
+ var db = OpenDatabase("Server=db;Username=postgres;Password=credential;");
+ var cache = OpenCache("redis");
+ }
+ static NpgsqlConnection OpenDatabase(string address) {
+ var connection = new NpgsqlConnection(address);
+ connection.Open();
+ return connection;
+ }
+ static ConnectionMultiplexer OpenCache(string hostname) {
+ var address = GetIp(hostname);
+ return ConnectionMultiplexer.Connect(address);
+ }
+}`,
+};
+
+describe('Compose container topology', () => {
+ it('recognizes qualified transport constructors without matching unrelated methods', () => {
+ const result = buildContainerTopology([project(voting, {
+ 'vote/app.py': 'import redis\nclient = redis.Redis(host="redis")\n',
+ 'result/server.js': 'const pool = new pg.Pool({connectionString: "postgres://db/votes"});\nother.Pool("redis");',
+ })]);
+ expect(links(result)).toEqual(['result>db:postgres', 'vote>redis:redis']);
+ });
+ it('finds the four source connections in a voting microservice shape, retaining isolated/profiled declarations', () => {
+ const result = buildContainerTopology([project(voting, votingSources)]);
+ expect(result.services).toHaveLength(6);
+ expect(links(result)).toEqual(['result>db:postgres', 'vote>redis:redis', 'worker>db:postgres', 'worker>redis:redis']);
+ expect(links(result, 'startup')).toEqual(['vote>redis:startup']);
+ expect(result.services.find(service => service.name === 'seed')?.profiles).toEqual(['seed']);
+ expect(result.services.find(service => service.name === 'redis')?.sourcePaths).toEqual([]);
+ const vote = result.connections.find(edge => edge.kind === 'call' && edge.protocol === 'redis'
+ && result.services.find(service => service.id === edge.source)?.name === 'vote');
+ expect(vote?.evidence[0]).toMatchObject({ project: 'sample', path: 'vote/app.py', line: 2 });
+ expect(JSON.stringify(result)).not.toMatch(/credential|top-secret|Username|Password/);
+ expect(result.services.find(service => service.name === 'worker')?.sourcePaths).toEqual(['/repos/sample/worker/Program.cs']);
+ });
+
+ it('never derives network traffic from a shared network, comments, log strings or route names', () => {
+ const result = buildContainerTopology([project(voting, {
+ 'vote/app.py': '# Redis(host="redis")\nprint("Redis(host=redis)")\nlabel = "redis"\n',
+ 'worker/worker.js': 'console.log("http://db/users");\napp.get("/users", handler);\n',
+ })]);
+ expect(links(result)).toEqual([]);
+ expect(result.services).toHaveLength(6);
+ });
+
+ it('scopes default DNS to each Compose manifest and project despite duplicate service names', () => {
+ const compose = 'services:\n web:\n build: ./web\n environment: {REDIS_HOST: redis}\n redis:\n image: redis:7\n';
+ const one = project(compose, {}, { project: 'one', rootPath: '/repos/one' });
+ const two = project(compose, {}, { project: 'two', rootPath: '/repos/two' });
+ const result = buildContainerTopology([one, two]);
+ expect(new Set(result.services.map(service => service.id)).size).toBe(4);
+ expect(result.connections).toHaveLength(2);
+ expect(result.connections.every(edge => result.services.find(service => service.id === edge.source)?.project
+ === result.services.find(service => service.id === edge.target)?.project)).toBe(true);
+ expect(result.unresolved).toEqual([]);
+ });
+
+ it('connects selected repositories only when the hostname is unique on an explicitly shared network', () => {
+ const caller = project('services:\n web:\n build: ./web\n networks: [mesh]\nnetworks:\n mesh: {external: true, name: shared-mesh}\n', {
+ 'web/client.ts': 'fetch("http://api:8080/items");',
+ }, { project: 'front', rootPath: '/repos/front' });
+ const callee = project('services:\n api:\n image: example/api\n networks:\n mesh: {aliases: [catalog]}\nnetworks:\n mesh: {external: true, name: shared-mesh}\n', {}, { project: 'back', rootPath: '/repos/back' });
+ const result = buildContainerTopology([caller, callee]);
+ expect(links(result)).toEqual(['web>api:http']);
+ expect(result.connections[0].evidence[0]).toMatchObject({ project: 'front', path: 'web/client.ts', line: 1 });
+ const collision = project('services:\n api:\n image: example/other\n networks: [mesh]\nnetworks:\n mesh: {external: true, name: shared-mesh}\n', {}, { project: 'other', rootPath: '/repos/other' });
+ const ambiguous = buildContainerTopology([caller, callee, collision]);
+ expect(links(ambiguous)).toEqual([]);
+ expect(ambiguous.unresolved[0].summary).toContain('Ambiguous');
+ });
+
+ it('does not connect identical hostnames across separate networks or treat depends_on as a call', () => {
+ const result = buildContainerTopology([project('services:\n web:\n build: ./web\n networks: [front]\n depends_on: [db]\n db:\n image: postgres\n networks: [back]\nnetworks:\n front:\n back:\n', {
+ 'web/client.ts': 'fetch("http://db/query");',
+ })]);
+ expect(links(result)).toEqual([]);
+ expect(links(result, 'startup')).toEqual(['web>db:startup']);
+ expect(result.unresolved[0].summary).toContain('shared network');
+ });
+
+ it('resolves endpoint configuration separately and never expands variables or consumes secrets/.env', () => {
+ const result = buildContainerTopology([project('services:\n web:\n build: ./web\n environment:\n - REDIS_HOST=redis\n - DATABASE_URL=${DB_URL}\n - ACCESS_TOKEN=http://db/secret\n env_file: .env\n redis: {image: redis}\n db: {image: postgres}\n', {
+ 'web/client.ts': 'fetch(process.env.DATABASE_URL);\nredis.connect(process.env.REDIS_HOST);',
+ '.env': 'DB_URL=http://db/private\n',
+ })]);
+ expect(links(result, 'configuration')).toEqual(['web>redis:redis']);
+ expect(links(result)).toEqual(['web>redis:redis']);
+ expect(result.unresolved.some(item => item.summary.includes('unresolved variables'))).toBe(true);
+ expect(result.warnings.join(' ')).toContain('env_file');
+ expect(JSON.stringify(result)).not.toContain('http://db/secret');
+ expect(JSON.stringify(result)).not.toContain('private');
+ });
+
+ it('supports long port declarations and source-local links aliases without leaking an alias to unrelated services', () => {
+ const result = buildContainerTopology([project('services:\n web:\n build: ./web\n links: ["db:storage"]\n ports:\n - target: 8080\n published: "80"\n protocol: tcp\n other:\n build: ./other\n db: {image: postgres}\n', {
+ 'web/client.py': 'psycopg.connect("host=storage")\npsycopg.connect("postgres://storage/data")',
+ 'other/client.py': 'psycopg.connect("postgres://storage/data")',
+ })]);
+ expect(links(result)).toEqual(['web>db:postgres']);
+ expect(result.services.find(service => service.name === 'web')?.ports).toEqual(['80:8080/tcp']);
+ expect(result.unresolved.some(item => item.path === 'other/client.py')).toBe(true);
+ });
+
+ it('uses selected sibling source roots for ../ builds without requiring a sibling manifest', () => {
+ const owner = project('services:\n api: {build: ../backend}\n db: {image: postgres}\n');
+ const sourceOnly = project('', { 'src/index.ts': 'fetch("http://db/items")', Dockerfile: 'FROM node\nCOPY src ./src\n' }, {
+ project: 'backend', rootPath: '/repos/backend', manifest: '',
+ });
+ const result = buildContainerTopology([owner, sourceOnly]);
+ expect(result.services).toHaveLength(2);
+ expect(result.services[0].sourcePaths).toContain('/repos/backend/src/index.ts');
+ expect(links(result)).toEqual(['api>db:http']);
+ expect(result.connections[0].evidence[0]).toMatchObject({ project: 'backend', path: 'src/index.ts' });
+ expect(result.warnings).toEqual([]);
+ });
+
+ it('refines root contexts with explicit COPY sources while excluding shared ownership and multi-stage copies', () => {
+ const compose = 'services:\n api:\n build: {context: ., dockerfile: api.Dockerfile}\n worker:\n build: {context: ., dockerfile: worker.Dockerfile}\n db: {image: postgres}\n';
+ const result = buildContainerTopology([project(compose, {
+ 'api.Dockerfile': 'FROM node\nCOPY ["api", "/app"]\nCOPY shared /shared\nCOPY --from=build /generated /app/generated\n',
+ 'worker.Dockerfile': 'FROM node AS build\nCOPY worker /app\nCOPY shared /shared\nFROM node\nCOPY --from=build /app /app\n',
+ 'api/a.ts': 'fetch("http://db/a")', 'worker/w.ts': 'fetch("http://db/w")',
+ 'shared/s.ts': 'fetch("http://db/shared")', 'unowned/u.ts': 'fetch("http://db/no")',
+ })]);
+ expect(links(result)).toEqual(['api>db:http', 'worker>db:http']);
+ expect(result.services).toHaveLength(3);
+ expect(result.services.flatMap(service => service.sourcePaths)).not.toContain('/repos/sample/shared/s.ts');
+ expect(result.warnings.join(' ')).toContain('overlapping');
+ const noEvidence = buildContainerTopology([project('services:\n api: {build: .}\n db: {image: postgres}\n', {
+ Dockerfile: 'FROM node\nCOPY . /app\n', 'client.ts': 'fetch("http://db/no")',
+ })]);
+ expect(links(noEvidence)).toEqual([]);
+ expect(noEvidence.warnings.join(' ')).toContain('root build context');
+ });
+
+ it.each([
+ ['duplicate keys', 'services:\n api: {image: one}\n api: {image: two}\n'],
+ ['aliases', 'x-base: &base {image: example}\nservices:\n api: *base\n'],
+ ['merge', 'services:\n api:\n <<: {image: example}\n'],
+ ['include', 'include: other.yaml\nservices:\n api: {image: example}\n'],
+ ['invalid syntax', 'services: [unclosed'],
+ ['custom tags', 'services:\n api: !custom value\n'],
+ ['size', 'services:\n' + '#'.repeat(256 * 1024)],
+ ['depth', 'services:\n api:\n x: ' + '['.repeat(45) + 'x' + ']'.repeat(45)],
+ ])('fails closed with a visible warning for %s', (_name, manifest) => {
+ const result = buildContainerTopology([project(manifest)]);
+ expect(result.services).toEqual([]);
+ expect(result.connections).toEqual([]);
+ expect(result.warnings.length).toBeGreaterThan(0);
+ });
+
+ it('omits an unsupported extended service instead of guessing inherited settings', () => {
+ const result = buildContainerTopology([project('services:\n api:\n extends: {file: other.yaml, service: base}\n isolated: {image: busybox}\n')]);
+ expect(result.services.map(service => service.name)).toEqual(['isolated']);
+ expect(result.warnings.join(' ')).toContain('extends');
+ });
+
+ it('keeps graph IDs project-scoped and refuses to join relative route paths', () => {
+ const node = (id: number, path: string) => ({ id, name: '/items', label: 'Function', file_path: path,
+ start_line: 4, x: 0, y: 0, z: 0, size: 1, color: '' });
+ const routeGraph: RouteGraphSnapshot = { truncated: false, warnings: [], relationships: [{
+ source: node(1, 'web/client.ts'), target: node(2, ''), type: 'HTTP_CALLS', routePath: '/items',
+ }] };
+ const result = buildContainerTopology([
+ project('services:\n web: {build: ./web}\n', { 'web/client.ts': 'const x = 1;' }, { routeGraph }),
+ project('services:\n api: {build: ./api}\n', { 'api/server.ts': 'app.get("/items", handler)' }, { project: 'other', rootPath: '/repos/other',
+ routeGraph: { truncated: false, warnings: [], relationships: [{ source: node(2, ''), target: node(1, 'api/server.ts'), type: 'HANDLES', routePath: '/items' }] } }),
+ ]);
+ expect(result.connections).toEqual([]);
+ });
+
+ it('bounds service declarations and preserves warnings for missing/oversized source evidence', () => {
+ const declarations = Array.from({ length: 130 }, (_, index) => ` service${index}: {image: example}`).join('\n');
+ const result = buildContainerTopology([project(`services:\n${declarations}\n`)]);
+ expect(result.services).toHaveLength(128);
+ expect(result.warnings.join(' ')).toContain('128');
+ const oversized = buildContainerTopology([project('services:\n api: {build: ./api}\n', { 'api/index.ts': 'x'.repeat(256 * 1024 + 1) })]);
+ expect(oversized.warnings.join(' ')).toContain('size limit');
+ });
+
+ it('normalizes source identities without filesystem access', () => {
+ expect(normalizeSourcePath('/repos/front', '../back/src/../main.ts')).toBe('/repos/back/main.ts');
+ expect(normalizeSourcePath('/repos/front', '/repos/back/main.ts')).toBe('/repos/back/main.ts');
+ expect(normalizeSourcePath('C:/repos/front', '../back/main.ts')).toBe('C:/repos/back/main.ts');
+ });
+});
+
+describe('Spring service connection evidence', () => {
+ const compose = 'services:\n gateway: {build: ./gateway}\n catalog: {image: example/catalog}\n payment: {image: example/payment}\n';
+ const model = (java: string, extra: Record<string, string> = {}) => buildContainerTopology([project(compose, {
+ 'gateway/src/main/java/Client.java': java, ...extra,
+ })]);
+
+ it('resolves typed RestTemplate URLs from literal concatenation and local URI bindings', () => {
+ const result = model(`class Client {
+ private RestTemplate transport;
+ Response load(String id) {
+ final String host = "catalog";
+ String address = "http://" + host + ":8080/api/items/" + id;
+ URI endpoint = URI.create(address);
+ return transport.exchange(endpoint, HttpMethod.GET, null, Response.class);
+ }
+ void save(String id) {
+ transport.postForEntity("http://payment:8081/api/pay/" + id, body, Response.class);
+ }
+}`);
+ expect(links(result)).toEqual(['gateway>catalog:http', 'gateway>payment:http']);
+ expect(result.connections.find(edge => edge.target.endsWith(':catalog'))?.evidence[0]).toMatchObject({
+ path: 'gateway/src/main/java/Client.java', line: 7,
+ });
+ });
+
+ it('substitutes literal arguments into a simple local string helper without repository-specific rules', () => {
+ const result = model(`class Client {
+ private RestTemplate transport;
+ private String endpointFor(String host) { return "http://" + host; }
+ Object load(String id) {
+ String address = endpointFor("catalog");
+ return transport.exchange(address + "/items/" + id, HttpMethod.GET, null, Object.class);
+ }
+ Object pay() {
+ String address = endpointFor("payment");
+ return transport.exchange(address + "/pay", HttpMethod.POST, null, Object.class);
+ }
+}`);
+ expect(links(result)).toEqual(['gateway>catalog:http', 'gateway>payment:http']);
+ });
+
+ it('follows renamed RestOperations clients and same-scope sequential string assignments', () => {
+ const result = model(`class Client {
+ private RestOperations api;
+ String load() {
+ String endpoint = "http://catalog:8080";
+ endpoint = endpoint + "/items";
+ return api.getForObject(endpoint, String.class);
+ }
+}`);
+ expect(links(result)).toEqual(['gateway>catalog:http']);
+ });
+
+ it('recognizes typed WebClient requests with explicit URLs and a statically configured base URL', () => {
+ const result = model(`class Client {
+ private WebClient catalogClient = WebClient.create("http://catalog:8080");
+ private WebClient paymentClient;
+ Object load(String id) {
+ return catalogClient.get().uri("/items/" + id).retrieve().bodyToMono(String.class);
+ }
+ Object pay() {
+ String url = "https://payment:8443/pay";
+ return paymentClient.post().uri(url).retrieve().bodyToMono(String.class);
+ }
+}`);
+ expect(links(result)).toEqual(['gateway>catalog:http', 'gateway>payment:https']);
+ });
+
+ it('does not borrow same-named locals from another method or guess a dynamic hostname', () => {
+ const result = model(`class Client {
+ private RestTemplate transport;
+ void unused() { String address = "http://catalog:8080/items"; }
+ Object dynamic(String hostname) {
+ String address = "http://" + hostname + "/items";
+ return transport.getForObject(address, String.class);
+ }
+ Object unrelated() { return transport.getForObject(address, String.class); }
+}`);
+ expect(links(result)).toEqual([]);
+ });
+
+ it('rejects conditional endpoint reassignment and method parameters shadowing a constant', () => {
+ const result = model(`class Client {
+ private RestTemplate transport;
+ private static final String address = "http://catalog:8080/items";
+ Object shadowed(String address) { return transport.getForObject(address, String.class); }
+ Object conditional(boolean change) {
+ String url = "http://catalog:8080/items";
+ if (change) { url = "http://payment:8080/pay"; }
+ return transport.getForObject(url, String.class);
+ }
+}`);
+ expect(links(result)).toEqual([]);
+ });
+
+ it('ignores comments, logging, arbitrary exchange methods, client construction alone and test-only sources', () => {
+ const result = model(`class Client {
+ private RestTemplate transport;
+ private OtherType fake;
+ void observe() {
+ // transport.getForObject("http://catalog", String.class);
+ log.info("http://catalog:8080/items");
+ fake.exchange("http://payment:8080/pay");
+ WebClient setup = WebClient.create("http://catalog:8080");
+ }
+}`, {
+ 'gateway/src/test/java/ClientTest.java': 'class ClientTest { RestTemplate transport; void test() { transport.getForObject("http://payment", String.class); } }',
+ });
+ expect(links(result)).toEqual([]);
+ });
+});
diff --git a/graph-ui/src/architecture/container-topology.ts b/graph-ui/src/architecture/container-topology.ts
new file mode 100644
index 000000000..51de635aa
--- /dev/null
+++ b/graph-ui/src/architecture/container-topology.ts
@@ -0,0 +1,691 @@
+import { isAlias, isMap, isScalar, isSeq, LineCounter, parseDocument } from 'yaml';
+import type { RouteGraphSnapshot } from './route-graph-source';
+
+export interface ServiceProject {
+ project: string;
+ rootPath: string;
+ manifest: string;
+ sources: ReadonlyMap<string, string>;
+ files: readonly string[];
+ routeGraph?: RouteGraphSnapshot;
+}
+export interface ServiceEvidence { project: string; path: string; line: number; summary: string }
+export interface ContainerService {
+ id: string;
+ name: string;
+ project: string;
+ manifest: string;
+ line: number;
+ image?: string;
+ buildContext?: string;
+ dockerfile?: string;
+ sourcePaths: string[];
+ networks: string[];
+ ports: string[];
+ profiles?: string[];
+}
+export interface ContainerConnection {
+ id: string;
+ source: string;
+ target: string;
+ kind: 'call' | 'configuration' | 'startup';
+ protocol: string;
+ evidence: ServiceEvidence[];
+}
+export interface ContainerTopology {
+ services: ContainerService[];
+ connections: ContainerConnection[];
+ warnings: string[];
+ unresolved: ServiceEvidence[];
+}
+
+const MAX_MANIFEST = 256 * 1024;
+const MAX_SOURCE = 256 * 1024;
+const MAX_TOTAL_SOURCE = 4 * 1024 * 1024;
+const MAX_FILES = 4_000;
+const MAX_SERVICES = 128;
+const MAX_CONNECTIONS = 2048;
+const NAME = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
+const ENDPOINT_KEY = /(?:HOST|HOSTNAME|ADDR|ADDRESS|ENDPOINT|URL|URI|SERVER|SERVERS|CONNECTION(?:_?STRING)?|BROKERS?|BOOTSTRAP_SERVERS)$/i;
+const PRIVATE_KEY = /PASSWORD|SECRET|TOKEN|CREDENTIAL|API_?KEY/i;
+const CODE_FILE = /\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|kts|cs|fs|rb|php|[ch](?:pp|xx)?|scala|swift)$/i;
+const str = (node: unknown): string | undefined => isScalar(node)
+ && ['string', 'number', 'boolean'].includes(typeof node.value) ? String(node.value) : undefined;
+const entries = (node: unknown): [string, unknown][] => isMap(node)
+ ? node.items.flatMap(pair => { const key = str(pair.key); return key === undefined ? [] : [[key, pair.value]]; }) : [];
+const field = (node: unknown, key: string): unknown => entries(node).find(entry => entry[0] === key)?.[1];
+const list = (node: unknown): string[] => isSeq(node) ? node.items.flatMap(item => str(item) ?? []) : [];
+const tidy = (value: string): string => value.replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 180);
+const unique = <T>(values: T[]): T[] => [...new Set(values)];
+const idPart = (value: string): string => encodeURIComponent(value);
+
+function normal(path: string): string {
+ const absolute = path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path);
+ const result: string[] = [];
+ for (const part of path.replaceAll('\\', '/').split('/')) {
+ if (!part || part === '.') continue;
+ if (part === '..' && result.length && result.at(-1) !== '..') result.pop();
+ else if (part !== '..' || !absolute) result.push(part);
+ }
+ return `${path.startsWith('/') ? '/' : ''}${result.join('/')}`;
+}
+const directory = (path: string): string => normal(path).slice(0, normal(path).lastIndexOf('/'));
+export const normalizeSourcePath = (root: string, path: string): string => normal(path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path)
+ ? path : `${root}/${path}`);
+const absolute = normalizeSourcePath;
+const inside = (path: string, parent: string): boolean => path === parent || path.startsWith(`${parent}/`);
+const dynamic = (value: string): boolean => /\$|\{\{|\}\}|%[A-Z_]+%/.test(value);
+function lineOf(node: unknown, counter: LineCounter): number {
+ if (node && typeof node === 'object' && 'range' in node && Array.isArray(node.range)) {
+ return counter.linePos(Number(node.range[0])).line;
+ }
+ return 1;
+}
+interface FileSource { project: ServiceProject; path: string; absolute: string; text?: string }
+interface ParsedService {
+ view: ContainerService;
+ input: ServiceProject;
+ node: unknown;
+ counter: LineCounter;
+ aliases: Map<string, string[]>;
+ environment: Map<string, { value: string; line: number }>;
+ prefixes: string[];
+}
+interface Endpoint { host: string; protocol: string }
+
+function protocolFor(hint: string): string {
+ if (/redis/i.test(hint)) return 'redis';
+ if (/postgres|pgsql/i.test(hint)) return 'postgres';
+ if (/mysql/i.test(hint)) return 'mysql';
+ if (/mongo/i.test(hint)) return 'mongodb';
+ if (/kafka|broker|bootstrap/i.test(hint)) return 'kafka';
+ if (/amqp|rabbit/i.test(hint)) return 'amqp';
+ if (/grpc/i.test(hint)) return 'grpc';
+ if (/http|fetch|axios|urlopen|requests\./i.test(hint)) return 'http';
+ return 'tcp';
+}
+/** Values are examined only in endpoint-bearing configuration or network-call arguments. */
+function endpoints(value: string, hint: string, bare: boolean): Endpoint[] {
+ if (dynamic(value) || value.length > 4096) return [];
+ const result: Endpoint[] = [];
+ for (const match of value.matchAll(/\b(https?|grpcs?|rediss?|postgres(?:ql)?|mysql|mongodb(?:\+srv)?|amqps?|kafka):\/\/(?:[^\s/@]*@)?([a-zA-Z0-9][a-zA-Z0-9_.-]*)(?=[:/?#\s]|$)/g)) {
+ result.push({ host: match[2].toLowerCase(), protocol: match[1].replace('postgresql', 'postgres') });
+ }
+ if (result.length) return result;
+ const connectionHost = /(?:^|;)\s*(?:Server|Host|Data Source)\s*=\s*([a-zA-Z0-9][a-zA-Z0-9_.-]*)(?:[:,]\d+)?\s*(?:;|$)/i.exec(value);
+ if (connectionHost) return [{ host: connectionHost[1].toLowerCase(), protocol: protocolFor(hint) }];
+ if (bare) for (const part of value.split(',')) {
+ const match = /^\s*([a-zA-Z0-9][a-zA-Z0-9_.-]*)(?::\d+)?\s*$/.exec(part);
+ if (match) result.push({ host: match[1].toLowerCase(), protocol: protocolFor(hint) });
+ }
+ return result;
+}
+
+function validateDocument(root: unknown): void {
+ let count = 0;
+ const walk = (node: unknown, depth: number): void => {
+ if (++count > 15_000 || depth > 40) throw new Error('YAML structure exceeds the analysis limit');
+ if (isAlias(node)) throw new Error('YAML aliases are not supported');
+ if (isMap(node)) for (const pair of node.items) {
+ if (str(pair.key) === '<<') throw new Error('YAML merge keys are not supported');
+ if (!isScalar(pair.key) || typeof pair.key.value !== 'string') throw new Error('YAML mapping keys must be strings');
+ walk(pair.value, depth + 1);
+ }
+ else if (isSeq(node)) for (const item of node.items) walk(item, depth + 1);
+ };
+ walk(root, 0);
+}
+
+function parseServices(input: ServiceProject, warnings: string[]): ParsedService[] {
+ if (!input.manifest) return [];
+ const manifestPath = absolute(input.rootPath, input.manifest);
+ const source = [...input.sources].find(([path]) => absolute(input.rootPath, path) === manifestPath)?.[1];
+ const warn = (message: string): void => { warnings.push(`${tidy(input.project)}/${tidy(input.manifest)}: ${message}.`); };
+ if (source === undefined) { warn('Compose source is unavailable'); return []; }
+ if (source.length > MAX_MANIFEST) { warn('Compose source exceeds the 256 KiB analysis limit'); return []; }
+ const counter = new LineCounter();
+ let document;
+ try {
+ document = parseDocument(source, { lineCounter: counter, uniqueKeys: true, merge: false, prettyErrors: false });
+ // Parser diagnostics can contain source values. Never copy them into the public result.
+ if (document.errors.length || document.warnings.length) { warn('Compose YAML is invalid or uses unsupported syntax'); return []; }
+ validateDocument(document.contents);
+ } catch (error) {
+ warn(error instanceof Error && error.message.startsWith('YAML ') ? error.message : 'Compose YAML could not be safely parsed');
+ return [];
+ }
+ if (field(document.contents, 'include') !== undefined) { warn('Compose include is unsupported; this manifest was omitted'); return []; }
+ const serviceMap = field(document.contents, 'services');
+ if (!isMap(serviceMap)) { warn('No services mapping was found'); return []; }
+ const networkMap = field(document.contents, 'networks');
+ const scope = `${idPart(input.project)}:${idPart(normal(input.manifest))}`;
+ const services: ParsedService[] = [];
+ for (const [name, node] of entries(serviceMap).slice(0, MAX_SERVICES)) {
+ if (!NAME.test(name) || !isMap(node)) { warn('A service declaration has an invalid name or shape'); continue; }
+ if (field(node, 'extends') !== undefined) { warn(`Service ${tidy(name)} uses unsupported extends and was omitted`); continue; }
+ const networkMode = str(field(node, 'network_mode'));
+ const networkNode = field(node, 'networks');
+ const networkKeys = networkMode ? [] : networkNode === undefined ? ['default']
+ : isSeq(networkNode) ? list(networkNode) : entries(networkNode).map(([key]) => key);
+ const aliases = new Map<string, string[]>();
+ const networks: string[] = [];
+ for (const key of networkKeys) {
+ const config = field(networkMap, key);
+ const configuredName = str(field(config, 'name'));
+ const external = str(field(config, 'external')) === 'true';
+ const networkName = configuredName ?? key;
+ if (dynamic(networkName) || !NAME.test(networkName)) { warn(`Service ${name} has an unresolved network name`); continue; }
+ const identity = configuredName || external ? `shared:${networkName}` : `local:${scope}:${key}`;
+ networks.push(identity);
+ const containerName = str(field(node, 'container_name'));
+ const declaredAliases = list(field(field(networkNode, key), 'aliases'));
+ aliases.set(identity, unique([name, ...(containerName && NAME.test(containerName) ? [containerName] : []),
+ ...declaredAliases.filter(alias => NAME.test(alias) && !dynamic(alias))].map(alias => alias.toLowerCase())));
+ }
+ if (networkMode) warn(`Service ${name} uses network_mode; its Docker DNS links are not inferred`);
+ const build = field(node, 'build');
+ const context = str(build) ?? str(field(build, 'context')) ?? (isMap(build) ? '.' : undefined);
+ const localContext = context !== undefined && !dynamic(context) && !/^[a-zA-Z]+:\/\/|^git@/.test(context)
+ ? absolute(directory(manifestPath), context) : undefined;
+ if (context && !localContext) warn(`Service ${name} has a remote or unresolved build context`);
+ const dockerfileName = str(field(build, 'dockerfile')) ?? 'Dockerfile';
+ const dockerfile = localContext && !dynamic(dockerfileName) ? absolute(localContext, dockerfileName) : undefined;
+ const environment = new Map<string, { value: string; line: number }>();
+ const envNode = field(node, 'environment');
+ for (const [key, value] of entries(envNode)) {
+ const scalar = str(value);
+ if (!PRIVATE_KEY.test(key) && scalar !== undefined) environment.set(key, { value: scalar, line: lineOf(value, counter) });
+ }
+ if (isSeq(envNode)) for (const item of envNode.items) {
+ const value = str(item), index = value?.indexOf('=') ?? -1;
+ if (value && index > 0 && !PRIVATE_KEY.test(value.slice(0, index))) {
+ environment.set(value.slice(0, index), { value: value.slice(index + 1), line: lineOf(item, counter) });
+ }
+ }
+ if (field(node, 'env_file') !== undefined) warn(`Service ${name} uses env_file; external environment values are not read`);
+ const portsNode = field(node, 'ports');
+ const ports = isSeq(portsNode) ? portsNode.items.flatMap(port => {
+ const value = str(port);
+ if (value && !dynamic(value) && /^[\d.:/a-z[\]-]+$/i.test(value)) return [value];
+ const published = str(field(port, 'published')), target = str(field(port, 'target'));
+ const protocol = str(field(port, 'protocol')) ?? 'tcp';
+ return target && /^\d+$/.test(target) && (!published || /^\d+(?:-\d+)?$/.test(published)) && /^(tcp|udp)$/.test(protocol)
+ ? [`${published ? `${published}:` : ''}${target}/${protocol}`] : [];
+ }) : [];
+ const image = str(field(node, 'image'));
+ services.push({ input, node, counter, environment, aliases, prefixes: [], view: {
+ id: `service:${scope}:${idPart(name)}`, name, project: input.project, manifest: input.manifest,
+ line: lineOf(node, counter), image: image && !dynamic(image) ? tidy(image) : undefined,
+ buildContext: localContext, dockerfile, sourcePaths: [], networks: unique(networks), ports,
+ profiles: list(field(node, 'profiles')).filter(profile => NAME.test(profile)),
+ } });
+ }
+ if (entries(serviceMap).length > MAX_SERVICES) warn(`Only the first ${MAX_SERVICES} service declarations were analyzed`);
+ return services;
+}
+
+/** A root build context is ownership evidence only when COPY names a specific local subtree/file. */
+function copyPrefixes(text: string, context: string): string[] {
+ const result: string[] = [];
+ for (const line of text.split('\n')) {
+ const match = /^\s*COPY\s+(.+)$/i.exec(line);
+ if (!match || /--from(?:=|\s)/i.test(match[1])) continue;
+ const args = match[1].replace(/--[\w-]+=\S+\s*/g, '').trim();
+ let words: string[];
+ try {
+ const parsed: unknown = args.startsWith('[') ? JSON.parse(args) : args.match(/"[^"]*"|'[^']*'|\S+/g);
+ if (!Array.isArray(parsed) || !parsed.every(value => typeof value === 'string')) continue;
+ words = (parsed as string[]).map(value => value.replace(/^["']|["']$/g, ''));
+ } catch { continue; }
+ for (const path of words.slice(0, -1)) {
+ if (dynamic(path) || /[*?\[\]]|^\.\.?\/?$|^\/|^https?:/.test(path)) continue;
+ const resolved = absolute(context, path);
+ if (resolved !== context && inside(resolved, context)) result.push(resolved);
+ }
+ }
+ return unique(result);
+}
+
+interface Literal { start: number; end: number; value: string }
+/** Keep offsets, erase comments and literals from syntax matching, and never evaluate source. */
+function sourceSyntax(source: string): { code: string; literals: Literal[] } {
+ const output = source.split('');
+ const literals: Literal[] = [];
+ let index = 0;
+ while (index < source.length) {
+ const start = index;
+ if (source[index] === '#' || source.slice(index, index + 2) === '//') {
+ while (index < source.length && source[index] !== '\n') output[index++] = ' ';
+ } else if (source.slice(index, index + 2) === '/*') {
+ const end = source.indexOf('*/', index + 2);
+ index = end < 0 ? source.length : end + 2;
+ for (let i = start; i < index; i++) if (source[i] !== '\n') output[i] = ' ';
+ } else if ('"\'`'.includes(source[index])) {
+ const quote = source[index++];
+ while (index < source.length) {
+ if (source[index] === '\\') { index += 2; continue; }
+ if (source[index++] === quote) break;
+ }
+ index = Math.min(index, source.length);
+ if (source[index - 1] === quote) literals.push({ start, end: index, value: source.slice(start + 1, index - 1).replace(/\\(["'\\])/g, '$1') });
+ for (let i = start; i < index; i++) if (source[i] !== '\n') output[i] = ' ';
+ } else index++;
+ }
+ return { code: output.join(''), literals };
+}
+interface Call { name: string; start: number; open: number; end: number; firstEnd: number }
+function callsIn(code: string): Call[] {
+ const closing = new Map<number, number>(), stack: number[] = [];
+ for (let i = 0; i < code.length; i++) {
+ if (code[i] === '(') stack.push(i);
+ else if (code[i] === ')' && stack.length) closing.set(stack.pop()!, i);
+ }
+ const calls: Call[] = [];
+ for (const match of code.matchAll(/\b([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/g)) {
+ const open = match.index + match[0].lastIndexOf('('), end = closing.get(open);
+ if (end === undefined || end - open > 8192) continue;
+ let nesting = 0, firstEnd = end;
+ for (let i = open + 1; i < end; i++) {
+ if ('([{'.includes(code[i])) nesting++;
+ else if (')]}'.includes(code[i])) nesting--;
+ else if (code[i] === ',' && nesting === 0) { firstEnd = i; break; }
+ }
+ calls.push({ name: match[1].replaceAll(/\s/g, ''), start: match.index, open, end, firstEnd });
+ }
+ return calls;
+}
+function networkCall(name: string): boolean {
+ return /^(?:fetch|axios|urlopen|Redis|StrictRedis|MongoClient|Pool|NpgsqlConnection|SqlConnection|Kafka|KafkaProducer|KafkaConsumer)$/i.test(name)
+ || /^(?:redis\.(?:Redis|StrictRedis)|pg\.Pool|pymongo\.MongoClient)$/.test(name)
+ || /^(?:requests|http|https|axios|urllib\.request|urllib3|grpc|redis|psycopg2?|pymysql|mysql|amqp|amqplib|net|socket|ConnectionMultiplexer|Dns)\./i.test(name)
+ && /(?:get|post|put|patch|delete|request|urlopen|dial|newclient|connect|connectasync|createclient|createconnection|insecure_channel|secure_channel|gethostentry(?:async)?)$/i.test(name);
+}
+const wordIn = (code: string, name: string): boolean => new RegExp(`\\b${name.replace(/[$]/g, '\\$&')}\\b`).test(code);
+interface Wrapper { parameter: number; hint: string }
+/** Bounded local argument propagation to known transport APIs, not a function-name dictionary. */
+function connectionWrappers(code: string, calls: Call[]): Map<string, Wrapper> {
+ const result = new Map<string, Wrapper>();
+ const definitions = new Set<string>(), ambiguous = new Set<string>();
+ for (const candidate of calls) {
+ const after = /^\s*\{/.exec(code.slice(candidate.end + 1));
+ if (!after || candidate.name.includes('.') || /^(if|for|while|switch|catch)$/.test(candidate.name)) continue;
+ if (definitions.has(candidate.name)) { ambiguous.add(candidate.name); result.delete(candidate.name); continue; }
+ definitions.add(candidate.name);
+ const bodyStart = candidate.end + 1 + after[0].length;
+ let depth = 1, bodyEnd = bodyStart;
+ while (bodyEnd < code.length && bodyEnd - bodyStart < 16_384 && depth) {
+ if (code[bodyEnd] === '{') depth++;
+ if (code[bodyEnd++] === '}') depth--;
+ }
+ if (depth) continue;
+ const body = code.slice(bodyStart, bodyEnd);
+ const sinks = calls.filter(call => call.start >= bodyStart && call.end < bodyEnd && networkCall(call.name));
+ if (!sinks.length) continue;
+ const parameters = code.slice(candidate.open + 1, candidate.end).split(',').map(part => part.trim().match(/[A-Za-z_$][\w$]*$/)?.[0]);
+ for (let parameter = 0; parameter < parameters.length; parameter++) {
+ const name = parameters[parameter];
+ if (!name) continue;
+ const tainted = new Set([name]);
+ for (let pass = 0; pass < 3; pass++) {
+ for (const assignment of body.matchAll(/\b([A-Za-z_$][\w$]*)\s*=\s*([^;\n]+)[;\n]/g)) {
+ if ([...tainted].some(value => wordIn(assignment[2], value))) tainted.add(assignment[1]);
+ }
+ }
+ const sink = sinks.find(call => [...tainted].some(value => wordIn(code.slice(call.open + 1, call.firstEnd), value)));
+ if (sink) { result.set(candidate.name, { parameter, hint: sink.name }); break; }
+ }
+ }
+ for (const name of ambiguous) result.delete(name);
+ return result;
+}
+interface SourceEndpoint { endpoint: Endpoint; line: number; via: string }
+
+interface StaticString { prefix: string; complete: boolean }
+interface JavaScope { start: number; end: number; parent?: JavaScope; method?: Call; parameters: string[] }
+interface JavaBinding { name: string; start: number; expressionStart: number; end: number; declaration: boolean; scope: JavaScope }
+interface JavaReceiver { name: string; type: string; start: number; end: number; scope: JavaScope }
+
+/** Small static string interpreter for typed Spring call sites, never a general Java evaluator. */
+function springEndpoints(text: string, code: string, literals: Literal[], calls: Call[]): SourceEndpoint[] {
+ const literalAt = new Map(literals.map(literal => [literal.start, literal]));
+ const literalEnding = new Set(literals.map(literal => literal.end));
+ const delimiters = new Map<number, number>(), delimiterStack: number[] = [];
+ for (let index = 0; index < code.length; index++) {
+ if ('([{'.includes(code[index])) delimiterStack.push(index);
+ else if (')]}'.includes(code[index]) && delimiterStack.length) delimiters.set(delimiterStack.pop()!, index);
+ }
+ const root: JavaScope = { start: -1, end: code.length, parameters: [] };
+ const scopes: JavaScope[] = [root], stack = [root];
+ const methodsAt = new Map<number, Call>();
+ for (const call of calls) {
+ const following = /^\s*\{/.exec(code.slice(call.end + 1));
+ if (following && !call.name.includes('.') && !/^(?:if|for|while|switch|catch|synchronized)$/.test(call.name)) {
+ methodsAt.set(call.end + following[0].length, call);
+ }
+ }
+ for (let index = 0; index < code.length; index++) {
+ if (code[index] === '{') {
+ const method = methodsAt.get(index);
+ const parameters = method ? code.slice(method.open + 1, method.end).split(',')
+ .flatMap(parameter => parameter.trim().match(/([A-Za-z_$][\w$]*)\s*(?:\[\])?$/)?.[1] ?? []) : [];
+ const scope: JavaScope = { start: index, end: delimiters.get(index) ?? code.length,
+ parent: stack.at(-1), method, parameters };
+ scopes.push(scope); stack.push(scope);
+ } else if (code[index] === '}' && stack.length > 1) stack.pop();
+ }
+ const scopeAt = (position: number): JavaScope => {
+ let result = root;
+ for (const scope of scopes) if (scope.start < position && position < scope.end && scope.start > result.start) result = scope;
+ return result;
+ };
+ const containsScope = (parent: JavaScope, child: JavaScope): boolean => parent.start <= child.start && child.end <= parent.end;
+ const trim = (start: number, end: number): [number, number] => {
+ while (start < end && /\s/.test(code[start]) && !literalAt.has(start)) start++;
+ while (end > start && /\s/.test(code[end - 1]) && !literalEnding.has(end)) end--;
+ return [start, end];
+ };
+ const split = (start: number, end: number, separator: string): [number, number][] => {
+ const parts: [number, number][] = [];
+ let beginning = start;
+ for (let index = start; index < end; index++) {
+ const close = delimiters.get(index);
+ if (close !== undefined && close < end) { index = close; continue; }
+ if (code[index] === separator) { parts.push([beginning, index]); beginning = index + 1; }
+ }
+ parts.push([beginning, end]);
+ return parts;
+ };
+ const bindings: JavaBinding[] = [];
+ for (const match of code.matchAll(/(?<![\w$.])(?:(?:final\s+)?(?:String|URI|URL|var)\s+)?(?:this\.)?([A-Za-z_$][\w$]*)\s*=(?!=)\s*/g)) {
+ const expressionStart = match.index + match[0].lastIndexOf('=') + 1;
+ const end = code.indexOf(';', expressionStart);
+ if (end < 0 || end - expressionStart > 8192) continue;
+ bindings.push({ name: match[1], start: match.index, expressionStart, end,
+ declaration: /^(?:final\s+)?(?:String|URI|URL|var)\s/.test(match[0]), scope: scopeAt(match.index) });
+ }
+ const receivers: JavaReceiver[] = [];
+ for (const match of code.matchAll(/\b(RestTemplate|RestOperations|WebClient)\s+([A-Za-z_$][\w$]*)\b/g)) {
+ receivers.push({ type: match[1], name: match[2], start: match.index,
+ end: match.index + match[0].length, scope: scopeAt(match.index) });
+ }
+ const receiverAt = (name: string, position: number): JavaReceiver | undefined => receivers
+ .filter(receiver => receiver.name === name && receiver.start < position && containsScope(receiver.scope, scopeAt(position)))
+ .sort((left, right) => right.scope.start - left.scope.start || right.start - left.start)[0];
+ const helpers = new Map<string, { scope: JavaScope; start: number; end: number }>();
+ const methodNames = new Set<string>(), ambiguousHelpers = new Set<string>();
+ for (const scope of scopes) {
+ const method = scope.method;
+ if (!method) continue;
+ if (methodNames.has(method.name)) ambiguousHelpers.add(method.name);
+ methodNames.add(method.name);
+ if (!/\bString\s+$/.test(code.slice(Math.max(0, method.start - 120), method.start))) continue;
+ const body = code.slice(scope.start + 1, scope.end);
+ const returned = /^\s*return\b([^;]*);\s*$/.exec(body);
+ if (returned) {
+ const start = scope.start + 1 + returned[0].indexOf('return') + 6;
+ helpers.set(method.name, { scope, start, end: code.indexOf(';', start) });
+ }
+ }
+ for (const name of ambiguousHelpers) helpers.delete(name);
+ let budget = 20_000;
+ const unknown = (): StaticString => ({ prefix: '', complete: false });
+ const evaluate = (start: number, end: number, before: number, scope: JavaScope,
+ parameters = new Map<string, StaticString>(), depth = 0): StaticString => {
+ if (--budget < 0 || depth > 10 || end - start > 8192) return unknown();
+ [start, end] = trim(start, end);
+ if (start >= end) return unknown();
+ if (code[start] === '(' && delimiters.get(start) === end - 1) return evaluate(start + 1, end - 1, before, scope, parameters, depth + 1);
+ const parts = split(start, end, '+');
+ if (parts.length > 1) {
+ let prefix = '';
+ for (const [partStart, partEnd] of parts) {
+ const part = evaluate(partStart, partEnd, before, scope, parameters, depth + 1);
+ prefix += part.prefix;
+ if (prefix.length > 4096) return unknown();
+ if (!part.complete) return { prefix, complete: false };
+ }
+ return { prefix, complete: true };
+ }
+ const literal = literalAt.get(start);
+ if (literal?.end === end) return { prefix: literal.value, complete: true };
+ const expression = code.slice(start, end);
+ const variable = /^(?:this\.)?([A-Za-z_$][\w$]*)$/.exec(expression);
+ if (variable) {
+ const name = variable[1];
+ if (parameters.has(name)) return parameters.get(name)!;
+ const visible = bindings.filter(binding => binding.name === name && binding.start < before && containsScope(binding.scope, scope));
+ const declaration = visible.filter(binding => binding.declaration)
+ .sort((left, right) => right.scope.start - left.scope.start || right.start - left.start)[0];
+ for (let current: JavaScope | undefined = scope; current; current = current.parent) {
+ if (current.parameters.includes(name) && (!declaration || declaration.scope.start <= current.start)) return unknown();
+ }
+ if (!declaration) return unknown();
+ // Writes in a conditional/loop cannot be ordered as one unconditional destination.
+ if (bindings.some(binding => binding.name === name && !binding.declaration && binding.start > declaration.start
+ && binding.start < before && containsScope(declaration.scope, binding.scope) && binding.scope !== declaration.scope)) return unknown();
+ const binding = visible.filter(candidate => candidate.scope === declaration.scope && candidate.start >= declaration.start)
+ .sort((left, right) => right.start - left.start)[0];
+ return binding ? evaluate(binding.expressionStart, binding.end, binding.start, binding.scope, parameters, depth + 1) : unknown();
+ }
+ const invocation = /^(?:new\s+)?((?:this\.)?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/.exec(expression);
+ if (invocation) {
+ const open = start + invocation[0].lastIndexOf('(');
+ if (delimiters.get(open) !== end - 1) return unknown();
+ const argumentsList = split(open + 1, end - 1, ',');
+ if (/^(?:URI\.create|URI|URL)$/.test(invocation[1]) && argumentsList.length === 1) {
+ return evaluate(...argumentsList[0], before, scope, parameters, depth + 1);
+ }
+ const helper = helpers.get(invocation[1].replace(/^this\./, ''));
+ if (helper && helper.scope.parameters.length === argumentsList.length) {
+ const values = new Map<string, StaticString>();
+ argumentsList.forEach(([a, b], index) => values.set(helper.scope.parameters[index], evaluate(a, b, before, scope, parameters, depth + 1)));
+ return evaluate(helper.start, helper.end, helper.start, helper.scope, values, depth + 1);
+ }
+ }
+ return unknown();
+ };
+ const result: SourceEndpoint[] = [];
+ const emit = (value: StaticString, position: number, via: string): void => {
+ // A runtime suffix is safe only after the entire URI authority is visibly delimited.
+ if (!value.complete && !/^https?:\/\/[^/?#\s]+[/?#]/.test(value.prefix)) return;
+ for (const endpoint of endpoints(value.prefix, 'http', false)) result.push({ endpoint,
+ line: text.slice(0, position).split('\n').length, via });
+ };
+ for (const call of calls) {
+ const method = /^(?:this\.)?([A-Za-z_$][\w$]*)\.(getForObject|getForEntity|postForObject|postForEntity|postForLocation|put|patchForObject|delete|exchange|execute|optionsForAllow|headForHeaders)$/.exec(call.name);
+ if (!method) continue;
+ const receiver = receiverAt(method[1], call.start);
+ if (!receiver || !/^Rest(?:Template|Operations)$/.test(receiver.type)) continue;
+ emit(evaluate(call.open + 1, call.firstEnd, call.start, scopeAt(call.start)), call.start, 'Spring HTTP call');
+ }
+ for (const match of code.matchAll(/\b((?:this\.)?[A-Za-z_$][\w$]*)\s*\.\s*(?:get|post|put|patch|delete|head|options)\s*\(\s*\)\s*\.\s*uri\s*\(/g)) {
+ const receiver = receiverAt(match[1].replace(/^this\./, ''), match.index);
+ if (receiver?.type !== 'WebClient') continue;
+ const open = match.index + match[0].lastIndexOf('('), call = calls.find(candidate => candidate.open === open);
+ if (!call) continue;
+ let value = evaluate(open + 1, call.firstEnd, match.index, scopeAt(match.index));
+ if (value.prefix.startsWith('/')) {
+ const initializer = /^\s*=\s*WebClient\s*\.\s*create\s*\(/.exec(code.slice(receiver.end));
+ if (!initializer) continue;
+ const baseOpen = receiver.end + initializer[0].lastIndexOf('('), baseEnd = delimiters.get(baseOpen);
+ if (baseEnd === undefined) continue;
+ const base = evaluate(baseOpen + 1, baseEnd, receiver.start, receiver.scope);
+ if (!base.complete) continue;
+ value = { prefix: base.prefix.replace(/\/$/, '') + value.prefix, complete: value.complete };
+ }
+ emit(value, match.index, 'Spring WebClient HTTP request');
+ }
+ return result;
+}
+function codeEndpoints(text: string, service: ParsedService, path: string): SourceEndpoint[] {
+ const { code, literals } = sourceSyntax(text);
+ const calls = callsIn(code), wrappers = connectionWrappers(code, calls);
+ const found: SourceEndpoint[] = /\.java$/i.test(path) ? springEndpoints(text, code, literals, calls) : [];
+ for (const call of calls) {
+ const wrapper = wrappers.get(call.name);
+ if (!networkCall(call.name) && !wrapper) continue;
+ // Function declarations are not executed calls. Only first-argument wrappers are supported.
+ if (/^\s*\{/.test(code.slice(call.end + 1)) || (wrapper && wrapper.parameter !== 0)) continue;
+ const hint = wrapper?.hint ?? call.name;
+ const argument = text.slice(call.open + 1, call.firstEnd);
+ let low = 0, high = literals.length;
+ while (low < high) { const mid = (low + high) >>> 1; if (literals[mid].start <= call.open) low = mid + 1; else high = mid; }
+ for (let index = low; index < literals.length && literals[index].start < call.firstEnd; index++) {
+ const literal = literals[index];
+ if (literal.end > call.firstEnd) continue;
+ const prefix = code.slice(call.open + 1, literal.start);
+ const hasField = /\b(?:host|hostname|address|addr|url|uri|endpoint|connectionString|connection_string|server)\s*[:=]\s*$/i.test(prefix);
+ const firstValue = !prefix.trim();
+ if (!firstValue && !hasField) continue;
+ for (const endpoint of endpoints(literal.value, hint, hasField || Boolean(wrapper) || !/fetch|axios|requests|http|urlopen/i.test(hint))) {
+ found.push({ endpoint, line: text.slice(0, literal.start).split('\n').length, via: wrapper ? 'local connection wrapper' : 'network call' });
+ }
+ }
+ // Explicit Compose values can resolve a directly used environment variable; no shell expansion or defaults.
+ for (const match of argument.matchAll(/(?:process\.env\.([A-Za-z_]\w*)|(?:getenv|GetEnvironmentVariable|Getenv|env::var|env\.var)\s*\(\s*["']([A-Za-z_]\w*)["']|process\.env\[\s*["']([A-Za-z_]\w*)["'])/g)) {
+ const key = match[1] ?? match[2] ?? match[3], configured = service.environment.get(key);
+ if (!configured || !ENDPOINT_KEY.test(key)) continue;
+ for (const endpoint of endpoints(configured.value, key, true)) found.push({ endpoint,
+ line: text.slice(0, call.start).split('\n').length, via: `network call using ${tidy(key)}` });
+ }
+ }
+ return found;
+}
+
+/** Read-only static evidence. No Docker, shell expansion, .env loading, or runtime traffic is involved. */
+export function buildContainerTopology(projects: readonly ServiceProject[]): ContainerTopology {
+ const warnings: string[] = [], unresolved: ServiceEvidence[] = [];
+ const parsed = projects.flatMap(project => parseServices(project, warnings));
+ const services = parsed.slice(0, MAX_SERVICES);
+ if (parsed.length > MAX_SERVICES) warnings.push(`Only the first ${MAX_SERVICES} services across selected projects were analyzed.`);
+ const files = new Map<string, FileSource>();
+ let bytes = 0, limited = false;
+ for (const project of projects) {
+ const sourceByPath = new Map([...project.sources].map(([path, text]) => [absolute(project.rootPath, path), text]));
+ for (const path of unique([...project.files, ...project.sources.keys()])) {
+ if (/(?:^|\/)\.env(?:\.|$)/i.test(path)) continue;
+ const abs = absolute(project.rootPath, path);
+ const key = `${project.project}\0${abs}`;
+ if (files.has(key)) continue;
+ if (files.size >= MAX_FILES) { limited = true; continue; }
+ const value = sourceByPath.get(abs);
+ const text = value !== undefined && value.length <= MAX_SOURCE && bytes + value.length <= MAX_TOTAL_SOURCE ? value : undefined;
+ if (text !== undefined) bytes += text.length;
+ else if (value !== undefined) limited = true;
+ const root = normal(project.rootPath);
+ files.set(key, { project, path: inside(abs, root) ? abs.slice(root.length + 1) : normal(path), absolute: abs, text });
+ }
+ }
+ if (limited) warnings.push('Source analysis reached its file or size limit; some call evidence is unavailable.');
+ const fileList = [...files.values()];
+ for (const service of services) {
+ const context = service.view.buildContext;
+ if (!context) continue;
+ const selectedRoots = unique(projects.map(project => normal(project.rootPath)));
+ const contained = selectedRoots.some(root => inside(context, root));
+ if (!contained) { warnings.push(`Service ${service.view.name}: build context is outside selected indexed projects.`); continue; }
+ if (!selectedRoots.includes(context)) service.prefixes = [context];
+ else {
+ const dockerfile = fileList.find(file => file.absolute === service.view.dockerfile)?.text;
+ service.prefixes = dockerfile ? copyPrefixes(dockerfile, context) : [];
+ if (!service.prefixes.length) warnings.push(`Service ${service.view.name}: root build context does not identify a specific source subtree.`);
+ }
+ }
+ const owners = new Map<string, ParsedService>();
+ let ambiguous = 0;
+ for (const file of fileList) {
+ const candidates = services.filter(service => service.prefixes.some(prefix => inside(file.absolute, prefix)));
+ if (candidates.length === 1) {
+ owners.set(`${file.project.project}\0${file.absolute}`, candidates[0]);
+ candidates[0].view.sourcePaths.push(file.absolute);
+ } else if (candidates.length > 1) ambiguous++;
+ }
+ if (ambiguous) warnings.push(`${ambiguous} files belong to overlapping service build contexts; their call evidence was omitted.`);
+ const edges = new Map<string, ContainerConnection>();
+ const evidence = (service: ParsedService, line: number, summary: string): ServiceEvidence => ({
+ project: service.input.project, path: service.input.manifest, line, summary,
+ });
+ const add = (source: ParsedService, target: ParsedService, kind: ContainerConnection['kind'], protocol: string, proof: ServiceEvidence): void => {
+ if (source === target) return;
+ const id = `${source.view.id}->${target.view.id}:${kind}:${protocol}`;
+ const existing = edges.get(id);
+ if (existing) {
+ if (existing.evidence.length < 12 && !existing.evidence.some(item => item.project === proof.project && item.path === proof.path && item.line === proof.line && item.summary === proof.summary)) existing.evidence.push(proof);
+ } else if (edges.size < MAX_CONNECTIONS) {
+ edges.set(id, { id, source: source.view.id, target: target.view.id, kind, protocol, evidence: [proof] });
+ } else if (!warnings.includes('Connection analysis reached its 2048-link limit.')) {
+ warnings.push('Connection analysis reached its 2048-link limit.');
+ }
+ };
+ const connectHost = (source: ParsedService, endpoint: Endpoint, kind: 'call' | 'configuration', proof: ServiceEvidence): void => {
+ if (['localhost', '127.0.0.1', '0.0.0.0'].includes(endpoint.host)) return;
+ const linkTarget = list(field(source.node, 'links')).find(link => link.split(':')[1]?.toLowerCase() === endpoint.host)?.split(':')[0];
+ const targets = services.filter(target => source.view.networks.some(network => target.aliases.get(network)?.includes(endpoint.host)
+ || (target.input === source.input && target.view.name === linkTarget && target.view.networks.includes(network))));
+ if (targets.length === 1) {
+ const protocol = endpoint.protocol === 'tcp' ? protocolFor(targets[0].view.image ?? '') : endpoint.protocol;
+ add(source, targets[0], kind, protocol, proof);
+ } else unresolved.push({ ...proof, summary: targets.length ? `Ambiguous Docker DNS destination ${tidy(endpoint.host)}` : `No selected service on a shared network resolves ${tidy(endpoint.host)}` });
+ };
+ for (const service of services) {
+ const depends = field(service.node, 'depends_on');
+ const dependencies: [string, unknown][] = isSeq(depends) ? depends.items.flatMap(item => str(item) ? [[str(item)!, item]] : []) : entries(depends);
+ for (const [name, node] of dependencies) {
+ const target = services.find(candidate => candidate.input === service.input && candidate.view.name === name);
+ const proof = evidence(service, lineOf(node, service.counter), `Declared startup dependency on ${tidy(name)}`);
+ if (target) add(service, target, 'startup', 'startup', proof);
+ else unresolved.push({ ...proof, summary: `Startup dependency ${tidy(name)} is not present in this manifest` });
+ }
+ for (const link of list(field(service.node, 'links'))) {
+ const name = link.split(':')[0];
+ const target = services.find(candidate => candidate.input === service.input && candidate.view.name === name);
+ const proof = evidence(service, lineOf(field(service.node, 'links'), service.counter), `Declared service link to ${tidy(name)}`);
+ if (target && service.view.networks.some(network => target.view.networks.includes(network))) add(service, target, 'configuration', 'tcp', proof);
+ else unresolved.push(proof);
+ }
+ for (const [key, configured] of service.environment) {
+ if (!ENDPOINT_KEY.test(key) || /^(?:HOSTNAME|BIND_|LISTEN_|ADVERTISE_)/i.test(key)) continue;
+ if (dynamic(configured.value)) {
+ unresolved.push(evidence(service, configured.line, `Endpoint ${tidy(key)} contains unresolved variables`));
+ continue;
+ }
+ for (const endpoint of endpoints(configured.value, key, true)) connectHost(service, endpoint, 'configuration',
+ evidence(service, configured.line, `${tidy(key)} configures ${endpoint.protocol} destination ${tidy(endpoint.host)}`));
+ }
+ }
+ for (const file of fileList) {
+ const service = owners.get(`${file.project.project}\0${file.absolute}`);
+ if (!service || !file.text || !CODE_FILE.test(file.path) || /(?:^|\/)(?:test|tests|__tests__)(?:\/|$)/i.test(file.path)) continue;
+ for (const candidate of codeEndpoints(file.text, service, file.path)) connectHost(service, candidate.endpoint, 'call', {
+ project: file.project.project, path: file.path, line: candidate.line,
+ summary: `${candidate.via} references ${candidate.endpoint.protocol} destination ${tidy(candidate.endpoint.host)}`,
+ });
+ }
+ // Graph identities are project-scoped; paths must independently map to unambiguous service ownership.
+ for (const project of projects) {
+ if (project.routeGraph?.truncated) warnings.push(`${tidy(project.project)}: route graph evidence is incomplete.`);
+ if (project.routeGraph?.warnings.length) warnings.push(`${tidy(project.project)}: route graph reported unavailable or limited evidence.`);
+ for (const relationship of project.routeGraph?.relationships ?? []) {
+ if (relationship.type === 'HANDLES') continue;
+ const sourcePath = relationship.source.file_path;
+ if (!sourcePath) continue;
+ const source = owners.get(`${project.project}\0${absolute(project.rootPath, sourcePath)}`);
+ if (!source) continue;
+ const targetPath = relationship.target.file_path;
+ const target = targetPath ? owners.get(`${project.project}\0${absolute(project.rootPath, targetPath)}`) : undefined;
+ const proof: ServiceEvidence = { project: project.project, path: sourcePath,
+ line: relationship.source.start_line ?? 1, summary: `Indexed ${relationship.type} relationship` };
+ if (target && source.view.networks.some(network => target.view.networks.includes(network))) {
+ add(source, target, 'call', relationship.type === 'HTTP_CALLS' ? 'http' : 'async', proof);
+ } else {
+ // Relative URL paths are not a service identity and are deliberately never joined.
+ const hosts = endpoints(relationship.routePath ?? '', relationship.type === 'HTTP_CALLS' ? 'http' : '', false);
+ for (const endpoint of hosts) connectHost(source, endpoint, 'call', proof);
+ }
+ }
+ }
+ for (const service of services) service.view.sourcePaths = unique(service.view.sourcePaths).sort();
+ const seenUnresolved = new Set<string>();
+ return { services: services.map(service => service.view), connections: [...edges.values()], warnings: unique(warnings),
+ unresolved: unresolved.filter(item => { const key = JSON.stringify(item); if (seenUnresolved.has(key)) return false; seenUnresolved.add(key); return true; }).slice(0, 100) };
+}
diff --git a/graph-ui/src/architecture/hotspot-map.test.ts b/graph-ui/src/architecture/hotspot-map.test.ts
new file mode 100644
index 000000000..595afeae8
--- /dev/null
+++ b/graph-ui/src/architecture/hotspot-map.test.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from 'vitest';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import type { ArchitectureHotspot } from '../core/intelligence-provider';
+import { buildSemanticGraph } from './semantic-graph';
+import { buildHotspotGraph, collectHotspots, gravityPercent, gravityStrength, hotspotSignals, hotspotsForNode } from './hotspot-map';
+
+const node = (id: number, name: string, file: string): GraphNode => ({ id, name, qualified_name: `project.${name}`, label: 'Function', file_path: file, start_line: 10, end_line: 80, x: 0, y: 0, z: 0, size: 1, color: '' });
+const graph: GraphData = { nodes: [node(1, 'busy', 'src/api/busy.ts'), node(2, 'complex', 'src/api/complex.ts'), node(3, 'plain', 'other/plain.py')],
+ edges: [{ id: 5, source: 1, target: 2, type: 'CALLS' }], total_nodes: 3 };
+const findings: ArchitectureHotspot[] = [{ name: 'busy', qualifiedName: 'project.busy', fanIn: 100 },
+ { name: 'complex', qualifiedName: 'project.complex', complexity: 25, cognitive: 30 },
+ { name: 'plain', qualifiedName: 'project.plain', fanIn: 0, complexity: 0 }];
+
+describe('hotspot overlays and gravity', () => {
+ it('joins exact symbol identities and aggregates a folder by peak fan-in, not a misleading sum', () => {
+ const catalog = collectHotspots(findings, graph);
+ expect(catalog.findings).toHaveLength(2);
+ const overview = buildSemanticGraph(graph, { view: 'overview' });
+ const area = overview.nodes.find(node => node.areaPath === 'src/api')!;
+ expect(hotspotsForNode(area, catalog)).toMatchObject({ maxFanIn: 100, findings: expect.any(Array) });
+ expect(hotspotsForNode(area, catalog)?.findings).toHaveLength(2);
+ expect(catalog.byFile.get('src/api/complex.ts')?.maxFanIn).toBeUndefined();
+ });
+ it('does not turn complexity or missing fan-in into a gravity measurement', () => {
+ const catalog = collectHotspots(findings, graph);
+ expect(gravityStrength(catalog.byFile.get('src/api/complex.ts')!.maxFanIn, catalog.maxFanIn)).toBe(0);
+ expect(hotspotSignals(findings[1])).toEqual(['Complexity 25', 'Cognitive 30']);
+ expect(hotspotSignals({ name: 'zero', fanIn: 0 })).toEqual(['Fan-in 0']);
+ expect(hotspotSignals({ name: 'unknown' })).toEqual([]);
+ });
+ it('uses a bounded percentage field without changing semantic positions', () => {
+ const strengths = [0, 1, 10, 100, 1000000].map(count => gravityStrength(count, 1000000));
+ expect(strengths).toEqual([...strengths].sort((a, b) => a - b));
+ expect(strengths.every(value => value >= 0 && value <= 1)).toBe(true);
+ expect(gravityStrength(Infinity, 10)).toBe(0);
+ expect(gravityStrength(1e9, 100)).toBe(1);
+ expect(gravityPercent(100, 100)).toBe(100);
+ expect(gravityPercent(25, 100)).toBe(25);
+ expect(gravityPercent(0, 100)).toBe(0);
+ expect(gravityPercent(undefined, 100)).toBeUndefined();
+ expect(gravityStrength(1, 100)).toBeCloseTo(0.1);
+ expect(gravityStrength(25, 100)).toBeCloseTo(0.5);
+ expect(gravityStrength(1, 100)).toBeLessThan(gravityStrength(100, 100) / 5);
+ });
+ it('keeps actual hotspot nodes and exact edges, without inventing calls to missing identities', () => {
+ const catalog = collectHotspots([...findings, { name: 'outside', qualifiedName: 'project.outside', filePath: 'unloaded/source.ts', fanIn: 50 }], graph);
+ const model = buildHotspotGraph(graph, catalog);
+ expect(model.view).toBe('hotspots');
+ expect(model.nodes.find(node => node.graphNode?.id === 1)?.graphNode).toBe(graph.nodes[0]);
+ const outside = model.nodes.find(node => node.filePath === 'unloaded/source.ts')!;
+ expect(outside.graphNode).toBeUndefined();
+ expect(outside.members).toEqual([]);
+ expect(model.edges).toHaveLength(1);
+ expect(model.edges[0].evidence[0].id).toBe(5);
+ expect(model.edges[0].evidence[0].source).toBe(graph.nodes[0]);
+ });
+ it('preserves source metadata and source navigation under a file filter', () => {
+ const catalog = collectHotspots(findings, graph);
+ const model = buildHotspotGraph(graph, catalog, 'busy.ts');
+ expect(model.nodes).toHaveLength(1);
+ expect(model.nodes[0]).toMatchObject({ label: 'busy', filePath: 'src/api/busy.ts', line: 10 });
+ expect(model.edges).toEqual([]);
+ expect(catalog.maxFanIn).toBe(100);
+ });
+ it('keeps actual folder positions stable when text filters or hotspot rank change', () => {
+ const input: GraphData = { nodes: [node(1, 'busy', 'src/api/busy.ts'), node(2, 'complex', 'src/api/complex.ts'),
+ node(3, 'save', 'src/store/save.ts'), node(4, 'render', 'apps/web/render.ts')], edges: graph.edges, total_nodes: 4 };
+ const ranked = input.nodes.map((item, index) => ({ name: item.name, qualifiedName: item.qualified_name, fanIn: (index + 1) * 10 }));
+ const full = buildHotspotGraph(input, collectHotspots(ranked, input));
+ expect(full.platforms?.map(platform => platform.path).sort()).toEqual(['apps', 'apps/web', 'src', 'src/api', 'src/store']);
+ for (const item of full.nodes) {
+ const folder = full.platforms!.find(platform => platform.path === item.filePath!.slice(0, item.filePath!.lastIndexOf('/')))!;
+ expect(Math.abs(item.position[0] - folder.position[0]) + 10).toBeLessThanOrEqual(folder.width / 2);
+ expect(Math.abs(item.position[2] - folder.position[2]) + 10).toBeLessThanOrEqual(folder.depth / 2);
+ }
+ const filtered = buildHotspotGraph(input, collectHotspots(ranked, input), 'busy.ts');
+ expect(filtered.platforms?.map(platform => platform.path)).toEqual(['src', 'src/api']);
+ expect(filtered.nodes[0].position).toEqual(full.nodes.find(item => item.id === filtered.nodes[0].id)!.position);
+ const reordered = buildHotspotGraph(input, collectHotspots(ranked.map((finding, index) => ({ ...finding, fanIn: (ranked.length - index) * 100 })), input));
+ expect(reordered.nodes.map(item => item.id)).not.toEqual(full.nodes.map(item => item.id));
+ reordered.nodes.forEach(item => expect(item.position).toEqual(full.nodes.find(original => original.id === item.id)!.position));
+ expect(reordered.platforms).toEqual(full.platforms);
+ expect(reordered.edges).toEqual(full.edges);
+ expect(full.edges[0].evidence[0].source).toBe(input.nodes[0]);
+ });
+ it('retains the matching finding for an unresolved file while using its unfiltered placement', () => {
+ const input: GraphData = { nodes: [], edges: [], total_nodes: 0 };
+ const catalog = collectHotspots([{ name: 'first', filePath: 'src/api/file.ts', line: 2, fanIn: 100 },
+ { name: 'second', filePath: 'src/api/file.ts', line: 50, complexity: 20 },
+ { name: 'elsewhere', filePath: 'other/file.ts', fanIn: 5 }], input);
+ const full = buildHotspotGraph(input, catalog);
+ const filtered = buildHotspotGraph(input, catalog, 'second');
+ expect(filtered.nodes).toHaveLength(1);
+ expect(filtered.nodes[0]).toMatchObject({ line: 50, filePath: 'src/api/file.ts', graphNode: undefined });
+ expect(filtered.nodes[0].position).toEqual(full.nodes.find(item => item.filePath === 'src/api/file.ts')!.position);
+ expect(filtered.edges).toEqual([]);
+ });
+ it('does not guess a source file for an ambiguous qualified identity', () => {
+ const ambiguous = { ...graph, nodes: [...graph.nodes, { ...graph.nodes[0], id: 11, file_path: 'other/busy.ts' }], total_nodes: 4 };
+ const catalog = collectHotspots([findings[0]], ambiguous);
+ expect(catalog.findings[0].filePath).toBeUndefined();
+ expect(catalog.unmapped).toBe(1);
+ expect(buildHotspotGraph(ambiguous, catalog).nodes[0].graphNode).toBeUndefined();
+ });
+ it('does not attach an ambiguous pathless finding to a separately resolved method', () => {
+ const duplicate = { ...graph.nodes[0], id: 11, file_path: 'other/busy.ts' };
+ const ambiguous = { ...graph, nodes: [...graph.nodes, duplicate], total_nodes: 4 };
+ const explicit = { ...findings[0], filePath: 'src/api/busy.ts', fanIn: 5 };
+ const catalog = collectHotspots([findings[0], explicit], ambiguous);
+ const model = buildHotspotGraph(ambiguous, catalog);
+ const resolved = model.nodes.find(node => node.graphNode?.id === 1)!;
+ expect(hotspotsForNode(resolved, catalog)?.findings).toHaveLength(1);
+ expect(hotspotsForNode(resolved, catalog)?.maxFanIn).toBe(5);
+ });
+ it('distinguishes an unknown group fan-in from a measured zero', () => {
+ const catalog = collectHotspots([{ ...findings[1], fanIn: 0 }, { name: 'missing', filePath: 'other/missing.ts', complexity: 20 }], graph);
+ expect(catalog.byFile.get('src/api/complex.ts')?.maxFanIn).toBe(0);
+ expect(catalog.byFile.get('other/missing.ts')?.maxFanIn).toBeUndefined();
+ });
+});
diff --git a/graph-ui/src/architecture/hotspot-map.ts b/graph-ui/src/architecture/hotspot-map.ts
new file mode 100644
index 000000000..f66c8557b
--- /dev/null
+++ b/graph-ui/src/architecture/hotspot-map.ts
@@ -0,0 +1,126 @@
+import type { ArchitectureHotspot } from '../core/intelligence-provider';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import { layoutFolderHierarchy, pruneHierarchyPlatforms, type SemanticGraph, type SemanticNode } from './semantic-graph';
+import { areaOf } from './repository-map';
+import { hotspotScore } from '../provider/cbm-rpc-provider';
+
+export interface HotspotGroup { findings: ArchitectureHotspot[]; maxFanIn?: number; peakScore: number }
+export interface HotspotCatalog {
+ findings: ArchitectureHotspot[];
+ byFile: Map<string, HotspotGroup>;
+ byArea: Map<string, HotspotGroup>;
+ bySymbolId: Map<number, HotspotGroup>;
+ maxFanIn: number;
+ unmapped: number;
+}
+const positive = (value?: number) => value !== undefined && Number.isFinite(value) && value > 0 ? value : 0;
+const score = (finding: ArchitectureHotspot) => hotspotScore({ ...finding, fanIn: positive(finding.fanIn), complexity: positive(finding.complexity), cognitive: positive(finding.cognitive), loopDepth: positive(finding.loopDepth) });
+export const hotspotIdentity = (finding: ArchitectureHotspot) => `${finding.qualifiedName ?? finding.name}@${finding.filePath ?? ''}:${finding.line ?? ''}`;
+const identity = hotspotIdentity;
+const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
+function summarize(findings: ArchitectureHotspot[]): HotspotGroup {
+ const measured = findings.flatMap(finding => finding.fanIn !== undefined && Number.isFinite(finding.fanIn) && finding.fanIn >= 0 ? [finding.fanIn] : []);
+ return { findings, maxFanIn: measured.length ? Math.max(...measured) : undefined, peakScore: Math.max(0, ...findings.map(score)) };
+}
+
+export function collectHotspots(findings: ArchitectureHotspot[], graph: GraphData): HotspotCatalog {
+ const byName = new Map<string, GraphNode[]>();
+ for (const node of graph.nodes) if (node.qualified_name) { const matches = byName.get(node.qualified_name) ?? []; matches.push(node); byName.set(node.qualified_name, matches); }
+ const unique = new Map<string, ArchitectureHotspot>();
+ for (const finding of findings) {
+ if (score(finding) <= 0) continue;
+ const matches = finding.qualifiedName ? byName.get(finding.qualifiedName) ?? [] : [];
+ const candidates = matches.filter(node => !finding.filePath || node.file_path === finding.filePath);
+ const symbol = candidates.length === 1 ? candidates[0] : undefined;
+ const value = { ...finding, filePath: finding.filePath ?? symbol?.file_path, line: finding.line ?? symbol?.start_line };
+ const key = identity(value); const previous = unique.get(key);
+ if (!previous || score(value) > score(previous)) unique.set(key, value);
+ }
+ const ranked = [...unique.values()].sort((a, b) => score(b) - score(a) || compare(identity(a), identity(b)));
+ const files = new Map<string, ArchitectureHotspot[]>(); const areas = new Map<string, ArchitectureHotspot[]>();
+ const symbols = new Map<number, ArchitectureHotspot[]>();
+ for (const finding of ranked) {
+ const candidates = (finding.qualifiedName ? byName.get(finding.qualifiedName) ?? [] : []).filter(node => !finding.filePath || node.file_path === finding.filePath);
+ if (candidates.length === 1) {
+ const id = candidates[0].id; const values = symbols.get(id) ?? [];
+ values.push(finding); symbols.set(id, values);
+ }
+ }
+ for (const finding of ranked) if (finding.filePath) {
+ const file = files.get(finding.filePath) ?? []; file.push(finding); files.set(finding.filePath, file);
+ const area = areaOf(finding.filePath); const members = areas.get(area) ?? []; members.push(finding); areas.set(area, members);
+ }
+ return { findings: ranked, byFile: new Map([...files].map(([key, group]) => [key, summarize(group)])),
+ byArea: new Map([...areas].map(([key, group]) => [key, summarize(group)])),
+ bySymbolId: new Map([...symbols].map(([key, group]) => [key, summarize(group)])),
+ maxFanIn: Math.max(0, ...ranked.map(finding => positive(finding.fanIn))), unmapped: ranked.filter(finding => !finding.filePath).length };
+}
+
+export function hotspotsForNode(node: SemanticNode, catalog: HotspotCatalog): HotspotGroup | undefined {
+ if (node.kind === 'area') return node.areaPath ? catalog.byArea.get(node.areaPath) : undefined;
+ if (node.kind === 'file') return node.filePath ? catalog.byFile.get(node.filePath) : undefined;
+ return node.graphNode ? catalog.bySymbolId.get(node.graphNode.id) : undefined;
+}
+
+/** Static fan-in percentage; missing measurements stay distinct from zero. */
+export function gravityPercent(fanIn: number | undefined, referenceFanIn: number): number | undefined {
+ if (fanIn === undefined || !Number.isFinite(fanIn) || fanIn < 0) return undefined;
+ return Math.min(1, fanIn / Math.max(1, Number.isFinite(referenceFanIn) ? referenceFanIn : 1)) * 100;
+}
+
+/** Use the same square-root compression as source height, with no field at zero. */
+export function gravityStrength(fanIn: number | undefined, referenceFanIn: number): number {
+ return Math.sqrt((gravityPercent(fanIn, referenceFanIn) ?? 0) / 100);
+}
+
+export function hotspotSignals(finding: ArchitectureHotspot): string[] {
+ const signals: string[] = [];
+ if (finding.fanIn !== undefined && Number.isFinite(finding.fanIn)) signals.push(`Fan-in ${finding.fanIn}`);
+ if (finding.complexity !== undefined && Number.isFinite(finding.complexity)) signals.push(`Complexity ${finding.complexity}`);
+ if (finding.cognitive !== undefined && Number.isFinite(finding.cognitive)) signals.push(`Cognitive ${finding.cognitive}`);
+ if (finding.loopDepth !== undefined && Number.isFinite(finding.loopDepth)) signals.push(`Loop depth ${finding.loopDepth}`);
+ if (finding.allocationInLoop) signals.push('Allocation in a loop');
+ if (finding.scanInLoop) signals.push('Linear scan in a loop');
+ if (finding.unguardedRecursion) signals.push('Unguarded recursion');
+ return signals;
+}
+
+/** A dedicated hotspot view keeps exact symbol identities and real connecting edges. */
+export function buildHotspotGraph(graph: GraphData, catalog: HotspotCatalog, filter = ''): SemanticGraph {
+ const byName = new Map<string, GraphNode[]>();
+ for (const node of graph.nodes) if (node.qualified_name) {
+ const list = byName.get(node.qualified_name) ?? []; list.push(node); byName.set(node.qualified_name, list);
+ }
+ const match = filter.trim().toLowerCase();
+ const nodes: SemanticNode[] = []; const byGraphId = new Map<number, string>(); const seen = new Set<string>();
+ const matchingNodes = new Map<string, SemanticNode>();
+ for (const finding of catalog.findings) {
+ const candidates = finding.qualifiedName ? byName.get(finding.qualifiedName) ?? [] : [];
+ const exact = candidates.filter(node => (!finding.filePath || node.file_path === finding.filePath) && ['Function', 'Method'].includes(node.label));
+ const symbol = exact.length === 1 ? exact[0] : undefined;
+ const id = symbol ? `hotspot:${symbol.id}` : `hotspot-file:${finding.filePath ?? identity(finding)}`;
+ const projected: SemanticNode = { id, kind: symbol || !finding.filePath ? 'symbol' : 'file', label: symbol?.name ?? finding.filePath ?? finding.name,
+ detail: symbol ? hotspotSignals(finding).join(' · ') : 'Ranked hotspot; symbol identity is outside the loaded graph',
+ position: [0, 0, 0], count: 1, graphNode: symbol, filePath: finding.filePath, line: finding.line,
+ areaPath: finding.filePath ? areaOf(finding.filePath) : undefined, members: symbol ? [symbol] : [] };
+ if (!matchingNodes.has(id) && `${finding.name} ${finding.filePath ?? ''} ${hotspotSignals(finding).join(' ')}`.toLowerCase().includes(match)) matchingNodes.set(id, projected);
+ if (seen.has(id)) continue; seen.add(id);
+ nodes.push(projected);
+ if (symbol) byGraphId.set(symbol.id, id);
+ }
+ const platforms = layoutFolderHierarchy(nodes);
+ const positions = new Map(nodes.map(node => [node.id, node.position]));
+ const matchedNodes = [...matchingNodes.values()].map(node => ({ ...node, position: positions.get(node.id)! }));
+ const allEdges = graph.edges.filter(edge => matchingNodes.has(byGraphId.get(edge.source)!) && matchingNodes.has(byGraphId.get(edge.target)!) && ['CALLS', 'IMPORTS', 'USAGE', 'DATA_FLOWS', 'INHERITS', 'IMPLEMENTS'].includes(edge.type))
+ .sort((a, b) => compare(`${a.source}:${a.type}:${a.target}:${a.id ?? ''}`, `${b.source}:${b.type}:${b.target}:${b.id ?? ''}`));
+ const totalNodes = matchedNodes.length; const shown = matchedNodes.slice(0, 40); const visible = new Set(shown.map(node => node.id));
+ const graphById = new Map(graph.nodes.map(node => [node.id, node]));
+ const edges = allEdges.filter(edge => visible.has(byGraphId.get(edge.source)!) && visible.has(byGraphId.get(edge.target)!)).slice(0, 100).map((edge, index) => ({
+ id: `hotspot-edge:${edge.id ?? index}`, source: byGraphId.get(edge.source)!, target: byGraphId.get(edge.target)!, type: edge.type, count: 1,
+ evidence: [{ source: graphById.get(edge.source)!, target: graphById.get(edge.target)!, type: edge.type, id: edge.id, strategy: edge.strategy }],
+ }));
+ return { view: 'hotspots', scopeKey: `hotspots:${filter}`, title: 'Hotspots and their connections',
+ positionMeaning: 'Platforms follow source folders; symbol positions follow file and source order, independently of rank. Gravity fields encode static fan-in, not runtime activity.',
+ nodes: shown, platforms: pruneHierarchyPlatforms(platforms, shown), edges, totalNodes, totalEdges: allEdges.length, omittedNodes: totalNodes - shown.length, omittedEdges: allEdges.length - edges.length,
+ warnings: ['Hotspots are ranked review signals, not confirmed defects. Unmarked code has not been certified safe.', ...(graph.total_nodes > graph.nodes.length ? ['Some hotspot identities or relationships are outside the loaded graph.'] : [])] };
+}
diff --git a/graph-ui/src/architecture/semantic-graph.test.ts b/graph-ui/src/architecture/semantic-graph.test.ts
index 0c5e20179..e7ae46626 100644
--- a/graph-ui/src/architecture/semantic-graph.test.ts
+++ b/graph-ui/src/architecture/semantic-graph.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { buildSemanticGraph, semanticEntryPoints } from './semantic-graph';
+import { buildSemanticGraph, layoutFolderHierarchy, semanticEntryPoints, type SemanticNode, type SemanticPlatform } from './semantic-graph';
import type { GraphData, GraphNode } from '../galaxy/types';
const node = (id: number, file: string, name = `symbol${id}`, status: GraphNode['status'] = 'normal'): GraphNode => ({
@@ -16,7 +16,83 @@ const fixture: GraphData = { nodes: [node(1, 'src/api/server.ts', 'start', 'entr
{ id: 5, source: 3, target: 1, type: 'CALLS' },
] };
+const containsNode = (platform: SemanticPlatform, item: SemanticNode) => Math.abs(platform.position[0] - item.position[0]) + 10 <= platform.width / 2
+ && Math.abs(platform.position[2] - item.position[2]) + 10 <= platform.depth / 2;
+const hierarchyNode = (id: string, filePath?: string, line = 1): SemanticNode => ({ id, kind: 'symbol', label: id, detail: '',
+ position: [0, 0, 0], count: 1, members: [], filePath, line });
+
+describe('source folder hierarchy layout', () => {
+ it('connects overview and dependency projections to real ancestor platforms without changing evidence', () => {
+ const input: GraphData = { ...fixture, nodes: [...fixture.nodes, node(20, 'apps/web/app.ts'), node(21, 'README.md')], total_nodes: 6 };
+ const full = buildSemanticGraph(input, { view: 'overview' });
+ expect(full.platforms?.map(platform => platform.path).sort()).toEqual(['apps', 'src']);
+ const source = full.platforms!.find(platform => platform.path === 'src')!;
+ full.nodes.filter(item => item.areaPath?.startsWith('src/')).forEach(item => expect(containsNode(source, item)).toBe(true));
+ expect(full.nodes.find(item => item.areaPath === '(root)')?.position[1]).toBeCloseTo(0.08);
+ const filtered = buildSemanticGraph(input, { view: 'dependencies', filter: 'src/store' });
+ expect(filtered.platforms?.map(platform => platform.path)).toEqual(['src']);
+ filtered.nodes.forEach(item => expect(item.position).toEqual(full.nodes.find(original => original.id === item.id)!.position));
+ filtered.edges.forEach(edge => expect(edge).toEqual(full.edges.find(original => original.id === edge.id)));
+ const capped = buildSemanticGraph(input, { view: 'overview', maxNodes: 1 });
+ expect(capped.nodes[0].position).toEqual(full.nodes.find(item => item.id === capped.nodes[0].id)!.position);
+ const imports = buildSemanticGraph(input, { view: 'dependencies', relations: ['IMPORTS'] });
+ imports.nodes.forEach(item => expect(item.position).toEqual(full.nodes.find(original => original.id === item.id)!.position));
+ });
+ it('packs nested siblings and node footprints separately while retaining ancestor containment', () => {
+ const nodes = Array.from({ length: 24 }, (_, index) => hierarchyNode(`symbol${index}`,
+ `services/service${Math.floor(index / 8)}/src/file${Math.floor(index / 3)}.ts`, index));
+ const platforms = layoutFolderHierarchy(nodes);
+ platforms.forEach((platform, index) => platforms.slice(index + 1).forEach(other => {
+ if (platform.path.startsWith(`${other.path}/`) || other.path.startsWith(`${platform.path}/`)) return;
+ expect(Math.abs(platform.position[0] - other.position[0]) >= (platform.width + other.width) / 2
+ || Math.abs(platform.position[2] - other.position[2]) >= (platform.depth + other.depth) / 2).toBe(true);
+ }));
+ for (const item of nodes) {
+ platforms.filter(platform => item.filePath!.startsWith(`${platform.path}/`)).forEach(platform => expect(containsNode(platform, item)).toBe(true));
+ const parent = platforms.find(platform => platform.path === item.filePath!.slice(0, item.filePath!.lastIndexOf('/')))!;
+ expect(item.position[1] - parent.position[1]).toBeCloseTo(0.08);
+ }
+ nodes.forEach((item, index) => nodes.slice(index + 1).forEach(other => expect(Math.hypot(item.position[0] - other.position[0], item.position[2] - other.position[2])).toBeGreaterThanOrEqual(20)));
+ });
+ it('keeps root files flat, caps real ancestor depth, and separates unknown source without inventing a path', () => {
+ const nodes = [hierarchyNode('root', 'root.ts'), hierarchyNode('deep', 'services/api/src/internal/jobs/run.ts'), hierarchyNode('unknown')];
+ const before = nodes.map(item => ({ ...item, position: undefined }));
+ const platforms = layoutFolderHierarchy(nodes);
+ expect(platforms.filter(platform => platform.path).map(platform => platform.path)).toEqual(['services', 'services/api', 'services/api/src']);
+ expect(platforms.every(platform => platform.level <= 3)).toBe(true);
+ expect(platforms.find(platform => platform.label === 'Unknown source')?.path).toBe('');
+ expect(nodes[0].position[1]).toBeCloseTo(0.08);
+ expect(nodes[1].filePath).toBe('services/api/src/internal/jobs/run.ts');
+ expect(nodes.map(item => ({ ...item, position: undefined }))).toEqual(before);
+ const reversed = nodes.map(item => ({ ...item, position: [0, 0, 0] as [number, number, number] })).reverse();
+ expect(layoutFolderHierarchy(reversed)).toEqual(platforms);
+ reversed.forEach(item => expect(item.position).toEqual(nodes.find(original => original.id === item.id)!.position));
+ expect(layoutFolderHierarchy([])).toEqual([]);
+ });
+ it('keeps direct source-folder files beside descendant area bricks inside their common source container', () => {
+ const input: GraphData = { nodes: [node(1, 'src/main.ts'), node(2, 'src/store/db.ts')], edges: [], total_nodes: 2 };
+ const model = buildSemanticGraph(input, { view: 'overview' });
+ expect(model.nodes.map(item => item.id)).toEqual(['area:src', 'area:src/store']);
+ expect(model.platforms?.map(platform => platform.path)).toEqual(['src']);
+ model.nodes.forEach(item => expect(containsNode(model.platforms![0], item)).toBe(true));
+ expect(model.edges).toEqual([]);
+ });
+});
+
describe('semantic architecture projection', () => {
+ it('represents disconnected and inventory-only files without inventing graph evidence', () => {
+ const graph: GraphData = { nodes: [node(1, 'src/api/main.ts'), { ...node(2, 'isolated/empty.ts'), label: 'File' }], edges: [], total_nodes: 2 };
+ const knownFiles = ['src/api/main.ts', 'isolated/empty.ts', 'assets/logo.svg'];
+ const model = buildSemanticGraph(graph, { view: 'overview', knownFiles });
+ expect(model.nodes.map(node => node.id)).toEqual(['area:assets', 'area:isolated', 'area:src/api']);
+ expect(model.edges).toEqual([]);
+ const empty = buildSemanticGraph(graph, { view: 'overview', knownFiles, areaPath: 'isolated' });
+ expect(empty.nodes[0].filePath).toBe('isolated/empty.ts');
+ const missing = buildSemanticGraph(graph, { view: 'overview', knownFiles, filePath: 'assets/logo.svg' });
+ expect(missing.nodes[0]).toMatchObject({ kind: 'file', filePath: 'assets/logo.svg', members: [], count: 0 });
+ expect(missing.nodes[0].graphNode).toBeUndefined();
+ expect(buildSemanticGraph(graph, { view: 'overview', knownFiles, visibleFiles: new Set(['assets/logo.svg']) }).nodes.map(node => node.id)).toEqual(['area:assets']);
+ });
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']);
diff --git a/graph-ui/src/architecture/semantic-graph.ts b/graph-ui/src/architecture/semantic-graph.ts
index 372929a0a..1f1fb4d09 100644
--- a/graph-ui/src/architecture/semantic-graph.ts
+++ b/graph-ui/src/architecture/semantic-graph.ts
@@ -3,7 +3,7 @@ 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 type SemanticView = 'overview' | 'dependencies' | 'entryPoints' | 'routes' | 'hotspots';
export interface SemanticNode {
id: string;
kind: 'area' | 'file' | 'symbol' | 'route';
@@ -18,6 +18,10 @@ export interface SemanticNode {
areaPath?: string;
members: GraphNode[];
depth?: number;
+ /** Optional scene treatment for service declarations; source maps keep their defaults. */
+ footprint?: [number, number];
+ tint?: string;
+ kindLabel?: string;
}
export interface SemanticEvidence {
source: GraphNode;
@@ -38,12 +42,24 @@ export interface SemanticEdge {
count: number;
evidence: SemanticEvidence[];
}
+/** Visual folder context only; these containers are never graph nodes. */
+export interface SemanticPlatform {
+ id: string;
+ path: string;
+ label: string;
+ /** Y denotes the top surface of the shallow platform. */
+ position: [number, number, number];
+ width: number;
+ depth: number;
+ level: number;
+}
export interface SemanticGraph {
view: SemanticView;
scopeKey: string;
title: string;
positionMeaning: string;
nodes: SemanticNode[];
+ platforms?: SemanticPlatform[];
edges: SemanticEdge[];
totalNodes: number;
totalEdges: number;
@@ -64,6 +80,9 @@ export interface SemanticGraphOptions {
routeSnapshot?: RouteGraphSnapshot;
maxNodes?: number;
maxEdges?: number;
+ /** File inventory is independent of the dependency graph and its row cap. */
+ knownFiles?: string[];
+ visibleFiles?: ReadonlySet<string>;
}
const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
@@ -117,6 +136,117 @@ function bounded(value: number | undefined, fallback: number, maximum: number):
return Number.isFinite(value) ? Math.max(1, Math.min(maximum, Math.floor(value!))) : fallback;
}
+interface HierarchyBox {
+ key: string;
+ path: string;
+ level: number;
+ unknown?: boolean;
+ node?: SemanticNode;
+ children: HierarchyBox[];
+ width: number;
+ depth: number;
+ x: number;
+ z: number;
+}
+const hierarchyPath = (path: string | undefined) => !path || path === '{}' ? undefined
+ : path.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+/g, '/').replace(/\/$/, '');
+const parentPath = (path: string) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';
+const hierarchyNodeOrder = (a: SemanticNode, b: SemanticNode) => compare(hierarchyPath(a.filePath) ?? a.areaPath ?? '', hierarchyPath(b.filePath) ?? b.areaPath ?? '')
+ || (a.line ?? 0) - (b.line ?? 0) || compare(a.id, b.id);
+
+/** Deterministic shelf packing; its inputs are source identity and hierarchy only. */
+function packHierarchy(box: HierarchyBox): void {
+ if (box.node) return;
+ const gap = 10;
+ const padding = box.level ? 12 : 0;
+ const labelEdge = box.level ? 16 : 0;
+ for (const child of box.children) packHierarchy(child);
+ const target = Math.max(24, ...box.children.map(child => child.width),
+ Math.sqrt(box.children.reduce((sum, child) => sum + (child.width + gap) * (child.depth + gap), 0)) * 1.2);
+ let x = 0; let z = 0; let rowDepth = 0; let width = 0;
+ for (const child of box.children) {
+ if (x > 0 && x + child.width > target) { x = 0; z += rowDepth + gap; rowDepth = 0; }
+ child.x = x + child.width / 2;
+ child.z = z + child.depth / 2;
+ width = Math.max(width, x + child.width);
+ rowDepth = Math.max(rowDepth, child.depth);
+ x += child.width + gap;
+ }
+ box.width = width + padding * 2;
+ box.depth = z + rowDepth + padding + labelEdge;
+ for (const child of box.children) {
+ child.x += padding - box.width / 2;
+ child.z += labelEdge - box.depth / 2;
+ }
+}
+
+/**
+ * Arrange unfiltered candidates by actual source folders, never relation count
+ * or hotspot rank. Only positions change; callers retain all graph identities.
+ * Deep paths share their third real ancestor to keep the steps shallow.
+ */
+export function layoutFolderHierarchy(nodes: SemanticNode[]): SemanticPlatform[] {
+ if (!nodes.length) return [];
+ const root: HierarchyBox = { key: '', path: '', level: 0, children: [], width: 0, depth: 0, x: 0, z: 0 };
+ const folders = new Map<string, HierarchyBox>();
+ const areaPaths = nodes.filter(node => node.kind === 'area').map(node => hierarchyPath(node.areaPath)).filter((path): path is string => Boolean(path && path !== '(root)'));
+ const areasWithDescendants = new Set<string>();
+ for (const path of areaPaths) {
+ let ancestor = parentPath(path);
+ while (ancestor) { areasWithDescendants.add(ancestor); ancestor = parentPath(ancestor); }
+ }
+ for (const node of [...nodes].sort(hierarchyNodeOrder)) {
+ const path = hierarchyPath(node.kind === 'area' ? node.areaPath : node.filePath);
+ const containing = path === '(root)' ? '' : path === undefined ? undefined
+ : node.kind === 'area' && areasWithDescendants.has(path) ? path : parentPath(path);
+ let owner = root;
+ if (containing === undefined) {
+ let unknown = folders.get('unknown');
+ if (!unknown) {
+ unknown = { key: 'unknown', path: '', unknown: true, level: 1, children: [], width: 0, depth: 0, x: 0, z: 0 };
+ root.children.push(unknown); folders.set('unknown', unknown);
+ }
+ owner = unknown;
+ } else {
+ const parts = containing.split('/').filter(Boolean).slice(0, 3);
+ parts.forEach((_, index) => {
+ const folderPath = parts.slice(0, index + 1).join('/');
+ const key = `folder:${folderPath}`;
+ let folder = folders.get(key);
+ if (!folder) {
+ folder = { key, path: folderPath, level: index + 1, children: [], width: 0, depth: 0, x: 0, z: 0 };
+ owner.children.push(folder); folders.set(key, folder);
+ }
+ owner = folder;
+ });
+ }
+ owner.children.push({ key: `node:${node.id}`, path: path ?? '', level: owner.level, node, children: [], width: 24, depth: 24, x: 0, z: 0 });
+ }
+ const sortChildren = (box: HierarchyBox) => {
+ box.children.sort((a, b) => a.node && b.node ? hierarchyNodeOrder(a.node, b.node)
+ : Number(Boolean(a.node)) - Number(Boolean(b.node)) || Number(Boolean(a.unknown)) - Number(Boolean(b.unknown)) || compare(a.key, b.key));
+ box.children.filter(child => !child.node).forEach(sortChildren);
+ };
+ sortChildren(root);
+ packHierarchy(root);
+ const platforms: SemanticPlatform[] = [];
+ const place = (box: HierarchyBox, x: number, z: number) => {
+ if (box.node) { box.node.position = [x, box.level * 1.6 + 0.08, z]; return; }
+ if (box.level) platforms.push({ id: `hierarchy:${box.key}`, path: box.path,
+ label: box.unknown ? 'Unknown source' : box.path, position: [x, box.level * 1.6, z], width: box.width, depth: box.depth, level: box.level });
+ for (const child of box.children) place(child, x + child.x, z + child.z);
+ };
+ place(root, 0, 0);
+ return platforms;
+}
+
+/** Prune empty containers without repacking the stable unfiltered layout. */
+export function pruneHierarchyPlatforms(platforms: SemanticPlatform[], nodes: SemanticNode[]): SemanticPlatform[] {
+ return platforms.filter(platform => nodes.some(node => node.position[1] >= platform.position[1]
+ && Math.abs(node.position[0] - platform.position[0]) < platform.width / 2
+ && Math.abs(node.position[2] - platform.position[2]) < platform.depth / 2));
+}
+
/** 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]));
@@ -133,7 +263,7 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
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.';
+ let positionMeaning = 'Nested platforms follow source folders. Positions are stable across text filters; boxes represent source grouping, not deployed services.';
const depth = bounded(options.depth, 3, 8);
let rootId: string | undefined;
@@ -221,6 +351,7 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
const groups = new Map<string, SemanticNode>();
const nodeGroups = new Map<number, string>();
for (const node of graph.nodes.filter(sourceNode).sort(nodeOrder)) {
+ if (options.visibleFiles && !options.visibleFiles.has(node.file_path!)) continue;
const area = areaOf(node.file_path!);
if (options.areaPath && area !== options.areaPath) continue;
if (options.filePath && node.file_path !== options.filePath) continue;
@@ -236,9 +367,26 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
filePath: kind === 'file' ? path : undefined, areaPath: area, members: [] };
group.members.push(node); group.count++; groups.set(id, group); nodeGroups.set(node.id, id);
}
+ // Retain files with no graph nodes/edges as navigable inventory objects.
+ // They deliberately have no graphNode and cannot fabricate impact evidence.
+ const inventory = new Map<string, Set<string>>();
+ for (const path of options.knownFiles ?? []) {
+ if (!path || path === '{}' || (options.visibleFiles && !options.visibleFiles.has(path))) continue;
+ const area = areaOf(path);
+ if ((options.areaPath && area !== options.areaPath) || (options.filePath && path !== options.filePath)) continue;
+ const kind = options.areaPath || options.filePath ? 'file' : 'area';
+ const key = kind === 'file' ? path : area;
+ const id = `${kind}:${key}`;
+ const paths = inventory.get(id) ?? new Set<string>(); paths.add(path); inventory.set(id, paths);
+ if (options.filePath && [...groups.values()].some(group => group.filePath === path)) continue;
+ if (!groups.has(id)) groups.set(id, { id, kind, label: key,
+ detail: options.filePath ? 'File inventory · no symbols in the loaded graph' : '',
+ position: [0, 0, 0], count: 0, areaPath: area, filePath: kind === 'file' ? path : undefined, members: [] });
+ }
let scopedEvidence = evidence;
if (options.areaPath || options.filePath) {
const inScope = (node: GraphNode) => sourceNode(node)
+ && (!options.visibleFiles || options.visibleFiles.has(node.file_path!))
&& (!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));
@@ -247,6 +395,7 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
const inside = inScope(edge.source) ? edge.source : edge.target;
const outside = inside === edge.source ? edge.target : edge.source;
if (!sourceNode(outside)) continue;
+ if (options.visibleFiles && !options.visibleFiles.has(outside.file_path!)) 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)) {
@@ -268,11 +417,12 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
}
}
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` }));
+ detail: node.detail || `${new Set([...node.members.map(member => member.file_path), ...(inventory.get(node.id) ?? [])]).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 platforms = options.view !== 'entryPoints' && options.view !== 'routes' ? layoutFolderHierarchy(nodes) : undefined;
const filter = options.filter?.trim().toLowerCase();
const matching = new Set<string>();
if (filter) {
@@ -298,8 +448,6 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
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
@@ -310,7 +458,7 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
// 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) => {
+ nodes.forEach(node => {
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;
@@ -320,13 +468,12 @@ export function buildSemanticGraph(graph: GraphData, options: SemanticGraphOptio
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,
+ title, positionMeaning, nodes, ...(platforms ? { platforms: pruneHierarchyPlatforms(platforms, nodes) } : {}),
+ edges, totalNodes, totalEdges, omittedNodes: totalNodes - nodes.length,
omittedEdges: totalEdges - edges.length, warnings: [...new Set(warnings)] };
}
diff --git a/graph-ui/src/architecture/source-metrics.test.ts b/graph-ui/src/architecture/source-metrics.test.ts
new file mode 100644
index 000000000..5cd8950d4
--- /dev/null
+++ b/graph-ui/src/architecture/source-metrics.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+import type { GraphData, GraphNode } from '../galaxy/types';
+import { buildSemanticGraph } from './semantic-graph';
+import { collectSourceMetrics, measureSourceNode, sourceBrickHeight, sourceLanguage, languageColor, sourceNodeSizePercent } from './source-metrics';
+
+const node = (id: number, file_path: string, label: string, start_line?: number, end_line?: number): GraphNode => ({
+ id, file_path, label, start_line, end_line, name: `node${id}`, x: 0, y: 0, z: 0, size: 1, color: '',
+});
+const graph: GraphData = { nodes: [node(1, 'src/api/a.ts', 'File', 0, 0), node(2, 'src/api/a.ts', 'Module', 1, 100),
+ node(3, 'src/api/a.ts', 'Class', 2, 95), node(4, 'src/api/a.ts', 'Method', 10, 80),
+ node(5, 'src/api/b.py', 'Module', 1, 300), node(6, 'src/api/b.py', 'Module', 1, 300),
+ node(7, 'src/store/save.go', 'Module', 1, 600), node(8, 'README.md', 'File', 0, 0)],
+ edges: [{ source: 4, target: 7, type: 'CALLS' }], total_nodes: 8 };
+
+describe('source size and language encoding', () => {
+ it('counts each whole-file module extent once without adding nested or duplicate spans', () => {
+ const catalog = collectSourceMetrics(graph);
+ expect(catalog.total).toMatchObject({ lines: 1000, measuredFiles: 3, files: 4 });
+ expect(catalog.areas.get('src/api')).toMatchObject({ lines: 400, measuredFiles: 2, files: 2 });
+ expect(catalog.areas.get('src/api')?.languages.map(language => [language.name, language.lines])).toEqual([['Python', 300], ['TypeScript', 100]]);
+ expect(catalog.total.languages.reduce((sum, language) => sum + language.lines, 0)).toBe(1000);
+ });
+ it('keeps unknown file sizes and unknown language distinct from zero', () => {
+ const catalog = collectSourceMetrics(graph, ['assets/custom.undocumented']);
+ expect(catalog.files.get('README.md')?.lines).toBeUndefined();
+ expect(catalog.files.get('assets/custom.undocumented')?.language).toBe('Unknown');
+ expect(catalog.partial).toBe(true);
+ expect(sourceBrickHeight(undefined, 1000)).not.toBe(sourceBrickHeight(0, 1000));
+ const onlySymbols = collectSourceMetrics({ nodes: [node(1, 'file.ts', 'Function', 1, 999)], edges: [], total_nodes: 1 });
+ expect(onlySymbols.total.lines).toBeUndefined();
+ });
+ it('normalizes file identity and uses the longest complete module range deterministically', () => {
+ const input: GraphData = { nodes: [node(1, './src/api/a.ts', 'Module', 1, 90), node(2, 'src\\api\\a.ts', 'Module', 1, 100),
+ node(3, 'src/api/a.ts', 'Module', 8, 800)], edges: [], total_nodes: 3 };
+ expect(collectSourceMetrics(input).total).toMatchObject({ lines: 100, files: 1 });
+ expect(collectSourceMetrics(input)).toEqual(collectSourceMetrics({ ...input, nodes: [...input.nodes].reverse() }));
+ });
+ it('keeps measurements, language colors and scale stable under scene caps, filters and drilldown', () => {
+ const catalog = collectSourceMetrics(graph);
+ const overview = buildSemanticGraph(graph, { view: 'overview' });
+ const filtered = buildSemanticGraph(graph, { view: 'dependencies', filter: 'src/api', maxNodes: 1 });
+ const area = overview.nodes.find(node => node.areaPath === 'src/api')!;
+ expect(measureSourceNode(filtered.nodes[0], catalog)).toEqual(measureSourceNode(area, catalog));
+ expect(sourceNodeSizePercent(filtered.nodes[0], catalog)).toBe(sourceNodeSizePercent(area, catalog));
+ const detail = buildSemanticGraph(graph, { view: 'overview', areaPath: 'src/api' });
+ expect(measureSourceNode(detail.nodes.find(node => node.filePath === 'src/api/a.ts')!, catalog)?.lines).toBe(100);
+ expect(catalog.referenceLines).toBe(600);
+ expect(catalog.referenceKind).toBe('folder');
+ expect(catalog.referencePath).toBe('src/store');
+ expect(languageColor('TypeScript')).toBe(languageColor(sourceLanguage('other/project/test.tsx')));
+ });
+ it('compresses million-line outliers into finite bounded monotonic heights', () => {
+ const heights = [0, 1, 100, 10000, 1000000].map(lines => sourceBrickHeight(lines, 1000000));
+ heights.forEach((height, index) => { expect(Number.isFinite(height)).toBe(true); expect(height).toBeGreaterThanOrEqual(1.5); expect(height).toBeLessThanOrEqual(14); if (index) expect(height).toBeGreaterThan(heights[index - 1]); });
+ expect(sourceBrickHeight(1e12, 1000000)).toBe(14);
+ expect(sourceBrickHeight(NaN, 100)).toBe(sourceBrickHeight(undefined, 100));
+ expect(Number.isFinite(sourceBrickHeight(100, Infinity))).toBe(true);
+ expect(sourceBrickHeight(Number.MAX_VALUE, 1)).toBe(14);
+ expect(sourceBrickHeight(-1, 100)).toBe(sourceBrickHeight(undefined, 100));
+ });
+ it('gives one, ten and one hundred percent sizes a perceptible bounded height spread', () => {
+ const heights = [100, 1000, 10000].map(lines => sourceBrickHeight(lines, 10000));
+ expect(heights[0]).toBeCloseTo(2.75);
+ expect(heights[1]).toBeCloseTo(1.5 + 12.5 * Math.sqrt(0.1));
+ expect(heights[2]).toBe(14);
+ expect(heights[1] - heights[0]).toBeGreaterThan(2);
+ expect(heights[2] - heights[1]).toBeGreaterThan(8);
+ expect(sourceBrickHeight(0, 10000)).toBe(1.5);
+ });
+ it('uses the largest non-root folder as 100 percent despite large root-direct files', () => {
+ const input: GraphData = { nodes: [node(1, 'root.ts', 'Module', 1, 1000000), node(2, 'other.ts', 'Module', 1, 2000000),
+ node(3, 'src/large/a.ts', 'Module', 1, 800), node(4, 'src/small/a.ts', 'Module', 1, 333)], edges: [], total_nodes: 4 };
+ const catalog = collectSourceMetrics(input);
+ const overview = buildSemanticGraph(input, { view: 'overview' });
+ const area = (path: string) => overview.nodes.find(item => item.areaPath === path)!;
+ expect(catalog.referenceLines).toBe(800);
+ expect(catalog.referencePath).toBe('src/large');
+ expect(catalog.referenceKind).toBe('folder');
+ expect(sourceNodeSizePercent(area('src/large'), catalog)).toBe(100);
+ expect(sourceNodeSizePercent(area('src/small'), catalog)).toBe(41.625);
+ expect(sourceNodeSizePercent(area('(root)'), catalog)).toBe(0);
+ expect(measureSourceNode(area('(root)'), catalog)?.lines).toBe(3000000);
+ expect(catalog.total.lines).toBe(3001133);
+ const file = buildSemanticGraph(input, { view: 'overview', areaPath: 'src/small' }).nodes.find(item => item.kind === 'file')!;
+ expect(sourceNodeSizePercent(file, catalog)).toBe(41.625);
+ const rootFile = buildSemanticGraph(input, { view: 'overview', areaPath: '(root)' }).nodes.find(item => item.kind === 'file')!;
+ expect(sourceNodeSizePercent(rootFile, catalog)).toBe(100);
+ });
+ it('uses an explicit largest-file fallback for a root-only repository without changing root measurements', () => {
+ const input: GraphData = { nodes: [node(1, 'big.ts', 'Module', 1, 800), node(2, 'small.py', 'Module', 1, 333)], edges: [], total_nodes: 2 };
+ const catalog = collectSourceMetrics(input);
+ const root = buildSemanticGraph(input, { view: 'overview' }).nodes[0];
+ expect(catalog.referenceKind).toBe('file');
+ expect(catalog.referencePath).toBe('big.ts');
+ expect(catalog.referenceLines).toBe(800);
+ expect(catalog.areas.get('(root)')?.lines).toBe(1133);
+ expect(sourceNodeSizePercent(root, catalog)).toBe(0);
+ const files = buildSemanticGraph(input, { view: 'overview', areaPath: '(root)' });
+ expect(sourceNodeSizePercent(files.nodes.find(item => item.filePath === 'small.py')!, catalog)).toBe(41.625);
+ });
+ it('leaves unknown non-root sizes undefined and preserves the root baseline with no measurements', () => {
+ const input: GraphData = { nodes: [node(1, 'src/api/a.ts', 'Function', 1, 99), node(2, 'README.md', 'File')], edges: [], total_nodes: 2 };
+ const catalog = collectSourceMetrics(input);
+ const overview = buildSemanticGraph(input, { view: 'overview' });
+ expect(catalog.referencePath).toBeUndefined();
+ expect(catalog.referenceKind).toBe('file');
+ expect(catalog.referenceLines).toBe(1);
+ expect(sourceNodeSizePercent(overview.nodes.find(item => item.areaPath === 'src/api')!, catalog)).toBeUndefined();
+ expect(sourceNodeSizePercent(overview.nodes.find(item => item.areaPath === '(root)')!, catalog)).toBe(0);
+ const file = buildSemanticGraph(input, { view: 'overview', areaPath: 'src/api' }).nodes[0];
+ expect(sourceNodeSizePercent(file, catalog)).toBeUndefined();
+ });
+ it('resolves equal-size reference ties by path independently of graph row order', () => {
+ const input: GraphData = { nodes: [node(1, 'src/z/a.ts', 'Module', 1, 200), node(2, 'src/a/z.ts', 'Module', 1, 200)], edges: [], total_nodes: 2 };
+ expect(collectSourceMetrics(input).referencePath).toBe('src/a');
+ expect(collectSourceMetrics({ ...input, nodes: [...input.nodes].reverse() }).referencePath).toBe('src/a');
+ const rootOnly: GraphData = { nodes: [node(1, 'z.ts', 'Module', 1, 200), node(2, 'a.ts', 'Module', 1, 200)], edges: [], total_nodes: 2 };
+ expect(collectSourceMetrics(rootOnly).referencePath).toBe('a.ts');
+ expect(collectSourceMetrics({ ...rootOnly, nodes: [...rootOnly.nodes].reverse() }).referencePath).toBe('a.ts');
+ });
+ it('classifies file types without guessing ambiguous header or MATLAB/Objective-C files', () => {
+ expect(sourceLanguage('types.H')).toBe('C / C++');
+ expect(sourceLanguage('plugin.m')).toBe('Objective-C / MATLAB');
+ expect(sourceLanguage('Dockerfile.dev')).toBe('Dockerfile');
+ expect(sourceLanguage('source.C')).toBe('C++');
+ expect(sourceLanguage('LICENSE')).toBe('Unknown');
+ });
+ it('distinguishes real connections, isolated files and missing graph evidence', () => {
+ const catalog = collectSourceMetrics(graph, ['outside/not-loaded.ts']);
+ expect(catalog.files.get('src/api/a.ts')?.connection).toBe('connected');
+ expect(catalog.files.get('src/api/b.py')?.connection).toBe('none');
+ expect(catalog.files.get('outside/not-loaded.ts')?.connection).toBe('unknown');
+ const partial = collectSourceMetrics({ ...graph, total_nodes: 99 });
+ expect(partial.files.get('src/api/b.py')?.connection).toBe('unknown');
+ expect(partial.files.get('src/api/a.ts')?.connection).toBe('connected');
+ });
+});
diff --git a/graph-ui/src/architecture/source-metrics.ts b/graph-ui/src/architecture/source-metrics.ts
new file mode 100644
index 000000000..d476c7508
--- /dev/null
+++ b/graph-ui/src/architecture/source-metrics.ts
@@ -0,0 +1,150 @@
+import type { GraphData } from '../galaxy/types';
+import type { SemanticNode } from './semantic-graph';
+import { areaOf, MAP_RELATIONS } from './repository-map';
+
+export interface LanguageMeasure { name: string; color: string; lines: number; files: number }
+export interface SourceMeasure {
+ /** Indexed whole-file line extent, including comments and blank lines. */
+ lines?: number;
+ measuredFiles: number;
+ files: number;
+ languages: LanguageMeasure[];
+}
+export interface FileMeasure { path: string; language: string; lines?: number; connection: 'connected' | 'none' | 'unknown' }
+export interface SourceCatalog {
+ files: Map<string, FileMeasure>;
+ areas: Map<string, SourceMeasure>;
+ total: SourceMeasure;
+ referenceLines: number;
+ referenceKind: 'folder' | 'file';
+ referencePath?: string;
+ partial: boolean;
+}
+
+const EXTENSIONS: Record<string, string> = {
+ ts: 'TypeScript', tsx: 'TypeScript', mts: 'TypeScript', cts: 'TypeScript',
+ js: 'JavaScript', jsx: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript',
+ py: 'Python', pyi: 'Python', c: 'C', h: 'C / C++', cc: 'C++', cpp: 'C++', cxx: 'C++', hpp: 'C++', hxx: 'C++', hh: 'C++',
+ cs: 'C#', java: 'Java', kt: 'Kotlin', kts: 'Kotlin', go: 'Go', rs: 'Rust', rb: 'Ruby', php: 'PHP', swift: 'Swift',
+ m: 'Objective-C / MATLAB', mm: 'Objective-C++', scala: 'Scala', sc: 'Scala', sh: 'Shell', bash: 'Shell', zsh: 'Shell', ps1: 'PowerShell',
+ sql: 'SQL', html: 'HTML', htm: 'HTML', css: 'CSS', scss: 'SCSS', sass: 'Sass', vue: 'Vue', svelte: 'Svelte', astro: 'Astro',
+ md: 'Markdown', mdx: 'MDX', json: 'JSON', jsonc: 'JSON', yml: 'YAML', yaml: 'YAML', toml: 'TOML', xml: 'XML', proto: 'Protobuf',
+ r: 'R', hs: 'Haskell', ex: 'Elixir', exs: 'Elixir', erl: 'Erlang', ml: 'OCaml', fs: 'F#', clj: 'Clojure',
+ dart: 'Dart', lua: 'Lua', jl: 'Julia', zig: 'Zig', sol: 'Solidity', tex: 'LaTeX', txt: 'Text', cmake: 'CMake',
+};
+const COLORS: Record<string, string> = {
+ TypeScript: '#75bbef', JavaScript: '#e5cd73', Python: '#79b7aa', C: '#a7afdf', 'C / C++': '#b6b5d4', 'C++': '#e198bd',
+ 'C#': '#bb9be9', Java: '#e5aa78', Kotlin: '#c99be9', Go: '#73c9d5', Rust: '#d79e7e', Ruby: '#df8e9c', PHP: '#b2a9df', Swift: '#edab87',
+ Vue: '#80d0ae', Svelte: '#e5a88d', HTML: '#dfa184', CSS: '#b8a0e2', SCSS: '#d9a0c4', SQL: '#d3be7e', Shell: '#a9c98c',
+ Markdown: '#a3b2bf', JSON: '#b7bfaa', YAML: '#c3afb0', TOML: '#bbaea2', Unknown: '#81939e',
+};
+const pathKey = (path: string) => path.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+/g, '/');
+const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
+
+/** File-type classification, not a claim that an embedded language was parsed. */
+export function sourceLanguage(path: string): string {
+ const name = pathKey(path).split('/').at(-1) ?? '';
+ if (/^dockerfile(?:\.|$)/i.test(name)) return 'Dockerfile';
+ if (/^(?:gnumakefile|makefile)(?:\.|$)/i.test(name)) return 'Makefile';
+ if (name === 'CMakeLists.txt') return 'CMake';
+ if (name.endsWith('.C')) return 'C++';
+ return EXTENSIONS[name.split('.').at(-1)?.toLowerCase() ?? ''] ?? 'Unknown';
+}
+export function languageColor(language: string): string {
+ if (COLORS[language]) return COLORS[language];
+ // Stable for less common languages, independent of repository or row order.
+ let hash = 0;
+ for (const char of language) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
+ return `hsl(${hash % 360}, 45%, 70%)`;
+}
+function summarize(files: FileMeasure[]): SourceMeasure {
+ const languages = new Map<string, LanguageMeasure>();
+ let measuredFiles = 0; let lines = 0;
+ for (const file of files) {
+ const language = languages.get(file.language) ?? { name: file.language, color: languageColor(file.language), lines: 0, files: 0 };
+ language.files++;
+ if (file.lines !== undefined) { lines += file.lines; measuredFiles++; language.lines += file.lines; }
+ languages.set(file.language, language);
+ }
+ return { lines: measuredFiles ? lines : undefined, measuredFiles, files: files.length,
+ languages: [...languages.values()].sort((a, b) => b.lines - a.lines || b.files - a.files || compare(a.name, b.name)) };
+}
+
+/** Build once from the unfiltered snapshot: scene caps and relations cannot resize a file. */
+export function collectSourceMetrics(graph: GraphData, knownFiles: string[] = []): SourceCatalog {
+ const files = new Map<string, FileMeasure>();
+ const addFile = (path: string | undefined) => {
+ if (!path || path === '{}') return undefined;
+ const key = pathKey(path);
+ if (!files.has(key)) files.set(key, { path: key, language: sourceLanguage(key), connection: 'unknown' });
+ return files.get(key)!;
+ };
+ for (const path of knownFiles) addFile(path);
+ const represented = new Set<string>();
+ for (const node of graph.nodes) {
+ if (['Project', 'Folder', 'Package', 'Branch'].includes(node.label)) continue;
+ const file = addFile(node.file_path);
+ if (file) represented.add(file.path);
+ // File nodes often have 0/0 coordinates. Only a whole-file Module range
+ // beginning at line 1 establishes this measure; symbol spans never do.
+ if (file && node.label === 'Module' && node.start_line === 1 && Number.isSafeInteger(node.end_line) && node.end_line! > 0) {
+ file.lines = Math.max(file.lines ?? 0, node.end_line!);
+ }
+ }
+ const byId = new Map(graph.nodes.map(node => [node.id, node]));
+ const relations = new Set<string>([...MAP_RELATIONS, 'HTTP_CALLS', 'ASYNC_CALLS', 'HANDLES']);
+ const incomplete = graph.total_nodes > graph.nodes.length || ('edgesTruncated' in graph && graph.edgesTruncated !== false);
+ for (const file of files.values()) if (!incomplete && represented.has(file.path)) file.connection = 'none';
+ for (const edge of graph.edges) {
+ if (!relations.has(edge.type)) continue;
+ for (const id of [edge.source, edge.target]) {
+ const path = byId.get(id)?.file_path; const file = path ? files.get(pathKey(path)) : undefined;
+ if (file) file.connection = 'connected';
+ }
+ }
+ const areaFiles = new Map<string, FileMeasure[]>();
+ for (const file of files.values()) {
+ const area = areaOf(file.path); const items = areaFiles.get(area) ?? [];
+ items.push(file); areaFiles.set(area, items);
+ }
+ const areas = new Map([...areaFiles].map(([area, members]) => [area, summarize(members)]));
+ const total = summarize([...files.values()]);
+ const largest = (entries: [string, number | undefined][]) => {
+ let result: { path: string; lines: number } | undefined;
+ for (const [path, lines] of entries) {
+ if (lines === undefined) continue;
+ if (!result || lines > result.lines || (lines === result.lines && compare(path, result.path) < 0)) result = { path, lines };
+ }
+ return result;
+ };
+ // Root-direct files remain truthful measurements, but the root platform is
+ // the visual baseline rather than a competing folder-size denominator.
+ const folderReference = largest([...areas].filter(([path]) => path !== '(root)').map(([path, area]) => [path, area.lines]));
+ const reference = folderReference ?? largest([...files.values()].map(file => [file.path, file.lines]));
+ return { files, areas, total, referenceLines: Math.max(1, reference?.lines ?? 1),
+ referenceKind: folderReference ? 'folder' : 'file', referencePath: reference?.path,
+ partial: graph.total_nodes > graph.nodes.length || total.measuredFiles < total.files };
+}
+
+export function measureSourceNode(node: SemanticNode, catalog: SourceCatalog): SourceMeasure | undefined {
+ if (node.kind === 'area') return node.areaPath ? catalog.areas.get(pathKey(node.areaPath)) : undefined;
+ if (node.kind !== 'file' || !node.filePath) return undefined;
+ const file = catalog.files.get(pathKey(node.filePath));
+ return file ? summarize([file]) : undefined;
+}
+
+/** Raw relative size, independent of the compressed height used by the scene. */
+export function sourceNodeSizePercent(node: SemanticNode, catalog: SourceCatalog): number | undefined {
+ if (node.kind === 'area' && node.areaPath && pathKey(node.areaPath) === '(root)') return 0;
+ const lines = measureSourceNode(node, catalog)?.lines;
+ if (lines === undefined || !Number.isFinite(lines) || lines < 0 || catalog.referencePath === undefined) return undefined;
+ const reference = Number.isFinite(catalog.referenceLines) ? Math.max(1, catalog.referenceLines) : 1;
+ return Math.min(1, lines / reference) * 100;
+}
+
+/** Bounded square-root scale keeps smaller files visible with a distinct height spread. */
+export function sourceBrickHeight(lines: number | undefined, referenceLines: number): number {
+ if (lines === undefined || !Number.isFinite(lines) || lines < 0) return 0.65;
+ const reference = Number.isFinite(referenceLines) ? Math.max(1, referenceLines) : 1;
+ return 1.5 + 12.5 * Math.sqrt(Math.min(1, lines / reference));
+}
diff --git a/graph-ui/src/architecture/spatial-architecture.css b/graph-ui/src/architecture/spatial-architecture.css
index e698ec42f..30714b60e 100644
--- a/graph-ui/src/architecture/spatial-architecture.css
+++ b/graph-ui/src/architecture/spatial-architecture.css
@@ -18,7 +18,17 @@
.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-map .architecture-node-label:not(.is-selected) { padding:5px 7px; min-width:0; max-width:112px; background:#0e1925e8; }
+.spatial-map .architecture-node-label:not(.is-selected) strong { font-size:10px; }
+.architecture-hotspot-mark { color:#edb780; }
+.spatial-hotspot-key { color:#d5b38d; }
+.spatial-gravity-toggle input { accent-color:#dbac7b; }
+.spatial-projection-modes { display:flex; gap:4px; }
+.spatial-hotspot-details { margin:16px 0; padding:0 0 12px; border-block:1px solid #66503a; }
+.spatial-hotspot-details article { padding:10px 0; border-bottom:1px solid #3c382d; }
+.spatial-hotspot-details article button { text-align:left; overflow-wrap:anywhere; }
+.spatial-hotspot-details article > div { display:flex; flex-wrap:wrap; gap:5px; margin-top:7px; }
+.spatial-hotspot-details article span { color:#dfc39f; background:#30271e; border:1px solid #574430; border-radius:4px; padding:3px 5px; font-size:10px; }
.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; }
@@ -41,6 +51,33 @@
.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-encoding-controls { display:flex; flex-wrap:wrap; align-items:center; gap:10px 18px; padding:10px 20px; border-bottom:1px solid var(--spatial-line); font-size:11px; color:var(--spatial-muted); background:#0d1b1e; }
+.spatial-encoding-controls label { display:flex; align-items:center; gap:7px; }
+.spatial-encoding-controls select { font-size:11px; padding:5px 8px; }
+.spatial-language-legend { display:flex; flex-wrap:wrap; gap:10px; margin-left:auto; font-size:10px; }
+.spatial-language-legend span, .spatial-language-breakdown li { display:flex; align-items:center; gap:6px; }
+.spatial-language-legend i, .spatial-language-breakdown i { width:7px; height:7px; border-radius:2px; flex-shrink:0; }
+.spatial-source-metrics { margin:16px 0; padding:14px 0; border-block:1px solid var(--spatial-line); }
+.spatial-source-total { display:flex; flex-wrap:wrap; align-items:baseline; gap:6px; }
+.spatial-source-total strong { font-size:28px; font-weight:500; letter-spacing:-.045em; }
+.spatial-source-total span { font-size:11px; color:var(--spatial-muted); }
+.spatial-source-share { margin:14px 0 8px; font-size:11px; color:#bbd6ce; }
+.spatial-source-share [role=meter] { height:4px; margin-top:7px; background:#203b38; border-radius:3px; overflow:hidden; }
+.spatial-source-share i { display:block; height:100%; background:#96d5c3; }
+.spatial-source-metrics h4 span { text-transform:none; letter-spacing:0; font-weight:400; }
+.spatial-language-bar { display:flex; height:6px; border-radius:3px; overflow:hidden; background:#263837; }
+.spatial-language-breakdown { padding:0; margin:10px 0; list-style:none; display:flex; flex-direction:column; gap:7px; font-size:11px; }
+.spatial-language-breakdown li > span:last-child { margin-left:auto; color:var(--spatial-muted); font-variant-numeric:tabular-nums; }
+.spatial-measure-note { padding:0 20px; font-size:10px; line-height:1.6; color:var(--spatial-muted); }
+.spatial-file-inventory { padding:0 20px 14px; border-top:1px solid var(--spatial-line); }
+.spatial-file-inventory > p { font-size:11px; line-height:1.6; color:var(--spatial-muted); max-width:900px; }
+.spatial-file-inventory label { display:flex; flex-wrap:wrap; align-items:center; gap:10px; margin:12px 0; font-size:12px; }
+.spatial-file-inventory input { border:1px solid var(--spatial-line); border-radius:5px; background:#0b1517; color:#deece7; padding:8px 10px; min-width:min(340px,65vw); }
+.spatial-inventory-list { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,320px),1fr)); gap:8px; }
+.spatial-inventory-list article { padding:10px; border:1px solid var(--spatial-line); border-radius:6px; min-width:0; }
+.spatial-inventory-list button:first-child { display:block; max-width:100%; overflow-wrap:anywhere; text-align:left; border:0; padding:0; background:none; }
+.spatial-inventory-list article > button:last-child { margin-top:8px; font-size:10px; padding:4px 7px; }
+.spatial-file-inventory > button { margin-top:10px; }
.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/graph-ui/src/architecture/strings.ts b/graph-ui/src/architecture/strings.ts
index d7efabfa9..97552c13a 100644
--- a/graph-ui/src/architecture/strings.ts
+++ b/graph-ui/src/architecture/strings.ts
@@ -7,7 +7,7 @@ export const architectureText = {
inspectEdges: 'Inspect edges',
retainedEdges: (count: number, reported: number) => `${count} retained edges from a boundary reporting ${reported} calls. Package membership uses the same index rule as the summary. Counts may differ across bounds or index updates.`,
edgeEvidenceUnavailable: 'No constituent edge is available in the loaded map snapshot. The summary count alone cannot establish a path or source location; refresh or inspect the source area.',
- views: { overview: 'Overview', dependencies: 'Dependencies', entryPoints: 'Entry points', routes: 'Routes', hotspots: 'Hotspots' },
+ views: { overview: 'Overview', dependencies: 'Overview', entryPoints: 'Entry points', routes: 'Routes', hotspots: 'Hotspots', structure: 'System structure', behavior: 'Behavior' },
navigation: 'Architecture views',
refresh: 'Refresh',
reset: 'Reset view',
diff --git a/graph-ui/src/architecture/system-architecture-model.test.ts b/graph-ui/src/architecture/system-architecture-model.test.ts
new file mode 100644
index 000000000..4f03b1513
--- /dev/null
+++ b/graph-ui/src/architecture/system-architecture-model.test.ts
@@ -0,0 +1,273 @@
+import { describe, expect, it } from 'vitest';
+import { isContiguousPath, rankSystemPaths, systemBehaviorGraph, systemComponentGraph, systemOverviewGraph, systemBehaviorOverviewGraph } from './system-architecture-model';
+import type { SystemComponent, SystemDependency, SystemPath, SystemProjection, SystemSymbol } from './system-architecture-source';
+
+const symbol = (id: number, component = 'app'): SystemSymbol => ({ id, name: `f${id}`, qualified_name: `app.f${id}`, label: 'Function', component_id: component, file_path: `src/${component}.ts`, start_line: id });
+const component = (id: string): SystemComponent => ({ id, label: id, basis: 'declared_module', member_count: 5, file_count: 1, representatives: [] });
+const dependency = (source: string, target: string, type = 'CALLS'): SystemDependency => ({ source, target, type, count: 1, witnesses: [] });
+const projection = (components: SystemComponent[], dependencies: SystemDependency[] = []): SystemProjection => ({
+ schema_version: 1, status: 'ready', kind: 'static_projection', complete: true, components, dependencies,
+ cycles: [], entrypoints: [], paths: [], totals: {}, limits: {}, warnings: [],
+});
+const path = (nodes: SystemSymbol[], edgeBase = 100): SystemPath => ({ entrypoint_id: nodes[0].id, nodes,
+ edges: nodes.slice(1).map((node, index) => ({ id: edgeBase + index, source_id: nodes[index].id, target_id: node.id, type: 'CALLS' })),
+});
+
+const overviewProjection = (ids: string[], dependencies: SystemDependency[]): SystemProjection => {
+ const components = ids.map(id => ({ ...component(`component-${id}`), group_id: id }));
+ return { ...projection(components), overview: { complete: true, grouping_basis: 'common_source_directory_aggregate',
+ groups: ids.map(id => ({ id, label: `src/${id}`, role: 'non_test', component_count: 1, member_count: 5,
+ file_count: 1, component_ids: [`component-${id}`], representatives: [] })),
+ components, connections: dependencies, totals: { groups: ids.length, components: ids.length }, limits: { omitted_connections: 0 } } };
+};
+
+describe('persistent system overview', () => {
+ it('keeps directory siblings on a shared platform without assigning execution order', () => {
+ const data = overviewProjection(['pkg/a', 'src/b', 'tools', 'src/a', 'pkg/b'], [dependency('pkg/a', 'src/a')]);
+ data.overview!.groups.forEach(group => { group.label = group.id; });
+ const model = systemOverviewGraph(data);
+ expect(model.lanes.map(lane => lane.label)).toEqual(['pkg', 'src', 'tools']);
+ for (const node of model.nodes) {
+ const lane = model.lanes.find(item => item.label === node.label.split('/')[0])!;
+ expect(Math.abs(node.position[0] - lane.position[0]) + node.size![0] / 2).toBeLessThan(lane.width / 2);
+ expect(Math.abs(node.position[1] - lane.position[1]) + node.size![1] / 2).toBeLessThan(lane.height! / 2);
+ }
+ const changedEdges = systemOverviewGraph({ ...data, overview: { ...data.overview!, connections: [dependency('src/a', 'pkg/b')] } });
+ expect(changedEdges.nodes.map(node => node.position)).toEqual(model.nodes.map(node => node.position));
+ expect(changedEdges.scopeKey).toBe(model.scopeKey);
+ expect(changedEdges.edges.map(edge => [edge.source, edge.target])).toEqual([['src/a', 'pkg/b']]);
+ });
+ it('orders by source paths rather than opaque group IDs and separates missing locations', () => {
+ const data = overviewProjection(['opaque-z', 'opaque-a', 'opaque-q', 'opaque-r'], []);
+ data.overview!.groups.forEach((group, index) => { group.label = ['src/api', 'src/store', '(root)', '@no-source'][index]; });
+ const base = systemOverviewGraph(data);
+ expect(base.lanes.map(lane => lane.label)).toEqual(['Repository root', 'src/api', 'src/store', 'Location unavailable']);
+ const renamed = systemOverviewGraph({ ...data, overview: { ...data.overview!, groups: [...data.overview!.groups].reverse().map(group => ({ ...group, id: `new-${group.label}` })) } });
+ for (const node of base.nodes) expect(renamed.nodes.find(item => item.label === node.label)?.position).toEqual(node.position);
+ expect(new Set(base.nodes.map(node => node.position.join(','))).size).toBe(4);
+ });
+ it('uses common source directories as layout hints when no aggregate directory is reported', () => {
+ const data = projection([{ ...component('opaque'), representatives: [
+ { ...symbol(1), file_path: 'client/api/start.ts' }, { ...symbol(2), file_path: 'client/api/end.ts' },
+ ] }, component('unknown')]);
+ const model = systemOverviewGraph(data);
+ expect(model.lanes.map(lane => lane.label)).toEqual(['client/api', 'Location unavailable']);
+ expect(model.nodes[0].component?.basis).toBe('declared_module');
+ });
+ it('represents every returned group and preserves all typed directed relationships, including internal aggregates', () => {
+ const dependencies = [dependency('a', 'b'), { ...dependency('a', 'b', 'IMPORTS'), count: 3 },
+ dependency('b', 'c'), dependency('c', 'a'), { ...dependency('a', 'a', 'USAGE'), count: 7 }];
+ const model = systemOverviewGraph(overviewProjection(['a', 'b', 'c', 'isolated'], dependencies));
+ expect(model.nodes.map(node => node.id).sort()).toEqual(['a', 'b', 'c', 'isolated']);
+ expect(model.edges).toHaveLength(4);
+ expect(model.edges.flatMap(edge => edge.dependencies ?? [])).toEqual(expect.arrayContaining(dependencies));
+ expect(model.edges.reduce((sum, edge) => sum + edge.count, 0)).toBe(13);
+ expect(model.edges.filter(edge => edge.cycle)).toHaveLength(3);
+ expect(model.edges.find(edge => edge.source === edge.target)?.cycle).toBe(false);
+ expect(model.omittedNodes).toBe(0); expect(model.omittedEdges).toBe(0);
+ });
+ it('keeps coordinates and layout identity stable across data order, selection scopes and relationship filters', () => {
+ const data = overviewProjection(['a', 'b', 'c'], [dependency('a', 'b'), dependency('b', 'c', 'IMPORTS')]);
+ const base = systemOverviewGraph(data);
+ const reversed = { ...data, overview: { ...data.overview!, groups: [...data.overview!.groups].reverse(), connections: [...data.overview!.connections].reverse() } };
+ const focused = systemOverviewGraph(reversed, { focusId: 'b', relationshipTypes: ['CALLS'] });
+ expect(focused.scopeKey).toBe(base.scopeKey);
+ for (const node of focused.nodes) expect(node.position).toEqual(base.nodes.find(other => other.id === node.id)!.position);
+ const filtered = systemOverviewGraph(data, { filter: 'src/b' });
+ expect(filtered.nodes).toHaveLength(1); expect(filtered.nodes[0].position).toEqual(base.nodes.find(node => node.id === 'b')!.position);
+ });
+ it('expands within a fixed boundary and retains full membership in an inspectable remainder', () => {
+ const data = overviewProjection(['a', 'b'], [dependency('a', 'b')]);
+ const members = Array.from({ length: 20 }, (_, index) => ({ ...component(`member-${index.toString().padStart(2, '0')}`), group_id: 'a' }));
+ data.overview!.components = [...members, data.overview!.components[1]];
+ data.overview!.groups[0] = { ...data.overview!.groups[0], component_count: members.length, component_ids: members.map(item => item.id) };
+ const base = systemOverviewGraph(data), expanded = systemOverviewGraph(data, { expandedGroupIds: ['a'], focusId: 'member-19' });
+ expect(expanded.nodes.find(node => node.id === 'b')!.position).toEqual(base.nodes.find(node => node.id === 'b')!.position);
+ expect(expanded.nodes.find(node => node.id === 'a')!.size).toEqual(base.nodes.find(node => node.id === 'a')!.size);
+ expect(expanded.edges.map(edge => [edge.source, edge.target])).toEqual([['a', 'b']]);
+ const children = expanded.nodes.filter(node => node.parentId === 'a');
+ expect(children).toHaveLength(12);
+ expect(new Set(children.flatMap(node => node.componentIds ?? []))).toEqual(new Set(members.map(item => item.id)));
+ expect(children.find(node => node.id === expanded.focusId)?.component?.id).toBe('member-19');
+ expect(children.find(node => node.kind === 'remainder')?.componentIds).toHaveLength(9);
+ });
+ it('does not derive a visible cycle through hidden test groups or excluded relationship types', () => {
+ const data = overviewProjection(['a', 'test'], [dependency('a', 'test'), dependency('test', 'a', 'IMPORTS')]);
+ data.overview!.groups[1].role = 'test';
+ expect(systemOverviewGraph(data, { cyclesOnly: true }).nodes).toHaveLength(0);
+ expect(systemOverviewGraph(data, { cyclesOnly: true, includeTests: true, relationshipTypes: ['CALLS'] }).nodes).toHaveLength(0);
+ expect(systemOverviewGraph(data, { cyclesOnly: true, includeTests: true }).edges).toHaveLength(2);
+ });
+ it('leaves the overview unhighlighted while choosing a target', () => {
+ const data = overviewProjection(['a', 'b'], [dependency('a', 'b')]);
+ data.behavior = { mode: 'targets', source_id: 1, complete: true, limits_hit: [], reachable_targets: [], totals: {}, nodes: [], edges: [], cycles: [], max_hops: 8 };
+ const base = systemOverviewGraph(data);
+ expect(systemBehaviorOverviewGraph(data, base, [path([symbol(1), symbol(2)])], 0)).toBe(base);
+ });
+ it('preserves corridor joins, cycle edges and exact provenance while reusing all overview coordinates', () => {
+ const data = overviewProjection(['a', 'b', 'c', 'd'], [dependency('a', 'b'), dependency('a', 'c'), dependency('b', 'd'), dependency('c', 'd'), dependency('d', 'b')]);
+ const symbols = ['a', 'b', 'c', 'd'].map((id, index) => ({ ...symbol(index + 1, `component-${id}`), group_id: id }));
+ const edge = (id: number, source: number, target: number) => ({ id, source_id: source, target_id: target, type: 'CALLS', callsite: { file_path: 'src/a.c', line: id } });
+ const evidence = [edge(10, 1, 2), edge(11, 1, 3), edge(12, 2, 4), edge(13, 3, 4), edge(14, 4, 2)];
+ data.behavior = { mode: 'corridor', source_id: 1, target_id: 4, complete: true, limits_hit: [], reachable_targets: [], totals: {}, nodes: symbols, edges: evidence, cycles: [{ node_ids: [2, 4] }], max_hops: 8 };
+ const paths = [{ entrypoint_id: 1, nodes: [symbols[0], symbols[1], symbols[3]], edges: [evidence[0], evidence[2]] },
+ { entrypoint_id: 1, nodes: [symbols[0], symbols[2], symbols[3]], edges: [evidence[1], evidence[3]] }];
+ const base = systemOverviewGraph(data), first = systemBehaviorOverviewGraph(data, base, paths, 0), second = systemBehaviorOverviewGraph(data, base, paths, 1);
+ expect(first.nodes.map(node => [node.id, node.position])).toEqual(base.nodes.map(node => [node.id, node.position]));
+ expect(first.scopeKey).toBe(base.scopeKey); expect(second.scopeKey).toBe(base.scopeKey);
+ expect(second.edges.map(item => item.id)).toEqual(first.edges.map(item => item.id));
+ expect(first.edges.flatMap(item => item.behaviorEdges ?? []).sort((a, b) => a.id - b.id)).toEqual(evidence);
+ expect(first.nodes.find(node => node.id === 'd')?.pathIndices).toEqual([0, 1]);
+ expect(first.edges.find(item => item.source === 'd' && item.target === 'b')?.behaviorEdges).toEqual([evidence[4]]);
+ expect(first.nodes).toHaveLength(4);
+ });
+});
+
+describe('focused component neighborhoods', () => {
+ it('draws only anchor-touching dependencies and keeps all underlying typed evidence', () => {
+ const first = dependency('client', 'service'), otherType = dependency('client', 'service', 'IMPORTS');
+ first.witnesses = [{ edge_id: 42, source: symbol(1, 'client'), target: symbol(2, 'service') }];
+ const data = projection(['client', 'service', 'store'].map(component), [first, otherType,
+ dependency('service', 'store'), dependency('client', 'store')]);
+ const model = systemComponentGraph(data, '', false, false, false, 'service');
+ expect(model.focusId).toBe('service');
+ expect(model.edges.every(edge => edge.source === 'service' || edge.target === 'service')).toBe(true);
+ expect(model.edges.map(edge => edge.type)).toEqual(['CALLS', 'IMPORTS', 'CALLS']);
+ expect(model.edges[0].dependency?.witnesses).toBe(first.witnesses);
+ expect(model.omittedEdges).toBe(1);
+ });
+ it('places callers before the anchor and callees after it', () => {
+ const data = projection(['client', 'service', 'store', 'peer'].map(component), [dependency('client', 'service'),
+ dependency('service', 'store'), dependency('service', 'peer'), dependency('peer', 'service')]);
+ const model = systemComponentGraph(data, '', false, false, false, 'service');
+ const nodes = new Map(model.nodes.map(node => [node.id, node]));
+ expect(nodes.get('client')!.position[0]).toBeLessThan(nodes.get('service')!.position[0]);
+ expect(nodes.get('store')!.position[0]).toBeGreaterThan(nodes.get('service')!.position[0]);
+ expect(nodes.get('peer')!.position[1]).toBeGreaterThan(nodes.get('service')!.position[1]);
+ expect(model.edges.filter(edge => edge.source === 'peer' || edge.target === 'peer')).toHaveLength(2);
+ });
+ it('bounds the neighborhood while accounting for the remaining components and neighbors', () => {
+ const data = projection(Array.from({ length: 31 }, (_, index) => component(`c${index}`)),
+ Array.from({ length: 30 }, (_, index) => dependency('c0', `c${index + 1}`)));
+ const model = systemComponentGraph(data, '', false);
+ expect(model.focusId).toBe('c0'); expect(model.nodes).toHaveLength(8); expect(model.edges).toHaveLength(7);
+ expect(model.omittedNodes).toBe(23); expect(model.omittedNeighbors).toBe(23);
+ expect(model.nodes.length + model.omittedNodes).toBe(data.components.length);
+ expect(model.nodes.slice(1).every(node => node.position[0] >= 60)).toBe(true);
+ expect(model.captions!.every(caption => caption.position[1] >= Math.max(...model.nodes.map(node => node.position[1])) + 17)).toBe(true);
+ });
+ it('retains both relationship directions without exceeding the total neighborhood cap', () => {
+ const ids = Array.from({ length: 20 }, (_, index) => `c${index}`);
+ const data = projection(['focus', ...ids].map(component), ids.map((id, index) => index < 10
+ ? dependency('focus', id) : dependency(id, 'focus')));
+ const model = systemComponentGraph(data, '', false, false, false, 'focus');
+ expect(model.nodes).toHaveLength(14);
+ expect(model.nodes.filter(node => node.position[0] < 0).length).toBeGreaterThanOrEqual(6);
+ expect(model.nodes.filter(node => node.position[0] > 0).length).toBeGreaterThanOrEqual(6);
+ expect(model.omittedNeighbors).toBe(7);
+ expect(model.captions?.map(caption => caption.label)).toEqual(['Used by', 'Focus', 'Uses']);
+ });
+ it('prioritizes strong direct focal relationships over globally popular weak neighbors', () => {
+ const local = Array.from({ length: 7 }, (_, index) => `local${index}`);
+ const hubs = Array.from({ length: 8 }, (_, index) => `hub${index}`);
+ const satellites = Array.from({ length: 8 }, (_, index) => `satellite${index}`);
+ const data = projection(['focus', ...local, ...hubs, ...satellites].map(component), [
+ ...local.map(id => ({ ...dependency('focus', id), count: id === 'local0' ? 1 : 2 })),
+ { ...dependency('focus', 'local0', 'IMPORTS'), count: 2 },
+ ...hubs.map(id => dependency('focus', id)),
+ ...hubs.flatMap(hub => satellites.map(satellite => ({ ...dependency(hub, satellite), count: 50 }))),
+ ]);
+ const model = systemComponentGraph(data, '', false, false, false, 'focus');
+ expect(model.nodes.slice(1).map(node => node.id)).toEqual(local);
+ expect(model.nodes.slice(1).every(node => node.position[0] > 0)).toBe(true);
+ expect(model.edges.filter(edge => edge.target === 'local0').map(edge => [edge.type, edge.count])).toEqual([['CALLS', 1], ['IMPORTS', 2]]);
+ expect(model.omittedNeighbors).toBe(8);
+ expect(model.nodes.length + model.omittedNodes).toBe(data.components.length);
+ });
+ it('allows any included isolated component to become the new focus without unrelated edges', () => {
+ const data = projection(['client', 'service', 'isolated'].map(component), [dependency('client', 'service')]);
+ const before = systemComponentGraph(data, '', false, true);
+ const after = systemComponentGraph(data, '', false, true, false, 'isolated');
+ expect(after.focusId).toBe('isolated'); expect(after.nodes.map(node => node.id)).toEqual(['isolated']);
+ expect(after.edges).toHaveLength(0); expect(after.omittedNodes).toBe(2);
+ expect(after.scopeKey).not.toBe(before.scopeKey);
+ });
+});
+
+describe('behavior prefix trees', () => {
+ it('shares common prefixes while retaining path membership and actual handoffs', () => {
+ const first = symbol(1, 'api'), second = symbol(2, 'service');
+ const left = path([first, second, symbol(3, 'store')]);
+ const right = path([first, second, symbol(4, 'queue')]); right.edges[1].id = 102;
+ const model = systemBehaviorGraph(projection([]), [left, right]);
+ expect(model.nodes).toHaveLength(4); expect(model.edges).toHaveLength(3);
+ expect(model.nodes.find(node => node.symbol?.id === 2)?.pathIndices).toEqual([0, 1]);
+ expect(model.nodes.find(node => node.symbol?.id === 3)?.pathIndices).toEqual([0]);
+ expect(model.nodes.find(node => node.symbol?.id === 4)?.pathIndices).toEqual([1]);
+ expect(model.edges.every(edge => edge.handoff)).toBe(true);
+ expect(model.nodes.find(node => node.symbol?.id === 3)?.position[1]).not.toBe(model.nodes.find(node => node.symbol?.id === 4)?.position[1]);
+ });
+ it('never reconverges separate branches through a shared symbol into a synthetic path', () => {
+ const first = symbol(1), last = symbol(4);
+ const paths = [path([first, symbol(2), last], 100), path([first, symbol(3), last], 200)];
+ const model = systemBehaviorGraph(projection([]), paths);
+ const endings = model.nodes.filter(node => node.symbol?.id === 4);
+ expect(endings).toHaveLength(2); expect(endings[0].id).not.toBe(endings[1].id);
+ for (const [index, original] of paths.entries()) {
+ const edges = model.edges.filter(edge => edge.pathIndices?.includes(index));
+ expect(edges.map(edge => edge.pathEdge)).toEqual(original.edges);
+ expect(edges[0].target).toBe(edges[1].source);
+ }
+ });
+ it('preserves relationship type distinctions instead of merging different evidence', () => {
+ const first = path([symbol(1), symbol(2)]);
+ const second = path([symbol(1), symbol(2)]); second.edges[0].type = 'ASYNC_CALLS';
+ const model = systemBehaviorGraph(projection([]), [first, second]);
+ expect(model.nodes).toHaveLength(3);
+ expect(model.edges.map(edge => edge.type)).toEqual(['CALLS', 'ASYNC_CALLS']);
+ expect(model.edges.map(edge => edge.pathIndices)).toEqual([[0], [1]]);
+ });
+ it('prefers a longer component-crossing path without changing the input indices', () => {
+ const paths = [path([symbol(1), symbol(2)]), path([symbol(1), symbol(3, 'service'), symbol(4, 'store')], 200)];
+ expect(rankSystemPaths(paths)).toEqual([1, 0]);
+ const model = systemBehaviorGraph(projection([]), paths);
+ expect(model.preferredPathIndex).toBe(1);
+ expect(model.nodes.find(node => node.symbol?.id === 4)?.pathIndices).toEqual([1]);
+ });
+ it('keeps only one entrypoint and rejects disconnected input paths', () => {
+ const valid = path([symbol(1), symbol(2)]), disconnected = path([symbol(1), symbol(3)]);
+ disconnected.edges[0].source_id = 88;
+ const model = systemBehaviorGraph(projection([]), [disconnected, valid, path([symbol(9), symbol(10)])]);
+ expect(isContiguousPath(disconnected)).toBe(false);
+ expect(model.nodes.map(node => node.symbol?.id)).toEqual([1, 2]);
+ expect(model.nodes.every(node => node.pathIndices?.join() === '1')).toBe(true);
+ });
+ it('caps visible prefixes while retaining their parents and reporting every omission', () => {
+ const paths = Array.from({ length: 20 }, (_, index) => path([symbol(1), ...Array.from({ length: 4 }, (_, depth) => symbol(index * 10 + depth + 2))], index * 10));
+ const model = systemBehaviorGraph(projection([]), paths);
+ expect(model.nodes).toHaveLength(36); expect(model.omittedNodes).toBe(45);
+ expect(model.edges).toHaveLength(35); expect(model.omittedEdges).toBe(45);
+ const ids = new Set(model.nodes.map(node => node.id));
+ expect(model.edges.every(edge => ids.has(edge.source) && ids.has(edge.target))).toBe(true);
+ expect(model.nodes.filter(node => node.id !== model.nodes[0].id).every(node => model.edges.some(edge => edge.target === node.id))).toBe(true);
+ });
+ it('brings a previously omitted selected branch into view without reassigning prefix identities', () => {
+ const paths = Array.from({ length: 20 }, (_, index) => path([symbol(1), ...Array.from({ length: 4 }, (_, depth) => symbol(index * 10 + depth + 2))], index * 10));
+ const initial = systemBehaviorGraph(projection([]), paths);
+ const selected = systemBehaviorGraph(projection([]), paths, 19);
+ expect(initial.nodes.some(node => node.symbol?.id === paths[19].nodes.at(-1)?.id)).toBe(false);
+ expect(selected.nodes.filter(node => node.pathIndices?.includes(19)).map(node => node.symbol?.id)).toEqual(paths[19].nodes.map(node => node.id));
+ expect(selected.nodes).toHaveLength(36);
+ for (const node of selected.nodes) {
+ const previous = initial.nodes.find(candidate => candidate.id === node.id);
+ if (previous) expect(previous.symbol?.id).toBe(node.symbol?.id);
+ }
+ expect(selected.scopeKey).not.toBe(initial.scopeKey);
+ });
+ it('keeps positions and fit scope stable when changing highlights inside an uncapped tree', () => {
+ const paths = [path([symbol(1), symbol(2)], 10), path([symbol(1), symbol(3)], 20)];
+ const first = systemBehaviorGraph(projection([]), paths, 0), second = systemBehaviorGraph(projection([]), paths, 1);
+ expect(first.scopeKey).toBe(second.scopeKey);
+ expect(first.nodes.map(node => [node.id, node.position])).toEqual(second.nodes.map(node => [node.id, node.position]));
+ });
+});
diff --git a/graph-ui/src/architecture/system-architecture-model.ts b/graph-ui/src/architecture/system-architecture-model.ts
new file mode 100644
index 000000000..21ba2d5fe
--- /dev/null
+++ b/graph-ui/src/architecture/system-architecture-model.ts
@@ -0,0 +1,388 @@
+import type { SystemComponent, SystemDependency, SystemOverviewGroup, SystemPath, SystemPathEdge, SystemProjection, SystemSymbol } from './system-architecture-source';
+
+export interface SystemSceneNode {
+ id: string; label: string; detail: string; position: [number, number, number];
+ component?: SystemComponent; symbol?: SystemSymbol;
+ pathIndices?: number[]; depth?: number; handoff?: boolean; hiddenChildren?: number;
+ group?: SystemOverviewGroup; groupId?: string; componentIds?: string[];
+ kind?: 'group' | 'component' | 'remainder'; parentId?: string; expanded?: boolean;
+ size?: [number, number, number]; inCorridor?: boolean;
+ visual?: { color: string; label: string; basis?: string };
+}
+export interface SystemSceneEdge {
+ id: string; source: string; target: string; type: string; count: number;
+ dependency?: SystemDependency; pathEdge?: SystemPath['edges'][number];
+ pathIndices?: number[]; depth?: number; handoff?: boolean;
+ dependencies?: SystemDependency[]; types?: string[]; cycle?: boolean;
+ inCorridor?: boolean; behaviorEdges?: SystemPathEdge[];
+}
+export interface SystemSceneLane {
+ id: string; label: string; position: [number, number, number]; width: number; depth: number;
+ height?: number; pathIndices?: number[];
+}
+export interface SystemSceneModel {
+ nodes: SystemSceneNode[]; edges: SystemSceneEdge[]; lanes: SystemSceneLane[];
+ omittedNodes: number; omittedEdges: number;
+ focusId?: string; scopeKey?: string; preferredPathIndex?: number;
+ omittedNeighbors?: number;
+ highlightActive?: boolean; componentNodeIds?: Record<string, string>; groupNodeIds?: Record<string, string>;
+ captions?: { label: string; position: [number, number, number] }[];
+}
+export const componentBasis = (basis: string): string => basis === 'declared_module' ? 'Declared module'
+ : basis === 'interaction_community' ? 'Inferred collaboration' : basis === 'unassigned' ? 'Unassigned'
+ : basis === 'common_source_directory_aggregate' ? 'Source directory group' : basis === 'aggregate_remainder' ? 'Other components' : 'Inferred component';
+
+export interface SystemOverviewOptions {
+ expandedGroupIds?: readonly string[]; focusId?: string; relationshipTypes?: readonly string[];
+ includeTests?: boolean; includeUnconnected?: boolean; filter?: string; cyclesOnly?: boolean; layoutKey?: string;
+}
+
+/** Tarjan groups are layout constraints, not a claim about execution cycles. */
+function stronglyConnected(ids: readonly string[], pairs: readonly { source: string; target: string }[]): string[][] {
+ const allowed = new Set(ids), adjacent = new Map(ids.map(id => [id, new Set<string>()]));
+ for (const edge of pairs) if (allowed.has(edge.source) && allowed.has(edge.target)) adjacent.get(edge.source)!.add(edge.target);
+ let next = 0;
+ const index = new Map<string, number>(), low = new Map<string, number>(), active = new Set<string>(), stack: string[] = [], result: string[][] = [];
+ const visit = (id: string) => {
+ index.set(id, next); low.set(id, next++); stack.push(id); active.add(id);
+ for (const target of [...adjacent.get(id)!].sort()) {
+ if (!index.has(target)) { visit(target); low.set(id, Math.min(low.get(id)!, low.get(target)!)); }
+ else if (active.has(target)) low.set(id, Math.min(low.get(id)!, index.get(target)!));
+ }
+ if (low.get(id) !== index.get(id)) return;
+ const members: string[] = [];
+ let member: string;
+ do { member = stack.pop()!; active.delete(member); members.push(member); } while (member !== id);
+ result.push(members.sort());
+ };
+ [...ids].sort().forEach(id => { if (!index.has(id)) visit(id); });
+ return result.sort((a, b) => a[0].localeCompare(b[0]));
+}
+
+interface OverviewLayout { positions: Map<string, [number, number, number]>; lanes: SystemSceneLane[]; key: string }
+const overviewLayouts = new Map<string, OverviewLayout>();
+const comparePath = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
+const normalizedPath = (path: string) => path.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+$/, '');
+
+/** A location hint only: representatives cannot establish full component membership. */
+function groupDirectory(group: SystemOverviewGroup, groupingBasis?: string): string | undefined {
+ if ((group.basis ?? groupingBasis) === 'common_source_directory_aggregate') {
+ const path = normalizedPath(group.label);
+ if (['.', '(root)'].includes(path)) return '';
+ if (path === '@no-source') return undefined;
+ return path;
+ }
+ const paths = group.representatives.map(symbol => symbol.file_path).filter((path): path is string => Boolean(path));
+ if (!paths.length) return undefined;
+ const directories = paths.map(path => normalizedPath(path).split('/').slice(0, -1));
+ const common = [...directories[0]];
+ for (const directory of directories.slice(1)) while (common.some((segment, index) => directory[index] !== segment)) common.pop();
+ return common.join('/');
+}
+
+/** Directory neighborhoods organize space, never execution order or responsibilities.
+ * Calculate from the full snapshot before filters; expansion stays inside fixed footprints. */
+function overviewLayout(groups: readonly SystemOverviewGroup[], groupingBasis?: string): OverviewLayout {
+ const ordered = groups.map(group => ({ group, path: groupDirectory(group, groupingBasis) }))
+ .sort((a, b) => comparePath(a.path ?? '\uffff', b.path ?? '\uffff') || comparePath(a.group.label, b.group.label) || comparePath(a.group.id, b.group.id));
+ const key = JSON.stringify(ordered.map(({ group, path }) => [group.id, group.label, path]));
+ const cached = overviewLayouts.get(key);
+ if (cached) return cached;
+ // Skip a common wrapper directory, so src/api and src/store can form distinct
+ // neighborhoods in repositories whose entire source lives below src.
+ const paths = ordered.flatMap(item => item.path ? [item.path.split('/')] : []);
+ const prefix = [...(paths[0] ?? [])];
+ for (const path of paths.slice(1)) while (prefix.some((part, index) => path[index] !== part)) prefix.pop();
+ const buckets = new Map<string, typeof ordered>();
+ for (const item of ordered) {
+ const parts = item.path?.split('/') ?? [];
+ const directory = item.path === undefined ? '\uffff' : !item.path ? '' : parts.slice(0, Math.min(parts.length, prefix.length + 1)).join('/');
+ if (!buckets.has(directory)) buckets.set(directory, []);
+ buckets.get(directory)!.push(item);
+ }
+ const regions = [...buckets].map(([path, members]) => {
+ const columns = Math.max(1, Math.min(6, Math.ceil(Math.sqrt(members.length * 34 / 76 * 1.3))));
+ return { path, members, columns, width: columns * 76 + 16, height: Math.ceil(members.length / columns) * 34 + 24 };
+ });
+ const rowWidth = Math.max(0, ...regions.map(region => region.width), Math.sqrt(regions.reduce((area, region) => area + (region.width + 18) * (region.height + 18), 0) * 1.5));
+ const positions = new Map<string, [number, number, number]>(), lanes: SystemSceneLane[] = [];
+ let x = 0, y = 0, rowHeight = 0, width = 0;
+ for (const region of regions) {
+ if (x && x + region.width > rowWidth) { x = 0; y += rowHeight + 18; rowHeight = 0; }
+ region.members.forEach(({ group }, index) => positions.set(group.id, [x + 46 + index % region.columns * 76, -y - 28 - Math.floor(index / region.columns) * 34, 0]));
+ lanes.push({ id: `directory:${region.path}`, label: region.path === '\uffff' ? 'Location unavailable' : region.path || 'Repository root',
+ position: [x + region.width / 2, -y - region.height / 2, -4], width: region.width, height: region.height, depth: .5 });
+ width = Math.max(width, x + region.width); rowHeight = Math.max(rowHeight, region.height); x += region.width + 18;
+ }
+ const height = y + rowHeight;
+ for (const position of [...positions.values(), ...lanes.map(lane => lane.position)]) { position[0] -= width / 2; position[1] += height / 2; }
+ const layout = { positions, lanes, key };
+ overviewLayouts.set(key, layout);
+ if (overviewLayouts.size > 12) overviewLayouts.delete(overviewLayouts.keys().next().value!);
+ return layout;
+}
+
+/** The default overview is the complete returned coarse graph, not an ego graph. */
+export function systemOverviewGraph(data: SystemProjection, options: SystemOverviewOptions = {}): SystemSceneModel {
+ const components = data.overview?.components ?? data.components;
+ const componentMap = new Map(components.map(component => [component.id, component]));
+ const groups: SystemOverviewGroup[] = data.overview?.groups ?? components.map(component => ({ ...component, component_count: 1, component_ids: [component.id] }));
+ const allEdges = data.overview?.connections ?? data.dependencies;
+ const layout = overviewLayout(groups, data.overview?.grouping_basis);
+ const relationshipTypes = options.relationshipTypes ? new Set(options.relationshipTypes) : undefined;
+ const eligibleGroups = groups.filter(group => options.includeTests || group.role !== 'test');
+ const eligibleIds = new Set(eligibleGroups.map(group => group.id));
+ const edges = allEdges.filter(edge => (!relationshipTypes || relationshipTypes.has(edge.type)) && eligibleIds.has(edge.source) && eligibleIds.has(edge.target));
+ const cycleIndex = new Map<string, number>();
+ stronglyConnected(eligibleGroups.map(group => group.id), edges).filter(members => members.length > 1)
+ .forEach((members, index) => members.forEach(id => cycleIndex.set(id, index)));
+ const connected = new Set(edges.filter(edge => edge.source !== edge.target).flatMap(edge => [edge.source, edge.target]));
+ const query = options.filter?.trim().toLocaleLowerCase();
+ const visibleGroups = eligibleGroups.filter(group => (options.includeUnconnected !== false || connected.has(group.id)) && (!options.cyclesOnly || cycleIndex.has(group.id))
+ && (!query || group.label.toLocaleLowerCase().includes(query) || group.component_ids.some(id => componentMap.get(id)?.label.toLocaleLowerCase().includes(query))));
+ const visible = new Set(visibleGroups.map(group => group.id)), expanded = new Set(options.expandedGroupIds);
+ const nodes: SystemSceneNode[] = [], componentNodeIds: Record<string, string> = {}, groupNodeIds: Record<string, string> = {};
+ for (const group of visibleGroups) {
+ const position = layout.positions.get(group.id)!, members = group.component_ids.map(id => componentMap.get(id)).filter((item): item is SystemComponent => Boolean(item));
+ const isExpanded = expanded.has(group.id) && members.length > 0;
+ const groupComponent: SystemComponent = data.overview ? { id: group.id, label: group.label,
+ basis: group.basis ?? data.overview.grouping_basis, member_count: group.member_count, file_count: group.file_count,
+ role: group.role, representatives: group.representatives } : members[0];
+ nodes.push({ id: group.id, label: group.label, detail: `${group.component_count.toLocaleString()} components · ${group.member_count.toLocaleString()} symbols`,
+ component: groupComponent, group: data.overview ? group : undefined, kind: data.overview ? 'group' : 'component',
+ groupId: group.id, componentIds: [...group.component_ids], expanded: isExpanded, position: [...position], size: [62, 22, 4] });
+ groupNodeIds[group.id] = group.id;
+ group.component_ids.forEach(id => { componentNodeIds[id] = group.id; });
+ if (!isExpanded) continue;
+ const sorted = [...members].sort((a, b) => Number(b.id === options.focusId) - Number(a.id === options.focusId) || a.id.localeCompare(b.id));
+ const shown = sorted.length > 12 ? sorted.slice(0, 11) : sorted, remainder = sorted.slice(shown.length);
+ const tiles = [...shown.map(component => ({ component, ids: [component.id], kind: 'component' as const })), ...(remainder.length ? [{
+ component: { id: `${group.id}:remaining`, label: `${remainder.length} other components`, basis: 'aggregate_remainder',
+ member_count: remainder.reduce((sum, component) => sum + component.member_count, 0), file_count: remainder.reduce((sum, component) => sum + component.file_count, 0), representatives: [] },
+ ids: remainder.map(component => component.id), kind: 'remainder' as const,
+ }] : [])];
+ tiles.forEach(({ component, ids, kind }, index) => {
+ const id = `member:${group.id}:${component.id}`;
+ nodes.push({ id, label: component.label, detail: `${component.member_count.toLocaleString()} symbols`, component, componentIds: ids,
+ kind, groupId: group.id, parentId: group.id, position: [position[0] + (index % 3 - 1) * 19, position[1] + 6 - Math.floor(index / 3) * 5, 4], size: [13, 3, 2] });
+ ids.forEach(componentId => { componentNodeIds[componentId] = id; });
+ });
+ }
+ const aggregates = new Map<string, SystemSceneEdge>();
+ for (const dependency of edges) {
+ if (!visible.has(dependency.source) || !visible.has(dependency.target)) continue;
+ const cycle = dependency.source !== dependency.target && cycleIndex.has(dependency.source) && cycleIndex.get(dependency.source) === cycleIndex.get(dependency.target);
+ if (options.cyclesOnly && !cycle) continue;
+ const id = `aggregate:${JSON.stringify([dependency.source, dependency.target])}`;
+ let aggregate = aggregates.get(id);
+ if (!aggregate) { aggregate = { id, source: dependency.source, target: dependency.target, type: dependency.type, count: 0, dependencies: [], types: [], cycle }; aggregates.set(id, aggregate); }
+ aggregate.dependencies!.push(dependency); aggregate.count += dependency.count;
+ if (!aggregate.types!.includes(dependency.type)) aggregate.types!.push(dependency.type);
+ aggregate.types!.sort(); aggregate.type = aggregate.types!.length === 1 ? aggregate.types![0] : 'RELATIONSHIPS';
+ }
+ const renderedEdges = [...aggregates.values()].sort((a, b) => a.id.localeCompare(b.id));
+ const shownDependencyCount = renderedEdges.reduce((sum, edge) => sum + (edge.dependencies?.length ?? 0), 0);
+ return { nodes, edges: renderedEdges, lanes: layout.lanes, componentNodeIds, groupNodeIds,
+ focusId: options.focusId ? (nodes.some(node => node.id === options.focusId) ? options.focusId : componentNodeIds[options.focusId]) : undefined,
+ scopeKey: `overview:${options.layoutKey ?? ''}:${layout.key}`, omittedNodes: groups.length - visibleGroups.length,
+ omittedEdges: allEdges.length - shownDependencyCount + Number(data.overview?.limits.omitted_connections ?? 0) };
+}
+
+/** Decorate the shared overview with exact corridor evidence; never infer extra joins. */
+export function systemBehaviorOverviewGraph(data: SystemProjection, base: SystemSceneModel, paths: readonly SystemPath[] = data.paths, activePathIndex?: number): SystemSceneModel {
+ const behavior = data.behavior;
+ if (!behavior || behavior.mode !== 'corridor' || behavior.target_id === undefined) return base;
+ const symbols = new Map(behavior.nodes.map(symbol => [symbol.id, symbol]));
+ const nodeFor = (symbol: SystemSymbol) => base.componentNodeIds?.[symbol.component_id] ?? base.groupNodeIds?.[symbol.group_id ?? ''];
+ const groupFor = (symbol: SystemSymbol) => symbol.group_id ?? base.nodes.find(node => node.componentIds?.includes(symbol.component_id))?.groupId;
+ const visibleIds = new Set(base.nodes.map(node => node.id)), corridorNodes = new Set<string>();
+ const nodePaths = new Map<string, Set<number>>(), edgePaths = new Map<number, Set<number>>();
+ for (const [index, path] of paths.entries()) if (isContiguousPath(path)) {
+ path.nodes.forEach(symbol => {
+ for (const id of new Set([nodeFor(symbol), groupFor(symbol)])) if (id) { if (!nodePaths.has(id)) nodePaths.set(id, new Set()); nodePaths.get(id)!.add(index); }
+ });
+ path.edges.forEach(edge => { if (!edgePaths.has(edge.id)) edgePaths.set(edge.id, new Set()); edgePaths.get(edge.id)!.add(index); });
+ }
+ behavior.nodes.forEach(symbol => { const id = nodeFor(symbol), group = groupFor(symbol); if (id) corridorNodes.add(id); if (group) corridorNodes.add(group); });
+ const edges = base.edges.map(edge => ({ ...edge, inCorridor: false, behaviorEdges: [] as SystemPathEdge[], pathIndices: [] as number[] }));
+ const aggregateByPair = new Map(edges.map(edge => [JSON.stringify([edge.source, edge.target]), edge]));
+ for (const evidence of behavior.edges) {
+ const source = symbols.get(evidence.source_id), target = symbols.get(evidence.target_id);
+ if (!source || !target) continue;
+ const from = groupFor(source), to = groupFor(target);
+ if (!from || !to || !visibleIds.has(from) || !visibleIds.has(to)) continue;
+ const key = JSON.stringify([from, to]);
+ let edge = aggregateByPair.get(key);
+ if (!edge) {
+ edge = { id: `corridor:${key}`, source: from, target: to, type: evidence.type, types: [evidence.type], count: 0,
+ dependencies: [], inCorridor: true, behaviorEdges: [], pathIndices: [] };
+ edges.push(edge); aggregateByPair.set(key, edge);
+ }
+ edge.inCorridor = true; edge.behaviorEdges.push(evidence);
+ edge.pathIndices = [...new Set([...edge.pathIndices, ...(edgePaths.get(evidence.id) ?? [])])].sort((a, b) => a - b);
+ if (!edge.dependencies?.length) edge.count++;
+ }
+ return { ...base, highlightActive: true, preferredPathIndex: activePathIndex,
+ nodes: base.nodes.map(node => ({ ...node, inCorridor: corridorNodes.has(node.id), pathIndices: [...(nodePaths.get(node.id) ?? [])] })), edges };
+}
+
+/** A component cycle does not establish a contiguous symbol path through that component. */
+export function isContiguousPath(path: SystemPath): boolean {
+ return path.nodes.length > 0 && path.entrypoint_id === path.nodes[0].id && path.edges.length === path.nodes.length - 1
+ && path.edges.every((edge, index) => edge.source_id === path.nodes[index].id && edge.target_id === path.nodes[index + 1].id);
+}
+
+/** Prioritize collaboration breadth, so isolated documents do not consume the scene budget. */
+export function systemComponents(data: SystemProjection, filter: string, cyclesOnly: boolean, includeUnconnected = false, includeTests = false): SystemComponent[] {
+ const query = filter.trim().toLocaleLowerCase();
+ const candidates = data.components.filter(component => includeTests || component.role !== 'test');
+ const candidateIds = new Set(candidates.map(component => component.id));
+ const neighbors = new Map<string, Set<string>>(), counts = new Map<string, number>();
+ for (const edge of data.dependencies) {
+ if (edge.source === edge.target || !candidateIds.has(edge.source) || !candidateIds.has(edge.target)) continue;
+ for (const [id, other] of [[edge.source, edge.target], [edge.target, edge.source]]) {
+ if (!neighbors.has(id)) neighbors.set(id, new Set());
+ neighbors.get(id)!.add(other); counts.set(id, (counts.get(id) ?? 0) + edge.count);
+ }
+ }
+ const cycles = new Set(data.cycles.flatMap(cycle => cycle.component_ids));
+ return candidates.filter(component => (includeUnconnected || neighbors.has(component.id)) && (!cyclesOnly || cycles.has(component.id))
+ && (!query || [component.label, ...component.representatives.flatMap(symbol => [symbol.name, symbol.file_path ?? ''])]
+ .some(value => value.toLocaleLowerCase().includes(query))))
+ .sort((a, b) => (neighbors.get(b.id)?.size ?? 0) - (neighbors.get(a.id)?.size ?? 0)
+ || (counts.get(b.id) ?? 0) - (counts.get(a.id) ?? 0) || a.id.localeCompare(b.id));
+}
+
+export function systemComponentGraph(data: SystemProjection, filter: string, cyclesOnly: boolean, includeUnconnected = false, includeTests = false, focusId?: string): SystemSceneModel {
+ const cycleGroups = new Map<string, number>();
+ data.cycles.forEach((cycle, index) => cycle.component_ids.forEach(id => cycleGroups.set(id, index)));
+ const matching = systemComponents(data, filter, cyclesOnly, includeUnconnected, includeTests);
+ const focus = matching.find(component => component.id === focusId) ?? matching[0];
+ if (!focus) return { nodes: [], edges: [], lanes: [], omittedNodes: 0, omittedEdges: 0, scopeKey: 'structure:empty' };
+ const matchingIds = new Set(matching.map(component => component.id));
+ const dependencies = data.dependencies.filter(edge => matchingIds.has(edge.source) && matchingIds.has(edge.target)
+ && (!cyclesOnly || cycleGroups.get(edge.source) === cycleGroups.get(edge.target)));
+ const adjacent = dependencies.filter(edge => edge.source === focus.id || edge.target === focus.id);
+ const inbound = new Set(adjacent.filter(edge => edge.target === focus.id).map(edge => edge.source));
+ const outbound = new Set(adjacent.filter(edge => edge.source === focus.id).map(edge => edge.target));
+ const focalCounts = new Map<string, number>();
+ for (const edge of adjacent) {
+ const neighbor = edge.source === focus.id ? edge.target : edge.source;
+ focalCounts.set(neighbor, (focalCounts.get(neighbor) ?? 0) + edge.count);
+ }
+ // The neighborhood explains this component, so unrelated global connectivity
+ // must not displace its strongest direct relationships from the scene budget.
+ const neighbors = matching.filter(component => component.id !== focus.id && (inbound.has(component.id) || outbound.has(component.id)))
+ .sort((a, b) => (focalCounts.get(b.id) ?? 0) - (focalCounts.get(a.id) ?? 0) || a.id.localeCompare(b.id));
+ const candidates: SystemComponent[][] = [[], [], []];
+ for (const component of neighbors) {
+ const column = inbound.has(component.id) && outbound.has(component.id) ? 1 : inbound.has(component.id) ? 0 : 2;
+ candidates[column].push(component);
+ }
+ // Keep one prolific direction from producing an unreadable vertical stack.
+ // Round-robin admission retains evidence from both directions under the total cap.
+ const columns: SystemComponent[][] = [[], [], []];
+ for (let row = 0, admitted = 0; row < 7 && admitted < 13; row++) {
+ for (const column of [0, 2, 1]) {
+ if (admitted >= 13 || (column === 1 && row >= 3) || !candidates[column][row]) continue;
+ columns[column].push(candidates[column][row]); admitted++;
+ }
+ }
+ const visible = [focus, ...columns.flat()];
+ const ids = new Set(visible.map(component => component.id));
+ const columnWidth = columns[0].length && columns[2].length ? 64 : 94;
+ const nodes = visible.map(component => {
+ const column = inbound.has(component.id) && outbound.has(component.id) ? 1 : inbound.has(component.id) ? 0 : 2;
+ const peers = columns[column], index = peers.indexOf(component);
+ return { id: component.id, label: component.label, component,
+ detail: `${component.member_count.toLocaleString()} symbols · ${component.file_count.toLocaleString()} files`,
+ position: component.id === focus.id ? [0, 0, 0] as [number, number, number]
+ : [(column - 1) * columnWidth, column === 1 ? 16 + index * 9 : (index - (peers.length - 1) / 2) * 9, column === 1 ? -3 : 0] as [number, number, number] };
+ });
+ const edges = adjacent.filter(edge => ids.has(edge.source) && ids.has(edge.target)).map(edge => ({
+ id: `dependency:${edge.source}:${edge.target}:${edge.type}`, source: edge.source, target: edge.target,
+ type: edge.type, count: edge.count, dependency: edge,
+ }));
+ const headingY = Math.max(...nodes.map(node => node.position[1])) + 17;
+ const captions = ['Used by', 'Focus', 'Uses'].flatMap((label, column) => column === 1 || columns[column].length
+ ? [{ label, position: [(column - 1) * columnWidth, headingY, 0] as [number, number, number] }] : []);
+ return { nodes, lanes: [], edges, captions, focusId: focus.id,
+ scopeKey: `structure:${focus.id}:${nodes.map(node => `${node.id}@${node.position.join(':')}`).join(',')}:${edges.map(edge => edge.id).join(',')}`,
+ omittedNodes: matching.length - nodes.length, omittedEdges: dependencies.length - edges.length, omittedNeighbors: neighbors.length - visible.length + 1 };
+}
+
+/** Prefer informative paths without changing their original indices or claiming runtime order. */
+export function rankSystemPaths(paths: readonly SystemPath[]): number[] {
+ const handoffs = (path: SystemPath) => path.edges.reduce((count, _, index) => count + Number(path.nodes[index].component_id !== path.nodes[index + 1].component_id), 0);
+ return paths.map((path, index) => ({ path, index })).filter(item => isContiguousPath(item.path))
+ .sort((a, b) => handoffs(b.path) - handoffs(a.path) || b.path.edges.length - a.path.edges.length || a.index - b.index).map(item => item.index);
+}
+
+/** Merge identical prefixes only: reconvergent symbols remain separate path occurrences. */
+export function systemBehaviorGraph(data: SystemProjection, input: SystemPath | readonly SystemPath[] | undefined, activePathIndex?: number): SystemSceneModel {
+ const paths: readonly SystemPath[] = !input ? [] : Array.isArray(input) ? input : [input as SystemPath];
+ const entry = paths.find(isContiguousPath)?.entrypoint_id;
+ const ranked = rankSystemPaths(paths).filter(index => paths[index].entrypoint_id === entry);
+ if (!ranked.length) return { nodes: [], edges: [], lanes: [], omittedNodes: 0, omittedEdges: 0, scopeKey: 'behavior:empty' };
+ const allNodes = new Map<string, SystemSceneNode>(), allEdges = new Map<string, SystemSceneEdge>();
+ const children = new Map<string, string[]>(), groups = new Map<string, string>();
+ const single = !Array.isArray(input);
+ for (const pathIndex of ranked) {
+ const path = paths[pathIndex];
+ let previous = '', prefix = `branch:${entry}`;
+ path.nodes.forEach((symbol, depth) => {
+ const sourceEdge = path.edges[depth - 1];
+ if (sourceEdge) prefix += `/${sourceEdge.id}:${sourceEdge.type}:${symbol.id}`;
+ const id = single ? `step:${depth}` : prefix;
+ const handoff = depth > 0 && symbol.component_id !== path.nodes[depth - 1].component_id;
+ if (!allNodes.has(id)) {
+ allNodes.set(id, { id, label: symbol.name, symbol, detail: symbol.file_path ?? symbol.qualified_name,
+ position: [depth * 18, 0, 0], pathIndices: [], depth, handoff });
+ groups.set(id, previous && !handoff ? groups.get(previous)! : id);
+ if (previous) children.set(previous, [...(children.get(previous) ?? []), id]);
+ }
+ allNodes.get(id)!.pathIndices!.push(pathIndex);
+ if (sourceEdge) {
+ const edgeId = single ? `path:${depth - 1}:${sourceEdge.id}` : `edge:${id}`;
+ if (!allEdges.has(edgeId)) allEdges.set(edgeId, { id: edgeId, source: previous, target: id, type: sourceEdge.type,
+ count: 1, pathEdge: sourceEdge, pathIndices: [], depth, handoff });
+ allEdges.get(edgeId)!.pathIndices!.push(pathIndex);
+ }
+ previous = id;
+ });
+ }
+ const ordered = [...allNodes.values()];
+ const visibleIds = new Set(ordered.filter(node => activePathIndex !== undefined && node.pathIndices?.includes(activePathIndex)).slice(0, 36).map(node => node.id));
+ for (const node of ordered) { if (visibleIds.size >= 36) break; visibleIds.add(node.id); }
+ // Preserve original prefix order when the chosen branch already fits. Highlighting alone
+ // must not move nodes, reset the camera, or alter what a selected node ID means.
+ const nodes = ordered.filter(node => visibleIds.has(node.id));
+ const edges = [...allEdges.values()].filter(edge => visibleIds.has(edge.source) && visibleIds.has(edge.target));
+ let leaf = 0;
+ const place = (id: string): number => {
+ const node = allNodes.get(id)!;
+ const childIds = (children.get(id) ?? []).filter(child => visibleIds.has(child));
+ const ys = childIds.map(place);
+ const y = ys.length ? (ys[0] + ys[ys.length - 1]) / 2 : leaf++ * 10;
+ node.position[1] = -y;
+ node.hiddenChildren = (children.get(id)?.length ?? 0) - childIds.length;
+ return y;
+ };
+ place(nodes[0].id);
+ const middle = Math.max(0, leaf - 1) * 5;
+ nodes.forEach(node => { node.position[1] += middle; node.pathIndices!.sort((a, b) => a - b); });
+ const components = new Map(data.components.map(component => [component.id, component]));
+ const laneGroups = new Map<string, SystemSceneNode[]>();
+ for (const node of nodes) { const group = groups.get(node.id)!; laneGroups.set(group, [...(laneGroups.get(group) ?? []), node]); }
+ const lanes = [...laneGroups.entries()].map(([id, members]) => {
+ const xs = members.map(node => node.position[0]), ys = members.map(node => node.position[1]);
+ const left = Math.min(...xs), right = Math.max(...xs), bottom = Math.min(...ys), top = Math.max(...ys);
+ const componentId = members[0].symbol!.component_id;
+ return { id, label: components.get(componentId)?.label ?? componentId,
+ position: [(left + right) / 2, (bottom + top) / 2 + 1, -3] as [number, number, number],
+ width: right - left + 10, height: top - bottom + 6, depth: 0.65,
+ pathIndices: [...new Set(members.flatMap(node => node.pathIndices ?? []))] };
+ });
+ return { nodes, edges, lanes, omittedNodes: allNodes.size - nodes.length, omittedEdges: allEdges.size - edges.length,
+ preferredPathIndex: ranked[0], scopeKey: `behavior:${nodes.map(node => node.id).join('|')}` };
+}
diff --git a/graph-ui/src/architecture/system-architecture-source.test.ts b/graph-ui/src/architecture/system-architecture-source.test.ts
new file mode 100644
index 000000000..828961174
--- /dev/null
+++ b/graph-ui/src/architecture/system-architecture-source.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { callToolJson } from '../provider/rpc-transport';
+import { loadSystemArchitecture, readSystemArchitecture } from './system-architecture-source';
+import type { SystemArchitectureResponse, SystemPathEdge, SystemSymbol } from './system-architecture-source';
+
+vi.mock('../provider/rpc-transport', () => ({ callToolJson: vi.fn() }));
+
+function response(): SystemArchitectureResponse {
+ const caller: SystemSymbol = { id: 1, name: 'start', qualified_name: 'app.start', label: 'Function', component_id: 'api', file_path: 'src/api.ts' };
+ const callee: SystemSymbol = { id: 2, name: 'save', qualified_name: 'app.save', label: 'Function', component_id: 'store', file_path: 'src/store.ts',
+ signature: 'save(value: Input): Result', return_type: 'Result', parameters: { names: ['value'], types: ['Input'], count: 1 } };
+ const edge: SystemPathEdge = { id: 10, source_id: 1, target_id: 2, type: 'CALLS',
+ arguments: [{ i: 7, e: 'input["key"]', v: 'literal\nvalue' }], argument_limit: 8, arguments_complete: false,
+ callsite: { file_path: 'src/api.ts', line: 42 } };
+ return { status: 'ready', generation: 'g1', result: { schema_version: 1, status: 'ready', kind: 'static_projection', complete: true,
+ components: [], dependencies: [{ source: 'api', target: 'store', type: 'CALLS', count: 1,
+ witnesses: [{ ...edge, edge_id: edge.id, source: caller, target: callee }] }], cycles: [], entrypoints: [caller],
+ paths: [{ entrypoint_id: 1, nodes: [caller, callee], edges: [edge] }], totals: {}, limits: {}, warnings: [],
+ behavior: { mode: 'corridor', source_id: 1, target_id: 2, complete: true, limits_hit: [], reachable_targets: [], totals: {},
+ nodes: [caller, callee], edges: [edge], cycles: [], max_hops: 10 },
+ } };
+}
+
+beforeEach(() => { vi.clearAllMocks(); vi.mocked(callToolJson).mockResolvedValue(response()); });
+
+describe('architecture evidence request opt-in', () => {
+ it.each([undefined, false])('omits the wire flag when includeBehaviorEvidence is %s', async includeBehaviorEvidence => {
+ const controller = new AbortController();
+ await loadSystemArchitecture({ project: 'sample', includeBehaviorEvidence }, controller.signal);
+ expect(callToolJson).toHaveBeenCalledWith('get_architecture', {
+ project: 'sample', aspects: ['system_structure'], format: 'json',
+ }, { signal: controller.signal });
+ });
+
+ it('forwards explicit evidence, exact endpoints, generation and cancellation together', async () => {
+ const controller = new AbortController();
+ await loadSystemArchitecture({ project: 'sample', entryNodeId: 1, targetNodeId: 2,
+ expectedGeneration: 'g1', includeBehaviorEvidence: true }, controller.signal);
+ expect(callToolJson).toHaveBeenCalledWith('get_architecture', {
+ project: 'sample', aspects: ['system_structure'], format: 'json', entry_node_id: 1, target_node_id: 2,
+ expected_generation: 'g1', include_behavior_evidence: true,
+ }, { signal: controller.signal });
+ });
+});
+
+describe('optional indexed behavior evidence at the wire boundary', () => {
+ it('preserves declarations and argument expressions without changing stored indices or implying completeness', () => {
+ const data = readSystemArchitecture(response()).result!;
+ expect(data.paths[0].nodes[1].parameters).toEqual({ names: ['value'], types: ['Input'], count: 1 });
+ expect(data.paths[0].nodes[1].return_type).toBe('Result');
+ expect(data.paths[0].edges[0].arguments).toEqual([{ i: 7, e: 'input["key"]', v: 'literal\nvalue' }]);
+ expect(data.behavior!.edges[0].arguments_complete).toBe(false);
+ expect(data.dependencies[0].witnesses[0].argument_limit).toBe(8);
+ expect(data.dependencies[0].witnesses[0].target.signature).toBe('save(value: Input): Result');
+ });
+
+ it.each([
+ ['signature', 42], ['return_type', false],
+ ['parameters', { names: ['value'], types: [42], count: 1 }],
+ ['parameters', { names: 'value', types: ['Input'], count: 1 }],
+ ['parameters', { names: ['value'], types: ['Input'], count: -1 }],
+ ])('rejects malformed declaration field %s', (field, value) => {
+ const data = response();
+ (data.result!.paths[0].nodes[1] as unknown as Record<string, unknown>)[field as string] = value;
+ expect(() => readSystemArchitecture(data)).toThrow('invalid shape');
+ });
+
+ it.each([
+ { i: -1, e: 'value' }, { i: 1.5, e: 'value' }, { i: 0, e: 42 }, { i: 0, e: 'value', v: false },
+ ])('rejects malformed argument records in corridor edges', argument => {
+ const data = response();
+ (data.result!.behavior!.edges[0] as unknown as Record<string, unknown>).arguments = [argument];
+ expect(() => readSystemArchitecture(data)).toThrow('invalid shape');
+ });
+
+ it('validates optional metadata on dependency witnesses as well as paths', () => {
+ const data = response();
+ (data.result!.dependencies[0].witnesses[0] as unknown as Record<string, unknown>).arguments_complete = 'yes';
+ expect(() => readSystemArchitecture(data)).toThrow('invalid shape');
+ });
+});
diff --git a/graph-ui/src/architecture/system-architecture-source.ts b/graph-ui/src/architecture/system-architecture-source.ts
new file mode 100644
index 000000000..b783a7d9e
--- /dev/null
+++ b/graph-ui/src/architecture/system-architecture-source.ts
@@ -0,0 +1,161 @@
+import { callToolJson } from '../provider/rpc-transport';
+import type { CallToolOptions } from '../provider/rpc-transport';
+
+export interface SystemSymbol {
+ id: number; name: string; qualified_name: string; label: string;
+ file_path?: string; start_line?: number; end_line?: number; component_id: string; group_id?: string;
+ signature?: string; return_type?: string;
+ parameters?: { names: string[]; types: string[]; count: number };
+}
+export interface SystemComponent {
+ id: string; label: string; basis: string; member_count: number; file_count: number;
+ role?: 'test' | 'non_test'; role_basis?: string; group_id?: string;
+ representatives: SystemSymbol[];
+}
+export interface SystemCallEvidence {
+ callsite?: { file_path: string; line: number };
+ resolution?: { strategy?: string; confidence?: number; candidates?: number };
+ arguments?: { i: number; e: string; v?: string }[];
+ argument_limit?: number; arguments_complete?: boolean;
+}
+export interface SystemWitness extends SystemCallEvidence { edge_id: number; source: SystemSymbol; target: SystemSymbol }
+export interface SystemDependency {
+ source: string; target: string; type: string; count: number; witnesses: SystemWitness[];
+}
+export interface SystemPathEdge extends SystemCallEvidence { id: number; source_id: number; target_id: number; type: string }
+export interface SystemPath {
+ entrypoint_id: number; nodes: SystemSymbol[];
+ edges: SystemPathEdge[];
+}
+export interface SystemOverviewGroup {
+ id: string; label: string; role?: 'test' | 'non_test'; basis?: string;
+ component_count: number; member_count: number; file_count: number;
+ component_ids: string[]; representatives: SystemSymbol[];
+}
+export interface SystemOverview {
+ complete: boolean; grouping_basis: string; groups: SystemOverviewGroup[];
+ components: SystemComponent[]; connections: SystemDependency[];
+ totals: Record<string, number>; limits: Record<string, number | boolean>;
+}
+export interface SystemBehavior {
+ mode: 'targets' | 'corridor'; source_id: number; target_id?: number; complete: boolean;
+ corridor_complete?: boolean; reachable?: boolean;
+ limits_hit: string[]; reachable_targets: (SystemSymbol & { distance: number })[];
+ totals: Record<string, number>; nodes: SystemSymbol[]; edges: SystemPathEdge[];
+ cycles: { node_ids: number[] }[]; max_hops: number;
+}
+export interface SystemProjection {
+ schema_version: 1; status: 'ready' | 'limited'; kind: 'static_projection'; complete: boolean;
+ components: SystemComponent[]; dependencies: SystemDependency[];
+ cycles: { component_ids: string[] }[]; entrypoints: SystemSymbol[]; paths: SystemPath[];
+ totals: Record<string, number>; limits: Record<string, number | boolean>; warnings: string[];
+ overview?: SystemOverview; behavior?: SystemBehavior;
+}
+export interface SystemArchitectureResponse {
+ status: 'pending' | 'ready' | 'failed'; generation: string; retry_after_ms?: number;
+ result?: SystemProjection; error?: string;
+}
+export interface SystemArchitectureRequest { project: string; entryNodeId?: number; targetNodeId?: number; expectedGeneration?: string; includeBehaviorEvidence?: boolean }
+export type SystemArchitectureLoader = (request: SystemArchitectureRequest, signal: AbortSignal) => Promise<SystemArchitectureResponse>;
+
+const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
+const list = (value: unknown): unknown[] => {
+ if (!Array.isArray(value)) throw new Error('Architecture response is missing a collection.');
+ return value;
+};
+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
+const symbol = (value: unknown): value is SystemSymbol => record(value) && integer(value.id)
+ && typeof value.name === 'string' && typeof value.qualified_name === 'string'
+ && typeof value.label === 'string' && typeof value.component_id === 'string'
+ && (value.group_id === undefined || typeof value.group_id === 'string')
+ && (value.file_path === undefined || typeof value.file_path === 'string')
+ && (value.start_line === undefined || integer(value.start_line))
+ && (value.end_line === undefined || integer(value.end_line))
+ && (value.signature === undefined || typeof value.signature === 'string')
+ && (value.return_type === undefined || typeof value.return_type === 'string')
+ && (value.parameters === undefined || (record(value.parameters) && integer(value.parameters.count)
+ && Array.isArray(value.parameters.names) && value.parameters.names.every(name => typeof name === 'string')
+ && Array.isArray(value.parameters.types) && value.parameters.types.every(type => typeof type === 'string')));
+const counters = (value: unknown): value is Record<string, number> => record(value) && Object.values(value).every(integer);
+const limits = (value: unknown) => record(value) && Object.values(value).every(item => integer(item) || typeof item === 'boolean');
+const role = (value: unknown) => value === undefined || value === 'test' || value === 'non_test';
+const evidence = (value: Record<string, unknown>): boolean => (value.callsite === undefined || (record(value.callsite)
+ && typeof value.callsite.file_path === 'string' && integer(value.callsite.line) && value.callsite.line > 0))
+ && (value.resolution === undefined || (record(value.resolution)
+ && (value.resolution.strategy === undefined || typeof value.resolution.strategy === 'string')
+ && (value.resolution.confidence === undefined || (typeof value.resolution.confidence === 'number' && Number.isFinite(value.resolution.confidence)))
+ && (value.resolution.candidates === undefined || integer(value.resolution.candidates))))
+ && (value.arguments === undefined || (Array.isArray(value.arguments) && value.arguments.every(argument => record(argument)
+ && integer(argument.i) && typeof argument.e === 'string' && (argument.v === undefined || typeof argument.v === 'string'))))
+ && (value.argument_limit === undefined || integer(value.argument_limit))
+ && (value.arguments_complete === undefined || typeof value.arguments_complete === 'boolean');
+const component = (value: unknown): value is SystemComponent => record(value) && typeof value.id === 'string'
+ && typeof value.label === 'string' && typeof value.basis === 'string' && role(value.role)
+ && (value.role_basis === undefined || typeof value.role_basis === 'string')
+ && (value.group_id === undefined || typeof value.group_id === 'string')
+ && integer(value.member_count) && integer(value.file_count) && list(value.representatives).every(symbol);
+const dependency = (value: unknown): value is SystemDependency => record(value) && typeof value.source === 'string' && typeof value.target === 'string'
+ && typeof value.type === 'string' && integer(value.count) && list(value.witnesses).every(witness => record(witness)
+ && integer(witness.edge_id) && symbol(witness.source) && symbol(witness.target) && evidence(witness));
+const pathEdge = (value: unknown): value is SystemPathEdge => record(value) && integer(value.id) && integer(value.source_id)
+ && integer(value.target_id) && typeof value.type === 'string' && evidence(value);
+
+function overview(value: unknown): boolean {
+ return record(value) && typeof value.complete === 'boolean' && typeof value.grouping_basis === 'string'
+ && list(value.groups).every(group => record(group) && typeof group.id === 'string' && typeof group.label === 'string' && role(group.role)
+ && (group.basis === undefined || typeof group.basis === 'string') && integer(group.component_count) && integer(group.member_count)
+ && integer(group.file_count) && list(group.component_ids).every(id => typeof id === 'string') && list(group.representatives).every(symbol))
+ && list(value.components).every(component) && list(value.connections).every(dependency) && counters(value.totals) && limits(value.limits);
+}
+function behavior(value: unknown): boolean {
+ if (!record(value) || !['targets', 'corridor'].includes(String(value.mode)) || !integer(value.source_id)
+ || (value.target_id !== undefined && !integer(value.target_id)) || typeof value.complete !== 'boolean'
+ || (value.corridor_complete !== undefined && typeof value.corridor_complete !== 'boolean')
+ || (value.reachable !== undefined && typeof value.reachable !== 'boolean')
+ || !list(value.limits_hit).every(item => typeof item === 'string') || !integer(value.max_hops)
+ || !counters(value.totals) || !list(value.reachable_targets).every(item => symbol(item) && integer((item as unknown as Record<string, unknown>).distance))
+ || !list(value.nodes).every(symbol) || !list(value.edges).every(pathEdge)
+ || !list(value.cycles).every(cycle => record(cycle) && list(cycle.node_ids).every(integer))) return false;
+ const ids = new Set((value.nodes as SystemSymbol[]).map(item => item.id));
+ return (value.edges as SystemPathEdge[]).every(edge => ids.has(edge.source_id) && ids.has(edge.target_id));
+}
+
+/** Validate the wire boundary before letting a response drive rendering or source navigation. */
+export function readSystemArchitecture(value: unknown): SystemArchitectureResponse {
+ if (!record(value) || !['pending', 'ready', 'failed'].includes(String(value.status)) || typeof value.generation !== 'string') {
+ throw new Error('This server returned an unsupported architecture response.');
+ }
+ if (value.retry_after_ms !== undefined && !integer(value.retry_after_ms)) throw new Error('Invalid architecture retry interval.');
+ if (value.error !== undefined && typeof value.error !== 'string') throw new Error('Invalid architecture error.');
+ if (value.status !== 'ready') return value as unknown as SystemArchitectureResponse;
+ const result = value.result;
+ if (!record(result) || result.schema_version !== 1 || result.kind !== 'static_projection'
+ || !['ready', 'limited'].includes(String(result.status)) || typeof result.complete !== 'boolean') {
+ throw new Error('This server returned an unsupported architecture projection.');
+ }
+ if (!list(result.components).every(component)
+ || !list(result.dependencies).every(dependency)
+ || !list(result.cycles).every(cycle => record(cycle) && list(cycle.component_ids).every(id => typeof id === 'string'))
+ || !list(result.entrypoints).every(symbol)
+ || !list(result.paths).every(path => record(path) && integer(path.entrypoint_id) && list(path.nodes).every(symbol)
+ && list(path.edges).every(pathEdge))
+ || !list(result.warnings).every(warning => typeof warning === 'string')
+ || !record(result.totals) || !Object.values(result.totals).every(integer)
+ || !record(result.limits) || !Object.values(result.limits).every(limit => integer(limit) || typeof limit === 'boolean')
+ || (result.overview !== undefined && !overview(result.overview)) || (result.behavior !== undefined && !behavior(result.behavior))) {
+ throw new Error('Architecture evidence has an invalid shape.');
+ }
+ return value as unknown as SystemArchitectureResponse;
+}
+
+/** The same on-demand backend projection is available to the browser and MCP clients. */
+export async function loadSystemArchitecture(request: SystemArchitectureRequest, signal: AbortSignal, options: CallToolOptions = {}): Promise<SystemArchitectureResponse> {
+ const value = await callToolJson('get_architecture', {
+ project: request.project, aspects: ['system_structure'], format: 'json',
+ ...(request.entryNodeId === undefined ? {} : { entry_node_id: request.entryNodeId }),
+ ...(request.targetNodeId === undefined ? {} : { target_node_id: request.targetNodeId }),
+ ...(request.expectedGeneration === undefined ? {} : { expected_generation: request.expectedGeneration }),
+ ...(request.includeBehaviorEvidence === true ? { include_behavior_evidence: true } : {}),
+ }, { ...options, signal });
+ return readSystemArchitecture(value);
+}
diff --git a/graph-ui/src/architecture/system-architecture.css b/graph-ui/src/architecture/system-architecture.css
new file mode 100644
index 000000000..82983d4d8
--- /dev/null
+++ b/graph-ui/src/architecture/system-architecture.css
@@ -0,0 +1,132 @@
+.system-architecture { min-width: 0; }
+.atlas-architecture[data-system-view] { padding: 16px; }
+.atlas-architecture[data-system-view] .atlas-arch-heading { align-items: center; margin-bottom: 12px; }
+.atlas-architecture[data-system-view] .atlas-arch-heading h1 { font-size: 24px; line-height: 1.2; margin: 0 0 5px; }
+.atlas-architecture[data-system-view] .atlas-arch-heading p { margin: 0; font-size: 12px; }
+.atlas-architecture[data-system-view] .atlas-arch-project { display: none; }
+.atlas-architecture[data-system-view] .atlas-arch-tabs { margin-bottom: 10px; gap: 5px; }
+.atlas-architecture[data-system-view] .atlas-arch-tab { padding: 7px 10px; }
+.atlas-architecture[data-system-view] .atlas-arch-toolbar { margin-bottom: 12px; gap: 8px; }
+.system-toolbar, .system-reading-status, .system-map-caption { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; justify-content: space-between; }
+.system-toolbar { margin-bottom: 10px; gap: 8px; }
+.system-toolbar p { margin: 0 auto 0 0; }
+.system-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 16px; margin-bottom: 12px; }
+.system-controls label, .system-path-picker { display: flex; align-items: center; gap: 7px; color: var(--atlas-dim); font-size: 11px; }
+.system-controls .system-focus-picker { flex: 1 1 100%; font-size: 12px; }
+.system-controls input { accent-color: #94afa3; }
+.system-focus-picker select { flex: 1; }
+.system-architecture select { max-width: min(480px, 52vw); border: 1px solid var(--atlas-line); color: var(--atlas-fg); background: var(--atlas-panel); border-radius: 6px; padding: 6px 9px; font: inherit; }
+.system-reading-status { color: var(--atlas-dim); font-size: 11px; margin-bottom: 12px; }
+.system-filter-count { color: var(--atlas-dim); font-size: 11px; margin-bottom: 12px !important; }
+.system-filter-count button { border: 0; padding: 0; background: transparent; color: inherit; font: inherit; text-decoration: underline; text-underline-offset: 3px; }
+.system-test-badge { display: inline-block; color: #b3aca0; font-size: 10px; border: 1px solid #b3aca038; border-radius: 4px; padding: 2px 5px; margin-bottom: 8px; }
+.system-reading-status button, .system-map-caption button { background: none; color: inherit; border: 0; text-decoration: underline; text-underline-offset: 3px; }
+.system-architecture .system-workspace { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 0; padding: 0; min-width: 0; box-sizing: border-box; border: 1px solid var(--atlas-line); border-radius: 12px; overflow: hidden; background: color-mix(in srgb, var(--atlas-panel) 65%, transparent); }
+.system-architecture .system-map { height: clamp(320px, calc(100dvh - 540px), 620px); min-width: 0; position: relative; overflow: hidden; }
+.system-map-caption { position: absolute; bottom: 0; left: 0; right: 0; padding: 11px 16px; font-size: 11px; color: var(--atlas-dim); background: linear-gradient(transparent, var(--atlas-panel)); pointer-events: none; }
+.system-map-caption button { pointer-events: auto; }
+.system-architecture .system-inspector { border-left: 1px solid var(--atlas-line); padding: 16px; min-height: 0; box-sizing: border-box; max-height: clamp(320px, calc(100dvh - 540px), 620px); overflow: auto; }
+.system-inspector h3 { font-size: 17px; margin: 8px 0 14px; overflow-wrap: anywhere; }
+.system-inspector h4 { margin: 18px 0 8px; font-size: 12px; font-weight: 500; }
+.system-inspector h4 span { float: right; color: var(--atlas-dim); }
+.system-neighbors button { display: grid; width: 100%; padding: 8px 0; text-align: left; background: transparent; border: 0; border-bottom: 1px solid #78928618; color: var(--atlas-fg); }
+.system-neighbors button strong { font-weight: 450; font-size: 11px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
+.system-neighbors button:hover strong { color: var(--atlas-cyan); }
+.system-neighbors small { color: var(--atlas-dim); font-size: 10px; }
+.system-neighbor-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 7px; }
+.system-architecture .system-neighbors .system-neighbor-evidence { width: auto; padding: 5px; font-size: 10px; color: var(--atlas-dim); border: 1px solid var(--atlas-line); border-radius: 4px; }
+.system-representatives { margin-top: 20px; }
+.system-representatives summary { color: var(--atlas-dim); font-size: 11px; cursor: pointer; }
+.system-step-controls { display: flex; gap: 10px; margin-top: 20px; }
+.system-step-controls button { background: transparent; color: var(--atlas-fg); border: 1px solid var(--atlas-line); border-radius: 5px; padding: 7px; font-size: 11px; }
+.system-step-controls button:disabled { opacity: .4; }
+.system-flow-guide { display: flex; gap: 12px; flex-wrap: wrap; margin: 12px 0; font-size: 11px; color: var(--atlas-dim); }
+.system-branch-list { display: flex; gap: 8px; overflow-x: auto; padding: 14px 0 5px; }
+.system-branch-list button { flex: 0 0 175px; display: grid; gap: 5px; text-align: left; border: 1px solid var(--atlas-line); background: transparent; border-radius: 8px; color: var(--atlas-fg); padding: 11px 13px; }
+.system-branch-list button[aria-pressed=true] { background: #82998f0f; border-color: #a8bdb06b; }
+.system-branch-list button span, .system-branch-list button small { font-size: 10px; color: var(--atlas-dim); }
+.system-branch-list button strong { font-size: 11px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.system-inspector p + p { margin-top: 14px; }
+.system-eyebrow { color: var(--atlas-dim); font-size: 10px; text-transform: uppercase; letter-spacing: 1.3px; }
+.system-source { margin: 10px 0; min-width: 0; }
+.system-source button { border: 0; background: none; color: var(--atlas-fg); padding: 0; text-align: left; overflow-wrap: anywhere; }
+.system-source button:hover:not(:disabled) { color: var(--atlas-cyan); }
+.system-source button:disabled { color: var(--atlas-dim); }
+.system-source small { display: block; font-size: 10px; color: var(--atlas-dim); overflow-wrap: anywhere; margin-top: 3px; }
+.system-witness { border-top: 1px solid var(--atlas-line); margin-top: 18px; padding-top: 7px; }
+.system-witness > span { color: var(--atlas-dim); font-size: 10px; }
+.system-small, .system-limit { font-size: 11px; margin-top: 14px !important; }
+.system-findings { margin-top: 18px; border-top: 1px solid var(--atlas-line); padding-top: 14px; }
+.system-findings > summary { cursor: pointer; color: var(--atlas-dim); margin-bottom: 12px; }
+.system-findings p { max-width: 950px; margin: 8px 0; }
+.system-component-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 7px; margin-bottom: 10px; }
+.system-component-list button, .system-dependency-list button { display: grid; gap: 3px; text-align: left; border: 1px solid var(--atlas-line); border-radius: 7px; padding: 11px 13px; color: var(--atlas-fg); background: transparent; overflow-wrap: anywhere; }
+.system-component-list button[aria-pressed=true], .system-component-list button:hover, .system-dependency-list button:hover { border-color: #718f84; background: #82998f0b; }
+.system-component-list strong { font-weight: 550; }
+.system-component-list span, .system-component-list small, .system-dependency-list small { color: var(--atlas-dim); font-size: 10px; }
+.system-dependency-list { display: grid; gap: 6px; margin: 10px 0; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); }
+.system-path-picker { margin-bottom: 12px; }
+.system-path-list { padding: 0; list-style: none; display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 6px; }
+.system-path-list li { border: 1px solid var(--atlas-line); border-radius: 7px; padding: 10px; position: relative; }
+.system-path-list li[data-selected=true] { background: #82998f10; border-color: #82998f66; }
+.system-step-select { background: #82998f15; color: var(--atlas-dim); border: 1px solid var(--atlas-line); border-radius: 50%; width: 24px; height: 24px; font-size: 10px; }
+.system-path-list li > span { color: var(--atlas-dim); font-size: 10px; }
+.system-scene-empty, .system-analysis-state { display: flex; align-items: center; justify-content: center; text-align: center; flex-direction: column; gap: 12px; height: 100%; min-height: 260px; padding: 30px; color: var(--atlas-dim); }
+.system-analysis-state { border: 1px solid var(--atlas-line); border-radius: 12px; }
+.system-analysis-state strong { color: var(--atlas-fg); font-weight: 500; }
+.system-progress { width: 26px; height: 26px; border: 1px solid #869f9638; border-top-color: #a0b6aa; border-radius: 50%; animation: system-progress-turn 1.3s linear infinite; }
+@keyframes system-progress-turn { to { transform: rotate(360deg); } }
+.system-architecture .system-scene-node-label { display: grid; align-content: center; gap: 0; width: 96px; height: 28px; min-height: 0; box-sizing: border-box; margin: 0; background: #101816ec; color: #c0cec7; border: 1px solid #78928638; border-radius: 6px; padding: 6px 7px; text-align: center; line-height: 14px; font-family: var(--atlas-ui-font, system-ui, sans-serif); box-shadow: 0 2px 8px #0002; }
+.system-architecture .system-scene-node-label strong { margin: 0; font-size: 11px; line-height: 14px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.system-architecture .system-scene-node-label small { margin: 0; font-size: 9px; line-height: 11px; color: #94a79c; white-space: nowrap; }
+.system-architecture .system-scene-node-label[data-selected=true] { border-color: #9db5a7; color: #edf2ef; }
+.system-architecture .system-scene-node-label[data-focus=true] { border-color: #a9c4b7a0; background: #192620ec; color: #e0e9e3; }
+.system-architecture .system-scene-node-label[data-muted=true] { opacity: .55; }
+.system-architecture .system-scene-node-label[data-kind=group] { border-style: dashed; }
+.system-architecture .system-scene-node-label[data-kind=group]:not([data-expanded=true]) { height: 42px; gap: 3px; }
+.system-architecture .system-scene-node-label[data-expanded=true] { width: 126px; }
+.system-architecture .system-scene-node-label[data-child=true] { width: 110px; }
+.system-architecture .system-scene-node-label[data-kind=remainder] { color: #b6b3a6; border-style: dashed; }
+.system-scene-lane-label { color: #92a89c; font: 10px var(--atlas-ui-font, system-ui, sans-serif); white-space: nowrap; background: #0d1512bb; padding: 3px 7px; border-radius: 4px; }
+.system-scene-lane-label[data-component=true] { font-size: 11px; color: #a7b9af; display: inline-block; max-width: 180px; overflow: hidden; text-overflow: ellipsis; }
+.system-scene-edge-label { display: inline-block; max-width: 230px; color: #c2c6cf; font-size: 10px; background: #111716f2; border: 1px solid #91a59a38; padding: 5px 8px; border-radius: 6px; }
+.system-scope-actions, .system-selection-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; margin: 8px 0 12px; }
+.system-scope-actions button, .system-selection-actions button { border: 1px solid var(--atlas-line); border-radius: 5px; background: #82998f0c; color: var(--atlas-fg); font: inherit; font-size: 11px; padding: 5px 8px; }
+.system-selection-actions button:disabled, .system-scope-actions button:disabled { opacity: .4; }
+.system-member-picker { display: grid; gap: 6px; color: var(--atlas-dim); font-size: 11px; }
+.system-member-picker select { width: 100%; min-width: 0; max-width: 100%; }
+.system-call-evidence { display: grid; gap: 4px; margin: 8px 0; }
+.system-call-evidence button { border: 0; padding: 0; background: transparent; color: #b7c8bd; text-align: left; font: inherit; font-size: 11px; overflow-wrap: anywhere; }
+.system-call-evidence small { color: var(--atlas-dim); font-size: 10px; overflow-wrap: anywhere; }
+.system-connection-evidence { margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--atlas-line); }
+@media (min-width: 761px) { .system-architecture[aria-label="Behavior"] .system-map { height: clamp(280px, calc(100dvh - 580px), 620px); } .system-architecture[aria-label="Behavior"] .system-inspector { max-height: clamp(280px, calc(100dvh - 580px), 620px); } }
+@media (max-width: 760px) { .system-architecture .system-workspace { grid-template-columns: minmax(0, 1fr); } .system-architecture .system-map { height: 400px; } .system-architecture .system-inspector { border-left: 0; border-top: 1px solid var(--atlas-line); max-height: 260px; } .system-architecture select { max-width: 70vw; } .system-neighbors { display: block; width: 100%; } .system-architecture .system-scene-node-label strong { font-size: 10px; } }
+@media (prefers-reduced-motion: reduce) { .system-progress { animation: none; } }
+
+/* System maps share the Overview ground-plane canvas and restrained source tint. */
+.system-architecture .system-scene { position: relative; isolation: isolate; width: 100%; height: 100%; min-width: 0; background: #0b1118; cursor: grab; }
+.system-architecture .system-scene:active { cursor: grabbing; }
+.system-architecture .system-scene canvas { display: block; outline: none; touch-action: none; }
+.system-architecture .system-scene .system-scene-node-label { color: #c4ced9; background: #111923ed; border-color: color-mix(in srgb, var(--system-node-tint, #91a6b4) 34%, transparent); box-shadow: 0 2px 8px #0003; cursor: pointer; }
+.system-architecture .system-scene .system-scene-node-label[data-kind=group]:not([data-expanded=true]) { width: 76px; height: 24px; gap: 0; padding: 4px 5px; }
+.system-architecture .system-scene .system-scene-node-label small { color: #99a8b8; }
+.system-architecture .system-scene .system-scene-node-label[data-focus=true] { border-color: #ced9e080; background: #1a2530ee; color: #e1e9ef; }
+.system-architecture .system-scene .system-scene-node-label[data-selected=true] { border-color: #eff5fa; color: #f1f6fa; background: #1c2732f2; }
+.system-architecture .system-scene .system-scene-node-label:focus-visible { outline: 2px solid #e5eef8; outline-offset: 2px; }
+.system-architecture .system-scene .system-scene-lane-label { display: inline-block; max-width: 180px; overflow: hidden; text-overflow: ellipsis; color: #9aaaba; background: #101923c9; font-size: 10px; }
+.system-architecture .system-scene .system-scene-edge-label { background: #111923f2; border-color: #91a6b440; }
+
+.system-display-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 16px; margin: 0 0 10px; color: var(--atlas-dim); font-size: 11px; }
+.system-layout-hint { margin-right: auto; }
+.system-display-controls label { display: flex; align-items: center; gap: 8px; }
+.system-view-switch { display: flex; border: 1px solid var(--atlas-line); border-radius: 7px; padding: 2px; }
+.system-view-switch button { background: transparent; color: var(--atlas-dim); border: 0; border-radius: 4px; padding: 5px 12px; font: inherit; }
+.system-view-switch button[aria-pressed=true] { background: #b6c7d51a; color: var(--atlas-fg); }
+.system-color-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 2px; color: var(--atlas-dim); font-size: 10px; }
+.system-color-legend span { display: inline-flex; align-items: center; gap: 6px; }
+.system-color-legend i { display: inline-block; width: 7px; height: 7px; border-radius: 2px; opacity: .7; }
+.system-color-legend small { flex-basis: 100%; font-size: 10px; }
+@media (min-width: 761px) {
+ .system-architecture .system-map, .system-architecture[aria-label="Behavior"] .system-map { height: clamp(420px, calc(100dvh - 440px), 760px); }
+ .system-architecture .system-inspector, .system-architecture[aria-label="Behavior"] .system-inspector { max-height: clamp(420px, calc(100dvh - 440px), 760px); }
+}
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
index 597fc5e84..4626fc388 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
@@ -58,7 +58,41 @@ describe('persistent local browser chat', () => {
expect(container.querySelector('pre')?.textContent).toBe(selection.text);
expect(container.querySelectorAll('option')).toHaveLength(BROWSER_MODELS.length);
expect(container.textContent).toContain('No model downloads automatically');
- expect(container.textContent).toContain('Session only');
+ expect(container.querySelector('.cbm-chat-settings h3')?.textContent).toBe('Enable chat');
+ expect(container.querySelector('[role="log"]')).toBeNull();
+ expect(container.querySelector('textarea')).toBeNull();
+ });
+
+ it('offers a compact enable action without starting a download or consuming selected code', async () => {
+ const { props } = fixture(); const onOpen = vi.fn();
+ await render({ ...props, open: false, showCollapsed: true, onOpen, attachment: selection });
+ expect(container.querySelector('aside')?.hidden).toBe(false);
+ expect(container.querySelector('form')).toBeNull();
+ expect(container.querySelector('select')).toBeNull();
+ await click('Enable chat');
+ expect(onOpen).toHaveBeenCalledOnce();
+ expect(props.createRuntime).not.toHaveBeenCalled();
+ expect(props.onAttachmentConsumed).not.toHaveBeenCalled();
+ await render({ ...props, showCollapsed: true, onOpen, attachment: selection });
+ expect(button('Download & load').disabled).toBe(false);
+ expect(container.querySelector('pre')?.textContent).toBe(selection.text);
+ expect(props.createRuntime).not.toHaveBeenCalled();
+ });
+
+ it('keeps an active answer and draft when only the collapsed header is visible', async () => {
+ const { props, runtime } = fixture(); const onOpen = vi.fn(); const answer = deferred<string>();
+ runtime.chat.mockReturnValueOnce(answer.promise);
+ await render({ ...props, showCollapsed: true, onOpen });
+ await click('Download & load'); await type('Explain'); await click('Send ↑'); await type('Next question');
+ await render({ ...props, open: false, showCollapsed: true, onOpen });
+ expect(container.querySelector('[role="log"]')).toBeNull();
+ await act(async () => answer.resolve('Finished while folded.'));
+ await click('Open chat'); expect(onOpen).toHaveBeenCalledOnce();
+ await render({ ...props, showCollapsed: true, onOpen });
+ expect(container.textContent).toContain('Finished while folded.');
+ expect(container.querySelector('textarea')?.value).toBe('Next question');
+ expect(runtime.dispose).not.toHaveBeenCalled();
+ expect(props.createRuntime).toHaveBeenCalledOnce();
});
it('retains draft, history and loaded model when the dock is collapsed', async () => {
@@ -151,7 +185,8 @@ describe('persistent local browser chat', () => {
await render(props); await click('Download & load'); await click('Stop download');
await act(async () => prepare.resolve());
expect(runtime.dispose).toHaveBeenCalledOnce(); expect(container.querySelector('.cbm-chat-status')?.textContent).toBe('Off');
- expect(button('Send ↑').disabled).toBe(true);
+ expect(container.querySelector('textarea')).toBeNull();
+ expect(button('Download & load').disabled).toBe(false);
});
it('unloads and deletes cached files separately while preserving the conversation', async () => {
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsx
index 3942d1db5..c4ac93cf3 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx
@@ -10,6 +10,8 @@ export type { BrowserChatAttachment, BrowserChatContext } from './chat-model';
export interface BrowserChatDockProps {
open: boolean;
onClose: () => void;
+ showCollapsed?: boolean;
+ onOpen?: () => void;
attachment?: BrowserChatAttachment;
context?: readonly BrowserChatContext[];
pendingContext?: BrowserChatContext;
@@ -39,7 +41,7 @@ function ContextSnapshot({ context }: { context: BrowserChatContext }): JSX.Elem
}
/** Keep mounted when collapsed: state and worker lifetime are independent of visibility. */
-export default function BrowserChatDock({ open, onClose, attachment, context = [], pendingContext, onContextConsumed, onContextRemoved, onAttachmentConsumed, onAttachmentRemoved, createRuntime = createBrowserChatRuntime, removeCache = removeBrowserModelCache }: BrowserChatDockProps): JSX.Element {
+export default function BrowserChatDock({ open, onClose, showCollapsed = false, onOpen, attachment, context = [], pendingContext, onContextConsumed, onContextRemoved, onAttachmentConsumed, onAttachmentRemoved, createRuntime = createBrowserChatRuntime, removeCache = removeBrowserModelCache }: BrowserChatDockProps): JSX.Element {
const [modelId, setModelId] = useState(initialModel.id);
const model = BROWSER_MODELS.find(candidate => candidate.id === modelId) ?? initialModel;
const [phase, setPhase] = useState<Phase>('off');
@@ -176,6 +178,15 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
};
const submit = (event: FormEvent): void => { event.preventDefault(); void send(); };
const status = stopping ? 'Stopping' : phase === 'preparing' ? 'Loading' : phase === 'counting' ? 'Checking context' : phase === 'generating' ? 'Answering' : phase === 'removing' ? 'Deleting cache' : phase === 'ready' ? 'Loaded' : 'Off';
+ const needsEnable = phase === 'off';
+ const showConversation = turns.length > 0 || phase === 'ready' || phase === 'counting' || phase === 'generating';
+
+ if (!open && showCollapsed) return <aside className="cbm-chat-dock is-collapsed" aria-label="Local chat">
+ <header className="cbm-chat-header">
+ <h2>Local chat</h2>
+ <button type="button" className="cbm-chat-primary" aria-expanded={false} onClick={onOpen}>{needsEnable ? 'Enable chat' : 'Open chat'}</button>
+ </header>
+ </aside>;
return <aside className="cbm-chat-dock" hidden={!open} aria-label="Local chat">
<header className="cbm-chat-header">
@@ -183,10 +194,11 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
<button type="button" className="cbm-chat-icon" aria-label="Collapse local chat" title="Collapse chat; keep conversation" onClick={onClose}>›</button>
</header>
<div className="cbm-chat-modelbar">
- <button type="button" aria-expanded={showModels} aria-controls="cbm-chat-model-settings" onClick={() => setShowModels(value => !value)}><span>{model.displayName}</span><span aria-hidden="true">⌄</span></button>
+ <button type="button" aria-expanded={showModels || needsEnable} aria-controls="cbm-chat-model-settings" disabled={needsEnable} onClick={() => setShowModels(value => !value)}><span>{model.displayName}</span><span aria-hidden="true">⌄</span></button>
<span className="cbm-chat-status" data-ready={phase === 'ready'} role="status">{status}</span>
</div>
- {showModels && <section id="cbm-chat-model-settings" className="cbm-chat-settings" aria-label="Local model settings">
+ {(showModels || needsEnable) && <section id="cbm-chat-model-settings" className={`cbm-chat-settings${needsEnable ? ' is-setup' : ''}`} aria-label="Local model settings">
+ {needsEnable && <h3>Enable chat</h3>}
<label htmlFor="cbm-chat-model">Model</label>
<select id="cbm-chat-model" value={modelId} disabled={busy} onChange={event => { release(); setModelId(event.target.value); setError(undefined); setNotice(undefined); }}>
{BROWSER_MODELS.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.displayName} · {candidate.availability === 'unsupported' ? 'Requires runtime support' : candidate.id === model.id && phase === 'ready' ? 'Loaded' : downloaded.has(candidate.id) ? 'Downloaded this session' : 'Available'}</option>)}
@@ -203,7 +215,7 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
{phase === 'preparing' && <div className="cbm-chat-loading" role="status"><progress max={100} value={progress?.progress} /><span>{progress?.file ?? 'Preparing browser model…'}</span><button type="button" onClick={stop}>Stop download</button></div>}
{error && <div className="cbm-chat-error" role="alert">{error}</div>}
{notice && <p className="cbm-chat-notice" role="status">{notice}</p>}
- <div className="cbm-chat-transcript" ref={transcript} role="log" aria-label="Conversation" aria-live="off" onScroll={() => {
+ {showConversation && <div className="cbm-chat-transcript" ref={transcript} role="log" aria-label="Conversation" aria-live="off" onScroll={() => {
const element = transcript.current;
if (!element) return;
followOutput.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;
@@ -218,7 +230,7 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
{index === turns.length - 1 && turn.status !== 'generating' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready'} onClick={() => { void send(turn); }}>Retry</button>}
</div>
</article>)}
- </div>
+ </div>}
{newOutput && <button type="button" className="cbm-chat-jump" onClick={() => { followOutput.current = true; setNewOutput(false); if (transcript.current) transcript.current.scrollTop = transcript.current.scrollHeight; }}>Latest answer ↓</button>}
<form className="cbm-chat-composer" onSubmit={submit}>
{attachment && <div className="cbm-chat-pending"><div className="cbm-chat-pending-title"><span>Attached to next message</span><button type="button" aria-label="Remove code attachment" disabled={!onAttachmentRemoved} onClick={() => onAttachmentRemoved?.(attachment.id)}>×</button></div><Attachment attachment={attachment} /></div>}
@@ -228,7 +240,7 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
const checked = event.target.checked;
setSelectedContext(previous => checked ? [...previous.filter(selected => selected.id !== item.id), { ...item }] : previous.filter(selected => selected.id !== item.id));
}} />{item.label}</label>)}</fieldset></details>}
- <label className="cbm-chat-visually-hidden" htmlFor="cbm-chat-prompt">Message local model</label>
+ {showConversation && <><label className="cbm-chat-visually-hidden" htmlFor="cbm-chat-prompt">Message local model</label>
<textarea ref={input} id="cbm-chat-prompt" value={draft} placeholder="Ask about this code…" rows={3} onChange={event => setDraft(event.target.value)} onKeyDown={event => {
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void send(); }
}} />
@@ -236,6 +248,7 @@ export default function BrowserChatDock({ open, onClose, attachment, context = [
{phase === 'counting' || phase === 'generating' ? <button type="button" disabled={stopping} onClick={stop}>{stopping ? 'Stopping…' : 'Stop'}</button> : <button className="cbm-chat-primary" type="submit" disabled={phase !== 'ready' || !draft.trim()}>Send ↑</button>}
</div>
<p className="cbm-chat-context">{tokenCount !== undefined ? `${tokenCount.toLocaleString()} input tokens in last check · ` : ''}{turns.length ? 'Earlier messages stay in context. ' : ''}Session only · Verify model answers.</p>
+ </>}
</form>
</aside>;
}
diff --git a/graph-ui/src/browser-ai/browser-chat.css b/graph-ui/src/browser-ai/browser-chat.css
index dce6d2992..21b9cc54b 100644
--- a/graph-ui/src/browser-ai/browser-chat.css
+++ b/graph-ui/src/browser-ai/browser-chat.css
@@ -3,10 +3,12 @@
--chat-muted: #93aba2;
--chat-accent: #40fca1;
display: flex; flex-direction: column; min-height: 0; height: 100%; min-width: 0;
- overflow: hidden; color: #e2eee8; background: #0e1814; border-left: 1px solid var(--chat-border);
+ overflow: auto; overscroll-behavior: contain; color: #e2eee8; background: #0e1814; border-left: 1px solid var(--chat-border);
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.cbm-chat-dock[hidden] { display: none; }
+.cbm-chat-dock.is-collapsed { height: auto; flex: 0 0 auto; }
+.cbm-chat-dock.is-collapsed .cbm-chat-header { padding: 9px 12px; }
.cbm-chat-dock * { box-sizing: border-box; }
.cbm-chat-dock button, .cbm-chat-dock select, .cbm-chat-dock textarea { font: inherit; }
.cbm-chat-dock button { color: inherit; background: #16251e; border: 1px solid var(--chat-border); border-radius: 6px; padding: 6px 10px; cursor: pointer; }
@@ -15,16 +17,18 @@
.cbm-chat-dock :is(button, select, textarea, summary, a):focus-visible { outline: 2px solid var(--chat-accent); outline-offset: 3px; }
.cbm-chat-dock p, .cbm-chat-dock h2, .cbm-chat-dock h3 { margin: 0; }
.cbm-chat-dock a { color: #91dce0; text-underline-offset: 3px; }
-.cbm-chat-header { padding: 15px 16px 12px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--chat-border); }
+.cbm-chat-header { flex-shrink: 0; padding: 15px 16px 12px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--chat-border); }
.cbm-chat-header h2 { font: 600 15px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; letter-spacing: -.2px; }
.cbm-chat-subtitle { color: var(--chat-muted); font-size: 11px; }
.cbm-chat-header .cbm-chat-icon { padding: 0; width: 30px; height: 30px; font-size: 24px; line-height: 1; background: transparent; }
-.cbm-chat-modelbar { display: flex; align-items: center; gap: 8px; padding: 9px 12px; }
+.cbm-chat-modelbar { flex-shrink: 0; display: flex; align-items: center; gap: 8px; padding: 9px 12px; }
.cbm-chat-modelbar > button { flex: 1; min-width: 0; display: flex; align-items: center; justify-content: space-between; gap: 8px; border-color: transparent; background: transparent; padding: 4px; text-align: left; }
.cbm-chat-modelbar > button > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cbm-chat-status { color: var(--chat-muted); font: 10px/1.4 ui-monospace, SFMono-Regular, monospace; white-space: nowrap; }
.cbm-chat-status[data-ready="true"] { color: var(--chat-accent); }
.cbm-chat-settings { flex-shrink: 1; min-height: 0; max-height: 40%; overflow-y: auto; margin: 0 12px 8px; border: 1px solid var(--chat-border); border-radius: 8px; padding: 12px; display: grid; gap: 9px; background: #101e17; }
+.cbm-chat-settings.is-setup { flex-shrink: 0; max-height: none; }
+.cbm-chat-settings h3 { font-size: 17px; font-weight: 500; }
.cbm-chat-settings label { font-weight: 600; }
.cbm-chat-settings select { width: 100%; min-width: 0; padding: 7px; color: #e2eee8; background: #0a140f; border: 1px solid var(--chat-border); border-radius: 5px; }
.cbm-chat-settings p { font-size: 11px; color: var(--chat-muted); }
@@ -36,7 +40,7 @@
.cbm-chat-loading button { justify-self: start; }
.cbm-chat-error, .cbm-chat-notice { flex-shrink: 0; max-height: 130px; overflow: auto; margin: 4px 12px 8px !important; padding: 10px; font-size: 12px; border: 1px solid #86525b; border-radius: 6px; background: #291a20; color: #ffb6bd; overflow-wrap: anywhere; }
.cbm-chat-notice { background: #14241b; border-color: var(--chat-border); color: var(--chat-muted); }
-.cbm-chat-transcript { flex: 1 1 0; min-height: 100px; overflow-y: auto; overscroll-behavior: contain; padding: 8px 16px 20px; }
+.cbm-chat-transcript { flex: 1 1 100px; min-height: 100px; overflow-y: auto; overscroll-behavior: contain; padding: 8px 16px 20px; }
.cbm-chat-empty { display: flex; flex-direction: column; justify-content: center; min-height: 220px; max-width: 33ch; margin: auto; gap: 12px; padding: 22px 0; }
.cbm-chat-empty > span { font-size: 30px; line-height: 1; color: var(--chat-accent); }
.cbm-chat-empty h3 { font-size: 18px; font-weight: 500; letter-spacing: -.4px; }
@@ -54,6 +58,7 @@
.cbm-chat-attachment pre { margin: 0; padding: 9px; border-top: 1px solid #284338; white-space: pre; max-height: 200px; overflow: auto; font: 11px/1.65 ui-monospace, SFMono-Regular, monospace; color: #d0e8d8; tab-size: 4; }
.cbm-chat-attachment small { display: block; padding: 5px 9px 9px; color: var(--chat-muted); font-size: 10px; overflow-wrap: anywhere; }
.cbm-chat-composer { flex-shrink: 0; max-height: 50%; overflow-y: auto; padding: 12px; border-top: 1px solid var(--chat-border); background: #101e17; }
+.cbm-chat-composer:empty { display: none; }
.cbm-chat-pending { margin-bottom: 9px; }
.cbm-chat-pending-title { display: flex; align-items: center; justify-content: space-between; color: var(--chat-muted); font-size: 10px; }
.cbm-chat-pending-title button { border: 0; padding: 0 5px; background: transparent; font-size: 19px; line-height: 1.3; }
diff --git a/graph-ui/src/diagnostics/DiagnosticsPanel.test.tsx b/graph-ui/src/diagnostics/DiagnosticsPanel.test.tsx
index 4ced0bc5e..044fe388e 100644
--- a/graph-ui/src/diagnostics/DiagnosticsPanel.test.tsx
+++ b/graph-ui/src/diagnostics/DiagnosticsPanel.test.tsx
@@ -41,7 +41,7 @@ describe('Local diagnosis user boundary', () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });
const onNavigate = vi.fn(); const onCoverage = vi.fn();
- await act(async () => root.render(<DiagnosticsPanel project="fixture" client={fixture.client} active onClose={vi.fn()} onNavigate={onNavigate} path="src/broken.ts" onCoverage={onCoverage} />));
+ await act(async () => root.render(<DiagnosticsPanel project="fixture" client={fixture.client} active onNavigate={onNavigate} path="src/broken.ts" onCoverage={onCoverage} />));
expect(fixture.calls).toHaveLength(0); expect(container.querySelector('textarea')).toBeNull();
await click('Run local diagnosis');
expect(fixture.calls.map((call) => call.tool)).toEqual(['index_status', 'check_index_coverage', 'check_index_coverage']);
@@ -69,14 +69,14 @@ describe('Local diagnosis user boundary', () => {
});
it('never presents a failed read as complete coverage', async () => {
const fixture = clientFixture(); fixture.fetch.mockRejectedValue(new Error('SQLite busy'));
- await act(async () => root.render(<DiagnosticsPanel project="fixture" client={fixture.client} active onClose={vi.fn()} onNavigate={vi.fn()} />));
+ await act(async () => root.render(<DiagnosticsPanel project="fixture" client={fixture.client} active onNavigate={vi.fn()} />));
await click('Run local diagnosis');
expect(container.querySelector('[role="alert"]')?.textContent).toContain('SQLite busy');
expect(container.textContent).toContain('Completeness is unknown');
expect(container.querySelector('textarea')).toBeNull();
});
it('renders shared coverage reasons and an honest empty state without refetching', async () => {
- const fixture = clientFixture(); const props: DiagnosticsPanelProps = { project: 'fixture', client: fixture.client, active: true, onClose: vi.fn(), onNavigate: vi.fn(), coverage: buildCoverageIndex({}) };
+ const fixture = clientFixture(); const props: DiagnosticsPanelProps = { project: 'fixture', client: fixture.client, active: true, onNavigate: vi.fn(), coverage: buildCoverageIndex({}) };
await act(async () => root.render(<DiagnosticsPanel {...props} />));
expect(container.textContent).toContain('does not prove complete indexing');
expect(fixture.calls).toHaveLength(0);
@@ -88,7 +88,7 @@ describe('Local diagnosis user boundary', () => {
const fixture = clientFixture();
vi.spyOn(fixture.client, 'indexStatusPayload').mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
const onCoverage = vi.fn();
- const props = { project: 'old-project', client: fixture.client, active: true, path: 'old.ts', onClose: vi.fn(), onNavigate: vi.fn(), onCoverage };
+ const props = { project: 'old-project', client: fixture.client, active: true, path: 'old.ts', onNavigate: vi.fn(), onCoverage };
await act(async () => root.render(<DiagnosticsPanel {...props} />));
await click('Run local diagnosis');
await act(async () => root.render(<DiagnosticsPanel {...props} project="new-project" path="new.ts" />));
diff --git a/graph-ui/src/diagnostics/DiagnosticsPanel.tsx b/graph-ui/src/diagnostics/DiagnosticsPanel.tsx
index 218a2cef7..4d295762a 100644
--- a/graph-ui/src/diagnostics/DiagnosticsPanel.tsx
+++ b/graph-ui/src/diagnostics/DiagnosticsPanel.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { loadCoverage, loadPathCoverage, type CoverageReading } from '../app/coverage-source';
import type { CoverageIndex } from '../app/tree-model';
import type { RpcIntelligenceClient } from '../provider/rpc-client';
@@ -11,14 +11,14 @@ export interface DiagnosticsPanelProps {
coverage?: CoverageIndex | null;
coverageError?: string | null;
active: boolean;
- onClose: () => void;
path?: string;
+ indexDetails?: ReactNode;
onNavigate: (path: string) => void;
/** App can update its shared coverage reading from the same diagnosis. */
onCoverage?: (reading: CoverageReading) => void;
}
-export default function DiagnosticsPanel({ project, client, coverage, coverageError, active, onClose, path, onNavigate, onCoverage }: DiagnosticsPanelProps) {
+export default function DiagnosticsPanel({ project, client, coverage, coverageError, active, path, indexDetails, onNavigate, onCoverage }: DiagnosticsPanelProps) {
const [diagnosis, setDiagnosis] = useState<LocalDiagnosis | null>(null);
const [report, setReport] = useState('');
const [busy, setBusy] = useState(false);
@@ -62,8 +62,8 @@ export default function DiagnosticsPanel({ project, client, coverage, coverageEr
anchor.click(); URL.revokeObjectURL(url); setStatus('Edited report downloaded locally. Nothing was sent.');
};
if (!active) return null;
- return <section className="diagnostics-panel" role="dialog" aria-label="Index coverage diagnosis" data-testid="diagnostics-panel">
- <header><div><p className="diagnostics-eyebrow">LOCAL EVIDENCE</p><h2>Index coverage diagnosis</h2><p><code>{project}</code>{path && <> · Selected <code>{path}</code></>}</p></div><button type="button" onClick={onClose}>Close diagnosis</button></header>
+ return <section className="diagnostics-panel" aria-label="Coverage" data-testid="diagnostics-panel">
+ <header><div><p className="diagnostics-eyebrow">{project}</p><h2>Coverage</h2>{path && <p>Selected <code>{path}</code></p>}</div></header>
<p>The map can omit excluded files, unsupported inputs and failed or partial parses. Inspect the recorded reasons before relying on missing graph relationships.</p>
{(error || coverageError) && <p role="alert" className="diagnostics-error">Coverage reading failed: {error || coverageError}. {index ? 'Previous records remain visible; this is not a fresh reading.' : 'Completeness is unknown.'}</p>}
<div className="diagnostics-actions"><button type="button" disabled={busy || !project} onClick={() => { void run(); }}>{busy ? 'Reading local diagnosis…' : 'Run local diagnosis'}</button><span>Reads existing coverage metadata through this daemon. No agent, upload or issue creation.</span></div>
@@ -75,6 +75,7 @@ export default function DiagnosticsPanel({ project, client, coverage, coverageEr
{index.listingComplete && <p className="diagnostics-caveat">All recorded coverage entries have been loaded. The parser limitations and exclusions listed below still apply.</p>}
{index.truncations.map((note) => <p key={note} className="diagnostics-caveat">Incomplete list: {note}</p>)}
</>}
+ {indexDetails && <details className="diagnostics-inventory"><summary>Index inventory and legend</summary>{indexDetails}</details>}
{diagnosis && <div className="diagnostics-reading"><p>Checked {diagnosis.checkedAt} · Index generation <code>{diagnosis.reading.answer.metadata.generation || 'unavailable'}</code> · Recording {diagnosis.reading.answer.metadata.recordingStatus || 'unavailable'}</p>
{!diagnosis.reading.answer.metadata.generationMatches && <p className="diagnostics-error">Coverage generation does not confirm the current index. Treat the map as potentially stale.</p>}
{path && <p>{diagnosis.pathAnswer ? freshnessText(diagnosis.pathAnswer.freshness) : 'No path-specific evidence returned. Freshness is unknown.'}</p>}
diff --git a/graph-ui/src/diagnostics/diagnostics.css b/graph-ui/src/diagnostics/diagnostics.css
index 9bc3fb492..198d933ff 100644
--- a/graph-ui/src/diagnostics/diagnostics.css
+++ b/graph-ui/src/diagnostics/diagnostics.css
@@ -11,7 +11,7 @@
.daemon-alert-error, .diagnostics-error { color: #ffc0cb; background: #3d1722; border-color: #ff637f; }.daemon-alert-warn { color: #f0d397; background: #2e2616; border-color: #dfa745; }
.daemon-alert-list pre { font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; overflow-wrap: anywhere; margin: 4px 0 0; }.daemon-alert-list time, .daemon-alert-list span { font-size: 11px; margin-left: 8px; }
.diagnostics-caveat { color: #b5c3ba; font-size: 11px; margin: 6px 0; }.diagnostics-error { padding: 9px 12px; border-left: 3px solid #ff637f; }
-.diagnostics-panel { position: fixed; z-index: 180; inset: 7vh max(18px, calc((100vw - 1100px) / 2)); padding: 24px; border-radius: 12px; overflow: auto; box-shadow: 0 12px 80px #000b; }
+.diagnostics-panel { height: 100%; min-width: 0; padding: clamp(18px, 3vw, 42px); border: 0; background: #0a100e; overflow: auto; }
.diagnostics-panel header { justify-content: space-between; align-items: start; }.diagnostics-panel h2 { margin: 3px 0 9px; font-size: 23px; }.diagnostics-panel h3 { font-size: 16px; }.diagnostics-eyebrow { font: 11px ui-monospace, monospace; color: #6df0b8; letter-spacing: .14em; margin: 0; }
.diagnostics-panel code { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }.diagnostics-actions { margin: 14px 0; }.diagnostics-actions > span { color: #b5c3ba; font-size: 12px; }
.diagnostics-counts { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 6px; }.diagnostics-counts span { padding: 7px 10px; background: #1b2b23; border: 1px solid #375044; border-radius: 5px; }
@@ -20,7 +20,7 @@
.diagnostics-panel textarea { width: 100%; min-height: 260px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
.diagnostics-records { list-style: none; padding: 0; max-height: 42vh; overflow: auto; }.diagnostics-records li { padding: 12px; margin: 8px 0; border: 1px solid #375044; border-left-width: 3px; border-radius: 5px; }.diagnostics-records p { margin: 5px 0; overflow-wrap: anywhere; }
.diagnostics-records .diagnostics-record-partial, .diagnostics-records .diagnostics-record-skipped { border-left-color: #ed7d91; }.diagnostics-records .diagnostics-record-excluded { border-left-color: #9eabb0; }
-@media (max-width: 600px) { .diagnostics-panel { inset: 12px; padding: 16px; }.daemon-alerts { max-height: 28vh; } }
+@media (max-width: 600px) { .diagnostics-panel { padding: 16px; }.daemon-alerts { max-height: 28vh; } }
.daemon-alerts-collapsed .daemon-alerts-heading { gap: 6px; }
.daemon-alerts-collapsed .daemon-alerts-heading button { padding: 3px 8px; font-size: 12px; }
diff --git a/graph-ui/src/galaxy/EdgeLines.tsx b/graph-ui/src/galaxy/EdgeLines.tsx
index 25874ff6b..fbaf2a387 100644
--- a/graph-ui/src/galaxy/EdgeLines.tsx
+++ b/graph-ui/src/galaxy/EdgeLines.tsx
@@ -10,37 +10,42 @@
* - Formatierung an den Stil dieses Projekts angeglichen (4 Leerzeichen,
* einfache Anfuehrungszeichen), lange Gedankenstriche in den Kommentaren
* ersetzt.
- * - Logik unveraendert, inklusive der Prop `targetNodes`: sie bediente im
+ * - Die Prop `targetNodes` bleibt erhalten: sie bediente im
* Original die Kanten zwischen zwei Galaxien. Dieses Projekt setzt sie
* nicht, sie bleibt aber stehen, damit die Datei gegen das Original
* vergleichbar bleibt.
- * - EDGE_TYPE_COLORS und DEFAULT_EDGE_COLOR sind exportiert (W4d). Die Werte
- * sind unveraendert; die Galaxy-Legende liest die Tabelle, statt sie zu
- * wiederholen. Eine zweite Farbtabelle waere die Sorte Legende, die nach
- * der ersten Aenderung an dieser Datei etwas anderes behauptet als das
- * Bild daneben.
+ * - EDGE_TYPE_COLORS und DEFAULT_EDGE_COLOR bleiben exportiert (W4d);
+ * seit der gemeinsamen Kantenpalette kommen sie aus graph/edge-style.
* - W9, Aenderung 1: die Deckkraft haengt an der Kantenzahl, statt fest zu
* sein. Die Zahlen und der Grund stehen an {@link edgeIntensityFor}. Ab
* 30000 Kanten rechnet weiter die Kurve der Uebernahme, Zeichen fuer
* Zeichen; darunter wird die Kante so hell, dass ihre Farbe eine Aussage
- * ist. Das ist die eine echte Abweichung dieser Datei vom Original.
+ * ist.
* - W9, Aenderung 3: eine Kante darf einen seitlichen Versatz tragen
* (`GraphEdge.offset`), damit zwei Beziehungen zwischen denselben zwei
* Symbolen nicht auf demselben Strich liegen. Ohne den Wert aendert sich
* nichts; die Galaxie setzt ihn nicht.
- * - W9, Aenderung 2: die Farbtabelle bekommt die Kantenarten dazu, die die
- * Engine dieses Projekts wirklich liefert (USAGE, CONFIGURES, RAISES,
- * CALL_REFERENCE, HAS_BRANCH). Die uebernommenen Eintraege bleiben Wert
- * fuer Wert stehen und liegen dafuer in einer eigenen Tabelle, damit die
- * Abweichung nachlesbar ist statt untergemischt.
+ * - W9, Aenderung 2 ergaenzte die Engine-Kantenarten. Die gemeinsame
+ * Palette traegt diese Arten jetzt fuer alle Graphansichten.
+ * - Ein GPU-Puls laeuft entlang gerichteter Kanten von Quelle zu Ziel.
+ * Geometrie und Material bleiben gebuendelt; nur eine Zeit-Uniform wird
+ * je Bild geaendert. Pause, reduzierte Bewegung und verborgene Ansichten
+ * stoppen den Puls ohne Geometrie-Neubau.
*/
-import { useMemo } from 'react';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import type { GraphNode, GraphEdge } from './types';
import { edgeIntensityScale } from './density';
+import { edgeColor, edgePhase, isDirectedEdge } from '../graph/edge-style';
+import { useEdgeMotion } from '../graph/edge-motion';
+
+// Keep the existing import surface; every graph now reads the shared palette.
+export { EDGE_TYPE_COLORS, DEFAULT_EDGE_COLOR } from '../graph/edge-style';
interface EdgeLinesProps {
+ active?: boolean;
nodes: GraphNode[];
edges: GraphEdge[];
highlightedIds: Set<number> | null;
@@ -60,82 +65,6 @@ function getClusterKey(fp?: string): string {
return parts.slice(0, Math.min(2, parts.length)).join('/');
}
-/* Edge type to color (matches the filter panel) */
-const PORTED_EDGE_TYPE_COLORS: Record<string, string> = {
- CALLS: '#1DA27E',
- IMPORTS: '#3b82f6',
- DEFINES: '#a855f7',
- DEFINES_METHOD: '#a855f7',
- CONTAINS_FILE: '#22c55e',
- CONTAINS_FOLDER: '#22c55e',
- CONTAINS_PACKAGE: '#22c55e',
- HANDLES: '#eab308',
- IMPLEMENTS: '#f97316',
- HTTP_CALLS: '#e11d48',
- ASYNC_CALLS: '#ec4899',
- GRPC_CALLS: '#f59e0b',
- GRAPHQL_CALLS: '#e879f9',
- TRPC_CALLS: '#a78bfa',
- CROSS_HTTP_CALLS: '#fb923c',
- CROSS_ASYNC_CALLS: '#fb7185',
- CROSS_GRPC_CALLS: '#fbbf24',
- CROSS_GRAPHQL_CALLS: '#f0abfc',
- CROSS_TRPC_CALLS: '#c4b5fd',
- CROSS_CHANNEL: '#fdba74',
- MEMBER_OF: '#64748b',
- TESTS_FILE: '#06b6d4',
-};
-
-/**
- * Die Kantenarten, die die Engine dieses Projekts liefert und die die
- * uebernommene Tabelle nicht kennt (W9).
- *
- * Gemessen an der laufenden Vorschau, fixtures/atlas-sample: von den zwoelf
- * Arten, die /api/layout dort schickt, standen fuenf in keiner Zeile der
- * Tabelle (USAGE 37, CONFIGURES 6, RAISES 3, CALL_REFERENCE 1, HAS_BRANCH 1)
- * und teilten sich deshalb {@link DEFAULT_EDGE_COLOR} mit allem anderen
- * Unbekannten. Das ist der Teil von Martins Befund vom 2026-08-29, den die
- * Deckkraft nicht heilt: eine Kante, die es nur in EINER Farbe gibt, kann noch
- * so hell gezeichnet sein und sagt trotzdem nicht, was sie ist. Der
- * Vorgabewert bleibt fuer alles, was auch diese Liste nicht kennt: eine
- * erfundene Farbe waere eine Behauptung ueber eine Beziehung, die dieses
- * Projekt nie gesehen hat.
- *
- * Die Werte sind gegen die schon belegten Toene gewaehlt: der kleinste Abstand
- * zwischen zwei Farben, die im Demo-Fixture zusammen im Bild stehen, ist
- * 47.6 (CALLS #1DA27E gegen CONTAINS_FILE #22c55e, euklidisch in RGB), der
- * kleinste unter den fuenf neuen 92 (USAGE gegen CONFIGURES). Der Beweislauf
- * misst mit einer Schwelle von 40.
- */
-export const ENGINE_EDGE_TYPE_COLORS: Record<string, string> = {
- /* Ein Symbol benutzt ein anderes, ohne es aufzurufen: Limette. */
- USAGE: '#a3e635',
- /* Zugriff auf eine Umgebungsvariable: Gelb, die Farbe der Einstellung. */
- CONFIGURES: '#fde047',
- /* Ein Fehlerpfad. Rot, und ausdruecklich nicht das Orange von IMPLEMENTS. */
- RAISES: '#ff4d4d',
- /* Ein Aufruf, den der Index nur als Verweis kennt: helles Blau. */
- CALL_REFERENCE: '#7dd3fc',
- /* Reine Struktur des Repositoriums, wie MEMBER_OF: gedecktes Grau. */
- HAS_BRANCH: '#94a3b8',
-};
-
-/**
- * Die Tabelle, aus der die Szene und die Legende ihre Farben nehmen.
- *
- * Die uebernommenen Eintraege stehen unveraendert in
- * {@link PORTED_EDGE_TYPE_COLORS}; was dieses Projekt dazugelegt hat, steht in
- * {@link ENGINE_EDGE_TYPE_COLORS}. Zwei Tabellen und ein Zusammenschluss, damit
- * die Abweichung vom Original nachlesbar bleibt: eine gemischte Liste waere in
- * einem Jahr nicht mehr auseinanderzuhalten.
- */
-export const EDGE_TYPE_COLORS: Record<string, string> = {
- ...PORTED_EDGE_TYPE_COLORS,
- ...ENGINE_EDGE_TYPE_COLORS,
-};
-
-export const DEFAULT_EDGE_COLOR = '#1C8585';
-
/* --------------------------------------------------------- Deckkraft (W9) --
*
* Bis W9 war die Deckkraft einer Kante eine Konstante: 0.25 innerhalb eines
@@ -214,129 +143,198 @@ export function edgeIntensityFor(sameCluster: boolean, edgeCount: number): numbe
return readable * Math.pow(atWash / readable, share);
}
-export function EdgeLines({
+export function createEdgeGeometry({
nodes,
edges,
highlightedIds,
- opacity = 1.0,
brightness = 1.0,
targetNodes,
-}: EdgeLinesProps) {
- const geometry = useMemo(() => {
- /* Shrink per-edge glow as the edge count grows so the additively-blended
- * center doesn't saturate to white; the user multiplier rides on top.
- * Seit W9 nur noch fuer den abgedunkelten Rest einer Auswahl: der
- * Grundwert bringt seine eigene Kurve mit (edgeIntensityFor).
- * `edges.length` ist die Zahl der WIRKLICH gezeichneten Kanten, also
- * die nach dem Kantenart-Filter: wer die Haelfte ausblendet, hat auch
- * die Haelfte des Schleiers, und die uebrigen duerfen dafuer heller
- * werden. */
- const densityScale = edgeIntensityScale(edges.length) * brightness;
- const srcMap = new Map<number, number>();
- for (let i = 0; i < nodes.length; i++) {
- srcMap.set(nodes[i].id, i);
- }
- const tgtArr = targetNodes ?? nodes;
- const tgtMap = targetNodes ? new Map<number, number>() : srcMap;
- if (targetNodes) {
- for (let i = 0; i < targetNodes.length; i++) {
- tgtMap.set(targetNodes[i].id, i);
- }
+}: EdgeLinesProps): THREE.BufferGeometry {
+ /* Shrink per-edge glow as the edge count grows so the additively-blended
+ * center doesn't saturate to white; the user multiplier rides on top.
+ * Seit W9 nur noch fuer den abgedunkelten Rest einer Auswahl: der
+ * Grundwert bringt seine eigene Kurve mit (edgeIntensityFor).
+ * `edges.length` ist die Zahl der WIRKLICH gezeichneten Kanten, also
+ * die nach dem Kantenart-Filter: wer die Haelfte ausblendet, hat auch
+ * die Haelfte des Schleiers, und die uebrigen duerfen dafuer heller
+ * werden. */
+ const densityScale = edgeIntensityScale(edges.length) * brightness;
+ const srcMap = new Map<number, number>();
+ for (let i = 0; i < nodes.length; i++) {
+ srcMap.set(nodes[i].id, i);
+ }
+ const tgtArr = targetNodes ?? nodes;
+ const tgtMap = targetNodes ? new Map<number, number>() : srcMap;
+ if (targetNodes) {
+ for (let i = 0; i < targetNodes.length; i++) {
+ tgtMap.set(targetNodes[i].id, i);
}
+ }
- const hasHighlight = highlightedIds && highlightedIds.size > 0;
- const positions = new Float32Array(edges.length * 6);
- const colors = new Float32Array(edges.length * 6);
- let validCount = 0;
+ const hasHighlight = highlightedIds && highlightedIds.size > 0;
+ const positions = new Float32Array(edges.length * 6);
+ const colors = new Float32Array(edges.length * 6);
+ const flow = new Float32Array(edges.length * 6);
+ const colorByType = new Map<string, THREE.Color>();
+ let validCount = 0;
- for (const edge of edges) {
- const si = srcMap.get(edge.source);
- const ti = tgtMap.get(edge.target);
- if (si === undefined || ti === undefined) continue;
+ for (const edge of edges) {
+ const si = srcMap.get(edge.source);
+ const ti = tgtMap.get(edge.target);
+ if (si === undefined || ti === undefined) continue;
- const s = nodes[si];
- const t = tgtArr[ti];
+ const s = nodes[si];
+ const t = tgtArr[ti];
- const sHL = !hasHighlight || highlightedIds.has(s.id);
- const tHL = !hasHighlight || highlightedIds.has(t.id);
- if (hasHighlight && !sHL && !tHL) continue;
+ const sHL = !hasHighlight || highlightedIds.has(s.id);
+ const tHL = !hasHighlight || highlightedIds.has(t.id);
+ if (hasHighlight && !sHL && !tHL) continue;
- const sameCluster =
- getClusterKey(s.file_path) === getClusterKey(t.file_path);
+ const sameCluster =
+ getClusterKey(s.file_path) === getClusterKey(t.file_path);
- /* Intensity based on cluster membership and highlight.
- * With additive blending + dark background, these glow nicely.
- * Seit W9 haengt der Grundwert an der Kantenzahl: siehe
- * edgeIntensityFor. Der Fokus-Zweig ist der der Uebernahme. */
- let intensity = edgeIntensityFor(sameCluster, edges.length) * brightness;
- if (hasHighlight) {
- /* A selection stays at full strength (never density-scaled) so it
- * pops against the dimmed rest; only the un-selected bulk is scaled. */
- intensity = sHL && tHL
- ? EDGE_INTENSITY_FOCUS
- : EDGE_INTENSITY_MUTED * densityScale;
- }
+ /* Intensity based on cluster membership and highlight.
+ * With additive blending + dark background, these glow nicely.
+ * Seit W9 haengt der Grundwert an der Kantenzahl: siehe
+ * edgeIntensityFor. Der Fokus-Zweig ist der der Uebernahme. */
+ let intensity = edgeIntensityFor(sameCluster, edges.length) * brightness;
+ if (hasHighlight) {
+ /* A selection stays at full strength (never density-scaled) so it
+ * pops against the dimmed rest; only the un-selected bulk is scaled. */
+ intensity = sHL && tHL
+ ? EDGE_INTENSITY_FOCUS
+ : EDGE_INTENSITY_MUTED * densityScale;
+ }
- /*
- * Der seitliche Versatz (W9, Aenderung 3).
- *
- * Zwei Symbole koennen mehr als eine Beziehung haben: im
- * Demo-Fixture ruft createUser die Klasse ValidationError UND wirft
- * sie. Beide Linien auf denselben Strich zu legen hiesse, sie
- * additiv zu einer dritten Farbe zu mischen, die in keiner Legende
- * steht. Also wird die zweite Linie um `edge.offset` Welteinheiten
- * neben die erste gelegt, senkrecht zur Verbindung in der
- * xy-Ebene. Die Enden bleiben dieselben Symbole; nur der Strich
- * dazwischen weicht aus.
- *
- * Ohne `offset` (die Galaxie setzt keinen) ist das ein
- * Vergleich und sonst nichts.
- */
- let ox = 0;
- let oy = 0;
- const offsetBy = edge.offset ?? 0;
- if (offsetBy !== 0) {
- const dx = t.x - s.x;
- const dy = t.y - s.y;
- const length = Math.sqrt(dx * dx + dy * dy);
- if (length > 0) {
- ox = (-dy / length) * offsetBy;
- oy = (dx / length) * offsetBy;
- }
+ /*
+ * Der seitliche Versatz (W9, Aenderung 3).
+ *
+ * Zwei Symbole koennen mehr als eine Beziehung haben: im
+ * Demo-Fixture ruft createUser die Klasse ValidationError UND wirft
+ * sie. Beide Linien auf denselben Strich zu legen hiesse, sie
+ * additiv zu einer dritten Farbe zu mischen, die in keiner Legende
+ * steht. Also wird die zweite Linie um `edge.offset` Welteinheiten
+ * neben die erste gelegt, senkrecht zur Verbindung in der
+ * xy-Ebene. Die Enden bleiben dieselben Symbole; nur der Strich
+ * dazwischen weicht aus.
+ *
+ * Ohne `offset` (die Galaxie setzt keinen) ist das ein
+ * Vergleich und sonst nichts.
+ */
+ let ox = 0;
+ let oy = 0;
+ const offsetBy = edge.offset ?? 0;
+ if (offsetBy !== 0) {
+ const dx = t.x - s.x;
+ const dy = t.y - s.y;
+ const length = Math.sqrt(dx * dx + dy * dy);
+ if (length > 0) {
+ ox = (-dy / length) * offsetBy;
+ oy = (dx / length) * offsetBy;
}
+ }
+
+ const off = validCount * 6;
+ positions[off] = s.x + ox;
+ positions[off + 1] = s.y + oy;
+ positions[off + 2] = s.z;
+ positions[off + 3] = t.x + ox;
+ positions[off + 4] = t.y + oy;
+ positions[off + 5] = t.z;
+
+ /* Color from edge TYPE (correlates with edge type filter) */
+ let color = colorByType.get(edge.type);
+ if (!color) {
+ color = new THREE.Color(edgeColor(edge.type));
+ colorByType.set(edge.type, color);
+ }
+ colors[off] = color.r * intensity;
+ colors[off + 1] = color.g * intensity;
+ colors[off + 2] = color.b * intensity;
+ colors[off + 3] = color.r * intensity;
+ colors[off + 4] = color.g * intensity;
+ colors[off + 5] = color.b * intensity;
+
+ const phase = edgePhase(`${edge.source}:${edge.target}:${edge.type}`);
+ const directed = isDirectedEdge(edge.type) ? 1 : 0;
+ flow[off] = 0;
+ flow[off + 1] = phase;
+ flow[off + 2] = directed;
+ flow[off + 3] = 1;
+ flow[off + 4] = phase;
+ flow[off + 5] = directed;
+ validCount++;
+ }
+
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute(
+ 'position',
+ new THREE.BufferAttribute(positions.slice(0, validCount * 6), 3),
+ );
+ geo.setAttribute(
+ 'color',
+ new THREE.BufferAttribute(colors.slice(0, validCount * 6), 3),
+ );
+ geo.setAttribute(
+ 'edgeFlow',
+ new THREE.BufferAttribute(flow.slice(0, validCount * 6), 3),
+ );
+ return geo;
+}
+
+const EDGE_PULSE_SECONDS = 4.8;
+
+export function EdgeLines({ active = true, opacity = 1.0, ...props }: EdgeLinesProps) {
+ const { nodes, edges, highlightedIds, targetNodes, brightness } = props;
+ const moving = useEdgeMotion(active);
+ const geometry = useMemo(
+ () => createEdgeGeometry({ nodes, edges, highlightedIds, targetNodes, brightness }),
+ [nodes, edges, highlightedIds, targetNodes, brightness],
+ );
+ const uniforms = useMemo(() => ({ edgeTime: { value: 0 }, edgeMotion: { value: 0 } }), []);
+ const lastFrame = useRef<number | null>(null);
- const off = validCount * 6;
- positions[off] = s.x + ox;
- positions[off + 1] = s.y + oy;
- positions[off + 2] = s.z;
- positions[off + 3] = t.x + ox;
- positions[off + 4] = t.y + oy;
- positions[off + 5] = t.z;
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ useEffect(() => {
+ uniforms.edgeMotion.value = moving ? 1 : 0;
+ lastFrame.current = null;
+ }, [moving, uniforms]);
- /* Color from edge TYPE (correlates with edge type filter) */
- const edgeColor = new THREE.Color(
- EDGE_TYPE_COLORS[edge.type] ?? DEFAULT_EDGE_COLOR,
- );
- colors[off] = edgeColor.r * intensity;
- colors[off + 1] = edgeColor.g * intensity;
- colors[off + 2] = edgeColor.b * intensity;
- colors[off + 3] = edgeColor.r * intensity;
- colors[off + 4] = edgeColor.g * intensity;
- colors[off + 5] = edgeColor.b * intensity;
- validCount++;
+ useFrame(() => {
+ if (!moving) return;
+ // FrameCapDriver supplies milliseconds to Fiber; wall time keeps the
+ // pulse at the same speed with capped and uncapped render loops.
+ const now = performance.now();
+ if (lastFrame.current !== null) {
+ uniforms.edgeTime.value =
+ (uniforms.edgeTime.value + (now - lastFrame.current) / 1000) % EDGE_PULSE_SECONDS;
}
+ lastFrame.current = now;
+ });
- const geo = new THREE.BufferGeometry();
- geo.setAttribute(
- 'position',
- new THREE.BufferAttribute(positions.slice(0, validCount * 6), 3),
- );
- geo.setAttribute(
- 'color',
- new THREE.BufferAttribute(colors.slice(0, validCount * 6), 3),
- );
- return geo;
- }, [nodes, edges, highlightedIds, targetNodes, brightness]);
+ const prepareMaterial = useCallback<THREE.Material['onBeforeCompile']>((shader) => {
+ shader.uniforms.edgeTime = uniforms.edgeTime;
+ shader.uniforms.edgeMotion = uniforms.edgeMotion;
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', `#include <common>
+attribute vec3 edgeFlow;
+varying vec3 vEdgeFlow;`)
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+vEdgeFlow = edgeFlow;`);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>
+uniform float edgeTime;
+uniform float edgeMotion;
+varying vec3 vEdgeFlow;`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+// A single soft band traverses the source (0) to target (1). Its padded
+// range enters and leaves the endpoints without wrapping across the line.
+float edgeHead = fract(edgeTime / ${EDGE_PULSE_SECONDS.toFixed(1)} + vEdgeFlow.y) * 1.24 - 0.12;
+float edgePulse = 1.0 - smoothstep(0.0, 0.10, abs(vEdgeFlow.x - edgeHead));
+// The pulse never exceeds the previous density-scaled intensity, including
+// in a dense additive cloud. All modulation preserves the relationship hue.
+diffuseColor.rgb *= 0.72 + 0.28 * edgeMotion * vEdgeFlow.z * edgePulse;`);
+ }, [uniforms]);
return (
<lineSegments geometry={geometry}>
@@ -347,6 +345,8 @@ export function EdgeLines({
blending={THREE.AdditiveBlending}
depthWrite={false}
toneMapped={false}
+ onBeforeCompile={prepareMaterial}
+ customProgramCacheKey={() => 'directed-edge-pulse-v1'}
/>
</lineSegments>
);
diff --git a/graph-ui/src/galaxy/GalaxyPanel.background.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.background.test.tsx
new file mode 100644
index 000000000..77b5de9d8
--- /dev/null
+++ b/graph-ui/src/galaxy/GalaxyPanel.background.test.tsx
@@ -0,0 +1,36 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import GalaxyPanel, { type GalaxyPanelProps } from './GalaxyPanel';
+
+vi.mock('./GraphScene', async importOriginal => ({ ...await importOriginal<typeof import('./GraphScene')>(), GraphScene: ({ onBackgroundClick }: { onBackgroundClick?: () => void }) =>
+ <button onClick={onBackgroundClick}>Empty canvas</button> }));
+let host: HTMLDivElement, root: Root;
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); globalThis.__atlasGalaxy = undefined; });
+const nodes = [1, 2, 3].map(id => ({ id, name: `node${id}`, qualified_name: `sample.node${id}`, file_path: `src/file${id}.ts`,
+ label: 'Function', x: id * 10, y: 0, z: 0, start_line: 1, end_line: 10, size: 1, color: '#999999' }));
+
+it('keeps the overall graph after clearing while the code caret stays put, and follows the next explicit source change', async () => {
+ const clear = vi.fn(), fetchLayout = vi.fn(async () => new Response(JSON.stringify({ nodes, edges: [{ source: 1, target: 2, type: 'CALLS' }], total_nodes: 3 })));
+ const props: GalaxyPanelProps = { project: 'sample', visible: true, onOpenNode: vi.fn(), onClearSelection: clear,
+ fetch: fetchLayout, focusQualifiedName: 'sample.node1', focusFilePath: 'src/file1.ts', focusSourceRange: { startLine: 1, endLine: 1 } };
+ await act(async () => root.render(<GalaxyPanel {...props} />));
+ expect(globalThis.__atlasGalaxy?.highlightedCount).toBe(2);
+ const fits = globalThis.__atlasGalaxy!.fits;
+ const background = [...host.querySelectorAll('button')].find(button => button.textContent === 'Empty canvas')!;
+ await act(async () => background.click());
+ expect(globalThis.__atlasGalaxy?.highlightedCount).toBe(0);
+ expect(globalThis.__atlasGalaxy!.fits).toBeGreaterThan(fits);
+ expect(clear).toHaveBeenCalledOnce();
+ await act(async () => root.render(<GalaxyPanel {...props} visible={false} focusSourceRange={{ startLine: 1, endLine: 1 }} />));
+ await act(async () => root.render(<GalaxyPanel {...props} focusSourceRange={{ startLine: 1, endLine: 1 }} />));
+ expect(globalThis.__atlasGalaxy?.highlightedCount).toBe(0);
+ await act(async () => root.render(<GalaxyPanel {...props} focusQualifiedName="sample.node3" focusFilePath="src/file3.ts" />));
+ expect(globalThis.__atlasGalaxy?.highlightedCount).toBe(1);
+ expect(globalThis.__atlasGalaxy?.lastTargetQn).toBe('sample.node3');
+});
diff --git a/graph-ui/src/galaxy/GalaxyPanel.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.test.tsx
index 2b13945c2..69d746424 100644
--- a/graph-ui/src/galaxy/GalaxyPanel.test.tsx
+++ b/graph-ui/src/galaxy/GalaxyPanel.test.tsx
@@ -297,8 +297,8 @@ describe('GalaxyPanel und die Legende', () => {
.toEqual(['CALLS', 'WHAT_IS_THIS']);
// CALLS steht in der Tabelle, WHAT_IS_THIS nicht: der zweite bekommt
// die Vorgabefarbe, die auch die Szene malt.
- expect(swatches[0]?.getAttribute('data-color')).toBe('#1DA27E');
- expect(swatches[1]?.getAttribute('data-color')).toBe('#1C8585');
+ expect(swatches[0]?.getAttribute('data-color')).toBe('#579fc7');
+ expect(swatches[1]?.getAttribute('data-color')).toBe('#84939d');
});
/*
diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsx
index 94fff97ad..927a3d0df 100644
--- a/graph-ui/src/galaxy/GalaxyPanel.tsx
+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx
@@ -591,6 +591,7 @@ export interface GalaxyPanelProps {
onSelectNode?: ((node: GraphNode) => void) | undefined;
onSelectShadowNode?: ((node: CoverageShadowNode) => void) | undefined;
selectedNode?: GraphNode | undefined;
+ onClearSelection?: () => void;
/** Das Projekt, dessen Layout gezeigt wird. Leer heisst: nichts laden. */
project: string;
/** Ob das Panel im Layout sichtbar ist. */
@@ -1412,9 +1413,14 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
};
}, [visible, mode, projection, picture, aspect, requestedFit, ownFit, coverageShadow, fitRequest, props.workspaceExpanded]);
+ const [backgroundCleared, setBackgroundCleared] = useState(false);
+ useEffect(() => {
+ if (focusQualifiedName || stepQualifiedName || props.focusFilePath) setBackgroundCleared(false);
+ }, [focusQualifiedName, stepQualifiedName, props.focusFilePath, props.focusSourceRange?.startLine, props.focusSourceRange?.endLine]);
+
// Hin-Richtung in der Galaxie: das Twin-Subjekt zieht die Kamera nach.
useEffect(() => {
- if (mode !== 'galaxy' || data === undefined) {
+ if (backgroundCleared || mode !== 'galaxy' || data === undefined) {
return;
}
const node = focusQualifiedName ? index.get(focusQualifiedName) : undefined;
@@ -1443,7 +1449,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
// `focusName` steht bewusst nicht in der Liste: er begleitet den
// qualifizierten Namen und darf keine zweite Kamerafahrt ausloesen.
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [mode, data, index, focusQualifiedName, flyTo, props.focusFilePath, props.focusSourceRange, aspect, visible]);
+ }, [backgroundCleared, mode, data, index, focusQualifiedName, flyTo, props.focusFilePath, props.focusSourceRange, aspect, visible]);
/*
* FOLLOW: die Kamera geht dorthin, wo sich zuletzt etwas bewegt hat.
@@ -1557,7 +1563,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
* dorthin gehoert, wo der Leser hingegangen ist.
*/
const pulsedNode = useMemo(() => {
- if (mode !== 'hierarchy') {
+ if (backgroundCleared || mode !== 'hierarchy') {
return undefined;
}
for (const candidate of [focusQualifiedName, stepQualifiedName]) {
@@ -1569,7 +1575,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
}
}
return undefined;
- }, [mode, focusQualifiedName, stepQualifiedName, index]);
+ }, [backgroundCleared, mode, focusQualifiedName, stepQualifiedName, index]);
/*
* In der Hierarchie bleibt alles hell.
@@ -1593,6 +1599,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
// Rueck-Richtung: ein Klick in die Szene oeffnet die Datei.
const handleNodeClick = useCallback(
(node: GraphNode) => {
+ setBackgroundCleared(false);
// In der Hierarchie bleibt die Kamera stehen und alles hell: sie
// rahmt den ganzen Subgraphen, und auf eine Spalte zu zoomen waere
// wieder die Nachbarschaftsansicht, gegen die dieses Bild gebaut
@@ -1619,9 +1626,12 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
);
const handleBackgroundClick = useCallback(() => {
+ setBackgroundCleared(true);
setHighlighted(null);
setNote(mode === 'hierarchy' ? HIERARCHY_NO_FOCUS_NOTE : GALAXY_NO_FOCUS_NOTE);
- }, [mode]);
+ refitNow();
+ props.onClearSelection?.();
+ }, [mode, refitNow, props.onClearSelection]);
/*
* Die Vorgabe der Ansicht, mit der Wahl des Lesers darauf.
@@ -1881,7 +1891,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
* darunter trifft.
*/
const pulseRing: ReactNode =
- mode === 'hierarchy' && pulsedNode !== undefined ? (
+ mode === 'hierarchy' && !backgroundCleared && pulsedNode !== undefined ? (
<Html
position={[pulsedNode.x, pulsedNode.y, pulsedNode.z]}
center
diff --git a/graph-ui/src/galaxy/GraphScene.tsx b/graph-ui/src/galaxy/GraphScene.tsx
index 59ddad32d..dc3ec20e7 100644
--- a/graph-ui/src/galaxy/GraphScene.tsx
+++ b/graph-ui/src/galaxy/GraphScene.tsx
@@ -650,6 +650,8 @@ function IdleAutoRotate({
/* Main scene */
+import { useGraphBackgroundReset } from '../graph/useGraphBackgroundReset';
+
interface GraphSceneProps {
/* False pauses the render loop (hidden-but-mounted panel). */
active?: boolean;
@@ -727,6 +729,7 @@ export function GraphScene({
const [hovered, setHovered] = useState<GraphNode | null>(null);
const [hoveredShadow, setHoveredShadow] = useState<CoverageShadowNode | null>(null);
const controlsRef = useRef<OrbitControlsImpl | null>(null);
+ const background = useGraphBackgroundReset(() => { setHovered(null); setHoveredShadow(null); onBackgroundClick?.(); });
const flat = projection === 'flat';
const sceneNodes = useMemo(() => coverageShadow ? [...data.nodes, ...coverageShadow.nodes] : data.nodes, [data.nodes, coverageShadow]);
const onCodeHover = useCallback((node: GraphNode | null) => {
@@ -817,6 +820,7 @@ export function GraphScene({
return (
<Canvas
+ {...background}
frameloop={frameloop}
camera={{ position: [0, 0, 800], fov: GRAPH_CAMERA_FOV, near: 0.1, far: 100000 }}
style={{ background: '#0D0F12' }}
@@ -826,7 +830,6 @@ export function GraphScene({
alpha: false,
powerPreference: 'high-performance',
}}
- onPointerMissed={onBackgroundClick}
>
<color attach="background" args={['#0D0F12']} />
<ambientLight intensity={0.5} />
@@ -841,6 +844,7 @@ export function GraphScene({
{drawEdges && (
<EdgeLines
+ active={active}
nodes={data.nodes}
edges={data.edges}
highlightedIds={highlightedIds}
diff --git a/graph-ui/src/galaxy/edge-lines.test.ts b/graph-ui/src/galaxy/edge-lines.test.ts
new file mode 100644
index 000000000..d69cf8c13
--- /dev/null
+++ b/graph-ui/src/galaxy/edge-lines.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest';
+import * as THREE from 'three';
+import { createEdgeGeometry, EDGE_INTENSITY_FOCUS, edgeIntensityFor } from './EdgeLines';
+import { edgeColor } from '../graph/edge-style';
+import type { GraphNode } from './types';
+
+const node = (id: number, x = id, y = 0, z = 0): GraphNode => ({
+ id, x, y, z, name: `node${id}`, label: 'Function', size: 1, color: '#ffffff',
+});
+
+describe('Galaxy edge geometry', () => {
+ it('binds pulse progress to source and target, regardless of node order', () => {
+ const geometry = createEdgeGeometry({
+ nodes: [node(2, -5, 6, 7), node(1, 2, 3, 4)],
+ edges: [{ source: 1, target: 2, type: 'CALLS' }],
+ highlightedIds: null,
+ });
+ const positions = geometry.getAttribute('position');
+ const flow = geometry.getAttribute('edgeFlow');
+ expect(Array.from(positions.array)).toEqual([2, 3, 4, -5, 6, 7]);
+ expect([flow.getX(0), flow.getX(1)]).toEqual([0, 1]);
+ expect([flow.getZ(0), flow.getZ(1)]).toEqual([1, 1]);
+ expect(flow.getY(0)).toBe(flow.getY(1));
+ expect(flow.getY(0)).toBeGreaterThanOrEqual(0);
+ expect(flow.getY(0)).toBeLessThan(1);
+ geometry.dispose();
+ });
+
+ it('keeps symmetric and unknown relations static while hierarchy containment stays directed', () => {
+ const types = ['SIMILAR_TO', 'SEMANTICALLY_RELATED', 'FILE_CHANGES_WITH', 'UNKNOWN', 'CONTAINS'];
+ const geometry = createEdgeGeometry({
+ nodes: [node(1), node(2)],
+ edges: types.map((type) => ({ source: 1, target: 2, type })),
+ highlightedIds: null,
+ });
+ const flow = geometry.getAttribute('edgeFlow');
+ expect(types.map((_, index) => flow.getZ(index * 2))).toEqual([0, 0, 0, 0, 1]);
+ expect(types.map((_, index) => flow.getZ(index * 2 + 1))).toEqual([0, 0, 0, 0, 1]);
+ geometry.dispose();
+ });
+
+ it('compacts invalid and out-of-focus edges without shifting the surviving pulse attributes', () => {
+ const nodes = [node(1), node(2), node(3)];
+ const kept = { source: 2, target: 3, type: 'IMPORTS' };
+ const single = createEdgeGeometry({ nodes, edges: [kept], highlightedIds: null });
+ const filtered = createEdgeGeometry({
+ nodes,
+ edges: [
+ { source: 404, target: 2, type: 'CALLS' },
+ { source: 1, target: 2, type: 'CALLS' },
+ kept,
+ ],
+ highlightedIds: new Set([3]),
+ });
+ expect(filtered.getAttribute('position').count).toBe(2);
+ expect(filtered.getAttribute('color').count).toBe(2);
+ expect(Array.from(filtered.getAttribute('edgeFlow').array))
+ .toEqual(Array.from(single.getAttribute('edgeFlow').array));
+ expect(Array.from(filtered.getAttribute('position').array))
+ .toEqual(Array.from(single.getAttribute('position').array));
+ single.dispose();
+ filtered.dispose();
+ });
+
+ it('preserves source-to-target direction with an alternate target array and edge offset', () => {
+ const geometry = createEdgeGeometry({
+ nodes: [node(1, 0, 0, 1)],
+ targetNodes: [node(2, 4, 0, 2)],
+ edges: [{ source: 1, target: 2, type: 'CALLS', offset: 3 }],
+ highlightedIds: null,
+ });
+ expect(Array.from(geometry.getAttribute('position').array)).toEqual([0, 3, 1, 4, 3, 2]);
+ const flow = geometry.getAttribute('edgeFlow');
+ expect([flow.getX(0), flow.getX(1)]).toEqual([0, 1]);
+ geometry.dispose();
+ });
+
+ it('retains the shared relationship hue under density scaling and focus', () => {
+ const nodes = [node(1), node(2)];
+ const edges = [{ source: 1, target: 2, type: 'IMPORTS' }];
+ const color = new THREE.Color(edgeColor('IMPORTS'));
+ for (const highlightedIds of [null, new Set([1, 2])]) {
+ const geometry = createEdgeGeometry({ nodes, edges, highlightedIds });
+ const rendered = geometry.getAttribute('color');
+ const intensity = highlightedIds ? EDGE_INTENSITY_FOCUS : edgeIntensityFor(true, 1);
+ expect(rendered.getX(0)).toBeCloseTo(color.r * intensity, 6);
+ expect(rendered.getY(0)).toBeCloseTo(color.g * intensity, 6);
+ expect(rendered.getZ(0)).toBeCloseTo(color.b * intensity, 6);
+ expect(Array.from(rendered.array).slice(0, 3)).toEqual(Array.from(rendered.array).slice(3));
+ geometry.dispose();
+ }
+ });
+});
diff --git a/graph-ui/src/galaxy/galaxy-legend.ts b/graph-ui/src/galaxy/galaxy-legend.ts
index 30c3ceea4..6baa597f1 100644
--- a/graph-ui/src/galaxy/galaxy-legend.ts
+++ b/graph-ui/src/galaxy/galaxy-legend.ts
@@ -15,7 +15,7 @@
* Label plus ein Zuschlag aus dem Grad. Diese Oberflaeche faerbt keinen
* Knoten selbst; sie malt, was im Layout steht.
* 2. **Die Kantenfarben kommen aus der Tabelle, die sie malt.** Importiert aus
- * EdgeLines.tsx, nicht abgeschrieben. Gezeigt werden nur die Typen, die im
+ * graph/edge-style, wie EdgeLines.tsx. Gezeigt werden nur die Typen, die im
* geladenen Layout wirklich vorkommen: eine Legende mit zwanzig Kantenarten
* fuer einen Graphen mit dreien ist eine Legende fuer ein anderes Bild.
* Seit W9 steht neben jeder Art ihre Zahl, GEZAEHLT in der geladenen
@@ -45,7 +45,7 @@
* weggefallen ist: gestrichen wurde Wiederholung, nicht Inhalt.
*/
-import { DEFAULT_EDGE_COLOR, EDGE_TYPE_COLORS } from './EdgeLines';
+import { edgeColor } from '../graph/edge-style';
import { HIERARCHY_DEFAULT_COLOR } from './hierarchy-layout';
import type { GraphData } from './types';
@@ -105,7 +105,7 @@ export interface EdgeKind {
/** Die Farbe eines Kantentyps, so wie EdgeLines sie malt. */
export function edgeColorFor(type: string): string {
- return EDGE_TYPE_COLORS[type] ?? DEFAULT_EDGE_COLOR;
+ return edgeColor(type);
}
/**
@@ -215,7 +215,8 @@ export function galaxyLegendEntries(data: GraphData | undefined): LegendEntry[]
swatches.length === 0
? 'one colour per edge type, from the table that draws the lines. The types appear once a layout is loaded.'
: 'one colour per edge type, from the table that draws the lines. Counted in this '
- + 'layout, most frequent first. Click a kind to take it out; it stays here, dimmed.';
+ + 'layout, most frequent first. A soft pulse follows known directed relations from source to target. '
+ + 'Click a kind to take it out; it stays here, dimmed.';
return [
{
key: 'edge-color',
diff --git a/graph-ui/src/graph/EdgePulseLayer.tsx b/graph-ui/src/graph/EdgePulseLayer.tsx
new file mode 100644
index 000000000..ab9ef5b82
--- /dev/null
+++ b/graph-ui/src/graph/EdgePulseLayer.tsx
@@ -0,0 +1,86 @@
+import { useEffect, useMemo, useRef } from 'react';
+import { useFrame, useThree } from '@react-three/fiber';
+import { BufferGeometry, Color, Float32BufferAttribute } from 'three';
+import { edgeColor, edgePhase, isDirectedEdge } from './edge-style';
+import { useEdgeMotion } from './edge-motion';
+
+export interface EdgePulsePath {
+ id: string | number; type: string; types?: readonly string[];
+ points: readonly { x: number; y: number; z: number }[]; opacity?: number;
+}
+/** One line batch for every curve; progress is measured from semantic source to target. */
+export function edgePulseGeometry(paths: readonly EdgePulsePath[]): BufferGeometry {
+ const positions: number[] = [], colors: number[] = [], flow: number[] = [];
+ for (const path of paths) {
+ if (!isDirectedEdge(path.type, path.types) || path.points.length < 2 || (path.opacity ?? 1) <= 0) continue;
+ if (path.points.some(point => ![point.x, point.y, point.z].every(Number.isFinite))) continue;
+ const distances = [0];
+ for (let i = 1; i < path.points.length; i++) {
+ const a = path.points[i - 1], b = path.points[i];
+ distances.push(distances[i - 1] + Math.hypot(b.x - a.x, b.y - a.y, b.z - a.z));
+ }
+ const total = distances.at(-1)!;
+ if (!total) continue;
+ const color = new Color(edgeColor(path.type, path.types)), phase = edgePhase(path.id);
+ for (let i = 1; i < path.points.length; i++) for (const index of [i - 1, i]) {
+ const point = path.points[index];
+ positions.push(point.x, point.y, point.z); colors.push(color.r, color.g, color.b);
+ flow.push(distances[index] / total, phase, Math.max(0, Math.min(1, path.opacity ?? .7)));
+ }
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
+ geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
+ geometry.setAttribute('edgeFlow', new Float32BufferAttribute(flow, 3));
+ geometry.computeBoundingSphere();
+ return geometry;
+}
+
+const vertexShader = `
+attribute vec3 edgeFlow;
+attribute vec3 color;
+varying vec3 vFlow;
+varying vec3 vColor;
+void main() {
+ vFlow = edgeFlow;
+ vColor = color;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+}`;
+const fragmentShader = `
+uniform float uTime;
+varying vec3 vFlow;
+varying vec3 vColor;
+void main() {
+ float age = fract(uTime / 6.0 + vFlow.y - vFlow.x + 1.0);
+ float pulse = 1.0 - smoothstep(0.0, 0.12, age);
+ float ends = smoothstep(0.0, 0.025, vFlow.x) * (1.0 - smoothstep(0.975, 1.0, vFlow.x));
+ gl_FragColor = vec4(vColor * 1.2, vFlow.z * pulse * ends);
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+}`;
+
+/** A single clock and draw call, sleeping when paused, hidden or motion is reduced. */
+export function EdgePulseLayer({ paths, active = true }: { paths: readonly EdgePulsePath[]; active?: boolean }) {
+ const motion = useEdgeMotion(active), { invalidate } = useThree();
+ const geometry = useMemo(() => edgePulseGeometry(paths), [paths]);
+ const uniforms = useMemo(() => ({ uTime: { value: 0 } }), []);
+ const lastTime = useRef<number | undefined>(undefined);
+ const enabled = motion && geometry.getAttribute('position').count > 0;
+ useEffect(() => () => geometry.dispose(), [geometry]);
+ useEffect(() => {
+ lastTime.current = undefined;
+ invalidate();
+ if (!enabled) return;
+ const timer = window.setInterval(invalidate, 1000 / 24);
+ return () => window.clearInterval(timer);
+ }, [enabled, invalidate]);
+ useFrame(() => {
+ if (!enabled) return;
+ const now = performance.now() / 1000;
+ if (lastTime.current !== undefined) uniforms.uTime.value += now - lastTime.current;
+ lastTime.current = now;
+ });
+ return <lineSegments geometry={geometry} visible={enabled} renderOrder={4} raycast={() => null} dispose={null}>
+ <shaderMaterial vertexShader={vertexShader} fragmentShader={fragmentShader} uniforms={uniforms} transparent depthWrite={false} />
+ </lineSegments>;
+}
diff --git a/graph-ui/src/graph/GraphEdgeControls.tsx b/graph-ui/src/graph/GraphEdgeControls.tsx
new file mode 100644
index 000000000..998c43cf7
--- /dev/null
+++ b/graph-ui/src/graph/GraphEdgeControls.tsx
@@ -0,0 +1,35 @@
+import { useEffect, useRef } from 'react';
+import { edgeColor } from './edge-style';
+import { useEdgeMotionPreference } from './edge-motion';
+import './edge-style.css';
+
+const KEY = [
+ ['CALLS', 'Calls'], ['IMPORTS', 'Imports'], ['USAGE', 'Usage'], ['DATA_FLOWS', 'Data flow'],
+ ['READS', 'Reads'], ['WRITES', 'Writes'],
+ ['HTTP_CALLS', 'HTTP'], ['ASYNC_CALLS', 'Async'], ['INHERITS', 'Inheritance'], ['IMPLEMENTS', 'Implementation'],
+ ['CONTAINS', 'Containment'], ['DEFINES', 'Definitions'], ['CONFIGURES', 'Configuration'], ['RAISES', 'Errors'],
+ ['CALL_REFERENCE', 'Call references'], ['TESTS', 'Tests'],
+ ['SIMILAR_TO', 'Similarity'], ['RELATIONSHIPS', 'Mixed / unknown'],
+];
+
+export default function GraphEdgeControls() {
+ const { enabled, reduced, setEnabled } = useEdgeMotionPreference();
+ const details = useRef<HTMLDetailsElement>(null);
+ useEffect(() => {
+ const close = (event: PointerEvent) => {
+ if (details.current?.open && !details.current.contains(event.target as Node)) details.current.open = false;
+ };
+ document.addEventListener('pointerdown', close);
+ return () => document.removeEventListener('pointerdown', close);
+ }, []);
+ return <details ref={details} className="graph-edge-controls" onKeyDown={event => {
+ if (event.key === 'Escape') { event.currentTarget.open = false; event.currentTarget.querySelector('summary')?.focus(); }
+ }}>
+ <summary title="3D graph edge colors and motion">Edges</summary>
+ <div className="graph-edge-settings" role="group" aria-label="3D edge appearance">
+ <label><input type="checkbox" checked={enabled && !reduced} disabled={reduced} onChange={event => setEnabled(event.target.checked)} />Direction pulse</label>
+ <p>{reduced ? 'Motion is paused by your reduced-motion setting.' : 'A subtle pulse shows relationship direction across all 3D graphs.'}</p>
+ <ul className="graph-edge-key" aria-label="Edge color key">{KEY.map(([type, label]) => <li key={type} title={type}><i style={{ backgroundColor: edgeColor(type) }} />{label}</li>)}</ul>
+ </div>
+ </details>;
+}
diff --git a/graph-ui/src/graph/connection-load.test.ts b/graph-ui/src/graph/connection-load.test.ts
new file mode 100644
index 000000000..7f427b129
--- /dev/null
+++ b/graph-ui/src/graph/connection-load.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { connectionLoad } from './connection-load';
+
+describe('visible connection load', () => {
+ it('counts typed lines once, including reciprocal links and self loops', () => {
+ const load = connectionLoad(['a', 'b', 'isolated'].map(id => ({ id })), [
+ { source: 'a', target: 'b', type: 'RELATIONSHIPS', types: ['CALLS', 'IMPORTS', 'calls'] },
+ { source: 'a', target: 'b', type: 'CALLS' },
+ { source: 'b', target: 'a', type: 'CALLS' },
+ { source: 'a', target: 'a', type: 'CALLS' },
+ { source: 'a', target: 'missing', type: 'CALLS' },
+ ]);
+ expect(load.get('a')).toEqual({ links: 4, neighbors: 1, strength: 1 });
+ expect(load.get('b')).toEqual({ links: 3, neighbors: 1, strength: Math.log1p(3) / Math.log1p(4) });
+ expect(load.get('isolated')).toEqual({ links: 0, neighbors: 0, strength: 0 });
+ });
+ it('handles empty scopes and keeps results independent of input order', () => {
+ expect(connectionLoad([], []).size).toBe(0);
+ expect(connectionLoad([{ id: 'a' }], []).get('a')?.strength).toBe(0);
+ const nodes = ['a', 'b', 'c'].map(id => ({ id }));
+ const edges = [{ source: 'a', target: 'b', type: 'CALLS' }, { source: 'a', target: 'c', type: 'IMPORTS' }];
+ const one = connectionLoad(nodes, edges), two = connectionLoad([...nodes].reverse(), [...edges].reverse());
+ for (const node of nodes) expect(two.get(node.id)).toEqual(one.get(node.id));
+ });
+});
diff --git a/graph-ui/src/graph/connection-load.ts b/graph-ui/src/graph/connection-load.ts
new file mode 100644
index 000000000..3f138c9c8
--- /dev/null
+++ b/graph-ui/src/graph/connection-load.ts
@@ -0,0 +1,27 @@
+import { normalizeEdgeType } from './edge-style';
+
+interface LoadEdge { source: string; target: string; type: string; types?: readonly string[] }
+export interface ConnectionLoad { links: number; neighbors: number; strength: number }
+
+/** Visual load counts distinct directed, typed lines, not aggregated calls or runtime traffic. */
+export function connectionLoad(nodes: readonly { id: string }[], edges: readonly LoadEdge[]): Map<string, ConnectionLoad> {
+ const links = new Map(nodes.map(node => [node.id, new Set<string>()]));
+ const neighbors = new Map(nodes.map(node => [node.id, new Set<string>()]));
+ for (const edge of edges) {
+ if (!links.has(edge.source) || !links.has(edge.target)) continue;
+ const types = new Set((edge.types?.length ? edge.types : [edge.type]).map(normalizeEdgeType));
+ for (const type of types) {
+ const key = JSON.stringify([edge.source, edge.target, type]);
+ links.get(edge.source)!.add(key); links.get(edge.target)!.add(key);
+ }
+ if (edge.source !== edge.target) {
+ neighbors.get(edge.source)!.add(edge.target); neighbors.get(edge.target)!.add(edge.source);
+ }
+ }
+ const maximum = Math.max(0, ...[...links.values()].map(items => items.size));
+ return new Map(nodes.map(node => {
+ const count = links.get(node.id)!.size;
+ return [node.id, { links: count, neighbors: neighbors.get(node.id)!.size,
+ strength: maximum ? Math.log1p(count) / Math.log1p(maximum) : 0 }];
+ }));
+}
diff --git a/graph-ui/src/graph/edge-motion.test.tsx b/graph-ui/src/graph/edge-motion.test.tsx
new file mode 100644
index 000000000..3555d0886
--- /dev/null
+++ b/graph-ui/src/graph/edge-motion.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import GraphEdgeControls from './GraphEdgeControls';
+import { setEdgeMotionPreference, useEdgeMotion } from './edge-motion';
+
+let container: HTMLDivElement, root: Root, reduced: boolean;
+let hidden: ReturnType<typeof vi.spyOn>;
+const mediaListeners = new Set<() => void>();
+function Probe({ id, active = true }: { id: string; active?: boolean }) { return <output data-testid={id}>{String(useEdgeMotion(active))}</output>; }
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ reduced = false; mediaListeners.clear();
+ vi.stubGlobal('matchMedia', vi.fn(() => ({ get matches() { return reduced; },
+ addEventListener: (_type: string, listener: () => void) => mediaListeners.add(listener), removeEventListener: (_type: string, listener: () => void) => mediaListeners.delete(listener) })));
+ hidden = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);
+ const values = new Map<string, string>();
+ vi.stubGlobal('localStorage', {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => { values.set(key, value); },
+ clear: () => values.clear(),
+ });
+ localStorage.clear(); setEdgeMotionPreference(true);
+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);
+});
+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+const state = (id: string) => container.querySelector(`[data-testid="${id}"]`)?.textContent;
+async function render() { await act(async () => root.render(<><GraphEdgeControls /><Probe id="first" /><Probe id="second" /><Probe id="inactive" active={false} /></>)); }
+
+describe('global edge motion preference', () => {
+ it('pauses every mounted scene through one persistent control', async () => {
+ await render();
+ expect(state('first')).toBe('true'); expect(state('inactive')).toBe('false');
+ await act(async () => container.querySelector<HTMLInputElement>('input')!.click());
+ expect(state('first')).toBe('false'); expect(state('second')).toBe('false');
+ expect(localStorage.getItem('cbm-edge-motion-v1')).toBe('off');
+ await act(async () => container.querySelector<HTMLInputElement>('input')!.click());
+ expect(state('first')).toBe('true'); expect(state('second')).toBe('true');
+ });
+ it('sleeps when hidden or reduced-motion is requested and resumes without changing the preference', async () => {
+ await render();
+ await act(async () => { hidden.mockReturnValue(true); document.dispatchEvent(new Event('visibilitychange')); });
+ expect(state('first')).toBe('false');
+ await act(async () => { hidden.mockReturnValue(false); document.dispatchEvent(new Event('visibilitychange')); reduced = true; mediaListeners.forEach(listener => listener()); });
+ expect(state('first')).toBe('false'); expect(container.querySelector('input')!.disabled).toBe(true);
+ expect(localStorage.getItem('cbm-edge-motion-v1')).toBe('on');
+ await act(async () => { reduced = false; mediaListeners.forEach(listener => listener()); });
+ expect(state('first')).toBe('true'); expect(state('inactive')).toBe('false');
+ });
+ it('retains a working session toggle when persistent storage rejects writes', async () => {
+ await render();
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => { throw new Error('Storage disabled'); });
+ await act(async () => container.querySelector<HTMLInputElement>('input')!.click());
+ expect(state('first')).toBe('false'); expect(state('second')).toBe('false');
+ });
+});
diff --git a/graph-ui/src/graph/edge-motion.ts b/graph-ui/src/graph/edge-motion.ts
new file mode 100644
index 000000000..e0c635da2
--- /dev/null
+++ b/graph-ui/src/graph/edge-motion.ts
@@ -0,0 +1,41 @@
+import { useSyncExternalStore } from 'react';
+
+const KEY = 'cbm-edge-motion-v1';
+const CHANGE = 'cbm-edge-motion-change';
+let fallback = true;
+let sessionPreference: boolean | undefined;
+export function edgeMotionPreference(): boolean {
+ if (sessionPreference !== undefined) return sessionPreference;
+ try { const value = window.localStorage.getItem(KEY); return value === null ? fallback : value !== 'off'; } catch { return fallback; }
+}
+export function setEdgeMotionPreference(enabled: boolean): void {
+ fallback = enabled;
+ try { window.localStorage.setItem(KEY, enabled ? 'on' : 'off'); sessionPreference = undefined; } catch { sessionPreference = enabled; }
+ window.dispatchEvent(new Event(CHANGE));
+}
+const reducedMotion = () => typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+const subscribers = new Set<() => void>();
+let detach: (() => void) | undefined;
+function subscribe(notify: () => void): () => void {
+ if (!subscribers.size) {
+ const broadcast = () => subscribers.forEach(listener => listener());
+ const query = typeof window.matchMedia === 'function' ? window.matchMedia('(prefers-reduced-motion: reduce)') : undefined;
+ window.addEventListener(CHANGE, broadcast); window.addEventListener('storage', broadcast);
+ document.addEventListener('visibilitychange', broadcast); query?.addEventListener('change', broadcast);
+ detach = () => {
+ window.removeEventListener(CHANGE, broadcast); window.removeEventListener('storage', broadcast);
+ document.removeEventListener('visibilitychange', broadcast); query?.removeEventListener('change', broadcast);
+ };
+ }
+ subscribers.add(notify);
+ return () => { subscribers.delete(notify); if (!subscribers.size) { detach?.(); detach = undefined; } };
+}
+const motionSnapshot = () => edgeMotionPreference() && !reducedMotion() && !document.hidden;
+export function useEdgeMotion(active = true): boolean {
+ return useSyncExternalStore(subscribe, motionSnapshot, () => false) && active;
+}
+export function useEdgeMotionPreference(): { enabled: boolean; reduced: boolean; setEnabled: typeof setEdgeMotionPreference } {
+ const enabled = useSyncExternalStore(subscribe, edgeMotionPreference, () => false);
+ const reduced = useSyncExternalStore(subscribe, reducedMotion, () => true);
+ return { enabled, reduced, setEnabled: setEdgeMotionPreference };
+}
diff --git a/graph-ui/src/graph/edge-pulse-geometry.test.ts b/graph-ui/src/graph/edge-pulse-geometry.test.ts
new file mode 100644
index 000000000..90b8d69aa
--- /dev/null
+++ b/graph-ui/src/graph/edge-pulse-geometry.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { edgePulseGeometry, type EdgePulsePath } from './EdgePulseLayer';
+
+const path = (id: string, type = 'CALLS'): EdgePulsePath => ({ id, type, points: [{ x: 4, y: 0, z: 0 }, { x: 3, y: 0, z: 0 }, { x: 3, y: 0, z: -3 }] });
+describe('batched direction pulse geometry', () => {
+ it('measures progress along source-to-target distance even when coordinates decrease', () => {
+ const geometry = edgePulseGeometry([path('a')]);
+ const positions = geometry.getAttribute('position'), flow = geometry.getAttribute('edgeFlow');
+ expect(positions.count).toBe(4);
+ expect([flow.getX(0), flow.getX(1), flow.getX(2), flow.getX(3)]).toEqual([0, .25, .25, 1]);
+ expect([positions.getX(0), positions.getZ(3)]).toEqual([4, -3]);
+ expect(flow.getY(0)).toBe(flow.getY(3));
+ geometry.dispose();
+ });
+ it('keeps separate curves disconnected in one batch and preserves focus intensity', () => {
+ const geometry = edgePulseGeometry([path('a'), { ...path('b'), opacity: .08 }]);
+ const flow = geometry.getAttribute('edgeFlow');
+ expect(flow.count).toBe(8);
+ expect(flow.getX(3)).toBe(1); expect(flow.getX(4)).toBe(0);
+ expect(flow.getY(0)).not.toBe(flow.getY(4));
+ expect(flow.getZ(4)).toBeCloseTo(.08);
+ geometry.dispose();
+ });
+ it('omits symmetric, unknown, invisible and invalid paths without fabricating a direction', () => {
+ const geometry = edgePulseGeometry([path('s', 'SIMILAR_TO'), path('u', 'NEW_TYPE'), { ...path('hidden'), opacity: 0 },
+ { ...path('zero'), points: [{ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }] },
+ { ...path('bad'), points: [{ x: NaN, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }] },
+ { ...path('mixed', 'RELATIONSHIPS'), types: ['CALLS', 'IMPORTS'] }]);
+ expect(geometry.getAttribute('position').count).toBe(4);
+ expect([...geometry.getAttribute('position').array].every(Number.isFinite)).toBe(true);
+ geometry.dispose();
+ });
+});
diff --git a/graph-ui/src/graph/edge-style.css b/graph-ui/src/graph/edge-style.css
new file mode 100644
index 000000000..cbaf8dfcd
--- /dev/null
+++ b/graph-ui/src/graph/edge-style.css
@@ -0,0 +1,10 @@
+.graph-edge-controls { position: relative; font-size: 11px; color: var(--atlas-dim, #98aaa3); }
+.graph-edge-controls > summary { list-style: none; cursor: pointer; padding: 7px 10px; border: 1px solid var(--atlas-line, #294139); border-radius: 6px; white-space: nowrap; }
+.graph-edge-controls > summary::-webkit-details-marker { display: none; }
+.graph-edge-settings { position: absolute; z-index: 100; top: calc(100% + 6px); right: 0; width: 260px; padding: 14px; white-space: normal; border: 1px solid var(--atlas-line, #294139); border-radius: 10px; background: var(--atlas-panel, #101917); box-shadow: 0 10px 30px #0005; }
+.graph-edge-settings label { display: flex; align-items: center; gap: 8px; color: var(--atlas-fg, #d1dcd6); font-size: 12px; }
+.graph-edge-settings input { accent-color: #91aaa7; }
+.graph-edge-settings p { margin: 8px 0 12px; font-size: 11px; line-height: 1.5; }
+.graph-edge-key { display: grid; grid-template-columns: 1fr 1fr; gap: 9px; margin: 0; padding: 0; list-style: none; }
+.graph-edge-key li { display: flex; align-items: center; gap: 6px; }
+.graph-edge-key i { width: 15px; height: 2px; display: inline-block; }
diff --git a/graph-ui/src/graph/edge-style.test.ts b/graph-ui/src/graph/edge-style.test.ts
new file mode 100644
index 000000000..5d7eca169
--- /dev/null
+++ b/graph-ui/src/graph/edge-style.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { DEFAULT_EDGE_COLOR, EDGE_TYPE_COLORS, edgeColor, edgePhase, isDirectedEdge } from './edge-style';
+
+describe('shared edge appearance', () => {
+ it('keeps equivalent type spelling and mixed aggregates honest', () => {
+ expect(edgeColor('calls')).toBe(EDGE_TYPE_COLORS.CALLS);
+ expect(edgeColor('http-calls')).toBe(EDGE_TYPE_COLORS.HTTP_CALLS);
+ expect(edgeColor('RELATIONSHIPS', ['CALLS', 'CALLS'])).toBe(edgeColor('CALLS'));
+ expect(edgeColor('RELATIONSHIPS', ['CALLS', 'IMPORTS'])).toBe(DEFAULT_EDGE_COLOR);
+ expect(edgeColor('future_relation')).toBe(DEFAULT_EDGE_COLOR);
+ expect(edgeColor(undefined as unknown as string)).toBe(DEFAULT_EDGE_COLOR);
+ expect(isDirectedEdge(undefined as unknown as string)).toBe(false);
+ });
+ it('animates only known directed relationships, including directed mixed aggregates', () => {
+ for (const type of ['CALLS', 'IMPORTS', 'DATA_FLOWS', 'INHERITS', 'CONTAINS_FILE', 'CONTAINS_FOLDER', 'CALL_REFERENCE', 'READS', 'WRITES', 'THROWS', 'TESTS']) expect(isDirectedEdge(type)).toBe(true);
+ for (const type of ['SIMILAR_TO', 'SEMANTICALLY_RELATED', 'FILE_CHANGES_WITH', 'RELATIONSHIPS', 'future_relation', '']) expect(isDirectedEdge(type)).toBe(false);
+ expect(isDirectedEdge('RELATIONSHIPS', ['CALLS', 'IMPORTS'])).toBe(true);
+ expect(isDirectedEdge('RELATIONSHIPS', ['CALLS', 'SIMILAR_TO'])).toBe(false);
+ expect(isDirectedEdge('RELATIONSHIPS', ['CALLS', 'future_relation'])).toBe(false);
+ });
+ it('uses stable, bounded phases independent of render order', () => {
+ const ids = Array.from({ length: 40 }, (_, index) => `source:${index}:target`);
+ const phases = new Map(ids.map(id => [id, edgePhase(id)]));
+ for (const id of [...ids].reverse()) { expect(edgePhase(id)).toBe(phases.get(id)); expect(edgePhase(id)).toBeGreaterThanOrEqual(0); expect(edgePhase(id)).toBeLessThan(1); }
+ expect(new Set(phases.values()).size).toBe(ids.length);
+ });
+});
diff --git a/graph-ui/src/graph/edge-style.ts b/graph-ui/src/graph/edge-style.ts
new file mode 100644
index 000000000..963a9c980
--- /dev/null
+++ b/graph-ui/src/graph/edge-style.ts
@@ -0,0 +1,40 @@
+/** Distinct relationship hues. Keep edges subdued with opacity, not gray hues. */
+export const DEFAULT_EDGE_COLOR = '#84939d';
+export const EDGE_TYPE_COLORS: Record<string, string> = {
+ CALLS: '#579fc7', IMPORTS: '#ad7acf', USAGE: '#72b877', DATA_FLOWS: '#49b8b0',
+ HTTP_CALLS: '#d58c60', ASYNC_CALLS: '#cb7fa9', GRPC_CALLS: '#b9ad58', GRAPHQL_CALLS: '#bd72ca', TRPC_CALLS: '#898cda',
+ CROSS_HTTP_CALLS: '#cda078', CROSS_ASYNC_CALLS: '#b96597', CROSS_GRPC_CALLS: '#a49649', CROSS_GRAPHQL_CALLS: '#a86bb7', CROSS_TRPC_CALLS: '#777fc0', CROSS_CHANNEL: '#c28676',
+ INHERITS: '#8294d7', IMPLEMENTS: '#c5b66a', OVERRIDE: '#bc7db8',
+ DEFINES: '#c6a05c', DEFINES_METHOD: '#dfb87a',
+ CONTAINS: '#719f89', CONTAINS_FILE: '#92ad71', CONTAINS_FOLDER: '#57a88c', CONTAINS_PACKAGE: '#abad65',
+ MEMBER_OF: '#649daa', HAS_BRANCH: '#9a79ae', HANDLES: '#aebb61',
+ CONFIGURES: '#bda644', RAISES: '#d26b72', THROWS: '#ba606e', CALL_REFERENCE: '#67c1cf', RETURNS: '#a1bd80',
+ SERVICE_CALLS: '#7da4ba', STARTUP_DEPENDENCY: '#8a8199',
+ READS: '#70b59f', WRITES: '#cc9862', TESTS: '#65a8bb', TESTS_FILE: '#83b9c5',
+ SIMILAR_TO: '#cb88b5', SEMANTICALLY_RELATED: '#b58ebf', FILE_CHANGES_WITH: '#b19b81',
+ RELATIONSHIPS: DEFAULT_EDGE_COLOR,
+};
+const symmetric = new Set(['SIMILAR_TO', 'SEMANTICALLY_RELATED', 'FILE_CHANGES_WITH']);
+export const normalizeEdgeType = (type: unknown) => typeof type === 'string' ? type.trim().replaceAll('-', '_').toUpperCase() : '';
+function constituents(type: string, types?: readonly string[]): string[] {
+ return [...new Set((types?.length ? types : [type]).map(normalizeEdgeType))];
+}
+export function edgeColor(type: string, types?: readonly string[]): string {
+ if (!types?.length) return EDGE_TYPE_COLORS[normalizeEdgeType(type)] ?? DEFAULT_EDGE_COLOR;
+ const kinds = constituents(type, types);
+ return kinds.length === 1 ? EDGE_TYPE_COLORS[kinds[0]] ?? DEFAULT_EDGE_COLOR : DEFAULT_EDGE_COLOR;
+}
+/** Direction is a relationship property, never evidence of observed execution. */
+export function isDirectedEdge(type: string, types?: readonly string[]): boolean {
+ if (!types?.length) {
+ const kind = normalizeEdgeType(type);
+ return Object.hasOwn(EDGE_TYPE_COLORS, kind) && kind !== 'RELATIONSHIPS' && !symmetric.has(kind);
+ }
+ return constituents(type, types).every(kind => Object.hasOwn(EDGE_TYPE_COLORS, kind) && kind !== 'RELATIONSHIPS' && !symmetric.has(kind));
+}
+/** Offset each edge deterministically so the graph does not flash in unison. */
+export function edgePhase(id: string | number): number {
+ let hash = 2166136261;
+ for (const character of String(id)) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0;
+ return hash / 4294967296;
+}
diff --git a/graph-ui/src/graph/useGraphBackgroundReset.test.tsx b/graph-ui/src/graph/useGraphBackgroundReset.test.tsx
new file mode 100644
index 000000000..945df104a
--- /dev/null
+++ b/graph-ui/src/graph/useGraphBackgroundReset.test.tsx
@@ -0,0 +1,51 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useGraphBackgroundReset } from './useGraphBackgroundReset';
+
+let host: HTMLDivElement, root: Root;
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); });
+function Fixture({ reset }: { reset: () => void }) {
+ const { onPointerMissed, ...capture } = useGraphBackgroundReset(reset);
+ return <div {...capture}><canvas onClick={event => onPointerMissed(event.nativeEvent)} />
+ <button onClick={event => onPointerMissed(event.nativeEvent)}>Node label</button></div>;
+}
+async function setup() {
+ const reset = vi.fn(); await act(async () => root.render(<Fixture reset={reset} />));
+ return { reset, canvas: host.querySelector('canvas')!, label: host.querySelector('button')! };
+}
+function pointer(target: Element, type: string, x = 10, y = 10, changes: { button?: number; pointerId?: number; isPrimary?: boolean } = {}) {
+ const event = new MouseEvent(type, { bubbles: true, clientX: x, clientY: y, button: changes.button ?? 0 });
+ Object.defineProperties(event, { pointerId: { value: changes.pointerId ?? 1 }, isPrimary: { value: changes.isPrimary ?? true } });
+ target.dispatchEvent(event);
+}
+it('resets only after a primary click on genuinely empty canvas', async () => {
+ const { reset, canvas } = await setup();
+ pointer(canvas, 'pointerdown'); pointer(canvas, 'pointerup'); pointer(canvas, 'click');
+ expect(reset).toHaveBeenCalledOnce();
+ pointer(canvas, 'click'); expect(reset).toHaveBeenCalledOnce();
+});
+it('does not reset orbit/pan drags, including drags that return to their starting point', async () => {
+ const { reset, canvas } = await setup();
+ pointer(canvas, 'pointerdown'); pointer(canvas, 'pointermove', 50); pointer(canvas, 'pointermove');
+ pointer(canvas, 'pointerup'); pointer(canvas, 'click'); expect(reset).not.toHaveBeenCalled();
+ pointer(canvas, 'pointerdown', 10, 10, { button: 2 }); pointer(canvas, 'click', 10, 10, { button: 2 });
+ expect(reset).not.toHaveBeenCalled();
+});
+it('does not treat labels or controls as empty canvas', async () => {
+ const { reset, canvas, label } = await setup();
+ pointer(label, 'pointerdown'); pointer(label, 'click');
+ pointer(canvas, 'pointerdown'); pointer(label, 'click');
+ expect(reset).not.toHaveBeenCalled();
+});
+it('ignores canceled and multitouch gestures', async () => {
+ const { reset, canvas } = await setup();
+ pointer(canvas, 'pointerdown'); pointer(canvas, 'pointercancel'); pointer(canvas, 'click');
+ pointer(canvas, 'pointerdown'); pointer(canvas, 'pointerdown', 20, 20, { pointerId: 2, isPrimary: false }); pointer(canvas, 'click');
+ expect(reset).not.toHaveBeenCalled();
+});
diff --git a/graph-ui/src/graph/useGraphBackgroundReset.ts b/graph-ui/src/graph/useGraphBackgroundReset.ts
new file mode 100644
index 000000000..fab91a179
--- /dev/null
+++ b/graph-ui/src/graph/useGraphBackgroundReset.ts
@@ -0,0 +1,27 @@
+import { useRef, type PointerEvent as ReactPointerEvent } from 'react';
+
+/** A missed raycast is a reset only after a primary, stationary canvas gesture.
+ * Tracking the entire gesture also excludes drags that return to their start. */
+export function useGraphBackgroundReset(onReset?: () => void) {
+ const gesture = useRef<{ id: number; x: number; y: number; moved: boolean } | undefined>(undefined);
+ const onPointerDownCapture = (event: ReactPointerEvent) => {
+ if (event.button !== 0 || event.isPrimary === false || !(event.target instanceof HTMLCanvasElement)) {
+ gesture.current = undefined;
+ return;
+ }
+ gesture.current = { id: event.pointerId, x: event.clientX, y: event.clientY, moved: false };
+ };
+ const onPointerMoveCapture = (event: ReactPointerEvent) => {
+ const start = gesture.current;
+ if (start && (event.pointerId !== start.id || Math.hypot(event.clientX - start.x, event.clientY - start.y) > 4)) start.moved = true;
+ };
+ const onPointerCancelCapture = () => { gesture.current = undefined; };
+ const onPointerMissed = (event: MouseEvent) => {
+ const start = gesture.current;
+ gesture.current = undefined;
+ if (event.type !== 'click' || event.button !== 0 || !(event.target instanceof HTMLCanvasElement)
+ || !start || start.moved || Math.hypot(event.clientX - start.x, event.clientY - start.y) > 4) return;
+ onReset?.();
+ };
+ return { onPointerDownCapture, onPointerMoveCapture, onPointerCancelCapture, onPointerMissed };
+}
diff --git a/graph-ui/src/styles/workspace.css b/graph-ui/src/styles/workspace.css
index 3e0bee49b..8981e349b 100644
--- a/graph-ui/src/styles/workspace.css
+++ b/graph-ui/src/styles/workspace.css
@@ -236,3 +236,14 @@
.atlas-header .atlas-project-switcher { flex-basis: 180px; min-width: 130px; }
@media (min-width: 1280px) { .atlas-header .atlas-workspace-tabs { margin-left: 6px; }.atlas-header .atlas-project-switcher-label { display: none; } }
@media (max-width: 1100px) { .atlas-header:has(.atlas-project-switcher) .atlas-version { display: none; }.atlas-header .atlas-workspace-tabs button { padding-inline: 8px; } }
+
+/* Explorer keeps chat and graph in one column, with a proportional split. */
+.atlas-chat-column[data-graph=true][data-selection-inspector=false] { display: grid; overflow: hidden; grid-template-rows: minmax(0, var(--atlas-chat-fraction)) 8px minmax(0, var(--atlas-graph-fraction)); }
+.atlas-chat-column[data-graph=true][data-selection-inspector=false][data-chat-expanded=false] { grid-template-rows: auto minmax(0, 1fr); }
+.atlas-chat-column[data-graph=true][data-selection-inspector=false] > .cbm-chat-dock { min-height: 0; height: 100%; flex: initial; overflow: auto; }
+.atlas-chat-column[data-graph=true][data-selection-inspector=false][data-chat-expanded=false] > .cbm-chat-dock { height: auto; }
+.atlas-shell[data-workspace=explore] .atlas-chat-column[data-graph=true][data-selection-inspector=false] > .atlas-galaxy-host { min-height: 0; height: 100%; flex: initial; }
+.atlas-reader-details { flex: 0 1 auto; max-height: 42%; min-height: 0; overflow: auto; border-bottom: 1px solid var(--atlas-line); }
+.atlas-command-palette > .atlas-menu { padding: 12px 18px; margin: 0; border-top: 1px solid var(--atlas-line); }
+.diagnostics-inventory { margin: 18px 0; }
+.diagnostics-inventory > summary { cursor: pointer; color: var(--atlas-cyan); }
diff --git a/graph-ui/src/system/SystemWorkspace.tsx b/graph-ui/src/system/SystemWorkspace.tsx
index c9bd1b176..a5cd72139 100644
--- a/graph-ui/src/system/SystemWorkspace.tsx
+++ b/graph-ui/src/system/SystemWorkspace.tsx
@@ -89,7 +89,7 @@ export default function SystemWorkspace({ api, onOpenProjects, active = true, ve
return <section className="system-workspace" aria-label="System" hidden={!active} data-testid="system-workspace">
<header className="system-heading">
- <div><p className="system-eyebrow">DAEMON</p><h1>System</h1><p>Processes, indexes, and the serving daemon log.</p></div>
+ <div><p className="system-eyebrow">DAEMON</p><h1>System</h1><p>Processes, indexes, and frontend, API, and daemon events.</p></div>
<div className="system-heading-actions">
{version && <span className="system-version">{version}</span>}
<button type="button" onClick={() => selectedReading.refresh()} disabled={selectedReading.loading}>Refresh</button>
@@ -135,7 +135,7 @@ export default function SystemWorkspace({ api, onOpenProjects, active = true, ve
<div id="system-panel-logs" role="tabpanel" aria-labelledby="system-tab-logs" hidden={tab !== 'logs'}>
<section className="system-section">
- <div className="system-section-heading"><div><h2>Daemon log</h2><p>{report && report.selfPid > 0 ? `Serving process ${report.selfPid}` : 'Serving daemon'} · Latest 200 matching events</p></div><button type="button" disabled={(visibleRecords?.length ?? visibleLines.length) === 0} onClick={() => { void copyLogs(); }}>Copy visible</button></div>
+ <div className="system-section-heading"><div><h2>Errors and logs</h2><p>{report && report.selfPid > 0 ? `Serving process ${report.selfPid}` : 'Serving daemon'} · Latest 200 matching events</p></div><button type="button" disabled={(visibleRecords?.length ?? visibleLines.length) === 0} onClick={() => { void copyLogs(); }}>Copy visible</button></div>
{logs.data && <p className="system-muted">{logs.data.persistent === true ? `SQLite history · ${logs.data.retentionLimit ?? 'bounded'} event retention limit · survives daemon restarts` : 'Persistent history unavailable; this tail may not survive a restart.'} Events identify affected paths or jobs only when the daemon recorded them.</p>}
<div className="system-log-controls">
<label><span>Scope</span><select aria-label="Log scope" value={scope} onChange={(event) => setScope(event.currentTarget.value as typeof scope)}>
diff --git a/src/mcp/architecture_jobs.c b/src/mcp/architecture_jobs.c
new file mode 100644
index 000000000..5859ae8c1
--- /dev/null
+++ b/src/mcp/architecture_jobs.c
@@ -0,0 +1,309 @@
+#include "mcp/architecture_jobs.h"
+#include "store/architecture_projection.h"
+#include "foundation/compat_fs.h"
+#include "foundation/compat_thread.h"
+#include "foundation/platform.h"
+#include <sqlite3.h>
+#include <yyjson/yyjson.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+enum {
+ ARCH_CACHE_ENTRIES = 4,
+ ARCH_RESULT_BYTES = 8 * 1024 * 1024,
+ ARCH_DEADLINE_MS = 5000,
+ ARCH_RETRY_MS = 500,
+ ARCH_FAILED_CACHE_MS = 5000,
+ ARCH_GENERATION_BYTES = 512,
+ ARCH_STAMP_BYTES = 160,
+};
+
+typedef struct {
+ char *path;
+ char *project;
+ char *indexed_at;
+ char generation[ARCH_GENERATION_BYTES];
+ char db_generation[64];
+ char stamp[ARCH_STAMP_BYTES];
+ int64_t entry_node_id;
+ int64_t target_node_id;
+ bool include_behavior_evidence;
+ char *result;
+ const char *error;
+ uint64_t touched_ms;
+} arch_job_t;
+
+struct cbm_architecture_jobs {
+ cbm_mutex_t mutex;
+ cbm_thread_t thread;
+ atomic_bool cancelled;
+ bool started;
+ bool done;
+ arch_job_t active;
+ arch_job_t cache[ARCH_CACHE_ENTRIES];
+};
+
+static char *copy_string(const char *text) {
+ size_t size = strlen(text) + 1;
+ char *copy = malloc(size);
+ if (copy) {
+ memcpy(copy, text, size);
+ }
+ return copy;
+}
+
+static void clear_job(arch_job_t *job) {
+ free(job->path);
+ free(job->project);
+ free(job->indexed_at);
+ free(job->result);
+ memset(job, 0, sizeof(*job));
+}
+
+/* Include WAL metadata: indexed_at alone has second resolution and does not
+ * identify commits made by every writer. Never hash or scan the database on
+ * the HTTP thread. Unavailable metadata invalidates rather than reuses. */
+static bool file_stamp(const char *path, char *out, size_t size) {
+ cbm_path_info_t db = {0}, wal = {0};
+ char sidecar[4096];
+ int n = snprintf(sidecar, sizeof(sidecar), "%s-wal", path);
+ if (n < 0 || (size_t)n >= sizeof(sidecar) ||
+ cbm_path_info_utf8(path, &db) != CBM_PATH_INFO_OK || !db.is_regular) {
+ return false;
+ }
+ int wal_rc = cbm_path_info_utf8(sidecar, &wal);
+ if (wal_rc != CBM_PATH_INFO_OK && wal_rc != CBM_PATH_INFO_ABSENT) {
+ return false;
+ }
+ snprintf(out, size, "%" PRId64 ":%" PRId64 ":%d:%" PRId64 ":%" PRId64, db.size, db.mtime_ns,
+ wal_rc, wal.size, wal.mtime_ns);
+ return true;
+}
+
+static int64_t data_version(sqlite3 *db) {
+ sqlite3_stmt *stmt = NULL;
+ int64_t version = -1;
+ if (sqlite3_prepare_v2(db, "PRAGMA data_version", -1, &stmt, NULL) == SQLITE_OK &&
+ sqlite3_step(stmt) == SQLITE_ROW) {
+ version = sqlite3_column_int64(stmt, 0);
+ }
+ sqlite3_finalize(stmt);
+ return version;
+}
+
+static bool is_cancelled(void *context) {
+ cbm_architecture_jobs_t *jobs = context;
+ return atomic_load(&jobs->cancelled);
+}
+
+static void *run_projection(void *context) {
+ cbm_architecture_jobs_t *jobs = context;
+ arch_job_t *job = &jobs->active;
+ char before[ARCH_STAMP_BYTES] = {0};
+ char *result = NULL;
+ const char *error = NULL;
+ cbm_store_t *store = NULL;
+ uint64_t deadline = cbm_now_ms() + ARCH_DEADLINE_MS;
+ if (!file_stamp(job->path, before, sizeof(before)) || strcmp(before, job->stamp) != 0) {
+ error = "The index changed before analysis. Request the current generation.";
+ } else {
+ store = cbm_store_open_path_query(job->path);
+ if (!store) {
+ error = "Could not open a read-only index snapshot.";
+ }
+ }
+ if (store) {
+ sqlite3 *db = cbm_store_get_db(store);
+ sqlite3_busy_timeout(db, 100);
+ cbm_project_t project = {0};
+ char db_generation[64] = {0};
+ if (sqlite3_exec(db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK ||
+ cbm_store_generation(store, db_generation, sizeof(db_generation)) != CBM_STORE_OK ||
+ strcmp(db_generation, job->db_generation) != 0 ||
+ cbm_store_get_project(store, job->project, &project) != CBM_STORE_OK ||
+ strcmp(project.indexed_at ? project.indexed_at : "", job->indexed_at) != 0) {
+ error = "The project generation is no longer available.";
+ } else {
+ cbm_architecture_projection_options_t options = {0};
+ options.entry_node_id = job->entry_node_id;
+ options.target_node_id = job->target_node_id;
+ options.include_behavior_evidence = job->include_behavior_evidence;
+ options.deadline_ms = deadline;
+ options.cancel = is_cancelled;
+ options.cancel_context = jobs;
+ int rc = cbm_store_architecture_projection(store, job->project, &options, &result);
+ if (rc != CBM_STORE_OK || !result) {
+ error = "Architecture analysis was interrupted or could not read the index.";
+ } else if (strlen(result) > ARCH_RESULT_BYTES) {
+ error = "Architecture output exceeded the response budget.";
+ }
+ }
+ cbm_project_free_fields(&project);
+ sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
+ cbm_store_close(store);
+ char after[ARCH_STAMP_BYTES] = {0};
+ if (!file_stamp(job->path, after, sizeof(after)) || strcmp(before, after) != 0) {
+ error = "The index changed during analysis. Request the current generation.";
+ }
+ }
+ if (error) {
+ free(result);
+ result = NULL;
+ }
+ cbm_mutex_lock(&jobs->mutex);
+ job->result = result;
+ job->error = error;
+ job->touched_ms = cbm_now_ms();
+ jobs->done = true;
+ cbm_mutex_unlock(&jobs->mutex);
+ return NULL;
+}
+
+cbm_architecture_jobs_t *cbm_architecture_jobs_new(void) {
+ cbm_architecture_jobs_t *jobs = calloc(1, sizeof(*jobs));
+ if (jobs) {
+ cbm_mutex_init(&jobs->mutex);
+ atomic_init(&jobs->cancelled, false);
+ }
+ return jobs;
+}
+
+void cbm_architecture_jobs_free(cbm_architecture_jobs_t *jobs) {
+ if (!jobs) {
+ return;
+ }
+ atomic_store(&jobs->cancelled, true);
+ if (jobs->started) {
+ cbm_thread_join(&jobs->thread);
+ }
+ clear_job(&jobs->active);
+ for (int i = 0; i < ARCH_CACHE_ENTRIES; i++) {
+ clear_job(&jobs->cache[i]);
+ }
+ cbm_mutex_destroy(&jobs->mutex);
+ free(jobs);
+}
+
+static char *envelope(const char *status, const char *generation, const char *result,
+ const char *error) {
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
+ if (!doc) {
+ return NULL;
+ }
+ yyjson_mut_val *root = yyjson_mut_obj(doc);
+ yyjson_mut_doc_set_root(doc, root);
+ yyjson_mut_obj_add_str(doc, root, "status", status);
+ yyjson_mut_obj_add_str(doc, root, "generation", generation ? generation : "");
+ if (strcmp(status, "pending") == 0) {
+ yyjson_mut_obj_add_int(doc, root, "retry_after_ms", ARCH_RETRY_MS);
+ }
+ if (error) {
+ yyjson_mut_obj_add_str(doc, root, "error", error);
+ }
+ yyjson_doc *payload = result ? yyjson_read(result, strlen(result), 0) : NULL;
+ if (payload) {
+ yyjson_mut_obj_add_val(doc, root, "result",
+ yyjson_val_mut_copy(doc, yyjson_doc_get_root(payload)));
+ }
+ char *json = yyjson_mut_write(doc, 0, NULL);
+ yyjson_doc_free(payload);
+ yyjson_mut_doc_free(doc);
+ return json;
+}
+
+char *cbm_architecture_jobs_request(cbm_architecture_jobs_t *jobs, cbm_store_t *store,
+ const char *project, int64_t entry_node_id) {
+ return cbm_architecture_jobs_request_query(jobs, store, project, entry_node_id, 0, NULL, false);
+}
+
+char *cbm_architecture_jobs_request_query(cbm_architecture_jobs_t *jobs, cbm_store_t *store,
+ const char *project, int64_t entry_node_id,
+ int64_t target_node_id, const char *expected_generation,
+ bool include_behavior_evidence) {
+ if (!jobs || !store || !project || entry_node_id < 0 || target_node_id < 0 ||
+ (target_node_id && !entry_node_id)) {
+ return envelope("failed", "", NULL, "Invalid architecture request.");
+ }
+ const char *path = cbm_store_db_path(store);
+ char stamp[ARCH_STAMP_BYTES], generation[ARCH_GENERATION_BYTES], db_generation[64];
+ if (!path || !file_stamp(path, stamp, sizeof(stamp))) {
+ return envelope("failed", "", NULL, "Architecture analysis needs a persisted index.");
+ }
+ cbm_project_t metadata = {0};
+ if (cbm_store_get_project(store, project, &metadata) != CBM_STORE_OK) {
+ return envelope("failed", "", NULL, "Project not found in this index.");
+ }
+ sqlite3 *db = cbm_store_get_db(store);
+ int64_t version = data_version(db);
+ if (version < 0 ||
+ cbm_store_generation(store, db_generation, sizeof(db_generation)) != CBM_STORE_OK) {
+ cbm_project_free_fields(&metadata);
+ return envelope("failed", "", NULL, "Could not identify the index generation.");
+ }
+ snprintf(generation, sizeof(generation), "%s:%s:%" PRId64 ":%d", db_generation, stamp, version,
+ sqlite3_total_changes(db));
+ if (expected_generation && strcmp(expected_generation, generation) != 0) {
+ cbm_project_free_fields(&metadata);
+ return envelope("failed", generation, NULL,
+ "The selected graph generation changed. Reload the overview.");
+ }
+ cbm_mutex_lock(&jobs->mutex);
+ if (jobs->started && jobs->done) {
+ cbm_thread_join(&jobs->thread);
+ jobs->started = false;
+ int oldest = 0;
+ for (int i = 1; i < ARCH_CACHE_ENTRIES; i++) {
+ if (jobs->cache[i].touched_ms < jobs->cache[oldest].touched_ms) {
+ oldest = i;
+ }
+ }
+ clear_job(&jobs->cache[oldest]);
+ jobs->cache[oldest] = jobs->active;
+ memset(&jobs->active, 0, sizeof(jobs->active));
+ }
+ for (int i = 0; i < ARCH_CACHE_ENTRIES; i++) {
+ arch_job_t *cached = &jobs->cache[i];
+ if (cached->project && strcmp(cached->project, project) == 0 &&
+ strcmp(cached->path, path) == 0 && strcmp(cached->generation, generation) == 0 &&
+ cached->entry_node_id == entry_node_id && cached->target_node_id == target_node_id &&
+ cached->include_behavior_evidence == include_behavior_evidence &&
+ (!cached->error || cbm_now_ms() - cached->touched_ms < ARCH_FAILED_CACHE_MS)) {
+ char *reply = envelope(cached->error ? "failed" : "ready", generation, cached->result,
+ cached->error);
+ if (!cached->error) {
+ cached->touched_ms = cbm_now_ms();
+ }
+ cbm_mutex_unlock(&jobs->mutex);
+ cbm_project_free_fields(&metadata);
+ return reply;
+ }
+ }
+ const char *error = NULL;
+ if (!jobs->started) {
+ arch_job_t *job = &jobs->active;
+ job->path = copy_string(path);
+ job->project = copy_string(project);
+ job->indexed_at = copy_string(metadata.indexed_at ? metadata.indexed_at : "");
+ job->entry_node_id = entry_node_id;
+ job->target_node_id = target_node_id;
+ job->include_behavior_evidence = include_behavior_evidence;
+ snprintf(job->generation, sizeof(job->generation), "%s", generation);
+ snprintf(job->db_generation, sizeof(job->db_generation), "%s", db_generation);
+ snprintf(job->stamp, sizeof(job->stamp), "%s", stamp);
+ jobs->done = false;
+ if (!job->path || !job->project || !job->indexed_at ||
+ cbm_thread_create(&jobs->thread, 0, run_projection, jobs) != 0) {
+ clear_job(job);
+ error = "Could not start architecture analysis.";
+ } else {
+ jobs->started = true;
+ }
+ }
+ char *reply = envelope(error ? "failed" : "pending", generation, NULL, error);
+ cbm_mutex_unlock(&jobs->mutex);
+ cbm_project_free_fields(&metadata);
+ return reply;
+}
diff --git a/src/mcp/architecture_jobs.h b/src/mcp/architecture_jobs.h
new file mode 100644
index 000000000..3b0d323ee
--- /dev/null
+++ b/src/mcp/architecture_jobs.h
@@ -0,0 +1,24 @@
+#ifndef CBM_ARCHITECTURE_JOBS_H
+#define CBM_ARCHITECTURE_JOBS_H
+
+#include <stdbool.h>
+#include <stdint.h>
+#include "store/store.h"
+
+typedef struct cbm_architecture_jobs cbm_architecture_jobs_t;
+
+/* One worker and a small result cache per server. Requests only enqueue/poll;
+ * the worker owns a separate read-only SQLite connection and snapshot. */
+cbm_architecture_jobs_t *cbm_architecture_jobs_new(void);
+void cbm_architecture_jobs_free(cbm_architecture_jobs_t *jobs);
+
+/* Returns owned JSON: {status, generation, retry_after_ms?, result?, error?}.
+ * The supplied store is inspected only on the calling thread. */
+char *cbm_architecture_jobs_request(cbm_architecture_jobs_t *jobs, cbm_store_t *store,
+ const char *project, int64_t entry_node_id);
+char *cbm_architecture_jobs_request_query(cbm_architecture_jobs_t *jobs, cbm_store_t *store,
+ const char *project, int64_t entry_node_id,
+ int64_t target_node_id, const char *expected_generation,
+ bool include_behavior_evidence);
+
+#endif
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index 9cd96d2ce..d339e0abc 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -53,6 +53,7 @@ enum {
#define SLEN(s) (sizeof(s) - 1)
#include "mcp/mcp.h"
#include "mcp/mcp_internal.h"
+#include "mcp/architecture_jobs.h"
#include "store/store.h"
#include <sqlite3.h>
#include "cypher/cypher.h"
@@ -614,18 +615,26 @@ static const tool_def_t TOOLS[] = {
"\"additionalProperties\":false}"},
{"get_architecture",
- "Compact counts, languages, packages, entry points. Request structure, dependencies, "
- "routes, hotspots, boundaries, layers, clusters, cycles, or file_tree; path scopes a "
- "directory.",
+ "Bounded static architecture; poll pending jobs. include_behavior_evidence=true adds "
+ "indexed call arguments, parameter declarations and return types; not full dataflow or "
+ "runtime traces.",
/* The aspects enum mirrors VALID_ASPECTS (see aspect_is_valid) — update both together. */
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"path\":{\"type\":"
- "\"string\",\"description\":\"Directory prefix (for example apps/hoa).\"},"
+ "\"string\",\"description\":\"Directory prefix.\"},"
"\"aspects\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"all\","
"\"overview\",\"structure\",\"dependencies\",\"routes\",\"languages\",\"packages\","
"\"entry_points\",\"hotspots\",\"boundaries\",\"layers\",\"file_tree\",\"clusters\","
- "\"cycles\"]},"
- "\"description\":\"all=everything; overview=compact except file_tree; omitted=languages/"
- "packages/entry_points; cycles is opt-in.\"},"
+ "\"cycles\",\"system_structure\"]},"
+ "\"description\":\"Default: languages/packages/entry_points. overview omits file_tree. "
+ "cycles/system_structure opt-in; system_structure alone, no path.\"},"
+ "\"entry_node_id\":{\"type\":\"integer\",\"minimum\":1,"
+ "\"description\":\"Start symbol.\"},"
+ "\"target_node_id\":{\"type\":\"integer\",\"minimum\":1,"
+ "\"description\":\"Requires entry_node_id.\"},"
+ "\"expected_generation\":{\"type\":\"string\",\"minLength\":1,"
+ "\"description\":\"Required generation.\"},"
+ "\"include_behavior_evidence\":{\"type\":\"boolean\",\"default\":false,"
+ "\"description\":\"system_structure only.\"},"
"\"format\":{\"type\":\"string\",\"enum\":[\"tree\",\"json\"],\"default\":\"tree\"}},"
"\"required\":[\"project\"]}"},
@@ -1702,6 +1711,7 @@ struct cbm_mcp_server {
int64_t active_request_id; /* JSON-RPC id of the in-progress tool call */
char *active_request_id_str; /* string JSON-RPC id of the in-progress tool call */
cbm_mcp_tool_profile_t tool_profile;
+ cbm_architecture_jobs_t *architecture_jobs;
};
cbm_mcp_server_t *cbm_mcp_server_new(const char *store_path) {
@@ -1723,6 +1733,7 @@ cbm_mcp_server_t *cbm_mcp_server_new(const char *store_path) {
srv->owns_store = true;
srv->tool_profile = CBM_MCP_TOOL_PROFILE_ALL;
srv->background_tasks = true;
+ srv->architecture_jobs = cbm_architecture_jobs_new();
return srv;
}
@@ -1875,6 +1886,7 @@ void cbm_mcp_server_free(cbm_mcp_server_t *srv) {
if (!srv) {
return;
}
+ cbm_architecture_jobs_free(srv->architecture_jobs);
if (srv->autoindex_active) {
cbm_thread_join(&srv->autoindex_tid);
}
@@ -6821,10 +6833,10 @@ static char *handle_delete_project(cbm_mcp_server_t *srv, const char *args) {
* of truth for the server-side validation (authoritative); the JSON-Schema
* enum in the TOOLS entry above is the advisory client-side mirror — update
* both together when the aspect set changes. */
-static const char *VALID_ASPECTS[] = {"all", "overview", "structure", "dependencies",
- "routes", "languages", "packages", "entry_points",
- "hotspots", "boundaries", "layers", "file_tree",
- "clusters", "cycles", NULL};
+static const char *VALID_ASPECTS[] = {"all", "overview", "structure", "dependencies",
+ "routes", "languages", "packages", "entry_points",
+ "hotspots", "boundaries", "layers", "file_tree",
+ "clusters", "cycles", "system_structure", NULL};
/* ── SCC / cycle condensation (get_architecture "cycles") ─────────
* Iterative Tarjan over the CALLS call graph. Recursion would overflow on a
@@ -7304,9 +7316,19 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {
/* Parse aspects array from args */
yyjson_doc *aspects_doc = NULL;
yyjson_val *aspects_arr = NULL;
+ bool include_behavior_evidence = false;
{
yyjson_doc *args_doc = yyjson_read(args, strlen(args), 0);
if (args_doc) {
+ yyjson_val *evidence =
+ yyjson_obj_get(yyjson_doc_get_root(args_doc), "include_behavior_evidence");
+ if (evidence && !yyjson_is_bool(evidence)) {
+ yyjson_doc_free(args_doc);
+ free(project);
+ free(scope_path);
+ return cbm_mcp_text_result("include_behavior_evidence must be a boolean.", true);
+ }
+ include_behavior_evidence = yyjson_get_bool(evidence);
yyjson_val *aval = yyjson_obj_get(yyjson_doc_get_root(args_doc), "aspects");
if (yyjson_is_arr(aval)) {
aspects_doc = args_doc; /* keep alive */
@@ -7317,6 +7339,14 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {
}
}
+ if (include_behavior_evidence && !aspect_explicitly_named(aspects_arr, "system_structure")) {
+ yyjson_doc_free(aspects_doc);
+ free(project);
+ free(scope_path);
+ return cbm_mcp_text_result(
+ "include_behavior_evidence=true requires aspects:[\"system_structure\"].", true);
+ }
+
/* Build a C string array from aspects for cbm_store_get_architecture.
* Strings point into aspects_doc memory so aspects_doc must outlive this array. */
const char *aspects_strs[MCP_COL_16];
@@ -7362,6 +7392,41 @@ static char *handle_get_architecture(cbm_mcp_server_t *srv, const char *args) {
}
}
+ if (aspect_explicitly_named(aspects_arr, "system_structure")) {
+ yyjson_val *entry = yyjson_obj_get(yyjson_doc_get_root(aspects_doc), "entry_node_id");
+ yyjson_val *target = yyjson_obj_get(yyjson_doc_get_root(aspects_doc), "target_node_id");
+ yyjson_val *generation =
+ yyjson_obj_get(yyjson_doc_get_root(aspects_doc), "expected_generation");
+ bool valid_entry = !entry || (yyjson_is_int(entry) && yyjson_get_sint(entry) > 0);
+ bool valid_target =
+ !target || (entry && yyjson_is_int(target) && yyjson_get_sint(target) > 0);
+ bool valid_generation =
+ !generation || (yyjson_is_str(generation) && yyjson_get_len(generation) > 0 &&
+ yyjson_get_len(generation) < 512);
+ char *json = NULL;
+ char *reply = NULL;
+ if (yyjson_arr_size(aspects_arr) != 1 || (scope_path && scope_path[0]) || !valid_entry ||
+ !valid_target || !valid_generation) {
+ reply = cbm_mcp_text_result(
+ "Request system_structure alone, without path; entry_node_id must be a positive "
+ "integer when supplied. target_node_id requires entry_node_id; expected_generation "
+ "must be a nonempty generation token.",
+ true);
+ } else {
+ json = cbm_architecture_jobs_request_query(
+ srv->architecture_jobs, store, project, entry ? yyjson_get_sint(entry) : 0,
+ target ? yyjson_get_sint(target) : 0,
+ generation ? yyjson_get_str(generation) : NULL, include_behavior_evidence);
+ reply = cbm_mcp_text_result(json ? json : "Architecture request allocation failed.",
+ json == NULL);
+ }
+ free(json);
+ free(project);
+ free(scope_path);
+ yyjson_doc_free(aspects_doc);
+ return reply;
+ }
+
/* Default (no aspects) = compact summary. The old default rendered ALL
* aspects including the full file_tree — ~94KB (~23K tokens) on a
* mid-size repo, a context bomb for the LLM consumers. Explicit
diff --git a/src/store/architecture_projection.c b/src/store/architecture_projection.c
new file mode 100644
index 000000000..6c8751749
--- /dev/null
+++ b/src/store/architecture_projection.c
@@ -0,0 +1,2045 @@
+/* Bounded architecture projections over a completed graph generation. */
+#include "store/architecture_projection.h"
+#include "foundation/hash_table.h"
+#include "foundation/platform.h"
+#include <sqlite3.h>
+#include <yyjson/yyjson.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+enum {
+ AP_TEXT_BUDGET = 64 * 1024 * 1024,
+ AP_REPRESENTATIVES = 5,
+ AP_ENTRYPOINTS = 128,
+ AP_PASSES = 6,
+ AP_GROUP_ATOMS = 32,
+ AP_JSON_BUDGET = 32 * 1024 * 1024,
+ AP_ARGUMENT_LIMIT = 8,
+ AP_SIGNATURE_BYTES = 4096,
+ AP_VALUE_BYTES = 1024,
+ AP_PARAMETER_LIMIT = 64
+};
+enum { AP_EVIDENCE_CONTEXT, AP_EVIDENCE_CORRIDOR, AP_EVIDENCE_PATH, AP_EVIDENCE_SCOPES };
+
+typedef struct {
+ size_t allocated;
+ bool failed;
+} ap_json_budget;
+
+static void *ap_json_malloc(void *context, size_t size) {
+ ap_json_budget *budget = context;
+ if (size > AP_JSON_BUDGET - budget->allocated) {
+ budget->failed = true;
+ return NULL;
+ }
+ void *p = malloc(size);
+ if (p)
+ budget->allocated += size;
+ else
+ budget->failed = true;
+ return p;
+}
+
+static void *ap_json_realloc(void *context, void *ptr, size_t old_size, size_t size) {
+ ap_json_budget *budget = context;
+ size_t growth = size > old_size ? size - old_size : 0;
+ if (growth > AP_JSON_BUDGET - budget->allocated) {
+ budget->failed = true;
+ return NULL;
+ }
+ void *p = realloc(ptr, size);
+ if (p)
+ budget->allocated += growth;
+ else
+ budget->failed = true;
+ return p;
+}
+
+static void ap_json_free(void *context, void *ptr) {
+ (void)context;
+ free(ptr);
+}
+
+/* Presence and references are deliberately separate from execution. */
+static const char *const ap_types[] = {
+ "", "CALLS", "HTTP_CALLS", "ASYNC_CALLS", "CALL_REFERENCE", "IMPORTS",
+ "IMPLEMENTS", "INHERITS", "CONFIGURES", "WRITES", "READS", "USAGE",
+ "PUBLISHES", "SUBSCRIBES", "DEFINES", "DEFINES_METHOD", "CONTAINS", "EMITS",
+ "LISTENS_ON", "HANDLES", "DATA_FLOWS", "INFRA_MAPS"};
+enum { AP_DEFINES = 14, AP_METHOD = 15, AP_CONTAINS = 16 };
+
+typedef struct {
+ int64_t id;
+ char *name, *qn, *file, *label;
+ int line, end, atom, component, degree;
+ bool entry, structural, declared, test, test_property;
+} ap_node;
+typedef struct {
+ int64_t id;
+ int source, target, type;
+} ap_edge;
+typedef struct {
+ int source, target, weight;
+} ap_pair;
+typedef struct {
+ int source, target, type, edge;
+} ap_dep;
+typedef struct {
+ int root, members, files, atoms, representative, degree, displayed;
+ int overview_group;
+ char *directory;
+ int samples[AP_REPRESENTATIVES], sample_count;
+} ap_component;
+typedef struct {
+ char *id, *label;
+ bool test;
+ int components, members, files;
+} ap_overview_group;
+typedef struct {
+ int index, members, degree;
+} ap_rank;
+typedef struct {
+ sqlite3 *db;
+ cbm_architecture_projection_options_t options;
+ uint64_t started;
+ bool cancelled, expired;
+ size_t text_bytes;
+ const char *limited;
+ int64_t total_nodes, total_edges, total_files;
+ ap_node *nodes;
+ ap_edge *edges;
+ int n, m;
+ ap_component *components;
+ int component_count, accounted, structural, unmodeled_edges, relationship_edges;
+ int cycle_count, omitted_cycles;
+ ap_overview_group groups[66];
+ int group_count, grouping_depth;
+ sqlite3_stmt *provenance;
+ sqlite3_stmt *symbol_metadata;
+ yyjson_doc **symbol_properties;
+ unsigned char *symbol_properties_loaded;
+ ap_json_budget metadata_budget;
+ size_t evidence_bytes[AP_EVIDENCE_SCOPES];
+ int evidence_scope;
+ bool evidence_omitted, evidence_suppressed;
+} ap_context;
+
+static int ap_bound(int requested, int fallback, int ceiling) {
+ return requested <= 0 ? fallback : requested > ceiling ? ceiling : requested;
+}
+
+static bool ap_stopped(ap_context *c) {
+ if (c->options.cancel && c->options.cancel(c->options.cancel_context))
+ c->cancelled = true;
+ if (cbm_now_ms() >= c->options.deadline_ms)
+ c->expired = true;
+ return c->cancelled || c->expired;
+}
+
+static int ap_progress(void *context) {
+ return ap_stopped(context) ? 1 : 0;
+}
+
+static char *ap_copy(ap_context *c, const unsigned char *text) {
+ const char *s = text ? (const char *)text : "";
+ size_t bytes = strlen(s) + 1;
+ if (bytes > AP_TEXT_BUDGET - c->text_bytes) {
+ c->limited = "Indexed symbol text exceeds the analysis memory budget.";
+ return NULL;
+ }
+ char *result = malloc(bytes);
+ if (!result)
+ return NULL;
+ memcpy(result, s, bytes);
+ c->text_bytes += bytes;
+ return result;
+}
+
+static int ap_find(const ap_context *c, int64_t id) {
+ int lo = 0, hi = c->n;
+ while (lo < hi) {
+ int mid = lo + (hi - lo) / 2;
+ if (c->nodes[mid].id < id)
+ lo = mid + 1;
+ else
+ hi = mid;
+ }
+ return lo < c->n && c->nodes[lo].id == id ? lo : -1;
+}
+
+static int ap_type(const char *type) {
+ for (int i = 1; i < (int)(sizeof(ap_types) / sizeof(ap_types[0])); i++)
+ if (strcmp(type, ap_types[i]) == 0)
+ return i;
+ return 0;
+}
+
+static bool ap_execution(int type) {
+ return type >= 1 && type <= 3;
+}
+static bool ap_dependency(int type) {
+ return (type > 0 && type < AP_DEFINES) || type > AP_CONTAINS;
+}
+static bool ap_cluster_edge(int type) {
+ return type == 1 || type == 5 || type == 11;
+}
+
+/* Conservative source conventions supplement the positive indexed is_test
+ * flag. Non-test classification means no test evidence, not production use. */
+static bool ap_test_path(const char *path) {
+ const char *base = path;
+ for (const char *p = path;; p++) {
+ if (*p == '/' || *p == '\\' || !*p) {
+ size_t len = (size_t)(p - base);
+ if ((len == 4 && !strncmp(base, "test", len)) ||
+ (len == 5 && !strncmp(base, "tests", len)) ||
+ (len == 9 && !strncmp(base, "__tests__", len)))
+ return true;
+ if (!*p)
+ break;
+ base = p + 1;
+ }
+ }
+ return !strncmp(base, "test_", 5) || strstr(base, "_test.") || strstr(base, ".test.") ||
+ strstr(base, ".spec.");
+}
+
+static int ap_counts(ap_context *c, const char *project) {
+ sqlite3_stmt *stmt = NULL;
+ const char *sql = "SELECT (SELECT count(*) FROM nodes WHERE project=?1),"
+ "(SELECT count(*) FROM edges WHERE project=?1),"
+ "(SELECT count(*) FROM nodes WHERE project=?1 AND label='File') "
+ "FROM projects WHERE name=?1";
+ if (sqlite3_prepare_v2(c->db, sql, -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ int step = sqlite3_step(stmt);
+ if (step == SQLITE_ROW) {
+ c->total_nodes = sqlite3_column_int64(stmt, 0);
+ c->total_edges = sqlite3_column_int64(stmt, 1);
+ c->total_files = sqlite3_column_int64(stmt, 2);
+ }
+ sqlite3_finalize(stmt);
+ if (step == SQLITE_DONE)
+ return CBM_STORE_NOT_FOUND;
+ if (step != SQLITE_ROW)
+ return CBM_STORE_ERR;
+ if (c->total_nodes > c->options.max_nodes)
+ c->limited = "Graph exceeds the node budget; no sampled architecture was inferred.";
+ else if (c->total_edges > c->options.max_edges)
+ c->limited = "Graph exceeds the edge budget; no sampled architecture was inferred.";
+ return CBM_STORE_OK;
+}
+
+static int ap_load(ap_context *c, const char *project) {
+ c->nodes = calloc((size_t)c->total_nodes + 1, sizeof(*c->nodes));
+ c->edges = calloc((size_t)c->total_edges + 1, sizeof(*c->edges));
+ if (!c->nodes || !c->edges)
+ return CBM_STORE_ERR;
+ sqlite3_stmt *stmt = NULL;
+ const char *sql =
+ "SELECT id,name,qualified_name,file_path,label,start_line,end_line,"
+ "CASE WHEN json_valid(properties) THEN json_extract(properties,'$.is_entry_point') "
+ "ELSE 0 END, CASE WHEN json_valid(properties) THEN json_extract(properties,'$.is_test') "
+ "ELSE 0 END FROM nodes WHERE project=?1 ORDER BY id";
+ if (sqlite3_prepare_v2(c->db, sql, -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ int step;
+ while ((step = sqlite3_step(stmt)) == SQLITE_ROW) {
+ if (c->n >= c->total_nodes || ap_stopped(c))
+ break;
+ ap_node *n = &c->nodes[c->n++];
+ n->id = sqlite3_column_int64(stmt, 0);
+ n->name = ap_copy(c, sqlite3_column_text(stmt, 1));
+ n->qn = ap_copy(c, sqlite3_column_text(stmt, 2));
+ n->file = ap_copy(c, sqlite3_column_text(stmt, 3));
+ n->label = ap_copy(c, sqlite3_column_text(stmt, 4));
+ if (!n->name || !n->qn || !n->file || !n->label)
+ break;
+ n->line = sqlite3_column_int(stmt, 5);
+ n->end = sqlite3_column_int(stmt, 6);
+ n->entry = sqlite3_column_int(stmt, 7) != 0;
+ n->test_property = sqlite3_column_int(stmt, 8) != 0;
+ n->test = n->test_property || ap_test_path(n->file);
+ n->structural = !strcmp(n->label, "Project") || !strcmp(n->label, "Folder");
+ n->declared = !strcmp(n->label, "Module") || !strcmp(n->label, "Package") ||
+ !strcmp(n->label, "Namespace") || !strcmp(n->label, "Class") ||
+ !strcmp(n->label, "Struct") || !strcmp(n->label, "Interface");
+ n->atom = c->n - 1;
+ n->component = -1;
+ }
+ sqlite3_finalize(stmt);
+ if (step != SQLITE_DONE)
+ return CBM_STORE_ERR;
+ sql = "SELECT id,source_id,target_id,type FROM edges WHERE project=?1 ORDER BY id";
+ if (sqlite3_prepare_v2(c->db, sql, -1, &stmt, NULL) != SQLITE_OK)
+ return CBM_STORE_ERR;
+ sqlite3_bind_text(stmt, 1, project, -1, SQLITE_TRANSIENT);
+ int scanned = 0;
+ while ((step = sqlite3_step(stmt)) == SQLITE_ROW) {
+ if (scanned++ >= c->total_edges || ap_stopped(c))
+ break;
+ int type = ap_type((const char *)sqlite3_column_text(stmt, 3));
+ if (!type) {
+ c->unmodeled_edges++;
+ continue;
+ }
+ int source = ap_find(c, sqlite3_column_int64(stmt, 1));
+ int target = ap_find(c, sqlite3_column_int64(stmt, 2));
+ if (source < 0 || target < 0)
+ continue;
+ c->edges[c->m++] = (ap_edge){sqlite3_column_int64(stmt, 0), source, target, type};
+ if (ap_dependency(type)) {
+ c->nodes[source].degree++;
+ c->nodes[target].degree++;
+ c->relationship_edges++;
+ }
+ }
+ sqlite3_finalize(stmt);
+ return step == SQLITE_DONE ? CBM_STORE_OK : CBM_STORE_ERR;
+}
+
+/* Ownership is grounded in declared module/type names and explicit definition
+ * edges. File ownership is only the fallback atom, never a folder component. */
+static int ap_ownership(ap_context *c) {
+ CBMHashTable *files = cbm_ht_create((uint32_t)c->n);
+ CBMHashTable *declared = cbm_ht_create((uint32_t)c->n);
+ if (!files || !declared) {
+ cbm_ht_free(files);
+ cbm_ht_free(declared);
+ return CBM_STORE_ERR;
+ }
+ for (int i = 0; i < c->n; i++) {
+ ap_node *n = &c->nodes[i];
+ if (n->declared)
+ cbm_ht_set(declared, n->qn, (void *)(intptr_t)(i + 1));
+ if (n->file[0] && (!strcmp(n->label, "File") || !strcmp(n->label, "Module"))) {
+ intptr_t old = (intptr_t)cbm_ht_get(files, n->file);
+ if (!old || (!strcmp(n->label, "Module") && strcmp(c->nodes[old - 1].label, "Module")))
+ cbm_ht_set(files, n->file, (void *)(intptr_t)(i + 1));
+ }
+ }
+ int rc = CBM_STORE_OK;
+ for (int i = 0; i < c->n; i++) {
+ if ((i & 255) == 0 && ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ break;
+ }
+ ap_node *n = &c->nodes[i];
+ if (n->structural) {
+ n->atom = -1;
+ c->structural++;
+ continue;
+ }
+ c->accounted++;
+ intptr_t file = (intptr_t)cbm_ht_get(files, n->file);
+ n->atom = file ? (int)file - 1 : i;
+ if (n->declared) {
+ n->atom = i;
+ continue;
+ }
+ /* QN ownership is an indexed declaration match, not a path heuristic. */
+ size_t len = strlen(n->qn);
+ char *qn = malloc(len + 1);
+ if (!qn) {
+ rc = CBM_STORE_ERR;
+ break;
+ }
+ memcpy(qn, n->qn, len + 1);
+ for (int depth = 0; depth < 64; depth++) {
+ char *dot = strrchr(qn, '.');
+ if (!dot)
+ break;
+ *dot = '\0';
+ intptr_t owner = (intptr_t)cbm_ht_get(declared, qn);
+ if (owner) {
+ n->atom = (int)owner - 1;
+ break;
+ }
+ }
+ free(qn);
+ /* Embedded tests can share a production file/class, but not its
+ * architecture atom. Prefer a same-role file declaration if present. */
+ if (n->test != c->nodes[n->atom].test)
+ n->atom = file && n->test == c->nodes[file - 1].test ? (int)file - 1 : i;
+ }
+ if (rc == CBM_STORE_OK)
+ for (int i = 0; i < c->m; i++) {
+ ap_edge *e = &c->edges[i];
+ ap_node *source = &c->nodes[e->source], *target = &c->nodes[e->target];
+ if ((e->type == AP_METHOD || e->type == AP_DEFINES || e->type == AP_CONTAINS) &&
+ source->declared && !target->structural && !target->declared &&
+ source->test == target->test)
+ target->atom = e->source;
+ }
+ cbm_ht_free(files);
+ cbm_ht_free(declared);
+ return rc;
+}
+
+static int ap_pair_compare(const void *a, const void *b) {
+ const ap_pair *x = a, *y = b;
+ if (x->source != y->source)
+ return x->source < y->source ? -1 : 1;
+ return x->target < y->target ? -1 : x->target != y->target;
+}
+
+/* Six local adjacency sweeps, O(passes * edges), with explicit declarations
+ * as atoms. Weak one-off calls cannot absorb an unrelated module; communities
+ * have a fixed atom-size ceiling. These remain component candidates. */
+static int ap_components(ap_context *c) {
+ int n = c->n;
+ int *group = malloc(((size_t)n + 1) * sizeof(int));
+ int *sizes = calloc((size_t)n + 1, sizeof(int));
+ int *offset = calloc((size_t)n + 2, sizeof(int));
+ int *score = calloc((size_t)n + 1, sizeof(int));
+ int *touched = malloc(((size_t)n + 1) * sizeof(int));
+ ap_pair *pairs = malloc(((size_t)c->m * 2 + 1) * sizeof(*pairs));
+ if (!group || !sizes || !offset || !score || !touched || !pairs) {
+ free(group);
+ free(sizes);
+ free(offset);
+ free(score);
+ free(touched);
+ free(pairs);
+ return CBM_STORE_ERR;
+ }
+ for (int i = 0; i < n; i++)
+ group[i] = i;
+ for (int i = 0; i < n; i++)
+ if (c->nodes[i].atom >= 0)
+ sizes[c->nodes[i].atom] = 1;
+ int pcount = 0;
+ for (int i = 0; i < c->m; i++) {
+ ap_edge *e = &c->edges[i];
+ int a = c->nodes[e->source].atom, b = c->nodes[e->target].atom;
+ if (a < 0 || b < 0 || a == b || !ap_cluster_edge(e->type) ||
+ c->nodes[a].test != c->nodes[b].test)
+ continue;
+ pairs[pcount++] = (ap_pair){a, b, 1};
+ pairs[pcount++] = (ap_pair){b, a, 1};
+ }
+ qsort(pairs, (size_t)pcount, sizeof(*pairs), ap_pair_compare);
+ for (int i = 0; i < pcount; i++)
+ offset[pairs[i].source + 1]++;
+ for (int i = 0; i < n; i++)
+ offset[i + 1] += offset[i];
+ int rc = CBM_STORE_OK;
+ for (int pass = 0; pass < AP_PASSES; pass++) {
+ bool changed = false;
+ for (int i = 0; i < n; i++) {
+ if ((i & 255) == 0 && ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto finish;
+ }
+ if (!sizes[group[i]] || offset[i] == offset[i + 1])
+ continue;
+ /* Explicit package/namespace boundaries remain separate. */
+ if (!strcmp(c->nodes[i].label, "Package") || !strcmp(c->nodes[i].label, "Namespace"))
+ continue;
+ int used = 0, total = 0, best = group[i], best_score = 0;
+ for (int j = offset[i]; j < offset[i + 1]; j++) {
+ int g = group[pairs[j].target];
+ if (!score[g])
+ touched[used++] = g;
+ score[g]++;
+ total++;
+ }
+ for (int j = 0; j < used; j++) {
+ int g = touched[j];
+ const int candidate_score = score[g];
+ if (candidate_score > best_score || (candidate_score == best_score && g < best)) {
+ best = g;
+ best_score = candidate_score;
+ }
+ }
+ int current_score = score[group[i]];
+ if (best != group[i] && best_score >= 3 && best_score > current_score &&
+ (int64_t)best_score * 100 >= (int64_t)total * 55 && sizes[best] < AP_GROUP_ATOMS) {
+ sizes[group[i]]--;
+ sizes[best]++;
+ group[i] = best;
+ changed = true;
+ }
+ for (int j = 0; j < used; j++)
+ score[touched[j]] = 0;
+ }
+ if (!changed)
+ break;
+ }
+ c->components = calloc((size_t)n + 1, sizeof(*c->components));
+ if (!c->components) {
+ rc = CBM_STORE_ERR;
+ goto finish;
+ }
+ for (int i = 0; i < n; i++)
+ score[i] = -1;
+ for (int i = 0; i < n; i++) {
+ ap_node *node = &c->nodes[i];
+ if (node->atom < 0)
+ continue;
+ int g = group[node->atom];
+ if (score[g] < 0) {
+ int k = c->component_count++;
+ score[g] = k;
+ c->components[k] = (ap_component){.root = g, .representative = i, .displayed = -1};
+ }
+ int k = score[g];
+ node->component = k;
+ ap_component *part = &c->components[k];
+ part->members++;
+ part->degree += node->degree;
+ if (node->atom == i)
+ part->atoms++;
+ ap_node *rep = &c->nodes[part->representative];
+ if ((node->declared && !rep->declared) ||
+ (node->declared == rep->declared && node->degree > rep->degree))
+ part->representative = i;
+ }
+ for (int i = 0; i < c->component_count; i++) {
+ c->components[i].samples[0] = c->components[i].representative;
+ c->components[i].sample_count = 1;
+ }
+ for (int i = 0; i < n; i++) {
+ if (c->nodes[i].component < 0)
+ continue;
+ ap_component *p = &c->components[c->nodes[i].component];
+ if (p->sample_count < AP_REPRESENTATIVES && i != p->representative)
+ p->samples[p->sample_count++] = i;
+ }
+ /* Count unique file memberships, including isolated files. */
+ CBMHashTable *seen = cbm_ht_create((uint32_t)n);
+ char **keys = calloc((size_t)n + 1, sizeof(char *));
+ if (!seen || !keys) {
+ cbm_ht_free(seen);
+ free(keys);
+ rc = CBM_STORE_ERR;
+ goto finish;
+ }
+ int key_count = 0;
+ for (int i = 0; i < n; i++) {
+ ap_node *node = &c->nodes[i];
+ if (node->component < 0 || !node->file[0])
+ continue;
+ size_t len = strlen(node->file) + 32;
+ char *key = malloc(len);
+ if (!key) {
+ rc = CBM_STORE_ERR;
+ break;
+ }
+ snprintf(key, len, "%d:%s", node->component, node->file);
+ if (!cbm_ht_has(seen, key)) {
+ cbm_ht_set(seen, key, (void *)1);
+ keys[key_count++] = key;
+ c->components[node->component].files++;
+ } else
+ free(key);
+ }
+ cbm_ht_free(seen);
+ for (int i = 0; i < key_count; i++)
+ free(keys[i]);
+ free(keys);
+finish:
+ free(group);
+ free(sizes);
+ free(offset);
+ free(score);
+ free(touched);
+ free(pairs);
+ return rc;
+}
+
+static void ap_component_id(const ap_context *c, int component, char id[48]) {
+ if (component < 0) {
+ id[0] = '\0';
+ return;
+ }
+ snprintf(id, 48, "component-%lld", (long long)c->nodes[c->components[component].root].id);
+}
+
+/* Coarse display aggregates, not newly inferred architectural components.
+ * A whole inferred component has one owner: the common directory of all of
+ * its source members. Uniform coarsening never drops small/isolated parts. */
+static int ap_overview_grouping(ap_context *c) {
+ for (int i = 0; i < c->n; i++) {
+ ap_node *node = &c->nodes[i];
+ if (node->component < 0 || !node->file[0])
+ continue;
+ ap_component *part = &c->components[node->component];
+ const char *last = NULL;
+ for (const char *p = node->file; *p; p++)
+ if (*p == '/' || *p == '\\')
+ last = p;
+ size_t length = last ? (size_t)(last - node->file) : 0;
+ if (!part->directory) {
+ part->directory = ap_copy(c, (const unsigned char *)node->file);
+ if (!part->directory)
+ return CBM_STORE_ERR;
+ part->directory[length] = '\0';
+ for (char *p = part->directory; *p; p++)
+ if (*p == '\\')
+ *p = '/';
+ } else {
+ size_t common = 0, old = strlen(part->directory);
+ while (common < old && common < length &&
+ part->directory[common] ==
+ (node->file[common] == '\\' ? '/' : node->file[common]))
+ common++;
+ bool boundary = (common == old && (common == length || node->file[common] == '/' ||
+ node->file[common] == '\\')) ||
+ (common == length && (common == old || part->directory[common] == '/'));
+ if (!boundary)
+ while (common && part->directory[common - 1] != '/')
+ common--;
+ if (common && part->directory[common - 1] == '/')
+ common--;
+ part->directory[common] = '\0';
+ }
+ if ((i & 255) == 0 && ap_stopped(c))
+ return CBM_STORE_ERR;
+ }
+ for (int depth = 2; depth >= 0; depth--) {
+ for (int g = 0; g < c->group_count; g++) {
+ free(c->groups[g].id);
+ free(c->groups[g].label);
+ }
+ c->group_count = 0;
+ bool retry = false;
+ for (int i = 0; i < c->component_count; i++) {
+ ap_component *part = &c->components[i];
+ const char *directory = part->directory ? part->directory : "@no-source";
+ size_t length = strlen(directory);
+ if (part->directory) {
+ if (!depth)
+ length = 0;
+ else {
+ int separators = 0;
+ for (size_t j = 0; j < length; j++)
+ if (directory[j] == '/' && ++separators == depth) {
+ length = j;
+ break;
+ }
+ }
+ }
+ bool test = c->nodes[part->root].test;
+ size_t bytes = length + 32;
+ char *key = malloc(bytes);
+ if (!key)
+ return CBM_STORE_ERR;
+ snprintf(key, bytes, "%s:%s:%.*s", part->directory ? "directory" : "unlocated",
+ test ? "test" : "non_test", (int)length, directory);
+ int g;
+ for (g = 0; g < c->group_count; g++)
+ if (!strcmp(c->groups[g].id, key))
+ break;
+ if (g == c->group_count) {
+ if (g >= 64) {
+ free(key);
+ retry = true;
+ break;
+ }
+ ap_overview_group *group = &c->groups[c->group_count++];
+ memset(group, 0, sizeof(*group));
+ group->test = test;
+ group->id = ap_copy(c, (const unsigned char *)key);
+ key[0] = '\0';
+ if (length)
+ snprintf(key, bytes, "%.*s", (int)length, directory);
+ else
+ snprintf(key, bytes, "(root)");
+ group->label = ap_copy(c, (const unsigned char *)key);
+ if (!group->id || !group->label) {
+ free(key);
+ return CBM_STORE_ERR;
+ }
+ }
+ free(key);
+ part->overview_group = g;
+ c->groups[g].components++;
+ c->groups[g].members += part->members;
+ if ((i & 255) == 0 && ap_stopped(c))
+ return CBM_STORE_ERR;
+ }
+ if (!retry) {
+ c->grouping_depth = depth;
+ break;
+ }
+ }
+ /* File counts are unique within a group; component file counts can overlap. */
+ CBMHashTable *seen = cbm_ht_create((uint32_t)c->n);
+ char **keys = calloc((size_t)c->n + 1, sizeof(*keys));
+ if (!seen || !keys) {
+ cbm_ht_free(seen);
+ free(keys);
+ return CBM_STORE_ERR;
+ }
+ int count = 0, rc = CBM_STORE_OK;
+ for (int i = 0; i < c->n; i++) {
+ ap_node *node = &c->nodes[i];
+ if (node->component < 0 || !node->file[0])
+ continue;
+ int g = c->components[node->component].overview_group;
+ size_t length = strlen(node->file) + 32;
+ char *key = malloc(length);
+ if (!key) {
+ rc = CBM_STORE_ERR;
+ break;
+ }
+ snprintf(key, length, "%d:%s", g, node->file);
+ if (cbm_ht_has(seen, key))
+ free(key);
+ else {
+ cbm_ht_set(seen, key, (void *)1);
+ keys[count++] = key;
+ c->groups[g].files++;
+ }
+ if ((i & 255) == 0 && ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ break;
+ }
+ }
+ cbm_ht_free(seen);
+ for (int i = 0; i < count; i++)
+ free(keys[i]);
+ free(keys);
+ return rc;
+}
+
+/* Only opt-in, displayed symbols load indexed properties. Cache each decoded
+ * object once across representatives, paths and witnesses in this response.
+ * Source code is never opened or parsed. Oversized values are omitted whole. */
+static yyjson_val *ap_symbol_properties(ap_context *c, int index) {
+ if (!c->options.include_behavior_evidence)
+ return NULL;
+ if (c->symbol_properties_loaded && c->symbol_properties_loaded[index])
+ return c->symbol_properties[index] ? yyjson_doc_get_root(c->symbol_properties[index])
+ : NULL;
+ if (c->metadata_budget.failed)
+ return NULL;
+ if (!c->symbol_properties) {
+ c->symbol_properties = calloc((size_t)c->n, sizeof(*c->symbol_properties));
+ c->symbol_properties_loaded = calloc((size_t)c->n, 1);
+ if (!c->symbol_properties || !c->symbol_properties_loaded) {
+ free(c->symbol_properties);
+ free(c->symbol_properties_loaded);
+ c->symbol_properties = NULL;
+ c->symbol_properties_loaded = NULL;
+ c->metadata_budget.failed = true;
+ return NULL;
+ }
+ }
+ c->symbol_properties_loaded[index] = 1;
+ if (!c->symbol_metadata &&
+ sqlite3_prepare_v2(c->db,
+ "SELECT CASE WHEN length(CAST(properties AS BLOB))<=16384 THEN "
+ "properties END FROM nodes WHERE id=?1",
+ -1, &c->symbol_metadata, NULL) != SQLITE_OK)
+ return NULL;
+ sqlite3_bind_int64(c->symbol_metadata, 1, c->nodes[index].id);
+ if (sqlite3_step(c->symbol_metadata) == SQLITE_ROW) {
+ char *text = (char *)sqlite3_column_text(c->symbol_metadata, 0);
+ yyjson_alc allocator = {ap_json_malloc, ap_json_realloc, ap_json_free, &c->metadata_budget};
+ if (text)
+ c->symbol_properties[index] = yyjson_read_opts(
+ text, (size_t)sqlite3_column_bytes(c->symbol_metadata, 0), 0, &allocator, NULL);
+ }
+ sqlite3_reset(c->symbol_metadata);
+ return c->symbol_properties[index] ? yyjson_doc_get_root(c->symbol_properties[index]) : NULL;
+}
+
+static bool ap_bounded_string(yyjson_val *value, size_t maximum) {
+ return yyjson_is_str(value) && yyjson_get_len(value) <= maximum;
+}
+
+static bool ap_parameter_array(yyjson_val *value) {
+ if (!yyjson_is_arr(value) || yyjson_arr_size(value) > AP_PARAMETER_LIMIT)
+ return false;
+ size_t index, maximum;
+ yyjson_val *item;
+ yyjson_arr_foreach(value, index, maximum,
+ item) if (!ap_bounded_string(item, AP_VALUE_BYTES)) return false;
+ return true;
+}
+
+/* Optional copies must leave room for the base graph and its serialized copy.
+ * Charge mutable values plus worst-case JSON escaping before allocation. The
+ * separate pools keep overview/catalog duplicates from consuming path evidence.
+ * The shared allocator remains the final hard bound on the entire response. */
+static size_t ap_evidence_limit(const ap_context *c) {
+ static const size_t limits[AP_EVIDENCE_SCOPES] = {256 * 1024, 768 * 1024, 1024 * 1024};
+ return limits[c->evidence_scope];
+}
+
+static size_t ap_evidence_string_cost(yyjson_val *value) {
+ return 128 + 8 * yyjson_get_len(value);
+}
+
+static bool ap_evidence_admit(ap_context *c, size_t bytes) {
+ if (c->evidence_suppressed)
+ return false;
+ if (bytes > ap_evidence_limit(c) - c->evidence_bytes[c->evidence_scope]) {
+ c->evidence_omitted = true;
+ return false;
+ }
+ c->evidence_bytes[c->evidence_scope] += bytes;
+ return true;
+}
+
+static void ap_declaration_evidence(yyjson_mut_doc *doc, ap_context *c, int index,
+ yyjson_mut_val *value) {
+ if (c->evidence_suppressed)
+ return;
+ if (ap_evidence_limit(c) - c->evidence_bytes[c->evidence_scope] < 128) {
+ c->evidence_omitted = true;
+ return;
+ }
+ yyjson_val *properties = ap_symbol_properties(c, index);
+ if (!yyjson_is_obj(properties))
+ return;
+ yyjson_val *signature = yyjson_obj_get(properties, "signature"),
+ *returns = yyjson_obj_get(properties, "return_type");
+ if (ap_bounded_string(signature, AP_SIGNATURE_BYTES) &&
+ ap_evidence_admit(c, ap_evidence_string_cost(signature)))
+ yyjson_mut_obj_add_val(doc, value, "signature", yyjson_val_mut_copy(doc, signature));
+ if (ap_bounded_string(returns, AP_VALUE_BYTES) &&
+ ap_evidence_admit(c, ap_evidence_string_cost(returns)))
+ yyjson_mut_obj_add_val(doc, value, "return_type", yyjson_val_mut_copy(doc, returns));
+ yyjson_val *names = yyjson_obj_get(properties, "param_names"),
+ *types = yyjson_obj_get(properties, "param_types"),
+ *count = yyjson_obj_get(properties, "param_count");
+ if (ap_parameter_array(names) && ap_parameter_array(types) && yyjson_is_int(count) &&
+ yyjson_get_sint(count) >= 0 && yyjson_get_sint(count) <= INT_MAX &&
+ yyjson_arr_size(names) <= (size_t)yyjson_get_sint(count) &&
+ yyjson_arr_size(types) <= (size_t)yyjson_get_sint(count)) {
+ size_t bytes = 384, at, maximum;
+ yyjson_val *item;
+ yyjson_arr_foreach(names, at, maximum, item) bytes += ap_evidence_string_cost(item);
+ yyjson_arr_foreach(types, at, maximum, item) bytes += ap_evidence_string_cost(item);
+ if (!ap_evidence_admit(c, bytes))
+ return;
+ yyjson_mut_val *parameters = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, parameters, "names", yyjson_val_mut_copy(doc, names));
+ yyjson_mut_obj_add_val(doc, parameters, "types", yyjson_val_mut_copy(doc, types));
+ yyjson_mut_obj_add_val(doc, parameters, "count", yyjson_val_mut_copy(doc, count));
+ yyjson_mut_obj_add_val(doc, value, "parameters", parameters);
+ }
+}
+
+static yyjson_mut_val *ap_symbol(yyjson_mut_doc *doc, ap_context *c, int index) {
+ const ap_node *n = &c->nodes[index];
+ yyjson_mut_val *value = yyjson_mut_obj(doc);
+ char id[48];
+ ap_component_id(c, n->component, id);
+ yyjson_mut_obj_add_sint(doc, value, "id", n->id);
+ yyjson_mut_obj_add_strcpy(doc, value, "name", n->name);
+ yyjson_mut_obj_add_strcpy(doc, value, "qualified_name", n->qn);
+ yyjson_mut_obj_add_strcpy(doc, value, "label", n->label);
+ yyjson_mut_obj_add_strcpy(doc, value, "file_path", n->file);
+ yyjson_mut_obj_add_int(doc, value, "start_line", n->line);
+ yyjson_mut_obj_add_int(doc, value, "end_line", n->end);
+ yyjson_mut_obj_add_strcpy(doc, value, "component_id", id);
+ if (n->component >= 0 && c->group_count)
+ yyjson_mut_obj_add_strcpy(doc, value, "group_id",
+ c->groups[c->components[n->component].overview_group].id);
+ if (c->options.include_behavior_evidence)
+ ap_declaration_evidence(doc, c, index, value);
+ return value;
+}
+
+static int ap_dep_compare(const void *a, const void *b) {
+ const ap_dep *x = a, *y = b;
+ if (x->source != y->source)
+ return x->source < y->source ? -1 : 1;
+ if (x->target != y->target)
+ return x->target < y->target ? -1 : 1;
+ if (x->type != y->type)
+ return x->type < y->type ? -1 : 1;
+ return x->edge < y->edge ? -1 : x->edge != y->edge;
+}
+
+static int ap_rank_compare(const void *a, const void *b) {
+ const ap_rank *x = a, *y = b;
+ if (x->members != y->members)
+ return x->members > y->members ? -1 : 1;
+ if (x->degree != y->degree)
+ return x->degree > y->degree ? -1 : 1;
+ return x->index < y->index ? -1 : x->index != y->index;
+}
+
+/* CALLS stores at most eight indexed expressions, without keyword names.
+ * Preserve stored indices/strings; do not infer parameter binding or values
+ * for absent arguments. Even a short array cannot establish completeness. */
+static void ap_argument_evidence(yyjson_mut_doc *doc, ap_context *c, yyjson_val *properties,
+ yyjson_mut_val *value) {
+ if (c->evidence_suppressed)
+ return;
+ yyjson_val *args = yyjson_obj_get(properties, "args");
+ if (!yyjson_is_arr(args))
+ return;
+ size_t count = yyjson_arr_size(args);
+ if (count > AP_ARGUMENT_LIMIT)
+ count = AP_ARGUMENT_LIMIT;
+ size_t bytes = 384;
+ for (size_t at = 0; at < count; at++) {
+ yyjson_val *arg = yyjson_arr_get(args, at), *index = yyjson_obj_get(arg, "i"),
+ *expression = yyjson_obj_get(arg, "e"), *resolved = yyjson_obj_get(arg, "v");
+ if (!yyjson_is_int(index) || yyjson_get_sint(index) < 0 ||
+ yyjson_get_sint(index) > INT_MAX || !ap_bounded_string(expression, AP_VALUE_BYTES))
+ continue;
+ bytes += 256 + ap_evidence_string_cost(expression);
+ if (ap_bounded_string(resolved, AP_VALUE_BYTES))
+ bytes += ap_evidence_string_cost(resolved);
+ }
+ if (!ap_evidence_admit(c, bytes))
+ return;
+ yyjson_mut_val *arguments = yyjson_mut_arr(doc);
+ for (size_t at = 0; at < count; at++) {
+ yyjson_val *arg = yyjson_arr_get(args, at), *index = yyjson_obj_get(arg, "i"),
+ *expression = yyjson_obj_get(arg, "e"), *resolved = yyjson_obj_get(arg, "v");
+ if (!yyjson_is_int(index) || yyjson_get_sint(index) < 0 ||
+ yyjson_get_sint(index) > INT_MAX || !ap_bounded_string(expression, AP_VALUE_BYTES))
+ continue;
+ yyjson_mut_val *copy = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, copy, "i", yyjson_val_mut_copy(doc, index));
+ yyjson_mut_obj_add_val(doc, copy, "e", yyjson_val_mut_copy(doc, expression));
+ if (ap_bounded_string(resolved, AP_VALUE_BYTES))
+ yyjson_mut_obj_add_val(doc, copy, "v", yyjson_val_mut_copy(doc, resolved));
+ yyjson_mut_arr_add_val(arguments, copy);
+ }
+ yyjson_mut_obj_add_val(doc, value, "arguments", arguments);
+ yyjson_mut_obj_add_int(doc, value, "argument_limit", AP_ARGUMENT_LIMIT);
+ yyjson_mut_obj_add_bool(doc, value, "arguments_complete", false);
+}
+
+/* Look up only displayed witnesses. Large/unavailable properties are omitted;
+ * resolver confidence is an uncalibrated score, never execution probability. */
+static void ap_provenance(yyjson_mut_doc *doc, ap_context *c, int edge, yyjson_mut_val *value) {
+ if (!c->provenance &&
+ sqlite3_prepare_v2(c->db,
+ "SELECT CASE WHEN length(CAST(properties AS BLOB))<=16384 THEN "
+ "properties END FROM edges WHERE id=?1",
+ -1, &c->provenance, NULL) != SQLITE_OK)
+ return;
+ sqlite3_bind_int64(c->provenance, 1, c->edges[edge].id);
+ yyjson_doc *properties = NULL;
+ if (sqlite3_step(c->provenance) == SQLITE_ROW) {
+ const char *text = (const char *)sqlite3_column_text(c->provenance, 0);
+ if (text)
+ properties = yyjson_read(text, (size_t)sqlite3_column_bytes(c->provenance, 0), 0);
+ }
+ sqlite3_reset(c->provenance);
+ if (!properties)
+ return;
+ yyjson_val *root = yyjson_doc_get_root(properties), *line = yyjson_obj_get(root, "line");
+ const char *file = c->nodes[c->edges[edge].source].file;
+ if (yyjson_is_int(line) && yyjson_get_sint(line) > 0 && file[0]) {
+ yyjson_mut_val *site = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_strcpy(doc, site, "file_path", file);
+ yyjson_mut_obj_add_sint(doc, site, "line", yyjson_get_sint(line));
+ yyjson_mut_obj_add_val(doc, value, "callsite", site);
+ }
+ yyjson_val *strategy = yyjson_obj_get(root, "strategy"),
+ *confidence = yyjson_obj_get(root, "confidence"),
+ *candidates = yyjson_obj_get(root, "candidates");
+ yyjson_mut_val *resolution = yyjson_mut_obj(doc);
+ bool any = false;
+ if (yyjson_is_str(strategy) && yyjson_get_len(strategy) <= 128) {
+ yyjson_mut_obj_add_strcpy(doc, resolution, "strategy", yyjson_get_str(strategy));
+ any = true;
+ }
+ if (yyjson_is_num(confidence)) {
+ yyjson_mut_obj_add_real(doc, resolution, "confidence", yyjson_get_num(confidence));
+ any = true;
+ }
+ if (yyjson_is_int(candidates) && yyjson_get_sint(candidates) >= 0) {
+ yyjson_mut_obj_add_sint(doc, resolution, "candidates", yyjson_get_sint(candidates));
+ any = true;
+ }
+ if (any)
+ yyjson_mut_obj_add_val(doc, value, "resolution", resolution);
+ if (c->options.include_behavior_evidence && c->edges[edge].type == 1)
+ ap_argument_evidence(doc, c, root, value);
+ yyjson_doc_free(properties);
+}
+
+static yyjson_mut_val *ap_path_edge(yyjson_mut_doc *doc, ap_context *c, int edge) {
+ const ap_edge *e = &c->edges[edge];
+ yyjson_mut_val *value = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_sint(doc, value, "id", e->id);
+ yyjson_mut_obj_add_sint(doc, value, "source_id", c->nodes[e->source].id);
+ yyjson_mut_obj_add_sint(doc, value, "target_id", c->nodes[e->target].id);
+ yyjson_mut_obj_add_str(doc, value, "type", ap_types[e->type]);
+ ap_provenance(doc, c, edge, value);
+ return value;
+}
+
+static yyjson_mut_val *ap_witness(yyjson_mut_doc *doc, ap_context *c, int edge) {
+ const ap_edge *e = &c->edges[edge];
+ yyjson_mut_val *value = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_sint(doc, value, "edge_id", e->id);
+ yyjson_mut_obj_add_val(doc, value, "source", ap_symbol(doc, c, e->source));
+ yyjson_mut_obj_add_val(doc, value, "target", ap_symbol(doc, c, e->target));
+ yyjson_mut_obj_add_str(doc, value, "type", ap_types[e->type]);
+ ap_provenance(doc, c, edge, value);
+ return value;
+}
+
+/* Iterative Kosaraju. A component SCC is a dependency cycle, not evidence of
+ * a runtime loop or a contiguous path through the member symbols. */
+static int ap_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *cycles, const ap_dep *deps,
+ int count) {
+ int n = c->component_count;
+ int *out = calloc((size_t)n + 2, sizeof(int));
+ int *in = calloc((size_t)n + 2, sizeof(int));
+ int *forward = malloc(((size_t)count + 1) * sizeof(int));
+ int *reverse = malloc(((size_t)count + 1) * sizeof(int));
+ int *cursor = calloc((size_t)n + 1, sizeof(int));
+ int *stack = malloc(((size_t)n + 1) * sizeof(int));
+ int *order = malloc(((size_t)n + 1) * sizeof(int));
+ unsigned char *seen = calloc((size_t)n + 1, 1);
+ if (!out || !in || !forward || !reverse || !cursor || !stack || !order || !seen) {
+ free(out);
+ free(in);
+ free(forward);
+ free(reverse);
+ free(cursor);
+ free(stack);
+ free(order);
+ free(seen);
+ return CBM_STORE_ERR;
+ }
+ for (int i = 0; i < count; i++) {
+ out[deps[i].source + 1]++;
+ in[deps[i].target + 1]++;
+ }
+ for (int i = 0; i < n; i++) {
+ out[i + 1] += out[i];
+ in[i + 1] += in[i];
+ }
+ memcpy(cursor, out, ((size_t)n + 1) * sizeof(int));
+ for (int i = 0; i < count; i++)
+ forward[cursor[deps[i].source]++] = deps[i].target;
+ memcpy(cursor, in, ((size_t)n + 1) * sizeof(int));
+ for (int i = 0; i < count; i++)
+ reverse[cursor[deps[i].target]++] = deps[i].source;
+ memcpy(cursor, out, ((size_t)n + 1) * sizeof(int));
+ int ordered = 0, rc = CBM_STORE_OK;
+ for (int root = 0; root < n; root++) {
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ if (seen[root])
+ continue;
+ int depth = 0;
+ stack[depth++] = root;
+ seen[root] = 1;
+ while (depth) {
+ int v = stack[depth - 1];
+ if (cursor[v] < out[v + 1]) {
+ int next = forward[cursor[v]++];
+ if (!seen[next]) {
+ seen[next] = 1;
+ stack[depth++] = next;
+ }
+ } else {
+ order[ordered++] = v;
+ depth--;
+ }
+ if ((ordered & 1023) == 0 && ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ }
+ memset(seen, 0, (size_t)n + 1);
+ for (int i = ordered - 1; i >= 0; i--) {
+ int root = order[i];
+ if (seen[root])
+ continue;
+ int depth = 0, members = 0;
+ stack[depth++] = root;
+ seen[root] = 1;
+ yyjson_mut_val *ids = yyjson_mut_arr(doc);
+ bool visible = true;
+ while (depth) {
+ int v = stack[--depth];
+ members++;
+ if (c->components[v].displayed < 0)
+ visible = false;
+ char id[48];
+ ap_component_id(c, v, id);
+ yyjson_mut_arr_add_strcpy(doc, ids, id);
+ for (int j = in[v]; j < in[v + 1]; j++) {
+ int next = reverse[j];
+ if (!seen[next]) {
+ seen[next] = 1;
+ stack[depth++] = next;
+ }
+ }
+ if ((members & 255) == 0 && ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ if (members > 1) {
+ c->cycle_count++;
+ if (visible) {
+ yyjson_mut_val *cycle = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, cycle, "component_ids", ids);
+ yyjson_mut_arr_add_val(cycles, cycle);
+ } else
+ c->omitted_cycles++;
+ }
+ }
+done:
+ free(out);
+ free(in);
+ free(forward);
+ free(reverse);
+ free(cursor);
+ free(stack);
+ free(order);
+ free(seen);
+ return rc;
+}
+
+typedef struct {
+ int node, first_hop, depth, crossings;
+ bool selected;
+} ap_path_candidate;
+
+static int ap_path_candidate_compare(const void *left, const void *right) {
+ const ap_path_candidate *a = left, *b = right;
+ if (a->depth != b->depth)
+ return a->depth > b->depth ? -1 : 1;
+ if (a->crossings != b->crossings)
+ return a->crossings > b->crossings ? -1 : 1;
+ return a->node < b->node ? -1 : a->node != b->node;
+}
+
+/* One bounded BFS per selected entry. Select representative terminal witnesses
+ * after traversal: emitting during BFS lets shallow utility leaves exhaust the
+ * display budget before deeper queued branches are visited. The predecessor
+ * tree stays linear in graph size; we never enumerate all possible paths. */
+static int ap_paths(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *paths, const int *entries,
+ int entry_count, bool *truncated) {
+ int *offset = calloc((size_t)c->n + 2, sizeof(int));
+ int *adj = malloc(((size_t)c->m + 1) * sizeof(int));
+ int *cursor = calloc((size_t)c->n + 1, sizeof(int));
+ int *queue = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *previous = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *depth = calloc((size_t)c->n + 1, sizeof(int));
+ ap_path_candidate *candidates = malloc(((size_t)c->n + 1) * sizeof(*candidates));
+ if (!offset || !adj || !cursor || !queue || !previous || !depth || !candidates) {
+ free(offset);
+ free(adj);
+ free(cursor);
+ free(queue);
+ free(previous);
+ free(depth);
+ free(candidates);
+ return CBM_STORE_ERR;
+ }
+ for (int i = 0; i < c->m; i++)
+ if (ap_execution(c->edges[i].type))
+ offset[c->edges[i].source + 1]++;
+ for (int i = 0; i < c->n; i++)
+ offset[i + 1] += offset[i];
+ memcpy(cursor, offset, ((size_t)c->n + 1) * sizeof(int));
+ for (int i = 0; i < c->m; i++)
+ if (ap_execution(c->edges[i].type))
+ adj[cursor[c->edges[i].source]++] = i;
+ int produced = 0, rc = CBM_STORE_OK;
+ for (int ent = 0; ent < entry_count; ent++) {
+ if (produced >= c->options.max_paths) {
+ *truncated = true;
+ break;
+ }
+ for (int i = 0; i < c->n; i++)
+ previous[i] = -1;
+ int entry = entries[ent], head = 0, tail = 0, candidate_count = 0;
+ queue[tail++] = entry;
+ previous[entry] = -2;
+ depth[entry] = 0;
+ /* Adjacency cursors are no longer needed; reuse them for first hops. */
+ cursor[entry] = entry;
+ while (head < tail) {
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ int node = queue[head++];
+ bool extended = false;
+ if (depth[node] < c->options.max_depth) {
+ for (int j = offset[node]; j < offset[node + 1]; j++) {
+ int edge = adj[j], next = c->edges[edge].target;
+ if (previous[next] != -1)
+ continue;
+ previous[next] = edge;
+ depth[next] = depth[node] + 1;
+ cursor[next] = node == entry ? next : cursor[node];
+ queue[tail++] = next;
+ extended = true;
+ }
+ } else if (offset[node] != offset[node + 1])
+ *truncated = true;
+ if (extended || node == entry)
+ continue;
+ int crossings = 0, current = node;
+ while (previous[current] >= 0) {
+ int parent = c->edges[previous[current]].source;
+ if (c->nodes[parent].component != c->nodes[current].component)
+ crossings++;
+ current = parent;
+ }
+ candidates[candidate_count++] = (ap_path_candidate){.node = node,
+ .first_hop = cursor[node],
+ .depth = depth[node],
+ .crossings = crossings};
+ }
+ qsort(candidates, (size_t)candidate_count, sizeof(*candidates), ap_path_candidate_compare);
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ /* Prefer different first-hop branches, then fill spare slots with
+ * other deep witnesses. Depth storage can now track selected branches. */
+ memset(depth, 0, ((size_t)c->n + 1) * sizeof(int));
+ int selection[32], selected = 0, available = c->options.max_paths - produced;
+ for (int pass = 0; pass < 2 && selected < available; pass++) {
+ for (int i = 0; i < candidate_count && selected < available; i++) {
+ ap_path_candidate *candidate = &candidates[i];
+ if (candidate->selected || (pass == 0 && depth[candidate->first_hop]))
+ continue;
+ depth[candidate->first_hop] = 1;
+ candidate->selected = true;
+ selection[selected++] = candidate->node;
+ }
+ }
+ if (candidate_count > selected)
+ *truncated = true;
+ for (int selected_index = 0; selected_index < selected; selected_index++) {
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ int node = selection[selected_index];
+ int chain[17], length = 0, current = node;
+ while (previous[current] >= 0 && length < 16) {
+ chain[length++] = previous[current];
+ current = c->edges[previous[current]].source;
+ }
+ yyjson_mut_val *path = yyjson_mut_obj(doc), *nodes = yyjson_mut_arr(doc),
+ *edges = yyjson_mut_arr(doc);
+ yyjson_mut_obj_add_sint(doc, path, "entrypoint_id", c->nodes[entry].id);
+ yyjson_mut_arr_add_val(nodes, ap_symbol(doc, c, entry));
+ for (int j = length - 1; j >= 0; j--) {
+ ap_edge *edge = &c->edges[chain[j]];
+ yyjson_mut_arr_add_val(nodes, ap_symbol(doc, c, edge->target));
+ yyjson_mut_arr_add_val(edges, ap_path_edge(doc, c, chain[j]));
+ }
+ yyjson_mut_obj_add_val(doc, path, "nodes", nodes);
+ yyjson_mut_obj_add_val(doc, path, "edges", edges);
+ yyjson_mut_arr_add_val(paths, path);
+ produced++;
+ }
+ }
+done:
+ free(offset);
+ free(adj);
+ free(cursor);
+ free(queue);
+ free(previous);
+ free(depth);
+ free(candidates);
+ return rc;
+}
+
+static const char *ap_component_basis(const ap_context *c, int i) {
+ const ap_component *p = &c->components[i];
+ return p->atoms > 1 ? "interaction_community"
+ : c->nodes[p->representative].declared ? "declared_module"
+ : "unassigned";
+}
+
+static int ap_overview(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root) {
+ yyjson_mut_val *overview = yyjson_mut_obj(doc), *groups = yyjson_mut_arr(doc),
+ *parts = yyjson_mut_arr(doc), *connections = yyjson_mut_arr(doc),
+ *totals = yyjson_mut_obj(doc), *limits = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, root, "overview", overview);
+ yyjson_mut_obj_add_str(doc, overview, "grouping_basis", "common_source_directory_aggregate");
+ yyjson_mut_obj_add_int(doc, overview, "grouping_depth", c->grouping_depth);
+ yyjson_mut_obj_add_val(doc, overview, "groups", groups);
+ yyjson_mut_obj_add_val(doc, overview, "components", parts);
+ yyjson_mut_obj_add_val(doc, overview, "connections", connections);
+ yyjson_mut_obj_add_val(doc, overview, "totals", totals);
+ yyjson_mut_obj_add_val(doc, overview, "limits", limits);
+ int connection_count = 0, shown = 0;
+ if (!c->limited) {
+ for (int g = 0; g < c->group_count; g++) {
+ ap_overview_group *group = &c->groups[g];
+ yyjson_mut_val *value = yyjson_mut_obj(doc), *ids = yyjson_mut_arr(doc),
+ *reps = yyjson_mut_arr(doc);
+ yyjson_mut_obj_add_strcpy(doc, value, "id", group->id);
+ yyjson_mut_obj_add_strcpy(doc, value, "label", group->label);
+ yyjson_mut_obj_add_str(doc, value, "role", group->test ? "test" : "non_test");
+ yyjson_mut_obj_add_str(doc, value, "basis", "common_source_directory_aggregate");
+ yyjson_mut_obj_add_int(doc, value, "component_count", group->components);
+ yyjson_mut_obj_add_int(doc, value, "member_count", group->members);
+ yyjson_mut_obj_add_int(doc, value, "file_count", group->files);
+ int samples = 0;
+ for (int i = 0; i < c->component_count; i++)
+ if (c->components[i].overview_group == g) {
+ char id[48];
+ ap_component_id(c, i, id);
+ yyjson_mut_arr_add_strcpy(doc, ids, id);
+ if (samples++ < 1)
+ yyjson_mut_arr_add_val(reps,
+ ap_symbol(doc, c, c->components[i].representative));
+ }
+ yyjson_mut_obj_add_val(doc, value, "component_ids", ids);
+ yyjson_mut_obj_add_val(doc, value, "representatives", reps);
+ yyjson_mut_obj_add_int(doc, value, "omitted_representatives",
+ group->components - (group->components > 0 ? 1 : 0));
+ yyjson_mut_arr_add_val(groups, value);
+ if (ap_stopped(c))
+ return CBM_STORE_ERR;
+ }
+ for (int i = 0; i < c->component_count; i++) {
+ ap_component *part = &c->components[i];
+ yyjson_mut_val *value = yyjson_mut_obj(doc), *reps = yyjson_mut_arr(doc);
+ char id[48];
+ ap_component_id(c, i, id);
+ yyjson_mut_obj_add_strcpy(doc, value, "id", id);
+ yyjson_mut_obj_add_strcpy(doc, value, "label", c->nodes[part->representative].name);
+ yyjson_mut_obj_add_strcpy(doc, value, "group_id", c->groups[part->overview_group].id);
+ yyjson_mut_obj_add_str(doc, value, "basis", ap_component_basis(c, i));
+ yyjson_mut_obj_add_str(doc, value, "role",
+ c->nodes[part->root].test ? "test" : "non_test");
+ yyjson_mut_obj_add_int(doc, value, "member_count", part->members);
+ yyjson_mut_obj_add_int(doc, value, "file_count", part->files);
+ for (int j = 0; j < part->sample_count && j < 1; j++)
+ yyjson_mut_arr_add_val(reps, ap_symbol(doc, c, part->samples[j]));
+ yyjson_mut_obj_add_val(doc, value, "representatives", reps);
+ yyjson_mut_obj_add_int(doc, value, "omitted_members",
+ part->members - (part->sample_count > 0 ? 1 : 0));
+ yyjson_mut_arr_add_val(parts, value);
+ if ((i & 255) == 0 && ap_stopped(c))
+ return CBM_STORE_ERR;
+ }
+ ap_dep *edges = malloc(((size_t)c->m + 1) * sizeof(*edges));
+ if (!edges)
+ return CBM_STORE_ERR;
+ int count = 0;
+ for (int i = 0; i < c->m; i++) {
+ ap_edge *edge = &c->edges[i];
+ int a = c->nodes[edge->source].component, b = c->nodes[edge->target].component;
+ if (a >= 0 && b >= 0 && ap_dependency(edge->type))
+ edges[count++] = (ap_dep){c->components[a].overview_group,
+ c->components[b].overview_group, edge->type, i};
+ }
+ qsort(edges, (size_t)count, sizeof(*edges), ap_dep_compare);
+ for (int i = 0; i < count;) {
+ int end = i + 1;
+ while (end < count && edges[end].source == edges[i].source &&
+ edges[end].target == edges[i].target && edges[end].type == edges[i].type)
+ end++;
+ connection_count++;
+ if (shown < 4096) {
+ yyjson_mut_val *value = yyjson_mut_obj(doc), *witnesses = yyjson_mut_arr(doc);
+ yyjson_mut_obj_add_strcpy(doc, value, "source", c->groups[edges[i].source].id);
+ yyjson_mut_obj_add_strcpy(doc, value, "target", c->groups[edges[i].target].id);
+ yyjson_mut_obj_add_str(doc, value, "type", ap_types[edges[i].type]);
+ yyjson_mut_obj_add_int(doc, value, "count", end - i);
+ yyjson_mut_arr_add_val(witnesses, ap_witness(doc, c, edges[i].edge));
+ yyjson_mut_obj_add_val(doc, value, "witnesses", witnesses);
+ yyjson_mut_obj_add_int(doc, value, "omitted_witnesses", end - i - 1);
+ yyjson_mut_arr_add_val(connections, value);
+ shown++;
+ }
+ i = end;
+ if (ap_stopped(c)) {
+ free(edges);
+ return CBM_STORE_ERR;
+ }
+ }
+ free(edges);
+ }
+ yyjson_mut_obj_add_bool(doc, overview, "complete", !c->limited && shown == connection_count);
+ yyjson_mut_obj_add_int(doc, totals, "groups", c->limited ? 0 : c->group_count);
+ yyjson_mut_obj_add_int(doc, totals, "components", c->limited ? 0 : c->component_count);
+ yyjson_mut_obj_add_int(doc, totals, "accounted_nodes", c->limited ? 0 : c->accounted);
+ yyjson_mut_obj_add_int(doc, totals, "connections", connection_count);
+ yyjson_mut_obj_add_int(doc, limits, "omitted_connections", connection_count - shown);
+ return CBM_STORE_OK;
+}
+
+/* SCCs here are on the displayed symbol corridor, never on aggregates. */
+static int ap_symbol_cycles(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *cycles,
+ const int *out, const int *in, const int *forward, const int *reverse,
+ const bool *nodes, const bool *edges) {
+ int *stack = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *cursor = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *order = malloc(((size_t)c->n + 1) * sizeof(int));
+ bool *seen = calloc((size_t)c->n + 1, sizeof(bool));
+ if (!stack || !cursor || !order || !seen) {
+ free(stack);
+ free(cursor);
+ free(order);
+ free(seen);
+ return CBM_STORE_ERR;
+ }
+ memcpy(cursor, out, ((size_t)c->n + 1) * sizeof(int));
+ int count = 0, rc = CBM_STORE_OK;
+ for (int start = 0; start < c->n; start++)
+ if (nodes[start] && !seen[start]) {
+ int top = 0;
+ stack[top++] = start;
+ seen[start] = true;
+ while (top) {
+ int node = stack[top - 1];
+ bool pushed = false;
+ while (cursor[node] < out[node + 1]) {
+ int e = forward[cursor[node]++], next = c->edges[e].target;
+ if (edges[e] && !seen[next]) {
+ seen[next] = true;
+ stack[top++] = next;
+ pushed = true;
+ break;
+ }
+ }
+ if (!pushed) {
+ order[count++] = node;
+ top--;
+ }
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ }
+ memset(seen, 0, ((size_t)c->n + 1) * sizeof(bool));
+ for (int i = count - 1; i >= 0; i--)
+ if (!seen[order[i]]) {
+ int top = 0, members = 0;
+ bool self = false;
+ stack[top++] = order[i];
+ seen[order[i]] = true;
+ yyjson_mut_val *ids = yyjson_mut_arr(doc);
+ while (top) {
+ int node = stack[--top];
+ members++;
+ yyjson_mut_arr_add_sint(doc, ids, c->nodes[node].id);
+ for (int j = in[node]; j < in[node + 1]; j++) {
+ int e = reverse[j], next = c->edges[e].source;
+ if (!edges[e])
+ continue;
+ if (next == node)
+ self = true;
+ if (!seen[next]) {
+ seen[next] = true;
+ stack[top++] = next;
+ }
+ }
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ if (members > 1 || self) {
+ yyjson_mut_val *cycle = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, cycle, "node_ids", ids);
+ yyjson_mut_arr_add_val(cycles, cycle);
+ }
+ }
+done:
+ free(stack);
+ free(cursor);
+ free(order);
+ free(seen);
+ return rc;
+}
+
+static int ap_behavior(ap_context *c, yyjson_mut_doc *doc, yyjson_mut_val *root,
+ yyjson_mut_val *paths) {
+ yyjson_mut_val *view = yyjson_mut_obj(doc), *targets = yyjson_mut_arr(doc),
+ *nodes = yyjson_mut_arr(doc), *edges = yyjson_mut_arr(doc),
+ *cycles = yyjson_mut_arr(doc), *limits = yyjson_mut_arr(doc),
+ *totals = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_val(doc, root, "behavior", view);
+ yyjson_mut_obj_add_str(doc, view, "mode", c->options.target_node_id ? "corridor" : "targets");
+ yyjson_mut_obj_add_sint(doc, view, "source_id", c->options.entry_node_id);
+ if (c->options.target_node_id)
+ yyjson_mut_obj_add_sint(doc, view, "target_id", c->options.target_node_id);
+ yyjson_mut_obj_add_int(doc, view, "max_hops", c->options.max_depth);
+ yyjson_mut_obj_add_val(doc, view, "reachable_targets", targets);
+ yyjson_mut_obj_add_val(doc, view, "nodes", nodes);
+ yyjson_mut_obj_add_val(doc, view, "edges", edges);
+ yyjson_mut_obj_add_val(doc, view, "cycles", cycles);
+ yyjson_mut_obj_add_val(doc, view, "limits_hit", limits);
+ yyjson_mut_obj_add_val(doc, view, "totals", totals);
+ int entry = ap_find(c, c->options.entry_node_id),
+ target = ap_find(c, c->options.target_node_id);
+ bool valid = !c->limited && entry >= 0 && c->nodes[entry].component >= 0;
+ if (!valid || (c->options.target_node_id && (target < 0 || c->nodes[target].component < 0))) {
+ yyjson_mut_obj_add_bool(doc, view, "complete", false);
+ yyjson_mut_obj_add_bool(doc, view, "corridor_complete", false);
+ yyjson_mut_arr_add_str(doc, limits,
+ c->limited ? "analysis_budget"
+ : !valid ? "select_source"
+ : "target_not_found");
+ yyjson_mut_obj_add_int(doc, totals, "reachable_nodes", 0);
+ yyjson_mut_obj_add_int(doc, totals, "corridor_nodes", 0);
+ yyjson_mut_obj_add_int(doc, totals, "corridor_edges", 0);
+ return CBM_STORE_OK;
+ }
+ int *out = calloc((size_t)c->n + 2, sizeof(int)), *in = calloc((size_t)c->n + 2, sizeof(int));
+ int *forward = malloc(((size_t)c->m + 1) * sizeof(int)),
+ *reverse = malloc(((size_t)c->m + 1) * sizeof(int));
+ int *queue = malloc(((size_t)c->n + 1) * sizeof(int)),
+ *cursor = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *distance = malloc(((size_t)c->n + 1) * sizeof(int)),
+ *back = malloc(((size_t)c->n + 1) * sizeof(int));
+ int *previous = malloc(((size_t)c->n + 1) * sizeof(int)),
+ *next = malloc(((size_t)c->n + 1) * sizeof(int));
+ bool *keep_nodes = calloc((size_t)c->n + 1, sizeof(bool)),
+ *keep_edges = calloc((size_t)c->m + 1, sizeof(bool));
+ int rc = CBM_STORE_OK, reachable = 0, kept_nodes = 0, kept_edges = 0, target_count = 0;
+ bool complete = true, corridor_complete = true;
+ if (!out || !in || !forward || !reverse || !queue || !cursor || !distance || !back ||
+ !previous || !next || !keep_nodes || !keep_edges) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ for (int i = 0; i < c->n; i++)
+ distance[i] = back[i] = previous[i] = next[i] = -1;
+ for (int i = 0; i < c->m; i++)
+ if (ap_execution(c->edges[i].type)) {
+ out[c->edges[i].source + 1]++;
+ in[c->edges[i].target + 1]++;
+ }
+ for (int i = 0; i < c->n; i++) {
+ out[i + 1] += out[i];
+ in[i + 1] += in[i];
+ }
+ memcpy(cursor, out, ((size_t)c->n + 1) * sizeof(int));
+ for (int i = 0; i < c->m; i++)
+ if (ap_execution(c->edges[i].type))
+ forward[cursor[c->edges[i].source]++] = i;
+ memcpy(cursor, in, ((size_t)c->n + 1) * sizeof(int));
+ for (int i = 0; i < c->m; i++)
+ if (ap_execution(c->edges[i].type))
+ reverse[cursor[c->edges[i].target]++] = i;
+ int head = 0, tail = 0;
+ queue[tail++] = entry;
+ distance[entry] = 0;
+ while (head < tail) {
+ int node = queue[head++];
+ if (node != entry) {
+ reachable++;
+ if (target_count < c->options.max_targets || node == target) {
+ yyjson_mut_val *symbol = ap_symbol(doc, c, node);
+ yyjson_mut_obj_add_int(doc, symbol, "distance", distance[node]);
+ yyjson_mut_arr_add_val(targets, symbol);
+ target_count++;
+ }
+ }
+ if (distance[node] < c->options.max_depth)
+ for (int j = out[node]; j < out[node + 1]; j++) {
+ int edge = forward[j], other = c->edges[edge].target;
+ if (distance[other] < 0) {
+ distance[other] = distance[node] + 1;
+ previous[other] = edge;
+ queue[tail++] = other;
+ }
+ }
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ if (reachable > target_count) {
+ complete = false;
+ yyjson_mut_arr_add_str(doc, limits, "target_catalog_budget");
+ }
+ if (c->options.target_node_id) {
+ head = tail = 0;
+ queue[tail++] = target;
+ back[target] = 0;
+ while (head < tail) {
+ int node = queue[head++];
+ if (back[node] < c->options.max_depth)
+ for (int j = in[node]; j < in[node + 1]; j++) {
+ int edge = reverse[j], other = c->edges[edge].source;
+ if (back[other] < 0) {
+ back[other] = back[node] + 1;
+ next[other] = edge;
+ queue[tail++] = other;
+ }
+ }
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ for (int i = 0; i < c->n; i++)
+ if (distance[i] >= 0 && back[i] >= 0 && distance[i] + back[i] <= c->options.max_depth) {
+ keep_nodes[i] = true;
+ kept_nodes++;
+ }
+ for (int i = 0; i < c->m; i++) {
+ ap_edge *edge = &c->edges[i];
+ if (ap_execution(edge->type) && distance[edge->source] >= 0 &&
+ back[edge->target] >= 0 &&
+ distance[edge->source] + 1 + back[edge->target] <= c->options.max_depth) {
+ keep_edges[i] = true;
+ kept_edges++;
+ }
+ }
+ if (kept_nodes > c->options.max_corridor_nodes ||
+ kept_edges > c->options.max_corridor_edges) {
+ complete = corridor_complete = false;
+ yyjson_mut_arr_add_str(doc, limits, "corridor_budget");
+ /* Abstain instead of returning a broken graph with hidden joins. */
+ } else {
+ c->evidence_scope = AP_EVIDENCE_CORRIDOR;
+ for (int i = 0; i < c->n; i++)
+ if (keep_nodes[i])
+ yyjson_mut_arr_add_val(nodes, ap_symbol(doc, c, i));
+ for (int i = 0; i < c->m; i++)
+ if (keep_edges[i]) {
+ yyjson_mut_arr_add_val(edges, ap_path_edge(doc, c, i));
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ if (ap_symbol_cycles(c, doc, cycles, out, in, forward, reverse, keep_nodes,
+ keep_edges) != CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ /* Each witness joins a shortest prefix, a real corridor edge, and
+ * a shortest suffix. These bounded graph walks may revisit a node;
+ * they never imply feasible branch conditions or runtime order. */
+ c->evidence_scope = AP_EVIDENCE_PATH;
+ int saved[32][16], lengths[32], produced = 0;
+ for (int e = -1; e < c->m && produced < c->options.max_paths; e++) {
+ if (e < 0 && distance[target] < 0)
+ continue;
+ if (e >= 0 && !keep_edges[e])
+ continue;
+ int chain[16], prefix[16], length = 0, before = 0;
+ int node = e < 0 ? target : c->edges[e].source;
+ while (previous[node] >= 0 && before < 16) {
+ prefix[before++] = previous[node];
+ node = c->edges[previous[node]].source;
+ }
+ for (int i = before - 1; i >= 0; i--)
+ chain[length++] = prefix[i];
+ if (e >= 0) {
+ chain[length++] = e;
+ node = c->edges[e].target;
+ while (next[node] >= 0 && length < 16) {
+ chain[length++] = next[node];
+ node = c->edges[next[node]].target;
+ }
+ }
+ bool duplicate = false;
+ for (int i = 0; i < produced; i++)
+ if (lengths[i] == length &&
+ !memcmp(saved[i], chain, (size_t)length * sizeof(int)))
+ duplicate = true;
+ if (duplicate)
+ continue;
+ memcpy(saved[produced], chain, (size_t)length * sizeof(int));
+ lengths[produced++] = length;
+ yyjson_mut_val *path = yyjson_mut_obj(doc), *pn = yyjson_mut_arr(doc),
+ *pe = yyjson_mut_arr(doc);
+ yyjson_mut_obj_add_sint(doc, path, "entrypoint_id", c->nodes[entry].id);
+ yyjson_mut_arr_add_val(pn, ap_symbol(doc, c, entry));
+ for (int i = 0; i < length; i++) {
+ yyjson_mut_arr_add_val(pn, ap_symbol(doc, c, c->edges[chain[i]].target));
+ yyjson_mut_arr_add_val(pe, ap_path_edge(doc, c, chain[i]));
+ }
+ yyjson_mut_obj_add_val(doc, path, "nodes", pn);
+ yyjson_mut_obj_add_val(doc, path, "edges", pe);
+ yyjson_mut_arr_add_val(paths, path);
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ }
+ yyjson_mut_obj_add_bool(doc, view, "reachable", distance[target] >= 0);
+ }
+ yyjson_mut_obj_add_bool(doc, view, "complete", complete);
+ yyjson_mut_obj_add_bool(doc, view, "corridor_complete", corridor_complete);
+ yyjson_mut_obj_add_int(doc, totals, "reachable_nodes", reachable);
+ yyjson_mut_obj_add_int(doc, totals, "omitted_targets", reachable - target_count);
+ yyjson_mut_obj_add_int(doc, totals, "corridor_nodes", kept_nodes);
+ yyjson_mut_obj_add_int(doc, totals, "corridor_edges", kept_edges);
+done:
+ c->evidence_scope = AP_EVIDENCE_CONTEXT;
+ free(out);
+ free(in);
+ free(forward);
+ free(reverse);
+ free(queue);
+ free(cursor);
+ free(distance);
+ free(back);
+ free(previous);
+ free(next);
+ free(keep_nodes);
+ free(keep_edges);
+ return rc;
+}
+
+static int ap_render(ap_context *c, const char *project, char **out_json) {
+ memset(c->evidence_bytes, 0, sizeof(c->evidence_bytes));
+ c->evidence_scope = AP_EVIDENCE_CONTEXT;
+ c->evidence_omitted = false;
+ c->cycle_count = c->omitted_cycles = 0;
+ ap_json_budget budget = {0};
+ yyjson_alc allocator = {ap_json_malloc, ap_json_realloc, ap_json_free, &budget};
+ yyjson_mut_doc *doc = yyjson_mut_doc_new(&allocator);
+ if (!doc)
+ return CBM_STORE_ERR;
+ yyjson_mut_val *root = yyjson_mut_obj(doc);
+ yyjson_mut_doc_set_root(doc, root);
+ yyjson_mut_val *parts = yyjson_mut_arr(doc), *dependencies = yyjson_mut_arr(doc),
+ *cycles = yyjson_mut_arr(doc), *entries = yyjson_mut_arr(doc),
+ *paths = yyjson_mut_arr(doc), *warnings = yyjson_mut_arr(doc),
+ *totals = yyjson_mut_obj(doc), *limits = yyjson_mut_obj(doc);
+ yyjson_mut_obj_add_int(doc, root, "schema_version", 1);
+ yyjson_mut_obj_add_str(doc, root, "kind", "static_projection");
+ yyjson_mut_obj_add_strcpy(doc, root, "project", project);
+ yyjson_mut_obj_add_val(doc, root, "components", parts);
+ yyjson_mut_obj_add_val(doc, root, "dependencies", dependencies);
+ yyjson_mut_obj_add_val(doc, root, "cycles", cycles);
+ yyjson_mut_obj_add_val(doc, root, "entrypoints", entries);
+ yyjson_mut_obj_add_val(doc, root, "paths", paths);
+ yyjson_mut_obj_add_val(doc, root, "warnings", warnings);
+ yyjson_mut_obj_add_val(doc, root, "totals", totals);
+ yyjson_mut_obj_add_val(doc, root, "limits", limits);
+ int shown = 0, dependency_count = 0, dependency_shown = 0, entry_count = 0, entry_total = 0;
+ int entry_indexes[AP_ENTRYPOINTS];
+ bool paths_truncated = false;
+ int rc = CBM_STORE_OK;
+ ap_dep *deps = NULL;
+ if (ap_overview(c, doc, root) != CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ if (!c->limited) {
+ /* Prefer the largest connected candidates, retaining deterministic IDs.
+ * Never relabel discarded components as a single invented component. */
+ ap_rank *ranks = malloc(((size_t)c->component_count + 1) * sizeof(*ranks));
+ if (!ranks) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ for (int i = 0; i < c->component_count; i++) {
+ c->components[i].displayed = -1;
+ ranks[i] = (ap_rank){i, c->components[i].members, c->components[i].degree};
+ }
+ qsort(ranks, (size_t)c->component_count, sizeof(*ranks), ap_rank_compare);
+ for (int pick = 0; pick < c->options.max_components && pick < c->component_count; pick++)
+ c->components[ranks[pick].index].displayed = shown++;
+ free(ranks);
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ for (int i = 0; i < c->component_count; i++) {
+ ap_component *p = &c->components[i];
+ if (p->displayed < 0)
+ continue;
+ yyjson_mut_val *part = yyjson_mut_obj(doc), *representatives = yyjson_mut_arr(doc);
+ char id[48];
+ ap_component_id(c, i, id);
+ yyjson_mut_obj_add_strcpy(doc, part, "id", id);
+ yyjson_mut_obj_add_strcpy(doc, part, "label", c->nodes[p->representative].name);
+ yyjson_mut_obj_add_str(doc, part, "basis",
+ p->atoms > 1 ? "interaction_community"
+ : c->nodes[p->representative].declared ? "declared_module"
+ : "unassigned");
+ yyjson_mut_obj_add_int(doc, part, "member_count", p->members);
+ yyjson_mut_obj_add_int(doc, part, "file_count", p->files);
+ yyjson_mut_obj_add_int(doc, part, "atom_count", p->atoms);
+ bool test = c->nodes[p->root].test;
+ yyjson_mut_obj_add_str(doc, part, "role", test ? "test" : "non_test");
+ yyjson_mut_obj_add_str(doc, part, "role_basis",
+ !test ? "no_test_evidence"
+ : c->nodes[p->root].test_property ? "indexed_is_test"
+ : "test_path_convention");
+ for (int j = 0; j < p->sample_count && j < 1; j++)
+ yyjson_mut_arr_add_val(representatives, ap_symbol(doc, c, p->samples[j]));
+ yyjson_mut_obj_add_val(doc, part, "representatives", representatives);
+ yyjson_mut_obj_add_int(doc, part, "omitted_members",
+ p->members - (p->sample_count > 0 ? 1 : 0));
+ yyjson_mut_arr_add_val(parts, part);
+ }
+ deps = malloc(((size_t)c->m + 1) * sizeof(*deps));
+ if (!deps) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ int count = 0;
+ for (int i = 0; i < c->m; i++) {
+ ap_edge *e = &c->edges[i];
+ int a = c->nodes[e->source].component, b = c->nodes[e->target].component;
+ if (a >= 0 && b >= 0 && a != b && ap_dependency(e->type))
+ deps[count++] = (ap_dep){a, b, e->type, i};
+ }
+ qsort(deps, (size_t)count, sizeof(*deps), ap_dep_compare);
+ for (int i = 0; i < count;) {
+ int end = i + 1;
+ while (end < count && deps[end].source == deps[i].source &&
+ deps[end].target == deps[i].target && deps[end].type == deps[i].type)
+ end++;
+ dependency_count++;
+ if (dependency_shown < c->options.max_dependencies &&
+ c->components[deps[i].source].displayed >= 0 &&
+ c->components[deps[i].target].displayed >= 0) {
+ yyjson_mut_val *dep = yyjson_mut_obj(doc), *witnesses = yyjson_mut_arr(doc);
+ char a[48], b[48];
+ ap_component_id(c, deps[i].source, a);
+ ap_component_id(c, deps[i].target, b);
+ yyjson_mut_obj_add_strcpy(doc, dep, "source", a);
+ yyjson_mut_obj_add_strcpy(doc, dep, "target", b);
+ yyjson_mut_obj_add_str(doc, dep, "type", ap_types[deps[i].type]);
+ yyjson_mut_obj_add_int(doc, dep, "count", end - i);
+ yyjson_mut_arr_add_val(witnesses, ap_witness(doc, c, deps[i].edge));
+ yyjson_mut_obj_add_val(doc, dep, "witnesses", witnesses);
+ yyjson_mut_obj_add_int(doc, dep, "omitted_witnesses", end - i - 1);
+ yyjson_mut_arr_add_val(dependencies, dep);
+ dependency_shown++;
+ }
+ i = end;
+ if (ap_stopped(c)) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ }
+ if (ap_cycles(c, doc, cycles, deps, count) != CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ for (int i = 0; i < c->n; i++) {
+ ap_node *node = &c->nodes[i];
+ if (node->component < 0)
+ continue;
+ if (node->entry) {
+ entry_total++;
+ if (entry_count < AP_ENTRYPOINTS) {
+ entry_indexes[entry_count++] = i;
+ c->evidence_scope = node->id == c->options.entry_node_id ? AP_EVIDENCE_PATH
+ : AP_EVIDENCE_CONTEXT;
+ yyjson_mut_arr_add_val(entries, ap_symbol(doc, c, i));
+ c->evidence_scope = AP_EVIDENCE_CONTEXT;
+ }
+ }
+ }
+ c->evidence_scope = AP_EVIDENCE_PATH;
+ if (c->options.target_node_id) {
+ /* The target query produces exact endpoint witnesses below. */
+ } else if (c->options.entry_node_id) {
+ int selected = ap_find(c, c->options.entry_node_id);
+ if (selected >= 0 && c->nodes[selected].component >= 0) {
+ if (ap_paths(c, doc, paths, &selected, 1, &paths_truncated) != CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ } else
+ yyjson_mut_arr_add_str(
+ doc, warnings,
+ "The selected entry point is absent from this indexed generation.");
+ } else if (ap_paths(c, doc, paths, entry_indexes, entry_count, &paths_truncated) !=
+ CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ c->evidence_scope = AP_EVIDENCE_CONTEXT;
+ }
+ if (ap_behavior(c, doc, root, paths) != CBM_STORE_OK) {
+ rc = CBM_STORE_ERR;
+ goto done;
+ }
+ yyjson_mut_obj_add_str(doc, root, "status", c->limited ? "limited" : "ready");
+ bool complete =
+ !c->limited && shown == c->component_count && dependency_shown == dependency_count;
+ yyjson_mut_obj_add_bool(doc, root, "complete", complete);
+ yyjson_mut_obj_add_sint(doc, totals, "nodes", c->total_nodes);
+ yyjson_mut_obj_add_sint(doc, totals, "files", c->total_files);
+ yyjson_mut_obj_add_sint(doc, totals, "edges", c->total_edges);
+ yyjson_mut_obj_add_int(doc, totals, "accounted_nodes", c->limited ? 0 : c->accounted);
+ yyjson_mut_obj_add_int(doc, totals, "structural_nodes", c->limited ? 0 : c->structural);
+ yyjson_mut_obj_add_int(doc, totals, "components", c->limited ? 0 : c->component_count);
+ yyjson_mut_obj_add_int(doc, totals, "dependencies", dependency_count);
+ yyjson_mut_obj_add_int(doc, totals, "entrypoints", entry_total);
+ yyjson_mut_obj_add_int(doc, totals, "cycles", c->limited ? 0 : c->cycle_count);
+ yyjson_mut_obj_add_int(doc, totals, "relationship_edges",
+ c->limited ? 0 : c->relationship_edges);
+ yyjson_mut_obj_add_int(doc, totals, "unmodeled_edges", c->limited ? 0 : c->unmodeled_edges);
+ yyjson_mut_obj_add_int(doc, limits, "node_budget", c->options.max_nodes);
+ yyjson_mut_obj_add_int(doc, limits, "edge_budget", c->options.max_edges);
+ yyjson_mut_obj_add_int(doc, limits, "omitted_components",
+ c->limited ? 0 : c->component_count - shown);
+ yyjson_mut_obj_add_int(doc, limits, "omitted_dependencies",
+ dependency_count - dependency_shown);
+ yyjson_mut_obj_add_int(doc, limits, "omitted_entrypoints", entry_total - entry_count);
+ yyjson_mut_obj_add_int(doc, limits, "omitted_cycles", c->limited ? 0 : c->omitted_cycles);
+ yyjson_mut_obj_add_bool(doc, limits, "paths_truncated", paths_truncated);
+ yyjson_mut_obj_add_int(doc, limits, "path_depth", c->options.max_depth);
+ yyjson_mut_obj_add_uint(doc, root, "elapsed_ms", cbm_now_ms() - c->started);
+ yyjson_mut_arr_add_str(
+ doc, warnings,
+ "Component candidates are inferred from indexed declarations and interactions; they do not "
+ "establish intended responsibilities or deployment boundaries.");
+ yyjson_mut_arr_add_str(
+ doc, warnings,
+ "Paths are bounded static witnesses, not observed executions. Callback references are not "
+ "invocation evidence. Index coverage gaps remain possible.");
+ if (c->unmodeled_edges && !c->limited)
+ yyjson_mut_arr_add_str(doc, warnings,
+ "Some indexed edge types are outside this projection's relationship "
+ "vocabulary; see unmodeled_edges. Similarity and change-history "
+ "edges are not structural interactions.");
+ if (c->limited)
+ yyjson_mut_arr_add_str(doc, warnings, c->limited);
+ if (!complete && !c->limited)
+ yyjson_mut_arr_add_str(doc, warnings,
+ "The displayed projection is capped; totals include omitted "
+ "components and dependencies.");
+ if (c->omitted_cycles && !c->limited)
+ yyjson_mut_arr_add_str(
+ doc, warnings,
+ "Dependency cycles involving omitted components are not drawn; see omitted_cycles.");
+ if (c->options.include_behavior_evidence) {
+ bool evidence_limited =
+ c->evidence_omitted || c->metadata_budget.failed || c->evidence_suppressed;
+ yyjson_mut_obj_add_bool(doc, limits, "behavior_evidence_budget_hit", evidence_limited);
+ if (c->evidence_suppressed)
+ yyjson_mut_arr_add_str(doc, warnings,
+ "Optional behavior evidence was omitted entirely to keep the "
+ "base graph within the response memory budget.");
+ else if (evidence_limited)
+ yyjson_mut_arr_add_str(
+ doc, warnings,
+ "Optional behavior evidence was omitted from some symbols or calls after reaching "
+ "its memory budget; absent fields remain unknown.");
+ }
+ if (budget.failed)
+ rc = CBM_STORE_SCAN_LIMIT;
+ else {
+ *out_json =
+ yyjson_mut_write_opts(doc, YYJSON_WRITE_ALLOW_INVALID_UNICODE, &allocator, NULL, NULL);
+ if (!*out_json)
+ rc = budget.failed ? CBM_STORE_SCAN_LIMIT : CBM_STORE_ERR;
+ }
+done:
+ free(deps);
+ yyjson_mut_doc_free(doc);
+ return rc;
+}
+
+int cbm_store_architecture_projection(cbm_store_t *store, const char *project,
+ const cbm_architecture_projection_options_t *options,
+ char **out_json) {
+ if (!store || !project || !project[0] || !out_json)
+ return CBM_STORE_ERR;
+ *out_json = NULL;
+ ap_context c = {.db = cbm_store_get_db(store), .started = cbm_now_ms()};
+ if (options)
+ c.options = *options;
+ if (c.options.entry_node_id < 0 || c.options.target_node_id < 0 ||
+ (c.options.target_node_id && !c.options.entry_node_id))
+ return CBM_STORE_ERR;
+ c.options.max_nodes = ap_bound(c.options.max_nodes, 100000, 250000);
+ c.options.max_edges = ap_bound(c.options.max_edges, 500000, 1000000);
+ c.options.max_components = ap_bound(c.options.max_components, 256, 512);
+ c.options.max_dependencies = ap_bound(c.options.max_dependencies, 2048, 4096);
+ c.options.max_paths = ap_bound(c.options.max_paths, 12, 32);
+ c.options.max_depth = ap_bound(c.options.max_depth, 10, 16);
+ c.options.max_targets = ap_bound(c.options.max_targets, 256, 1024);
+ c.options.max_corridor_nodes = ap_bound(c.options.max_corridor_nodes, 1024, 4096);
+ c.options.max_corridor_edges = ap_bound(c.options.max_corridor_edges, 4096, 16384);
+ if (!c.options.deadline_ms)
+ c.options.deadline_ms = c.started + 5000;
+ if (ap_stopped(&c))
+ return c.cancelled ? CBM_STORE_CANCELLED : CBM_STORE_SCAN_LIMIT;
+ /* Own a read transaction only when the caller has not established one. */
+ bool transaction = sqlite3_get_autocommit(c.db) != 0;
+ sqlite3_progress_handler(c.db, 1000, ap_progress, &c);
+ int rc = transaction && sqlite3_exec(c.db, "BEGIN", NULL, NULL, NULL) != SQLITE_OK
+ ? CBM_STORE_ERR
+ : CBM_STORE_OK;
+ if (rc == CBM_STORE_OK)
+ rc = ap_counts(&c, project);
+ if (rc == CBM_STORE_OK && !c.limited)
+ rc = ap_load(&c, project);
+ if (rc == CBM_STORE_OK && !c.limited)
+ rc = ap_ownership(&c);
+ if (rc == CBM_STORE_OK && !c.limited)
+ rc = ap_components(&c);
+ if (rc == CBM_STORE_OK && !c.limited)
+ rc = ap_overview_grouping(&c);
+ if (c.expired) {
+ c.limited = "Analysis reached its deadline; no partial architecture was inferred.";
+ rc = CBM_STORE_OK;
+ }
+ if (c.limited && !c.cancelled)
+ rc = CBM_STORE_OK;
+ if (rc == CBM_STORE_OK && !c.cancelled)
+ rc = ap_render(&c, project, out_json);
+ if (rc == CBM_STORE_SCAN_LIMIT && c.options.include_behavior_evidence && !c.limited &&
+ !c.expired && !c.cancelled && !*out_json) {
+ /* Reuse the loaded graph. Optional evidence must not turn a renderable
+ * base projection into an empty architecture or trigger another scan. */
+ c.evidence_suppressed = true;
+ rc = ap_render(&c, project, out_json);
+ }
+ if ((rc == CBM_STORE_SCAN_LIMIT || c.expired) && !c.cancelled && !*out_json) {
+ c.limited = c.expired
+ ? "Analysis reached its deadline; no partial architecture was inferred."
+ : "The architecture response exceeded its memory budget; narrow the "
+ "requested projection.";
+ rc = ap_render(&c, project, out_json);
+ }
+ sqlite3_progress_handler(c.db, 0, NULL, NULL);
+ sqlite3_finalize(c.provenance);
+ sqlite3_finalize(c.symbol_metadata);
+ if (transaction)
+ sqlite3_exec(c.db, "ROLLBACK", NULL, NULL, NULL);
+ for (int i = 0; i < c.n; i++) {
+ free(c.nodes[i].name);
+ free(c.nodes[i].qn);
+ free(c.nodes[i].file);
+ free(c.nodes[i].label);
+ if (c.symbol_properties)
+ yyjson_doc_free(c.symbol_properties[i]);
+ }
+ free(c.symbol_properties);
+ free(c.symbol_properties_loaded);
+ for (int i = 0; i < c.component_count; i++)
+ free(c.components[i].directory);
+ for (int i = 0; i < c.group_count; i++) {
+ free(c.groups[i].id);
+ free(c.groups[i].label);
+ }
+ free(c.nodes);
+ free(c.edges);
+ free(c.components);
+ if (c.cancelled) {
+ free(*out_json);
+ *out_json = NULL;
+ return CBM_STORE_CANCELLED;
+ }
+ return rc;
+}
diff --git a/src/store/architecture_projection.h b/src/store/architecture_projection.h
new file mode 100644
index 000000000..f472fa4db
--- /dev/null
+++ b/src/store/architecture_projection.h
@@ -0,0 +1,39 @@
+#ifndef CBM_ARCHITECTURE_PROJECTION_H
+#define CBM_ARCHITECTURE_PROJECTION_H
+
+#include "store/store.h"
+
+typedef struct {
+ /* Zero selects the bounded default. Larger requests are clamped. */
+ int max_nodes; /* 100000; ceiling 250000 */
+ int max_edges; /* 500000; ceiling 1000000 */
+ int max_components; /* 256; ceiling 512 */
+ int max_dependencies; /* 2048; ceiling 4096 */
+ int max_paths; /* 12; ceiling 32 */
+ int max_depth; /* 10; ceiling 16 */
+ int max_targets; /* 256; ceiling 1024 */
+ int max_corridor_nodes; /* 1024; ceiling 4096 */
+ int max_corridor_edges; /* 4096; ceiling 16384 */
+ int64_t entry_node_id; /* zero chooses indexed entry points */
+ int64_t target_node_id; /* optional bounded call corridor; requires entry */
+ bool include_behavior_evidence; /* opt-in indexed declarations and bounded call arguments */
+ uint64_t deadline_ms; /* absolute cbm_now_ms(); zero = now + 5000 */
+ cbm_store_cancel_fn cancel;
+ void *cancel_context;
+} cbm_architecture_projection_options_t;
+
+/* On-demand, bounded, read-only projection of one consistent indexed graph.
+ * Requires exclusive use of the store connection (prefer a dedicated worker
+ * connection). Installs and removes its SQLite progress handler. No parsing,
+ * indexing, database writes, or runtime execution observations are performed.
+ * Returns malloc-owned JSON on OK, including explicit status="limited" when
+ * graph/resource limits prevent a complete projection. Cancel returns
+ * CBM_STORE_CANCELLED, unknown projects return CBM_STORE_NOT_FOUND.
+ * Component membership is inferred; every dependency witness is an indexed
+ * edge. CALL_REFERENCE is never treated as execution or traversed in paths.
+ */
+int cbm_store_architecture_projection(cbm_store_t *store, const char *project,
+ const cbm_architecture_projection_options_t *options,
+ char **out_json);
+
+#endif
diff --git a/tests/test_architecture_projection.c b/tests/test_architecture_projection.c
new file mode 100644
index 000000000..4e93ed30a
--- /dev/null
+++ b/tests/test_architecture_projection.c
@@ -0,0 +1,1168 @@
+#include "test_framework.h"
+#include <store/architecture_projection.h>
+#include <foundation/platform.h>
+#include <yyjson/yyjson.h>
+#include <sqlite3.h>
+
+static int64_t projection_node(cbm_store_t *store, const char *label, const char *qn,
+ const char *file, bool entry) {
+ cbm_node_t n = {.project = "projection",
+ .label = label,
+ .name = qn,
+ .qualified_name = qn,
+ .file_path = file,
+ .start_line = 10,
+ .end_line = 20,
+ .properties_json = entry ? "{\"is_entry_point\":true}" : "{}"};
+ return cbm_store_upsert_node(store, &n);
+}
+
+static int64_t projection_edge(cbm_store_t *store, int64_t source, int64_t target,
+ const char *type) {
+ cbm_edge_t e = {
+ .project = "projection", .source_id = source, .target_id = target, .type = type};
+ return cbm_store_insert_edge(store, &e);
+}
+
+static cbm_store_t *projection_store(void) {
+ cbm_store_t *store = cbm_store_open_memory();
+ if (store)
+ cbm_store_upsert_project(store, "projection", "/tmp/projection");
+ return store;
+}
+
+static yyjson_val *projection_field(yyjson_doc *doc, const char *field) {
+ return yyjson_obj_get(yyjson_doc_get_root(doc), field);
+}
+
+TEST(projection_accounts_for_isolated_nodes_and_files) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Project", "projection", "", false);
+ projection_node(store, "Folder", "projection.folder", "folder", false);
+ projection_node(store, "File", "projection.alone.c", "alone.c", false);
+ projection_node(store, "Module", "projection.alone", "alone.c", false);
+ projection_node(store, "Function", "projection.alone.work", "alone.c", false);
+ projection_node(store, "File", "projection.notes.md", "notes.md", false);
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *totals = projection_field(doc, "totals");
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(totals, "nodes")), 6);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(totals, "accounted_nodes")), 4);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(totals, "structural_nodes")), 2);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(totals, "files")), 2);
+ ASSERT_TRUE(yyjson_get_bool(projection_field(doc, "complete")));
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 2);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "dependencies")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_preserves_typed_edges_and_contiguous_paths) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Package", "projection.a", "", false);
+ projection_node(store, "Package", "projection.b", "", false);
+ projection_node(store, "Package", "projection.c", "", false);
+ int64_t a = projection_node(store, "Function", "projection.a.start", "a.c", true);
+ int64_t b1 = projection_node(store, "Function", "projection.b.one", "b.c", false);
+ int64_t b2 = projection_node(store, "Function", "projection.b.two", "b.c", false);
+ int64_t c = projection_node(store, "Function", "projection.c.end", "c.c", false);
+ int64_t first = projection_edge(store, a, b1, "CALLS");
+ projection_edge(store, b2, c, "CALLS");
+ projection_edge(store, b1, b2, "CALL_REFERENCE");
+ char *json = NULL;
+ cbm_architecture_projection_options_t opts = {.entry_node_id = a};
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *paths = projection_field(doc, "paths");
+ ASSERT_EQ(yyjson_arr_size(paths), 1);
+ yyjson_val *path = yyjson_arr_get(paths, 0);
+ yyjson_val *nodes = yyjson_obj_get(path, "nodes"), *edges = yyjson_obj_get(path, "edges");
+ ASSERT_EQ(yyjson_arr_size(nodes), 2);
+ ASSERT_EQ(yyjson_arr_size(edges), 1);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(nodes, 1), "id")), b1);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(edges, 0), "id")), first);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "dependencies")), 2);
+ yyjson_doc_free(doc);
+ free(json);
+ /* A real binding changes the answer; projected component edges alone did not. */
+ projection_edge(store, b1, b2, "CALLS");
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ nodes = yyjson_obj_get(yyjson_arr_get(projection_field(doc, "paths"), 0), "nodes");
+ ASSERT_EQ(yyjson_arr_size(nodes), 4);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(nodes, 3), "id")), c);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_reports_dependency_cycles_without_fabricated_execution) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Package", "projection.a", "", false);
+ projection_node(store, "Package", "projection.b", "", false);
+ projection_node(store, "Package", "projection.c", "", false);
+ int64_t a = projection_node(store, "Function", "projection.a.run", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b.run", "b.c", false);
+ int64_t c = projection_node(store, "Function", "projection.c.run", "c.c", false);
+ projection_edge(store, a, b, "IMPORTS");
+ projection_edge(store, b, c, "IMPLEMENTS");
+ projection_edge(store, c, a, "USAGE");
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *cycles = projection_field(doc, "cycles");
+ ASSERT_EQ(yyjson_arr_size(cycles), 1);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(yyjson_arr_get(cycles, 0), "component_ids")), 3);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_architecture_projection_options_t opts = {.max_components = 2};
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "cycles")), 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "cycles")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "limits"), "omitted_cycles")), 1);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_graph_limits_abstain_instead_of_sampling) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ projection_edge(store, a, b, "CALLS");
+ projection_edge(store, b, a, "CALLS");
+ cbm_architecture_projection_options_t opts = {.max_nodes = 1};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_STR_EQ(yyjson_get_str(projection_field(doc, "status")), "limited");
+ ASSERT_FALSE(yyjson_get_bool(projection_field(doc, "complete")));
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "nodes")), 2);
+ yyjson_doc_free(doc);
+ free(json);
+ opts.max_nodes = 0;
+ opts.max_edges = 1;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_STR_EQ(yyjson_get_str(projection_field(doc, "status")), "limited");
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+static bool projection_cancel(void *context) {
+ (void)context;
+ return true;
+}
+
+TEST(projection_cancellation_deadline_and_store_reuse) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Function", "projection.a", "a.c", true);
+ char *json = NULL;
+ cbm_architecture_projection_options_t opts = {.cancel = projection_cancel};
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json),
+ CBM_STORE_CANCELLED);
+ ASSERT_NULL(json);
+ opts.cancel = NULL;
+ opts.deadline_ms = cbm_now_ms() - 1;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json),
+ CBM_STORE_SCAN_LIMIT);
+ ASSERT_NULL(json);
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ ASSERT_NOT_NULL(json);
+ free(json);
+ ASSERT_EQ(sqlite3_get_autocommit(cbm_store_get_db(store)), 1);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_display_caps_preserve_total_accounting) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "File", "projection.a.c", "a.c", false);
+ projection_node(store, "File", "projection.b.c", "b.c", false);
+ projection_node(store, "File", "projection.c.c", "c.c", false);
+ cbm_architecture_projection_options_t opts = {.max_components = 1};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "components")), 3);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "accounted_nodes")),
+ 3);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "limits"), "omitted_components")),
+ 2);
+ ASSERT_FALSE(yyjson_get_bool(projection_field(doc, "complete")));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_unknown_project_and_empty_project) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "absent", NULL, &json), CBM_STORE_NOT_FOUND);
+ ASSERT_NULL(json);
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_TRUE(yyjson_get_bool(projection_field(doc, "complete")));
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ projection_node(store, "Project", "projection", "", false);
+ projection_node(store, "Folder", "projection.folder", "folder", false);
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_TRUE(yyjson_get_bool(projection_field(doc, "complete")));
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "structural_nodes")),
+ 2);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_paths_depth_cap_is_explicit) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t nodes[5];
+ for (int i = 0; i < 5; i++) {
+ char qn[48];
+ snprintf(qn, sizeof(qn), "projection.n%d", i);
+ nodes[i] = projection_node(store, "Function", qn, "chain.c", i == 0);
+ if (i)
+ projection_edge(store, nodes[i - 1], nodes[i], "CALLS");
+ }
+ cbm_architecture_projection_options_t opts = {.max_depth = 2};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_TRUE(
+ yyjson_get_bool(yyjson_obj_get(projection_field(doc, "limits"), "paths_truncated")));
+ yyjson_val *path = yyjson_arr_get(projection_field(doc, "paths"), 0);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(path, "edges")), 2);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_channel_relationships_are_typed_not_fake_calls) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t producer = projection_node(store, "Function", "projection.producer", "send.c", true);
+ int64_t consumer =
+ projection_node(store, "Function", "projection.consumer", "receive.c", false);
+ int64_t channel = projection_node(store, "Channel", "projection.orders", "", false);
+ projection_edge(store, producer, channel, "EMITS");
+ projection_edge(store, consumer, channel, "LISTENS_ON");
+ projection_edge(store, producer, consumer, "DATA_FLOWS");
+ projection_edge(store, producer, consumer, "SIMILAR_TO");
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "dependencies")), 3);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "unmodeled_edges")),
+ 1);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_test_callers_cannot_absorb_source_components) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Module", "projection.store", "src/store.c", false);
+ int64_t production =
+ projection_node(store, "Function", "projection.store.read", "src/store.c", false);
+ for (int file = 0; file < 2; file++) {
+ char module[64], path[64];
+ snprintf(module, sizeof(module), "projection.test%d", file);
+ snprintf(path, sizeof(path), "tests/check%d.c", file);
+ projection_node(store, "Module", module, path, false);
+ for (int i = 0; i < 3; i++) {
+ char qn[80];
+ snprintf(qn, sizeof(qn), "%s.check%d", module, i);
+ int64_t test = projection_node(store, "Function", qn, path, false);
+ projection_edge(store, test, production, "CALLS");
+ }
+ }
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *parts = projection_field(doc, "components");
+ ASSERT_EQ(yyjson_arr_size(parts), 3);
+ int non_test = 0, tests = 0;
+ for (size_t i = 0; i < yyjson_arr_size(parts); i++) {
+ yyjson_val *part = yyjson_arr_get(parts, i);
+ const char *role = yyjson_get_str(yyjson_obj_get(part, "role"));
+ ASSERT_NOT_NULL(role);
+ if (!strcmp(role, "non_test")) {
+ non_test++;
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(part, "member_count")), 2);
+ } else {
+ tests++;
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(part, "member_count")), 4);
+ }
+ }
+ ASSERT_EQ(non_test, 1);
+ ASSERT_EQ(tests, 2);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(projection_field(doc, "totals"), "accounted_nodes")),
+ 10);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_indexed_embedded_test_has_separate_membership) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t type = projection_node(store, "Class", "projection.Store", "src/store.rs", false);
+ int64_t method =
+ projection_node(store, "Method", "projection.Store.read", "src/store.rs", false);
+ cbm_node_t test = {.project = "projection",
+ .label = "Method",
+ .name = "embedded_check",
+ .qualified_name = "projection.Store.embedded_check",
+ .file_path = "src/store.rs",
+ .properties_json = "{\"is_test\":true}"};
+ int64_t embedded = cbm_store_upsert_node(store, &test);
+ projection_edge(store, type, method, "DEFINES_METHOD");
+ projection_edge(store, type, embedded, "DEFINES_METHOD");
+ projection_edge(store, embedded, method, "CALLS");
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *parts = projection_field(doc, "components");
+ ASSERT_EQ(yyjson_arr_size(parts), 2);
+ bool found = false;
+ for (size_t i = 0; i < yyjson_arr_size(parts); i++) {
+ yyjson_val *part = yyjson_arr_get(parts, i);
+ if (!strcmp(yyjson_get_str(yyjson_obj_get(part, "role")), "test")) {
+ found = true;
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(part, "member_count")), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(part, "role_basis")), "indexed_is_test");
+ }
+ }
+ ASSERT_TRUE(found);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_shallow_leaves_do_not_hide_deeper_behavior) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t entry = projection_node(store, "Function", "projection.main", "main.c", true);
+ /* These precede the meaningful branch in both node and edge order. */
+ for (int i = 0; i < 13; i++) {
+ char qn[64];
+ snprintf(qn, sizeof(qn), "projection.utility%d", i);
+ int64_t leaf = projection_node(store, "Function", qn, "utility.c", false);
+ projection_edge(store, entry, leaf, "CALLS");
+ }
+ int64_t a = projection_node(store, "Function", "projection.dispatch", "dispatch.c", false);
+ int64_t b = projection_node(store, "Function", "projection.query", "query.c", false);
+ int64_t end = projection_node(store, "Function", "projection.persist", "store.c", false);
+ projection_edge(store, entry, a, "CALLS");
+ projection_edge(store, a, b, "CALLS");
+ projection_edge(store, b, end, "CALLS");
+ char *json = NULL;
+ cbm_architecture_projection_options_t opts = {.entry_node_id = entry};
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *paths = projection_field(doc, "paths");
+ ASSERT_EQ(yyjson_arr_size(paths), 12);
+ yyjson_val *first = yyjson_arr_get(paths, 0);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(first, "edges")), 3);
+ yyjson_val *nodes = yyjson_obj_get(first, "nodes");
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(nodes, 3), "id")), end);
+ ASSERT_TRUE(
+ yyjson_get_bool(yyjson_obj_get(projection_field(doc, "limits"), "paths_truncated")));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_behavior_preserves_first_hop_diversity) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t entry = projection_node(store, "Function", "projection.main", "main.c", true);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", false);
+ int64_t a1 = projection_node(store, "Function", "projection.a1", "a.c", false);
+ int64_t a2 = projection_node(store, "Function", "projection.a2", "a.c", false);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ int64_t b1 = projection_node(store, "Function", "projection.b1", "b.c", false);
+ projection_edge(store, entry, a, "CALLS");
+ projection_edge(store, a, a1, "CALLS");
+ projection_edge(store, a, a2, "CALLS");
+ projection_edge(store, entry, b, "CALLS");
+ projection_edge(store, b, b1, "CALLS");
+ char *json = NULL;
+ cbm_architecture_projection_options_t opts = {.entry_node_id = entry, .max_paths = 2};
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *paths = projection_field(doc, "paths");
+ ASSERT_EQ(yyjson_arr_size(paths), 2);
+ yyjson_val *first = yyjson_obj_get(yyjson_arr_get(paths, 0), "nodes");
+ yyjson_val *second = yyjson_obj_get(yyjson_arr_get(paths, 1), "nodes");
+ int64_t hop1 = yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(first, 1), "id"));
+ int64_t hop2 = yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(second, 1), "id"));
+ ASSERT_TRUE((hop1 == a && hop2 == b) || (hop1 == b && hop2 == a));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_corridor_preserves_joins_cycles_and_callsite_evidence) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "src/api/main.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "src/engine/b.c", false);
+ int64_t c = projection_node(store, "Function", "projection.c", "src/engine/c.c", false);
+ int64_t d = projection_node(store, "Function", "projection.d", "src/store/d.c", false);
+ int64_t ignored =
+ projection_node(store, "Function", "projection.callback", "src/events/e.c", false);
+ cbm_edge_t evidence = {
+ .project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "CALLS",
+ .properties_json =
+ "{\"line\":42,\"strategy\":\"lsp_direct\",\"confidence\":0.95,\"candidates\":1}"};
+ int64_t ab = cbm_store_insert_edge(store, &evidence);
+ projection_edge(store, a, c, "CALLS");
+ projection_edge(store, b, d, "CALLS");
+ projection_edge(store, c, d, "CALLS");
+ projection_edge(store, b, c, "CALLS");
+ projection_edge(store, c, b, "CALLS");
+ projection_edge(store, a, ignored, "CALL_REFERENCE");
+ projection_edge(store, ignored, d, "EMITS");
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = d, .max_depth = 4};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *view = projection_field(doc, "behavior"), *nodes = yyjson_obj_get(view, "nodes"),
+ *edges = yyjson_obj_get(view, "edges");
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(view, "complete")));
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(view, "reachable")));
+ ASSERT_EQ(yyjson_arr_size(nodes), 4);
+ ASSERT_EQ(yyjson_arr_size(edges), 6);
+ int into_d = 0;
+ bool found_evidence = false;
+ for (size_t i = 0; i < yyjson_arr_size(edges); i++) {
+ yyjson_val *edge = yyjson_arr_get(edges, i);
+ if (yyjson_get_sint(yyjson_obj_get(edge, "target_id")) == d)
+ into_d++;
+ if (yyjson_get_sint(yyjson_obj_get(edge, "id")) == ab) {
+ found_evidence = true;
+ yyjson_val *site = yyjson_obj_get(edge, "callsite"),
+ *resolution = yyjson_obj_get(edge, "resolution");
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(site, "line")), 42);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(site, "file_path")), "src/api/main.c");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(resolution, "strategy")), "lsp_direct");
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(resolution, "candidates")), 1);
+ }
+ }
+ ASSERT_EQ(into_d, 2);
+ ASSERT_TRUE(found_evidence);
+ yyjson_val *cycles = yyjson_obj_get(view, "cycles");
+ ASSERT_EQ(yyjson_arr_size(cycles), 1);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(yyjson_arr_get(cycles, 0), "node_ids")), 2);
+ yyjson_val *paths = projection_field(doc, "paths");
+ ASSERT_TRUE(yyjson_arr_size(paths) >= 2);
+ for (size_t i = 0; i < yyjson_arr_size(paths); i++) {
+ yyjson_val *path = yyjson_arr_get(paths, i), *pn = yyjson_obj_get(path, "nodes"),
+ *pe = yyjson_obj_get(path, "edges");
+ ASSERT_EQ(yyjson_arr_size(pn), yyjson_arr_size(pe) + 1);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(pn, 0), "id")), a);
+ ASSERT_EQ(
+ yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(pn, yyjson_arr_size(pn) - 1), "id")), d);
+ ASSERT_TRUE(yyjson_arr_size(pe) <= 4);
+ for (size_t j = 0; j < yyjson_arr_size(pe); j++) {
+ yyjson_val *edge = yyjson_arr_get(pe, j);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(edge, "source_id")),
+ yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(pn, j), "id")));
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(edge, "target_id")),
+ yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(pn, j + 1), "id")));
+ }
+ }
+ yyjson_doc_free(doc);
+ free(json);
+ opts.target_node_id = ignored;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ view = projection_field(doc, "behavior");
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(view, "reachable")));
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(view, "corridor_complete")));
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "nodes")), 0);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_corridor_caps_abstain_without_hiding_joins) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ int64_t d = projection_node(store, "Function", "projection.d", "d.c", false);
+ projection_edge(store, a, b, "CALLS");
+ projection_edge(store, b, d, "CALLS");
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = d, .max_corridor_nodes = 2};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *view = projection_field(doc, "behavior");
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(view, "complete")));
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(view, "corridor_complete")));
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(yyjson_obj_get(view, "totals"), "corridor_nodes")), 3);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "nodes")), 0);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "edges")), 0);
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "paths")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ opts.target_node_id = 0;
+ opts.max_targets = 1;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ view = projection_field(doc, "behavior");
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(view, "reachable_targets")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(yyjson_obj_get(view, "totals"), "omitted_targets")), 1);
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(view, "complete")));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_overview_accounts_for_components_beyond_legacy_cap) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ for (int i = 0; i < 300; i++) {
+ char qn[80], file[80];
+ snprintf(qn, sizeof(qn), "projection.part%d", i);
+ snprintf(file, sizeof(file), "packages/part%d/file.c", i);
+ projection_node(store, "File", qn, file, false);
+ }
+ int64_t entry = projection_node(store, "Function", "projection.entry", "src/main.c", true);
+ int64_t target =
+ projection_node(store, "Function", "projection.target", "src/service.c", false);
+ projection_edge(store, entry, target, "CALLS");
+ cbm_architecture_projection_options_t opts = {.max_components = 1, .entry_node_id = entry};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *overview = projection_field(doc, "overview"),
+ *groups = yyjson_obj_get(overview, "groups"),
+ *parts = yyjson_obj_get(overview, "components");
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(overview, "complete")));
+ ASSERT_EQ(yyjson_arr_size(projection_field(doc, "components")), 1);
+ ASSERT_EQ(yyjson_arr_size(parts), 302);
+ ASSERT_TRUE(yyjson_arr_size(groups) <= 64);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(overview, "grouping_depth")), 1);
+ size_t membership = 0;
+ int members = 0;
+ for (size_t i = 0; i < yyjson_arr_size(groups); i++) {
+ yyjson_val *group = yyjson_arr_get(groups, i);
+ membership += yyjson_arr_size(yyjson_obj_get(group, "component_ids"));
+ members += yyjson_get_int(yyjson_obj_get(group, "member_count"));
+ }
+ ASSERT_EQ(membership, 302);
+ ASSERT_EQ(members, 302);
+ yyjson_val *symbol =
+ yyjson_arr_get(yyjson_obj_get(projection_field(doc, "behavior"), "reachable_targets"), 0);
+ const char *group_id = yyjson_get_str(yyjson_obj_get(symbol, "group_id"));
+ ASSERT_NOT_NULL(group_id);
+ char stable[128];
+ snprintf(stable, sizeof(stable), "%s", group_id);
+ yyjson_doc_free(doc);
+ free(json);
+ opts.target_node_id = target;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ symbol =
+ yyjson_arr_get(yyjson_obj_get(projection_field(doc, "behavior"), "reachable_targets"), 0);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(symbol, "group_id")), stable);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "overview"), "components")),
+ 302);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_aggregate_cycle_does_not_invent_symbol_cycle) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "src/api/a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "src/store/b.c", false);
+ int64_t c = projection_node(store, "Function", "projection.c", "src/api/c.c", false);
+ projection_edge(store, a, b, "CALLS");
+ projection_edge(store, b, c, "CALLS");
+ cbm_architecture_projection_options_t opts = {.entry_node_id = a, .target_node_id = c};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "overview"), "groups")), 2);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "overview"), "connections")), 2);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(projection_field(doc, "behavior"), "cycles")), 0);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_provenance_budget_counts_utf8_bytes) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ int64_t d = projection_node(store, "Function", "projection.d", "d.c", false);
+ char properties[19000];
+ size_t used = (size_t)snprintf(properties, sizeof(properties),
+ "{\"line\":42,\"strategy\":\"unique_name\",\"ignored\":\"");
+ for (int i = 0; i < 9000; i++) {
+ properties[used++] = (char)0xc3;
+ properties[used++] = (char)0xa9;
+ }
+ memcpy(properties + used, "\"}", 3);
+ ASSERT_TRUE(strlen(properties) > 16384);
+ cbm_edge_t edge = {.project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "CALLS",
+ .properties_json = properties};
+ int64_t oversized = cbm_store_insert_edge(store, &edge);
+ edge.source_id = b;
+ edge.target_id = d;
+ edge.properties_json = "{\"line\":24}";
+ int64_t normal = cbm_store_insert_edge(store, &edge);
+ cbm_architecture_projection_options_t opts = {.entry_node_id = a, .target_node_id = d};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *edges = yyjson_obj_get(projection_field(doc, "behavior"), "edges");
+ ASSERT_EQ(yyjson_arr_size(edges), 2);
+ for (size_t i = 0; i < yyjson_arr_size(edges); i++) {
+ yyjson_val *value = yyjson_arr_get(edges, i);
+ int64_t id = yyjson_get_sint(yyjson_obj_get(value, "id"));
+ if (id == oversized) {
+ ASSERT_NULL(yyjson_obj_get(value, "callsite"));
+ ASSERT_NULL(yyjson_obj_get(value, "resolution"));
+ } else {
+ ASSERT_EQ(id, normal);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(yyjson_obj_get(value, "callsite"), "line")),
+ 24);
+ }
+ }
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_example_budgets_preserve_full_aggregate_counts) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Package", "projection.a", "a.c", false);
+ projection_node(store, "Package", "projection.b", "b.c", false);
+ for (int i = 0; i < 5; i++) {
+ char source[64], target[64];
+ snprintf(source, sizeof(source), "projection.a.caller%d", i);
+ snprintf(target, sizeof(target), "projection.b.callee%d", i);
+ int64_t a = projection_node(store, "Function", source, "a.c", i == 0);
+ int64_t b = projection_node(store, "Function", target, "b.c", false);
+ projection_edge(store, a, b, "CALLS");
+ }
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", NULL, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *parts = projection_field(doc, "components"),
+ *deps = projection_field(doc, "dependencies");
+ ASSERT_EQ(yyjson_arr_size(parts), 2);
+ ASSERT_EQ(yyjson_arr_size(deps), 1);
+ yyjson_val *dependency = yyjson_arr_get(deps, 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(dependency, "count")), 5);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(dependency, "witnesses")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(dependency, "omitted_witnesses")), 4);
+ yyjson_val *overview = projection_field(doc, "overview");
+ ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(overview, "complete")));
+ yyjson_val *all = yyjson_obj_get(overview, "components"),
+ *groups = yyjson_obj_get(overview, "groups");
+ ASSERT_EQ(yyjson_arr_size(all), 2);
+ ASSERT_EQ(yyjson_arr_size(groups), 1);
+ for (size_t i = 0; i < yyjson_arr_size(all); i++) {
+ yyjson_val *part = yyjson_arr_get(all, i);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(part, "member_count")), 6);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(part, "representatives")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(part, "omitted_members")), 5);
+ }
+ yyjson_val *group = yyjson_arr_get(groups, 0);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(group, "component_ids")), 2);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(group, "member_count")), 12);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(group, "representatives")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(group, "omitted_representatives")), 1);
+ yyjson_val *connection = yyjson_arr_get(yyjson_obj_get(overview, "connections"), 0);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(connection, "count")), 5);
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(connection, "witnesses")), 1);
+ ASSERT_EQ(yyjson_get_int(yyjson_obj_get(connection, "omitted_witnesses")), 4);
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+static int64_t projection_node_properties(cbm_store_t *store, const char *qn, const char *file,
+ const char *properties) {
+ cbm_node_t node = {.project = "projection",
+ .label = "Function",
+ .name = qn,
+ .qualified_name = qn,
+ .file_path = file,
+ .start_line = 10,
+ .end_line = 20,
+ .properties_json = properties};
+ return cbm_store_upsert_node(store, &node);
+}
+
+static int projection_count_metadata_queries(unsigned kind, void *context, void *statement,
+ void *detail) {
+ (void)detail;
+ if (kind == SQLITE_TRACE_STMT) {
+ const char *sql = sqlite3_sql(statement);
+ if (sql && strstr(sql, "FROM nodes WHERE id=?1"))
+ (*(int *)context)++;
+ }
+ return 0;
+}
+
+/* Validate every duplicated occurrence, not just the first path or witness. */
+static int projection_check_contracts(yyjson_val *value, int64_t symbol_id, int64_t edge_id,
+ int *symbols, int *edges) {
+ if (yyjson_is_obj(value)) {
+ if (yyjson_obj_get(value, "qualified_name") &&
+ yyjson_get_sint(yyjson_obj_get(value, "id")) == symbol_id) {
+ (*symbols)++;
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(value, "signature")),
+ "save(value: Value) -> Result");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(value, "return_type")), "Result");
+ yyjson_val *parameters = yyjson_obj_get(value, "parameters");
+ ASSERT_NOT_NULL(parameters);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(parameters, "count")), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_obj_get(parameters, "names"), 0)),
+ "value");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_obj_get(parameters, "types"), 0)),
+ "Value");
+ }
+ if ((yyjson_obj_get(value, "source_id") &&
+ yyjson_get_sint(yyjson_obj_get(value, "id")) == edge_id) ||
+ yyjson_get_sint(yyjson_obj_get(value, "edge_id")) == edge_id) {
+ (*edges)++;
+ yyjson_val *arguments = yyjson_obj_get(value, "arguments");
+ ASSERT_EQ(yyjson_arr_size(arguments), 1);
+ yyjson_val *argument = yyjson_arr_get(arguments, 0);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(argument, "i")), 7);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(argument, "e")), "input[\"key\"]");
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(argument, "v")), "line\nvalue");
+ ASSERT_NULL(yyjson_obj_get(argument, "keyword"));
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(value, "argument_limit")), 8);
+ ASSERT_TRUE(yyjson_is_bool(yyjson_obj_get(value, "arguments_complete")));
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(value, "arguments_complete")));
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_obj_get(value, "callsite"), "line")),
+ 42);
+ }
+ size_t index, maximum;
+ yyjson_val *key, *child;
+ yyjson_obj_foreach(value, index, maximum, key,
+ child) if (projection_check_contracts(child, symbol_id, edge_id, symbols,
+ edges)) return 1;
+ } else if (yyjson_is_arr(value)) {
+ size_t index, maximum;
+ yyjson_val *child;
+ yyjson_arr_foreach(value, index, maximum,
+ child) if (projection_check_contracts(child, symbol_id, edge_id, symbols,
+ edges)) return 1;
+ }
+ return 0;
+}
+
+TEST(projection_behavior_evidence_is_opt_in_and_shared_across_surfaces) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ projection_node(store, "Package", "projection.a", "", false);
+ projection_node(store, "Package", "projection.b", "", false);
+ int64_t a = projection_node(store, "Function", "projection.a.start", "src/api/start.c", true);
+ int64_t b = projection_node_properties(
+ store, "projection.b.save", "src/store/save.c",
+ "{\"signature\":\"save(value: Value) -> Result\",\"return_type\":\"Result\","
+ "\"param_names\":[\"value\"],\"param_types\":[\"Value\"],\"param_count\":1}");
+ cbm_edge_t evidence = {.project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "CALLS",
+ .properties_json =
+ "{\"line\":42,\"args\":[{\"i\":7,\"e\":\"input[\\\"key\\\"]\",\"v\":"
+ "\"line\\nvalue\",\"keyword\":\"value\"}]}"};
+ int64_t call = cbm_store_insert_edge(store, &evidence);
+ ASSERT_TRUE(call > 0);
+ int queries = 0;
+ sqlite3_trace_v2(cbm_store_get_db(store), SQLITE_TRACE_STMT, projection_count_metadata_queries,
+ &queries);
+ cbm_architecture_projection_options_t opts = {.entry_node_id = a, .target_node_id = b};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ ASSERT_NULL(strstr(json, "\"signature\""));
+ ASSERT_NULL(strstr(json, "\"return_type\""));
+ ASSERT_NULL(strstr(json, "\"parameters\""));
+ ASSERT_NULL(strstr(json, "\"arguments\""));
+ ASSERT_NULL(strstr(json, "\"argument_limit\""));
+ ASSERT_EQ(queries, 0);
+ free(json);
+
+ opts.include_behavior_evidence = true;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ int symbols = 0, edges = 0;
+ ASSERT_EQ(projection_check_contracts(yyjson_doc_get_root(doc), b, call, &symbols, &edges), 0);
+ ASSERT_TRUE(symbols >= 3);
+ ASSERT_TRUE(edges >= 4);
+ ASSERT_TRUE(queries > 0);
+ ASSERT_TRUE(queries <= 4); /* cache once per displayed indexed node */
+ yyjson_doc_free(doc);
+ free(json);
+
+ queries = 0;
+ opts.include_behavior_evidence = false;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ ASSERT_NULL(strstr(json, "\"return_type\""));
+ ASSERT_NULL(strstr(json, "\"arguments\""));
+ ASSERT_EQ(queries, 0);
+ free(json);
+ sqlite3_trace_v2(cbm_store_get_db(store), 0, NULL, NULL);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_argument_validation_keeps_exact_edge_and_callsite_identity) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ int64_t target = projection_node(store, "Function", "projection.target", "target.c", false);
+ projection_edge(store, a, b, "CALLS");
+ cbm_edge_t evidence = {
+ .project = "projection",
+ .source_id = a,
+ .target_id = target,
+ .type = "CALLS",
+ .properties_json =
+ "{\"line\":42,\"args\":[{\"i\":0,\"e\":\"first\",\"v\":\"exact\"},"
+ "{\"i\":-1,\"e\":\"negative\"},{\"i\":2},{\"i\":3,\"e\":42},"
+ "{\"i\":4,\"e\":\"keep\",\"v\":false},{\"i\":5,\"e\":\"actual\"},"
+ "{\"i\":6.5,\"e\":\"float\"},{\"i\":7,\"e\":\"last\"},{\"i\":8,\"e\":\"ninth\"}]}"};
+ int64_t first = cbm_store_insert_edge(store, &evidence);
+ ASSERT_TRUE(first > 0);
+ evidence.source_id = b;
+ evidence.properties_json = "{\"line\":84,\"args\":[{\"i\":0,\"e\":\"different\"}]}";
+ int64_t second = cbm_store_insert_edge(store, &evidence);
+ ASSERT_TRUE(second > 0);
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = target, .include_behavior_evidence = true};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *edges = yyjson_obj_get(projection_field(doc, "behavior"), "edges");
+ int seen = 0;
+ for (size_t i = 0; i < yyjson_arr_size(edges); i++) {
+ yyjson_val *value = yyjson_arr_get(edges, i), *args = yyjson_obj_get(value, "arguments");
+ int64_t id = yyjson_get_sint(yyjson_obj_get(value, "id"));
+ if (id == first) {
+ seen++;
+ ASSERT_EQ(yyjson_arr_size(args), 4);
+ int indexes[] = {0, 4, 5, 7};
+ for (size_t at = 0; at < 4; at++)
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_arr_get(args, at), "i")),
+ indexes[at]);
+ ASSERT_NULL(yyjson_obj_get(yyjson_arr_get(args, 1), "v"));
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(args, 3), "e")), "last");
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_obj_get(value, "callsite"), "line")),
+ 42);
+ } else if (id == second) {
+ seen++;
+ ASSERT_EQ(yyjson_arr_size(args), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(yyjson_arr_get(args, 0), "e")),
+ "different");
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(yyjson_obj_get(value, "callsite"), "line")),
+ 84);
+ ASSERT_STR_EQ(
+ yyjson_get_str(yyjson_obj_get(yyjson_obj_get(value, "callsite"), "file_path")),
+ "b.c");
+ }
+ }
+ ASSERT_EQ(seen, 2);
+ ASSERT_NULL(strstr(json, "ninth"));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_missing_corrupt_and_noncall_arguments_remain_unknown) {
+ const char *properties[] = {"{}", "{\"args\":\"corrupt\"}", "{\"args\":null}", "{\"args\":{}}",
+ "{\"args\":[]}"};
+ for (size_t i = 0; i < sizeof(properties) / sizeof(properties[0]); i++) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node_properties(
+ store, "projection.b", "b.c",
+ "{\"signature\":42,\"return_type\":\"Known\",\"param_count\":1,\"param_names\":[\"x\"],"
+ "\"param_types\":[false]}");
+ cbm_edge_t evidence = {.project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "CALLS",
+ .properties_json = properties[i]};
+ ASSERT_TRUE(cbm_store_insert_edge(store, &evidence) > 0);
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = b, .include_behavior_evidence = true};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json),
+ CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *edge =
+ yyjson_arr_get(yyjson_obj_get(projection_field(doc, "behavior"), "edges"), 0);
+ if (i == 4) {
+ ASSERT_TRUE(yyjson_is_arr(yyjson_obj_get(edge, "arguments")));
+ ASSERT_EQ(yyjson_arr_size(yyjson_obj_get(edge, "arguments")), 0);
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(edge, "arguments_complete")));
+ } else
+ ASSERT_NULL(yyjson_obj_get(edge, "arguments"));
+ ASSERT_NULL(strstr(json, "\"signature\""));
+ ASSERT_NULL(strstr(json, "\"parameters\""));
+ ASSERT_NOT_NULL(strstr(json, "\"return_type\":\"Known\""));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ }
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ int64_t b = projection_node(store, "Function", "projection.b", "b.c", false);
+ cbm_edge_t evidence = {.project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "HTTP_CALLS",
+ .properties_json =
+ "{\"args\":[{\"i\":0,\"e\":\"not_a_CALLS_property\"}]}"};
+ ASSERT_TRUE(cbm_store_insert_edge(store, &evidence) > 0);
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = b, .include_behavior_evidence = true};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ ASSERT_NULL(strstr(json, "\"arguments\""));
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_oversized_evidence_is_omitted_without_truncating_values) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ int64_t a = projection_node(store, "Function", "projection.a", "a.c", true);
+ char signature[4098], expression[1026], node_properties[4300], edge_properties[2300];
+ memset(signature, 's', sizeof(signature) - 1);
+ signature[sizeof(signature) - 1] = '\0';
+ memset(expression, 'e', sizeof(expression) - 1);
+ expression[sizeof(expression) - 1] = '\0';
+ snprintf(node_properties, sizeof(node_properties),
+ "{\"signature\":\"%s\",\"return_type\":\"Preserved\"}", signature);
+ int64_t b = projection_node_properties(store, "projection.b", "b.c", node_properties);
+ snprintf(edge_properties, sizeof(edge_properties),
+ "{\"args\":[{\"i\":0,\"e\":\"%s\"},{\"i\":1,\"e\":\"kept\",\"v\":\"%s\"}]}",
+ expression, expression);
+ cbm_edge_t evidence = {.project = "projection",
+ .source_id = a,
+ .target_id = b,
+ .type = "CALLS",
+ .properties_json = edge_properties};
+ ASSERT_TRUE(cbm_store_insert_edge(store, &evidence) > 0);
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = a, .target_node_id = b, .include_behavior_evidence = true};
+ char *json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &json), CBM_STORE_OK);
+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
+ ASSERT_NOT_NULL(doc);
+ ASSERT_NULL(strstr(json, "\"signature\""));
+ ASSERT_NOT_NULL(strstr(json, "\"return_type\":\"Preserved\""));
+ yyjson_val *edge =
+ yyjson_arr_get(yyjson_obj_get(projection_field(doc, "behavior"), "edges"), 0);
+ yyjson_val *args = yyjson_obj_get(edge, "arguments");
+ ASSERT_EQ(yyjson_arr_size(args), 1);
+ yyjson_val *arg = yyjson_arr_get(args, 0);
+ ASSERT_EQ(yyjson_get_sint(yyjson_obj_get(arg, "i")), 1);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(arg, "e")), "kept");
+ ASSERT_NULL(yyjson_obj_get(arg, "v"));
+ ASSERT_FALSE(yyjson_get_bool(yyjson_obj_get(edge, "arguments_complete")));
+ yyjson_doc_free(doc);
+ free(json);
+ cbm_store_close(store);
+ PASS();
+}
+
+TEST(projection_repeated_behavior_evidence_preserves_base_graph_under_budget) {
+ cbm_store_t *store = projection_store();
+ ASSERT_NOT_NULL(store);
+ enum { components = 80 };
+ int64_t symbols[components];
+ char signature[4097], expression[1025], properties[4400], arguments[1200];
+ memset(signature, 's', sizeof(signature) - 1);
+ signature[sizeof(signature) - 1] = '\0';
+ memset(expression, 'e', sizeof(expression) - 1);
+ expression[sizeof(expression) - 1] = '\0';
+ snprintf(properties, sizeof(properties),
+ "{\"signature\":\"%s\",\"return_type\":\"Result\",\"is_entry_point\":true}",
+ signature);
+ snprintf(arguments, sizeof(arguments), "{\"line\":42,\"args\":[{\"i\":0,\"e\":\"%s\"}]}",
+ expression);
+ for (int i = 0; i < components; i++) {
+ char package[80], name[100], file[100];
+ snprintf(package, sizeof(package), "projection.package%02d", i);
+ snprintf(name, sizeof(name), "%s.function", package);
+ snprintf(file, sizeof(file), "src/package%02d/function.c", i);
+ ASSERT_TRUE(projection_node(store, "Package", package, "", false) > 0);
+ symbols[i] = projection_node_properties(store, name, file, properties);
+ ASSERT_TRUE(symbols[i] > 0);
+ }
+ /* Thousands of witnesses repeat a small indexed declaration set. Its
+ uncapped mutable JSON plus serialized copy exceeded the shared budget. */
+ for (int from = 0; from < components; from++)
+ for (int to = 0; to < components; to++) {
+ if (from == to)
+ continue;
+ cbm_edge_t edge = {.project = "projection",
+ .source_id = symbols[from],
+ .target_id = symbols[to],
+ .type = "CALLS",
+ .properties_json = arguments};
+ ASSERT_TRUE(cbm_store_insert_edge(store, &edge) > 0);
+ }
+ cbm_architecture_projection_options_t opts = {
+ .entry_node_id = symbols[0], .target_node_id = symbols[1], .max_depth = 1, .max_paths = 1};
+ char *baseline_json = NULL, *enriched_json = NULL;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &baseline_json),
+ CBM_STORE_OK);
+ yyjson_doc *baseline = yyjson_read(baseline_json, strlen(baseline_json), 0);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(yyjson_arr_size(projection_field(baseline, "components")), components);
+ opts.include_behavior_evidence = true;
+ ASSERT_EQ(cbm_store_architecture_projection(store, "projection", &opts, &enriched_json),
+ CBM_STORE_OK);
+ yyjson_doc *enriched = yyjson_read(enriched_json, strlen(enriched_json), 0);
+ ASSERT_NOT_NULL(enriched);
+ const char *collections[] = {"components", "dependencies", "entrypoints", "paths"};
+ for (size_t i = 0; i < sizeof(collections) / sizeof(collections[0]); i++)
+ ASSERT_EQ(yyjson_arr_size(projection_field(enriched, collections[i])),
+ yyjson_arr_size(projection_field(baseline, collections[i])));
+ ASSERT_EQ(
+ yyjson_get_sint(yyjson_obj_get(projection_field(enriched, "totals"), "accounted_nodes")),
+ yyjson_get_sint(yyjson_obj_get(projection_field(baseline, "totals"), "accounted_nodes")));
+ ASSERT_NULL(strstr(enriched_json, "The architecture response exceeded its memory budget"));
+ yyjson_val *path = yyjson_arr_get(projection_field(enriched, "paths"), 0);
+ yyjson_val *source = yyjson_arr_get(yyjson_obj_get(path, "nodes"), 0);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(source, "signature")), signature);
+ yyjson_val *edge = yyjson_arr_get(yyjson_obj_get(path, "edges"), 0);
+ yyjson_val *argument = yyjson_arr_get(yyjson_obj_get(edge, "arguments"), 0);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(argument, "e")), expression);
+ ASSERT_NOT_NULL(strstr(enriched_json, "Optional behavior evidence was omitted"));
+ yyjson_doc_free(baseline);
+ yyjson_doc_free(enriched);
+ free(baseline_json);
+ free(enriched_json);
+ cbm_store_close(store);
+ PASS();
+}
+
+SUITE(architecture_projection) {
+ RUN_TEST(projection_accounts_for_isolated_nodes_and_files);
+ RUN_TEST(projection_preserves_typed_edges_and_contiguous_paths);
+ RUN_TEST(projection_reports_dependency_cycles_without_fabricated_execution);
+ RUN_TEST(projection_graph_limits_abstain_instead_of_sampling);
+ RUN_TEST(projection_cancellation_deadline_and_store_reuse);
+ RUN_TEST(projection_display_caps_preserve_total_accounting);
+ RUN_TEST(projection_unknown_project_and_empty_project);
+ RUN_TEST(projection_paths_depth_cap_is_explicit);
+ RUN_TEST(projection_channel_relationships_are_typed_not_fake_calls);
+ RUN_TEST(projection_test_callers_cannot_absorb_source_components);
+ RUN_TEST(projection_indexed_embedded_test_has_separate_membership);
+ RUN_TEST(projection_shallow_leaves_do_not_hide_deeper_behavior);
+ RUN_TEST(projection_behavior_preserves_first_hop_diversity);
+ RUN_TEST(projection_corridor_preserves_joins_cycles_and_callsite_evidence);
+ RUN_TEST(projection_corridor_caps_abstain_without_hiding_joins);
+ RUN_TEST(projection_overview_accounts_for_components_beyond_legacy_cap);
+ RUN_TEST(projection_aggregate_cycle_does_not_invent_symbol_cycle);
+ RUN_TEST(projection_provenance_budget_counts_utf8_bytes);
+ RUN_TEST(projection_example_budgets_preserve_full_aggregate_counts);
+ RUN_TEST(projection_behavior_evidence_is_opt_in_and_shared_across_surfaces);
+ RUN_TEST(projection_argument_validation_keeps_exact_edge_and_callsite_identity);
+ RUN_TEST(projection_missing_corrupt_and_noncall_arguments_remain_unknown);
+ RUN_TEST(projection_oversized_evidence_is_omitted_without_truncating_values);
+ RUN_TEST(projection_repeated_behavior_evidence_preserves_base_graph_under_budget);
+}
diff --git a/tests/test_main.c b/tests/test_main.c
index 72d45be10..ac34cf33a 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -23,7 +23,7 @@ int tf_skip_count = 0;
#include "daemon/version_cohort.h" /* Windows crash-turnover re-exec probe */
#include "mcp/index_supervisor.h" /* cbm_index_set_worker_role */
#include "mcp/mcp.h" /* cbm_mcp_handle_tool — act as a real worker */
-#include "ui/http_server.h" /* deleted-self executable probe */
+#include "ui/http_server.h" /* deleted-self executable probe */
#include <sqlite3.h>
#include <errno.h>
#include <stdbool.h>
@@ -822,6 +822,7 @@ extern void suite_java_lsp_coverage(void);
extern void suite_kotlin_lsp(void);
extern void suite_rust_lsp(void);
extern void suite_store_arch(void);
+extern void suite_architecture_projection(void);
extern void suite_store_bulk(void);
extern void suite_store_pragmas(void);
extern void suite_store_checkpoint(void);
@@ -1121,6 +1122,7 @@ int main(int argc, char **argv) {
/* Architecture + ADR + Louvain */
RUN_SELECTED_SUITE(store_arch);
+ RUN_SELECTED_SUITE(architecture_projection);
/* HTTP link */
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 3c418c117..aa64cbcbb 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -1605,10 +1605,10 @@ TEST(mcp_get_architecture_aspects_schema_enum_pr560) {
ASSERT_TRUE(yyjson_is_arr(enum_arr));
/* The enum must be exactly the valid-token set — no more, no less. */
- static const char *expected[] = {"all", "overview", "structure", "dependencies",
- "routes", "languages", "packages", "entry_points",
- "hotspots", "boundaries", "layers", "file_tree",
- "clusters", "cycles"};
+ static const char *expected[] = {"all", "overview", "structure", "dependencies",
+ "routes", "languages", "packages", "entry_points",
+ "hotspots", "boundaries", "layers", "file_tree",
+ "clusters", "cycles", "system_structure"};
size_t expected_count = sizeof(expected) / sizeof(expected[0]);
ASSERT_EQ(yyjson_arr_size(enum_arr), expected_count);
for (size_t i = 0; i < expected_count; i++) {
@@ -1630,6 +1630,28 @@ TEST(mcp_get_architecture_aspects_schema_enum_pr560) {
PASS();
}
+TEST(mcp_get_architecture_behavior_evidence_schema) {
+ const char *schema = cbm_mcp_tool_input_schema("get_architecture");
+ ASSERT_NOT_NULL(schema);
+ yyjson_doc *doc = yyjson_read(schema, strlen(schema), 0);
+ ASSERT_NOT_NULL(doc);
+ yyjson_val *properties = yyjson_obj_get(yyjson_doc_get_root(doc), "properties");
+ yyjson_val *flag = yyjson_obj_get(properties, "include_behavior_evidence");
+ ASSERT_NOT_NULL(flag);
+ ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(flag, "type")), "boolean");
+ ASSERT_TRUE(yyjson_is_false(yyjson_obj_get(flag, "default")));
+ const char *description = cbm_mcp_tool_description("get_architecture");
+ ASSERT_NOT_NULL(description);
+ ASSERT_NOT_NULL(strstr(description, "include_behavior_evidence=true"));
+ ASSERT_NOT_NULL(strstr(description, "indexed"));
+ ASSERT_NOT_NULL(strstr(description, "call arguments"));
+ ASSERT_NOT_NULL(strstr(description, "parameter declarations"));
+ ASSERT_NOT_NULL(strstr(description, "return types"));
+ ASSERT_NOT_NULL(strstr(description, "not full dataflow"));
+ yyjson_doc_free(doc);
+ PASS();
+}
+
TEST(mcp_text_result) {
char *json = cbm_mcp_text_result("{\"total\":5}", false);
ASSERT_NOT_NULL(json);
@@ -7910,6 +7932,143 @@ TEST(tool_get_architecture_empty) {
PASS();
}
+TEST(tool_get_architecture_behavior_evidence_validation) {
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
+ ASSERT_NOT_NULL(srv);
+ cbm_store_t *store = cbm_mcp_server_store(srv);
+ ASSERT_NOT_NULL(store);
+ cbm_mcp_server_set_project(srv, "arch-flag");
+ ASSERT_EQ(cbm_store_upsert_project(store, "arch-flag", "/tmp/arch-flag"), CBM_STORE_OK);
+
+ const char *invalid[] = {"\"true\"", "1", "0", "null", "[]", "{}"};
+ const char *aspects[] = {"", ",\"aspects\":[\"system_structure\"]"};
+ for (size_t a = 0; a < sizeof(aspects) / sizeof(aspects[0]); a++) {
+ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); i++) {
+ char args[256];
+ snprintf(args, sizeof(args),
+ "{\"project\":\"arch-flag\"%s,\"include_behavior_evidence\":%s}", aspects[a],
+ invalid[i]);
+ char *response = cbm_mcp_handle_tool(srv, "get_architecture", args);
+ ASSERT_NOT_NULL(response);
+ ASSERT_TRUE(response_contains_json_fragment(response, "\"isError\":true"));
+ ASSERT_NOT_NULL(strstr(response, "include_behavior_evidence must be a boolean"));
+ free(response);
+ }
+ }
+ char *wrong_scope = cbm_mcp_handle_tool(
+ srv, "get_architecture", "{\"project\":\"arch-flag\",\"include_behavior_evidence\":true}");
+ ASSERT_NOT_NULL(wrong_scope);
+ ASSERT_TRUE(response_contains_json_fragment(wrong_scope, "\"isError\":true"));
+ ASSERT_NOT_NULL(strstr(wrong_scope, "requires aspects"));
+ free(wrong_scope);
+
+ char *implicit = cbm_mcp_handle_tool(srv, "get_architecture", "{\"project\":\"arch-flag\"}");
+ char *explicit_false = cbm_mcp_handle_tool(
+ srv, "get_architecture", "{\"project\":\"arch-flag\",\"include_behavior_evidence\":false}");
+ ASSERT_NOT_NULL(implicit);
+ ASSERT_NOT_NULL(explicit_false);
+ ASSERT_STR_EQ(implicit, explicit_false);
+ free(implicit);
+ free(explicit_false);
+ cbm_mcp_server_free(srv);
+ PASS();
+}
+
+/* Wait for the stable terminal job state, without asserting a transient pending
+ * window or a particular number of worker polls. */
+static char *architecture_wait_for_result(cbm_mcp_server_t *srv, const char *args) {
+ uint64_t deadline = cbm_now_ms() + 10000;
+ for (;;) {
+ char *response = cbm_mcp_handle_tool(srv, "get_architecture", args);
+ char *text = extract_text_content(response);
+ free(response);
+ yyjson_doc *doc = text ? yyjson_read(text, strlen(text), 0) : NULL;
+ yyjson_val *status = doc ? yyjson_obj_get(yyjson_doc_get_root(doc), "status") : NULL;
+ const char *value = yyjson_get_str(status);
+ bool pending = value && strcmp(value, "pending") == 0;
+ yyjson_doc_free(doc);
+ if (!pending || cbm_now_ms() >= deadline) {
+ return text;
+ }
+ free(text);
+ sqlite3_sleep(1);
+ }
+}
+
+TEST(tool_get_architecture_behavior_evidence_cache_isolation) {
+ char cache[CBM_SZ_1K];
+ snprintf(cache, sizeof(cache), "%s/cbm-arch-flag-XXXXXX", cbm_tmpdir());
+ ASSERT_NOT_NULL(cbm_mkdtemp(cache));
+ const char *saved_cache = getenv("CBM_CACHE_DIR");
+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;
+ cbm_setenv("CBM_CACHE_DIR", cache, 1);
+
+ const char *project = "arch-evidence-cache";
+ cbm_mcp_server_t *srv = cbm_mcp_server_new(project);
+ ASSERT_NOT_NULL(srv);
+ cbm_store_t *store = cbm_mcp_server_store(srv);
+ ASSERT_NOT_NULL(store);
+ ASSERT_EQ(cbm_store_upsert_project(store, project, cache), CBM_STORE_OK);
+ cbm_node_t entry = {.project = project,
+ .label = "Function",
+ .name = "entry",
+ .qualified_name = "arch-evidence-cache.entry",
+ .file_path = "src/entry.c",
+ .start_line = 1,
+ .end_line = 5,
+ .properties_json = "{\"return_type\":\"EvidenceCacheSentinel\"}"};
+ int64_t entry_id = cbm_store_upsert_node(store, &entry);
+ ASSERT_GT(entry_id, 0);
+ cbm_node_t target = {.project = project,
+ .label = "Function",
+ .name = "target",
+ .qualified_name = "arch-evidence-cache.target",
+ .file_path = "src/target.c",
+ .start_line = 1,
+ .end_line = 3,
+ .properties_json = "{\"return_type\":\"EvidenceCacheSentinel\"}"};
+ int64_t target_id = cbm_store_upsert_node(store, &target);
+ ASSERT_GT(target_id, 0);
+ cbm_edge_t edge = {.project = project,
+ .source_id = entry_id,
+ .target_id = target_id,
+ .type = "CALLS",
+ .properties_json = "{\"line\":2}"};
+ ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);
+
+ char args[512];
+ const char *flags[] = {"", ",\"include_behavior_evidence\":true",
+ ",\"include_behavior_evidence\":false",
+ ",\"include_behavior_evidence\":true"};
+ char *results[4] = {0};
+ for (size_t i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) {
+ snprintf(args, sizeof(args),
+ "{\"project\":\"%s\",\"aspects\":[\"system_structure\"],"
+ "\"entry_node_id\":%lld%s}",
+ project, (long long)entry_id, flags[i]);
+ results[i] = architecture_wait_for_result(srv, args);
+ ASSERT_NOT_NULL(results[i]);
+ ASSERT_TRUE(response_contains_json_fragment(results[i], "\"status\":\"ready\""));
+ if (i % 2 == 0) {
+ ASSERT_NULL(strstr(results[i], "EvidenceCacheSentinel"));
+ ASSERT_NULL(strstr(results[i], "\"return_type\""));
+ } else {
+ ASSERT_NOT_NULL(strstr(results[i], "EvidenceCacheSentinel"));
+ ASSERT_NOT_NULL(strstr(results[i], "\"return_type\""));
+ }
+ }
+ ASSERT_STR_EQ(results[0], results[2]);
+ ASSERT_STR_EQ(results[1], results[3]);
+ for (size_t i = 0; i < sizeof(results) / sizeof(results[0]); i++) {
+ free(results[i]);
+ }
+ cbm_mcp_server_free(srv);
+ restore_cache_dir(saved_cache_copy);
+ free(saved_cache_copy);
+ ASSERT_EQ(th_rmtree(cache), 0);
+ PASS();
+}
+
/* Regression for #281: handle_get_architecture must actually call
* cbm_store_get_architecture and surface its sections. Before the fix
* only label/edge histograms were emitted regardless of which aspects
@@ -19996,6 +20155,7 @@ SUITE(mcp) {
RUN_TEST(mcp_tools_array_schemas_have_items);
RUN_TEST(mcp_ingest_traces_items_disallow_additional_properties_issue731);
RUN_TEST(mcp_get_architecture_aspects_schema_enum_pr560);
+ RUN_TEST(mcp_get_architecture_behavior_evidence_schema);
RUN_TEST(mcp_text_result);
RUN_TEST(mcp_text_result_omits_structured_content_for_plain_text);
RUN_TEST(mcp_text_result_reversibly_encodes_invalid_utf8_as_standard_json);
@@ -20134,6 +20294,8 @@ SUITE(mcp) {
RUN_TEST(tool_trace_call_path_dts_stub_unions_with_impl);
RUN_TEST(tool_delete_project_not_found);
RUN_TEST(tool_get_architecture_empty);
+ RUN_TEST(tool_get_architecture_behavior_evidence_validation);
+ RUN_TEST(tool_get_architecture_behavior_evidence_cache_isolation);
RUN_TEST(tool_get_architecture_emits_populated_sections);
RUN_TEST(tool_get_architecture_overview_compact_subset_pr560);
RUN_TEST(tool_get_architecture_rejects_unknown_aspect_pr560);