@dimassetoid/septum-mcp 0.2.1 → 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 (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
@@ -0,0 +1,79 @@
1
+ import { relative, resolve } from "node:path";
2
+ import type { SeptumRepository } from "../database/repository.ts";
3
+ import { computeContentHash } from "../ingestion/hasher.ts";
4
+ import { TopologyDetector } from "../discovery/topology-detector.ts";
5
+ import { SemanticSliceExtractorRegistry, type AdapterExtractionResult } from "../parser/extractors/registry.ts";
6
+ import { SEMANTIC_FINGERPRINT } from "../parser/semantic-revision.ts";
7
+ import { scanSourceFiles, type SourceInventory } from "../resources/source-inventory.ts";
8
+ import { collectSourceSkips, readSourceFile, SOURCE_READ_REVISION, sourceObservationsCurrent } from "../resources/source-files.ts";
9
+ import { assertPathContained } from "./path-resolver.ts";
10
+ import { CallGraphTracer } from "./call-graph-tracer.ts";
11
+
12
+ interface CatalogOptions {
13
+ ignorePatterns: string[];
14
+ signal?: AbortSignal;
15
+ semanticRevision?: string;
16
+ inventoryRevision?: string;
17
+ }
18
+
19
+ export function sliceInputsCurrent(repo: SeptumRepository, root: string, signal?: AbortSignal): boolean {
20
+ try {
21
+ if (repo.getMeta("semantic_extractor_revision") !== SEMANTIC_FINGERPRINT ||
22
+ (!!repo.getMeta("semantic_inputs") && repo.getMeta("semantic_input_revision") !== SOURCE_READ_REVISION) ||
23
+ !sourceObservationsCurrent(root, JSON.parse(repo.getMeta("semantic_observations") || '{"paths":[],"directories":[]}'))) return false;
24
+ const inputs = JSON.parse(repo.getMeta("semantic_inputs") || "[]") as Array<{ path: string; hash: string }>;
25
+ return inputs.every(input => {
26
+ signal?.throwIfAborted();
27
+ assertPathContained(input.path, root, "Semantic source");
28
+ return computeContentHash(readSourceFile(resolve(root, input.path))) === input.hash;
29
+ });
30
+ } catch { signal?.throwIfAborted(); return false; }
31
+ }
32
+
33
+ /** Publish slices and their input evidence together; failed builds retain a dirty catalog. */
34
+ export async function rebuildSliceCatalog(repo: SeptumRepository, root: string, options: CatalogOptions): Promise<void> {
35
+ try {
36
+ const reports: AdapterExtractionResult[] = [];
37
+ let inventory: SourceInventory;
38
+ const extracted = await collectSourceSkips(root, async () => {
39
+ inventory = scanSourceFiles(root, { ignorePatterns: options.ignorePatterns, signal: options.signal });
40
+ const topology = TopologyDetector.detect(root);
41
+ const slices = await SemanticSliceExtractorRegistry.extractAllSlices(root, topology.framework, undefined, options.signal, {
42
+ ignorePatterns: options.ignorePatterns, inventory, onResult: result => reports.push(result),
43
+ });
44
+ // Complement uncovered files only. Reinterpreting an adapter's router file
45
+ // could invent unprefixed routes from mounted framework routers.
46
+ const coveredFiles = new Set<string>();
47
+ for (const slice of slices) {
48
+ if (slice.controller_file) coveredFiles.add(slice.controller_file);
49
+ const chain = JSON.parse(slice.execution_chain_json) as Array<{ stage?: string; file?: string }>;
50
+ for (const node of chain) if (node.stage === "ingress" && node.file) coveredFiles.add(node.file);
51
+ }
52
+ const fallback = new CallGraphTracer(repo, root).traceAllSlices(8, {
53
+ includeInferredControllers: slices.length === 0, excludeEntrypointFiles: coveredFiles,
54
+ });
55
+ return [...slices, ...fallback];
56
+ });
57
+ options.signal?.throwIfAborted();
58
+ if (extracted.skipped.length) {
59
+ repo.setMeta("semantic_skipped_files", JSON.stringify(extracted.skipped));
60
+ const skipped = JSON.parse(repo.getMeta("skipped_files") || "[]") as Array<{ path: string; reason: string }>;
61
+ repo.setMeta("skipped_files", JSON.stringify([...new Map([...skipped, ...extracted.skipped].map(file => [file.path, file])).values()]));
62
+ throw new Error("Semantic extraction incomplete: source read limit exceeded.");
63
+ }
64
+ repo.runInTransaction(() => {
65
+ repo.clearVerticalSlices();
66
+ for (const slice of extracted.value) repo.upsertVerticalSlice(slice);
67
+ repo.setMeta("slices_dirty", "");
68
+ repo.setMeta("semantic_extractor_revision", SEMANTIC_FINGERPRINT);
69
+ repo.setMeta("semantic_inputs", JSON.stringify(extracted.inputs));
70
+ repo.setMeta("semantic_observations", JSON.stringify(extracted.observations));
71
+ repo.setMeta("semantic_input_revision", SOURCE_READ_REVISION);
72
+ repo.setMeta("semantic_skipped_files", "[]");
73
+ repo.setMeta("semantic_adapter_results", JSON.stringify(reports));
74
+ if (options.semanticRevision !== undefined) repo.setMeta("semantic_revision", options.semanticRevision);
75
+ if (options.inventoryRevision !== undefined) repo.setMeta("semantic_inventory", options.inventoryRevision);
76
+ repo.setMeta("semantic_catalog_files", JSON.stringify(inventory.files.map(file => relative(root, file).replace(/\\/g, "/"))));
77
+ });
78
+ } catch (error) { repo.setMeta("slices_dirty", "1"); throw error; }
79
+ }
@@ -0,0 +1,9 @@
1
+ import type { ExecutionChainNode } from "../../types/index.ts";
2
+
3
+ export const SLICE_RELATIONSHIP_LIMITS =
4
+ "Static, partial context. Relation labels describe evidence attached to nodes, not a proven sequential execution path. Imports do not prove calls; static calls do not prove runtime execution. Missing relationship metadata is unknown.";
5
+
6
+ export function formatSliceNode(node: ExecutionChainNode): string {
7
+ const relation = node.relationship;
8
+ return `[${(node.stage || "stage").toUpperCase()}] ${node.symbol} [${relation?.kind ?? "unknown"}; ${relation?.derivation ?? "unknown"}]${node.semantic_analysis ? " [lexical heuristic]" : ""}`;
9
+ }
@@ -0,0 +1,381 @@
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 }>;
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
+ if (resolution.status !== "resolved" || !resolution.targets.some(target => target.files.some(path => definingFiles.has(path)))) continue;
80
+ const clause = statement.importClause;
81
+ if (clause?.name && targetSymRows.some(row => row.signature?.includes("export default"))) { const binding = checker.getSymbolAtLocation(clause.name); if (binding) bindings.add(binding); }
82
+ if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const specifier of clause.namedBindings.elements) {
83
+ if (specifier.isTypeOnly || (specifier.propertyName ?? specifier.name).text !== targetContainer) continue;
84
+ const binding = checker.getSymbolAtLocation(specifier.name); if (binding) bindings.add(binding);
85
+ }
86
+ }
87
+ if (bindings.size === 0) continue;
88
+
89
+ const recordUsage = (expr: ts.Node, usageKind: "call" | "instantiation" | "heritage") => {
90
+ const line = source.getLineAndCharacterOfPosition(expr.getStart(source)).line + 1;
91
+ const enclosing = findEnclosingSymbol(file, line);
92
+ callersMap.set(`${file}:${line}:${usageKind}`, {
93
+ file,
94
+ line,
95
+ caller: enclosing?.name ?? `${file}:${line}`,
96
+ kind: usageKind,
97
+ domain: domainByFile.get(file),
98
+ });
99
+ };
100
+
101
+ const visit = (node: ts.Node) => {
102
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
103
+ recordUsage(node.expression, "call");
104
+ } else if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
105
+ recordUsage(node.expression, "instantiation");
106
+ } else if (ts.isExpressionWithTypeArguments(node) && ts.isHeritageClause(node.parent) && ts.isIdentifier(node.expression) && bindings.has(checker.getSymbolAtLocation(node.expression)!)) {
107
+ recordUsage(node.expression, "heritage");
108
+ }
109
+ ts.forEachChild(node, visit);
110
+ };
111
+ visit(source);
112
+ }
113
+ }
114
+ }
115
+
116
+ for (const row of depRows) {
117
+ const enclosing = findEnclosingSymbol(row.file, row.line_number);
118
+ const callerName = enclosing ? enclosing.name : `${row.file}:${row.line_number}`;
119
+ const key = `${row.file}:${row.line_number}:${callerName}`;
120
+
121
+ if (!callersMap.has(key)) {
122
+ callersMap.set(key, {
123
+ file: row.file,
124
+ caller: callerName,
125
+ line: row.line_number,
126
+ kind: "import",
127
+ domain: row.domain_name ?? undefined,
128
+ });
129
+ }
130
+ }
131
+
132
+ // 4. Scan file content of callers for exact method/function calls
133
+ const targetMethodRow = targetSymRows.find((r) => r.kind === "method");
134
+ const effectiveMethod =
135
+ targetMethod ||
136
+ (targetMethodRow ? (targetMethodRow.name.split("::").pop() ?? "") : "");
137
+ const targetMethodOwnerFull = targetMethodRow?.name.includes("::")
138
+ ? targetMethodRow.name.split("::")[0]
139
+ : targetMethod
140
+ ? targetContainer
141
+ : undefined;
142
+ const targetMethodOwnerShort = targetMethodOwnerFull?.split(/[\\/]/).pop();
143
+ const isStaticPhpMethod =
144
+ Boolean(effectiveMethod) &&
145
+ targetSymRows.length > 0 &&
146
+ targetSymRows.every((r) => /\bstatic\s+function\b/.test(r.signature ?? ""));
147
+ const staticOwnerCallRegex =
148
+ effectiveMethod && targetMethodOwnerShort
149
+ ? new RegExp(
150
+ `\\b(?:${escapeRegExp(targetMethodOwnerShort)}${
151
+ targetMethodOwnerFull && targetMethodOwnerFull !== targetMethodOwnerShort
152
+ ? `|${escapeRegExp(targetMethodOwnerFull)}`
153
+ : ""
154
+ })::${escapeRegExp(effectiveMethod)}\\s*\\(`
155
+ )
156
+ : null;
157
+ const nonTsFnCallRegex =
158
+ !effectiveMethod && targetSymRows.some((r) => r.kind === "function")
159
+ ? new RegExp(`(?:^|[^.\\w$:]|\\.)\\b${escapeRegExp(targetContainer)}\\s*\\(`)
160
+ : null;
161
+ const nonTsFnDeclRegex = nonTsFnCallRegex
162
+ ? new RegExp(`\\b(?:function|func|def|fn)\\s+${escapeRegExp(targetContainer)}\\b`)
163
+ : null;
164
+
165
+ if (effectiveMethod || nonTsFnCallRegex) {
166
+ for (const filePath of uniqueCallerFiles) {
167
+ if (nonTsFnCallRegex && /\.[cm]?[jt]sx?$/.test(filePath)) continue;
168
+ try {
169
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
170
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
171
+ if (probeSourcePath(fullPath) === "file") {
172
+ const content = readSourceFile(fullPath);
173
+ const lines = content.split(/\r?\n/);
174
+ for (let i = 0; i < lines.length; i++) {
175
+ const line = lines[i];
176
+ const trimmedLine = line.trim();
177
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
178
+ continue;
179
+ }
180
+ const matched = effectiveMethod
181
+ ? (!isStaticPhpMethod &&
182
+ line.includes(`->${effectiveMethod}(`) &&
183
+ (definingFiles.has(filePath) || !line.includes(`$this->${effectiveMethod}(`))) ||
184
+ (staticOwnerCallRegex
185
+ ? staticOwnerCallRegex.test(line)
186
+ : line.includes(`::${effectiveMethod}(`)) ||
187
+ (!isStaticPhpMethod && line.includes(`.${effectiveMethod}(`))
188
+ : Boolean(nonTsFnCallRegex?.test(line) && !nonTsFnDeclRegex?.test(line));
189
+ if (matched) {
190
+ const lineNum = i + 1;
191
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
192
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
193
+ const key = `${filePath}:${lineNum}:${callerName}`;
194
+ if (!callersMap.has(key)) {
195
+ callersMap.set(key, {
196
+ file: filePath,
197
+ caller: callerName,
198
+ line: lineNum,
199
+ kind: "call",
200
+ domain: domainByFile.get(filePath),
201
+ });
202
+ }
203
+ }
204
+ }
205
+ }
206
+ } catch {
207
+ // Ignore read errors
208
+ }
209
+ }
210
+ }
211
+
212
+ // 4b. Scan same-file (definingFiles outside target declaration range) and same-package/namespace files
213
+ const isLineInsideTargetSpan = (filePath: string, lineNum: number): boolean => {
214
+ const spans = targetSpansByFile.get(filePath);
215
+ if (!spans || spans.length === 0) return false;
216
+ return spans.some((span) => lineNum >= span.start && lineNum <= span.end);
217
+ };
218
+
219
+ const targetIsFunctionOnly =
220
+ !targetMethod &&
221
+ targetSymRows.every((r) => r.kind === "function" || r.kind === "method");
222
+ const escapedMethod = targetMethod ? escapeRegExp(targetMethod) : "";
223
+ const escapedContainer = escapeRegExp(targetContainer);
224
+ const sameFileMethodCallRegex = targetMethod
225
+ ? new RegExp(
226
+ `(?:\\$this->|self::|static::|\\bthis\\.|\\bself\\.|\\b${escapedContainer}::)${escapedMethod}\\s*\\(`
227
+ )
228
+ : null;
229
+ const goReceiverMethodCallRegex = targetMethod
230
+ ? new RegExp(`\\b[A-Za-z_]\\w*\\.${escapedMethod}\\s*\\(`)
231
+ : null;
232
+ const fnCallRegex = !targetMethod
233
+ ? new RegExp(`(?:^|[^.\\w$:])${escapedContainer}\\s*\\(`)
234
+ : null;
235
+ const fnDeclRegex = !targetMethod
236
+ ? new RegExp(`\\b(?:function|func|def|fn)\\s+${escapedContainer}\\b`)
237
+ : null;
238
+ const classUsageRegex = !targetMethod
239
+ ? new RegExp(
240
+ `(?:\\bnew\\s+${escapedContainer}\\b|\\b${escapedContainer}::|&?\\b${escapedContainer}\\s*\\{|\\*?\\b${escapedContainer}\\b)`
241
+ )
242
+ : null;
243
+
244
+ // Same-file call-site scan (outside target symbol's own line_start..line_end)
245
+ for (const filePath of definingFiles) {
246
+ try {
247
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
248
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
249
+ if (probeSourcePath(fullPath) !== "file") continue;
250
+ const content = readSourceFile(fullPath);
251
+ const lines = content.split(/\r?\n/);
252
+ for (let i = 0; i < lines.length; i++) {
253
+ const lineNum = i + 1;
254
+ if (isLineInsideTargetSpan(filePath, lineNum)) continue;
255
+ const line = lines[i];
256
+ const trimmedLine = line.trim();
257
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
258
+ continue;
259
+ }
260
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
261
+ let matched = false;
262
+ if (targetMethod) {
263
+ if (sameFileMethodCallRegex?.test(line)) {
264
+ matched = true;
265
+ } else if (/\.go$/i.test(filePath) && goReceiverMethodCallRegex?.test(line) && enclosing) {
266
+ const recv = enclosing.signature.match(/^func\s*\(\s*(?:[A-Za-z_]\w*\s+)?\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)/);
267
+ if (recv?.[1] === targetContainer) matched = true;
268
+ }
269
+ } else if (targetIsFunctionOnly) {
270
+ if (fnCallRegex?.test(line) && !fnDeclRegex?.test(line)) {
271
+ matched = true;
272
+ }
273
+ } else if (enclosing && classUsageRegex?.test(line)) {
274
+ matched = true;
275
+ }
276
+
277
+ if (matched) {
278
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
279
+ const key = `${filePath}:${lineNum}:${callerName}`;
280
+ if (!callersMap.has(key)) {
281
+ callersMap.set(key, {
282
+ file: filePath,
283
+ caller: callerName,
284
+ line: lineNum,
285
+ kind: "call",
286
+ domain: domainByFile.get(filePath),
287
+ });
288
+ }
289
+ }
290
+ }
291
+ } catch {
292
+ // Ignore read errors
293
+ }
294
+ }
295
+
296
+ // Same-package / same-namespace call-site scan for .go, .php, .java, .cs files without explicit import
297
+ const explicitCallerSet = new Set(uniqueCallerFiles);
298
+ for (const filePath of implicitPackageFiles) {
299
+ if (explicitCallerSet.has(filePath)) continue;
300
+ try {
301
+ const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
302
+ if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
303
+ if (probeSourcePath(fullPath) !== "file") continue;
304
+ const content = readSourceFile(fullPath);
305
+ if (!containerWordRegex.test(content)) continue;
306
+ const lines = content.split(/\r?\n/);
307
+ for (let i = 0; i < lines.length; i++) {
308
+ const lineNum = i + 1;
309
+ const line = lines[i];
310
+ const trimmedLine = line.trim();
311
+ if (!trimmedLine || trimmedLine.startsWith("//") || trimmedLine.startsWith("#") || trimmedLine.startsWith("*")) {
312
+ continue;
313
+ }
314
+ let matched = false;
315
+ if (targetMethod) {
316
+ if (
317
+ line.includes(`->${targetMethod}(`) ||
318
+ line.includes(`::${targetMethod}(`) ||
319
+ line.includes(`.${targetMethod}(`)
320
+ ) {
321
+ matched = true;
322
+ }
323
+ } else if (targetIsFunctionOnly) {
324
+ if (fnCallRegex?.test(line) && !fnDeclRegex?.test(line)) {
325
+ matched = true;
326
+ }
327
+ } else if (classUsageRegex?.test(line) && !/\b(?:class|interface|trait|enum|type|struct)\s+/.test(line)) {
328
+ matched = true;
329
+ }
330
+
331
+ if (matched) {
332
+ const enclosing = findEnclosingSymbol(filePath, lineNum);
333
+ const callerName = enclosing ? enclosing.name : `${filePath}:${lineNum}`;
334
+ const key = `${filePath}:${lineNum}:${callerName}`;
335
+ if (!callersMap.has(key)) {
336
+ callersMap.set(key, {
337
+ file: filePath,
338
+ caller: callerName,
339
+ line: lineNum,
340
+ kind: "call",
341
+ domain: domainByFile.get(filePath),
342
+ });
343
+ }
344
+ }
345
+ }
346
+ } catch {
347
+ // Ignore read errors
348
+ }
349
+ }
350
+
351
+ const inboundCallers = Array.from(callersMap.values());
352
+ const affectedFiles = new Set(inboundCallers.map((c) => c.file));
353
+ const distinctDomains = new Set(
354
+ inboundCallers.map((c) => c.domain).filter(Boolean)
355
+ );
356
+
357
+ let riskLevel: "low" | "medium" | "high" = "low";
358
+ if (affectedFiles.size > 5 || distinctDomains.size > 2) {
359
+ riskLevel = "high";
360
+ } else if (affectedFiles.size >= 2 || distinctDomains.size >= 2) {
361
+ riskLevel = "medium";
362
+ }
363
+
364
+ // 5. Determine if symbol exists in index
365
+ const foundInIndex = targetSymRows.length > 0 || depRows.length > 0;
366
+ const warning = foundInIndex
367
+ ? undefined
368
+ : `Symbol '${trimmed}' was not found in Septum index (neither in declared symbols nor tracked dependencies). Risk cannot be assessed without index evidence.`;
369
+
370
+ return {
371
+ target_symbol: trimmed,
372
+ found_in_index: foundInIndex,
373
+ warning,
374
+ impact_summary: {
375
+ total_dependents: inboundCallers.length,
376
+ risk_level: foundInIndex ? riskLevel : "unknown",
377
+ affected_files_count: affectedFiles.size,
378
+ },
379
+ inbound_callers: inboundCallers,
380
+ };
381
+ }