claude-db 0.11.1 → 0.12.1

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.
Files changed (175) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +5 -4
  3. package/dist/cli/commands/graph.js +104 -80
  4. package/dist/cli/commands/languages.d.ts +1 -0
  5. package/dist/cli/commands/languages.js +22 -0
  6. package/dist/cli/commands/pick.js +4 -2
  7. package/dist/cli/index.js +4 -0
  8. package/dist/cli/usage.js +3 -1
  9. package/dist/graph/ast.d.ts +4 -0
  10. package/dist/graph/ast.js +11 -0
  11. package/dist/graph/grammars.d.ts +14 -0
  12. package/dist/graph/grammars.js +58 -0
  13. package/dist/graph/index.d.ts +2 -2
  14. package/dist/graph/index.js +2 -2
  15. package/dist/graph/languages/basic.js +5 -1
  16. package/dist/graph/languages/ecmascript.js +7 -0
  17. package/dist/graph/languages/go.js +0 -1
  18. package/dist/graph/languages/index.d.ts +1 -1
  19. package/dist/graph/languages/index.js +34 -9
  20. package/dist/graph/languages/java.d.ts +2 -0
  21. package/dist/graph/languages/java.js +38 -0
  22. package/dist/graph/languages/kotlin.d.ts +2 -0
  23. package/dist/graph/languages/kotlin.js +19 -0
  24. package/dist/graph/languages/python.js +10 -2
  25. package/dist/graph/languages/rules.d.ts +11 -0
  26. package/dist/graph/languages/rust.js +2 -1
  27. package/dist/graph/modules/binding.d.ts +61 -0
  28. package/dist/graph/modules/binding.js +43 -0
  29. package/dist/graph/modules/ecmascript/bind.d.ts +4 -0
  30. package/dist/graph/modules/ecmascript/bind.js +17 -0
  31. package/dist/graph/modules/ecmascript/contexts.d.ts +6 -0
  32. package/dist/graph/modules/ecmascript/contexts.js +86 -0
  33. package/dist/graph/modules/ecmascript/exports.d.ts +9 -0
  34. package/dist/graph/modules/ecmascript/exports.js +91 -0
  35. package/dist/graph/modules/ecmascript/imports.d.ts +4 -0
  36. package/dist/graph/modules/ecmascript/imports.js +73 -0
  37. package/dist/graph/modules/ecmascript/package-resolver.d.ts +4 -0
  38. package/dist/graph/modules/ecmascript/package-resolver.js +73 -0
  39. package/dist/graph/modules/ecmascript/resolver.d.ts +2 -0
  40. package/dist/graph/modules/ecmascript/resolver.js +22 -0
  41. package/dist/graph/modules/ecmascript/specifiers.d.ts +3 -0
  42. package/dist/graph/modules/ecmascript/specifiers.js +15 -0
  43. package/dist/graph/modules/ecmascript/system.d.ts +2 -0
  44. package/dist/graph/modules/ecmascript/system.js +18 -0
  45. package/dist/graph/modules/ecmascript/workspace-resolver.d.ts +5 -0
  46. package/dist/graph/modules/ecmascript/workspace-resolver.js +38 -0
  47. package/dist/graph/modules/go/grammar.d.ts +2 -0
  48. package/dist/graph/modules/go/grammar.js +54 -0
  49. package/dist/graph/modules/go/imports.d.ts +4 -0
  50. package/dist/graph/modules/go/imports.js +32 -0
  51. package/dist/graph/modules/go/resolver.d.ts +2 -0
  52. package/dist/graph/modules/go/resolver.js +54 -0
  53. package/dist/graph/modules/go/system.d.ts +2 -0
  54. package/dist/graph/modules/go/system.js +16 -0
  55. package/dist/graph/modules/java/declarations.d.ts +9 -0
  56. package/dist/graph/modules/java/declarations.js +108 -0
  57. package/dist/graph/modules/java/grammar.d.ts +2 -0
  58. package/dist/graph/modules/java/grammar.js +135 -0
  59. package/dist/graph/modules/java/imports.d.ts +4 -0
  60. package/dist/graph/modules/java/imports.js +13 -0
  61. package/dist/graph/modules/java/receivers.d.ts +3 -0
  62. package/dist/graph/modules/java/receivers.js +139 -0
  63. package/dist/graph/modules/java/system.d.ts +1 -0
  64. package/dist/graph/modules/java/system.js +13 -0
  65. package/dist/graph/modules/jvm/linking.d.ts +20 -0
  66. package/dist/graph/modules/jvm/linking.js +64 -0
  67. package/dist/graph/modules/jvm/packages.d.ts +5 -0
  68. package/dist/graph/modules/jvm/packages.js +58 -0
  69. package/dist/graph/modules/jvm/receivers.d.ts +44 -0
  70. package/dist/graph/modules/jvm/receivers.js +77 -0
  71. package/dist/graph/modules/jvm/system.d.ts +18 -0
  72. package/dist/graph/modules/jvm/system.js +29 -0
  73. package/dist/graph/modules/jvm/types.d.ts +3 -0
  74. package/dist/graph/modules/jvm/types.js +11 -0
  75. package/dist/graph/modules/kotlin/declarations.d.ts +8 -0
  76. package/dist/graph/modules/kotlin/declarations.js +69 -0
  77. package/dist/graph/modules/kotlin/grammar.d.ts +2 -0
  78. package/dist/graph/modules/kotlin/grammar.js +78 -0
  79. package/dist/graph/modules/kotlin/imports.d.ts +4 -0
  80. package/dist/graph/modules/kotlin/imports.js +25 -0
  81. package/dist/graph/modules/kotlin/receivers.d.ts +3 -0
  82. package/dist/graph/modules/kotlin/receivers.js +105 -0
  83. package/dist/graph/modules/kotlin/references.d.ts +8 -0
  84. package/dist/graph/modules/kotlin/references.js +69 -0
  85. package/dist/graph/modules/kotlin/system.d.ts +1 -0
  86. package/dist/graph/modules/kotlin/system.js +15 -0
  87. package/dist/graph/modules/members.d.ts +17 -0
  88. package/dist/graph/modules/members.js +30 -0
  89. package/dist/graph/modules/module-index.d.ts +9 -0
  90. package/dist/graph/modules/module-index.js +62 -0
  91. package/dist/graph/modules/names.d.ts +2 -0
  92. package/dist/graph/modules/names.js +3 -0
  93. package/dist/graph/modules/python/grammar.d.ts +2 -0
  94. package/dist/graph/modules/python/grammar.js +100 -0
  95. package/dist/graph/modules/python/imports.d.ts +3 -0
  96. package/dist/graph/modules/python/imports.js +72 -0
  97. package/dist/graph/modules/python/resolver.d.ts +2 -0
  98. package/dist/graph/modules/python/resolver.js +78 -0
  99. package/dist/graph/modules/python/system.d.ts +2 -0
  100. package/dist/graph/modules/python/system.js +16 -0
  101. package/dist/graph/modules/rebind.d.ts +8 -0
  102. package/dist/graph/modules/rebind.js +51 -0
  103. package/dist/graph/modules/registry.d.ts +5 -0
  104. package/dist/graph/modules/registry.js +47 -0
  105. package/dist/graph/modules/rust/grammar.d.ts +2 -0
  106. package/dist/graph/modules/rust/grammar.js +94 -0
  107. package/dist/graph/modules/rust/imports.d.ts +3 -0
  108. package/dist/graph/modules/rust/imports.js +90 -0
  109. package/dist/graph/modules/rust/resolver.d.ts +3 -0
  110. package/dist/graph/modules/rust/resolver.js +153 -0
  111. package/dist/graph/modules/rust/system.d.ts +2 -0
  112. package/dist/graph/modules/rust/system.js +16 -0
  113. package/dist/graph/modules/shadowing.d.ts +17 -0
  114. package/dist/graph/modules/shadowing.js +65 -0
  115. package/dist/graph/modules/system.d.ts +39 -0
  116. package/dist/graph/modules/system.js +1 -0
  117. package/dist/graph/modules/uses.d.ts +14 -0
  118. package/dist/graph/modules/uses.js +62 -0
  119. package/dist/graph/parser.d.ts +9 -11
  120. package/dist/graph/parser.js +5 -4
  121. package/dist/graph/query/answer.d.ts +15 -0
  122. package/dist/graph/query/answer.js +22 -0
  123. package/dist/graph/query/format.d.ts +8 -1
  124. package/dist/graph/query/format.js +103 -30
  125. package/dist/graph/query/groups.d.ts +14 -0
  126. package/dist/graph/query/groups.js +51 -0
  127. package/dist/graph/query/index.d.ts +2 -1
  128. package/dist/graph/query/index.js +2 -1
  129. package/dist/graph/query/lookup.d.ts +2 -0
  130. package/dist/graph/query/lookup.js +19 -2
  131. package/dist/graph/query/refresh.js +17 -18
  132. package/dist/graph/query/stale.d.ts +2 -0
  133. package/dist/graph/query/stale.js +39 -0
  134. package/dist/graph/query/text.d.ts +12 -0
  135. package/dist/graph/query/text.js +26 -0
  136. package/dist/graph/scan/binder.d.ts +13 -0
  137. package/dist/graph/scan/binder.js +210 -0
  138. package/dist/graph/scan/cache.d.ts +11 -0
  139. package/dist/graph/scan/cache.js +140 -0
  140. package/dist/graph/scan/extract.d.ts +4 -17
  141. package/dist/graph/scan/extract.js +105 -83
  142. package/dist/graph/scan/files.d.ts +3 -9
  143. package/dist/graph/scan/files.js +3 -2
  144. package/dist/graph/scan/index.d.ts +8 -3
  145. package/dist/graph/scan/index.js +96 -36
  146. package/dist/graph/scan/job.d.ts +1 -0
  147. package/dist/graph/scan/job.js +1 -0
  148. package/dist/graph/scan/persist.d.ts +3 -0
  149. package/dist/graph/scan/persist.js +22 -0
  150. package/dist/graph/scan/receivers.d.ts +21 -0
  151. package/dist/graph/scan/receivers.js +87 -0
  152. package/dist/graph/scan/resolve.d.ts +8 -2
  153. package/dist/graph/scan/resolve.js +50 -56
  154. package/dist/graph/scan/spans.d.ts +13 -0
  155. package/dist/graph/scan/spans.js +42 -0
  156. package/dist/graph/symbols.d.ts +10 -0
  157. package/dist/graph/symbols.js +30 -0
  158. package/dist/graph/types.d.ts +56 -0
  159. package/dist/graph/types.js +1 -0
  160. package/dist/hooks/background.js +1 -16
  161. package/dist/hooks/detached.d.ts +3 -0
  162. package/dist/hooks/detached.js +16 -0
  163. package/dist/hooks/graph-refresh.d.ts +1 -0
  164. package/dist/hooks/graph-refresh.js +9 -0
  165. package/dist/hooks/prefer-usages.js +53 -12
  166. package/dist/hooks/session-start.js +8 -8
  167. package/dist/mcp/tools/usages.js +40 -31
  168. package/dist/pick/run.d.ts +6 -0
  169. package/dist/pick/run.js +8 -1
  170. package/dist/types.d.ts +1 -1
  171. package/dist/usages/find.js +1 -0
  172. package/dist/util/claude-cli.d.ts +1 -0
  173. package/dist/util/claude-cli.js +15 -3
  174. package/docs/how-it-works.md +10 -8
  175. package/package.json +16 -5
@@ -1,2 +1,9 @@
1
1
  import type { GraphAnswer } from './lookup.js';
2
- export declare function formatGraph(answer: GraphAnswer, root: string): string;
2
+ import type { TextMatches } from './text.js';
3
+ export declare const TEXT_SHOWN = 20;
4
+ export interface FormatOptions {
5
+ text?: boolean;
6
+ textShown?: number;
7
+ }
8
+ export declare function formatText(text: TextMatches | undefined, shown?: number): string[];
9
+ export declare function formatGraph(answer: GraphAnswer, root: string, options?: FormatOptions): string;
@@ -1,43 +1,116 @@
1
+ import { importsNames, isTracked } from '../modules/registry.js';
2
+ import { groupByDefinition } from './groups.js';
1
3
  import { formatSuggestions } from './suggest.js';
4
+ export const TEXT_SHOWN = 20;
5
+ const TEXT_WIDTH = 160;
2
6
  function tag(edge) {
3
7
  const score = edge.confidence === 'INFERRED' ? ` ${edge.score.toFixed(2)}` : '';
4
8
  return `[${edge.relation}] [${edge.confidence}${score}]`;
5
9
  }
6
- export function formatGraph(answer, root) {
7
- if (answer.mode === 'path') {
8
- if (answer.path.length === 0) {
9
- return (`No path found from "${answer.symbol}" to "${answer.target ?? ''}".` +
10
- formatSuggestions(answer.suggestions));
11
- }
12
- return [
13
- `Shortest path (${answer.path.length - 1} hops):`,
14
- ` ${answer.path.join(' --> ')}`,
15
- ].join('\n');
16
- }
17
- if (answer.empty) {
18
- return (`No symbol "${answer.symbol}" in the graph for ${root}.` +
19
- formatSuggestions(answer.suggestions));
10
+ const referenceLine = (edge) => ` <-- ${edge.srcName} ${tag(edge)} ${edge.file}:${edge.line}`;
11
+ const importLine = (edge) => ` <-- ${edge.file}:${edge.line} ${tag(edge)}`;
12
+ const edgeLine = (edge) => edge.relation === 'imports' ? importLine(edge) : referenceLine(edge);
13
+ const reachLine = (edge) => ` --> ${edge.dstName} ${tag(edge)} ${edge.file}:${edge.line}`;
14
+ function definitionLines(group, mode) {
15
+ const { definition } = group;
16
+ const lines = [
17
+ `${definition.name} [${definition.kind}]`,
18
+ ` Source: ${definition.file}:${definition.line}`,
19
+ ];
20
+ if (definition.signature)
21
+ lines.push(` ${definition.signature}`);
22
+ for (const owner of group.owners)
23
+ lines.push(` Member of: ${owner.srcName}`);
24
+ lines.push(` Referenced by (${group.references.length}):`, ...group.references.map(referenceLine));
25
+ if (importsNames(definition.lang)) {
26
+ lines.push(` Imported by (${group.imports.length}):`, ...group.imports.map(importLine));
20
27
  }
21
- const lines = [];
22
- for (const definition of answer.definitions) {
23
- lines.push(`${definition.name} [${definition.kind}]`);
24
- lines.push(` Source: ${definition.file}:${definition.line}`);
25
- if (definition.signature)
26
- lines.push(` ${definition.signature}`);
28
+ if (!isTracked(definition.lang)) {
29
+ lines.push(` Imports are not tracked yet for: ${definition.lang}`);
27
30
  }
28
- if (answer.definitions.length === 0) {
29
- lines.push(`${answer.symbol} [no definition in this repository]`);
31
+ if (mode === 'explain') {
32
+ lines.push(` Reaches (${group.reaches.length}):`, ...group.reaches.map(reachLine));
30
33
  }
31
- lines.push(` Referenced by (${answer.inbound.length}):`);
32
- for (const edge of answer.inbound) {
33
- lines.push(` <-- ${edge.srcName} ${tag(edge)} ${edge.file}:${edge.line}`);
34
+ return lines;
35
+ }
36
+ function withoutDefinitionLines(symbol, unbound) {
37
+ const imported = unbound.filter((edge) => edge.relation === 'imports');
38
+ const referenced = unbound.filter((edge) => edge.relation !== 'imports');
39
+ return [
40
+ `${symbol} [no definition in this repository]`,
41
+ ` Referenced by (${referenced.length}):`,
42
+ ...referenced.map(referenceLine),
43
+ ` Imported by (${imported.length}):`,
44
+ ...imported.map(importLine),
45
+ ];
46
+ }
47
+ function guessedLines(guessed, definitions) {
48
+ if (guessed.length === 0)
49
+ return [];
50
+ return [
51
+ `Matched by name, could be any of the ${definitions} definitions above (${guessed.length}):`,
52
+ ...guessed.map(edgeLine),
53
+ ];
54
+ }
55
+ function unboundLines(unbound) {
56
+ if (unbound.length === 0)
57
+ return [];
58
+ return [
59
+ `Matched by name, not linked to one definition (${unbound.length}):`,
60
+ ...unbound.map(edgeLine),
61
+ ];
62
+ }
63
+ function textHeading(text, shown) {
64
+ const count = `${text.lines.length}${text.truncated ? '+' : ''}`;
65
+ if (text.lines.length > shown)
66
+ return `Text matches, not linked (showing ${shown} of ${count}):`;
67
+ return `Text matches, not linked (${count}):`;
68
+ }
69
+ export function formatText(text, shown = TEXT_SHOWN) {
70
+ if (!text)
71
+ return [];
72
+ if (text.error)
73
+ return [`Text matches: not searched (${text.error})`];
74
+ if (text.lines.length === 0)
75
+ return [];
76
+ return [
77
+ textHeading(text, shown),
78
+ ...text.lines
79
+ .slice(0, shown)
80
+ .map((line) => ` ${line.file}:${line.line} ${line.text.slice(0, TEXT_WIDTH)}`),
81
+ ];
82
+ }
83
+ function pathLines(answer) {
84
+ if (answer.path.length === 0) {
85
+ return [
86
+ `No path found from "${answer.symbol}" to "${answer.target ?? ''}".` +
87
+ formatSuggestions(answer.suggestions),
88
+ ];
34
89
  }
35
- if (answer.mode === 'explain') {
36
- lines.push(` Reaches (${answer.outbound.length}):`);
37
- for (const edge of answer.outbound) {
38
- lines.push(` --> ${edge.dstName} ${tag(edge)} ${edge.file}:${edge.line}`);
39
- }
90
+ return [`Shortest path (${answer.path.length - 1} hops):`, ` ${answer.path.join(' --> ')}`];
91
+ }
92
+ function graphLines(answer, root) {
93
+ if (answer.empty) {
94
+ return [
95
+ `No symbol "${answer.symbol}" in the graph for ${root}.` +
96
+ formatSuggestions(answer.suggestions),
97
+ ];
40
98
  }
99
+ const { groups, guessed, unbound } = groupByDefinition(answer.definitions, answer.inbound, answer.outbound);
100
+ if (groups.length === 0)
101
+ return withoutDefinitionLines(answer.symbol, unbound);
102
+ return [
103
+ ...groups.flatMap((group) => definitionLines(group, answer.mode)),
104
+ ...guessedLines(guessed, groups.length),
105
+ ...unboundLines(unbound),
106
+ ];
107
+ }
108
+ export function formatGraph(answer, root, options = {}) {
109
+ if (answer.mode === 'path')
110
+ return pathLines(answer).join('\n');
111
+ const lines = graphLines(answer, root);
112
+ if (options.text !== false)
113
+ lines.push(...formatText(answer.text, options.textShown));
41
114
  if (answer.refreshed.length > 0) {
42
115
  lines.push(` (re-parsed ${answer.refreshed.length} changed file(s) before answering)`);
43
116
  }
@@ -0,0 +1,14 @@
1
+ import type { CodeEdge, CodeSymbol } from '../../types.js';
2
+ export interface DefinitionGroup {
3
+ definition: CodeSymbol;
4
+ owners: CodeEdge[];
5
+ references: CodeEdge[];
6
+ imports: CodeEdge[];
7
+ reaches: CodeEdge[];
8
+ }
9
+ export interface GroupedEdges {
10
+ groups: DefinitionGroup[];
11
+ guessed: CodeEdge[];
12
+ unbound: CodeEdge[];
13
+ }
14
+ export declare function groupByDefinition(definitions: CodeSymbol[], inbound: CodeEdge[], outbound: CodeEdge[]): GroupedEdges;
@@ -0,0 +1,51 @@
1
+ const ALIAS_HOPS = 4;
2
+ function aliasTargets(edges) {
3
+ const targets = new Map();
4
+ for (const edge of edges) {
5
+ if (edge.relation === 'aliases' && edge.srcId && edge.dstId) {
6
+ targets.set(edge.srcId, edge.dstId);
7
+ }
8
+ }
9
+ return targets;
10
+ }
11
+ function definitionOf(id, defined, aliases) {
12
+ let current = id;
13
+ for (let hop = 0; current !== undefined && hop <= ALIAS_HOPS; hop += 1) {
14
+ if (defined.has(current))
15
+ return current;
16
+ current = aliases.get(current);
17
+ }
18
+ return undefined;
19
+ }
20
+ function place(group, edge) {
21
+ if (edge.relation === 'defines')
22
+ group.owners.push(edge);
23
+ else if (edge.relation === 'imports')
24
+ group.imports.push(edge);
25
+ else
26
+ group.references.push(edge);
27
+ }
28
+ export function groupByDefinition(definitions, inbound, outbound) {
29
+ const groups = new Map(definitions.map((definition) => [
30
+ definition.id,
31
+ { definition, owners: [], references: [], imports: [], reaches: [] },
32
+ ]));
33
+ const defined = new Set(groups.keys());
34
+ const aliases = aliasTargets(inbound);
35
+ const several = groups.size > 1;
36
+ const guessed = [];
37
+ const unbound = [];
38
+ for (const edge of inbound) {
39
+ const owner = definitionOf(edge.dstId, defined, aliases);
40
+ const group = owner === undefined ? undefined : groups.get(owner);
41
+ if (!group)
42
+ unbound.push(edge);
43
+ else if (several && edge.confidence === 'INFERRED')
44
+ guessed.push(edge);
45
+ else
46
+ place(group, edge);
47
+ }
48
+ for (const edge of outbound)
49
+ groups.get(edge.srcId)?.reaches.push(edge);
50
+ return { groups: [...groups.values()], guessed, unbound };
51
+ }
@@ -1,4 +1,5 @@
1
- export { formatGraph } from './format.js';
1
+ export { NO_GRAPH, NO_GRAPH_FOR_PATH, addText, answerQuery, hasGraph } from './answer.js';
2
+ export { formatGraph, formatText } from './format.js';
2
3
  export { queryGraph } from './lookup.js';
3
4
  export { refreshGraph } from './refresh.js';
4
5
  export { nearest, suggestFor } from './suggest.js';
@@ -1,4 +1,5 @@
1
- export { formatGraph } from './format.js';
1
+ export { NO_GRAPH, NO_GRAPH_FOR_PATH, addText, answerQuery, hasGraph } from './answer.js';
2
+ export { formatGraph, formatText } from './format.js';
2
3
  export { queryGraph } from './lookup.js';
3
4
  export { refreshGraph } from './refresh.js';
4
5
  export { nearest, suggestFor } from './suggest.js';
@@ -1,5 +1,6 @@
1
1
  import type { MemoryStore } from '../../store/adapter.js';
2
2
  import type { CodeEdge, CodeSymbol } from '../../types.js';
3
+ import type { TextMatches } from './text.js';
3
4
  export type GraphMode = 'usages' | 'explain' | 'path';
4
5
  export interface GraphAnswer {
5
6
  mode: GraphMode;
@@ -12,6 +13,7 @@ export interface GraphAnswer {
12
13
  refreshed: string[];
13
14
  empty: boolean;
14
15
  suggestions: string[];
16
+ text?: TextMatches;
15
17
  }
16
18
  export interface GraphQuery {
17
19
  mode: GraphMode;
@@ -1,5 +1,20 @@
1
1
  import { shortestPath } from './path.js';
2
2
  import { suggestFor } from './suggest.js';
3
+ const ALIAS_DEPTH = 3;
4
+ const aliasIds = (edges) => edges.filter((edge) => edge.relation === 'aliases').map((edge) => edge.srcId);
5
+ async function throughAliases(store, project, inbound, limit) {
6
+ const seen = new Set(inbound.map((edge) => edge.id));
7
+ const found = [];
8
+ let frontier = aliasIds(inbound);
9
+ for (let depth = 0; depth < ALIAS_DEPTH && frontier.length > 0; depth += 1) {
10
+ const fresh = (await store.findEdges({ project, dstIds: frontier, limit })).filter((edge) => !seen.has(edge.id));
11
+ for (const edge of fresh)
12
+ seen.add(edge.id);
13
+ found.push(...fresh);
14
+ frontier = aliasIds(fresh);
15
+ }
16
+ return found;
17
+ }
3
18
  export async function queryGraph(store, project, query) {
4
19
  const answer = {
5
20
  mode: query.mode,
@@ -27,16 +42,18 @@ export async function queryGraph(store, project, query) {
27
42
  limit: query.limit,
28
43
  });
29
44
  const ids = answer.definitions.map((symbol) => symbol.id);
45
+ const edgeLimit = Math.max(query.limit * 10, 500);
30
46
  const edges = await store.findEdges({
31
47
  project,
32
48
  ...(ids.length > 0 ? { srcIds: ids, dstIds: ids } : { dstName: query.symbol }),
33
- limit: Math.max(query.limit * 10, 500),
49
+ limit: edgeLimit,
34
50
  });
35
51
  const idSet = new Set(ids);
36
52
  const pointsAtSymbol = (edge) => edge.dstName === query.symbol ||
37
53
  edge.dstName.endsWith(`.${query.symbol}`) ||
38
54
  (edge.dstId !== '' && idSet.has(edge.dstId));
39
- answer.inbound = edges.filter(pointsAtSymbol);
55
+ const direct = edges.filter(pointsAtSymbol);
56
+ answer.inbound = [...direct, ...(await throughAliases(store, project, direct, edgeLimit))];
40
57
  answer.outbound = edges.filter((edge) => idSet.has(edge.srcId) && !pointsAtSymbol(edge));
41
58
  answer.empty = answer.definitions.length === 0 && answer.inbound.length === 0;
42
59
  if (answer.empty)
@@ -1,21 +1,20 @@
1
- import { currentHashes, scanRepository } from '../scan/index.js';
1
+ import { currentHashes, saveScan, scanRepository } from '../scan/index.js';
2
+ function changesOnDisk(root, stored) {
3
+ const current = currentHashes(root);
4
+ for (const [path, hash] of current)
5
+ if (stored.get(path) !== hash)
6
+ return current;
7
+ for (const path of stored.keys())
8
+ if (!current.has(path))
9
+ return current;
10
+ return null;
11
+ }
2
12
  export async function refreshGraph(store, root, project) {
3
13
  const stored = new Map((await store.scannedFiles(project)).map((file) => [file.path, file.hash]));
4
- const current = currentHashes(root);
5
- const changed = [...current.entries()]
6
- .filter(([path, hash]) => stored.get(path) !== hash)
7
- .map(([path]) => path);
8
- const deleted = [...stored.keys()].filter((path) => !current.has(path));
9
- if (deleted.length > 0)
10
- await store.removeGraph(project, deleted);
11
- if (changed.length === 0)
12
- return deleted;
13
- const scan = scanRepository({ root, project, known: new Map() });
14
- await store.removeGraph(project, scan.changed);
15
- await store.upsertGraph({
16
- symbols: scan.symbols,
17
- edges: scan.edges,
18
- files: scan.files,
19
- });
20
- return [...deleted, ...changed];
14
+ const hashes = changesOnDisk(root, stored);
15
+ if (!hashes)
16
+ return [];
17
+ const scan = await scanRepository({ root, project, stored, hashes, saveCacheLater: true });
18
+ await saveScan(store, project, scan);
19
+ return [...scan.removed, ...scan.changed];
21
20
  }
@@ -0,0 +1,2 @@
1
+ import type { ScannedFile } from '../../types.js';
2
+ export declare function staleFiles(root: string, stored: ScannedFile[]): string[];
@@ -0,0 +1,39 @@
1
+ import { closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { hashOf, sourceFiles } from '../scan/files.js';
4
+ const MTIME_SLACK_MS = 2000;
5
+ function changedSinceScan(root, entry) {
6
+ let fd;
7
+ try {
8
+ fd = openSync(join(root, entry.path), 'r');
9
+ }
10
+ catch {
11
+ return true;
12
+ }
13
+ try {
14
+ if (fstatSync(fd).mtimeMs <= entry.scannedAt - MTIME_SLACK_MS)
15
+ return false;
16
+ return hashOf(readFileSync(fd)) !== entry.hash;
17
+ }
18
+ catch {
19
+ return true;
20
+ }
21
+ finally {
22
+ closeSync(fd);
23
+ }
24
+ }
25
+ export function staleFiles(root, stored) {
26
+ const known = new Map(stored.map((entry) => [entry.path, entry]));
27
+ const current = sourceFiles(root);
28
+ const stale = [];
29
+ for (const path of current) {
30
+ const entry = known.get(path);
31
+ if (!entry || changedSinceScan(root, entry))
32
+ stale.push(path);
33
+ }
34
+ const present = new Set(current);
35
+ for (const path of known.keys())
36
+ if (!present.has(path))
37
+ stale.push(path);
38
+ return stale;
39
+ }
@@ -0,0 +1,12 @@
1
+ import type { CodeEdge, CodeSymbol } from '../../types.js';
2
+ export interface TextLine {
3
+ file: string;
4
+ line: number;
5
+ text: string;
6
+ }
7
+ export interface TextMatches {
8
+ lines: TextLine[];
9
+ truncated: boolean;
10
+ error?: string;
11
+ }
12
+ export declare function unlinkedText(root: string, symbol: string, definitions: CodeSymbol[], inbound: CodeEdge[]): TextMatches;
@@ -0,0 +1,26 @@
1
+ import { findUsages } from '../../usages/find.js';
2
+ const SCAN_LIMIT = 2000;
3
+ const lineKey = (file, line) => `${file}\0${line}`;
4
+ function explainedLines(definitions, inbound) {
5
+ const explained = new Set();
6
+ for (const definition of definitions)
7
+ explained.add(lineKey(definition.file, definition.line));
8
+ for (const edge of inbound)
9
+ explained.add(lineKey(edge.file, edge.line));
10
+ return explained;
11
+ }
12
+ export function unlinkedText(root, symbol, definitions, inbound) {
13
+ let result;
14
+ try {
15
+ result = findUsages({ symbol, path: root, regex: false, context: 0, limit: SCAN_LIMIT });
16
+ }
17
+ catch (error) {
18
+ const reason = error instanceof Error ? error.message : String(error);
19
+ return { lines: [], truncated: false, error: reason };
20
+ }
21
+ const explained = explainedLines(definitions, inbound);
22
+ const lines = result.matches
23
+ .filter((match) => !explained.has(lineKey(match.file, match.line)))
24
+ .map((match) => ({ file: match.file, line: match.line, text: match.text.trim() }));
25
+ return { lines, truncated: result.truncated };
26
+ }
@@ -0,0 +1,13 @@
1
+ import type { CodeEdge, CodeSymbol } from '../../types.js';
2
+ import type { ModuleContext } from '../modules/system.js';
3
+ import type { Reference } from '../types.js';
4
+ export interface Resolution {
5
+ target: CodeSymbol | undefined;
6
+ confidence: CodeEdge['confidence'];
7
+ score: number;
8
+ external: boolean;
9
+ }
10
+ export interface Binder {
11
+ resolve: (reference: Reference) => Resolution | null;
12
+ }
13
+ export declare function createBinder(symbols: CodeSymbol[], references: Reference[], context: ModuleContext): Binder;
@@ -0,0 +1,210 @@
1
+ import { moduleIndex } from '../modules/module-index.js';
2
+ import { lastSegment } from '../modules/names.js';
3
+ import { OUTSIDE, createReceivers } from './receivers.js';
4
+ const SAME_FILE = 1;
5
+ const SINGLE_MATCH = 0.95;
6
+ const AMBIGUOUS_MATCH = 0.85;
7
+ const INHERITANCE_DEPTH = 6;
8
+ const OWNERS = new Set(['class', 'interface', 'enum']);
9
+ const MEMBERS = new Set(['method', 'function', 'class', 'interface', 'enum']);
10
+ const HERITAGE = new Set(['extends', 'implements']);
11
+ const CALLABLE = new Set(['method', 'function']);
12
+ const OUTSIDE_CALL = {
13
+ target: undefined,
14
+ confidence: 'EXTRACTED',
15
+ score: SAME_FILE,
16
+ external: true,
17
+ };
18
+ function enterNamespaces(index, file, path = []) {
19
+ let current = file ?? undefined;
20
+ for (const segment of path)
21
+ current = current ? index.enter(current, segment) : undefined;
22
+ return current;
23
+ }
24
+ function group(items, keyOf) {
25
+ const grouped = new Map();
26
+ for (const item of items) {
27
+ const key = keyOf(item);
28
+ if (key === undefined)
29
+ continue;
30
+ const bucket = grouped.get(key);
31
+ if (bucket)
32
+ bucket.push(item);
33
+ else
34
+ grouped.set(key, [item]);
35
+ }
36
+ return grouped;
37
+ }
38
+ export function createBinder(symbols, references, context) {
39
+ const index = moduleIndex(symbols, references, context);
40
+ const byName = group(symbols, (symbol) => symbol.name);
41
+ const byId = new Map(symbols.map((symbol) => [symbol.id, symbol]));
42
+ const members = new Map();
43
+ for (const reference of references) {
44
+ const member = reference.to ? byId.get(reference.to) : undefined;
45
+ if (reference.relation !== 'defines' || !reference.from || !member)
46
+ continue;
47
+ if (!MEMBERS.has(member.kind))
48
+ continue;
49
+ const owned = members.get(reference.from.id) ?? new Map();
50
+ members.set(reference.from.id, owned);
51
+ const named = owned.get(member.name);
52
+ if (named)
53
+ named.push(member);
54
+ else
55
+ owned.set(member.name, [member]);
56
+ }
57
+ const parents = new Map();
58
+ const cache = new Map();
59
+ const types = new Map();
60
+ const typesByRef = new WeakMap();
61
+ const opened = (reference, wanted) => {
62
+ for (const specifier of reference.link?.opens ?? []) {
63
+ const file = index.fileOf(reference.file, specifier);
64
+ const found = file ? index.find(file, wanted) : undefined;
65
+ if (found)
66
+ return found;
67
+ }
68
+ return undefined;
69
+ };
70
+ const inherited = (owner, wanted, seen = new Set()) => {
71
+ if (seen.has(owner.id) || seen.size > INHERITANCE_DEPTH)
72
+ return undefined;
73
+ seen.add(owner.id);
74
+ const named = members.get(owner.id)?.get(wanted);
75
+ if (named)
76
+ return named.find((symbol) => symbol.kind === 'method') ?? named[0];
77
+ for (const parent of parents.get(owner.id) ?? []) {
78
+ const found = inherited(parent, wanted, seen);
79
+ if (found)
80
+ return found;
81
+ }
82
+ return undefined;
83
+ };
84
+ const memberOf = (reference, source, wanted) => {
85
+ const via = reference.link?.via;
86
+ const owner = source && via?.length === 1 ? index.find(source, via[0] ?? '') : undefined;
87
+ return owner && OWNERS.has(owner.kind) ? inherited(owner, wanted) : undefined;
88
+ };
89
+ const declaredHere = (reference, wanted) => (byName.get(wanted) ?? []).find((symbol) => symbol.file === reference.file && symbol.kind !== 'method');
90
+ const lookupType = (file, type) => {
91
+ const link = type.link ? { link: type.link } : {};
92
+ const resolution = compute({
93
+ file,
94
+ name: type.name,
95
+ relation: 'references',
96
+ line: 0,
97
+ from: null,
98
+ ...link,
99
+ });
100
+ if (resolution?.external)
101
+ return OUTSIDE;
102
+ const target = resolution?.confidence === 'EXTRACTED' ? resolution.target : undefined;
103
+ if (target && OWNERS.has(target.kind))
104
+ return { symbol: target };
105
+ const named = byName.get(lastSegment(type.name)) ?? [];
106
+ return named.some((symbol) => OWNERS.has(symbol.kind)) ? null : OUTSIDE;
107
+ };
108
+ const typeOf = (file, type) => {
109
+ const known = typesByRef.get(type);
110
+ if (known !== undefined)
111
+ return known;
112
+ const value = typeByKey(file, type);
113
+ typesByRef.set(type, value);
114
+ return value;
115
+ };
116
+ const typeByKey = (file, type) => {
117
+ const key = `${file}\0${type.name}\0${type.link?.specifier ?? ''}\0${type.link?.via?.join('.') ?? ''}`;
118
+ if (!types.has(key))
119
+ types.set(key, lookupType(file, type));
120
+ return types.get(key) ?? null;
121
+ };
122
+ const callee = (call) => {
123
+ const resolution = resolve(call);
124
+ const target = resolution?.confidence === 'EXTRACTED' ? resolution.target : undefined;
125
+ return target && CALLABLE.has(target.kind) ? target : undefined;
126
+ };
127
+ const receivers = createReceivers(references, {
128
+ inherited: (owner, wanted) => inherited(owner, wanted),
129
+ parentsOf: (owner) => parents.get(owner.id) ?? [],
130
+ typeOf,
131
+ callee,
132
+ });
133
+ const throughReceiver = (reference) => {
134
+ if (reference.relation !== 'calls' || !reference.receiver)
135
+ return undefined;
136
+ const member = receivers.memberFor(reference, lastSegment(reference.name));
137
+ if (!member)
138
+ return undefined;
139
+ if ('outside' in member)
140
+ return OUTSIDE_CALL;
141
+ return { target: member.target, confidence: 'EXTRACTED', score: SAME_FILE, external: false };
142
+ };
143
+ const compute = (reference) => {
144
+ const typed = throughReceiver(reference);
145
+ if (typed !== undefined)
146
+ return typed;
147
+ const link = reference.link;
148
+ const source = link ? index.fileOf(reference.file, link.specifier) : null;
149
+ const here = (symbol) => context.unit(symbol.file) === context.unit(reference.file);
150
+ const external = !!link &&
151
+ !source &&
152
+ (reference.relation === 'imports'
153
+ ? context.isExternal(reference.file, link.specifier)
154
+ : context.isForeign(reference.file, link.specifier));
155
+ const lookedUp = link ? lastSegment(reference.name) : reference.name;
156
+ const wanted = link?.member ?? lookedUp;
157
+ const home = enterNamespaces(index, source, link?.via);
158
+ const direct = home ? index.find(home, wanted) : undefined;
159
+ const found = direct ??
160
+ opened(reference, wanted) ??
161
+ (home === undefined ? memberOf(reference, source, wanted) : undefined);
162
+ const inOwnUnit = source !== null && source === context.unit(reference.file);
163
+ const bound = inOwnUnit && !link?.via ? (declaredHere(reference, wanted) ?? found) : found;
164
+ const isModule = !bound && home !== undefined && index.enter(home, wanted) !== undefined;
165
+ const named = byName.get(lookedUp) ?? [];
166
+ const candidates = external || isModule ? [] : link ? named.filter((symbol) => !here(symbol)) : named;
167
+ const exact = reference.to
168
+ ? candidates.find((candidate) => candidate.id === reference.to)
169
+ : undefined;
170
+ const local = exact ??
171
+ bound ??
172
+ candidates.find((symbol) => symbol.file === reference.file) ??
173
+ candidates.find(here);
174
+ if (link?.strict && !bound)
175
+ return null;
176
+ const target = local ?? candidates[0];
177
+ if (!target && reference.weak)
178
+ return null;
179
+ const guessed = !exact && !bound && reference.receiver?.kind === 'unknown';
180
+ if (local && !guessed)
181
+ return { target, confidence: 'EXTRACTED', score: SAME_FILE, external };
182
+ if (candidates.length === 1) {
183
+ return { target, confidence: 'INFERRED', score: SINGLE_MATCH, external };
184
+ }
185
+ const ambiguous = candidates.length > 1;
186
+ return {
187
+ target,
188
+ confidence: ambiguous ? 'INFERRED' : 'EXTRACTED',
189
+ score: ambiguous ? AMBIGUOUS_MATCH : SAME_FILE,
190
+ external,
191
+ };
192
+ };
193
+ const resolve = (reference) => {
194
+ if (cache.has(reference))
195
+ return cache.get(reference) ?? null;
196
+ cache.set(reference, null);
197
+ const resolution = compute(reference);
198
+ cache.set(reference, resolution);
199
+ return resolution;
200
+ };
201
+ for (const reference of references) {
202
+ const child = reference.from;
203
+ if (!HERITAGE.has(reference.relation) || !child)
204
+ continue;
205
+ const parent = resolve(reference)?.target;
206
+ if (parent)
207
+ parents.set(child.id, [...(parents.get(child.id) ?? []), parent]);
208
+ }
209
+ return { resolve };
210
+ }
@@ -0,0 +1,11 @@
1
+ import type { CodeSymbol } from '../../types.js';
2
+ import type { Reference } from '../types.js';
3
+ export interface CachedFile {
4
+ hash: string;
5
+ symbols: CodeSymbol[];
6
+ references: Reference[];
7
+ edgesHash: string;
8
+ }
9
+ export declare const cacheHome: () => string;
10
+ export declare function loadCache(project: string): ReadonlyMap<string, CachedFile>;
11
+ export declare function saveCache(project: string, files: ReadonlyMap<string, CachedFile>): void;