@ttsc/graph 0.16.4 → 0.16.6

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 (115) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +24 -53
  3. package/lib/TtscGraphApplication.js +59 -0
  4. package/lib/TtscGraphApplication.js.map +1 -0
  5. package/lib/index.js +31 -108
  6. package/lib/index.js.map +1 -1
  7. package/lib/model/TtscGraphMemory.js +185 -0
  8. package/lib/model/TtscGraphMemory.js.map +1 -0
  9. package/lib/model/loadGraph.js +418 -0
  10. package/lib/model/loadGraph.js.map +1 -0
  11. package/lib/reduce.js +101 -0
  12. package/lib/reduce.js.map +1 -0
  13. package/lib/resolveGraphBinary.js +42 -0
  14. package/lib/resolveGraphBinary.js.map +1 -0
  15. package/lib/server/accessAliases.js +53 -0
  16. package/lib/server/accessAliases.js.map +1 -0
  17. package/lib/server/createServer.js +1726 -0
  18. package/lib/server/createServer.js.map +1 -0
  19. package/lib/server/instructions.js +80 -0
  20. package/lib/server/instructions.js.map +1 -0
  21. package/lib/server/resolveHandle.js +25 -0
  22. package/lib/server/resolveHandle.js.map +1 -0
  23. package/lib/server/runDetails.js +413 -0
  24. package/lib/server/runDetails.js.map +1 -0
  25. package/lib/server/runEntrypoints.js +211 -0
  26. package/lib/server/runEntrypoints.js.map +1 -0
  27. package/lib/server/runLookup.js +234 -0
  28. package/lib/server/runLookup.js.map +1 -0
  29. package/lib/server/runOverview.js +160 -0
  30. package/lib/server/runOverview.js.map +1 -0
  31. package/lib/server/runTrace.js +314 -0
  32. package/lib/server/runTrace.js.map +1 -0
  33. package/lib/server/startServer.js +21 -0
  34. package/lib/server/startServer.js.map +1 -0
  35. package/lib/structures/ITtscGraphApplication.js +3 -0
  36. package/lib/structures/ITtscGraphApplication.js.map +1 -0
  37. package/lib/structures/ITtscGraphDecorator.js +3 -0
  38. package/lib/structures/ITtscGraphDecorator.js.map +1 -0
  39. package/lib/structures/ITtscGraphDetails.js +3 -0
  40. package/lib/structures/ITtscGraphDetails.js.map +1 -0
  41. package/lib/structures/ITtscGraphDiagnostic.js +3 -0
  42. package/lib/structures/ITtscGraphDiagnostic.js.map +1 -0
  43. package/lib/structures/ITtscGraphDump.js +3 -0
  44. package/lib/structures/ITtscGraphDump.js.map +1 -0
  45. package/lib/structures/ITtscGraphEdge.js +3 -0
  46. package/lib/structures/ITtscGraphEdge.js.map +1 -0
  47. package/lib/structures/ITtscGraphEntrypoints.js +3 -0
  48. package/lib/structures/ITtscGraphEntrypoints.js.map +1 -0
  49. package/lib/structures/ITtscGraphEscape.js +3 -0
  50. package/lib/structures/ITtscGraphEscape.js.map +1 -0
  51. package/lib/structures/ITtscGraphEvidence.js +3 -0
  52. package/lib/structures/ITtscGraphEvidence.js.map +1 -0
  53. package/lib/structures/ITtscGraphLookup.js +3 -0
  54. package/lib/structures/ITtscGraphLookup.js.map +1 -0
  55. package/lib/structures/ITtscGraphNode.js +3 -0
  56. package/lib/structures/ITtscGraphNode.js.map +1 -0
  57. package/lib/structures/ITtscGraphOverview.js +3 -0
  58. package/lib/structures/ITtscGraphOverview.js.map +1 -0
  59. package/lib/structures/ITtscGraphTrace.js +3 -0
  60. package/lib/structures/ITtscGraphTrace.js.map +1 -0
  61. package/lib/structures/TtscGraphEdgeKind.js +3 -0
  62. package/lib/structures/TtscGraphEdgeKind.js.map +1 -0
  63. package/lib/structures/TtscGraphNodeKind.js +3 -0
  64. package/lib/structures/TtscGraphNodeKind.js.map +1 -0
  65. package/lib/structures/TtscGraphNodeModifier.js +3 -0
  66. package/lib/structures/TtscGraphNodeModifier.js.map +1 -0
  67. package/lib/structures/index.js +38 -0
  68. package/lib/structures/index.js.map +1 -0
  69. package/lib/view.js +140 -0
  70. package/lib/view.js.map +1 -0
  71. package/lib/viewer/index.html +123 -0
  72. package/lib/viewer/viewer.js +4610 -0
  73. package/package.json +17 -4
  74. package/src/TtscGraphApplication.ts +64 -0
  75. package/src/index.ts +40 -126
  76. package/src/model/TtscGraphMemory.ts +204 -0
  77. package/src/model/loadGraph.ts +85 -0
  78. package/src/reduce.ts +165 -0
  79. package/src/resolveGraphBinary.ts +40 -0
  80. package/src/server/accessAliases.ts +55 -0
  81. package/src/server/createServer.ts +101 -0
  82. package/src/server/instructions.ts +76 -0
  83. package/src/server/resolveHandle.ts +34 -0
  84. package/src/server/runDetails.ts +469 -0
  85. package/src/server/runEntrypoints.ts +256 -0
  86. package/src/server/runLookup.ts +257 -0
  87. package/src/server/runOverview.ts +166 -0
  88. package/src/server/runTrace.ts +359 -0
  89. package/src/server/startServer.ts +25 -0
  90. package/src/structures/ITtscGraphApplication.ts +116 -0
  91. package/src/structures/ITtscGraphDecorator.ts +31 -0
  92. package/src/structures/ITtscGraphDetails.ts +134 -0
  93. package/src/structures/ITtscGraphDiagnostic.ts +34 -0
  94. package/src/structures/ITtscGraphDump.ts +35 -0
  95. package/src/structures/ITtscGraphEdge.ts +24 -0
  96. package/src/structures/ITtscGraphEntrypoints.ts +118 -0
  97. package/src/structures/ITtscGraphEscape.ts +39 -0
  98. package/src/structures/ITtscGraphEvidence.ts +26 -0
  99. package/src/structures/ITtscGraphLookup.ts +61 -0
  100. package/src/structures/ITtscGraphNode.ts +70 -0
  101. package/src/structures/ITtscGraphOverview.ts +87 -0
  102. package/src/structures/ITtscGraphTrace.ts +140 -0
  103. package/src/structures/TtscGraphEdgeKind.ts +23 -0
  104. package/src/structures/TtscGraphNodeKind.ts +26 -0
  105. package/src/structures/TtscGraphNodeModifier.ts +19 -0
  106. package/src/structures/index.ts +22 -0
  107. package/src/view.ts +155 -0
  108. package/src/viewer/index.html +123 -0
  109. package/src/viewer/main.ts +209 -0
  110. package/lib/bin.d.ts +0 -2
  111. package/lib/diagnostics.d.ts +0 -23
  112. package/lib/diagnostics.js +0 -84
  113. package/lib/diagnostics.js.map +0 -1
  114. package/lib/index.d.ts +0 -29
  115. package/src/diagnostics.ts +0 -93
@@ -0,0 +1,256 @@
1
+ import { TtscGraphMemory } from "../model/TtscGraphMemory";
2
+ import { ITtscGraphEdge } from "../structures/ITtscGraphEdge";
3
+ import { ITtscGraphEntrypoints } from "../structures/ITtscGraphEntrypoints";
4
+ import { ITtscGraphNode } from "../structures/ITtscGraphNode";
5
+ import { resolveGraphHandle } from "./resolveHandle";
6
+ import { decoratorsOf, edgeEvidenceOf, signatureOf } from "./runDetails";
7
+ import { runLookup } from "./runLookup";
8
+
9
+ const DEFAULT_LIMIT = 4;
10
+ const MAX_LIMIT = 8;
11
+ const DEFAULT_NEIGHBORS = 0;
12
+ const MAX_NEIGHBORS = 2;
13
+ const MAX_SEEDS = 3;
14
+ const STRUCTURAL_KINDS = new Set<string>(["contains", "exports", "imports"]);
15
+
16
+ /**
17
+ * Build the first source-free entrypoints list for a code question. The result
18
+ * gives the model stable handles, declaration signatures, and direct graph
19
+ * context. It is deliberately not a source reader; details adds selected symbol
20
+ * shape and ranges, not implementation text.
21
+ */
22
+ export function runEntrypoints(
23
+ graph: TtscGraphMemory,
24
+ props: ITtscGraphEntrypoints.IRequest,
25
+ ): ITtscGraphEntrypoints {
26
+ const query = props.query.trim();
27
+ const limit = bound(props.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
28
+ const neighborLimit = bound(
29
+ props.neighbors,
30
+ DEFAULT_NEIGHBORS,
31
+ 0,
32
+ MAX_NEIGHBORS,
33
+ );
34
+
35
+ const lookupResult = runLookup(graph, { type: "lookup", query, limit });
36
+ const hits = lookupResult.hits.map((hit) => ({ ...hit }));
37
+
38
+ const mentions = directMentions(graph, query).map((handle) => {
39
+ const resolved = resolveGraphHandle(graph, handle, 6);
40
+ const mention: ITtscGraphEntrypoints.IMention = { handle };
41
+ if (resolved.node !== undefined)
42
+ mention.node = nodeOf(graph, resolved.node);
43
+ if (resolved.candidates !== undefined) {
44
+ mention.candidates = resolved.candidates.map((node) =>
45
+ nodeOf(graph, node),
46
+ );
47
+ }
48
+ return mention;
49
+ });
50
+
51
+ const seeds: ITtscGraphNode[] = [];
52
+ const seen = new Set<string>();
53
+ const addSeed = (node: ITtscGraphNode | undefined): void => {
54
+ if (node === undefined || seen.has(node.id)) return;
55
+ seen.add(node.id);
56
+ seeds.push(node);
57
+ };
58
+ for (const mention of mentions) {
59
+ if (mention.node !== undefined) addSeed(graph.node(mention.node.id));
60
+ }
61
+ for (const hit of hits) addSeed(graph.node(hit.id));
62
+
63
+ let truncated = seeds.length > MAX_SEEDS;
64
+ const neighborhood: ITtscGraphEntrypoints.INeighborhood[] = [];
65
+ for (const seed of seeds.slice(0, MAX_SEEDS)) {
66
+ const outgoing = refs(graph, graph.outgoing(seed.id), "to", neighborLimit);
67
+ const incoming = refs(
68
+ graph,
69
+ graph.incoming(seed.id),
70
+ "from",
71
+ neighborLimit,
72
+ );
73
+ if (outgoing.truncated || incoming.truncated) truncated = true;
74
+ neighborhood.push({
75
+ ...nodeOf(graph, seed),
76
+ dependsOn: outgoing.items,
77
+ dependedOnBy: incoming.items,
78
+ });
79
+ }
80
+
81
+ return {
82
+ type: "entrypoints",
83
+ query,
84
+ hits,
85
+ mentions,
86
+ neighborhood,
87
+ next: {
88
+ details: seeds.slice(0, MAX_SEEDS).map((node) => node.id),
89
+ traceFrom: seeds.slice(0, MAX_SEEDS).map((node) => node.id),
90
+ },
91
+ ...(truncated ? { truncated: true } : {}),
92
+ };
93
+ }
94
+
95
+ function nodeOf(
96
+ graph: TtscGraphMemory,
97
+ node: ITtscGraphNode,
98
+ ): ITtscGraphEntrypoints.INode {
99
+ const out: ITtscGraphEntrypoints.INode = {
100
+ id: node.id,
101
+ name: node.qualifiedName ?? node.name,
102
+ kind: node.kind,
103
+ file: node.file,
104
+ };
105
+ if (node.evidence?.startLine !== undefined)
106
+ out.line = node.evidence.startLine;
107
+ const signature = signatureOf(graph.project, node);
108
+ if (signature !== undefined) out.signature = signature;
109
+ const decorators = decoratorsOf(node);
110
+ if (decorators !== undefined) out.decorators = decorators;
111
+ return out;
112
+ }
113
+
114
+ function refOf(
115
+ node: ITtscGraphNode,
116
+ edge: ITtscGraphEdge,
117
+ ): ITtscGraphEntrypoints.IReference {
118
+ const out: ITtscGraphEntrypoints.IReference = {
119
+ id: node.id,
120
+ name: node.qualifiedName ?? node.name,
121
+ kind: node.kind,
122
+ file: node.file,
123
+ relation: edge.kind,
124
+ };
125
+ if (node.evidence?.startLine !== undefined)
126
+ out.line = node.evidence.startLine;
127
+ const evidence = edgeEvidenceOf(edge);
128
+ if (evidence !== undefined) out.evidence = evidence;
129
+ return out;
130
+ }
131
+
132
+ function refs(
133
+ graph: TtscGraphMemory,
134
+ edges: readonly ITtscGraphEdge[],
135
+ end: "to" | "from",
136
+ limit: number,
137
+ ): { items: ITtscGraphEntrypoints.IReference[]; truncated: boolean } {
138
+ const ranked: Array<{ ref: ITtscGraphEntrypoints.IReference; rank: number }> =
139
+ [];
140
+ const seen = new Set<string>();
141
+ let available = 0;
142
+ for (const edge of edges) {
143
+ if (STRUCTURAL_KINDS.has(edge.kind)) continue;
144
+ const other = graph.node(end === "to" ? edge.to : edge.from);
145
+ if (other === undefined || other.kind === "file") continue;
146
+ const key = `${edge.kind}:${other.id}`;
147
+ if (seen.has(key)) continue;
148
+ seen.add(key);
149
+ available++;
150
+ const ref = refOf(other, edge);
151
+ ranked.push({ ref, rank: refRank(ref, edge) });
152
+ }
153
+ ranked.sort((a, b) => a.rank - b.rank);
154
+ const items: ITtscGraphEntrypoints.IReference[] = [];
155
+ for (const item of ranked) {
156
+ if (items.length < limit) items.push(item.ref);
157
+ }
158
+ return { items, truncated: available > items.length };
159
+ }
160
+
161
+ function refRank(
162
+ ref: ITtscGraphEntrypoints.IReference,
163
+ edge: ITtscGraphEdge,
164
+ ): number {
165
+ return (
166
+ edgeKindRank(edge.kind) * 100_000 +
167
+ evidenceRank(edge) +
168
+ (ref.file.startsWith("bundled://") ? 20_000 : 0)
169
+ );
170
+ }
171
+
172
+ function evidenceRank(edge: ITtscGraphEdge): number {
173
+ const line = edge.evidence?.startLine ?? 9_999;
174
+ const col = edge.evidence?.startCol ?? 999;
175
+ return line * 100 + col;
176
+ }
177
+
178
+ function edgeKindRank(kind: string): number {
179
+ switch (kind) {
180
+ case "calls":
181
+ return 0;
182
+ case "instantiates":
183
+ return 1;
184
+ case "accesses":
185
+ case "renders":
186
+ return 2;
187
+ case "tests":
188
+ return 3;
189
+ case "overrides":
190
+ case "decorates":
191
+ return 4;
192
+ case "extends":
193
+ case "implements":
194
+ return 5;
195
+ case "type_ref":
196
+ return 6;
197
+ default:
198
+ return 10;
199
+ }
200
+ }
201
+
202
+ function directMentions(graph: TtscGraphMemory, query: string): string[] {
203
+ const handles = new Set<string>();
204
+ for (const token of query.split(/\s+/)) {
205
+ const handle = normalizeNodeIdToken(token);
206
+ if (handle !== undefined && graph.node(handle) !== undefined) {
207
+ handles.add(handle);
208
+ }
209
+ }
210
+ for (const match of query.matchAll(/`([^`]+)`/g)) {
211
+ const raw = match[1] ?? "";
212
+ const id = normalizeNodeIdToken(raw);
213
+ if (id !== undefined && graph.node(id) !== undefined) {
214
+ handles.add(id);
215
+ continue;
216
+ }
217
+ const handle = normalizeHandle(raw);
218
+ if (handle !== undefined) handles.add(handle);
219
+ }
220
+ for (const match of query.matchAll(
221
+ /\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+\b/g,
222
+ )) {
223
+ const handle = normalizeHandle(match[0]);
224
+ if (handle !== undefined) handles.add(handle);
225
+ }
226
+ return [...handles];
227
+ }
228
+
229
+ function normalizeNodeIdToken(raw: string): string | undefined {
230
+ const value = raw
231
+ .trim()
232
+ .replace(/^[`"'([{]+/, "")
233
+ .replace(/[`"',.;:)\]}]+$/, "");
234
+ return /^[^\s#]+#[^\s#]+:(class|interface|type|enum|function|method|variable|property)$/.test(
235
+ value,
236
+ )
237
+ ? value
238
+ : undefined;
239
+ }
240
+
241
+ function normalizeHandle(raw: string): string | undefined {
242
+ const value = raw.trim();
243
+ return /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(value)
244
+ ? value
245
+ : undefined;
246
+ }
247
+
248
+ function bound(
249
+ value: number | undefined,
250
+ fallback: number,
251
+ min: number,
252
+ max: number,
253
+ ): number {
254
+ const n = value === undefined || !Number.isFinite(value) ? fallback : value;
255
+ return Math.max(min, Math.min(max, Math.floor(n)));
256
+ }
@@ -0,0 +1,257 @@
1
+ import { TtscGraphMemory } from "../model/TtscGraphMemory";
2
+ import { ITtscGraphLookup } from "../structures/ITtscGraphLookup";
3
+ import { ITtscGraphNode } from "../structures/ITtscGraphNode";
4
+ import { decoratorsOf, signatureOf } from "./runDetails";
5
+
6
+ // One file should not crowd out the rest of the ranking, so cap hits per file.
7
+ const PER_FILE = 3;
8
+ const DEFAULT_LIMIT = 5;
9
+ const MAX_LIMIT = 6;
10
+
11
+ /**
12
+ * Rank the graph's symbols against a natural query. Scoring blends exact and
13
+ * dotted-name matches, CamelCase/subword coverage, file-path terms, a prefix
14
+ * bonus, and dependency centrality, then dampens external, generated, and test
15
+ * nodes and caps per file so the result is a diverse, relevant shortlist rather
16
+ * than one file's roster.
17
+ */
18
+ export function runLookup(
19
+ graph: TtscGraphMemory,
20
+ props: ITtscGraphLookup.IRequest,
21
+ ): ITtscGraphLookup {
22
+ const terms = subwords(props.query);
23
+ const codeTerms = exactCodeTerms(props.query);
24
+ const requestedKinds = requestedSymbolKinds(props.query);
25
+ const queryLc = props.query.trim().toLowerCase();
26
+ const wantsInternal = wantsInternalSymbol(queryLc, codeTerms);
27
+ if (terms.length === 0)
28
+ return { type: "lookup", hits: [], next: { details: [], traceFrom: [] } };
29
+
30
+ const scored: ITtscGraphLookup.IHit[] = [];
31
+ for (const node of graph.nodes) {
32
+ if (node.kind === "file") continue;
33
+ const score = scoreNode(
34
+ graph,
35
+ node,
36
+ queryLc,
37
+ terms,
38
+ codeTerms,
39
+ requestedKinds,
40
+ wantsInternal,
41
+ );
42
+ if (score <= 0) continue;
43
+ const hit: ITtscGraphLookup.IHit = {
44
+ id: node.id,
45
+ name: node.qualifiedName ?? node.name,
46
+ kind: node.kind,
47
+ file: node.file,
48
+ line: node.evidence?.startLine,
49
+ score: Math.round(score),
50
+ };
51
+ const decorators = decoratorsOf(node);
52
+ if (decorators !== undefined) hit.decorators = decorators;
53
+ scored.push(hit);
54
+ }
55
+
56
+ scored.sort((a, b) => b.score - a.score);
57
+
58
+ // Diversity: keep at most PER_FILE hits per file while filling up to the limit.
59
+ const limit = bound(props.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
60
+ const perFile = new Map<string, number>();
61
+ const hits: ITtscGraphLookup.IHit[] = [];
62
+ for (const hit of scored) {
63
+ const used = perFile.get(hit.file) ?? 0;
64
+ if (used >= PER_FILE) continue;
65
+ perFile.set(hit.file, used + 1);
66
+ hits.push(hit);
67
+ if (hits.length >= limit) break;
68
+ }
69
+
70
+ // Attach each kept hit's signature only for the shortlist, so the model can
71
+ // often answer from lookup alone without a details call.
72
+ for (const hit of hits) {
73
+ const node = graph.node(hit.id);
74
+ if (node === undefined) continue;
75
+ const sig = signatureOf(graph.project, node);
76
+ if (sig !== undefined) hit.signature = sig;
77
+ }
78
+ return {
79
+ type: "lookup",
80
+ hits,
81
+ next: {
82
+ details: hits.map((hit) => hit.id),
83
+ traceFrom: hits.map((hit) => hit.id),
84
+ },
85
+ };
86
+ }
87
+
88
+ /** Score one node against the query; 0 means no match. */
89
+ function scoreNode(
90
+ graph: TtscGraphMemory,
91
+ node: ITtscGraphNode,
92
+ queryLc: string,
93
+ terms: string[],
94
+ codeTerms: string[],
95
+ requestedKinds: Set<string>,
96
+ wantsInternal: boolean,
97
+ ): number {
98
+ const name = node.name.toLowerCase();
99
+ const qualified = (node.qualifiedName ?? node.name).toLowerCase();
100
+ const nameSubs = subwords(node.name);
101
+ const qualifiedSubs = subwords(node.qualifiedName ?? node.name);
102
+ const pathSubs = subwords(node.file);
103
+
104
+ let score = 0;
105
+ if (queryLc === name || queryLc === qualified) {
106
+ score += 100;
107
+ } else if (qualified.includes(".") && queryLc.includes(qualified)) {
108
+ score += 85;
109
+ } else if (queryLc.includes(".") && qualified.includes(queryLc)) {
110
+ score += 60;
111
+ }
112
+
113
+ for (const codeTerm of codeTerms) {
114
+ if (name === codeTerm || qualified === codeTerm) {
115
+ score += 110;
116
+ } else if (qualified.endsWith(`.${codeTerm}`)) {
117
+ score += 95;
118
+ } else if (codeTerm.includes(".") && qualified.endsWith(codeTerm)) {
119
+ score += 85;
120
+ }
121
+ }
122
+
123
+ if (requestedKinds.has(node.kind)) score += 16;
124
+
125
+ let covered = 0;
126
+ for (const term of terms) {
127
+ if (nameSubs.includes(term)) {
128
+ score += 12;
129
+ covered++;
130
+ } else if (qualifiedSubs.includes(term)) {
131
+ score += 8;
132
+ covered++;
133
+ } else if (name.includes(term)) {
134
+ score += 5;
135
+ covered++;
136
+ } else if (pathSubs.includes(term)) {
137
+ score += 3;
138
+ }
139
+ }
140
+ // Every query term landed somewhere in the name: a strong whole-query match.
141
+ if (covered === terms.length) score += 10;
142
+ if (name.startsWith(terms[0]!)) score += 4;
143
+
144
+ if (score <= 0) return 0;
145
+
146
+ // Centrality: a symbol the codebase leans on is a likelier target.
147
+ const fan = degree(graph, node.id);
148
+ score += Math.min(8, Math.log2(1 + fan) * 2);
149
+
150
+ // Dampen what is rarely the intended target.
151
+ if (node.external) score *= 0.5;
152
+ if (node.ignored) score *= 0.3;
153
+ if (isTestFile(node.file)) score *= 0.7;
154
+ if (!wantsInternal && isInternalish(node)) score *= 0.82;
155
+ return score;
156
+ }
157
+
158
+ function wantsInternalSymbol(queryLc: string, codeTerms: string[]): boolean {
159
+ return (
160
+ /\b(internal|private|implementation|impl)\b/.test(queryLc) ||
161
+ codeTerms.some((term) => term.startsWith("_") || term.includes("internal"))
162
+ );
163
+ }
164
+
165
+ function isInternalish(node: ITtscGraphNode): boolean {
166
+ const name = node.qualifiedName ?? node.name;
167
+ return (
168
+ name.startsWith("_") ||
169
+ name.includes("._") ||
170
+ subwords(name).some((word) => word === "internal" || word === "internals")
171
+ );
172
+ }
173
+
174
+ function exactCodeTerms(query: string): string[] {
175
+ const out = new Set<string>();
176
+ for (const match of query.matchAll(/`([^`]+)`/g)) {
177
+ const normalized = normalizeCodeTerm(match[1] ?? "");
178
+ if (normalized !== undefined) out.add(normalized);
179
+ }
180
+ for (const match of query.matchAll(
181
+ /\b([A-Za-z_$][\w$]*)\s+(method|function|class|interface|type|variable)\b/gi,
182
+ )) {
183
+ const normalized = normalizeCodeTerm(match[1] ?? "");
184
+ if (normalized !== undefined) out.add(normalized);
185
+ }
186
+ for (const match of query.matchAll(
187
+ /\b[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+\b/g,
188
+ )) {
189
+ const normalized = normalizeCodeTerm(match[0]);
190
+ if (normalized !== undefined) out.add(normalized);
191
+ }
192
+ return [...out];
193
+ }
194
+
195
+ function requestedSymbolKinds(query: string): Set<string> {
196
+ const kinds = new Set<string>();
197
+ const lc = query.toLowerCase();
198
+ if (/\bmethods?\b/.test(lc)) kinds.add("method");
199
+ if (/\bfunctions?\b/.test(lc)) {
200
+ kinds.add("function");
201
+ kinds.add("method");
202
+ kinds.add("variable");
203
+ }
204
+ if (/\bclasses?\b/.test(lc)) kinds.add("class");
205
+ if (/\binterfaces?\b/.test(lc)) kinds.add("interface");
206
+ if (/\btypes?\b/.test(lc)) kinds.add("type");
207
+ if (/\bvariables?\b|\bconst\b|\blet\b/.test(lc)) kinds.add("variable");
208
+ return kinds;
209
+ }
210
+
211
+ function normalizeCodeTerm(raw: string): string | undefined {
212
+ const value = raw.trim().toLowerCase();
213
+ return /^[a-z_$][\w$]*(?:\.[a-z_$][\w$]*)*$/.test(value) ? value : undefined;
214
+ }
215
+
216
+ /** Non-structural in+out degree (code dependency, not nesting). */
217
+ function degree(graph: TtscGraphMemory, id: string): number {
218
+ let n = 0;
219
+ for (const edge of graph.outgoing(id)) if (!isStructural(edge.kind)) n++;
220
+ for (const edge of graph.incoming(id)) if (!isStructural(edge.kind)) n++;
221
+ return n;
222
+ }
223
+
224
+ function isStructural(kind: string): boolean {
225
+ return kind === "contains" || kind === "exports" || kind === "imports";
226
+ }
227
+
228
+ function isTestFile(file: string): boolean {
229
+ return (
230
+ /(^|\/)(test|tests|__tests__|spec)\//.test(file) ||
231
+ /\.(test|spec)\.[cm]?tsx?$/.test(file)
232
+ );
233
+ }
234
+
235
+ function bound(
236
+ value: number | undefined,
237
+ fallback: number,
238
+ min: number,
239
+ max: number,
240
+ ): number {
241
+ const n = value === undefined || !Number.isFinite(value) ? fallback : value;
242
+ return Math.max(min, Math.min(max, Math.floor(n)));
243
+ }
244
+
245
+ /**
246
+ * Split an identifier or phrase into lowercase subword tokens: CamelCase,
247
+ * snake, dotted, and space boundaries all break, so `getHTTPResponse`,
248
+ * `find_by_id`, and `OrderService.create` tokenize the way a query would.
249
+ */
250
+ function subwords(text: string): string[] {
251
+ return text
252
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
253
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
254
+ .split(/[^a-zA-Z0-9]+/)
255
+ .filter((w) => w.length > 0)
256
+ .map((w) => w.toLowerCase());
257
+ }
@@ -0,0 +1,166 @@
1
+ import { TtscGraphMemory } from "../model/TtscGraphMemory";
2
+ import { ITtscGraphNode } from "../structures/ITtscGraphNode";
3
+ import { ITtscGraphOverview } from "../structures/ITtscGraphOverview";
4
+
5
+ /** Edges that express nesting/packaging, not code dependency. */
6
+ const STRUCTURAL_KINDS = new Set<string>(["contains", "exports", "imports"]);
7
+
8
+ /**
9
+ * Project a compact, source-read-free architecture map: counts by kind, folder
10
+ * layering with export density, the highest-dependency symbols (ranked by real
11
+ * fan-in/out, excluding structural edges so nesting does not masquerade as
12
+ * dependency), and the export surface by file. Output is bounded so a model
13
+ * reads structure cheaply.
14
+ */
15
+ export function runOverview(
16
+ graph: TtscGraphMemory,
17
+ props: ITtscGraphOverview.IRequest,
18
+ ): ITtscGraphOverview {
19
+ const aspect = props.aspect ?? "all";
20
+ const want = (a: ITtscGraphOverview.IRequest["aspect"]): boolean =>
21
+ aspect === "all" || aspect === a;
22
+
23
+ const byKind: Record<string, number> = {};
24
+ let files = 0;
25
+ for (const node of graph.nodes) {
26
+ byKind[node.kind] = (byKind[node.kind] ?? 0) + 1;
27
+ if (node.kind === "file") files++;
28
+ }
29
+
30
+ const result: ITtscGraphOverview = {
31
+ type: "overview",
32
+ project: graph.project,
33
+ counts: {
34
+ files,
35
+ nodes: graph.nodes.length,
36
+ edges: graph.edges.length,
37
+ byKind,
38
+ },
39
+ };
40
+ if (want("layers")) result.layers = layers(graph);
41
+ if (want("hotspots")) result.hotspots = hotspots(graph);
42
+ if (want("publicApi")) result.publicApi = publicApi(graph);
43
+ return result;
44
+ }
45
+
46
+ /** Folder-level layering: how source and its export surface spread by directory. */
47
+ function layers(graph: TtscGraphMemory): ITtscGraphOverview.ILayer[] {
48
+ const byDir = new Map<string, { files: Set<string>; exported: number }>();
49
+ for (const node of graph.nodes) {
50
+ if (node.external || node.kind === "file") continue;
51
+ const dir = dirname(node.file);
52
+ let entry = byDir.get(dir);
53
+ if (!entry) {
54
+ entry = { files: new Set(), exported: 0 };
55
+ byDir.set(dir, entry);
56
+ }
57
+ entry.files.add(node.file);
58
+ if (node.exported) entry.exported++;
59
+ }
60
+ return [...byDir.entries()]
61
+ .map(([dir, entry]) => ({
62
+ dir,
63
+ files: entry.files.size,
64
+ exported: entry.exported,
65
+ }))
66
+ .sort((a, b) => b.files - a.files)
67
+ .slice(0, 10);
68
+ }
69
+
70
+ /**
71
+ * The symbols at the center of the dependency graph, ranked by real fan-in and
72
+ * fan-out. Structural `contains`/`exports`/`imports` edges are excluded so the
73
+ * ranking reflects code dependency, not nesting.
74
+ */
75
+ function hotspots(graph: TtscGraphMemory): ITtscGraphOverview.IHotspot[] {
76
+ const real = (id: string, side: "in" | "out"): number => {
77
+ const edges = side === "in" ? graph.incoming(id) : graph.outgoing(id);
78
+ let n = 0;
79
+ for (const edge of edges) if (!STRUCTURAL_KINDS.has(edge.kind)) n++;
80
+ return n;
81
+ };
82
+ return graph.nodes
83
+ .filter((node) => !node.external && node.kind !== "file")
84
+ .map((node) => ({
85
+ ...nodeOf(node),
86
+ fanIn: real(node.id, "in"),
87
+ fanOut: real(node.id, "out"),
88
+ }))
89
+ .filter((h) => h.fanIn + h.fanOut > 0)
90
+ .sort((a, b) => b.fanIn + b.fanOut - (a.fanIn + a.fanOut))
91
+ .slice(0, 10);
92
+ }
93
+
94
+ /** Declaration kinds that make up a meaningful public API surface. */
95
+ const API_KINDS = new Set<string>([
96
+ "class",
97
+ "interface",
98
+ "function",
99
+ "type",
100
+ "enum",
101
+ ]);
102
+
103
+ /**
104
+ * The exported API surface: the exported symbols a consumer of the project
105
+ * would use, ranked by how depended-on each is (real fan-in/out, structural
106
+ * edges excluded). Ranking by dependency rather than by which file declares the
107
+ * most exports surfaces the load-bearing types (a DataSource, a
108
+ * SelectQueryBuilder) instead of whichever file bundles the most type aliases;
109
+ * test, typings, and generated files are dropped so they cannot crowd the real
110
+ * surface out.
111
+ */
112
+ function publicApi(graph: TtscGraphMemory): ITtscGraphOverview.IPublicApi[] {
113
+ const degree = (id: string): number => {
114
+ let n = 0;
115
+ for (const edge of graph.outgoing(id))
116
+ if (!STRUCTURAL_KINDS.has(edge.kind)) n++;
117
+ for (const edge of graph.incoming(id))
118
+ if (!STRUCTURAL_KINDS.has(edge.kind)) n++;
119
+ return n;
120
+ };
121
+ return graph
122
+ .exported()
123
+ .filter((node) => API_KINDS.has(node.kind) && !isNoiseFile(node.file))
124
+ .map((node) => ({
125
+ node: nodeOf(node),
126
+ degree: degree(node.id),
127
+ }))
128
+ .sort((a, b) => b.degree - a.degree)
129
+ .slice(0, 15)
130
+ .map((ranked) => ranked.node);
131
+ }
132
+
133
+ /**
134
+ * A file whose exports are noise for an architecture overview: a test, a
135
+ * dependency's bundled `.d.ts`/typings, or generated output. The conventions
136
+ * are universal (a `test`/`spec` path, a `typings` file), so excluding them is
137
+ * not framework-specific; it keeps the API surface to authored, used code.
138
+ */
139
+ function isNoiseFile(file: string): boolean {
140
+ return (
141
+ /(^|\/)(test|tests|__tests__|spec|sample|samples)\//.test(file) ||
142
+ /\.(test|spec)\.[cm]?tsx?$/.test(file) ||
143
+ /(^|\/|\.)typings\.[cm]?ts$/.test(file) ||
144
+ /\.d\.[cm]?ts$/.test(file)
145
+ );
146
+ }
147
+
148
+ /** The parent directory of a project-relative path (`.` at the root). */
149
+ function dirname(file: string): string {
150
+ const slash = file.lastIndexOf("/");
151
+ return slash >= 0 ? file.slice(0, slash) : ".";
152
+ }
153
+
154
+ /** Stable symbol coordinate shared by overview facets. */
155
+ function nodeOf(node: ITtscGraphNode): ITtscGraphOverview.INode {
156
+ const out: ITtscGraphOverview.INode = {
157
+ id: node.id,
158
+ name: node.qualifiedName ?? node.name,
159
+ kind: node.kind,
160
+ file: node.file,
161
+ };
162
+ if (node.evidence?.startLine !== undefined) {
163
+ out.line = node.evidence.startLine;
164
+ }
165
+ return out;
166
+ }