Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(ui): keep large Galaxy scopes whole for the local agent
Bernhard Jackiewiczd53b008db84b
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsxindex e2519bce8..499dcbf36 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx@@ -910,18 +910,37 @@ describe('graph answers and answer limits', () => {expect(request[2].content).toContain('test_values_list');});+ // 40 callers with long names in their own files: the snapshot names 24, a default prompt fewer.+ const longCallers = () => {+ const callers = Array.from({ length: 40 }, (_, index) => ({ id: 2000 + index, name: `caller_with_a_long_descriptive_name_number_${index}`, label: 'Function',+ file_path: `tests/postgres_tests/callers/test_module_number_${index}.py`, x: 0, y: 0, z: 0, size: 1, color: '#999' }));+ return jsonbAggEvidence({ edges: callers.map(caller => ({ source: caller.id, target: 32360, type: 'CALLS' })), nodes: callers });+ };+ const capacityNote = () => [...[...container.querySelectorAll('.cbm-chat-turn')].at(-1)?.querySelectorAll('.cbm-chat-answer-note') ?? []]+ .map(item => item.textContent ?? '').find(note => note.includes('too large'));+it('marks an answer cut at the output token limit and shows the capacity of an oversized scope', async () => {const { props, runtime } = fixture();runtime.chat.mockImplementationOnce(async (_messages, _onToken, options) => {options?.onComplete?.({ stopReason: 'length' }); return 'A long list that';});- const many = Array.from({ length: 40 }, (_, index) => ({ source: 2000 + index, target: 32360, type: 'CALLS' }));- await render({ ...props, proactiveSelection: jsonbAggEvidence({ edges: many }) }); await click('Download & load');+ await render({ ...props, proactiveSelection: longCallers() }); await click('Download & load');await type('Explain this class'); await click('Send ↑');const notes = [...container.querySelectorAll('.cbm-chat-answer-note')].map(item => item.textContent);expect(notes).toContain('Shortened (token limit)');- expect(notes.some(note => /^15 nodes \/ 40 edges: too large for the local Qwen2\.5 Coder 0\.5B model; showing 24$/.test(note ?? ''))).toBe(true);+ const capacity = notes.map(note => /^55 nodes \/ 40 edges: too large for the local Qwen2\.5 Coder 0\.5B model; showing (\d+)$/.exec(note ?? '')).find(Boolean);+ expect(Number(capacity?.[1])).toBeGreaterThan(0);+ expect(Number(capacity?.[1])).toBeLessThan(24);+ expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toMatch(/\+\d+ more/);+ });++ it('does not blame the model when only the snapshot bounds the names', async () => {+ const { props, runtime } = fixture();+ const many = Array.from({ length: 40 }, (_, index) => ({ source: 2000 + index, target: 32360, type: 'CALLS' }));+ await render({ ...props, proactiveSelection: jsonbAggEvidence({ edges: many }) }); await click('Download & load');+ await type('Explain this class'); await click('Send ↑');expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toContain('+16 more');+ expect(capacityNote()).toBeUndefined();});it('leaves the oldest history out when the input limit is exceeded and says so', async () => {diff --git a/graph-ui/src/browser-ai/explanation-context.test.ts b/graph-ui/src/browser-ai/explanation-context.test.tsindex a5308280a..e614443f0 100644--- a/graph-ui/src/browser-ai/explanation-context.test.ts+++ b/graph-ui/src/browser-ai/explanation-context.test.ts@@ -1,7 +1,8 @@import { describe, expect, it } from 'vitest';import type { BrowserChatContext, BrowserChatReaderContext } from './chat-model';import { prepareExplanationContext } from './explanation-context';-import { JSONB_AGG_CALLERS, jsonbAggEvidence, jsonbAggScope } from './galaxy-evidence.fixture';+import { selectionEvidenceContext } from '../galaxy/selection-evidence';+import { JSONB_AGG_CALLERS, jsonbAggEvidence, jsonbAggScope, largeFolderScope } from './galaxy-evidence.fixture';function reader(text: string, kind: 'file' | 'selection' = 'file'): BrowserChatReaderContext {const lines = text.split('\n');@@ -188,6 +189,18 @@ describe('bounded explanation evidence', () => {expect(text).toMatch(/- CALLS from 71: .*; \+47 more/);});+ it('keeps a large documented scope readable and says when its snapshot cut relationships', () => {+ const whole = outputText(prepareExplanationContext(undefined, selectionEvidenceContext(largeFolderScope()), 6000));+ expect(whole).toContain('Incoming relationships: 150 from 150 symbols.');+ expect(whole).toContain('Outgoing relationships: 150 to 150 symbols.');+ expect(whole).not.toMatch(/Snapshot\.|Selected\.|Relationships\.|incompl/);+ const evidence = largeFolderScope();+ const cut = selectionEvidenceContext({ ...evidence, selected: { ...evidence.selected as object, notes: Array.from({ length: 13 }, () => 'n'.repeat(1200)) } });+ const text = outputText(prepareExplanationContext(undefined, cut, 6000));+ expect(text).toContain('counts and names can be incomplete');+ expect(text).not.toMatch(/Snapshot\.view|to 0 symbols|from 0 symbols/);+ });+it('says when a side was not loaded instead of reporting no callers', () => {const text = outputText(prepareExplanationContext(undefined, jsonbAggEvidence({ direction: 'outbound' })));expect(text).toContain('Incoming relationships: not loaded; the scope does not follow incoming edges.');diff --git a/graph-ui/src/browser-ai/explanation-context.ts b/graph-ui/src/browser-ai/explanation-context.tsindex 813f28be1..402b0101d 100644--- a/graph-ui/src/browser-ai/explanation-context.ts+++ b/graph-ui/src/browser-ai/explanation-context.ts@@ -16,7 +16,7 @@ export interface PreparedExplanationContext {fallback: string;/** Human-readable strings only; callers must still count the final model tokens. */characterCount: number;- /** Set when the selection's relationships did not all fit: scope size and how many are named. */+ /** Set when the prompt could not name every related symbol the evidence carried: scope size and how many are named. */capacity?: { nodes: number; edges: number; shown: number };}@@ -151,8 +151,9 @@ function graphFacts(value: unknown, name: string, maxCharacters: number): string}/** A fact renders itself into a character budget. Relationship facts count the- * names they could list, so a bounded prompt can say how much it left out. */-interface GraphFact { natural: number; render(budget: number): { text: string; listed?: number; total?: number } }+ * names the snapshot carried and how many fit, so a bounded prompt can say how+ * much it left out. */+interface GraphFact { natural: number; render(budget: number): { text: string; listed?: number; available?: number } }interface GraphPreparation { facts: GraphFact[]; limitations: string[]; scope?: { nodes: number; edges: number } }function fixedFact(fact: string): GraphFact {@@ -178,13 +179,14 @@ function fitGraphFact(fact: string, budget: number): string {function relationshipFact(galaxy: GalaxyEvidence, side: 'incoming' | 'outgoing'): GraphFact {const words = relationshipWords.en, groups = galaxy.relationships[side];const total = groups.reduce((sum, group) => sum + group.count, 0);+ const available = groups.reduce((sum, group) => sum + group.files.reduce((names, file) => names + file.symbols.length, 0), 0);const empty = !sideLoaded(galaxy, side) ? (side === 'incoming' ? words.incomingNotLoaded : words.outgoingNotLoaded)- : !groups.length ? (side === 'incoming' ? words.noIncoming : words.noOutgoing) : undefined;+ : !groups.length ? (galaxy.truncated ? words.cut(side) : side === 'incoming' ? words.noIncoming : words.noOutgoing) : undefined;const header = side === 'incoming' ? words.incoming(total, galaxy.relationships.incomingSymbols): words.outgoing(total, galaxy.relationships.outgoingSymbols);const render = (budget: number) => {if (empty) return { text: empty.length <= budget ? empty : '' };- if (header.length > budget) return { text: '', listed: 0, total };+ if (header.length > budget) return { text: '', listed: 0, available };const natural = groups.map(group => relationshipLine(group, side, Infinity, words).text.length + 1);const shares = fairShares(natural, budget - header.length);const lines = groups.map((group, index) => relationshipLine(group, side, shares[index] - 1, words));@@ -192,7 +194,7 @@ function relationshipFact(galaxy: GalaxyEvidence, side: 'incoming' | 'outgoing')const note = omittedTypes ? words.moreTypes(omittedTypes) : '';const text = [header, ...lines.filter(item => item.text).map(item => item.text)].join('\n');return { text: note && text.length + note.length + 1 <= budget ? `${text}\n${note}` : text,- listed: lines.reduce((sum, item) => sum + item.listed, 0), total };+ listed: lines.reduce((sum, item) => sum + item.listed, 0), available };};return { natural: render(Infinity).text.length, render };}@@ -268,20 +270,21 @@ export function prepareExplanationContext(reader?: BrowserChatReaderContext,? 'sampled source regions, not the full file' : 'only a prefix of the selected source is included'}. Ranges identify the literal excerpts.`);const evidence = code.evidence;const remaining = evidenceBudget - evidence.reduce((count, item) => count + item.text.length, 0);- let omittedFacts = 0, listed = 0, related = 0;+ let omittedFacts = 0, listed = 0, available = 0;const facts = selectedGraphs.flatMap(prepared => prepared.facts);// Leave room for relationships as well as selected identity: short facts stay// whole and long ones share the rest. Never silently cut a quoted field.const shares = fairShares(facts.map(fact => fact.natural), remaining);facts.forEach((fact, index) => {const rendered = fact.render(shares[index]);- listed += rendered.listed ?? 0; related += rendered.total ?? 0;+ listed += rendered.listed ?? 0; available += rendered.available ?? 0;if (rendered.text) evidence.push({ id: `graph-${evidence.filter(item => item.source === 'graph').length + 1}`, text: rendered.text, source: 'graph' });else omittedFacts++;});if (omittedFacts) desiredLimits.splice(code.omitted ? 1 : 0, 0, `${omittedFacts} graph fact groups omitted from this explanation.`);const scope = selectedGraphs.find(prepared => prepared.scope)?.scope;- const capacity = scope && listed < related ? { ...scope, shown: listed } : undefined;+ // Only the prompt budget is the model's capacity; the snapshot's own name bound is not.+ const capacity = scope && listed < available ? { ...scope, shown: listed } : undefined;const limitations: string[] = [];let limitRemaining = limitBudget;for (let index = 0; index < desiredLimits.length; index++) {diff --git a/graph-ui/src/browser-ai/galaxy-evidence.fixture.ts b/graph-ui/src/browser-ai/galaxy-evidence.fixture.tsindex 3a0e7e302..afab5a94e 100644--- a/graph-ui/src/browser-ai/galaxy-evidence.fixture.ts+++ b/graph-ui/src/browser-ai/galaxy-evidence.fixture.ts@@ -1,4 +1,4 @@-import { graphNodeEvidence, scopeRelationships, selectionEvidenceContext } from '../galaxy/selection-evidence';+import { galaxyScopeEvidence, selectionEvidenceContext, type GalaxyScope, type SelectionEvidence } from '../galaxy/selection-evidence';import type { GraphEdge, GraphNode } from '../galaxy/types';import type { BrowserChatContext } from './chat-model';@@ -25,14 +25,29 @@ export function jsonbAggScope(): { nodes: GraphNode[]; edges: GraphEdge[]; roots}/** The context GalaxyPanel publishes for that scope, with optional scope overrides. */-export function jsonbAggEvidence(overrides: { depth?: number; direction?: string; state?: string; edges?: GraphEdge[] } = {}): BrowserChatContext {+export function jsonbAggEvidence(overrides: { depth?: number; direction?: string; state?: GalaxyScope['state']; edges?: GraphEdge[]; nodes?: GraphNode[] } = {}): BrowserChatContext {const scope = jsonbAggScope();- const edges = overrides.edges ?? scope.edges;const [root] = scope.nodes;- return selectionEvidenceContext({ project: 'django-demo', view: 'galaxy', source: 'query_graph scoped indexed relationships', label: 'JSONBAgg',- selected: { scope: { kind: 'symbol', qualifiedName: root.qualified_name, name: 'JSONBAgg' }, rootCount: 1, roots: [graphNodeEvidence(root)], omittedRoots: 0 },- scope: { depth: overrides.depth ?? 1, direction: overrides.direction ?? 'both', edgeTypes: 'all', nodes: scope.nodes.length, edges: edges.length },- relationships: scopeRelationships(scope.nodes, edges, scope.roots),- limitations: { state: overrides.state ?? 'complete-indexed-scope', exhausted: false, indexCoverage: 'unavailable',- interpretation: 'Static indexed relationships, not runtime activity.' } });+ return selectionEvidenceContext(galaxyScopeEvidence({ project: 'django-demo', identity: { kind: 'symbol', qualifiedName: root.qualified_name!, name: 'JSONBAgg' },+ nodes: [...scope.nodes, ...overrides.nodes ?? []], edges: overrides.edges ?? scope.edges, roots: scope.roots,+ depth: overrides.depth ?? 1, direction: overrides.direction ?? 'both', edgeTypes: 'all',+ state: overrides.state ?? 'complete-indexed-scope', exhausted: false }));+}++/** A folder of 40 documented symbols with five incoming and five outgoing edge types of 30 symbols each. */+export function largeFolderScope(): SelectionEvidence {+ const node = (id: number, name: string, file: string, documentation?: string): GraphNode => ({ id, name, label: 'Function', qualified_name: `pkg.${file}.${name}`,+ file_path: `django/contrib/postgres/aggregates/${file}.py`, start_line: 10, end_line: 20, documentation, x: 0, y: 0, z: 0, size: 1, color: '#999' });+ const roots = Array.from({ length: 40 }, (_, index) => node(index + 1, `postgres_member_${index}`, 'members', 'd'.repeat(1500)));+ const types = ['CALLS', 'TESTS', 'USAGE', 'IMPORTS', 'DEFINES_METHOD'];+ const nodes: GraphNode[] = [...roots], edges: GraphEdge[] = [];+ types.forEach((type, typeIndex) => (['incoming', 'outgoing'] as const).forEach(side => {+ for (let index = 0; index < 30; index++) {+ const id = 1000 + typeIndex * 100 + (side === 'incoming' ? 0 : 50) + index;+ nodes.push(node(id, `${side}_${type.toLowerCase()}_relationship_${index}`, `${side}_module_${Math.floor(index / 3)}`));+ edges.push(side === 'incoming' ? { source: id, target: 1 + index, type } : { source: 1 + index, target: id, type });+ }+ }));+ return galaxyScopeEvidence({ project: 'django-demo', identity: { kind: 'folder', path: 'django/contrib/postgres', name: 'postgres' }, nodes, edges,+ roots: new Set(roots.map(root => root.id)), depth: 1, direction: 'both', edgeTypes: 'all', state: 'complete-indexed-scope', exhausted: false });}diff --git a/graph-ui/src/browser-ai/galaxy-evidence.ts b/graph-ui/src/browser-ai/galaxy-evidence.tsindex ed19f7558..62651e4ea 100644--- a/graph-ui/src/browser-ai/galaxy-evidence.ts+++ b/graph-ui/src/browser-ai/galaxy-evidence.ts@@ -19,7 +19,10 @@ export interface GalaxyEvidence {state: 'complete' | 'loading' | 'partial';error?: string;exhausted: boolean;- relationships: ScopeRelationships;+ /** Distinct related symbols per side; undefined when the snapshot lost the total. */+ relationships: Omit<ScopeRelationships, 'incomingSymbols' | 'outgoingSymbols'> & { incomingSymbols?: number; outgoingSymbols?: number };+ /** The snapshot budget cut relationship data, so counts and names can be incomplete. */+ truncated: boolean;}const record = (value: unknown): Record<string, unknown> | undefined => value !== null && typeof value === 'object' && !Array.isArray(value)@@ -51,13 +54,17 @@ export function readGalaxyEvidence(snapshot: string): GalaxyEvidence | undefinedlet parsed: Record<string, unknown> | undefined;try { parsed = record(JSON.parse(snapshot)); } catch { return undefined; }const evidence = record(parsed?.evidence);- const relationships = record(evidence?.relationships);- if (evidence?.kind !== 'current-selection-evidence' || evidence.view !== 'galaxy' || !relationships- || !Array.isArray(relationships.incoming) || !Array.isArray(relationships.outgoing)) return undefined;- const selected = record(evidence.selected), scope = record(evidence.scope), limits = record(evidence.limitations);+ const selected = record(evidence?.selected), scope = record(evidence?.scope), limits = record(evidence?.limitations);const identity = record(selected?.scope);- const direction = scope?.direction === 'inbound' || scope?.direction === 'outbound' ? scope.direction : 'both';- const edgeTypes = Array.isArray(scope?.edgeTypes) ? scope.edgeTypes.flatMap(type => text(type, 60) ?? []) : 'all';+ // A traced Galaxy scope, recognised by its identity and depth even when its relationships were cut.+ if (evidence?.kind !== 'current-selection-evidence' || evidence.view !== 'galaxy' || typeof identity?.kind !== 'string'+ || typeof scope?.depth !== 'number') return undefined;+ const relationships = record(evidence.relationships);+ const truncated = !relationships || !Array.isArray(relationships.incoming) || !Array.isArray(relationships.outgoing)+ || records(parsed?.omissions).some(item => typeof item.path === 'string' && item.path.startsWith('$.relationships'));+ const total = (value: unknown) => typeof value === 'number' ? count(value) : undefined;+ const direction = scope.direction === 'inbound' || scope.direction === 'outbound' ? scope.direction : 'both';+ const edgeTypes = Array.isArray(scope.edgeTypes) ? scope.edgeTypes.flatMap(type => text(type, 60) ?? []) : 'all';const state = limits?.state === 'complete-indexed-scope' ? 'complete' : limits?.state === 'loading-partial-preview' ? 'loading' : 'partial';const roots = records(selected?.roots).flatMap(root => {const name = text(root.name, 120);@@ -65,14 +72,15 @@ export function readGalaxyEvidence(snapshot: string): GalaxyEvidence | undefinedendLine: line(root.endLine), documentation: text(root.documentation, 300) }] : [];});return {- project: text(evidence.project, 120) ?? '', label: text(identity?.name, 120) ?? roots[0]?.name ?? 'selection',- identity: identity ?? null, selectionKind: text(identity?.kind, 20) ?? 'node',+ project: text(evidence.project, 120) ?? '', label: text(identity.name, 120) ?? roots[0]?.name ?? 'selection',+ identity, selectionKind: text(identity.kind, 20) ?? 'node',roots, rootCount: Math.max(count(selected?.rootCount), roots.length),- depth: count(scope?.depth), direction, edgeTypes, nodes: count(scope?.nodes), edges: count(scope?.edges),+ depth: count(scope.depth), direction, edgeTypes, nodes: count(scope.nodes), edges: count(scope.edges),state, error: text(limits?.error, 200), exhausted: limits?.exhausted === true,- relationships: { incoming: groups(relationships.incoming), incomingSymbols: count(relationships.incomingSymbols),- outgoing: groups(relationships.outgoing), outgoingSymbols: count(relationships.outgoingSymbols),- internal: totals(relationships.internal), beyond: totals(relationships.beyond) },+ relationships: { incoming: groups(relationships?.incoming), incomingSymbols: total(relationships?.incomingSymbols),+ outgoing: groups(relationships?.outgoing), outgoingSymbols: total(relationships?.outgoingSymbols),+ internal: totals(relationships?.internal), beyond: totals(relationships?.beyond) },+ truncated,};}@@ -121,8 +129,8 @@ export function scopeSentence(evidence: GalaxyEvidence, words: RelationshipWordsconst direction = evidence.direction === 'inbound' ? words.inbound : evidence.direction === 'outbound' ? words.outbound : words.both;const types = evidence.edgeTypes === 'all' ? words.allTypes : words.onlyTypes(evidence.edgeTypes);const state = evidence.state === 'complete' ? words.complete : evidence.state === 'loading' ? words.loading : words.partial(evidence.error);- return words.scope(`${words.hops(evidence.depth)} ${direction}, ${types}`, words.size(evidence.nodes, evidence.edges),- evidence.state === 'complete' && evidence.exhausted ? `${state}; ${words.exhausted}` : state);+ const notes = [state, ...evidence.state === 'complete' && evidence.exhausted ? [words.exhausted] : [], ...evidence.truncated ? [words.truncated] : []];+ return words.scope(`${words.hops(evidence.depth)} ${direction}, ${types}`, words.size(evidence.nodes, evidence.edges), notes.join('; '));}/** Whether the loaded scope followed this side at all; otherwise "none" would be a guess. */diff --git a/graph-ui/src/browser-ai/relationship-answer.test.ts b/graph-ui/src/browser-ai/relationship-answer.test.tsindex 087c71d2c..c5da4a689 100644--- a/graph-ui/src/browser-ai/relationship-answer.test.ts+++ b/graph-ui/src/browser-ai/relationship-answer.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';-import { JSONB_AGG_CALLERS, jsonbAggEvidence } from './galaxy-evidence.fixture';+import { selectionEvidenceContext } from '../galaxy/selection-evidence';+import { JSONB_AGG_CALLERS, jsonbAggEvidence, largeFolderScope } from './galaxy-evidence.fixture';import { relationshipAnswer, relationshipQuestion } from './relationship-answer';const line = (markdown: string, type: string) => markdown.split('\n').find(item => item.startsWith(`- **${type}** `)) ?? '';@@ -74,6 +75,22 @@ describe('listed relationship answers', () => {expect(line(answer.markdown, 'CALLS')).toMatch(/^- \*\*CALLS\*\* from 40: .*; \+16 more$/);});+ it('answers for a large documented scope with complete counts and every edge type', () => {+ const markdown = relationshipAnswer('What does postgres call?', [selectionEvidenceContext(largeFolderScope())])!.markdown;+ expect(markdown).toContain('Outgoing relationships: 150 to 150 symbols.');+ for (const type of ['CALLS', 'TESTS', 'USAGE', 'IMPORTS', 'DEFINES_METHOD']) expect(line(markdown, type)).toMatch(/^- \*\*\w+\*\* to 30: .*; \+\d+ more$/);+ expect(markdown).toContain('complete for the indexed graph.');+ });++ it('says so when the snapshot cut relationships instead of claiming a complete list', () => {+ const evidence = largeFolderScope();+ const cut = selectionEvidenceContext({ ...evidence, selected: { ...evidence.selected as object, notes: Array.from({ length: 13 }, () => 'n'.repeat(1200)) } });+ const markdown = relationshipAnswer('What does postgres call?', [cut])!.markdown;+ expect(markdown).not.toMatch(/to 0 symbols/);+ expect(markdown).toContain('the snapshot left part of its relationships out, so counts and names can be incomplete');+ expect(markdown).toMatch(/Outgoing relationships: left out of this snapshot\.|Outgoing relationships: \d+\./);+ });+it('leaves questions about another symbol, attached non-Galaxy evidence and other questions to the model', () => {expect(relationshipAnswer('Who calls BaseCommand?', [jsonbAggEvidence()])).toBeUndefined();expect(relationshipAnswer('Who calls JSONBAgg?', [{ id: 'g', label: 'Callers', text: '{"kind":"graph-context-snapshot"}' }])).toBeUndefined();diff --git a/graph-ui/src/browser-ai/relationship-answer.ts b/graph-ui/src/browser-ai/relationship-answer.tsindex 903eed999..581aea047 100644--- a/graph-ui/src/browser-ai/relationship-answer.ts+++ b/graph-ui/src/browser-ai/relationship-answer.ts@@ -37,7 +37,7 @@ function listed(question: RelationshipQuestion, evidence: GalaxyEvidence): strinif (evidence.depth === 0) { sections.push(`${heading}. ${words.notExpanded}`); continue; }if (!sideLoaded(evidence, side)) { sections.push(`${heading}. ${words.notLoaded(side)}`); continue; }const groups = evidence.relationships[side];- if (!groups.length) { sections.push(`${heading}. ${words.noRelationships}`); continue; }+ if (!groups.length) { sections.push(`${heading}. ${evidence.truncated ? words.cut(side) : words.noRelationships}`); continue; }const symbols = side === 'incoming' ? evidence.relationships.incomingSymbols : evidence.relationships.outgoingSymbols;const total = groups.reduce((sum, group) => sum + group.count, 0);const calls = groups.find(group => group.type === 'CALLS');diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.tsindex eb0afe296..a1c707827 100644--- a/graph-ui/src/browser-ai/strings.ts+++ b/graph-ui/src/browser-ai/strings.ts@@ -46,12 +46,14 @@ const englishRelationshipWords = {partial: (error?: string) => `incomplete${error ? `: ${error}` : ''}`,exhausted: 'nothing further beyond this depth',scope: (shape: string, size: string, state: string) => `Scope: ${shape}; ${size}; ${state}.`,- incoming: (total: number, symbols: number) => `Incoming relationships: ${total} from ${symbols} ${symbols === 1 ? 'symbol' : 'symbols'}.`,- outgoing: (total: number, symbols: number) => `Outgoing relationships: ${total} to ${symbols} ${symbols === 1 ? 'symbol' : 'symbols'}.`,+ incoming: (total: number, symbols?: number) => `Incoming relationships: ${total}${symbols === undefined ? '' : ` from ${symbols} ${symbols === 1 ? 'symbol' : 'symbols'}`}.`,+ outgoing: (total: number, symbols?: number) => `Outgoing relationships: ${total}${symbols === undefined ? '' : ` to ${symbols} ${symbols === 1 ? 'symbol' : 'symbols'}`}.`,noIncoming: 'Incoming relationships: none in this scope.',noOutgoing: 'Outgoing relationships: none in this scope.',incomingNotLoaded: 'Incoming relationships: not loaded; the scope does not follow incoming edges.',outgoingNotLoaded: 'Outgoing relationships: not loaded; the scope does not follow outgoing edges.',+ cut: (side: 'incoming' | 'outgoing') => `${side === 'incoming' ? 'Incoming' : 'Outgoing'} relationships: left out of this snapshot.`,+ truncated: 'the snapshot left part of its relationships out, so counts and names can be incomplete',moreTypes: (count: number) => `+${count} more relationship ${count === 1 ? 'type' : 'types'}`,internal: (summary: string) => `Between the selected symbols: ${summary}.`,beyond: (summary: string) => `Further out in the scope: ${summary}.`,@@ -85,12 +87,14 @@ export const relationshipWords: { en: RelationshipWords; de: RelationshipWords }partial: (error?: string) => `unvollständig${error ? `: ${error}` : ''}`,exhausted: 'dahinter folgt nichts mehr',scope: (shape: string, size: string, state: string) => `Ausschnitt: ${shape}; ${size}; ${state}.`,- incoming: (total: number, symbols: number) => `Eingehende Beziehungen: ${total} von ${symbols} ${symbols === 1 ? 'Symbol' : 'Symbolen'}.`,- outgoing: (total: number, symbols: number) => `Ausgehende Beziehungen: ${total} zu ${symbols} ${symbols === 1 ? 'Symbol' : 'Symbolen'}.`,+ incoming: (total: number, symbols?: number) => `Eingehende Beziehungen: ${total}${symbols === undefined ? '' : ` von ${symbols} ${symbols === 1 ? 'Symbol' : 'Symbolen'}`}.`,+ outgoing: (total: number, symbols?: number) => `Ausgehende Beziehungen: ${total}${symbols === undefined ? '' : ` zu ${symbols} ${symbols === 1 ? 'Symbol' : 'Symbolen'}`}.`,noIncoming: 'Eingehende Beziehungen: keine in diesem Ausschnitt.',noOutgoing: 'Ausgehende Beziehungen: keine in diesem Ausschnitt.',incomingNotLoaded: 'Eingehende Beziehungen: nicht geladen; der Ausschnitt folgt keinen eingehenden Kanten.',outgoingNotLoaded: 'Ausgehende Beziehungen: nicht geladen; der Ausschnitt folgt keinen ausgehenden Kanten.',+ cut: (side: 'incoming' | 'outgoing') => `${side === 'incoming' ? 'Eingehende' : 'Ausgehende'} Beziehungen: in diesem Schnappschuss ausgelassen.`,+ truncated: 'der Schnappschuss hat einen Teil der Beziehungen ausgelassen, Anzahlen und Namen können unvollständig sein',moreTypes: (count: number) => `+${count} weitere ${count === 1 ? 'Beziehungstyp' : 'Beziehungstypen'}`,internal: (summary: string) => `Zwischen den ausgewählten Symbolen: ${summary}.`,beyond: (summary: string) => `Weiter außen im Ausschnitt: ${summary}.`,diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsxindex 2467352e6..ae122b5c4 100644--- a/graph-ui/src/galaxy/GalaxyPanel.tsx+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx@@ -143,7 +143,7 @@ import { useGraphScope } from './use-graph-scope';import { limitGraphRender, scopedHierarchy } from './graph-scope';import './graph-exploration.css';import { layoutNodeForSelection } from './selected-node';-import { graphNodeEvidence, scopeRelationships, useSelectionEvidence, type SelectionEvidenceListener } from './selection-evidence';+import { galaxyScopeEvidence, useSelectionEvidence, type SelectionEvidenceListener } from './selection-evidence';import { buildCoverageShadow } from './coverage-shadow';import type { CoverageShadowNode } from './coverage-shadow';import {@@ -1134,24 +1134,12 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {);const traceKinds = useMemo(() => edgeKinds(shown), [shown]);- const agentEvidence = useMemo(() => {- if (!scope.scope) return undefined;- const selected = scope.result?.data;- const rootIds = scope.result?.roots ?? new Set<number>();- const roots = selected?.nodes.filter(node => rootIds.has(node.id)) ?? [];- const edges = selected?.edges ?? [];- // Every scope edge is classified against the roots first; only the names are- // bounded afterwards. Render budgets are a drawing concern and stay out of it.- return { project, view: 'galaxy', source: 'query_graph scoped indexed relationships', label: scope.scope.name,- selected: { scope: scope.scope, rootCount: roots.length, roots: roots.slice(0, 8).map(graphNodeEvidence), omittedRoots: Math.max(0, roots.length - 8) },- scope: { depth: scope.depth, direction: props.workspaceExpanded ? scope.direction : 'both', edgeTypes: traceTypes ?? 'all',- nodes: selected?.nodes.length ?? 0, edges: edges.length },- relationships: scopeRelationships(selected?.nodes ?? [], edges, rootIds),- limitations: { state: scope.complete ? 'complete-indexed-scope' : scope.loading ? 'loading-partial-preview' : 'partial', error: scope.error,- exhausted: scope.result?.exhausted, indexCoverage: 'unavailable',- interpretation: 'Static indexed relationships, not runtime activity. Scope completeness is relative to the indexed graph and selected depth/types.' },- };- }, [project, scope.scope, scope.result, scope.depth, scope.direction, scope.complete, scope.loading, scope.error, traceTypes, props.workspaceExpanded]);+ const agentEvidence = useMemo(() => scope.scope ? galaxyScopeEvidence({ project, identity: scope.scope,+ nodes: scope.result?.data.nodes ?? [], edges: scope.result?.data.edges ?? [], roots: scope.result?.roots ?? new Set<number>(),+ depth: scope.depth, direction: props.workspaceExpanded ? scope.direction : 'both', edgeTypes: traceTypes ?? 'all',+ state: scope.complete ? 'complete-indexed-scope' : scope.loading ? 'loading-partial-preview' : 'partial',+ error: scope.error, exhausted: scope.result?.exhausted }) : undefined,+ [project, scope.scope, scope.result, scope.depth, scope.direction, scope.complete, scope.loading, scope.error, traceTypes, props.workspaceExpanded]);useSelectionEvidence(props.onSelectionEvidence, agentEvidence, visible && props.workspaceExpanded === true);const toggleKind = useCallback((type: string) => {if (props.workspaceExpanded && scope.scope) {diff --git a/graph-ui/src/galaxy/selection-evidence.test.tsx b/graph-ui/src/galaxy/selection-evidence.test.tsxindex 1bd6e9e22..d7028bfe8 100644--- a/graph-ui/src/galaxy/selection-evidence.test.tsx+++ b/graph-ui/src/galaxy/selection-evidence.test.tsx@@ -2,6 +2,8 @@import { act } from 'react';import { createRoot } from 'react-dom/client';import { expect, it, vi } from 'vitest';+import { readGalaxyEvidence } from '../browser-ai/galaxy-evidence';+import { largeFolderScope } from '../browser-ai/galaxy-evidence.fixture';import { graphNodeEvidence, RELATED_NAMES_PER_GROUP, scopeRelationships, selectionEvidenceContext, useSelectionEvidence, type SelectionEvidence } from './selection-evidence';const evidence: SelectionEvidence = { project: 'sample', view: 'galaxy', label: 'read', source: 'indexed graph',@@ -58,6 +60,41 @@ it('classifies every scope edge by direction relative to the roots before boundiexpect(JSON.parse(context.text).evidence.relationships).toEqual(related);});+it('keeps every relationship count and type of a large documented scope inside the snapshot budget', () => {+ const context = selectionEvidenceContext(largeFolderScope());+ const snapshot = JSON.parse(context.text);+ expect(context.text.length).toBeLessThan(14_000);+ expect(snapshot.omissions.filter((omission: { path: string }) => omission.path.startsWith('$.relationships'))).toEqual([]);+ const galaxy = readGalaxyEvidence(context.text)!;+ expect(galaxy.truncated).toBe(false);+ for (const side of ['incoming', 'outgoing'] as const) {+ expect(galaxy.relationships[side].map(group => [group.type, group.count]).sort()).toEqual(+ ['CALLS', 'DEFINES_METHOD', 'IMPORTS', 'TESTS', 'USAGE'].map(type => [type, 30]));+ // Names share the budget: every group lists some, none beyond its bound, and none is cut.+ for (const group of galaxy.relationships[side]) {+ const names = group.files.flatMap(file => file.symbols.map(symbol => symbol.name));+ expect(names.length).toBeGreaterThanOrEqual(5);+ expect(names.length).toBeLessThanOrEqual(RELATED_NAMES_PER_GROUP);+ for (const name of names) expect(name).toMatch(/_relationship_\d+$/);+ }+ }+ expect(galaxy.relationships.incomingSymbols).toBe(150);+ expect(galaxy.relationships.outgoingSymbols).toBe(150);+ expect(galaxy.rootCount).toBe(40);+ expect(galaxy.roots).toHaveLength(8);+ expect(galaxy.roots[0].documentation).toHaveLength(300);+});++it('reads a snapshot whose relationships were cut as truncated instead of complete', () => {+ const evidence = largeFolderScope();+ // Another producer's oversized selection pushes the relationships out of the budget.+ const context = selectionEvidenceContext({ ...evidence, selected: { ...evidence.selected as object, notes: Array.from({ length: 13 }, () => 'n'.repeat(1200)) } });+ const galaxy = readGalaxyEvidence(context.text)!;+ expect(galaxy).toBeDefined();+ expect(galaxy.truncated).toBe(true);+ expect(galaxy.label).toBe('postgres');+});+it('does not republish equivalent evidence or let hidden workspaces replace the active selection, and clears on background', async () => {(globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;const host = document.createElement('div'), root = createRoot(host), listener = vi.fn();diff --git a/graph-ui/src/galaxy/selection-evidence.ts b/graph-ui/src/galaxy/selection-evidence.tsindex bf1f6078b..af365592c 100644--- a/graph-ui/src/galaxy/selection-evidence.ts+++ b/graph-ui/src/galaxy/selection-evidence.ts@@ -1,5 +1,7 @@import { useEffect } from 'react';import type { BrowserChatContext } from '../browser-ai/chat-model';+import { fairShares } from '../browser-ai/galaxy-evidence';+import type { GraphScope } from './graph-scope';import type { GraphEdge, GraphNode } from './types';export type SelectionEvidenceListener = (context: BrowserChatContext | undefined) => void;@@ -27,21 +29,36 @@ export function graphNodeEvidence(node: GraphNode) {* complete; `files` lists at most `RELATED_NAMES_PER_GROUP` symbols. */export interface RelationshipGroup { type: string; count: number; files: { path: string; symbols: { name: string; kind?: string }[] }[] }export interface ScopeRelationships {- /** Edges into a selected root from outside the selection. */- incoming: RelationshipGroup[];incomingSymbols: number;- /** Edges from a selected root to outside the selection. */- outgoing: RelationshipGroup[];outgoingSymbols: number;/** Edge counts between selected roots and between symbols further out. */internal: { type: string; count: number }[];beyond: { type: string; count: number }[];+ /** Edges into a selected root from outside the selection. */+ incoming: RelationshipGroup[];+ /** Edges from a selected root to outside the selection. */+ outgoing: RelationshipGroup[];}export const RELATED_NAMES_PER_GROUP = 24;+/** Characters of names and paths across every group of both sides. With the bounded+ * roots this keeps a scope inside the snapshot budget, so no count or type is cut. */+export const RELATED_NAME_CHARACTERS = 6000;+/** Readers of the evidence use no more of a root's documentation than this. */+export const ROOT_DOCUMENTATION_CHARACTERS = 300;+const ROOTS_LISTED = 8;++type RelatedSymbol = { name: string; kind?: string; path: string };+/** Roughly what a listed symbol, and the first symbol of each file, add to the snapshot. */+function namesCost(symbols: readonly RelatedSymbol[]): number {+ return symbols.reduce((sum, symbol, index) => sum + symbol.name.length + (symbol.kind?.length ?? 0) + 24+ + (index === 0 || symbols[index - 1].path !== symbol.path ? symbol.path.length + 24 : 0), 0);+}/** Classify every scope edge by its direction relative to the roots before any- * bound applies, so counts stay complete and callers never mix with callees. */-export function scopeRelationships(nodes: readonly GraphNode[], edges: readonly GraphEdge[], roots: ReadonlySet<number>): ScopeRelationships {+ * bound applies, so counts stay complete and callers never mix with callees.+ * Counts come first; names share an explicit budget fairly between the groups. */+export function scopeRelationships(nodes: readonly GraphNode[], edges: readonly GraphEdge[], roots: ReadonlySet<number>,+ nameCharacters = RELATED_NAME_CHARACTERS): ScopeRelationships {const byId = new Map(nodes.map(node => [node.id, node]));const related = { incoming: new Map<string, Set<number>>(), outgoing: new Map<string, Set<number>>() };const counted = { internal: new Map<string, number>(), beyond: new Map<string, number>() };@@ -56,7 +73,7 @@ export function scopeRelationships(nodes: readonly GraphNode[], edges: readonlyside.set(edge.type, (side.get(edge.type) ?? 0) + 1);}}- const groups = (side: Map<string, Set<number>>): RelationshipGroup[] => [...side].map(([type, members]) => {+ const ranked = (members: ReadonlySet<number>): RelatedSymbol[] => {const symbols = [...members].map(id => {const node = byId.get(id);return { name: node?.name ?? `#${id}`, kind: node?.label || undefined, path: node?.file_path ?? '' };@@ -64,18 +81,56 @@ export function scopeRelationships(nodes: readonly GraphNode[], edges: readonlyconst perFile = new Map<string, number>();symbols.forEach(symbol => perFile.set(symbol.path, (perFile.get(symbol.path) ?? 0) + 1));// Files with the most related symbols first, so a bounded list keeps the densest evidence.- symbols.sort((left, right) => perFile.get(right.path)! - perFile.get(left.path)!- || left.path.localeCompare(right.path) || left.name.localeCompare(right.name));+ return symbols.sort((left, right) => perFile.get(right.path)! - perFile.get(left.path)!+ || left.path.localeCompare(right.path) || left.name.localeCompare(right.name)).slice(0, RELATED_NAMES_PER_GROUP);+ };+ const ordered = (side: Map<string, Set<number>>) => [...side].sort(([leftType, left], [rightType, right]) =>+ right.size - left.size || leftType.localeCompare(rightType));+ const sides = [ordered(related.incoming), ordered(related.outgoing)];+ const candidates = sides.flat().map(([, members]) => ranked(members));+ const shares = fairShares(candidates.map(namesCost), nameCharacters);+ let next = 0;+ const [incoming, outgoing] = sides.map(side => side.map(([type, members]): RelationshipGroup => {+ const index = next++;+ let symbols = candidates[index];+ while (symbols.length && namesCost(symbols) > shares[index]) symbols = symbols.slice(0, -1);const files = new Map<string, { name: string; kind?: string }[]>();- for (const { path, ...symbol } of symbols.slice(0, RELATED_NAMES_PER_GROUP)) files.set(path, [...files.get(path) ?? [], symbol]);+ for (const { path, ...symbol } of symbols) files.set(path, [...files.get(path) ?? [], symbol]);return { type, count: members.size, files: [...files].map(([path, listed]) => ({ path, symbols: listed })) };- }).sort((left, right) => right.count - left.count || left.type.localeCompare(right.type));+ }));const distinct = (side: Map<string, Set<number>>) => new Set([...side.values()].flatMap(members => [...members])).size;const totals = (side: Map<string, number>) => [...side].map(([type, count]) => ({ type, count })).sort((left, right) => right.count - left.count || left.type.localeCompare(right.type));- return { incoming: groups(related.incoming), incomingSymbols: distinct(related.incoming),- outgoing: groups(related.outgoing), outgoingSymbols: distinct(related.outgoing),- internal: totals(counted.internal), beyond: totals(counted.beyond) };+ return { incomingSymbols: distinct(related.incoming), outgoingSymbols: distinct(related.outgoing),+ internal: totals(counted.internal), beyond: totals(counted.beyond), incoming, outgoing };+}++/** A traced Galaxy scope as the local agent reads it. */+export interface GalaxyScope {+ project: string;+ identity: GraphScope;+ nodes: readonly GraphNode[];+ edges: readonly GraphEdge[];+ roots: ReadonlySet<number>;+ depth: number;+ direction: string;+ edgeTypes: readonly string[] | 'all';+ state: 'complete-indexed-scope' | 'loading-partial-preview' | 'partial';+ error?: string;+ exhausted?: boolean;+}++/** Every scope edge is classified against the roots first; only the names are+ * bounded afterwards. Render budgets are a drawing concern and stay out of it. */+export function galaxyScopeEvidence(scope: GalaxyScope): SelectionEvidence {+ const roots = scope.nodes.filter(node => scope.roots.has(node.id));+ return { project: scope.project, view: 'galaxy', source: 'query_graph scoped indexed relationships', label: scope.identity.name,+ selected: { scope: scope.identity, rootCount: roots.length, roots: roots.slice(0, ROOTS_LISTED).map(root => ({ ...graphNodeEvidence(root),+ documentation: root.documentation?.slice(0, ROOT_DOCUMENTATION_CHARACTERS) })), omittedRoots: Math.max(0, roots.length - ROOTS_LISTED) },+ scope: { depth: scope.depth, direction: scope.direction, edgeTypes: scope.edgeTypes, nodes: scope.nodes.length, edges: scope.edges.length },+ relationships: scopeRelationships(scope.nodes, scope.edges, scope.roots),+ limitations: { state: scope.state, error: scope.error, exhausted: scope.exhausted, indexCoverage: 'unavailable',+ interpretation: 'Static indexed relationships, not runtime activity. Scope completeness is relative to the indexed graph and selected depth/types.' } };}/** Bound every collection/string and the total snapshot; report each omission.