@denizokcu/haze 1.7.11 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +142 -102
- package/SECURITY.md +1 -1
- package/assets/graph-grammars/NOTICE.md +21 -0
- package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
- package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
- package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.js +4056 -0
- package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
- package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
- package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
- package/bin/haze.js +47 -19
- package/dist/buildInfo.json +3 -3
- package/dist/cli/chat/BusyBar.d.ts +1 -2
- package/dist/cli/chat/ChatHeader.d.ts +6 -0
- package/dist/cli/chat/ChatHeader.js +11 -0
- package/dist/cli/chat/ChatScreen.d.ts +16 -0
- package/dist/cli/chat/ChatScreen.js +399 -0
- package/dist/cli/chat/ChatScreenView.d.ts +68 -0
- package/dist/cli/chat/ChatScreenView.js +47 -0
- package/dist/cli/chat/LiveTail.d.ts +11 -0
- package/dist/cli/chat/LiveTail.js +26 -0
- package/dist/cli/chat/TaskBar.d.ts +3 -2
- package/dist/cli/chat/TaskBar.js +4 -0
- package/dist/cli/chat/agentTurnRunner.d.ts +12 -0
- package/dist/cli/chat/agentTurnRunner.js +177 -0
- package/dist/cli/chat/busyIndicator.js +9 -5
- package/dist/cli/chat/chatMetrics.d.ts +7 -0
- package/dist/cli/chat/chatMetrics.js +15 -1
- package/dist/cli/chat/chatViewModel.d.ts +85 -0
- package/dist/cli/chat/chatViewModel.js +66 -0
- package/dist/cli/chat/fileMentionSuggestions.d.ts +0 -14
- package/dist/cli/chat/fileMentionSuggestions.js +4 -21
- package/dist/cli/chat/inputSuggestions.js +1 -0
- package/dist/cli/chat/liveTheme.d.ts +11 -0
- package/dist/cli/chat/liveTheme.js +26 -0
- package/dist/cli/chat/messageFinalize.d.ts +4 -0
- package/dist/cli/chat/messageFinalize.js +8 -0
- package/dist/cli/chat/messages.js +1 -1
- package/dist/cli/chat/pickerOpeners.d.ts +23 -0
- package/dist/cli/chat/pickerOpeners.js +36 -0
- package/dist/cli/chat/promptSessionState.d.ts +11 -0
- package/dist/cli/chat/promptSessionState.js +39 -0
- package/dist/cli/chat/renderMetrics.d.ts +8 -0
- package/dist/cli/chat/renderMetrics.js +14 -0
- package/dist/cli/chat/resizeGuard.d.ts +11 -0
- package/dist/cli/chat/resizeGuard.js +25 -0
- package/dist/cli/chat/screenDeps.d.ts +116 -0
- package/dist/cli/chat/screenDeps.js +1 -0
- package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
- package/dist/cli/chat/sessionLifecycle.js +6 -2
- package/dist/cli/chat/sessionRecorder.js +4 -1
- package/dist/cli/chat/settingsSelection.d.ts +33 -0
- package/dist/cli/chat/settingsSelection.js +46 -0
- package/dist/cli/chat/skillNotices.d.ts +18 -0
- package/dist/cli/chat/skillNotices.js +26 -0
- package/dist/cli/chat/startupInfo.js +1 -1
- package/dist/cli/chat/startupSequence.d.ts +2 -0
- package/dist/cli/chat/startupSequence.js +6 -0
- package/dist/cli/chat/submitPipeline.d.ts +8 -0
- package/dist/cli/chat/submitPipeline.js +141 -0
- package/dist/cli/chat/terminalControl.js +1 -1
- package/dist/cli/chat/toolSummaries.d.ts +29 -0
- package/dist/cli/chat/toolSummaries.js +268 -0
- package/dist/cli/chat/turnState.d.ts +8 -0
- package/dist/cli/chat/turnState.js +1 -0
- package/dist/cli/chat/userCommandFlow.d.ts +21 -0
- package/dist/cli/chat/userCommandFlow.js +66 -0
- package/dist/cli/chat/userCommandRunner.d.ts +14 -0
- package/dist/cli/chat/userCommandRunner.js +56 -0
- package/dist/cli/chat/wizard/providerHandlers.js +19 -2
- package/dist/cli/chat/wizardTrail.d.ts +22 -0
- package/dist/cli/chat/wizardTrail.js +55 -0
- package/dist/cli/commands/chat.d.ts +1 -13
- package/dist/cli/commands/chat.js +10 -795
- package/dist/cli/commands/commandHelp.js +11 -6
- package/dist/cli/commands/commandSuggest.d.ts +2 -0
- package/dist/cli/commands/commandSuggest.js +35 -0
- package/dist/cli/commands/commands.js +12 -3
- package/dist/cli/commands/formatters.d.ts +1 -23
- package/dist/cli/commands/formatters.js +3 -224
- package/dist/cli/commands/graphCommand.d.ts +2 -0
- package/dist/cli/commands/graphCommand.js +60 -0
- package/dist/cli/commands/initCommand.js +14 -0
- package/dist/cli/commands/modelCommand.js +11 -7
- package/dist/cli/commands/reasoningCommand.js +3 -3
- package/dist/cli/commands/runCommand.js +6 -2
- package/dist/cli/commands/streaming/agentAttempt.js +11 -1
- package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
- package/dist/cli/commands/streaming/attemptOutcome.js +8 -3
- package/dist/cli/commands/streaming/attemptSetup.d.ts +4 -0
- package/dist/cli/commands/streaming/attemptSetup.js +34 -5
- package/dist/cli/commands/streaming/goalCheckpoint.d.ts +1 -1
- package/dist/cli/commands/streaming/goalSupervisor.js +5 -3
- package/dist/cli/commands/streaming/prepareStep.js +1 -0
- package/dist/cli/commands/streaming/stepProjection.d.ts +59 -0
- package/dist/cli/commands/streaming/stepProjection.js +54 -0
- package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
- package/dist/cli/commands/streaming/streamLoop.js +34 -23
- package/dist/cli/commands/streaming/toolGroupRenderer.js +1 -1
- package/dist/cli/commands/streaming/toolPartHandlers.js +8 -2
- package/dist/cli/commands/streaming.d.ts +3 -1
- package/dist/cli/commands/streaming.js +5 -0
- package/dist/cli/commands/wizardFlow.d.ts +2 -0
- package/dist/cli/commands/wizardFlow.js +3 -0
- package/dist/cli/index.js +8 -4
- package/dist/cli/terminalTitle.js +9 -3
- package/dist/config/contextFiles.d.ts +2 -5
- package/dist/config/contextFiles.js +1 -1
- package/dist/config/inputHistory.js +2 -2
- package/dist/config/providerAuth.js +2 -2
- package/dist/config/providerModelFacts.js +5 -0
- package/dist/config/providerPresets.js +1 -1
- package/dist/config/settings.d.ts +7 -0
- package/dist/config/settings.js +9 -2
- package/dist/config/updateCheck.js +2 -2
- package/dist/core/agent/compaction.d.ts +1 -0
- package/dist/core/agent/compaction.js +3 -0
- package/dist/core/agent/completionController.d.ts +1 -1
- package/dist/core/agent/contextBudget.d.ts +1 -1
- package/dist/core/agent/goalPolicy.js +8 -2
- package/dist/core/agent/overflow.js +5 -0
- package/dist/core/agent/toolCapabilities.js +14 -0
- package/dist/core/agent/userCommands.d.ts +53 -0
- package/dist/core/agent/userCommands.js +116 -0
- package/dist/core/agent/workState.d.ts +3 -1
- package/dist/core/agent/workState.js +57 -26
- package/dist/core/contextFileTypes.d.ts +12 -0
- package/dist/core/contextFileTypes.js +1 -0
- package/dist/core/graph/analyze.d.ts +61 -0
- package/dist/core/graph/analyze.js +274 -0
- package/dist/core/graph/buildGraph.d.ts +44 -0
- package/dist/core/graph/buildGraph.js +290 -0
- package/dist/core/graph/digest.d.ts +2 -0
- package/dist/core/graph/digest.js +40 -0
- package/dist/core/graph/extract.d.ts +58 -0
- package/dist/core/graph/extract.js +394 -0
- package/dist/core/graph/model.d.ts +63 -0
- package/dist/core/graph/model.js +96 -0
- package/dist/core/graph/query.d.ts +69 -0
- package/dist/core/graph/query.js +391 -0
- package/dist/core/graph/store.d.ts +64 -0
- package/dist/core/graph/store.js +171 -0
- package/dist/core/limits.d.ts +2 -0
- package/dist/core/limits.js +2 -0
- package/dist/core/log/llmLog.js +2 -2
- package/dist/{config → core/persistence}/privateStorage.js +1 -1
- package/dist/core/process/runBoundedProcess.d.ts +7 -4
- package/dist/core/process/runBoundedProcess.js +22 -11
- package/dist/core/safety/redaction.d.ts +2 -0
- package/dist/core/safety/redaction.js +26 -5
- package/dist/core/safety/secretPaths.js +12 -3
- package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
- package/dist/core/safety/untrustedEnvelopes.js +17 -2
- package/dist/core/safety/urlGuard.js +2 -0
- package/dist/core/session/sessionStore.d.ts +8 -1
- package/dist/core/session/sessionStore.js +15 -4
- package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
- package/dist/core/shellOutput/types.d.ts +1 -1
- package/dist/core/subagent/executionProfiles.js +4 -4
- package/dist/core/tasks/taskStorage.js +11 -1
- package/dist/{llm → core}/toolResultTypes.d.ts +1 -1
- package/dist/core/validation/outputParser.d.ts +1 -1
- package/dist/core/validation/outputParser.js +16 -8
- package/dist/llm/hazeTools.d.ts +2 -12426
- package/dist/llm/hazeTools.js +4 -0
- package/dist/llm/lsp/pool.js +1 -1
- package/dist/llm/lsp/workspaceEdit.d.ts +1 -1
- package/dist/llm/lspTools.d.ts +3 -12622
- package/dist/llm/requestContext.d.ts +6 -0
- package/dist/llm/requestContext.js +28 -7
- package/dist/llm/subagentRunner.d.ts +2 -308
- package/dist/llm/systemPrompt.js +17 -7
- package/dist/llm/toolGroups.d.ts +534 -0
- package/dist/llm/toolGroups.js +57 -0
- package/dist/llm/tools/editMatch.d.ts +1 -1
- package/dist/llm/tools/failures.d.ts +1 -1
- package/dist/llm/tools/fetchTool.d.ts +2 -1221
- package/dist/llm/tools/fileToolShared.d.ts +1 -1
- package/dist/llm/tools/fileToolShared.js +1 -1
- package/dist/llm/tools/fileTools.d.ts +2 -7768
- package/dist/llm/tools/fileTools.js +1 -1
- package/dist/llm/tools/gitTools.d.ts +12 -0
- package/dist/llm/tools/gitTools.js +527 -0
- package/dist/llm/tools/graphAdvisory.d.ts +22 -0
- package/dist/llm/tools/graphAdvisory.js +68 -0
- package/dist/llm/tools/graphTools.d.ts +13 -0
- package/dist/llm/tools/graphTools.js +195 -0
- package/dist/llm/tools/processTool.d.ts +2 -1081
- package/dist/llm/tools/readRecovery.d.ts +1 -1
- package/dist/llm/tools/replaceInFiles.d.ts +1 -1
- package/dist/llm/tools/replaceInFiles.js +1 -1
- package/dist/llm/tools/shellTool.d.ts +2 -1513
- package/dist/llm/tools/storedOutputTool.d.ts +2 -355
- package/dist/llm/tools/taskTool.d.ts +2 -489
- package/dist/llm/tools/taskTool.js +4 -1
- package/dist/llm/tools/toolContext.js +29 -11
- package/dist/llm/tools/toolContextState.d.ts +4 -1
- package/dist/llm/tools/toolContextState.js +2 -1
- package/dist/llm/tools/workspaceFile.d.ts +2 -2
- package/dist/llm/tools/workspaceFile.js +10 -5
- package/dist/skills/SkillRegistry.js +1 -1
- package/dist/skills/builder/SkillBuilder.js +1 -1
- package/dist/skills/plugins/installer.js +1 -1
- package/dist/skills/plugins/runtime.js +1 -1
- package/dist/skills/skillTools.js +4 -1
- package/dist/ui/components/MarkdownText.d.ts +14 -0
- package/dist/ui/components/MarkdownText.js +77 -12
- package/dist/ui/components/NativeIndicators.js +5 -1
- package/dist/ui/components/StreamingMarkdownText.d.ts +3 -1
- package/dist/ui/components/StreamingMarkdownText.js +39 -11
- package/dist/ui/components/TextInput.d.ts +1 -2
- package/dist/ui/components/TextInput.js +79 -9
- package/dist/ui/components/WizardChoices.d.ts +1 -2
- package/dist/ui/components/useInputSuggestions.d.ts +1 -1
- package/dist/ui/components/useInputSuggestions.js +1 -1
- package/dist/ui/mentionDetection.d.ts +20 -0
- package/dist/ui/mentionDetection.js +24 -0
- package/dist/ui/terminalColors.d.ts +4 -4
- package/dist/ui/terminalColors.js +23 -6
- package/dist/ui/terminalSanitize.js +8 -3
- package/dist/ui/textGeometry.d.ts +2 -0
- package/dist/ui/textGeometry.js +6 -0
- package/dist/ui/themes/registry.js +33 -33
- package/dist/utils/openPath.js +7 -0
- package/package.json +22 -19
- /package/dist/{llm/tools → core/ignore}/gitIgnore.d.ts +0 -0
- /package/dist/{llm/tools → core/ignore}/gitIgnore.js +0 -0
- /package/dist/{config → core}/paths.d.ts +0 -0
- /package/dist/{config → core}/paths.js +0 -0
- /package/dist/{config → core/persistence}/privateStorage.d.ts +0 -0
- /package/dist/{llm → core}/toolResultTypes.js +0 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type CodeGraph, type GraphIndex } from './model.js';
|
|
2
|
+
/**
|
|
3
|
+
* Deterministic label propagation. Iteration order is node-id sorted and the
|
|
4
|
+
* min-label rule breaks ties, so the same graph always yields the same
|
|
5
|
+
* partition. Mutates `graph.nodes[].community` in place.
|
|
6
|
+
*/
|
|
7
|
+
export declare function detectCommunities(graph: CodeGraph): void;
|
|
8
|
+
export interface CommunitySummary {
|
|
9
|
+
community: number;
|
|
10
|
+
size: number;
|
|
11
|
+
/** Highest-degree members, files first: a one-line identity for the cluster. */
|
|
12
|
+
members: Array<{
|
|
13
|
+
id: string;
|
|
14
|
+
label: string;
|
|
15
|
+
kind: string;
|
|
16
|
+
degree: number;
|
|
17
|
+
}>;
|
|
18
|
+
/** Most common top-level directories among member files. */
|
|
19
|
+
directories: string[];
|
|
20
|
+
}
|
|
21
|
+
export declare function communitySummaries(index: GraphIndex, limit?: number): CommunitySummary[];
|
|
22
|
+
/** Test-path heuristic shared by god-node ranking and query demotion. */
|
|
23
|
+
export declare function isTestPath(file: string): boolean;
|
|
24
|
+
export interface GodNode {
|
|
25
|
+
id: string;
|
|
26
|
+
label: string;
|
|
27
|
+
kind: string;
|
|
28
|
+
file: string;
|
|
29
|
+
degree: number;
|
|
30
|
+
}
|
|
31
|
+
/** Top-degree symbol nodes (files excluded; test helpers demoted — they mirror, not shape, the architecture). */
|
|
32
|
+
export declare function godNodes(index: GraphIndex, limit?: number): GodNode[];
|
|
33
|
+
/** Tarjan strongly-connected components over file-level `imports` edges. */
|
|
34
|
+
export declare function importCycles(index: GraphIndex, limit?: number): string[][];
|
|
35
|
+
export interface AffectedEntry {
|
|
36
|
+
id: string;
|
|
37
|
+
label: string;
|
|
38
|
+
kind: string;
|
|
39
|
+
file: string;
|
|
40
|
+
depth: number;
|
|
41
|
+
viaRelation: string;
|
|
42
|
+
confidence: string;
|
|
43
|
+
viaFile: string;
|
|
44
|
+
viaLine?: number;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Reverse blast radius from a symbol: who calls/inherits/imports it, transitively.
|
|
48
|
+
* File-level `imports` edges are followed one hop (the file importing the
|
|
49
|
+
* changed symbol's file) so consumers surface even when call sites are dynamic.
|
|
50
|
+
*/
|
|
51
|
+
export declare function affectedBySymbol(index: GraphIndex, symbolId: string, maxDepth?: number, limit?: number): AffectedEntry[];
|
|
52
|
+
export interface GraphReportInput {
|
|
53
|
+
graph: CodeGraph;
|
|
54
|
+
files: number;
|
|
55
|
+
parsedFiles: number;
|
|
56
|
+
cachedFiles: number;
|
|
57
|
+
durationMs: number;
|
|
58
|
+
stale: boolean;
|
|
59
|
+
}
|
|
60
|
+
/** Human-readable orientation report for /graph: structure, hubs, risk areas. */
|
|
61
|
+
export declare function renderGraphReport(index: GraphIndex, input: GraphReportInput): string;
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph analysis: god nodes (degree hubs), import cycles (Tarjan SCC over
|
|
3
|
+
* file-level import edges), communities (deterministic label propagation),
|
|
4
|
+
* reverse blast radius, and the /graph report renderer.
|
|
5
|
+
*
|
|
6
|
+
* Everything here is plain TS over the in-memory index — no dependencies, no
|
|
7
|
+
* LLM, deterministic output (sorted iteration everywhere).
|
|
8
|
+
*/
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { buildGraphIndex, nodeDegree } from './model.js';
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Communities: label propagation over the undirected projection
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
const COMMUNITY_ITERATIONS = 8;
|
|
15
|
+
/**
|
|
16
|
+
* Deterministic label propagation. Iteration order is node-id sorted and the
|
|
17
|
+
* min-label rule breaks ties, so the same graph always yields the same
|
|
18
|
+
* partition. Mutates `graph.nodes[].community` in place.
|
|
19
|
+
*/
|
|
20
|
+
export function detectCommunities(graph) {
|
|
21
|
+
const index = buildGraphIndex(graph);
|
|
22
|
+
const labels = new Map();
|
|
23
|
+
const ids = [...index.nodes.keys()].sort();
|
|
24
|
+
for (const id of ids)
|
|
25
|
+
labels.set(id, id);
|
|
26
|
+
for (let iteration = 0; iteration < COMMUNITY_ITERATIONS; iteration++) {
|
|
27
|
+
let changed = false;
|
|
28
|
+
for (const id of ids) {
|
|
29
|
+
const counts = new Map();
|
|
30
|
+
const bump = (label) => counts.set(label, (counts.get(label) ?? 0) + 1);
|
|
31
|
+
bump(labels.get(id));
|
|
32
|
+
for (const edge of index.out.get(id) ?? [])
|
|
33
|
+
bump(labels.get(edge.target) ?? edge.target);
|
|
34
|
+
for (const edge of index.in.get(id) ?? [])
|
|
35
|
+
bump(labels.get(edge.source) ?? edge.source);
|
|
36
|
+
let bestLabel = labels.get(id);
|
|
37
|
+
let bestCount = -1;
|
|
38
|
+
for (const [label, count] of [...counts].sort(([a], [b]) => a.localeCompare(b))) {
|
|
39
|
+
if (count > bestCount) {
|
|
40
|
+
bestLabel = label;
|
|
41
|
+
bestCount = count;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (bestLabel !== labels.get(id)) {
|
|
45
|
+
labels.set(id, bestLabel);
|
|
46
|
+
changed = true;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (!changed)
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
// Renumber communities by sorted representative for stable, readable ids.
|
|
53
|
+
const communityIds = new Map();
|
|
54
|
+
for (const id of ids) {
|
|
55
|
+
const label = labels.get(id);
|
|
56
|
+
if (!communityIds.has(label))
|
|
57
|
+
communityIds.set(label, communityIds.size);
|
|
58
|
+
}
|
|
59
|
+
for (const node of graph.nodes) {
|
|
60
|
+
const label = labels.get(node.id);
|
|
61
|
+
if (label == null)
|
|
62
|
+
continue;
|
|
63
|
+
const community = communityIds.get(label);
|
|
64
|
+
if (community != null)
|
|
65
|
+
node.community = community;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export function communitySummaries(index, limit = 12) {
|
|
69
|
+
const byCommunity = new Map();
|
|
70
|
+
for (const node of index.nodes.values()) {
|
|
71
|
+
if (node.community == null)
|
|
72
|
+
continue;
|
|
73
|
+
const bucket = byCommunity.get(node.community) ?? [];
|
|
74
|
+
bucket.push(node.id);
|
|
75
|
+
byCommunity.set(node.community, bucket);
|
|
76
|
+
}
|
|
77
|
+
const summaries = [];
|
|
78
|
+
for (const [community, ids] of byCommunity) {
|
|
79
|
+
const ranked = ids
|
|
80
|
+
.map(id => ({ id, node: index.nodes.get(id), degree: nodeDegree(index, id) }))
|
|
81
|
+
.filter(entry => entry.node != null)
|
|
82
|
+
.sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id));
|
|
83
|
+
const members = [
|
|
84
|
+
...ranked.filter(entry => entry.node.kind === 'file').slice(0, 3),
|
|
85
|
+
...ranked.filter(entry => entry.node.kind !== 'file').slice(0, 4),
|
|
86
|
+
].map(entry => ({ id: entry.id, label: entry.node.label, kind: entry.node.kind, degree: entry.degree }));
|
|
87
|
+
const dirCounts = new Map();
|
|
88
|
+
for (const entry of ranked) {
|
|
89
|
+
const segments = path.posix.dirname(entry.node.file).split('/');
|
|
90
|
+
// 'src' alone says nothing in a monoglot repo; keep two segments there.
|
|
91
|
+
const dir = segments[0] === 'src' || segments[0] === 'tests' ? segments.slice(0, 2).join('/') : segments[0] ?? '';
|
|
92
|
+
if (dir && dir !== '.')
|
|
93
|
+
dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + 1);
|
|
94
|
+
}
|
|
95
|
+
const directories = [...dirCounts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 2).map(([dir]) => dir);
|
|
96
|
+
summaries.push({ community, size: ids.length, members, directories });
|
|
97
|
+
}
|
|
98
|
+
return summaries.sort((a, b) => b.size - a.size || a.community - b.community).slice(0, limit);
|
|
99
|
+
}
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// God nodes and import cycles
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
/** Test-path heuristic shared by god-node ranking and query demotion. */
|
|
104
|
+
export function isTestPath(file) {
|
|
105
|
+
const lowered = file.toLowerCase();
|
|
106
|
+
return lowered.includes('.test.') || lowered.includes('.spec.') || lowered.includes('__tests__/') || /(^|\/)(tests?|fixtures?)\//.test(lowered);
|
|
107
|
+
}
|
|
108
|
+
/** Top-degree symbol nodes (files excluded; test helpers demoted — they mirror, not shape, the architecture). */
|
|
109
|
+
export function godNodes(index, limit = 10) {
|
|
110
|
+
const ranked = [];
|
|
111
|
+
for (const node of index.nodes.values()) {
|
|
112
|
+
if (node.kind === 'file')
|
|
113
|
+
continue;
|
|
114
|
+
if (isTestPath(node.file))
|
|
115
|
+
continue;
|
|
116
|
+
ranked.push({ id: node.id, label: node.label, kind: node.kind, file: node.file, degree: nodeDegree(index, node.id) });
|
|
117
|
+
}
|
|
118
|
+
return ranked.sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id)).slice(0, limit);
|
|
119
|
+
}
|
|
120
|
+
/** Tarjan strongly-connected components over file-level `imports` edges. */
|
|
121
|
+
export function importCycles(index, limit = 5) {
|
|
122
|
+
const fileIds = [...index.nodes.values()].filter(node => node.kind === 'file').map(node => node.id).sort();
|
|
123
|
+
const adjacency = new Map();
|
|
124
|
+
for (const id of fileIds) {
|
|
125
|
+
const targets = (index.out.get(id) ?? [])
|
|
126
|
+
.filter(edge => edge.relation === 'imports')
|
|
127
|
+
.map(edge => edge.target);
|
|
128
|
+
adjacency.set(id, targets);
|
|
129
|
+
}
|
|
130
|
+
let counter = 0;
|
|
131
|
+
const stack = [];
|
|
132
|
+
const onStack = new Set();
|
|
133
|
+
const indices = new Map();
|
|
134
|
+
const lowlinks = new Map();
|
|
135
|
+
const cycles = [];
|
|
136
|
+
const strongConnect = (start) => {
|
|
137
|
+
const work = [{ node: start, next: 0 }];
|
|
138
|
+
while (work.length > 0) {
|
|
139
|
+
const frame = work[work.length - 1];
|
|
140
|
+
if (frame.next === 0) {
|
|
141
|
+
indices.set(frame.node, counter);
|
|
142
|
+
lowlinks.set(frame.node, counter);
|
|
143
|
+
counter += 1;
|
|
144
|
+
stack.push(frame.node);
|
|
145
|
+
onStack.add(frame.node);
|
|
146
|
+
}
|
|
147
|
+
const neighbors = adjacency.get(frame.node) ?? [];
|
|
148
|
+
let advanced = false;
|
|
149
|
+
while (frame.next < neighbors.length) {
|
|
150
|
+
const neighbor = neighbors[frame.next];
|
|
151
|
+
frame.next += 1;
|
|
152
|
+
if (!indices.has(neighbor)) {
|
|
153
|
+
work.push({ node: neighbor, next: 0 });
|
|
154
|
+
advanced = true;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
if (onStack.has(neighbor)) {
|
|
158
|
+
lowlinks.set(frame.node, Math.min(lowlinks.get(frame.node), indices.get(neighbor)));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (advanced)
|
|
162
|
+
continue;
|
|
163
|
+
if (lowlinks.get(frame.node) === indices.get(frame.node)) {
|
|
164
|
+
const component = [];
|
|
165
|
+
while (true) {
|
|
166
|
+
const member = stack.pop();
|
|
167
|
+
onStack.delete(member);
|
|
168
|
+
component.push(member);
|
|
169
|
+
if (member === frame.node)
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
if (component.length > 1)
|
|
173
|
+
cycles.push(component.sort());
|
|
174
|
+
}
|
|
175
|
+
work.pop();
|
|
176
|
+
const parent = work[work.length - 1];
|
|
177
|
+
if (parent)
|
|
178
|
+
lowlinks.set(parent.node, Math.min(lowlinks.get(parent.node), lowlinks.get(frame.node)));
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
for (const id of fileIds) {
|
|
182
|
+
if (!indices.has(id))
|
|
183
|
+
strongConnect(id);
|
|
184
|
+
}
|
|
185
|
+
return cycles.sort((a, b) => b.length - a.length || a[0].localeCompare(b[0])).slice(0, limit);
|
|
186
|
+
}
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// Blast radius
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
const AFFECTED_RELATIONS = new Set(['calls', 'inherits', 'references']);
|
|
191
|
+
/**
|
|
192
|
+
* Reverse blast radius from a symbol: who calls/inherits/imports it, transitively.
|
|
193
|
+
* File-level `imports` edges are followed one hop (the file importing the
|
|
194
|
+
* changed symbol's file) so consumers surface even when call sites are dynamic.
|
|
195
|
+
*/
|
|
196
|
+
export function affectedBySymbol(index, symbolId, maxDepth = 3, limit = 40) {
|
|
197
|
+
const results = new Map();
|
|
198
|
+
const visited = new Set([symbolId]);
|
|
199
|
+
// `imports` edges are file→file, so the one-hop importer surfacing is
|
|
200
|
+
// reachable only through the file that defines the queried symbol: seed
|
|
201
|
+
// that file alongside the symbol (never as a result itself).
|
|
202
|
+
const definingFiles = (index.in.get(symbolId) ?? [])
|
|
203
|
+
.filter(edge => edge.relation === 'defines')
|
|
204
|
+
.map(edge => edge.source);
|
|
205
|
+
for (const id of definingFiles)
|
|
206
|
+
visited.add(id);
|
|
207
|
+
let frontier = [{ id: symbolId, depth: 0 }, ...definingFiles.map(id => ({ id, depth: 0 }))];
|
|
208
|
+
while (frontier.length > 0 && results.size < limit) {
|
|
209
|
+
const next = [];
|
|
210
|
+
for (const current of frontier) {
|
|
211
|
+
for (const edge of index.in.get(current.id) ?? []) {
|
|
212
|
+
if (visited.has(edge.source))
|
|
213
|
+
continue;
|
|
214
|
+
if (!AFFECTED_RELATIONS.has(edge.relation) && !(edge.relation === 'imports' && current.depth === 0))
|
|
215
|
+
continue;
|
|
216
|
+
visited.add(edge.source);
|
|
217
|
+
const node = index.nodes.get(edge.source);
|
|
218
|
+
if (!node)
|
|
219
|
+
continue;
|
|
220
|
+
// Symbols are entries; files surface only as the documented one-hop
|
|
221
|
+
// importers of the defining file (the defining file itself is a
|
|
222
|
+
// pre-visited seed, never a result).
|
|
223
|
+
if (node.kind !== 'file' || edge.relation === 'imports') {
|
|
224
|
+
results.set(edge.source, {
|
|
225
|
+
id: edge.source, label: node.label, kind: node.kind, file: node.file,
|
|
226
|
+
depth: current.depth + 1, viaRelation: edge.relation, confidence: edge.confidence,
|
|
227
|
+
viaFile: edge.file ?? node.file, ...(edge.line ? { viaLine: edge.line } : {}),
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
next.push({ id: edge.source, depth: current.depth + 1 });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
frontier = next;
|
|
234
|
+
if (frontier.some(entry => entry.depth >= maxDepth))
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
return [...results.values()].sort((a, b) => a.depth - b.depth || b.viaRelation.localeCompare(a.viaRelation) || a.id.localeCompare(b.id)).slice(0, limit);
|
|
238
|
+
}
|
|
239
|
+
/** Human-readable orientation report for /graph: structure, hubs, risk areas. */
|
|
240
|
+
export function renderGraphReport(index, input) {
|
|
241
|
+
const lines = [];
|
|
242
|
+
const cacheHint = input.cachedFiles > 0 ? `, ${input.cachedFiles} cached / ${input.parsedFiles} parsed` : '';
|
|
243
|
+
lines.push(`Code graph: ${input.graph.nodes.length} nodes · ${input.graph.edges.length} edges · ${input.files} source files (${(input.durationMs / 1000).toFixed(1)}s${cacheHint})`);
|
|
244
|
+
if (input.stale)
|
|
245
|
+
lines.push('Note: some files changed since this graph was built; run /graph to refresh.');
|
|
246
|
+
const communities = communitySummaries(index, 8);
|
|
247
|
+
if (communities.length > 0) {
|
|
248
|
+
lines.push('');
|
|
249
|
+
lines.push('Subsystems (graph communities):');
|
|
250
|
+
for (const community of communities) {
|
|
251
|
+
const dirs = community.directories.length > 0 ? ` [${community.directories.join(', ')}]` : '';
|
|
252
|
+
lines.push(` ${community.community}: ${community.size} nodes${dirs}`);
|
|
253
|
+
const memberLabels = community.members.slice(0, 4).map(member => member.kind === 'file' ? member.label : `${member.label} (${member.kind})`);
|
|
254
|
+
lines.push(` ${memberLabels.join(' · ')}`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const gods = godNodes(index, 8);
|
|
258
|
+
if (gods.length > 0) {
|
|
259
|
+
lines.push('');
|
|
260
|
+
lines.push('Hub symbols (god nodes — change these carefully):');
|
|
261
|
+
for (const god of gods) {
|
|
262
|
+
lines.push(` ${god.label} (${god.kind}, degree ${god.degree}) — ${god.file}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
const cycles = importCycles(index, 3);
|
|
266
|
+
if (cycles.length > 0) {
|
|
267
|
+
lines.push('');
|
|
268
|
+
lines.push(`Import cycles: ${cycles.length} shown`);
|
|
269
|
+
for (const cycle of cycles) {
|
|
270
|
+
lines.push(` ${cycle.join(' -> ')}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return lines.join('\n');
|
|
274
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type FileExtraction } from './extract.js';
|
|
2
|
+
import { type CodeGraph, type GraphEdge, type GraphNode } from './model.js';
|
|
3
|
+
import { type GraphStore } from './store.js';
|
|
4
|
+
export interface GraphBuildOptions {
|
|
5
|
+
/** Permit intentional shrink (mass deletion); otherwise a near-empty rebuild of a healthy graph is refused. */
|
|
6
|
+
force?: boolean;
|
|
7
|
+
/** Progress callback per processed file (used by /graph for user feedback). */
|
|
8
|
+
onProgress?: (processed: number, total: number) => void;
|
|
9
|
+
}
|
|
10
|
+
export interface GraphBuildResult {
|
|
11
|
+
ok: boolean;
|
|
12
|
+
store: GraphStore;
|
|
13
|
+
graph: CodeGraph;
|
|
14
|
+
files: number;
|
|
15
|
+
skippedLarge: number;
|
|
16
|
+
parsedFiles: number;
|
|
17
|
+
cachedFiles: number;
|
|
18
|
+
durationMs: number;
|
|
19
|
+
incremental: boolean;
|
|
20
|
+
capped: boolean;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* One-shot, non-blocking graph ensure for startup: kick off a single
|
|
24
|
+
* incremental build in the background on every startup — creating the graph
|
|
25
|
+
* when none exists yet, refreshing it otherwise (content-hash cached, so an
|
|
26
|
+
* unchanged workspace only re-runs cheap cross-file resolution) — and return
|
|
27
|
+
* its promise; while one is running, return the same promise. Never rejects —
|
|
28
|
+
* on failure the graph tools still report `graph_not_built` with a rebuild
|
|
29
|
+
* hint. Not a daemon: one build per process, no watching.
|
|
30
|
+
*/
|
|
31
|
+
export declare function ensureGraphInBackground(deps?: {
|
|
32
|
+
build?: () => Promise<GraphBuildResult>;
|
|
33
|
+
onActivity?: (building: boolean) => void;
|
|
34
|
+
}): Promise<GraphBuildResult | undefined>;
|
|
35
|
+
export declare function buildWorkspaceGraph(options?: GraphBuildOptions): Promise<GraphBuildResult>;
|
|
36
|
+
/**
|
|
37
|
+
* Pure corpus resolution: per-file extractions → graph nodes and edges with
|
|
38
|
+
* cross-file bindings resolved (imports rewritten through NodeNext `.js`
|
|
39
|
+
* specifiers, calls/heritage bound to imported symbols as INFERRED edges).
|
|
40
|
+
*/
|
|
41
|
+
export declare function resolveGraph(extractions: Map<string, FileExtraction>): {
|
|
42
|
+
nodes: GraphNode[];
|
|
43
|
+
edges: GraphEdge[];
|
|
44
|
+
};
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph build orchestration: walk the workspace, extract (cache-first), and
|
|
3
|
+
* resolve cross-file relationships into the final edge set.
|
|
4
|
+
*
|
|
5
|
+
* Safety: the walk reuses the file tools' own confinement — in-process
|
|
6
|
+
* gitignore evaluation, `.git`/`node_modules` skipping (walkDir), cwd
|
|
7
|
+
* confinement, and the shared secret-path refusals — so the graph never reads
|
|
8
|
+
* a file the file tools would refuse. Parsing is deterministic tree-sitter
|
|
9
|
+
* only: no LLM, no network, no shell.
|
|
10
|
+
*
|
|
11
|
+
* Incremental behavior: extraction results are content-hash cached, so a
|
|
12
|
+
* rebuild only re-parses new/changed files; removed files drop out naturally.
|
|
13
|
+
* Cross-file resolution always re-runs — it is cheap and corpus-wide.
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs/promises';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { walkDir } from '../../utils/fs.js';
|
|
19
|
+
import { workspaceRoot } from '../../utils/path.js';
|
|
20
|
+
import { createIgnoreClassifier } from '../ignore/gitIgnore.js';
|
|
21
|
+
import { isProtectedSecretPath } from '../safety/secretPaths.js';
|
|
22
|
+
import { contentHash, extractFile, isGraphSupportedExtension, EXTRACTOR_VERSION, MAX_SOURCE_BYTES } from './extract.js';
|
|
23
|
+
import { detectCommunities } from './analyze.js';
|
|
24
|
+
import { GRAPH_SCHEMA_VERSION, symbolNodeId } from './model.js';
|
|
25
|
+
import { graphStoreFor, pruneExtractionCache, readCachedExtraction, writeCachedExtraction, writeGraph } from './store.js';
|
|
26
|
+
/** Upper bound on files considered per build; larger workspaces get a visible partial notice, not a silent hang. */
|
|
27
|
+
const GRAPH_MAX_FILES = 20_000;
|
|
28
|
+
const EXTRACTION_CACHE_MAX_ENTRIES = 40_000;
|
|
29
|
+
let backgroundBuildInFlight;
|
|
30
|
+
/**
|
|
31
|
+
* One-shot, non-blocking graph ensure for startup: kick off a single
|
|
32
|
+
* incremental build in the background on every startup — creating the graph
|
|
33
|
+
* when none exists yet, refreshing it otherwise (content-hash cached, so an
|
|
34
|
+
* unchanged workspace only re-runs cheap cross-file resolution) — and return
|
|
35
|
+
* its promise; while one is running, return the same promise. Never rejects —
|
|
36
|
+
* on failure the graph tools still report `graph_not_built` with a rebuild
|
|
37
|
+
* hint. Not a daemon: one build per process, no watching.
|
|
38
|
+
*/
|
|
39
|
+
export function ensureGraphInBackground(deps = {}) {
|
|
40
|
+
if (backgroundBuildInFlight)
|
|
41
|
+
return backgroundBuildInFlight;
|
|
42
|
+
const build = deps.build ?? (() => buildWorkspaceGraph());
|
|
43
|
+
backgroundBuildInFlight = (async () => {
|
|
44
|
+
deps.onActivity?.(true);
|
|
45
|
+
try {
|
|
46
|
+
return await build();
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
deps.onActivity?.(false);
|
|
50
|
+
}
|
|
51
|
+
})().catch(() => undefined).finally(() => {
|
|
52
|
+
backgroundBuildInFlight = undefined;
|
|
53
|
+
});
|
|
54
|
+
return backgroundBuildInFlight;
|
|
55
|
+
}
|
|
56
|
+
/** Candidate path resolutions for a relative import specifier (extensionless, ESM `.js`-style rewriting, index files). */
|
|
57
|
+
function resolveImportSpecifier(fromFile, specifier, fileSet) {
|
|
58
|
+
if (!specifier.startsWith('.'))
|
|
59
|
+
return undefined; // package imports carry no workspace edge
|
|
60
|
+
const base = path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), specifier));
|
|
61
|
+
if (fileSet.has(base))
|
|
62
|
+
return base;
|
|
63
|
+
const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts', '.mjs', '.cjs'];
|
|
64
|
+
// NodeNext ESM rewrites: `./foo.js` may name foo.ts; strip the emitted
|
|
65
|
+
// extension and try every source extension (including the extensionless file).
|
|
66
|
+
for (const emitted of ['.js', '.mjs', '.cjs', '.jsx']) {
|
|
67
|
+
if (base.endsWith(emitted)) {
|
|
68
|
+
const stem = base.slice(0, -emitted.length);
|
|
69
|
+
if (fileSet.has(stem))
|
|
70
|
+
return stem;
|
|
71
|
+
for (const extension of extensions) {
|
|
72
|
+
if (fileSet.has(`${stem}${extension}`))
|
|
73
|
+
return `${stem}${extension}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const extension of extensions) {
|
|
78
|
+
if (fileSet.has(`${base}${extension}`))
|
|
79
|
+
return `${base}${extension}`;
|
|
80
|
+
}
|
|
81
|
+
for (const index of ['/index.ts', '/index.tsx', '/index.js']) {
|
|
82
|
+
if (fileSet.has(`${base}${index}`))
|
|
83
|
+
return `${base}${index}`;
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
/** Attribute a source line to the nearest preceding symbol (call/heritage site), else the file node. */
|
|
88
|
+
function enclosingSymbolId(extraction, line) {
|
|
89
|
+
let best;
|
|
90
|
+
for (const symbol of extraction.symbols) {
|
|
91
|
+
if (symbol.line > line)
|
|
92
|
+
continue;
|
|
93
|
+
if (!best || symbol.line > best.line)
|
|
94
|
+
best = symbol;
|
|
95
|
+
}
|
|
96
|
+
return best?.id;
|
|
97
|
+
}
|
|
98
|
+
/** Nearest class whose definition precedes the line — best-effort owner for `this.method()` calls. */
|
|
99
|
+
function enclosingClassName(extraction, line) {
|
|
100
|
+
let best;
|
|
101
|
+
for (const symbol of extraction.symbols) {
|
|
102
|
+
if (symbol.kind !== 'class' || symbol.line > line)
|
|
103
|
+
continue;
|
|
104
|
+
if (!best || symbol.line > best.line)
|
|
105
|
+
best = symbol;
|
|
106
|
+
}
|
|
107
|
+
return best?.name;
|
|
108
|
+
}
|
|
109
|
+
export async function buildWorkspaceGraph(options = {}) {
|
|
110
|
+
const started = Date.now();
|
|
111
|
+
const root = workspaceRoot();
|
|
112
|
+
const store = graphStoreFor(root);
|
|
113
|
+
// --- Walk -----------------------------------------------------------------
|
|
114
|
+
const ignoreClassifier = createIgnoreClassifier(root);
|
|
115
|
+
const ignoreBatch = (entries) => ignoreClassifier.classify(entries);
|
|
116
|
+
const walked = await walkDir(root, { recursive: true, maxEntries: GRAPH_MAX_FILES * 3, ignoreBatch });
|
|
117
|
+
const homeDir = os.homedir();
|
|
118
|
+
const sourceFiles = walked
|
|
119
|
+
.filter(entry => entry.isFile && isGraphSupportedExtension(path.extname(entry.name).toLowerCase()))
|
|
120
|
+
.filter(entry => !isProtectedSecretPath(entry.absolutePath, homeDir))
|
|
121
|
+
.map(entry => entry.path.replace(/\\/g, '/'))
|
|
122
|
+
.sort();
|
|
123
|
+
const capped = sourceFiles.length > GRAPH_MAX_FILES;
|
|
124
|
+
const files = capped ? sourceFiles.slice(0, GRAPH_MAX_FILES) : sourceFiles;
|
|
125
|
+
// --- Extract (cache-first) -------------------------------------------------
|
|
126
|
+
const extractions = new Map();
|
|
127
|
+
let parsedFiles = 0;
|
|
128
|
+
let cachedFiles = 0;
|
|
129
|
+
let skippedLarge = 0;
|
|
130
|
+
for (const [index, file] of files.entries()) {
|
|
131
|
+
options.onProgress?.(index + 1, files.length);
|
|
132
|
+
let content;
|
|
133
|
+
try {
|
|
134
|
+
const absolute = path.join(root, file);
|
|
135
|
+
const stat = await fs.stat(absolute);
|
|
136
|
+
if (stat.size > MAX_SOURCE_BYTES) {
|
|
137
|
+
skippedLarge += 1;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
content = await fs.readFile(absolute, 'utf8');
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
continue; // Unreadable file: skip honestly; staleness reports it, builds never fail on one file.
|
|
144
|
+
}
|
|
145
|
+
const hash = contentHash(content);
|
|
146
|
+
const cached = await readCachedExtraction(store, hash);
|
|
147
|
+
let extraction;
|
|
148
|
+
if (cached && cached.file === file) {
|
|
149
|
+
extraction = cached;
|
|
150
|
+
cachedFiles += 1;
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
try {
|
|
154
|
+
extraction = await extractFile(file, content);
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
continue; // e.g. grammar unavailable; keep building the rest.
|
|
158
|
+
}
|
|
159
|
+
parsedFiles += 1;
|
|
160
|
+
await writeCachedExtraction(store, hash, extraction);
|
|
161
|
+
}
|
|
162
|
+
extractions.set(file, extraction);
|
|
163
|
+
}
|
|
164
|
+
// --- Resolve + persist --------------------------------------------------------
|
|
165
|
+
const { nodes, edges } = resolveGraph(extractions);
|
|
166
|
+
const graph = {
|
|
167
|
+
schemaVersion: GRAPH_SCHEMA_VERSION,
|
|
168
|
+
extractorVersion: EXTRACTOR_VERSION,
|
|
169
|
+
builtAt: new Date().toISOString(),
|
|
170
|
+
fileCount: files.length,
|
|
171
|
+
nodes,
|
|
172
|
+
edges,
|
|
173
|
+
};
|
|
174
|
+
detectCommunities(graph);
|
|
175
|
+
const signatures = {};
|
|
176
|
+
for (const file of files) {
|
|
177
|
+
try {
|
|
178
|
+
const stat = await fs.stat(path.join(root, file));
|
|
179
|
+
signatures[file] = { size: stat.size, mtimeMs: stat.mtimeMs };
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
// Deleted between walk and stat: omit; the next build reports it as removed.
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
await writeGraph(store, graph, { extractorVersion: EXTRACTOR_VERSION, workspaceRoot: root, files: signatures }, { force: options.force });
|
|
186
|
+
await pruneExtractionCache(store, EXTRACTION_CACHE_MAX_ENTRIES);
|
|
187
|
+
return { ok: true, store, graph, files: files.length, skippedLarge, parsedFiles, cachedFiles, durationMs: Date.now() - started, incremental: cachedFiles > 0, capped };
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Pure corpus resolution: per-file extractions → graph nodes and edges with
|
|
191
|
+
* cross-file bindings resolved (imports rewritten through NodeNext `.js`
|
|
192
|
+
* specifiers, calls/heritage bound to imported symbols as INFERRED edges).
|
|
193
|
+
*/
|
|
194
|
+
export function resolveGraph(extractions) {
|
|
195
|
+
const nodes = [];
|
|
196
|
+
const edges = [];
|
|
197
|
+
const fileSet = new Set(extractions.keys());
|
|
198
|
+
for (const [file, extraction] of extractions) {
|
|
199
|
+
nodes.push({ id: file, label: path.posix.basename(file), kind: 'file', file, line: 1 });
|
|
200
|
+
const taken = new Set([file]);
|
|
201
|
+
for (const symbol of extraction.symbols) {
|
|
202
|
+
nodes.push({ id: symbolNodeId(file, symbol.name, symbol.line, taken), label: symbol.name, kind: symbol.kind, file, line: symbol.line });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/** Resolve an exported name in a file to its symbol id (one re-export hop). */
|
|
206
|
+
const resolveExportedSymbol = (targetFile, exportedName, depth = 0) => {
|
|
207
|
+
const target = extractions.get(targetFile);
|
|
208
|
+
if (!target || depth > 1)
|
|
209
|
+
return undefined;
|
|
210
|
+
const direct = target.symbols.find(symbol => symbol.name === exportedName);
|
|
211
|
+
if (direct)
|
|
212
|
+
return direct.id;
|
|
213
|
+
for (const reExport of target.imports) {
|
|
214
|
+
if (reExport.kind !== 'export-from')
|
|
215
|
+
continue;
|
|
216
|
+
const resolved = resolveImportSpecifier(targetFile, reExport.specifier, fileSet);
|
|
217
|
+
if (!resolved)
|
|
218
|
+
continue;
|
|
219
|
+
const binding = reExport.bindings.find(candidate => candidate.importedName === exportedName);
|
|
220
|
+
if (binding)
|
|
221
|
+
return resolveExportedSymbol(resolved, binding.importedName, depth + 1);
|
|
222
|
+
}
|
|
223
|
+
return undefined;
|
|
224
|
+
};
|
|
225
|
+
for (const [file, extraction] of extractions) {
|
|
226
|
+
const firstSymbolByName = new Map();
|
|
227
|
+
for (const symbol of extraction.symbols) {
|
|
228
|
+
if (!firstSymbolByName.has(symbol.name))
|
|
229
|
+
firstSymbolByName.set(symbol.name, { id: symbol.id, kind: symbol.kind });
|
|
230
|
+
}
|
|
231
|
+
// local binding name (imports included) -> symbol id in another file
|
|
232
|
+
const importedBindingToSymbol = new Map();
|
|
233
|
+
for (const entry of extraction.imports) {
|
|
234
|
+
if (!entry.specifier.startsWith('.'))
|
|
235
|
+
continue;
|
|
236
|
+
const targetFile = resolveImportSpecifier(file, entry.specifier, fileSet);
|
|
237
|
+
if (!targetFile)
|
|
238
|
+
continue;
|
|
239
|
+
edges.push({ source: file, target: targetFile, relation: 'imports', confidence: 'EXTRACTED', file, line: entry.line });
|
|
240
|
+
for (const binding of entry.bindings) {
|
|
241
|
+
const targetId = resolveExportedSymbol(targetFile, binding.importedName);
|
|
242
|
+
if (targetId)
|
|
243
|
+
importedBindingToSymbol.set(binding.localName, targetId);
|
|
244
|
+
}
|
|
245
|
+
if (entry.defaultImport) {
|
|
246
|
+
// Default imports bind to the target's single callable export when
|
|
247
|
+
// unambiguous; several candidates stay unresolved rather than guessed.
|
|
248
|
+
const target = extractions.get(targetFile);
|
|
249
|
+
const callables = target.symbols.filter(symbol => target.exports.includes(symbol.name) && (symbol.kind === 'function' || symbol.kind === 'class'));
|
|
250
|
+
const unique = callables.length === 1 ? callables[0] : undefined;
|
|
251
|
+
if (unique)
|
|
252
|
+
importedBindingToSymbol.set(entry.defaultImport, unique.id);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const call of extraction.calls) {
|
|
256
|
+
const sourceId = enclosingSymbolId(extraction, call.line);
|
|
257
|
+
if (call.thisCall) {
|
|
258
|
+
const className = enclosingClassName(extraction, call.line);
|
|
259
|
+
const targetId = className
|
|
260
|
+
? extraction.symbols.find(symbol => symbol.name === call.name && symbol.owner === className)?.id
|
|
261
|
+
: undefined;
|
|
262
|
+
if (targetId)
|
|
263
|
+
edges.push({ source: sourceId ?? file, target: targetId, relation: 'calls', confidence: 'EXTRACTED', file, line: call.line });
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
const importedId = importedBindingToSymbol.get(call.name);
|
|
267
|
+
if (importedId) {
|
|
268
|
+
edges.push({ source: sourceId ?? file, target: importedId, relation: 'calls', confidence: 'INFERRED', file, line: call.line });
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const local = firstSymbolByName.get(call.name);
|
|
272
|
+
if (local && (local.kind === 'function' || local.kind === 'method' || local.kind === 'class')) {
|
|
273
|
+
edges.push({ source: sourceId ?? file, target: local.id, relation: 'calls', confidence: 'EXTRACTED', file, line: call.line });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const heritage of extraction.heritage) {
|
|
277
|
+
const sourceId = enclosingSymbolId(extraction, heritage.line);
|
|
278
|
+
const importedId = importedBindingToSymbol.get(heritage.name);
|
|
279
|
+
const localId = firstSymbolByName.get(heritage.name);
|
|
280
|
+
const target = importedId ?? (localId?.kind === 'class' ? localId.id : undefined);
|
|
281
|
+
if (target) {
|
|
282
|
+
edges.push({ source: sourceId ?? file, target, relation: 'inherits', confidence: importedId ? 'INFERRED' : 'EXTRACTED', file, line: heritage.line });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
for (const symbol of extraction.symbols) {
|
|
286
|
+
edges.push({ source: file, target: symbol.id, relation: 'defines', confidence: 'EXTRACTED', file, line: symbol.line });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return { nodes, edges };
|
|
290
|
+
}
|