@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,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph query engine: natural-language-ish retrieval over the code graph,
|
|
3
|
+
* following the design that made graphify's retrieval outperform grep/read
|
|
4
|
+
* loops on large repos —
|
|
5
|
+
*
|
|
6
|
+
* - IDF-weighted exact/prefix/substring scoring over symbol labels and file
|
|
7
|
+
* paths, with coverage scaling so one incidental exact match cannot drown
|
|
8
|
+
* out multi-term matches;
|
|
9
|
+
* - one guaranteed seed per distinct query term (a collision on one term
|
|
10
|
+
* cannot starve the others);
|
|
11
|
+
* - hub-damped BFS/DFS (nodes above ~p99 degree are never expanded as
|
|
12
|
+
* transit; seeds are exempt) so framework hubs don't flood the answer;
|
|
13
|
+
* - token-budgeted rendering that cuts at line boundaries and never cuts the
|
|
14
|
+
* seed block, file-first so answers read like a map.
|
|
15
|
+
*
|
|
16
|
+
* Haze's 4-chars-per-token heuristic sets the char budget from a token budget.
|
|
17
|
+
*/
|
|
18
|
+
import { type GraphEdge, type GraphIndex, type GraphNode } from './model.js';
|
|
19
|
+
export declare function tokenizeQuery(question: string): string[];
|
|
20
|
+
interface ScoredNode {
|
|
21
|
+
id: string;
|
|
22
|
+
score: number;
|
|
23
|
+
/** Query tokens matched by this node's label (coverage numerator). */
|
|
24
|
+
matched: number;
|
|
25
|
+
}
|
|
26
|
+
/** Pick BFS seeds: top-scoring with a score-gap cutoff, then guarantee one seed per query term. */
|
|
27
|
+
export declare function pickSeeds(index: GraphIndex, ranked: ScoredNode[], bestByTerm: Map<string, string>, maxSeeds?: number, gapRatio?: number): string[];
|
|
28
|
+
/** p99-degree threshold, floored at 50: nodes at/above it are transit-opaque hubs. */
|
|
29
|
+
export declare function hubThreshold(index: GraphIndex): number;
|
|
30
|
+
export interface TraversalResult {
|
|
31
|
+
visited: Set<string>;
|
|
32
|
+
edges: Array<{
|
|
33
|
+
source: string;
|
|
34
|
+
target: string;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
/** Hub-damped BFS/DFS over both edge directions; records induced edges among visited nodes. */
|
|
38
|
+
export declare function traverse(index: GraphIndex, seeds: string[], depth: number, mode?: 'bfs' | 'dfs'): TraversalResult;
|
|
39
|
+
export interface QueryResult {
|
|
40
|
+
answer: string;
|
|
41
|
+
truncated: boolean;
|
|
42
|
+
seedCount: number;
|
|
43
|
+
nodeCount: number;
|
|
44
|
+
edgeCount: number;
|
|
45
|
+
}
|
|
46
|
+
/** Render the traversed subgraph under a token budget; the seed block is never cut. */
|
|
47
|
+
export declare function renderSubgraph(index: GraphIndex, traversal: TraversalResult, seeds: string[], budgetTokens?: number): {
|
|
48
|
+
answer: string;
|
|
49
|
+
truncated: boolean;
|
|
50
|
+
};
|
|
51
|
+
/** Full question-to-subgraph pipeline. */
|
|
52
|
+
export declare function queryGraph(index: GraphIndex, question: string, options?: {
|
|
53
|
+
mode?: 'bfs' | 'dfs';
|
|
54
|
+
depth?: number;
|
|
55
|
+
budgetTokens?: number;
|
|
56
|
+
}): QueryResult;
|
|
57
|
+
/** Symbol lookup for explain/path/affected: exact label, then label substring, then path substring. */
|
|
58
|
+
export declare function findNodeCandidates(index: GraphIndex, query: string, limit?: number): GraphNode[];
|
|
59
|
+
/** Shortest path between two nodes over the undirected projection; BFS with parent tracking. */
|
|
60
|
+
export declare function shortestPath(index: GraphIndex, from: string, to: string, maxDepth?: number): {
|
|
61
|
+
path: string[];
|
|
62
|
+
edges: GraphEdge[];
|
|
63
|
+
} | undefined;
|
|
64
|
+
/** Render a path result: one line per hop with relation and confidence. */
|
|
65
|
+
export declare function renderPath(index: GraphIndex, result: {
|
|
66
|
+
path: string[];
|
|
67
|
+
edges: GraphEdge[];
|
|
68
|
+
}): string;
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph query engine: natural-language-ish retrieval over the code graph,
|
|
3
|
+
* following the design that made graphify's retrieval outperform grep/read
|
|
4
|
+
* loops on large repos —
|
|
5
|
+
*
|
|
6
|
+
* - IDF-weighted exact/prefix/substring scoring over symbol labels and file
|
|
7
|
+
* paths, with coverage scaling so one incidental exact match cannot drown
|
|
8
|
+
* out multi-term matches;
|
|
9
|
+
* - one guaranteed seed per distinct query term (a collision on one term
|
|
10
|
+
* cannot starve the others);
|
|
11
|
+
* - hub-damped BFS/DFS (nodes above ~p99 degree are never expanded as
|
|
12
|
+
* transit; seeds are exempt) so framework hubs don't flood the answer;
|
|
13
|
+
* - token-budgeted rendering that cuts at line boundaries and never cuts the
|
|
14
|
+
* seed block, file-first so answers read like a map.
|
|
15
|
+
*
|
|
16
|
+
* Haze's 4-chars-per-token heuristic sets the char budget from a token budget.
|
|
17
|
+
*/
|
|
18
|
+
import { nodeDegree } from './model.js';
|
|
19
|
+
import { isTestPath } from './analyze.js';
|
|
20
|
+
const QUERY_STOPWORDS = new Set([
|
|
21
|
+
'how', 'what', 'why', 'when', 'where', 'which', 'who', 'does', 'did', 'is', 'are', 'was', 'were',
|
|
22
|
+
'can', 'could', 'should', 'would', 'will', 'shall', 'may', 'might', 'must', 'has', 'have', 'had',
|
|
23
|
+
'the', 'and', 'but', 'not', 'for', 'from', 'with', 'into', 'that', 'this', 'these', 'those',
|
|
24
|
+
'work', 'works', 'working', 'get', 'gets', 'call', 'calls', 'called', 'use', 'uses', 'used', 'using',
|
|
25
|
+
'me', 'my', 'it', 'its',
|
|
26
|
+
]);
|
|
27
|
+
const EXACT_TIER = 1000;
|
|
28
|
+
const PREFIX_TIER = 100;
|
|
29
|
+
const SUBSTRING_TIER = 1;
|
|
30
|
+
const PATH_TIER = 0.5;
|
|
31
|
+
export function tokenizeQuery(question) {
|
|
32
|
+
const tokens = question.toLowerCase().split(/[^a-z0-9_$]+/).filter(token => token.length > 1);
|
|
33
|
+
const content = tokens.filter(token => !QUERY_STOPWORDS.has(token));
|
|
34
|
+
return [...new Set(content.length > 0 ? content : tokens)];
|
|
35
|
+
}
|
|
36
|
+
/** Document frequency per token over lowercased labels + file paths, for IDF weighting. */
|
|
37
|
+
function computeIdf(index, tokens) {
|
|
38
|
+
const total = index.nodes.size || 1;
|
|
39
|
+
const idf = new Map();
|
|
40
|
+
for (const token of tokens) {
|
|
41
|
+
let df = 0;
|
|
42
|
+
for (const node of index.nodes.values()) {
|
|
43
|
+
const haystack = `${node.label.toLowerCase()} ${node.file.toLowerCase()}`;
|
|
44
|
+
if (haystack.includes(token))
|
|
45
|
+
df += 1;
|
|
46
|
+
}
|
|
47
|
+
idf.set(token, Math.log(1 + total / (1 + df)));
|
|
48
|
+
}
|
|
49
|
+
return idf;
|
|
50
|
+
}
|
|
51
|
+
function scoreNodes(index, tokens, idf) {
|
|
52
|
+
const ranked = [];
|
|
53
|
+
const bestByTerm = new Map();
|
|
54
|
+
for (const node of index.nodes.values()) {
|
|
55
|
+
const label = node.label.toLowerCase();
|
|
56
|
+
const filePath = node.file.toLowerCase();
|
|
57
|
+
let score = 0;
|
|
58
|
+
let matched = 0;
|
|
59
|
+
let tiered = 0;
|
|
60
|
+
for (const token of tokens) {
|
|
61
|
+
const weight = idf.get(token) ?? 1;
|
|
62
|
+
const substringHit = label.includes(token);
|
|
63
|
+
const pathHit = filePath.includes(token);
|
|
64
|
+
let tier = 0;
|
|
65
|
+
if (token === label) {
|
|
66
|
+
tier = EXACT_TIER * weight;
|
|
67
|
+
matched += 1;
|
|
68
|
+
}
|
|
69
|
+
else if (label.startsWith(token)) {
|
|
70
|
+
tier = PREFIX_TIER * weight;
|
|
71
|
+
matched += 1;
|
|
72
|
+
}
|
|
73
|
+
else if (substringHit) {
|
|
74
|
+
score += SUBSTRING_TIER * weight;
|
|
75
|
+
matched += 1;
|
|
76
|
+
}
|
|
77
|
+
if (pathHit)
|
|
78
|
+
score += PATH_TIER * weight;
|
|
79
|
+
tiered += tier;
|
|
80
|
+
// Track the best node per term for the per-term seed guarantee. Ties
|
|
81
|
+
// prefer the higher-degree node (the more load-bearing definition).
|
|
82
|
+
const singleton = tier > 0 || substringHit || pathHit ? (tier > 0 ? tier : SUBSTRING_TIER * weight) : 0;
|
|
83
|
+
if (singleton > 0) {
|
|
84
|
+
const degree = nodeDegree(index, node.id);
|
|
85
|
+
const current = bestByTerm.get(token);
|
|
86
|
+
if (!current || singleton > current.score || (singleton === current.score && degree > current.degree)) {
|
|
87
|
+
bestByTerm.set(token, { score: singleton, degree, id: node.id });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
// Coverage scaling: a lone exact hit on one of many terms must not beat
|
|
92
|
+
// nodes matching several terms (squared because exact is 10x prefix).
|
|
93
|
+
if (tiered > 0 && tokens.length > 0) {
|
|
94
|
+
score += tiered * (matched / tokens.length) ** 2;
|
|
95
|
+
}
|
|
96
|
+
// Test helpers repeat the question's words in their own names; demote them
|
|
97
|
+
// unless the question itself asks about tests.
|
|
98
|
+
if (score > 0 && isTestPath(node.file) && !tokens.some(token => token === 'test' || token === 'tests' || token === 'testing' || token === 'spec')) {
|
|
99
|
+
score *= 0.3;
|
|
100
|
+
}
|
|
101
|
+
if (score > 0)
|
|
102
|
+
ranked.push({ id: node.id, score, matched });
|
|
103
|
+
}
|
|
104
|
+
ranked.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
105
|
+
return { ranked, bestByTerm: new Map([...bestByTerm].map(([token, value]) => [token, value.id])) };
|
|
106
|
+
}
|
|
107
|
+
/** Pick BFS seeds: top-scoring with a score-gap cutoff, then guarantee one seed per query term. */
|
|
108
|
+
export function pickSeeds(index, ranked, bestByTerm, maxSeeds = 4, gapRatio = 0.15) {
|
|
109
|
+
if (ranked.length === 0)
|
|
110
|
+
return [];
|
|
111
|
+
const seeds = [];
|
|
112
|
+
const seen = new Set();
|
|
113
|
+
const top = ranked[0].score;
|
|
114
|
+
for (const entry of ranked) {
|
|
115
|
+
if (seeds.length >= maxSeeds)
|
|
116
|
+
break;
|
|
117
|
+
if (seeds.length > 0 && entry.score < top * gapRatio)
|
|
118
|
+
break;
|
|
119
|
+
const labelKey = index.nodes.get(entry.id)?.label.toLowerCase() ?? entry.id;
|
|
120
|
+
if (seen.has(labelKey))
|
|
121
|
+
continue;
|
|
122
|
+
seen.add(labelKey);
|
|
123
|
+
seeds.push(entry.id);
|
|
124
|
+
}
|
|
125
|
+
// Per-term guarantee: an incidental exact match on one term cannot starve matches on the others.
|
|
126
|
+
for (const id of bestByTerm.values()) {
|
|
127
|
+
const node = index.nodes.get(id);
|
|
128
|
+
if (!node || seeds.includes(id))
|
|
129
|
+
continue;
|
|
130
|
+
const labelKey = node.label.toLowerCase();
|
|
131
|
+
if (seen.has(labelKey))
|
|
132
|
+
continue;
|
|
133
|
+
seen.add(labelKey);
|
|
134
|
+
seeds.push(id);
|
|
135
|
+
if (seeds.length >= maxSeeds + 4)
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
return seeds;
|
|
139
|
+
}
|
|
140
|
+
/** p99-degree threshold, floored at 50: nodes at/above it are transit-opaque hubs. */
|
|
141
|
+
export function hubThreshold(index) {
|
|
142
|
+
if (index.nodes.size === 0)
|
|
143
|
+
return 50;
|
|
144
|
+
const degrees = [];
|
|
145
|
+
for (const id of index.nodes.keys())
|
|
146
|
+
degrees.push(nodeDegree(index, id));
|
|
147
|
+
degrees.sort((a, b) => a - b);
|
|
148
|
+
const p99 = degrees[Math.floor(degrees.length * 0.99)] ?? 50;
|
|
149
|
+
return Math.max(50, p99);
|
|
150
|
+
}
|
|
151
|
+
/** Hub-damped BFS/DFS over both edge directions; records induced edges among visited nodes. */
|
|
152
|
+
export function traverse(index, seeds, depth, mode = 'bfs') {
|
|
153
|
+
const seedSet = new Set(seeds);
|
|
154
|
+
const visited = new Set(seeds);
|
|
155
|
+
const edgesSeen = [];
|
|
156
|
+
const edgeKey = new Set();
|
|
157
|
+
const threshold = hubThreshold(index);
|
|
158
|
+
const neighborsOf = (id) => {
|
|
159
|
+
const result = [];
|
|
160
|
+
for (const edge of index.out.get(id) ?? [])
|
|
161
|
+
result.push(edge.target);
|
|
162
|
+
for (const edge of index.in.get(id) ?? [])
|
|
163
|
+
result.push(edge.source);
|
|
164
|
+
return result;
|
|
165
|
+
};
|
|
166
|
+
const record = (from, to) => {
|
|
167
|
+
const key = `${from}\u0000${to}`;
|
|
168
|
+
if (!edgeKey.has(key)) {
|
|
169
|
+
edgeKey.add(key);
|
|
170
|
+
edgesSeen.push({ source: from, target: to });
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
if (mode === 'bfs') {
|
|
174
|
+
let frontier = [...seeds];
|
|
175
|
+
for (let hop = 0; hop < depth && frontier.length > 0; hop++) {
|
|
176
|
+
const next = [];
|
|
177
|
+
for (const current of frontier) {
|
|
178
|
+
if (!seedSet.has(current) && nodeDegree(index, current) >= threshold)
|
|
179
|
+
continue;
|
|
180
|
+
for (const neighbor of neighborsOf(current)) {
|
|
181
|
+
if (visited.has(neighbor))
|
|
182
|
+
continue;
|
|
183
|
+
visited.add(neighbor);
|
|
184
|
+
record(current, neighbor);
|
|
185
|
+
next.push(neighbor);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
frontier = next;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const stack = seeds.map(id => ({ id, depth: 0 }));
|
|
193
|
+
while (stack.length > 0) {
|
|
194
|
+
const { id, depth: currentDepth } = stack.pop();
|
|
195
|
+
if (visited.has(id) && !seedSet.has(id))
|
|
196
|
+
continue;
|
|
197
|
+
if (currentDepth > depth)
|
|
198
|
+
continue;
|
|
199
|
+
visited.add(id);
|
|
200
|
+
if (!seedSet.has(id) && nodeDegree(index, id) >= threshold)
|
|
201
|
+
continue;
|
|
202
|
+
for (const neighbor of neighborsOf(id)) {
|
|
203
|
+
if (!visited.has(neighbor)) {
|
|
204
|
+
record(id, neighbor);
|
|
205
|
+
stack.push({ id: neighbor, depth: currentDepth + 1 });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// Complete induced edges among visited nodes (traversals only record discovery edges).
|
|
211
|
+
for (const id of [...visited].sort()) {
|
|
212
|
+
for (const edge of index.out.get(id) ?? []) {
|
|
213
|
+
if (edge.target !== id && visited.has(edge.target))
|
|
214
|
+
record(id, edge.target);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return { visited, edges: edgesSeen };
|
|
218
|
+
}
|
|
219
|
+
const DEFAULT_TOKEN_BUDGET = 1500;
|
|
220
|
+
const MAX_TOKEN_BUDGET = 4000;
|
|
221
|
+
const CHARS_PER_TOKEN = 4;
|
|
222
|
+
function edgeLine(index, source, target) {
|
|
223
|
+
const sourceNode = index.nodes.get(source);
|
|
224
|
+
const targetNode = index.nodes.get(target);
|
|
225
|
+
if (!sourceNode || !targetNode)
|
|
226
|
+
return undefined;
|
|
227
|
+
const first = index.out.get(source)?.find(edge => edge.target === target)
|
|
228
|
+
?? index.in.get(source)?.find(edge => edge.source === target);
|
|
229
|
+
if (!first)
|
|
230
|
+
return undefined;
|
|
231
|
+
const at = first.line ? ` at ${first.file}:${first.line}` : '';
|
|
232
|
+
return `EDGE ${sourceNode.label} --${first.relation} [${first.confidence}]--> ${targetNode.label}${at}`;
|
|
233
|
+
}
|
|
234
|
+
function nodeLine(index, id, seed) {
|
|
235
|
+
const node = index.nodes.get(id);
|
|
236
|
+
const community = node.community != null ? ` community=${node.community}` : '';
|
|
237
|
+
return `NODE ${node.label} [${seed ? 'seed ' : ''}${node.kind} src=${node.file}:${node.line}${community}]`;
|
|
238
|
+
}
|
|
239
|
+
/** Render the traversed subgraph under a token budget; the seed block is never cut. */
|
|
240
|
+
export function renderSubgraph(index, traversal, seeds, budgetTokens = DEFAULT_TOKEN_BUDGET) {
|
|
241
|
+
const charBudget = Math.min(budgetTokens, MAX_TOKEN_BUDGET) * CHARS_PER_TOKEN;
|
|
242
|
+
const seedSet = new Set(seeds);
|
|
243
|
+
const dist = new Map(seeds.map(id => [id, 0]));
|
|
244
|
+
// Hop distance from seeds over both directions, for budget-cut ordering:
|
|
245
|
+
// the nodes that answer the question survive the cut, hubs don't push them out.
|
|
246
|
+
let frontier = [...seeds];
|
|
247
|
+
let hop = 0;
|
|
248
|
+
while (frontier.length > 0) {
|
|
249
|
+
hop += 1;
|
|
250
|
+
const next = [];
|
|
251
|
+
for (const id of frontier) {
|
|
252
|
+
for (const edge of index.out.get(id) ?? []) {
|
|
253
|
+
if (!dist.has(edge.target) && traversal.visited.has(edge.target)) {
|
|
254
|
+
dist.set(edge.target, hop);
|
|
255
|
+
next.push(edge.target);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
for (const edge of index.in.get(id) ?? []) {
|
|
259
|
+
if (!dist.has(edge.source) && traversal.visited.has(edge.source)) {
|
|
260
|
+
dist.set(edge.source, hop);
|
|
261
|
+
next.push(edge.source);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
frontier = next;
|
|
266
|
+
}
|
|
267
|
+
const orderedNodes = [...seeds, ...[...traversal.visited]
|
|
268
|
+
.filter(id => !seedSet.has(id))
|
|
269
|
+
.sort((a, b) => (dist.get(a) ?? 99) - (dist.get(b) ?? 99) || nodeDegree(index, b) - nodeDegree(index, a) || a.localeCompare(b))];
|
|
270
|
+
const lines = [];
|
|
271
|
+
for (const id of orderedNodes) {
|
|
272
|
+
if (index.nodes.has(id))
|
|
273
|
+
lines.push(nodeLine(index, id, seedSet.has(id)));
|
|
274
|
+
}
|
|
275
|
+
for (const edge of traversal.edges) {
|
|
276
|
+
const line = edgeLine(index, edge.source, edge.target);
|
|
277
|
+
if (line)
|
|
278
|
+
lines.push(line);
|
|
279
|
+
}
|
|
280
|
+
let output = lines.join('\n');
|
|
281
|
+
if (output.length <= charBudget)
|
|
282
|
+
return { answer: output, truncated: false };
|
|
283
|
+
const cutCandidate = output.slice(0, charBudget);
|
|
284
|
+
let cutAt = cutCandidate.lastIndexOf('\n');
|
|
285
|
+
if (cutAt <= 0)
|
|
286
|
+
cutAt = charBudget;
|
|
287
|
+
// Never cut the seed block: extend the cut to cover it (seeds are bounded).
|
|
288
|
+
const seedBlockEnd = lines.slice(0, seeds.length).reduce((sum, line) => sum + line.length + 1, 0) - 1;
|
|
289
|
+
cutAt = Math.max(cutAt, Math.min(seedBlockEnd, output.length));
|
|
290
|
+
output = `${output.slice(0, cutAt)}\n[… truncated; raise budget or query more specifically]`;
|
|
291
|
+
return { answer: output, truncated: true };
|
|
292
|
+
}
|
|
293
|
+
/** Full question-to-subgraph pipeline. */
|
|
294
|
+
export function queryGraph(index, question, options = {}) {
|
|
295
|
+
const tokens = tokenizeQuery(question);
|
|
296
|
+
if (tokens.length === 0) {
|
|
297
|
+
return { answer: 'No searchable terms in the question.', truncated: false, seedCount: 0, nodeCount: 0, edgeCount: 0 };
|
|
298
|
+
}
|
|
299
|
+
const idf = computeIdf(index, tokens);
|
|
300
|
+
const { ranked, bestByTerm } = scoreNodes(index, tokens, idf);
|
|
301
|
+
if (ranked.length === 0) {
|
|
302
|
+
return { answer: `No graph nodes matched: ${tokens.join(', ')}.`, truncated: false, seedCount: 0, nodeCount: 0, edgeCount: 0 };
|
|
303
|
+
}
|
|
304
|
+
const seeds = pickSeeds(index, ranked, bestByTerm);
|
|
305
|
+
const traversal = traverse(index, seeds, options.depth ?? 2, options.mode ?? 'bfs');
|
|
306
|
+
const { answer, truncated } = renderSubgraph(index, traversal, seeds, options.budgetTokens);
|
|
307
|
+
return { answer, truncated, seedCount: seeds.length, nodeCount: traversal.visited.size, edgeCount: traversal.edges.length };
|
|
308
|
+
}
|
|
309
|
+
/** Symbol lookup for explain/path/affected: exact label, then label substring, then path substring. */
|
|
310
|
+
export function findNodeCandidates(index, query, limit = 5) {
|
|
311
|
+
const lowered = query.toLowerCase();
|
|
312
|
+
const exact = index.labels.get(lowered) ?? [];
|
|
313
|
+
const scored = [];
|
|
314
|
+
for (const id of exact) {
|
|
315
|
+
const node = index.nodes.get(id);
|
|
316
|
+
if (node)
|
|
317
|
+
scored.push({ node, score: 1000 + nodeDegree(index, id) });
|
|
318
|
+
}
|
|
319
|
+
if (scored.length === 0) {
|
|
320
|
+
for (const node of index.nodes.values()) {
|
|
321
|
+
if (node.kind === 'file')
|
|
322
|
+
continue;
|
|
323
|
+
const label = node.label.toLowerCase();
|
|
324
|
+
if (label === lowered)
|
|
325
|
+
scored.push({ node, score: 1000 + nodeDegree(index, node.id) });
|
|
326
|
+
else if (label.includes(lowered))
|
|
327
|
+
scored.push({ node, score: 100 + nodeDegree(index, node.id) });
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (scored.length === 0) {
|
|
331
|
+
for (const node of index.nodes.values()) {
|
|
332
|
+
if (node.file.toLowerCase().includes(lowered))
|
|
333
|
+
scored.push({ node, score: 50 + nodeDegree(index, node.id) });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return scored.sort((a, b) => b.score - a.score || a.node.id.localeCompare(b.node.id)).slice(0, limit).map(entry => entry.node);
|
|
337
|
+
}
|
|
338
|
+
/** Shortest path between two nodes over the undirected projection; BFS with parent tracking. */
|
|
339
|
+
export function shortestPath(index, from, to, maxDepth = 8) {
|
|
340
|
+
if (from === to)
|
|
341
|
+
return { path: [from], edges: [] };
|
|
342
|
+
const parent = new Map();
|
|
343
|
+
const visited = new Set([from]);
|
|
344
|
+
let frontier = [from];
|
|
345
|
+
let depth = 0;
|
|
346
|
+
while (frontier.length > 0 && depth < maxDepth) {
|
|
347
|
+
depth += 1;
|
|
348
|
+
const next = [];
|
|
349
|
+
for (const current of frontier) {
|
|
350
|
+
const steps = [];
|
|
351
|
+
for (const edge of index.out.get(current) ?? [])
|
|
352
|
+
steps.push({ neighbor: edge.target, edge });
|
|
353
|
+
for (const edge of index.in.get(current) ?? [])
|
|
354
|
+
steps.push({ neighbor: edge.source, edge });
|
|
355
|
+
for (const step of steps) {
|
|
356
|
+
if (visited.has(step.neighbor))
|
|
357
|
+
continue;
|
|
358
|
+
visited.add(step.neighbor);
|
|
359
|
+
parent.set(step.neighbor, { node: current, edge: step.edge });
|
|
360
|
+
if (step.neighbor === to) {
|
|
361
|
+
const path = [to];
|
|
362
|
+
const edges = [];
|
|
363
|
+
let cursor = to;
|
|
364
|
+
while (cursor !== from) {
|
|
365
|
+
const link = parent.get(cursor);
|
|
366
|
+
edges.unshift(link.edge);
|
|
367
|
+
cursor = link.node;
|
|
368
|
+
path.unshift(cursor);
|
|
369
|
+
}
|
|
370
|
+
return { path, edges };
|
|
371
|
+
}
|
|
372
|
+
next.push(step.neighbor);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
frontier = next;
|
|
376
|
+
}
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
/** Render a path result: one line per hop with relation and confidence. */
|
|
380
|
+
export function renderPath(index, result) {
|
|
381
|
+
const lines = [];
|
|
382
|
+
for (const [position, edge] of result.edges.entries()) {
|
|
383
|
+
const fromNode = index.nodes.get(result.path[position]);
|
|
384
|
+
const toNode = index.nodes.get(result.path[position + 1]);
|
|
385
|
+
if (!fromNode || !toNode)
|
|
386
|
+
continue;
|
|
387
|
+
const at = edge.line ? ` at ${edge.file}:${edge.line}` : '';
|
|
388
|
+
lines.push(`${fromNode.label} (${fromNode.kind} ${fromNode.file}) --${edge.relation} [${edge.confidence}]--> ${toNode.label}${at}`);
|
|
389
|
+
}
|
|
390
|
+
return lines.length > 0 ? lines.join('\n') : `${index.nodes.get(result.path[0])?.label ?? result.path[0]} (same node)`;
|
|
391
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { type CodeGraph } from './model.js';
|
|
2
|
+
import { type FileExtraction } from './extract.js';
|
|
3
|
+
export interface FileSignature {
|
|
4
|
+
size: number;
|
|
5
|
+
mtimeMs: number;
|
|
6
|
+
hash?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface GraphManifest {
|
|
9
|
+
extractorVersion: number;
|
|
10
|
+
workspaceRoot: string;
|
|
11
|
+
files: Record<string, FileSignature>;
|
|
12
|
+
}
|
|
13
|
+
export interface GraphStore {
|
|
14
|
+
dir: string;
|
|
15
|
+
graphPath: string;
|
|
16
|
+
manifestPath: string;
|
|
17
|
+
cacheDir: string;
|
|
18
|
+
}
|
|
19
|
+
/** Stable directory key for a workspace root (real path, hashed for filename safety). */
|
|
20
|
+
export declare function workspaceGraphKey(root: string): string;
|
|
21
|
+
export declare function graphStoreFor(root: string): GraphStore;
|
|
22
|
+
/** Read the persisted graph; undefined when none exists. Throws on corrupt JSON (caller decides to rebuild). */
|
|
23
|
+
export declare function readGraph(store: GraphStore): Promise<CodeGraph | undefined>;
|
|
24
|
+
export declare function readManifest(store: GraphStore): Promise<GraphManifest | undefined>;
|
|
25
|
+
export interface WriteGraphOptions {
|
|
26
|
+
/** Permit intentional shrink (mass deletion); otherwise a graph that loses most of its nodes is refused. */
|
|
27
|
+
force?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Persist graph + manifest atomically. The shrink guard refuses to replace a
|
|
31
|
+
* healthy graph with a near-empty one unless `force` — a half walk or a parser
|
|
32
|
+
* failure must not silently destroy a good map (mirrors graphify's #479 guard).
|
|
33
|
+
*/
|
|
34
|
+
export declare function writeGraph(store: GraphStore, graph: CodeGraph, manifest: GraphManifest, options?: WriteGraphOptions): Promise<void>;
|
|
35
|
+
export declare function readCachedExtraction(store: GraphStore, hash: string): Promise<FileExtraction | undefined>;
|
|
36
|
+
export declare function writeCachedExtraction(store: GraphStore, hash: string, extraction: FileExtraction): Promise<void>;
|
|
37
|
+
/** Drop cache entries beyond a bounded count (oldest mtime first). */
|
|
38
|
+
export declare function pruneExtractionCache(store: GraphStore, maxEntries: number): Promise<void>;
|
|
39
|
+
export interface StaleFileSet {
|
|
40
|
+
changed: string[];
|
|
41
|
+
added: string[];
|
|
42
|
+
removed: string[];
|
|
43
|
+
}
|
|
44
|
+
export interface StalenessReport {
|
|
45
|
+
stale: boolean;
|
|
46
|
+
files: StaleFileSet;
|
|
47
|
+
}
|
|
48
|
+
/** Compare manifest signatures against the current tree; size/mtime mismatches count as changed. */
|
|
49
|
+
export declare function computeStaleness(store: GraphStore, currentSignatures: Record<string, FileSignature>): Promise<StalenessReport>;
|
|
50
|
+
/**
|
|
51
|
+
* Delete the whole persisted graph for a workspace (graph.json, manifest,
|
|
52
|
+
* extraction cache). Returns true when a graph store existed and was removed.
|
|
53
|
+
*/
|
|
54
|
+
export declare function deleteGraph(store: GraphStore): Promise<boolean>;
|
|
55
|
+
/** Cheap existence + freshness check used by tool entry points and /graph. */
|
|
56
|
+
export declare function graphStatus(store: GraphStore): Promise<{
|
|
57
|
+
exists: boolean;
|
|
58
|
+
stale: boolean;
|
|
59
|
+
builtAt?: string;
|
|
60
|
+
nodeCount: number;
|
|
61
|
+
edgeCount: number;
|
|
62
|
+
fileCount: number;
|
|
63
|
+
graph?: CodeGraph;
|
|
64
|
+
}>;
|