@dimassetoid/septum-mcp 0.2.1 → 0.5.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 (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -0,0 +1,477 @@
1
+ import type { GetSymbolImpactResponse, InboundCaller } from "../../types/index.ts";
2
+ import { resolve } from "node:path";
3
+ import { assertPathContained } from "./path-resolver.ts";
4
+ import { probeSourcePath, readSourceFile } from "../resources/source-files.ts";
5
+ import ts from "typescript";
6
+ import { ImportResolver } from "./import-resolver.ts";
7
+
8
+ type SymbolSpan = { name: string; kind: string; signature?: string; line_start: number; line_end: number; file_path: string };
9
+ interface ImpactFacts {
10
+ query: string;
11
+ container: string;
12
+ method: string;
13
+ targets: SymbolSpan[];
14
+ dependencies: Array<{ file: string; line_number: number; domain_name?: string | null; import_statement?: string }>;
15
+ samePackageFiles: Set<string>;
16
+ symbolsByFile: Map<string, Array<{ name: string; kind: string; signature: string; line_start: number; line_end: number }>>;
17
+ domainsByFile: Map<string, string>;
18
+ workspaceRoot?: string;
19
+ }
20
+ function escapeRegExp(str: string): string { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
21
+
22
+ /** Inferred caller evidence, independent of SQLite queries and persistence. */
23
+ export function analyzeSymbolImpact(facts: ImpactFacts): GetSymbolImpactResponse {
24
+ const { query: trimmed, container: targetContainer, method: targetMethod, targets: targetSymRows,
25
+ dependencies: depRows, samePackageFiles: implicitPackageFiles, symbolsByFile: callerSymbolsByFile, domainsByFile: domainByFile } = facts;
26
+ const options = { workspaceRoot: facts.workspaceRoot };
27
+ const definingFiles = new Set(targetSymRows.map(row => row.file_path.replace(/\\/g, "/")));
28
+ const uniqueCallerFiles = [...new Set(depRows.map(row => row.file))];
29
+ const containerWordRegex = new RegExp(`\\b${escapeRegExp(targetContainer)}\\b`);
30
+ const targetSpansByFile = new Map<string, Array<{ start: number; end: number }>>();
31
+ for (const row of targetSymRows) {
32
+ if (!targetMethod && row.name.includes("::") && !trimmed.includes("::")) continue;
33
+ const path = row.file_path.replace(/\\/g, "/");
34
+ const spans = targetSpansByFile.get(path) ?? [];
35
+ spans.push({ start: row.line_start, end: row.line_end });
36
+ targetSpansByFile.set(path, spans);
37
+ }
38
+ const findEnclosingSymbol = (
39
+ filePath: string,
40
+ lineNum: number
41
+ ): { name: string; kind: string; signature: string } | undefined => {
42
+ const syms = callerSymbolsByFile.get(filePath);
43
+ if (!syms) return undefined;
44
+ return syms.find((s) => lineNum >= s.line_start && lineNum <= s.line_end);
45
+ };
46
+
47
+ const callersMap = new Map<string, InboundCaller>();
48
+
49
+ // Import-bound identifier calls/instantiations carry call-site coordinates, not import lines.
50
+ if (!targetMethod && targetSymRows.some(row => row.kind === "function" || row.kind === "class")) {
51
+ const tsCallerEntries: Array<{ file: string; fullPath: string; source: ts.SourceFile }> = [];
52
+ for (const file of uniqueCallerFiles) {
53
+ if (!/\.[cm]?[jt]sx?$/.test(file) || !options.workspaceRoot) continue;
54
+ const fullPath = resolve(options.workspaceRoot, file);
55
+ assertPathContained(fullPath, options.workspaceRoot, "Caller source");
56
+ if (probeSourcePath(fullPath) !== "file") continue;
57
+ tsCallerEntries.push({
58
+ file,
59
+ fullPath,
60
+ source: ts.createSourceFile(fullPath, readSourceFile(fullPath), ts.ScriptTarget.Latest, true),
61
+ });
62
+ }
63
+
64
+ if (tsCallerEntries.length > 0) {
65
+ const sourceByPath = new Map(tsCallerEntries.map(entry => [entry.fullPath, entry.source]));
66
+ const host = ts.createCompilerHost({ noLib: true, noResolve: true });
67
+ host.getSourceFile = name => sourceByPath.get(name);
68
+ const checker = ts.createProgram(
69
+ tsCallerEntries.map(entry => entry.fullPath),
70
+ { noLib: true, noResolve: true },
71
+ host
72
+ ).getTypeChecker();
73
+
74
+ for (const { file, source } of tsCallerEntries) {
75
+ const bindings = new Set<ts.Symbol>();
76
+ for (const statement of source.statements) {
77
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue;
78
+ const resolution = new ImportResolver(options.workspaceRoot!).resolve(statement.moduleSpecifier.text, file);
79
+ const hitsDefiningOrBarrel = resolution.status === "resolved" && resolution.targets.some(target => target.files.some(path => {
80
+ if (definingFiles.has(path)) return true;
81
+ if (/\/index\.[cm]?[jt]sx?$/.test(path)) {
82
+ const barrelDir = path.replace(/\/index\.[cm]?[jt]sx?$/, "");
83
+ return Array.from(definingFiles).some(df => df.startsWith(barrelDir + "/"));
84
+ }
85
+ return false;
86
+ }));
87
+ if (!hitsDefiningOrBarrel) continue;
88
+ const clause = statement.importClause;
89
+ if (clause?.name && targetSymRows.some(row => row.signature?.includes("export default"))) { const binding = checker.getSymbolAtLocation(clause.name); if (binding) bindings.add(binding); }
90
+ if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const specifier of clause.namedBindings.elements) {
91
+ if (specifier.isTypeOnly || (specifier.propertyName ?? specifier.name).text !== targetContainer) continue;
92
+ const binding = checker.getSymbolAtLocation(specifier.name); if (binding) bindings.add(binding);
93
+ }
94
+ }
95
+ if (bindings.size === 0) continue;
96
+
97
+ const recordUsage = (expr: ts.Node, usageKind: "call" | "instantiation" | "heritage") => {
98
+ const line = source.getLineAndCharacterOfPosition(expr.getStart(source)).line + 1;
99
+ const enclosing = findEnclosingSymbol(file, line);
100
+ callersMap.set(`${file}:${line}:${usageKind}`, {
101
+ file,
102
+ line,
103
+ caller: enclosing?.name ?? `${file}:${line}`,
104
+ kind: usageKind,
105
+ domain: domainByFile.get(file),
106
+ });
107
+ };
108
+
109
+ const visit = (node: ts.Node) => {
110
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
111
+ recordUsage(node.expression, "call");
112
+ } else if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
113
+ recordUsage(node.expression, "instantiation");
114
+ } else if (ts.isExpressionWithTypeArguments(node) && ts.isHeritageClause(node.parent) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
115
+ recordUsage(node.expression, "heritage");
116
+ }
117
+ ts.forEachChild(node, visit);
118
+ };
119
+ visit(source);
120
+ }
121
+ }
122
+ }
123
+
124
+ for (const row of depRows) {
125
+ const enclosing = findEnclosingSymbol(row.file, row.line_number);
126
+ const callerName = enclosing ? enclosing.name : `${row.file}:${row.line_number}`;
127
+ const key = `${row.file}:${row.line_number}:${callerName}`;
128
+
129
+ if (!callersMap.has(key)) {
130
+ callersMap.set(key, {
131
+ file: row.file,
132
+ caller: callerName,
133
+ line: row.line_number,
134
+ kind: "import",
135
+ domain: row.domain_name ?? undefined,
136
+ });
137
+ }
138
+ }
139
+
140
+ // 4. Scan file content of callers for exact method/function calls
141
+ const targetMethodRow = targetSymRows.find((r) => r.kind === "method");
142
+ const effectiveMethod =
143
+ targetMethod ||
144
+ (targetMethodRow ? (targetMethodRow.name.split("::").pop() ?? "") : "");
145
+ const targetMethodOwnerFull = targetMethodRow?.name.includes("::")
146
+ ? targetMethodRow.name.split("::")[0]
147
+ : targetMethod
148
+ ? targetContainer
149
+ : undefined;
150
+ const targetMethodOwnerShort = targetMethodOwnerFull?.split(/[\\/]/).pop();
151
+ const isStaticPhpMethod =
152
+ Boolean(effectiveMethod) &&
153
+ targetSymRows.length > 0 &&
154
+ targetSymRows.every((r) => /\bstatic\s+function\b/.test(r.signature ?? ""));
155
+ const staticOwnerCallRegex =
156
+ effectiveMethod && targetMethodOwnerShort
157
+ ? new RegExp(
158
+ `\\b(?:${escapeRegExp(targetMethodOwnerShort)}${
159
+ targetMethodOwnerFull && targetMethodOwnerFull !== targetMethodOwnerShort
160
+ ? `|${escapeRegExp(targetMethodOwnerFull)}`
161
+ : ""
162
+ })::${escapeRegExp(effectiveMethod)}\\s*\\(`
163
+ )
164
+ : null;
165
+ // For standalone functions, match unqualified calls (`fn(...)`) and only allow qualified calls
166
+ // (`alias.fn(...)`) when `alias` is a module/namespace import binding (never `cls.fn`, `self.fn`, etc.).
167
+ const isFunctionTarget = !effectiveMethod && targetSymRows.some((r) => r.kind === "function");
168
+ const nonTsFnCallRegex = isFunctionTarget
169
+ ? new RegExp(`(?:^|[^.\\w$:])\\b${escapeRegExp(targetContainer)}\\s*\\(`)
170
+ : null;
171
+ const nonTsFnDeclRegex = nonTsFnCallRegex
172
+ ? new RegExp(`\\b(?:function|func|def|fn)\\s+${escapeRegExp(targetContainer)}\\b`)
173
+ : null;
174
+
175
+ const definingStems = new Set(
176
+ Array.from(definingFiles).flatMap((df) => {
177
+ const stem = df.split("/").pop()?.replace(/\.[^.]+$/, "") ?? "";
178
+ const dir = df.split("/").slice(-2, -1)[0] ?? "";
179
+ return /\.go$/i.test(df) ? [stem, dir] : [stem];
180
+ }).filter(Boolean)
181
+ );
182
+ const moduleAliasesByFile = new Map<string, Set<string>>();
183
+ const directAliasesByFile = new Map<string, Set<string>>();
184
+ const filesWithImportStmts = new Set<string>();
185
+ if (isFunctionTarget) {
186
+ for (const row of depRows) {
187
+ const stmt = String(row.import_statement || "");
188
+ if (!stmt) continue;
189
+ filesWithImportStmts.add(row.file);
190
+ // Python: `from pkg import stem as alias` or `from pkg import stem`
191
+ const fromMatch = stmt.match(/^\s*from\s+([^\s]+)\s+import\s+([\s\S]+)$/);
192
+ if (fromMatch) {
193
+ const items = fromMatch[2]!.replace(/[()]/g, "").split(",");
194
+ for (const rawItem of items) {
195
+ const item = rawItem.trim();
196
+ if (!item) continue;
197
+ const asMatch = item.match(/^([A-Za-z_]\w*)\s+as\s+([A-Za-z_]\w*)$/);
198
+ const orig = asMatch ? asMatch[1]! : item.split(/\s+/)[0]!;
199
+ const bound = asMatch ? asMatch[2]! : orig;
200
+ if (orig === targetContainer && bound !== targetContainer) {
201
+ const set = directAliasesByFile.get(row.file) ?? new Set<string>();
202
+ set.add(bound);
203
+ directAliasesByFile.set(row.file, set);
204
+ } else if (definingStems.has(orig) && !["cls", "self", "this", "super"].includes(bound)) {
205
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
206
+ set.add(bound);
207
+ moduleAliasesByFile.set(row.file, set);
208
+ }
209
+ }
210
+ continue;
211
+ }
212
+ // Python: `import pkg.stem as alias` or `import pkg.stem`
213
+ const pyImportAs = stmt.match(/^\s*import\s+([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z_]\w*))?/);
214
+ if (pyImportAs) {
215
+ const modTail = pyImportAs[1]!.split(".").pop() ?? "";
216
+ const bound = pyImportAs[2] ?? modTail;
217
+ if (definingStems.has(modTail) && !["cls", "self", "this", "super"].includes(bound)) {
218
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
219
+ set.add(bound);
220
+ moduleAliasesByFile.set(row.file, set);
221
+ }
222
+ continue;
223
+ }
224
+ // Go: `import "pkg/dir"` or `import alias "pkg/dir"`
225
+ const goImport = stmt.match(/^\s*(?:import\s+)?(?:([A-Za-z_]\w*)\s+)?"([^"]+)"/);
226
+ if (goImport) {
227
+ const pkgTail = goImport[2]!.split("/").pop() ?? "";
228
+ const bound = goImport[1] ?? pkgTail;
229
+ if (definingStems.has(pkgTail)) {
230
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
231
+ set.add(bound);
232
+ moduleAliasesByFile.set(row.file, set);
233
+ }
234
+ }
235
+ }
236
+ }
237
+
238
+ if (effectiveMethod || nonTsFnCallRegex) {
239
+ for (const filePath of uniqueCallerFiles) {
240
+ if (nonTsFnCallRegex && /\.[cm]?[jt]sx?$/.test(filePath)) continue;
241
+ const moduleAliases = moduleAliasesByFile.get(filePath);
242
+ const directAliases = directAliasesByFile.get(filePath);
243
+ const fallbackPkgAliases = !filesWithImportStmts.has(filePath) && definingStems.size > 0
244
+ ? definingStems
245
+ : undefined;
246
+ const effectiveModuleAliases = moduleAliases && moduleAliases.size > 0 ? moduleAliases : fallbackPkgAliases;
247
+ const qualifiedFnRegex =
248
+ effectiveModuleAliases && effectiveModuleAliases.size > 0
249
+ ? new RegExp(
250
+ `\\b(?:${Array.from(effectiveModuleAliases).map(escapeRegExp).join("|")})\\.${escapeRegExp(targetContainer)}\\s*\\(`
251
+ )
252
+ : null;
253
+ const aliasedDirectFnRegex =
254
+ directAliases && directAliases.size > 0
255
+ ? new RegExp(
256
+ `(?:^|[^.\\w$:])\\b(?:${Array.from(directAliases).map(escapeRegExp).join("|")})\\s*\\(`
257
+ )
258
+ : null;
259
+ try {
260
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
261
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
262
+ if (probeSourcePath(fullPath) === "file") {
263
+ const content = readSourceFile(fullPath);
264
+ const lines = content.split(/\r?\n/);
265
+ for (let i = 0; i < lines.length; i++) {
266
+ const line = lines[i];
267
+ const trimmedLine = line.trim();
268
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
269
+ continue;
270
+ }
271
+ const matched = effectiveMethod
272
+ ? (!isStaticPhpMethod &&
273
+ line.includes(`->${effectiveMethod}(`) &&
274
+ (definingFiles.has(filePath) || !line.includes(`$this->${effectiveMethod}(`))) ||
275
+ (staticOwnerCallRegex
276
+ ? staticOwnerCallRegex.test(line)
277
+ : line.includes(`::${effectiveMethod}(`)) ||
278
+ (!isStaticPhpMethod && line.includes(`.${effectiveMethod}(`))
279
+ : Boolean(
280
+ !nonTsFnDeclRegex?.test(line) &&
281
+ (nonTsFnCallRegex?.test(line) ||
282
+ qualifiedFnRegex?.test(line) ||
283
+ aliasedDirectFnRegex?.test(line))
284
+ );
285
+ if (matched) {
286
+ const lineNum = i + 1;
287
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
288
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
289
+ const key = `${filePath}:${lineNum}:${callerName}`;
290
+ if (!callersMap.has(key)) {
291
+ callersMap.set(key, {
292
+ file: filePath,
293
+ caller: callerName,
294
+ line: lineNum,
295
+ kind: "call",
296
+ domain: domainByFile.get(filePath),
297
+ });
298
+ }
299
+ }
300
+ }
301
+ }
302
+ } catch {
303
+ // Ignore read errors
304
+ }
305
+ }
306
+ }
307
+
308
+ // 4b. Scan same-file (definingFiles outside target declaration range) and same-package/namespace files
309
+ const isLineInsideTargetSpan = (filePath: string, lineNum: number): boolean => {
310
+ const spans = targetSpansByFile.get(filePath);
311
+ if (!spans || spans.length === 0) return false;
312
+ return spans.some((span) => lineNum >= span.start && lineNum <= span.end);
313
+ };
314
+
315
+ const targetIsFunctionOnly =
316
+ !targetMethod &&
317
+ targetSymRows.every((r) => r.kind === "function" || r.kind === "method");
318
+ const escapedMethod = targetMethod ? escapeRegExp(targetMethod) : "";
319
+ const escapedContainer = escapeRegExp(targetContainer);
320
+ const sameFileMethodCallRegex = targetMethod
321
+ ? new RegExp(
322
+ `(?:\\$this->|self::|static::|\\bthis\\.|\\bself\\.|\\b${escapedContainer}::)${escapedMethod}\\s*\\(`
323
+ )
324
+ : null;
325
+ const goReceiverMethodCallRegex = targetMethod
326
+ ? new RegExp(`\\b[A-Za-z_]\\w*\\.${escapedMethod}\\s*\\(`)
327
+ : null;
328
+ const fnCallRegex = !targetMethod
329
+ ? new RegExp(`(?:^|[^.\\w$:])${escapedContainer}\\s*\\(`)
330
+ : null;
331
+ const fnDeclRegex = !targetMethod
332
+ ? new RegExp(`\\b(?:function|func|def|fn)\\s+${escapedContainer}\\b`)
333
+ : null;
334
+ const classUsageRegex = !targetMethod
335
+ ? new RegExp(
336
+ `(?:\\bnew\\s+${escapedContainer}\\b|\\b${escapedContainer}::|&?\\b${escapedContainer}\\s*\\{|\\*?\\b${escapedContainer}\\b)`
337
+ )
338
+ : null;
339
+
340
+ // Same-file call-site scan (outside target symbol's own line_start..line_end)
341
+ for (const filePath of definingFiles) {
342
+ try {
343
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
344
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
345
+ if (probeSourcePath(fullPath) !== "file") continue;
346
+ const content = readSourceFile(fullPath);
347
+ const lines = content.split(/\r?\n/);
348
+ for (let i = 0; i < lines.length; i++) {
349
+ const lineNum = i + 1;
350
+ if (isLineInsideTargetSpan(filePath, lineNum)) continue;
351
+ const line = lines[i];
352
+ const trimmedLine = line.trim();
353
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
354
+ continue;
355
+ }
356
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
357
+ let matched = false;
358
+ if (targetMethod) {
359
+ if (sameFileMethodCallRegex?.test(line)) {
360
+ matched = true;
361
+ } else if (/\.go$/i.test(filePath) && goReceiverMethodCallRegex?.test(line) && enclosing) {
362
+ const recv = enclosing.signature.match(/^func\s*\(\s*(?:[A-Za-z_]\w*\s+)?\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)/);
363
+ if (recv?.[1] === targetContainer) matched = true;
364
+ }
365
+ } else if (targetIsFunctionOnly) {
366
+ if (fnCallRegex?.test(line) && !fnDeclRegex?.test(line)) {
367
+ matched = true;
368
+ }
369
+ } else if (enclosing && classUsageRegex?.test(line)) {
370
+ matched = true;
371
+ }
372
+
373
+ if (matched) {
374
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
375
+ const key = `${filePath}:${lineNum}:${callerName}`;
376
+ if (!callersMap.has(key)) {
377
+ callersMap.set(key, {
378
+ file: filePath,
379
+ caller: callerName,
380
+ line: lineNum,
381
+ kind: "call",
382
+ domain: domainByFile.get(filePath),
383
+ });
384
+ }
385
+ }
386
+ }
387
+ } catch {
388
+ // Ignore read errors
389
+ }
390
+ }
391
+
392
+ // Same-package / same-namespace call-site scan for .go, .php, .java, .cs files without explicit import
393
+ const explicitCallerSet = new Set(uniqueCallerFiles);
394
+ for (const filePath of implicitPackageFiles) {
395
+ if (explicitCallerSet.has(filePath)) continue;
396
+ try {
397
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
398
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
399
+ if (probeSourcePath(fullPath) !== "file") continue;
400
+ const content = readSourceFile(fullPath);
401
+ if (!containerWordRegex.test(content)) continue;
402
+ const lines = content.split(/\r?\n/);
403
+ for (let i = 0; i < lines.length; i++) {
404
+ const lineNum = i + 1;
405
+ const line = lines[i];
406
+ const trimmedLine = line.trim();
407
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
408
+ continue;
409
+ }
410
+ let matched = false;
411
+ if (targetMethod) {
412
+ if (
413
+ line.includes(`->${targetMethod}(`) ||
414
+ line.includes(`::${targetMethod}(`) ||
415
+ line.includes(`.${targetMethod}(`)
416
+ ) {
417
+ matched = true;
418
+ }
419
+ } else if (targetIsFunctionOnly) {
420
+ if (fnCallRegex?.test(line) && !fnDeclRegex?.test(line)) {
421
+ matched = true;
422
+ }
423
+ } else if (classUsageRegex?.test(line) && !/\b(?:class|interface|trait|enum|type|struct)\s+/.test(line)) {
424
+ matched = true;
425
+ }
426
+
427
+ if (matched) {
428
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
429
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
430
+ const key = `${filePath}:${lineNum}:${callerName}`;
431
+ if (!callersMap.has(key)) {
432
+ callersMap.set(key, {
433
+ file: filePath,
434
+ caller: callerName,
435
+ line: lineNum,
436
+ kind: "call",
437
+ domain: domainByFile.get(filePath),
438
+ });
439
+ }
440
+ }
441
+ }
442
+ } catch {
443
+ // Ignore read errors
444
+ }
445
+ }
446
+
447
+ const inboundCallers = Array.from(callersMap.values());
448
+ const affectedFiles = new Set(inboundCallers.map((c) => c.file));
449
+ const distinctDomains = new Set(
450
+ inboundCallers.map((c) => c.domain).filter(Boolean)
451
+ );
452
+
453
+ let riskLevel: "low" | "medium" | "high" = "low";
454
+ if (affectedFiles.size > 5 || distinctDomains.size > 2) {
455
+ riskLevel = "high";
456
+ } else if (affectedFiles.size >= 2 || distinctDomains.size >= 2) {
457
+ riskLevel = "medium";
458
+ }
459
+
460
+ // 5. Determine if symbol exists in index
461
+ const foundInIndex = targetSymRows.length > 0 || depRows.length > 0;
462
+ const warning = foundInIndex
463
+ ? undefined
464
+ : `Symbol '${trimmed}' was not found in Septum index (neither in declared symbols nor tracked dependencies). Risk cannot be assessed without index evidence.`;
465
+
466
+ return {
467
+ target_symbol: trimmed,
468
+ found_in_index: foundInIndex,
469
+ warning,
470
+ impact_summary: {
471
+ total_dependents: affectedFiles.size,
472
+ risk_level: foundInIndex ? riskLevel : "unknown",
473
+ affected_files_count: affectedFiles.size,
474
+ },
475
+ inbound_callers: inboundCallers,
476
+ };
477
+ }
@@ -16,6 +16,8 @@ export interface SuggestionMatch {
16
16
  signature: string;
17
17
  line_start: number;
18
18
  line_end: number;
19
+ start_line?: number;
20
+ end_line?: number;
19
21
  similarity_score: number; // 0.0 - 1.0
20
22
  file_path?: string;
21
23
  }
@@ -36,6 +38,8 @@ export interface SymbolLocationResult {
36
38
  visibility: string;
37
39
  line_start: number;
38
40
  line_end: number;
41
+ start_line?: number;
42
+ end_line?: number;
39
43
  };
40
44
  sibling_methods?: string[];
41
45
  suggestions: SuggestionMatch[];
@@ -156,7 +160,7 @@ export class SymbolLocator {
156
160
  return {
157
161
  ...base, found: true, file_path: exact.file_path, container_name: exact.symbol_ref.container,
158
162
  symbol_ref: exact.symbol_ref,
159
- exact_symbol: { name: exact.name, kind: exact.kind, signature: exact.signature, visibility: exact.visibility, line_start: exact.line_start, line_end: exact.line_end },
163
+ exact_symbol: { name: exact.name, kind: exact.kind, signature: exact.signature, visibility: exact.visibility, line_start: exact.line_start, line_end: exact.line_end, start_line: exact.line_start, end_line: exact.line_end },
160
164
  sibling_methods: details?.sibling_methods,
161
165
  message: `Found exact symbol '${exact.name}' in ${exact.file_path}:${exact.line_start}`,
162
166
  };
@@ -166,19 +170,68 @@ export class SymbolLocator {
166
170
  .filter(s => ["class", "interface", "trait", "struct", "enum"].includes(s.kind)) : [];
167
171
  const owner = owners.length === 1 ? owners[0] : undefined;
168
172
  const siblings = owner ? this.repo.getSymbolDetails(owner.name, { ...selection, reference: owner.symbol_ref, includeDependencies: false })?.sibling_methods : undefined;
173
+ const domainId = selection.domain ? this.repo.getAllDomains().find(d => d.name.toLowerCase() === selection.domain!.toLowerCase())?.id : undefined;
169
174
  const searchable = owner ? this.repo.getSymbolsByFileId(owner.file_id)
170
175
  .filter(s => s.kind === "method" && symbolReference({ ...s, file_path: owner.file_path, indexed_content_hash: owner.indexed_content_hash }).container === owner.name)
171
- .map(s => ({ ...s, file_path: owner.file_path })) : this.repo.getAllSymbolsWithFiles();
172
- const domainId = selection.domain ? this.repo.getAllDomains().find(d => d.name.toLowerCase() === selection.domain!.toLowerCase())?.id : undefined;
173
- const suggestions = searchable
174
- .filter(s => !selection.filePath || s.file_path === selection.filePath)
175
- .filter(s => !selection.domain || this.repo.getFileByPath(s.file_path)?.domain_id === domainId)
176
- .map(s => ({
177
- name: owner ? s.name.split(/::|[.#]/).pop()! : s.name, kind: s.kind, signature: s.signature, line_start: s.line_start, line_end: s.line_end, file_path: s.file_path,
178
- similarity_score: Math.round(Math.max(calculateSimilarity(target, s.name.split(/::|[.#]/).pop()!), calculateSimilarity(parsed.raw, s.name)) * 100) / 100,
179
- }))
180
- .filter(s => s.similarity_score >= 0.3)
181
- .sort((a, b) => b.similarity_score - a.similarity_score).slice(0, 10);
176
+ .map(s => ({ ...s, file_path: owner.file_path }))
177
+ : selection.domain && domainId === undefined
178
+ ? []
179
+ : typeof this.repo.findFuzzySymbolCandidates === "function"
180
+ ? this.repo.findFuzzySymbolCandidates(target, {
181
+ ...(selection.filePath ? { filePath: selection.filePath } : {}),
182
+ ...(domainId !== undefined ? { domainId } : {}),
183
+ limit: 500,
184
+ })
185
+ : this.repo.getAllSymbolsWithFiles({
186
+ ...(selection.filePath ? { filePath: selection.filePath } : {}),
187
+ ...(domainId !== undefined ? { domainId } : {}),
188
+ });
189
+ const charBitmask = (str: string): number => {
190
+ let mask = 0;
191
+ for (let i = 0; i < str.length; i++) {
192
+ const c = str.charCodeAt(i) | 32;
193
+ if (c >= 97 && c <= 122) mask |= 1 << (c - 97);
194
+ }
195
+ return mask;
196
+ };
197
+ const popcount = (n: number): number => {
198
+ let x = n;
199
+ let count = 0;
200
+ while (x) { x &= x - 1; count++; }
201
+ return count;
202
+ };
203
+ const targetMask = charBitmask(target);
204
+ const rawMask = charBitmask(parsed.raw);
205
+ const minOverlap = target.length >= 4 && searchable.length > 500 ? Math.min(2, popcount(targetMask)) : 0;
206
+ const seenNames = new Set<string>();
207
+ const scored: Array<{
208
+ name: string; kind: (typeof searchable)[number]["kind"]; signature: string;
209
+ line_start: number; line_end: number; start_line: number; end_line: number;
210
+ file_path: string; similarity_score: number;
211
+ }> = [];
212
+ for (const s of searchable) {
213
+ if (selection.filePath && s.file_path !== selection.filePath) continue;
214
+ if (minOverlap > 0) {
215
+ const candMask = charBitmask(s.name);
216
+ if (popcount(targetMask & candMask) < minOverlap && popcount(rawMask & candMask) < minOverlap) continue;
217
+ }
218
+ const leaf = s.name.split(/::|[.#]/).pop()!;
219
+ const score = Math.round(Math.max(calculateSimilarity(target, leaf), calculateSimilarity(parsed.raw, s.name)) * 100) / 100;
220
+ if (score < 0.3) continue;
221
+ scored.push({
222
+ name: owner ? leaf : s.name, kind: s.kind, signature: s.signature,
223
+ line_start: s.line_start, line_end: s.line_end, start_line: s.line_start, end_line: s.line_end,
224
+ file_path: s.file_path, similarity_score: score,
225
+ });
226
+ }
227
+ scored.sort((a, b) => b.similarity_score - a.similarity_score);
228
+ const suggestions = [];
229
+ for (const s of scored) {
230
+ if (seenNames.has(s.name)) continue;
231
+ seenNames.add(s.name);
232
+ suggestions.push(s);
233
+ if (suggestions.length >= 10) break;
234
+ }
182
235
  return { ...base, file_path: owner?.file_path, container_name: owner?.name, sibling_methods: siblings, suggestions, message: `Symbol '${parsed.raw}' not found.${suggestions.length ? ` Did you mean '${suggestions[0]!.name}'?` : ""}` };
183
236
  }
184
237
 
@@ -223,13 +276,19 @@ export function calculateSimilarity(source: string, target: string): number {
223
276
  const t1 = tokenize(source);
224
277
  const t2 = tokenize(target);
225
278
  let tokenBonus = 0;
279
+ let sharedTokenCount = 0;
280
+ let exactTokenMatchCount = 0;
226
281
  if (t1.length > 0 && t2.length > 0) {
282
+ const exactTokens = t1.filter((token) => t2.includes(token));
283
+ exactTokenMatchCount = exactTokens.length;
227
284
  const sharedTokens = t1.filter((token) =>
228
285
  t2.some((t) => t.includes(token) || token.includes(t))
229
286
  );
287
+ sharedTokenCount = sharedTokens.length;
230
288
  const allUniqueTokens = new Set([...t1, ...t2]);
231
289
  const jaccard = sharedTokens.length / (allUniqueTokens.size || 1);
232
- tokenBonus = jaccard * 0.35;
290
+ const exactCoverage = exactTokens.length / t1.length;
291
+ tokenBonus = jaccard * 0.35 + (exactTokens.length > 0 ? 0.25 + exactCoverage * 0.2 : 0);
233
292
  }
234
293
 
235
294
  // Damerau-Levenshtein Matrix
@@ -269,8 +328,16 @@ export function calculateSimilarity(source: string, target: string): number {
269
328
 
270
329
  const distance = matrix[len1][len2];
271
330
  const maxLen = Math.max(len1, len2);
272
- const rawSimilarity = 1.0 - distance / maxLen;
331
+ let rawSimilarity = 1.0 - distance / maxLen;
332
+
333
+ // Dampen accidental subsequence matches for short unrelated words against multi-token queries
334
+ if (t1.length > 1 && t2.length > 0 && sharedTokenCount === 0 && !s2.includes(s1) && !s1.includes(s2) && Math.min(len1, len2) / maxLen < 0.65) {
335
+ rawSimilarity *= 0.55;
336
+ }
273
337
 
274
- const totalScore = rawSimilarity + prefixBonus + substringBonus + tokenBonus;
338
+ // Boost exact word-boundary token matches (e.g. "Store" -> "SymbolDetailsStore") above edit-distance noise ("Scope", "close")
339
+ const totalScore = exactTokenMatchCount > 0
340
+ ? Math.max(rawSimilarity + prefixBonus + substringBonus + tokenBonus, 0.72 + (exactTokenMatchCount / t2.length) * 0.2)
341
+ : rawSimilarity + prefixBonus + substringBonus + tokenBonus;
275
342
  return Math.min(1.0, Math.max(0.0, totalScore));
276
343
  }