@dimassetoid/septum-mcp 0.3.0 → 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 (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  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 +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +253 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -1,7 +1,8 @@
1
- import { ImportResolver } from "./import-resolver.ts";
1
+ import { discoverDeclarativeRoutesFromFiles, type DiscoveredRoute } from "../discovery/declarative-routes.ts";
2
2
  import { readOptionalSourceFile } from "../resources/source-files.ts";
3
- import { existsSync, readFileSync } from "node:fs";
4
- import { dirname, join, normalize, relative, resolve } from "node:path";
3
+ import { ImportCandidateResolver } from "./import-candidates.ts";
4
+ import { existsSync } from "node:fs";
5
+ import { relative, resolve } from "node:path";
5
6
  import type {
6
7
  ExecutionChainNode,
7
8
  FileRecord,
@@ -9,21 +10,13 @@ import type {
9
10
  VerticalSliceRecord,
10
11
  } from "../../types/index.ts";
11
12
  import type { SeptumRepository } from "../database/repository.ts";
13
+ import { detectPipelineStage, extractImportedSymbolNames as extractImportedNames } from "./call-graph-helpers.ts";
14
+ import { traverseAstMethodGraph } from "./ast-method-tracer.ts";
15
+ import { traversePolyglotMethodDependencies } from "./polyglot-slice-tracer.ts";
12
16
 
13
- export interface DiscoveredRoute {
14
- method: string;
15
- uri: string;
16
- file: string;
17
- line: number;
18
- middlewareSymbols: string[];
19
- handlerSymbol?: string;
20
- handlerClass?: string;
21
- handlerMethod?: string;
22
- }
17
+ export type { DiscoveredRoute };
23
18
 
24
19
  export class CallGraphTracer {
25
- private importEvidence?: ReturnType<SeptumRepository["getImportRelationships"]>;
26
- private evidenceByFile = new Map<string, ReturnType<SeptumRepository["getImportRelationships"]>>();
27
20
  private fileMapByNormPath: Map<string, FileRecord> = new Map();
28
21
  private fileMapById: Map<number, FileRecord> = new Map();
29
22
  private symbolsByFileId: Map<number, SymbolRecord[]> = new Map();
@@ -32,7 +25,11 @@ export class CallGraphTracer {
32
25
  Array<{ target: string; statement: string; line_number: number; is_external: boolean }>
33
26
  > = new Map();
34
27
 
35
- constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd()) {}
28
+ private readonly importCandidates: ImportCandidateResolver;
29
+
30
+ constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd()) {
31
+ this.importCandidates = new ImportCandidateResolver(repo, projectRoot, this.fileMapByNormPath, path => this.fileForPath(path));
32
+ }
36
33
 
37
34
  private fileForPath(path: string): FileRecord | undefined {
38
35
  const key = this.normalizeFilePath(path);
@@ -56,14 +53,13 @@ export class CallGraphTracer {
56
53
  }
57
54
 
58
55
  /**
59
- * Initializes internal fast lookup maps from SQLite repository data.
56
+ * Initializes file lookup maps from SQLite repository data.
57
+ * Symbols and dependencies are loaded lazily per file on demand to keep memory bounded on large repos.
60
58
  */
61
59
  public initMaps(): void {
62
60
  this.fileMapByNormPath.clear(); this.fileMapById.clear();
63
- this.symbolsByFileId.clear(); this.dependenciesByFileId.clear(); this.evidenceByFile.clear();
64
- const allSymbolsWithFiles = this.repo.getAllSymbolsWithFiles();
65
- const allDeps = this.repo.getAllDependenciesWithDomains();
66
- this.importEvidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.projectRoot) : undefined;
61
+ this.symbolsByFileId.clear(); this.dependenciesByFileId.clear();
62
+ this.importCandidates.reset();
67
63
 
68
64
  // Map files
69
65
  const allFiles = this.repo.getAllFiles();
@@ -72,185 +68,106 @@ export class CallGraphTracer {
72
68
  this.fileMapByNormPath.set(norm, f);
73
69
  this.fileMapById.set(f.id, f);
74
70
  }
75
-
76
- // Map symbols
77
- for (const s of allSymbolsWithFiles) {
78
- const existing = this.symbolsByFileId.get(s.file_id) || [];
79
- existing.push(s);
80
- this.symbolsByFileId.set(s.file_id, existing);
81
- }
82
-
83
- // Map dependencies
84
- for (const d of allDeps) {
85
- const file = this.fileMapByNormPath.get(this.normalizeFilePath(d.source_file));
86
- if (file) {
87
- const existing = this.dependenciesByFileId.get(file.id) || [];
88
- existing.push({
89
- target: d.target,
90
- statement: d.statement,
91
- line_number: d.line_number,
92
- is_external: d.is_external,
93
- });
94
- this.dependenciesByFileId.set(file.id, existing);
95
- }
96
- }
97
71
  }
98
72
 
99
- /**
100
- * Discover declarative HTTP routes from known route/router files in the repository.
101
- */
102
- public discoverDeclarativeRoutes(): DiscoveredRoute[] {
103
- const discovered: DiscoveredRoute[] = [];
104
-
105
- for (const [normPath, file] of this.fileMapByNormPath.entries()) {
106
- const isRouteFile =
107
- file.archetype === "route" ||
108
- /routes?|router|endpoints?/i.test(normPath) ||
109
- /\.(routes?|router)\.[tj]sx?$/i.test(normPath);
110
-
111
- if (!isRouteFile) continue;
112
-
113
- const fullPath = resolve(this.projectRoot, file.path);
114
- if (!existsSync(fullPath)) continue;
115
-
116
- try {
117
- const content = readOptionalSourceFile(fullPath, "utf-8");
118
- const lines = content.split("\n");
119
-
120
- for (let i = 0; i < lines.length; i++) {
121
- const line = lines[i];
122
- // Pattern: router.post('/api/orders', validateMiddleware, controller.action)
123
- // or app.get('/orders', handler)
124
- const match = line.match(
125
- /(?:router|app|server|api)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(.+)\)/i
126
- );
127
-
128
- if (match) {
129
- const method = match[1].toUpperCase();
130
- const uri = match[2];
131
- const rawArgs = match[3];
132
-
133
- const argTokens = rawArgs
134
- .split(",")
135
- .map((t) => t.trim())
136
- .filter((t) => t.length > 0 && !t.startsWith("//"));
137
-
138
- const middlewareSymbols: string[] = [];
139
- let handlerSymbol: string | undefined;
140
- let handlerClass: string | undefined;
141
- let handlerMethod: string | undefined;
142
-
143
- if (argTokens.length === 1) {
144
- handlerSymbol = argTokens[0];
145
- } else if (argTokens.length > 1) {
146
- handlerSymbol = argTokens[argTokens.length - 1];
147
- middlewareSymbols.push(...argTokens.slice(0, argTokens.length - 1));
148
- }
149
-
150
- if (handlerSymbol) {
151
- // Extract Class.method or classInstance.method
152
- const parts = handlerSymbol.split(".");
153
- if (parts.length === 2) {
154
- handlerClass = parts[0];
155
- handlerMethod = parts[1];
156
- } else if (handlerSymbol.includes("::")) {
157
- const colParts = handlerSymbol.split("::");
158
- handlerClass = colParts[0];
159
- handlerMethod = colParts[1];
160
- }
161
- }
162
-
163
- discovered.push({
164
- method,
165
- uri,
166
- file: file.path,
167
- line: i + 1,
168
- middlewareSymbols,
169
- handlerSymbol,
170
- handlerClass,
171
- handlerMethod,
172
- });
173
- }
174
- }
175
- } catch (err: unknown) {
176
- const msg = err instanceof Error ? err.message : String(err);
177
- console.error(`[Septum CallGraph Warning] Route discovery failed for ${file.path}: ${msg}`);
178
- }
179
- }
180
-
181
- return discovered;
73
+ /** Legacy route modules sometimes receive their router as an ambient global. */
74
+ public discoverDeclarativeRoutes(excluded?: ReadonlySet<string>): DiscoveredRoute[] {
75
+ return discoverDeclarativeRoutesFromFiles(this.projectRoot, this.fileMapByNormPath, excluded);
182
76
  }
183
77
 
184
- /**
185
- * Build execution chains for all discovered entrypoints and controller actions.
186
- */
187
- public traceAllSlices(maxDepth: number = 5, options: { includeInferredControllers?: boolean; excludeEntrypointFiles?: ReadonlySet<string> } = {}): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
78
+ public traceAllSlices(maxDepth = 5, options: { includeInferredControllers?: boolean; excludeEntrypointFiles?: ReadonlySet<string> } = {}): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
188
79
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
189
80
  this.initMaps();
190
- const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
191
- const declarativeRoutes = this.discoverDeclarativeRoutes();
192
-
193
- // 1. Trace from declarative routes
194
- for (const route of declarativeRoutes) {
195
- if (options.excludeEntrypointFiles?.has(route.file)) continue;
81
+ const coveredFiles = options.excludeEntrypointFiles;
82
+ const slices = this.discoverDeclarativeRoutes(coveredFiles).map(route => {
196
83
  const chain = this.traceChainFromRoute(route, effectiveMaxDepth);
197
- if (chain.length > 0) {
198
- const sliceRecord = this.buildSliceRecordFromChain(
199
- route.method,
200
- route.uri,
201
- chain,
202
- "clean"
203
- );
204
- slices.push(sliceRecord);
205
- }
206
- }
207
-
84
+ chain[0].relationship = { kind: "route_binding", derivation: "inferred", reason: "ambient_router_convention" };
85
+ return this.buildSliceRecordFromChain(route.method, route.uri, chain, "clean");
86
+ });
208
87
  if (options.includeInferredControllers === false) return slices;
209
-
88
+ const coveredActions = new Set<string>();
89
+ for (const s of slices) {
90
+ if (s.controller_file) coveredActions.add(`${s.controller_file}\0${s.action_name.toLowerCase()}`);
91
+ }
210
92
  // 2. Trace controllers if routes were not explicitly bound or found
211
93
  for (const [normPath, file] of this.fileMapByNormPath.entries()) {
94
+ // Python web frameworks manage routing declaratively via URLconf (Django) or decorators (FastAPI/Flask).
95
+ // Do not synthesize speculative HTTP endpoints on Python view/handler files by convention.
96
+ if (normPath.endsWith(".py")) continue;
97
+
212
98
  const isController =
213
99
  file.archetype === "controller" ||
214
100
  /controller/i.test(normPath) ||
215
101
  normPath.endsWith("Controller.ts") ||
216
102
  normPath.endsWith("Controller.js");
217
103
 
218
- if (!isController) continue;
104
+ if (!isController || coveredFiles?.has(file.path)) continue;
219
105
 
220
106
  const symbols = this.fileSymbols(file.id);
221
107
  const methods = symbols.filter((s) => s.kind === "method" || s.kind === "function");
108
+ if (methods.length === 0) continue;
109
+
110
+ const defaultCtrlName =
111
+ symbols.find((s) => s.kind === "class")?.name ||
112
+ file.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
113
+ "Controller";
114
+
115
+ // Outbound dependencies depend only on controllerFile, not on individual methods;
116
+ // compute once per controller file instead of repeating BFS per method.
117
+ const outboundChain: ExecutionChainNode[] = [
118
+ { stage: "ingress", symbol: "", description: "" },
119
+ { stage: "controller", symbol: "", description: "" },
120
+ ];
121
+ this.traverseOutboundDependencies(file, outboundChain, effectiveMaxDepth);
122
+ const outboundTail = outboundChain.slice(2);
222
123
 
223
124
  for (const m of methods) {
125
+ const parts = m.name.split("::");
126
+ const action = parts.pop()!;
224
127
  // Skip constructors or private helpers
225
- if (m.name === "constructor" || m.name.startsWith("_")) continue;
226
-
227
- // Check if this method was already covered by declarative routes
228
- const alreadyCovered = slices.some(
229
- (s) =>
230
- s.controller_file === file.path &&
231
- s.action_name.toLowerCase() === m.name.toLowerCase()
232
- );
233
- if (alreadyCovered) continue;
234
-
235
- const chain = this.traceChainFromController(file, m, effectiveMaxDepth);
236
- if (chain.length > 0) {
237
- const defaultMethod = /create|store|save|add/i.test(m.name)
238
- ? "POST"
239
- : /update|edit|patch/i.test(m.name)
240
- ? "PUT"
241
- : /delete|remove|destroy/i.test(m.name)
242
- ? "DELETE"
243
- : "GET";
244
-
245
- const inferredUri = this.inferRouteUri(file.path, m.name);
246
- const sliceRecord = this.buildSliceRecordFromChain(
128
+ if (action === "constructor" || action.startsWith("_")) continue;
129
+
130
+ const actionKey = `${file.path}\0${action.toLowerCase()}`;
131
+ if (coveredActions.has(actionKey)) continue;
132
+
133
+ const ctrlName = parts.pop() || defaultCtrlName;
134
+ const defaultMethod = /create|store|save|add/i.test(action)
135
+ ? "POST"
136
+ : /update|edit|patch/i.test(action)
137
+ ? "PUT"
138
+ : /delete|remove|destroy/i.test(action)
139
+ ? "DELETE"
140
+ : "GET";
141
+ const inferredUri = this.inferRouteUri(file.path, action);
142
+
143
+ const chain: ExecutionChainNode[] = [
144
+ {
145
+ stage: "ingress",
146
+ symbol: `${defaultMethod} ${inferredUri}`,
147
+ file: file.path,
148
+ line: m.line_start,
149
+ relationship: { kind: "route_binding", derivation: "inferred", reason: "controller_convention" },
150
+ description: `Inferred Ingress: ${defaultMethod} ${inferredUri}`,
151
+ },
152
+ {
153
+ stage: "controller",
154
+ symbol: `${ctrlName}::${action}`,
155
+ file: file.path,
156
+ line: m.line_start,
157
+ description: `Controller Action: ${ctrlName}::${action}`,
158
+ },
159
+ ...outboundTail,
160
+ ];
161
+
162
+ coveredActions.add(actionKey);
163
+ slices.push(
164
+ this.buildSliceRecordFromChain(
247
165
  defaultMethod,
248
166
  inferredUri,
249
167
  chain,
250
168
  "clean"
251
- );
252
- slices.push(sliceRecord);
253
- }
169
+ )
170
+ );
254
171
  }
255
172
  }
256
173
 
@@ -343,18 +260,20 @@ export class CallGraphTracer {
343
260
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
344
261
  const chain: ExecutionChainNode[] = [];
345
262
  const syms = this.fileSymbols(controllerFile.id);
346
- const ctrlName =
263
+ const parts = method.name.split("::");
264
+ const action = parts.pop()!;
265
+ const ctrlName = parts.pop() ||
347
266
  syms.find((s) => s.kind === "class")?.name ||
348
267
  controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
349
268
  "Controller";
350
269
 
351
270
  // Stage 1: Ingress (inferred)
352
- const inferredUri = this.inferRouteUri(controllerFile.path, method.name);
353
- const defaultMethod = /create|store|save|add/i.test(method.name)
271
+ const inferredUri = this.inferRouteUri(controllerFile.path, action);
272
+ const defaultMethod = /create|store|save|add/i.test(action)
354
273
  ? "POST"
355
- : /update|edit|patch/i.test(method.name)
274
+ : /update|edit|patch/i.test(action)
356
275
  ? "PUT"
357
- : /delete|remove|destroy/i.test(method.name)
276
+ : /delete|remove|destroy/i.test(action)
358
277
  ? "DELETE"
359
278
  : "GET";
360
279
 
@@ -363,16 +282,17 @@ export class CallGraphTracer {
363
282
  symbol: `${defaultMethod} ${inferredUri}`,
364
283
  file: controllerFile.path,
365
284
  line: method.line_start,
285
+ relationship: { kind: "route_binding", derivation: "inferred", reason: "controller_convention" },
366
286
  description: `Inferred Ingress: ${defaultMethod} ${inferredUri}`,
367
287
  });
368
288
 
369
289
  // Stage 3: Controller
370
290
  chain.push({
371
291
  stage: "controller",
372
- symbol: `${ctrlName}::${method.name}`,
292
+ symbol: `${ctrlName}::${action}`,
373
293
  file: controllerFile.path,
374
294
  line: method.line_start,
375
- description: `Controller Action: ${ctrlName}::${method.name}`,
295
+ description: `Controller Action: ${ctrlName}::${action}`,
376
296
  });
377
297
 
378
298
  // Forward reachability BFS
@@ -417,10 +337,14 @@ export class CallGraphTracer {
417
337
  }
418
338
 
419
339
  const symbols = this.fileSymbols(startFile.id);
420
- const methodSymbol = symbols.find(
340
+ const candidates = symbols.filter(
421
341
  (s) => (s.kind === "method" || s.kind === "function") && (s.name.endsWith(`::${actionName}`) || s.name.endsWith(`@${actionName}`) || s.name === actionName)
422
342
  );
423
343
 
344
+ const line = existingChain.find(node => node.stage === "controller" && node.file === controllerFilePath)?.line;
345
+ const matches = line ? candidates.filter(s => s.line_start <= line && line <= s.line_end) : [];
346
+ if (candidates.length > 1 && matches.length !== 1) return existingChain;
347
+ const methodSymbol = matches[0] ?? candidates[0];
424
348
  if (!methodSymbol) {
425
349
  return this.expandChainFromFile(controllerFilePath, existingChain, maxDepth);
426
350
  }
@@ -436,13 +360,16 @@ export class CallGraphTracer {
436
360
  const lines = fileContent.split(/\r?\n/);
437
361
  const start = Math.max(0, methodSymbol.line_start - 1);
438
362
  const end = Math.min(lines.length, methodSymbol.line_end);
439
- methodBody = this.scopeWithInjectedTypes(fileContent, lines.slice(start, end).join("\n"));
363
+ const owner = symbols.find(s => s.kind === "class" && s.line_start <= methodSymbol.line_start && s.line_end >= methodSymbol.line_end);
364
+ const ownerSource = owner ? lines.slice(owner.line_start - 1, owner.line_end).join("\n") : fileContent;
365
+ methodBody = this.scopeWithInjectedTypes(ownerSource, lines.slice(start, end).join("\n"));
440
366
  } catch {
441
367
  return this.expandChainFromFile(controllerFilePath, existingChain, maxDepth);
442
368
  }
443
369
 
444
370
  const chain = [...existingChain];
445
- this.traverseMethodScopedDependencies(startFile, methodBody, methodSymbol, chain, effectiveMaxDepth);
371
+ // Method-scoped vertical slices stop at 1-hop direct collaborators (Option A).
372
+ this.traverseMethodScopedDependencies(startFile, methodBody, methodSymbol, chain, 1);
446
373
  return chain;
447
374
  }
448
375
 
@@ -563,78 +490,49 @@ export class CallGraphTracer {
563
490
  chain: ExecutionChainNode[],
564
491
  maxDepth: number = 5
565
492
  ): void {
566
- const visitedFiles = new Set<string>();
567
- visitedFiles.add(startFile.path);
568
-
569
- const deps = this.fileDependencies(startFile.id);
570
- const scopeText = (methodSymbol.signature || "") + "\n" + methodBody;
571
-
572
- for (const dep of deps) {
573
- if (/^\s*(?:import|export)\s+type\b/.test(dep.statement)) continue;
574
- if (chain.length >= CallGraphTracer.MAX_CHAIN_NODES) break;
575
- const importedNames = this.extractImportedSymbolNames(dep.statement);
576
- const baseTarget = dep.target.split(/[\/\\]/).pop()?.replace(/\.[^.]+$/, "") || "";
577
-
578
- // Only include if imported symbol or target name is referenced in the method scope (signature + body)
579
- const isReferenced =
580
- (importedNames.length > 0 &&
581
- importedNames.some((name) => {
582
- const camel = name.charAt(0).toLowerCase() + name.slice(1);
583
- return scopeText.includes(name) || scopeText.includes(camel);
584
- })) ||
585
- (baseTarget.length > 0 &&
586
- (scopeText.includes(baseTarget) ||
587
- scopeText.includes(baseTarget.charAt(0).toLowerCase() + baseTarget.slice(1))));
588
-
589
- if (!isReferenced) {
590
- // Drop uncalled static import to eliminate cognitive noise and payload bloat
591
- continue;
592
- }
593
-
594
- const resolvedFiles = this.repo.getMeta?.("workspace_root")
595
- ? this.resolveImportTargets(startFile.path, dep.target)
596
- : dep.is_external
597
- ? []
598
- : [this.resolveImportToFile(startFile.path, dep.target)].filter((file): file is FileRecord => !!file);
599
-
600
- for (const resolvedFile of resolvedFiles) {
601
- if (!resolvedFile || visitedFiles.has(resolvedFile.path)) continue;
602
- visitedFiles.add(resolvedFile.path);
603
-
604
- const stage = this.detectStage(resolvedFile.path, resolvedFile.archetype);
605
- const fileSymbols = this.fileSymbols(resolvedFile.id);
606
- const mainSymbol = this.resolveExecutableSymbol(fileSymbols, importedNames);
607
- if (!mainSymbol) {
608
- continue;
609
- }
610
-
611
- const symbolDisplay = mainSymbol.name;
612
-
613
- const shortSymbolDisplay = symbolDisplay.split(/[\\:]/).pop();
614
- const existingNode = chain.find(
615
- (c) =>
616
- (c.file && c.file === resolvedFile.path) ||
617
- (c.stage === stage &&
618
- (c.symbol === symbolDisplay || c.symbol.split(/[\\:]/).pop() === shortSymbolDisplay))
619
- );
620
-
621
- if (!existingNode) {
622
- chain.push({
623
- stage,
624
- symbol: symbolDisplay,
625
- file: resolvedFile.path,
626
- line: mainSymbol.line_start || 1,
627
- description: `${stage.toUpperCase()} (referenced import): ${symbolDisplay}`,
628
- relationship: {
629
- kind: "imports",
630
- derivation: "source",
631
- source: { file: startFile.path, line: dep.line_number, statement: dep.statement },
632
- reason: "import referenced in method scope; not proof of a call",
633
- },
634
- });
635
- }
636
- }
637
- }
493
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
494
+ const hasWorkspaceRoot = Boolean(this.repo.getMeta?.("workspace_root"));
495
+ if (/\.[cm]?[jt]sx?$/i.test(startFile.path)) {
496
+ traverseAstMethodGraph(
497
+ {
498
+ projectRoot: this.projectRoot,
499
+ maxChainNodes: CallGraphTracer.MAX_CHAIN_NODES,
500
+ hasWorkspaceRoot,
501
+ fileSymbols: (fileId) => this.fileSymbols(fileId),
502
+ fileDependencies: (fileId) => this.fileDependencies(fileId),
503
+ resolveImportTargets: (from, spec) => this.resolveImportTargets(from, spec),
504
+ resolveImportToFile: (from, spec) => this.resolveImportToFile(from, spec),
505
+ resolveExecutableSymbol: (symbols, names) => this.resolveExecutableSymbol(symbols, names),
506
+ isExecutableSymbol: (symbol) => this.isExecutableSymbol(symbol),
507
+ detectStage: (filePath, archetype) => this.detectStage(filePath, archetype),
508
+ },
509
+ startFile,
510
+ methodSymbol,
511
+ chain,
512
+ effectiveMaxDepth
513
+ );
514
+ return;
515
+ }
516
+
517
+ traversePolyglotMethodDependencies(
518
+ {
519
+ projectRoot: this.projectRoot,
520
+ maxChainNodes: CallGraphTracer.MAX_CHAIN_NODES,
521
+ hasWorkspaceRoot,
522
+ fileSymbols: (fileId) => this.fileSymbols(fileId),
523
+ fileDependencies: (fileId) => this.fileDependencies(fileId),
524
+ extractImportedSymbolNames: (stmt) => this.extractImportedSymbolNames(stmt),
525
+ resolveImportTargets: (from, target) => this.resolveImportTargets(from, target),
526
+ resolveImportToFile: (from, target) => this.resolveImportToFile(from, target),
527
+ resolveExecutableSymbol: (symbols, names) => this.resolveExecutableSymbol(symbols, names),
528
+ isExecutableSymbol: (symbol) => this.isExecutableSymbol(symbol),
529
+ detectStage: (filePath, archetype) => this.detectStage(filePath, archetype),
530
+ },
531
+ startFile,
532
+ methodBody,
533
+ methodSymbol,
534
+ chain
535
+ );
638
536
  }
639
537
 
640
538
  /**
@@ -725,165 +623,22 @@ export class CallGraphTracer {
725
623
  }
726
624
 
727
625
  private extractImportedSymbolNames(statement: string): string[] {
728
- if (!statement) return [];
729
- const names = new Set<string>();
730
- const braceMatch = statement.match(/\{([^}]+)\}/);
731
- if (braceMatch) {
732
- for (const spec of braceMatch[1].split(",")) {
733
- const cleaned = spec.trim().replace(/^type\s+/, "");
734
- const parts = cleaned.split(/\s+as\s+/);
735
- for (const p of parts) {
736
- const id = p.trim();
737
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(id)) names.add(id);
738
- }
739
- }
740
- }
741
- const defaultMatch = statement.match(/^\s*import\s+(?:type\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/);
742
- if (defaultMatch) names.add(defaultMatch[1]);
743
- const pyMatch = statement.match(/\bfrom\s+[^\s]+\s+import\s+([^;(\n]+)/);
744
- if (pyMatch) {
745
- for (const spec of pyMatch[1].split(",")) {
746
- const parts = spec.trim().split(/\s+as\s+/);
747
- const id = (parts[0] || "").trim();
748
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) names.add(id);
749
- }
750
- }
751
- const phpMatch = statement.match(/^\s*use\s+(?:function\s+|const\s+)?[A-Za-z0-9_\\]+\\([A-Za-z0-9_]+)/);
752
- if (phpMatch) names.add(phpMatch[1]);
753
- return Array.from(names);
626
+ return extractImportedNames(statement);
754
627
  }
755
628
 
756
629
  /**
757
630
  * Detect generic pipeline stage from file path and archetype.
758
631
  */
759
632
  public detectStage(filePath: string, archetype: string): string {
760
- const norm = filePath.toLowerCase();
761
-
762
- if (
763
- archetype === "validation" ||
764
- archetype === "dto" ||
765
- /validation|middleware|dto|request|schema/i.test(norm)
766
- ) {
767
- return "validation";
768
- }
769
-
770
- if (archetype === "controller" || /controller|handler/i.test(norm)) {
771
- return "controller";
772
- }
773
-
774
- if (
775
- archetype === "service" ||
776
- archetype === "use_case" ||
777
- /use-?cases?|interactor|application|workflow/i.test(norm)
778
- ) {
779
- return "use_case";
780
- }
781
-
782
- if (
783
- archetype === "model" ||
784
- archetype === "entity" ||
785
- /domain|entities|entity|aggregate/i.test(norm)
786
- ) {
787
- return "entity";
788
- }
789
-
790
- if (
791
- archetype === "repository" ||
792
- /repositories|repository|database|persistence|egress|adapter/i.test(norm)
793
- ) {
794
- return "repository";
795
- }
796
-
797
- return "service";
633
+ return detectPipelineStage(filePath, archetype);
798
634
  }
799
635
 
800
- /**
801
- * Resolve an import target path (relative or alias) to a FileRecord in the catalog.
802
- */
803
636
  public resolveImportTargets(sourceFilePath: string, importTarget: string): FileRecord[] {
804
- if (!this.importEvidence && !this.evidenceByFile.has(sourceFilePath)) {
805
- this.evidenceByFile.set(sourceFilePath, this.repo.getImportRelationships(this.projectRoot, sourceFilePath));
806
- }
807
- const evidence = (this.importEvidence ?? this.evidenceByFile.get(sourceFilePath))?.find(edge => edge.source.file === sourceFilePath && edge.resolution.source.target === importTarget);
808
- if (evidence && (evidence.freshness !== "current" || evidence.index_coverage !== "complete")) return [];
809
- const result = evidence?.resolution ?? new ImportResolver(this.projectRoot, this.repo.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(importTarget,sourceFilePath);
810
- if (result.status !== "resolved" || result.coverage === "conditional") {
811
- // Fallback: check symbols in repository (e.g. PHP namespace classes, Go packages, Python modules)
812
- const matching = this.repo.findSymbolsByName(importTarget);
813
- if (matching.length === 1) {
814
- const file = this.fileForPath(matching[0].file_path);
815
- if (file) return [file];
816
- }
817
- const shortName = importTarget.split(/[\/\\]/).pop();
818
- if (shortName && shortName !== importTarget) {
819
- const shortMatches = this.repo.findSymbolsByName(shortName);
820
- if (shortMatches.length === 1) {
821
- const file = this.fileForPath(shortMatches[0].file_path);
822
- if (file) return [file];
823
- }
824
- }
825
- return [];
826
- }
827
- return result.targets.flatMap(target => target.files).flatMap(file => {
828
- const indexed = this.fileForPath(file);
829
- return indexed ? [indexed] : [];
830
- });
637
+ return this.importCandidates.resolveImportTargets(sourceFilePath, importTarget);
831
638
  }
832
639
 
833
640
  public resolveImportToFile(sourceFilePath: string, importTarget: string): FileRecord | undefined {
834
- if (this.repo.getMeta?.("workspace_root")) {
835
- const targets = this.resolveImportTargets(sourceFilePath,importTarget);
836
- return targets.length === 1 ? targets[0] : undefined;
837
- }
838
- // 1. Relative import (./ or ../)
839
- if (importTarget.startsWith(".")) {
840
- const sourceDir = dirname(sourceFilePath);
841
- const combined = normalize(join(sourceDir, importTarget)).replace(/\\/g, "/");
842
-
843
- const candidates = [
844
- combined,
845
- `${combined}.ts`,
846
- `${combined}.tsx`,
847
- `${combined}.js`,
848
- `${combined}.jsx`,
849
- `${combined}/index.ts`,
850
- `${combined}/index.js`,
851
- ];
852
-
853
- for (const cand of candidates) {
854
- const found = this.fileForPath(cand);
855
- if (found) return found;
856
- }
857
- }
858
-
859
- // 2. Alias import (@/... or src/...)
860
- const cleanAlias = importTarget.replace(/^@\//, "src/");
861
- const aliasCandidates = [
862
- cleanAlias,
863
- `${cleanAlias}.ts`,
864
- `${cleanAlias}.tsx`,
865
- `${cleanAlias}.js`,
866
- `${cleanAlias}.jsx`,
867
- `${cleanAlias}/index.ts`,
868
- `${cleanAlias}/index.js`,
869
- ];
870
-
871
- for (const cand of aliasCandidates) {
872
- const found = this.fileForPath(cand);
873
- if (found) return found;
874
- }
875
-
876
- // 3. Basename search fallback
877
- const baseTarget = importTarget.split("/").pop()?.replace(/\.[^.]+$/, "");
878
- if (baseTarget && baseTarget.length > 3) {
879
- for (const [norm, file] of this.fileMapByNormPath.entries()) {
880
- if (norm.includes(`/${baseTarget.toLowerCase()}.`) || norm.endsWith(`/${baseTarget.toLowerCase()}`)) {
881
- return file;
882
- }
883
- }
884
- }
885
-
886
- return undefined;
641
+ return this.importCandidates.resolveImportToFile(sourceFilePath, importTarget);
887
642
  }
888
643
 
889
644
  /**
@@ -916,15 +671,11 @@ export class CallGraphTracer {
916
671
  }
917
672
  }
918
673
 
919
- // Global symbol search
920
- for (const [fileId, syms] of this.symbolsByFileId.entries()) {
921
- const match = syms.find((s) => s.name === cleanSymbol);
922
- if (match) {
923
- const file = this.fileMapById.get(fileId);
924
- if (file) {
925
- return { file: file.path, line: match.line_start };
926
- }
927
- }
674
+ // Global symbol search via indexed SQLite lookup (avoids loading all symbols into RAM)
675
+ const exactMatches = this.repo.findSymbolsByName(cleanSymbol);
676
+ const exactMatch = exactMatches.find((s) => s.name === cleanSymbol);
677
+ if (exactMatch) {
678
+ return { file: exactMatch.file_path, line: exactMatch.line_start };
928
679
  }
929
680
 
930
681
  return null;
@@ -1005,7 +756,7 @@ export class CallGraphTracer {
1005
756
  controller_file: controllerNode?.file || null,
1006
757
  controller_line: controllerNode?.line || 0,
1007
758
  architecture_style: architectureStyle,
1008
- entry_kind: "http_route",
759
+ entry_kind: "inferred_http_route",
1009
760
  execution_chain_json: JSON.stringify(chain),
1010
761
  };
1011
762
  }
@@ -1018,7 +769,11 @@ export class CallGraphTracer {
1018
769
  .replace(/\.[^.]+$/, "")
1019
770
  .toLowerCase();
1020
771
 
1021
- const resource = base ? `/${base}s` : "/resource";
772
+ const resource = base
773
+ ? base.endsWith("s")
774
+ ? `/${base}`
775
+ : `/${base}s`
776
+ : "/resource";
1022
777
  if (/store|create/i.test(methodName)) return resource;
1023
778
  if (/show|get|find/i.test(methodName)) return `${resource}/:id`;
1024
779
  if (/update|edit|patch/i.test(methodName)) return `${resource}/:id`;