@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,733 @@
1
+ import { analyzeSymbolImpact } from "../../resolver/symbol-impact.ts";
2
+ import { assertPathContained } from "../../resolver/path-resolver.ts";
3
+ import { ImportResolver } from "../../resolver/import-resolver.ts";
4
+ import { readSourceFile } from "../../resources/source-files.ts";
5
+ import { computeContentHash } from "../../ingestion/hasher.ts";
6
+ import { getLanguageCapability } from "../../parser/language-capabilities.ts";
7
+ import type { ImportRelationship } from "../../../types/index.ts";
8
+ import { posix, resolve, sep } from "node:path";
9
+ import type { Database } from "bun:sqlite";
10
+ import type {
11
+ ExtractedDependency,
12
+ FileConnectionsSummary,
13
+ GetSymbolImpactResponse,
14
+ SymbolReference,
15
+ VerticalSliceRecord,
16
+ } from "../../../types/index.ts";
17
+
18
+ function escapeRegExp(str: string): string {
19
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20
+ }
21
+
22
+ export class DependencyRepository {
23
+ constructor(private db: Database) {}
24
+
25
+ public replaceFileDependencies(fileId: number, deps: ExtractedDependency[]): void {
26
+ this.db.query("DELETE FROM dependencies WHERE source_file_id = ?").run(fileId);
27
+ if (deps.length === 0) return;
28
+
29
+ const stmt = this.db.query(
30
+ `INSERT INTO dependencies (source_file_id, target_symbol_or_path, import_statement, line_number, is_external)
31
+ VALUES (?, ?, ?, ?, ?)`
32
+ );
33
+
34
+ for (const dep of deps) {
35
+ stmt.run(fileId, dep.target, dep.statement, dep.line_number, dep.is_external ? 1 : 0);
36
+ }
37
+ }
38
+
39
+ public upsertVerticalSlice(
40
+ slice: Omit<VerticalSliceRecord, "id" | "created_at">
41
+ ): void {
42
+ const existing = this.db
43
+ .query<VerticalSliceRecord, [string, string, number | null, string | null, string, string, string]>(
44
+ `SELECT id FROM vertical_slices WHERE http_method = ? AND route_uri = ?
45
+ AND domain_id IS ? AND controller_file IS ? AND controller_class = ? AND action_name = ? AND entry_kind = ?`
46
+ )
47
+ .get(slice.http_method, slice.route_uri, slice.domain_id, slice.controller_file,
48
+ slice.controller_class, slice.action_name, slice.entry_kind ?? "http_route");
49
+
50
+ if (existing) {
51
+ this.db
52
+ .query(
53
+ `UPDATE vertical_slices
54
+ SET domain_id = ?, feature_key = ?, route_name = ?, controller_class = ?,
55
+ action_name = ?, controller_file = ?, controller_line = ?,
56
+ architecture_style = ?, entry_kind = ?, execution_chain_json = ?
57
+ WHERE id = ?`
58
+ )
59
+ .run(
60
+ slice.domain_id,
61
+ slice.feature_key,
62
+ slice.route_name,
63
+ slice.controller_class,
64
+ slice.action_name,
65
+ slice.controller_file,
66
+ slice.controller_line,
67
+ slice.architecture_style ?? "clean",
68
+ slice.entry_kind ?? "http_route",
69
+ slice.execution_chain_json,
70
+ existing.id
71
+ );
72
+ } else {
73
+ this.db
74
+ .query(
75
+ `INSERT INTO vertical_slices (
76
+ domain_id, feature_key, http_method, route_uri, route_name,
77
+ controller_class, action_name, controller_file, controller_line,
78
+ architecture_style, entry_kind, execution_chain_json
79
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
80
+ )
81
+ .run(
82
+ slice.domain_id,
83
+ slice.feature_key,
84
+ slice.http_method,
85
+ slice.route_uri,
86
+ slice.route_name,
87
+ slice.controller_class,
88
+ slice.action_name,
89
+ slice.controller_file,
90
+ slice.controller_line,
91
+ slice.architecture_style ?? "clean",
92
+ slice.entry_kind ?? "http_route",
93
+ slice.execution_chain_json
94
+ );
95
+ }
96
+ }
97
+
98
+ public findVerticalSlices(searchTerm: string): VerticalSliceRecord[] {
99
+ const term = searchTerm.trim();
100
+ const wild = `%${term}%`;
101
+ const query = `
102
+ SELECT * FROM vertical_slices
103
+ WHERE route_uri LIKE ?
104
+ OR route_name LIKE ?
105
+ OR controller_class LIKE ?
106
+ OR action_name LIKE ?
107
+ OR feature_key LIKE ?
108
+ OR execution_chain_json LIKE ?
109
+ ORDER BY id ASC
110
+ `;
111
+ return this.db.query<VerticalSliceRecord, [string, string, string, string, string, string]>(query).all(
112
+ wild, wild, wild, wild, wild, wild
113
+ );
114
+ }
115
+
116
+ public getAllVerticalSlices(): VerticalSliceRecord[] {
117
+ return this.db.query<VerticalSliceRecord, []>("SELECT * FROM vertical_slices ORDER BY id ASC").all();
118
+ }
119
+
120
+ public countVerticalSlices(): number {
121
+ const row = this.db
122
+ .query<{ cnt: number }, []>("SELECT COUNT(*) as cnt FROM vertical_slices")
123
+ .get();
124
+ return row?.cnt ?? 0;
125
+ }
126
+
127
+ public clearVerticalSlices(domainId?: number): void {
128
+ if (domainId) {
129
+ this.db.query("DELETE FROM vertical_slices WHERE domain_id = ?").run(domainId);
130
+ } else {
131
+ this.db.query("DELETE FROM vertical_slices").run();
132
+ }
133
+ }
134
+
135
+ public getAllDependenciesWithDomains(sourceFile?: string): Array<{
136
+ source_file: string;
137
+ source_domain: string;
138
+ line_number: number;
139
+ target: string;
140
+ statement: string;
141
+ is_external: boolean;
142
+ }> {
143
+ const query = `
144
+ SELECT
145
+ f.path AS source_file,
146
+ d.name AS source_domain,
147
+ dep.line_number,
148
+ dep.target_symbol_or_path AS target,
149
+ dep.import_statement AS statement,
150
+ dep.is_external
151
+ FROM dependencies dep
152
+ JOIN files f ON dep.source_file_id = f.id
153
+ JOIN domains d ON f.domain_id = d.id
154
+ ${sourceFile === undefined ? "" : "WHERE f.path = ?"}
155
+ ORDER BY d.name, f.path, dep.line_number
156
+ `;
157
+ return this.db.query<any, string[]>(query).all(...(sourceFile === undefined ? [] : [sourceFile]));
158
+ }
159
+
160
+ public getImportRelationships(workspaceRoot?: string, sourceFile?: string): ImportRelationship[] {
161
+ const root = workspaceRoot ?? this.db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get("workspace_root")?.value;
162
+ if (!root) return [];
163
+ const files = this.db.query<{ path: string; content_hash: string; domain_id: number }, string[]>(
164
+ `SELECT path, content_hash, domain_id FROM files ${sourceFile === undefined ? "" : "WHERE path = ?"}`
165
+ ).all(...(sourceFile === undefined ? [] : [sourceFile]));
166
+ const domains = this.db.query<{ name: string; root_path: string }, []>("SELECT name, root_path FROM domains").all().sort((a,b)=>b.root_path.length-a.root_path.length);
167
+ const resolver = new ImportResolver(root, domains.map(domain => domain.root_path));
168
+ const freshness = new Map<string, ImportRelationship["freshness"]>();
169
+ const hashes = new Map(files.map(f => [f.path, f.content_hash]));
170
+ return this.getAllDependenciesWithDomains(sourceFile).map(dep => {
171
+ if (!freshness.has(dep.source_file)) {
172
+ try { assertPathContained(dep.source_file, root, "Import source"); freshness.set(dep.source_file, computeContentHash(readSourceFile(resolve(root,dep.source_file))) === hashes.get(dep.source_file) ? "current" : "stale"); }
173
+ catch { freshness.set(dep.source_file,"unavailable"); }
174
+ }
175
+ const resolution = resolver.resolve(dep.target,dep.source_file,dep.statement);
176
+ const current = freshness.get(dep.source_file)!;
177
+ if (current !== "current") { resolution.status = "unresolved"; resolution.reason = `source_${current}`; resolution.targets = []; }
178
+ const targetDomains = resolution.targets.flatMap(target => target.files.map(file => domains.find(domain => {
179
+ const targetPath = resolve(root,file), domainPath = resolve(root,domain.root_path);
180
+ return targetPath === domainPath || targetPath.startsWith(domainPath + sep);
181
+ })?.name).filter((name): name is string => !!name));
182
+ return {
183
+ kind: "imports", derivation: "source",
184
+ source: { file: dep.source_file, line: dep.line_number, statement: dep.statement, indexed_content_hash: hashes.get(dep.source_file) ?? "" },
185
+ resolution, target_domains: [...new Set(targetDomains)], freshness: current,
186
+ index_coverage: resolution.targets.every(target => target.files.every(file => hashes.has(file) ||
187
+ (sourceFile !== undefined && !!this.db.query("SELECT 1 FROM files WHERE path = ?").get(file)) || !getLanguageCapability(file))) ? "complete" : "partial",
188
+ ...(dep.source_file.endsWith(".go") ? { import_binding: (() => {
189
+ const alias = dep.statement.replace(/^\s*import\s+/, "").match(/^\s*([A-Za-z_]\w*|\.)\s+["`]/)?.[1];
190
+ return { kind: alias === "_" ? "blank" : alias === "." ? "dot" : alias ? "named" : "default", alias };
191
+ })() } : {}),
192
+ ...(dep.source_file.endsWith(".py") ? { import_binding: (() => {
193
+ if (/^\s*from\s+.*\s+import\s+\*/.test(dep.statement)) return { kind: "star" };
194
+ const asMatch = dep.statement.match(/\bas\s+([A-Za-z_]\w*)\s*$/);
195
+ return { kind: asMatch ? "named" : "default", alias: asMatch?.[1] };
196
+ })() } : {}),
197
+ };
198
+ });
199
+ }
200
+
201
+ public getDomainFileConnections(domainId?: number, workspaceRoot?: string): Map<string, FileConnectionsSummary> {
202
+ const root = workspaceRoot ?? this.db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get("workspace_root")?.value;
203
+ if (root) {
204
+ const files = this.db.query<{ path: string; domain_id: number }, []>("SELECT path, domain_id FROM files").all();
205
+ const edges = this.getImportRelationships(root);
206
+ return new Map(files.filter(f => domainId === undefined || f.domain_id === domainId).map(file => {
207
+ const imports = edges.filter(edge => edge.source.file === file.path && edge.resolution.status === "resolved").flatMap(edge => edge.resolution.targets.flatMap(target => target.files));
208
+ const inbound = edges.filter(edge => edge.resolution.status === "resolved" && edge.resolution.targets.some(target => target.files.includes(file.path))).map(edge => edge.source.file);
209
+ return [file.path, { imports_from: [...new Set(imports)].sort(), imported_by: [...new Set(inbound)].sort(), imported_by_count: new Set(inbound).size }];
210
+ }));
211
+ }
212
+ const allFiles = this.db
213
+ .query<{ id: number; domain_id: number; path: string }, []>(
214
+ "SELECT id, domain_id, path FROM files ORDER BY path ASC"
215
+ )
216
+ .all();
217
+
218
+ const fileById = new Map<number, { id: number; domain_id: number; path: string }>();
219
+ const fileByNormPath = new Map<string, string>();
220
+ const fileByNoExtPath = new Map<string, string>();
221
+
222
+ for (const f of allFiles) {
223
+ const norm = f.path.replace(/\\/g, "/").replace(/^\.\//, "");
224
+ fileById.set(f.id, { ...f, path: norm });
225
+ fileByNormPath.set(norm.toLowerCase(), f.path);
226
+ const noExt = norm.replace(/\.[^/.]+$/, "").toLowerCase();
227
+ fileByNoExtPath.set(noExt, f.path);
228
+ if (noExt.endsWith("/index")) {
229
+ fileByNoExtPath.set(noExt.slice(0, -"/index".length), f.path);
230
+ }
231
+ }
232
+
233
+ const resolveInternalTarget = (sourcePath: string, rawTarget: string): string | null => {
234
+ const cleaned = rawTarget.trim().replace(/^['"]|['"]$/g, "").replace(/\\/g, "/");
235
+ if (!cleaned) return null;
236
+
237
+ if (cleaned.startsWith(".")) {
238
+ const srcDir = posix.dirname(sourcePath.replace(/\\/g, "/"));
239
+ const joined = posix.normalize(posix.join(srcDir, cleaned)).replace(/^\.\//, "");
240
+ const lowerJoined = joined.toLowerCase();
241
+ const exact = fileByNormPath.get(lowerJoined) ?? fileByNoExtPath.get(lowerJoined.replace(/\.[^/.]+$/, ""));
242
+ if (exact) return exact;
243
+ }
244
+
245
+ const aliasClean = cleaned.replace(/^@\//, "src/").replace(/^\.\//, "");
246
+ const lowerAlias = aliasClean.toLowerCase();
247
+ const byAlias = fileByNormPath.get(lowerAlias) ?? fileByNoExtPath.get(lowerAlias.replace(/\.[^/.]+$/, ""));
248
+ if (byAlias) return byAlias;
249
+
250
+ for (const [noExt, origPath] of fileByNoExtPath.entries()) {
251
+ if (noExt.endsWith(`/${lowerAlias}`)) {
252
+ return origPath;
253
+ }
254
+ }
255
+ return null;
256
+ };
257
+
258
+ const importsFromMap = new Map<string, Set<string>>();
259
+ const importedByMap = new Map<string, Set<string>>();
260
+ for (const f of allFiles) {
261
+ importsFromMap.set(f.path, new Set());
262
+ importedByMap.set(f.path, new Set());
263
+ }
264
+
265
+ const allInternalDeps = this.db
266
+ .query<{ source_file_id: number; target_symbol_or_path: string }, []>(
267
+ "SELECT source_file_id, target_symbol_or_path FROM dependencies WHERE is_external = 0"
268
+ )
269
+ .all();
270
+
271
+ for (const dep of allInternalDeps) {
272
+ const srcFile = fileById.get(dep.source_file_id);
273
+ if (!srcFile) continue;
274
+ const resolvedTarget = resolveInternalTarget(srcFile.path, dep.target_symbol_or_path);
275
+ if (resolvedTarget && resolvedTarget !== srcFile.path) {
276
+ importsFromMap.get(srcFile.path)?.add(resolvedTarget);
277
+ if (!importedByMap.has(resolvedTarget)) {
278
+ importedByMap.set(resolvedTarget, new Set());
279
+ }
280
+ importedByMap.get(resolvedTarget)?.add(srcFile.path);
281
+ }
282
+ }
283
+
284
+ const result = new Map<string, FileConnectionsSummary>();
285
+ for (const f of allFiles) {
286
+ if (domainId !== undefined && f.domain_id !== domainId) continue;
287
+ const importsFrom = Array.from(importsFromMap.get(f.path) ?? []).sort();
288
+ const importedBy = Array.from(importedByMap.get(f.path) ?? []).sort();
289
+ result.set(f.path, {
290
+ imports_from: importsFrom,
291
+ imported_by_count: importedBy.length,
292
+ imported_by: importedBy,
293
+ });
294
+ }
295
+
296
+ return result;
297
+ }
298
+
299
+ public getFileConnections(filePath: string, workspaceRoot?: string): FileConnectionsSummary {
300
+ const clean = filePath.replace(/\\/g, "/").replace(/^\.\//, "");
301
+ const allConns = this.getDomainFileConnections(undefined,workspaceRoot);
302
+ return (
303
+ allConns.get(clean) ??
304
+ allConns.get(filePath) ?? {
305
+ imports_from: [],
306
+ imported_by_count: 0,
307
+ imported_by: [],
308
+ }
309
+ );
310
+ }
311
+
312
+ public getSymbolImpact(
313
+ symbolQuery: string,
314
+ options: { domain?: string; workspaceRoot?: string; filePath?: string; reference?: SymbolReference } = {}
315
+ ): GetSymbolImpactResponse {
316
+ const trimmed = symbolQuery.trim();
317
+ if (!trimmed) {
318
+ return {
319
+ target_symbol: symbolQuery,
320
+ found_in_index: false,
321
+ warning: "Empty symbol query provided.",
322
+ impact_summary: {
323
+ total_dependents: 0,
324
+ risk_level: "unknown",
325
+ affected_files_count: 0,
326
+ },
327
+ inbound_callers: [],
328
+ };
329
+ }
330
+
331
+ let targetContainer = trimmed;
332
+ let targetMethod = "";
333
+ if (trimmed.includes("::")) {
334
+ const parts = trimmed.split("::");
335
+ targetContainer = parts[0];
336
+ targetMethod = parts[1];
337
+ } else if (trimmed.includes("@")) {
338
+ const parts = trimmed.split("@");
339
+ targetContainer = parts[0];
340
+ targetMethod = parts[1];
341
+ }
342
+
343
+ // 1. Look up target symbol in symbols joined with files and optionally domains
344
+ let targetSymRows: Array<{
345
+ name: string;
346
+ kind: string;
347
+ line_start: number;
348
+ line_end: number;
349
+ file_path: string;
350
+ domain_name?: string | null;
351
+ }>;
352
+ if (targetMethod) {
353
+ let methodSql = `
354
+ SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
355
+ FROM symbols s
356
+ JOIN files f ON s.file_id = f.id
357
+ LEFT JOIN domains dom ON f.domain_id = dom.id
358
+ `;
359
+ const methodParams: any[] = [];
360
+ if (options.domain) {
361
+ methodSql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
362
+ methodParams.push(options.domain);
363
+ } else {
364
+ methodSql += ` WHERE `;
365
+ }
366
+ methodSql += ` (s.name = ? OR s.name = ? OR (s.name = ? AND s.kind = 'method')) `;
367
+ methodParams.push(trimmed, `${targetContainer}::${targetMethod}`, targetMethod);
368
+ targetSymRows = this.db
369
+ .query<
370
+ {
371
+ name: string;
372
+ kind: string;
373
+ signature: string;
374
+ line_start: number;
375
+ line_end: number;
376
+ file_path: string;
377
+ domain_name?: string | null;
378
+ },
379
+ any[]
380
+ >(methodSql)
381
+ .all(...methodParams)
382
+ .filter(row => {
383
+ if (row.name !== targetMethod) return true;
384
+ // Go indexes bare method names; the receiver in its signature proves identity.
385
+ const receiver = row.signature.match(/^func\s*\(\s*(?:[A-Za-z_]\w*\s+)?\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)/);
386
+ return receiver?.[1] === targetContainer;
387
+ });
388
+
389
+ if (targetSymRows.length === 0) {
390
+ return {
391
+ target_symbol: trimmed,
392
+ found_in_index: false,
393
+ warning: `Symbol '${trimmed}' was not found in Septum index${options.domain ? ` for domain '${options.domain}'` : ""}. Method does not exist.`,
394
+ impact_summary: {
395
+ total_dependents: 0,
396
+ risk_level: "unknown",
397
+ affected_files_count: 0,
398
+ },
399
+ inbound_callers: [],
400
+ };
401
+ }
402
+ } else {
403
+ let containerSql = `
404
+ SELECT s.name, s.kind, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
405
+ FROM symbols s
406
+ JOIN files f ON s.file_id = f.id
407
+ LEFT JOIN domains dom ON f.domain_id = dom.id
408
+ `;
409
+ const containerParams: any[] = [];
410
+ if (options.domain) {
411
+ containerSql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
412
+ containerParams.push(options.domain);
413
+ } else {
414
+ containerSql += ` WHERE `;
415
+ }
416
+ containerSql += ` (s.name = ? OR s.name = ? OR s.name LIKE ? OR s.name LIKE ?) `;
417
+ containerParams.push(trimmed, targetContainer, `${targetContainer}::%`, `%::${targetContainer}`);
418
+ targetSymRows = this.db
419
+ .query<
420
+ {
421
+ name: string;
422
+ kind: string;
423
+ line_start: number;
424
+ line_end: number;
425
+ file_path: string;
426
+ domain_name?: string | null;
427
+ },
428
+ any[]
429
+ >(containerSql)
430
+ .all(...containerParams);
431
+
432
+ if (targetSymRows.length === 0) {
433
+ return {
434
+ target_symbol: trimmed,
435
+ found_in_index: false,
436
+ warning: `Symbol '${trimmed}' was not found in Septum index${options.domain ? ` for domain '${options.domain}'` : ""}.`,
437
+ impact_summary: {
438
+ total_dependents: 0,
439
+ risk_level: "unknown",
440
+ affected_files_count: 0,
441
+ },
442
+ inbound_callers: [],
443
+ };
444
+ }
445
+ }
446
+
447
+ const targetFilePath = (options.filePath ?? options.reference?.file_path)?.replace(/\\/g, "/");
448
+ if (targetFilePath) {
449
+ targetSymRows = targetSymRows.filter((r) => r.file_path.replace(/\\/g, "/") === targetFilePath);
450
+ if (targetSymRows.length === 0) {
451
+ return {
452
+ target_symbol: trimmed,
453
+ found_in_index: false,
454
+ warning: `Symbol '${trimmed}' was not found in Septum index for file '${targetFilePath}'${options.domain ? ` in domain '${options.domain}'` : ""}.`,
455
+ impact_summary: {
456
+ total_dependents: 0,
457
+ risk_level: "unknown",
458
+ affected_files_count: 0,
459
+ },
460
+ inbound_callers: [],
461
+ };
462
+ }
463
+ }
464
+
465
+ const definingFiles = new Set<string>(
466
+ targetSymRows.map((r) => r.file_path.replace(/\\/g, "/"))
467
+ );
468
+ const domainByFile = new Map<string, string>();
469
+ for (const row of targetSymRows) if (row.domain_name) domainByFile.set(row.file_path.replace(/\\/g, "/"), row.domain_name);
470
+
471
+ const definingFileStems = Array.from(
472
+ new Set(
473
+ Array.from(definingFiles)
474
+ .map((p) => p.split("/").pop()?.replace(/\.[^.]+$/, "") || "")
475
+ .filter((s) => s.length >= 2)
476
+ )
477
+ );
478
+
479
+ // 2. Query dependencies matching targetContainer, trimmed, import_statement, or defining file stem
480
+ const whereClauses: string[] = [
481
+ "d.target_symbol_or_path LIKE ?",
482
+ "d.import_statement LIKE ?",
483
+ "d.target_symbol_or_path LIKE ?",
484
+ ];
485
+ const queryParams: string[] = [
486
+ `%${targetContainer}%`,
487
+ `%${targetContainer}%`,
488
+ `%${trimmed}%`,
489
+ ];
490
+
491
+ for (const stem of definingFileStems) {
492
+ whereClauses.push("d.target_symbol_or_path LIKE ?");
493
+ queryParams.push(`%${stem}%`);
494
+ }
495
+
496
+ const depSql = `
497
+ SELECT
498
+ f.path AS file,
499
+ d.line_number,
500
+ d.target_symbol_or_path,
501
+ d.import_statement,
502
+ dom.name AS domain_name
503
+ FROM dependencies d
504
+ JOIN files f ON d.source_file_id = f.id
505
+ LEFT JOIN domains dom ON f.domain_id = dom.id
506
+ WHERE ${whereClauses.join(" OR ")}
507
+ ORDER BY f.path ASC, d.line_number ASC
508
+ `;
509
+ const rawDepRows = this.db.query<any, string[]>(depSql).all(...queryParams);
510
+
511
+ const isTargetedFile = Boolean(targetFilePath);
512
+ const matchesDefiningFile = (df: string, stmt: string, target: string): boolean => {
513
+ const normStmt = stmt.replace(/\\/g, "/");
514
+ const normTarget = target.replace(/\\/g, "/");
515
+ const clean = df.replace(/\.[^.]+$/, "");
516
+ const parts = clean.split("/");
517
+ const suffixes: string[] = [];
518
+ for (let i = 0; i < parts.length; i++) {
519
+ suffixes.push(parts.slice(i).join("/"));
520
+ }
521
+ return suffixes.some((s) => {
522
+ const escaped = escapeRegExp(s);
523
+ const r = new RegExp(`(?:^|[\\\\/\"\x27.@:])(?:${escaped})(?:$|[\\\\/\"\x27;:.()\\s]|\\.[^\\\\/]+)`, "i");
524
+ return r.test(normStmt) || r.test(normTarget);
525
+ });
526
+ };
527
+
528
+ const containerWordRegex = new RegExp(`\\b${escapeRegExp(targetContainer)}\\b`);
529
+ const depRows = rawDepRows.filter((row) => {
530
+ const normCallerFile = String(row.file).replace(/\\/g, "/");
531
+ if (row.domain_name) domainByFile.set(normCallerFile, String(row.domain_name));
532
+ if (definingFiles.has(normCallerFile)) return false;
533
+
534
+ const stmt = String(row.import_statement || "");
535
+ const target = String(row.target_symbol_or_path || "");
536
+
537
+ if (containerWordRegex.test(stmt) || containerWordRegex.test(target)) {
538
+ if (isTargetedFile) {
539
+ const matchesDefining = Array.from(definingFiles).some((df) => matchesDefiningFile(df, stmt, target));
540
+ if (!matchesDefining) {
541
+ return false;
542
+ }
543
+ }
544
+ return true;
545
+ }
546
+
547
+ // If no named specifier braces are present, accept path match against defining file stem
548
+ if (!stmt.includes("{")) {
549
+ for (const stem of definingFileStems) {
550
+ const stemRegex = new RegExp(`(?:^|[\\\\/])${escapeRegExp(stem)}(?:\\.[^\\\\/]+)?$`);
551
+ if (stemRegex.test(target)) {
552
+ return true;
553
+ }
554
+ }
555
+ }
556
+
557
+ return false;
558
+ });
559
+
560
+ // 2b. Discover same-directory / same-package files for languages with implicit package/namespace resolution (.go, .php, .java, .cs)
561
+ const implicitPackageFiles = new Set<string>();
562
+ const implicitLangDirs = new Set<string>();
563
+ for (const df of definingFiles) {
564
+ if (/\.(go|php|java|cs)$/i.test(df)) {
565
+ const dir = posix.dirname(df);
566
+ implicitLangDirs.add(dir === "." ? "" : dir);
567
+ }
568
+ }
569
+ if (implicitLangDirs.size > 0) {
570
+ const dirClauses: string[] = [];
571
+ const dirParams: string[] = [];
572
+ for (const dir of implicitLangDirs) {
573
+ if (dir === "") {
574
+ dirClauses.push("f.path NOT LIKE '%/%'");
575
+ } else {
576
+ dirClauses.push("(f.path LIKE ? AND SUBSTR(f.path, LENGTH(?) + 2) NOT LIKE '%/%')");
577
+ dirParams.push(`${dir}/%`, dir);
578
+ }
579
+ }
580
+ const pkgRows = this.db
581
+ .query<{ path: string; domain_name: string | null }, string[]>(
582
+ `SELECT f.path, dom.name AS domain_name
583
+ FROM files f
584
+ LEFT JOIN domains dom ON f.domain_id = dom.id
585
+ WHERE ${dirClauses.join(" OR ")}`
586
+ )
587
+ .all(...dirParams);
588
+ for (const r of pkgRows) {
589
+ const norm = r.path.replace(/\\/g, "/");
590
+ if (r.domain_name) domainByFile.set(norm, r.domain_name);
591
+ if (!definingFiles.has(norm) && /\.(go|php|java|cs)$/i.test(norm)) {
592
+ implicitPackageFiles.add(norm);
593
+ }
594
+ }
595
+ }
596
+
597
+ // 3. Batch-load all symbols for candidate caller files in ONE query (zero N+1)
598
+ const uniqueCallerFiles = Array.from(new Set(depRows.map((r) => String(r.file))));
599
+ const allSymbolLookupFiles = Array.from(
600
+ new Set([...uniqueCallerFiles, ...definingFiles, ...implicitPackageFiles])
601
+ );
602
+ const callerSymbolsByFile = new Map<
603
+ string,
604
+ Array<{ name: string; kind: string; signature: string; line_start: number; line_end: number }>
605
+ >();
606
+
607
+ if (allSymbolLookupFiles.length > 0) {
608
+ const placeholders = allSymbolLookupFiles.map(() => "?").join(",");
609
+ const allCallerSyms = this.db
610
+ .query<
611
+ { name: string; kind: string; signature: string; line_start: number; line_end: number; path: string },
612
+ string[]
613
+ >(
614
+ `SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path
615
+ FROM symbols s
616
+ JOIN files f ON s.file_id = f.id
617
+ WHERE f.path IN (${placeholders})
618
+ ORDER BY (s.line_end - s.line_start) ASC`
619
+ )
620
+ .all(...allSymbolLookupFiles);
621
+
622
+ for (const sym of allCallerSyms) {
623
+ const list = callerSymbolsByFile.get(sym.path) || [];
624
+ list.push(sym);
625
+ callerSymbolsByFile.set(sym.path, list);
626
+ }
627
+ }
628
+
629
+ return analyzeSymbolImpact({
630
+ query: trimmed, container: targetContainer, method: targetMethod,
631
+ targets: targetSymRows, dependencies: depRows, samePackageFiles: implicitPackageFiles,
632
+ symbolsByFile: callerSymbolsByFile, domainsByFile: domainByFile, workspaceRoot: options.workspaceRoot,
633
+ });
634
+ }
635
+
636
+ public getFileInboundImpact(filePath: string): {
637
+ direct_dependents_count: number;
638
+ top_consumers: string[];
639
+ symbols_count: number;
640
+ risk_level: "low" | "medium" | "high";
641
+ } {
642
+ const cleanPath = filePath.replace(/\\/g, "/");
643
+ const baseName = cleanPath.split("/").pop()?.replace(/\.[^.]+$/, "") || "";
644
+
645
+ const symbols = this.db
646
+ .query<{ name: string }, [string, string]>(
647
+ `SELECT s.name
648
+ FROM symbols s
649
+ JOIN files f ON s.file_id = f.id
650
+ WHERE f.path = ? OR f.path LIKE ?`
651
+ )
652
+ .all(cleanPath, `%${cleanPath}`);
653
+
654
+ const matchedFiles = new Set<string>();
655
+ const relationships = this.getImportRelationships();
656
+ if (relationships.length > 0) {
657
+ for (const edge of relationships) {
658
+ if (edge.freshness !== "current" || edge.resolution.status !== "resolved") continue;
659
+ if (edge.source.file === cleanPath) continue;
660
+ if (edge.resolution.targets.some((t) => t.files.includes(cleanPath))) {
661
+ matchedFiles.add(edge.source.file);
662
+ }
663
+ }
664
+ } else {
665
+ const orConditions: string[] = [];
666
+ const params: string[] = [];
667
+
668
+ if (baseName.length >= 3) {
669
+ orConditions.push("d.target_symbol_or_path LIKE ?");
670
+ params.push(`%${cleanPath}%`);
671
+ orConditions.push("d.target_symbol_or_path LIKE ?");
672
+ params.push(`%${baseName}%`);
673
+ }
674
+
675
+ for (const sym of symbols.slice(0, 8)) {
676
+ const symName = sym.name.split("::").pop() || sym.name;
677
+ if (symName.length >= 4) {
678
+ orConditions.push("d.target_symbol_or_path LIKE ?");
679
+ params.push(`%${symName}%`);
680
+ orConditions.push("d.import_statement LIKE ?");
681
+ params.push(`%${symName}%`);
682
+ }
683
+ }
684
+
685
+ if (orConditions.length > 0) {
686
+ params.push(`%${cleanPath}`);
687
+ const depRows = this.db
688
+ .query<{ file: string; target: string; stmt: string }, string[]>(
689
+ `SELECT DISTINCT f.path AS file, d.target_symbol_or_path AS target, d.import_statement AS stmt
690
+ FROM dependencies d
691
+ JOIN files f ON d.source_file_id = f.id
692
+ WHERE (${orConditions.join(" OR ")})
693
+ AND f.path NOT LIKE ?`
694
+ )
695
+ .all(...params);
696
+
697
+ const baseBoundary = baseName.length >= 3
698
+ ? new RegExp(`(?:^|[\\/\\\\.])${escapeRegExp(baseName)}(?:\\.[^.\\/\\\\]+)?$`, "i")
699
+ : null;
700
+ const symNames = symbols
701
+ .slice(0, 8)
702
+ .map((s) => s.name.split("::").pop() || s.name)
703
+ .filter((n) => n.length >= 4)
704
+ .map((n) => new RegExp(`\\b${escapeRegExp(n)}\\b`));
705
+
706
+ for (const row of depRows) {
707
+ const targetMatches =
708
+ row.target.includes(cleanPath) ||
709
+ (baseBoundary !== null && baseBoundary.test(row.target)) ||
710
+ symNames.some((re) => re.test(row.target) || re.test(row.stmt));
711
+ if (targetMatches) {
712
+ matchedFiles.add(row.file);
713
+ }
714
+ }
715
+ }
716
+ }
717
+
718
+ const consumerList = Array.from(matchedFiles);
719
+ let riskLevel: "low" | "medium" | "high" = "low";
720
+ if (consumerList.length >= 5) {
721
+ riskLevel = "high";
722
+ } else if (consumerList.length >= 2) {
723
+ riskLevel = "medium";
724
+ }
725
+
726
+ return {
727
+ direct_dependents_count: consumerList.length,
728
+ top_consumers: consumerList.slice(0, 5),
729
+ symbols_count: symbols.length,
730
+ risk_level: riskLevel,
731
+ };
732
+ }
733
+ }