@dimassetoid/septum-mcp 0.0.0-stage → 0.3.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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,647 @@
1
+ import { symbolReference, matchesSymbolName, matchesSymbolReference } from "../../resolver/symbol-reference.ts";
2
+ import * as path from "node:path";
3
+ import type { Database } from "bun:sqlite";
4
+ import type {
5
+ DomainRecord,
6
+ ExtractedSymbol,
7
+ FileRecord,
8
+ GetSymbolDetailsResponse,
9
+ FileConnectionsSummary,
10
+ ResolvedOutboundCall,
11
+ SymbolComplexitySmell,
12
+ SymbolKind,
13
+ SymbolRecord,
14
+ SymbolCandidate,
15
+ SymbolSelectionOptions,
16
+ } from "../../../types/index.ts";
17
+ import { DependencyRepository } from "./dependency.repository.ts";
18
+ import { probeSourcePath, readSourceFile } from "../../resources/source-files.ts";
19
+ import { assertPathContained } from "../../resolver/path-resolver.ts";
20
+
21
+ const SQL_KEYWORD_BLACKLIST = new Set([
22
+ "VALUES",
23
+ "WHERE",
24
+ "SELECT",
25
+ "FROM",
26
+ "JOIN",
27
+ "LIKE",
28
+ "INSERT",
29
+ "UPDATE",
30
+ "DELETE",
31
+ ]);
32
+
33
+ function stripCommentsAndStrings(source: string): string {
34
+ return source
35
+ .replace(/\/\*[\s\S]*?\*\//g, " ")
36
+ .replace(/\/\/.*$/gm, " ")
37
+ .replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, '""');
38
+ }
39
+
40
+ export class SymbolRepository {
41
+ constructor(private db: Database) {}
42
+
43
+ public replaceFileSymbols(fileId: number, symbols: ExtractedSymbol[]): void {
44
+ this.db.query("DELETE FROM symbols WHERE file_id = ?").run(fileId);
45
+ if (symbols.length === 0) return;
46
+
47
+ const stmt = this.db.query(
48
+ `INSERT INTO symbols (file_id, name, kind, signature, visibility, line_start, line_end, line_count, nesting_depth)
49
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
50
+ );
51
+
52
+ for (const sym of symbols) {
53
+ const lineCount = sym.line_count ?? Math.max(1, sym.line_end - sym.line_start + 1);
54
+ const nestingDepth = sym.nesting_depth ?? 1;
55
+ stmt.run(
56
+ fileId,
57
+ sym.name,
58
+ sym.kind,
59
+ sym.signature,
60
+ sym.visibility,
61
+ sym.line_start,
62
+ sym.line_end,
63
+ lineCount,
64
+ nestingDepth
65
+ );
66
+ }
67
+ }
68
+
69
+ public getSymbolsByFileId(fileId: number): SymbolRecord[] {
70
+ return this.db
71
+ .query<SymbolRecord, [number]>(
72
+ "SELECT * FROM symbols WHERE file_id = ? ORDER BY line_start ASC"
73
+ )
74
+ .all(fileId);
75
+ }
76
+
77
+ public findSymbolsByName(
78
+ name: string,
79
+ options: SymbolSelectionOptions = {}
80
+ ): SymbolCandidate[] {
81
+ const target = name.trim().replace(/\(\)$/, "");
82
+ const leaf = target.split(/::|->|[.#\\]/).pop() ?? target;
83
+ let query = `SELECT s.*, f.path AS file_path, f.content_hash AS indexed_content_hash, d.name AS domain_name
84
+ FROM symbols s JOIN files f ON s.file_id = f.id JOIN domains d ON f.domain_id = d.id
85
+ WHERE (s.name = ? OR substr(s.name, -length(?)) = ?)`;
86
+ const params: string[] = [target, leaf, leaf];
87
+ if (options.domain) { query += " AND d.name = ?"; params.push(options.domain); }
88
+ const filePath = options.filePath ?? options.reference?.file_path;
89
+ if (filePath) { query += " AND f.path = ?"; params.push(filePath); }
90
+ query += " ORDER BY f.path, s.line_start, s.line_end, s.signature, s.id";
91
+ return this.db.query<SymbolCandidate, string[]>(query).all(...params)
92
+ .filter(row => matchesSymbolName(row, target))
93
+ .map(row => ({ ...row, symbol_ref: symbolReference(row) }))
94
+ .filter(row => !options.reference || matchesSymbolReference(row.symbol_ref, options.reference));
95
+ }
96
+
97
+ public findContainers(
98
+ containerName: string
99
+ ): Array<{ file: FileRecord; symbol?: SymbolRecord }> {
100
+ const symbolQuery = `
101
+ SELECT s.*, f.path AS file_path, f.id AS f_id, f.domain_id AS f_domain_id,
102
+ f.archetype AS f_archetype, f.content_hash AS f_content_hash,
103
+ f.line_count AS f_line_count, f.mtime_ms AS f_mtime_ms,
104
+ f.size_bytes AS f_size_bytes, f.last_scanned_at AS f_last_scanned_at
105
+ FROM symbols s
106
+ JOIN files f ON s.file_id = f.id
107
+ WHERE (s.name = ? OR s.name LIKE ? OR s.name LIKE ?)
108
+ AND s.kind IN ('class', 'interface', 'trait', 'enum')
109
+ LIMIT 10
110
+ `;
111
+ const rows = this.db
112
+ .query<any, [string, string, string]>(symbolQuery)
113
+ .all(containerName, `%\\${containerName}`, `%/${containerName}`);
114
+
115
+ if (rows.length > 0) {
116
+ return rows.map((r) => ({
117
+ file: {
118
+ id: r.f_id,
119
+ domain_id: r.f_domain_id,
120
+ path: r.file_path,
121
+ archetype: r.f_archetype,
122
+ content_hash: r.f_content_hash,
123
+ line_count: r.f_line_count,
124
+ mtime_ms: r.f_mtime_ms,
125
+ size_bytes: r.f_size_bytes,
126
+ last_scanned_at: r.f_last_scanned_at,
127
+ },
128
+ symbol: {
129
+ id: r.id,
130
+ file_id: r.file_id,
131
+ name: r.name,
132
+ kind: r.kind,
133
+ signature: r.signature,
134
+ visibility: r.visibility,
135
+ line_start: r.line_start,
136
+ line_end: r.line_end,
137
+ line_count: r.line_count ?? (r.line_end - r.line_start + 1),
138
+ nesting_depth: r.nesting_depth ?? 1,
139
+ },
140
+ }));
141
+ }
142
+
143
+ const fileQuery = `
144
+ SELECT * FROM files
145
+ WHERE path LIKE ? OR path LIKE ?
146
+ LIMIT 10
147
+ `;
148
+ const files = this.db
149
+ .query<FileRecord, [string, string]>(fileQuery)
150
+ .all(`%/${containerName}.%`, `%\\${containerName}.%`);
151
+
152
+ return files.map((file) => ({ file }));
153
+ }
154
+
155
+ public getAllSymbolsWithFiles(): Array<SymbolRecord & { file_path: string }> {
156
+ const query = `
157
+ SELECT s.*, f.path AS file_path
158
+ FROM symbols s
159
+ JOIN files f ON s.file_id = f.id
160
+ WHERE s.kind IN ('class', 'interface', 'trait', 'struct', 'enum', 'type', 'method', 'function', 'constant')
161
+ ORDER BY s.line_start ASC, s.name ASC
162
+ `;
163
+ return this.db.query<SymbolRecord & { file_path: string }, []>(query).all();
164
+ }
165
+
166
+ public findSymbolWithDomain(symbolName: string): {
167
+ symbol_name: string;
168
+ kind: string;
169
+ file_path: string;
170
+ domain_name: string;
171
+ } | null {
172
+ const query = `
173
+ SELECT
174
+ s.name AS symbol_name,
175
+ s.kind,
176
+ f.path AS file_path,
177
+ d.name AS domain_name
178
+ FROM symbols s
179
+ JOIN files f ON s.file_id = f.id
180
+ JOIN domains d ON f.domain_id = d.id
181
+ WHERE s.name = ?
182
+ LIMIT 1
183
+ `;
184
+ return this.db.query<any, [string]>(query).get(symbolName) ?? null;
185
+ }
186
+
187
+ public findSymbolWithMembers(symbolName: string): {
188
+ symbol_name: string;
189
+ kind: string;
190
+ signature: string;
191
+ file_path: string;
192
+ domain_name: string;
193
+ methods: string[];
194
+ properties: string[];
195
+ } | null {
196
+ const rootQuery = `
197
+ SELECT
198
+ s.id AS symbol_id,
199
+ s.file_id,
200
+ s.name AS symbol_name,
201
+ s.kind,
202
+ s.signature,
203
+ f.path AS file_path,
204
+ d.name AS domain_name
205
+ FROM symbols s
206
+ JOIN files f ON s.file_id = f.id
207
+ JOIN domains d ON f.domain_id = d.id
208
+ WHERE s.name = ?
209
+ LIMIT 1
210
+ `;
211
+ const root = this.db.query<any, [string]>(rootQuery).get(symbolName);
212
+ if (!root) return null;
213
+
214
+ const membersQuery = `
215
+ SELECT name, kind, signature
216
+ FROM symbols
217
+ WHERE file_id = ? AND name LIKE ?
218
+ ORDER BY line_start ASC
219
+ `;
220
+ const members = this.db
221
+ .query<any, [number, string]>(membersQuery)
222
+ .all(root.file_id, `${symbolName}::%`);
223
+
224
+ const methods: string[] = [];
225
+ const properties: string[] = [];
226
+
227
+ for (const m of members) {
228
+ if (m.kind === "method") {
229
+ methods.push(m.signature);
230
+ } else if (m.kind === "property") {
231
+ properties.push(m.signature);
232
+ }
233
+ }
234
+
235
+ return {
236
+ symbol_name: root.symbol_name,
237
+ kind: root.kind,
238
+ signature: root.signature,
239
+ file_path: root.file_path,
240
+ domain_name: root.domain_name,
241
+ methods,
242
+ properties,
243
+ };
244
+ }
245
+
246
+ public getFileWithDomain(filePath: string): {
247
+ file_id: number;
248
+ file_path: string;
249
+ domain_name: string;
250
+ } | null {
251
+ const query = `
252
+ SELECT
253
+ f.id AS file_id,
254
+ f.path AS file_path,
255
+ d.name AS domain_name
256
+ FROM files f
257
+ JOIN domains d ON f.domain_id = d.id
258
+ WHERE f.path = ?
259
+ LIMIT 1
260
+ `;
261
+ return this.db.query<any, [string]>(query).get(filePath) ?? null;
262
+ }
263
+
264
+ public getSymbolDetails(
265
+ symbolQuery: string,
266
+ options: SymbolSelectionOptions & { includeDependencies?: boolean; workspaceRoot?: string } = {}
267
+ ): GetSymbolDetailsResponse | null {
268
+ const trimmed = symbolQuery.trim();
269
+ if (!trimmed) return null;
270
+
271
+ const candidates = this.findSymbolsByName(trimmed, options);
272
+ if (candidates.length !== 1) return null;
273
+ const row = candidates[0]!;
274
+
275
+ // 1. Sibling methods
276
+ const isRust = /\.rs$/i.test(row.file_path);
277
+ const containerName = row.symbol_ref.container ?? "";
278
+ const owner = ["class", "interface", "trait", "struct", "enum"].includes(row.kind) ? row.name
279
+ : row.kind === "method" ? containerName : "";
280
+ let siblingMethods: string[] = owner ? this.getSymbolsByFileId(row.file_id)
281
+ .filter(s => s.kind === "method" && s.id !== row.id)
282
+ .filter(s => symbolReference({ ...s, file_path: row.file_path, indexed_content_hash: row.indexed_content_hash }).container === owner)
283
+ .map(s => s.name.split(/::|[.#]/).pop()!) : [];
284
+
285
+ siblingMethods = Array.from(new Set(siblingMethods)).filter(
286
+ (m) => !SQL_KEYWORD_BLACKLIST.has(m.toUpperCase())
287
+ );
288
+
289
+ // 2. Dependencies Injected (from signature type-hints and constructor)
290
+ const dependenciesInjected = new Set<string>();
291
+ const outboundCalls = new Set<string>();
292
+ const resolvedOutboundCalls: ResolvedOutboundCall[] = [];
293
+ let connectedFiles: FileConnectionsSummary = { imports_from: [], imported_by_count: 0 };
294
+
295
+ const shouldIncludeDeps = options.includeDependencies !== false;
296
+
297
+ if (shouldIncludeDeps) {
298
+ const varTypes = new Map<string, string>();
299
+ const primitiveTypes = new Set([
300
+ "int", "string", "str", "bool", "boolean", "float", "double", "decimal",
301
+ "number", "bigint", "symbol", "array", "list", "dict", "tuple", "set",
302
+ "iterable", "callable", "function", "void", "mixed", "object", "null",
303
+ "undefined", "never", "any", "unknown", "true", "false", "record",
304
+ "partial", "omit", "pick", "readonly", "required", "promise", "map",
305
+ "weakmap", "weakset", "date", "error", "regexp", "buffer", "abortsignal",
306
+ "uint8array", "self", "cls",
307
+ ]);
308
+ const modifierWords = new Set([
309
+ "public", "private", "protected", "readonly", "final", "var", "val",
310
+ "mut", "ref", "in", "out", "params", "async",
311
+ ]);
312
+
313
+ const splitTopLevel = (input: string, delimiter: string): string[] => {
314
+ const result: string[] = [];
315
+ let current = "";
316
+ let depth = 0;
317
+ for (let i = 0; i < input.length; i++) {
318
+ const ch = input[i];
319
+ if (ch === "(" || ch === "<" || ch === "[" || ch === "{") depth++;
320
+ else if (ch === ")" || ch === ">" || ch === "]" || ch === "}") depth = Math.max(0, depth - 1);
321
+ if (depth === 0 && input.startsWith(delimiter, i)) {
322
+ result.push(current);
323
+ current = "";
324
+ i += delimiter.length - 1;
325
+ } else {
326
+ current += ch;
327
+ }
328
+ }
329
+ if (current.trim()) result.push(current);
330
+ return result;
331
+ };
332
+
333
+ const registerTypeToken = (rawToken: string, paramName?: string) => {
334
+ let token = rawToken.trim()
335
+ .replace(/^\?+/, "")
336
+ .replace(/^&+/, "")
337
+ .replace(/^\*+/, "")
338
+ .replace(/\[\]$/, "")
339
+ .replace(/<.*>$/s, "")
340
+ .replace(/^[\\$]/, "")
341
+ .trim();
342
+ if (token.includes("\\")) token = token.split("\\").pop() || token;
343
+ if (token.includes(".")) token = token.split(".").pop() || token;
344
+ if (!token || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(token)) return;
345
+ if (primitiveTypes.has(token.toLowerCase()) || modifierWords.has(token.toLowerCase())) return;
346
+ dependenciesInjected.add(token);
347
+ if (paramName && /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(paramName) && !varTypes.has(paramName)) {
348
+ varTypes.set(paramName, token);
349
+ }
350
+ };
351
+
352
+ const extractTypeHints = (sig: string) => {
353
+ const openIdx = sig.indexOf("(");
354
+ if (openIdx === -1) return;
355
+ let closeIdx = -1;
356
+ let depth = 0;
357
+ for (let i = openIdx; i < sig.length; i++) {
358
+ if (sig[i] === "(") depth++;
359
+ else if (sig[i] === ")") {
360
+ depth--;
361
+ if (depth === 0) {
362
+ closeIdx = i;
363
+ break;
364
+ }
365
+ }
366
+ }
367
+ if (closeIdx <= openIdx + 1) return;
368
+ const paramBlock = sig.slice(openIdx + 1, closeIdx);
369
+ const params = splitTopLevel(paramBlock, ",");
370
+ const isGo = /\.go$/i.test(row.file_path);
371
+
372
+ for (const rawParam of params) {
373
+ let p = rawParam.trim();
374
+ if (!p) continue;
375
+ // Strip top-level default value `= ...` (ignoring `=>` in arrow types)
376
+ let eqDepth = 0;
377
+ for (let i = 0; i < p.length; i++) {
378
+ const ch = p[i];
379
+ if (ch === "(" || ch === "<" || ch === "[" || ch === "{") eqDepth++;
380
+ else if (ch === ")" || ch === ">" || ch === "]" || ch === "}") eqDepth = Math.max(0, eqDepth - 1);
381
+ else if (eqDepth === 0 && ch === "=" && p[i + 1] !== ">" && p[i - 1] !== "!" && p[i - 1] !== "=" && p[i - 1] !== "<" && p[i - 1] !== ">") {
382
+ p = p.slice(0, i).trim();
383
+ break;
384
+ }
385
+ }
386
+ // Check for top-level colon `param: Type` (TypeScript, Python, etc.)
387
+ let colonIdx = -1;
388
+ let colDepth = 0;
389
+ for (let i = 0; i < p.length; i++) {
390
+ const ch = p[i];
391
+ if (ch === "(" || ch === "<" || ch === "[" || ch === "{") colDepth++;
392
+ else if (ch === ")" || ch === ">" || ch === "]" || ch === "}") colDepth = Math.max(0, colDepth - 1);
393
+ else if (colDepth === 0 && ch === ":" && p[i + 1] !== ":" && p[i - 1] !== ":") {
394
+ colonIdx = i;
395
+ break;
396
+ }
397
+ }
398
+
399
+ if (colonIdx !== -1) {
400
+ const leftTokens = p.slice(0, colonIdx).trim().replace(/^\.{3}/, "").split(/\s+/)
401
+ .filter(t => !modifierWords.has(t.toLowerCase()));
402
+ const rawParamName = (leftTokens.pop() || "").replace(/\?$/, "").replace(/^\$/, "");
403
+ const typeExpr = p.slice(colonIdx + 1).trim();
404
+ if (typeExpr.startsWith("{") || typeExpr.startsWith("(") || typeExpr.startsWith("[")) continue;
405
+ // Support generic wrappers like Promise<Type> or Array<Type> or union TypeA | TypeB
406
+ for (const branch of splitTopLevel(typeExpr, "|")) {
407
+ const trimmedBranch = branch.trim();
408
+ const wrapperMatch = /^(?:Promise|Array|ReadonlyArray|Partial|Required|Readonly)\s*<(.+)>$/s.exec(trimmedBranch);
409
+ registerTypeToken(wrapperMatch ? wrapperMatch[1] : trimmedBranch, rawParamName);
410
+ }
411
+ } else {
412
+ const parts = p.replace(/^\.{3}/, "").split(/\s+/).filter(t => !modifierWords.has(t.toLowerCase()));
413
+ if (parts.length >= 2) {
414
+ if (isGo) {
415
+ const rawParamName = parts[0];
416
+ const rawType = parts[parts.length - 1];
417
+ registerTypeToken(rawType, rawParamName);
418
+ } else {
419
+ const rawType = parts[0];
420
+ const rawParamName = parts[1].replace(/^[$&]+/, "");
421
+ registerTypeToken(rawType, rawParamName);
422
+ }
423
+ }
424
+ }
425
+ }
426
+ };
427
+
428
+ // Rust parameter types do not establish a dependency injection binding.
429
+ if (!isRust) extractTypeHints(row.signature);
430
+
431
+ // Also check constructor injection if this is a method or class
432
+ const classOwner = containerName || (row.kind === "class" ? row.name : "");
433
+ if (classOwner && !isRust) {
434
+ const ctor = this.db
435
+ .query<{ signature: string }, [number, string, string, string, string]>(
436
+ "SELECT signature FROM symbols WHERE file_id = ? AND (name = ? OR name = ? OR name = ? OR name LIKE ?) LIMIT 1"
437
+ )
438
+ .get(
439
+ row.file_id,
440
+ `${classOwner}::__construct`,
441
+ `${classOwner}::constructor`,
442
+ `${classOwner}::__init__`,
443
+ `%::__construct`
444
+ );
445
+ if (ctor) {
446
+ extractTypeHints(ctor.signature);
447
+ }
448
+ }
449
+
450
+ // 3. Outbound Calls (inspected from physical source file lines if accessible)
451
+ try {
452
+ const fullPath = options.workspaceRoot
453
+ ? path.resolve(options.workspaceRoot, row.file_path)
454
+ : row.file_path;
455
+ // Public handlers provide a workspace; the legacy rootless repository API also accepts absolute paths.
456
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Outbound call source");
457
+ if (probeSourcePath(fullPath) === "file") {
458
+ const fileContent = readSourceFile(fullPath);
459
+ const lines = fileContent.split(/\r?\n/);
460
+ const start = Math.max(0, row.line_start - 1);
461
+ const end = Math.min(lines.length, row.line_end);
462
+ const rawSlice = lines.slice(start, end).join("\n");
463
+ const sanitizedSlice = stripCommentsAndStrings(rawSlice);
464
+
465
+ // Track local `new ClassName(...)` assignments inside the symbol slice
466
+ for (const m of sanitizedSlice.matchAll(/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*new\s+([A-Z][a-zA-Z0-9_]*)\s*\(/g)) {
467
+ varTypes.set(m[1], m[2]);
468
+ }
469
+ for (const m of sanitizedSlice.matchAll(/\$([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*new\s+([A-Z][a-zA-Z0-9_]*)\s*\(/g)) {
470
+ varTypes.set(m[1], m[2]);
471
+ }
472
+
473
+ // Match Static invocations: ClassName::methodName(
474
+ const staticCalls = sanitizedSlice.matchAll(/([A-Z][a-zA-Z0-9_]+)::([a-zA-Z0-9_]+)\s*\(/g);
475
+ for (const m of staticCalls) {
476
+ if (m[1] !== "self" && m[1] !== "parent" && m[1] !== "static") {
477
+ outboundCalls.add(`${m[1]}::${m[2]}`);
478
+ }
479
+ }
480
+
481
+ // Match PHP property calls: $this->property->method(
482
+ const propCalls = sanitizedSlice.matchAll(/\$this->([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*\(/g);
483
+ for (const m of propCalls) {
484
+ const propName = m[1];
485
+ const methodName = m[2];
486
+ const mappedType = varTypes.get(propName);
487
+ const inferredClass = mappedType || (propName.charAt(0).toUpperCase() + propName.slice(1));
488
+ outboundCalls.add(`${inferredClass}::${methodName}`);
489
+ }
490
+
491
+ // Match TS/JS property calls: this.property.method(
492
+ const tsPropCalls = sanitizedSlice.matchAll(/\bthis\.([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\s*\(/g);
493
+ for (const m of tsPropCalls) {
494
+ const propName = m[1];
495
+ const methodName = m[2];
496
+ if (propName !== "db") {
497
+ const mappedType = varTypes.get(propName);
498
+ const inferredClass = mappedType || (propName.charAt(0).toUpperCase() + propName.slice(1));
499
+ outboundCalls.add(`${inferredClass}::${methodName}`);
500
+ }
501
+ }
502
+
503
+ // Collect same-file symbols and explicitly imported symbols for high-precision direct & receiver call detection
504
+ const sameFileSymbols = this.getSymbolsByFileId(row.file_id);
505
+ const knownDirectCallables = new Set<string>();
506
+ const knownStaticReceivers = new Set<string>();
507
+ for (const s of sameFileSymbols) {
508
+ if (s.id === row.id) continue;
509
+ if (s.kind === "function") knownDirectCallables.add(s.name);
510
+ else if (s.kind === "class") knownStaticReceivers.add(s.name);
511
+ }
512
+
513
+ const fileDeps = this.db
514
+ .query<{ import_statement: string }, [number]>(
515
+ "SELECT import_statement FROM dependencies WHERE source_file_id = ? AND is_external = 0"
516
+ )
517
+ .all(row.file_id);
518
+ for (const dep of fileDeps) {
519
+ const stmt = dep.import_statement || "";
520
+ if (/^\s*import\s+type\b/.test(stmt)) continue;
521
+ const braceMatch = stmt.match(/\{([^}]+)\}/);
522
+ if (braceMatch) {
523
+ for (const spec of braceMatch[1].split(",")) {
524
+ const trimmedSpec = spec.trim();
525
+ if (/^type\s+/.test(trimmedSpec)) continue;
526
+ const aliasParts = trimmedSpec.split(/\s+as\s+/);
527
+ const localName = (aliasParts[1] || aliasParts[0] || "").trim();
528
+ if (/^[a-z_$][a-zA-Z0-9_$]*$/.test(localName)) knownDirectCallables.add(localName);
529
+ else if (/^[A-Z][a-zA-Z0-9_$]*$/.test(localName)) knownStaticReceivers.add(localName);
530
+ }
531
+ }
532
+ const defaultMatch = stmt.match(/^\s*import\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/);
533
+ if (defaultMatch) {
534
+ const localName = defaultMatch[1];
535
+ if (/^[a-z_$]/.test(localName)) knownDirectCallables.add(localName);
536
+ else knownStaticReceivers.add(localName);
537
+ }
538
+ }
539
+
540
+ // Match calls on typed parameters / local instances (`repo.findSymbolsByName(` or `TopologyDetector.detect(`)
541
+ for (const m of sanitizedSlice.matchAll(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g)) {
542
+ const receiver = m[1];
543
+ const method = m[2];
544
+ if (receiver === "this" || receiver === "super" || receiver === "console" || receiver === "process" || receiver === "Math" || receiver === "JSON" || receiver === "Object" || receiver === "Array" || receiver === "Buffer" || receiver === "Promise" || receiver === "Number" || receiver === "String") continue;
545
+ const mappedType = varTypes.get(receiver);
546
+ if (mappedType) {
547
+ outboundCalls.add(`${mappedType}::${method}`);
548
+ } else if (knownStaticReceivers.has(receiver)) {
549
+ outboundCalls.add(`${receiver}::${method}`);
550
+ }
551
+ }
552
+ for (const m of sanitizedSlice.matchAll(/\$([a-zA-Z_][a-zA-Z0-9_]*)\s*->\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g)) {
553
+ const receiver = m[1];
554
+ const method = m[2];
555
+ if (receiver === "this") continue;
556
+ const mappedType = varTypes.get(receiver);
557
+ if (mappedType) {
558
+ outboundCalls.add(`${mappedType}::${method}`);
559
+ }
560
+ }
561
+
562
+ // Match direct function calls inside symbol body (after opening `{`)
563
+ const bodyStartIdx = sanitizedSlice.indexOf("{");
564
+ const bodySlice = bodyStartIdx !== -1 ? sanitizedSlice.slice(bodyStartIdx + 1) : "";
565
+ if (bodySlice && knownDirectCallables.size > 0) {
566
+ for (const m of bodySlice.matchAll(/(?:^|[^.\w$:])([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g)) {
567
+ const fnName = m[1];
568
+ if (fnName !== row.name && knownDirectCallables.has(fnName)) {
569
+ outboundCalls.add(fnName);
570
+ }
571
+ }
572
+ }
573
+ }
574
+ } catch {
575
+ // Graceful fallback if file not physically accessible
576
+ }
577
+
578
+ const depRepo = new DependencyRepository(this.db);
579
+ connectedFiles = depRepo.getFileConnections(row.file_path,options.workspaceRoot);
580
+
581
+ // 4. Resolve Outbound Calls to target symbol line ranges
582
+ for (const call of outboundCalls) {
583
+ try {
584
+ const matches = this.findSymbolsByName(call);
585
+ const target = matches.length === 1 ? matches[0] : undefined;
586
+ if (target) {
587
+ resolvedOutboundCalls.push({
588
+ symbol: call,
589
+ target_file: target.file_path,
590
+ target_range: {
591
+ start_line: target.line_start,
592
+ end_line: target.line_end,
593
+ total_lines: target.line_count,
594
+ },
595
+ domain: target.domain_name,
596
+ is_resolved: true,
597
+ });
598
+ } else {
599
+ resolvedOutboundCalls.push({
600
+ symbol: call,
601
+ is_resolved: false,
602
+ });
603
+ }
604
+ } catch {
605
+ resolvedOutboundCalls.push({
606
+ symbol: call,
607
+ is_resolved: false,
608
+ });
609
+ }
610
+ }
611
+ }
612
+
613
+ const complexitySmell: SymbolComplexitySmell | undefined =
614
+ row.line_count > 300
615
+ ? {
616
+ is_high_complexity: true,
617
+ threshold: 300,
618
+ total_lines: row.line_count,
619
+ warning: `Symbol '${row.name}' spans ${row.line_count} lines (exceeds 300-line threshold). Candidate for decomposition/refactoring.`,
620
+ }
621
+ : undefined;
622
+
623
+ return {
624
+ symbol_ref: row.symbol_ref,
625
+ visibility_semantics: "legacy_normalized",
626
+ symbol: row.name,
627
+ kind: row.kind,
628
+ file_path: row.file_path,
629
+ domain: row.domain_name,
630
+ exact_range: {
631
+ start_line: row.line_start,
632
+ end_line: row.line_end,
633
+ total_lines: row.line_count,
634
+ },
635
+ signature: row.signature,
636
+ visibility: row.visibility,
637
+ dependencies_injected: Array.from(dependenciesInjected),
638
+ outbound_calls: Array.from(outboundCalls),
639
+ resolved_outbound_calls: resolvedOutboundCalls.length > 0 ? resolvedOutboundCalls.map(call => ({ ...call, derivation: "inferred" as const })) : undefined,
640
+ complexity_smell: complexitySmell,
641
+ sibling_methods: siblingMethods.length > 0 ? siblingMethods : undefined,
642
+ connected_files: connectedFiles,
643
+ ...(options.includeDependencies === true ? { relationships: new DependencyRepository(this.db).getImportRelationships(options.workspaceRoot).filter(edge => edge.source.file === row.file_path) } : {}),
644
+ };
645
+ }
646
+
647
+ }