@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,724 @@
1
+ import { ImportResolver } from "./import-resolver.ts";
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";
5
+ import type {
6
+ ExecutionChainNode,
7
+ FileRecord,
8
+ SymbolRecord,
9
+ VerticalSliceRecord,
10
+ } from "../../types/index.ts";
11
+ import type { SeptumRepository } from "../database/repository.ts";
12
+
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
+ }
23
+
24
+ export class CallGraphTracer {
25
+ private importEvidence?: ReturnType<SeptumRepository["getImportRelationships"]>;
26
+ private fileMapByNormPath: Map<string, FileRecord> = new Map();
27
+ private fileMapById: Map<number, FileRecord> = new Map();
28
+ private symbolsByFileId: Map<number, SymbolRecord[]> = new Map();
29
+ private dependenciesByFileId: Map<
30
+ number,
31
+ Array<{ target: string; statement: string; line_number: number; is_external: boolean }>
32
+ > = new Map();
33
+
34
+ constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd()) {}
35
+
36
+ /**
37
+ * Initializes internal fast lookup maps from SQLite repository data.
38
+ */
39
+ public initMaps(): void {
40
+ const allSymbolsWithFiles = this.repo.getAllSymbolsWithFiles();
41
+ const allDeps = this.repo.getAllDependenciesWithDomains();
42
+ this.importEvidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.projectRoot) : undefined;
43
+
44
+ // Map files
45
+ const allFiles = this.repo.getAllFiles();
46
+ for (const f of allFiles) {
47
+ const norm = this.normalizeFilePath(f.path);
48
+ this.fileMapByNormPath.set(norm, f);
49
+ this.fileMapById.set(f.id, f);
50
+ }
51
+
52
+ // Map symbols
53
+ for (const s of allSymbolsWithFiles) {
54
+ const existing = this.symbolsByFileId.get(s.file_id) || [];
55
+ existing.push(s);
56
+ this.symbolsByFileId.set(s.file_id, existing);
57
+ }
58
+
59
+ // Map dependencies
60
+ for (const d of allDeps) {
61
+ const file = this.fileMapByNormPath.get(this.normalizeFilePath(d.source_file));
62
+ if (file) {
63
+ const existing = this.dependenciesByFileId.get(file.id) || [];
64
+ existing.push({
65
+ target: d.target,
66
+ statement: d.statement,
67
+ line_number: d.line_number,
68
+ is_external: d.is_external,
69
+ });
70
+ this.dependenciesByFileId.set(file.id, existing);
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Discover declarative HTTP routes from known route/router files in the repository.
77
+ */
78
+ public discoverDeclarativeRoutes(): DiscoveredRoute[] {
79
+ const discovered: DiscoveredRoute[] = [];
80
+
81
+ for (const [normPath, file] of this.fileMapByNormPath.entries()) {
82
+ const isRouteFile =
83
+ file.archetype === "route" ||
84
+ /routes?|router|endpoints?/i.test(normPath) ||
85
+ /\.(routes?|router)\.[tj]sx?$/i.test(normPath);
86
+
87
+ if (!isRouteFile) continue;
88
+
89
+ const fullPath = resolve(this.projectRoot, file.path);
90
+ if (!existsSync(fullPath)) continue;
91
+
92
+ try {
93
+ const content = readOptionalSourceFile(fullPath, "utf-8");
94
+ const lines = content.split("\n");
95
+
96
+ for (let i = 0; i < lines.length; i++) {
97
+ const line = lines[i];
98
+ // Pattern: router.post('/api/orders', validateMiddleware, controller.action)
99
+ // or app.get('/orders', handler)
100
+ const match = line.match(
101
+ /(?:router|app|server|api)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(.+)\)/i
102
+ );
103
+
104
+ if (match) {
105
+ const method = match[1].toUpperCase();
106
+ const uri = match[2];
107
+ const rawArgs = match[3];
108
+
109
+ const argTokens = rawArgs
110
+ .split(",")
111
+ .map((t) => t.trim())
112
+ .filter((t) => t.length > 0 && !t.startsWith("//"));
113
+
114
+ const middlewareSymbols: string[] = [];
115
+ let handlerSymbol: string | undefined;
116
+ let handlerClass: string | undefined;
117
+ let handlerMethod: string | undefined;
118
+
119
+ if (argTokens.length === 1) {
120
+ handlerSymbol = argTokens[0];
121
+ } else if (argTokens.length > 1) {
122
+ handlerSymbol = argTokens[argTokens.length - 1];
123
+ middlewareSymbols.push(...argTokens.slice(0, argTokens.length - 1));
124
+ }
125
+
126
+ if (handlerSymbol) {
127
+ // Extract Class.method or classInstance.method
128
+ const parts = handlerSymbol.split(".");
129
+ if (parts.length === 2) {
130
+ handlerClass = parts[0];
131
+ handlerMethod = parts[1];
132
+ } else if (handlerSymbol.includes("::")) {
133
+ const colParts = handlerSymbol.split("::");
134
+ handlerClass = colParts[0];
135
+ handlerMethod = colParts[1];
136
+ }
137
+ }
138
+
139
+ discovered.push({
140
+ method,
141
+ uri,
142
+ file: file.path,
143
+ line: i + 1,
144
+ middlewareSymbols,
145
+ handlerSymbol,
146
+ handlerClass,
147
+ handlerMethod,
148
+ });
149
+ }
150
+ }
151
+ } catch (err: unknown) {
152
+ const msg = err instanceof Error ? err.message : String(err);
153
+ console.error(`[Septum CallGraph Warning] Route discovery failed for ${file.path}: ${msg}`);
154
+ }
155
+ }
156
+
157
+ return discovered;
158
+ }
159
+
160
+ /**
161
+ * Build execution chains for all discovered entrypoints and controller actions.
162
+ */
163
+ public traceAllSlices(maxDepth: number = 5): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
164
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
165
+ this.initMaps();
166
+ const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
167
+ const declarativeRoutes = this.discoverDeclarativeRoutes();
168
+
169
+ // 1. Trace from declarative routes
170
+ for (const route of declarativeRoutes) {
171
+ const chain = this.traceChainFromRoute(route, effectiveMaxDepth);
172
+ if (chain.length > 0) {
173
+ const sliceRecord = this.buildSliceRecordFromChain(
174
+ route.method,
175
+ route.uri,
176
+ chain,
177
+ "clean"
178
+ );
179
+ slices.push(sliceRecord);
180
+ }
181
+ }
182
+
183
+ // 2. Trace controllers if routes were not explicitly bound or found
184
+ for (const [normPath, file] of this.fileMapByNormPath.entries()) {
185
+ const isController =
186
+ file.archetype === "controller" ||
187
+ /controller/i.test(normPath) ||
188
+ normPath.endsWith("Controller.ts") ||
189
+ normPath.endsWith("Controller.js");
190
+
191
+ if (!isController) continue;
192
+
193
+ const symbols = this.symbolsByFileId.get(file.id) || [];
194
+ const methods = symbols.filter((s) => s.kind === "method" || s.kind === "function");
195
+
196
+ for (const m of methods) {
197
+ // Skip constructors or private helpers
198
+ if (m.name === "constructor" || m.name.startsWith("_")) continue;
199
+
200
+ // Check if this method was already covered by declarative routes
201
+ const alreadyCovered = slices.some(
202
+ (s) =>
203
+ s.controller_file === file.path &&
204
+ s.action_name.toLowerCase() === m.name.toLowerCase()
205
+ );
206
+ if (alreadyCovered) continue;
207
+
208
+ const chain = this.traceChainFromController(file, m, effectiveMaxDepth);
209
+ if (chain.length > 0) {
210
+ const defaultMethod = /create|store|save|add/i.test(m.name)
211
+ ? "POST"
212
+ : /update|edit|patch/i.test(m.name)
213
+ ? "PUT"
214
+ : /delete|remove|destroy/i.test(m.name)
215
+ ? "DELETE"
216
+ : "GET";
217
+
218
+ const inferredUri = this.inferRouteUri(file.path, m.name);
219
+ const sliceRecord = this.buildSliceRecordFromChain(
220
+ defaultMethod,
221
+ inferredUri,
222
+ chain,
223
+ "clean"
224
+ );
225
+ slices.push(sliceRecord);
226
+ }
227
+ }
228
+ }
229
+
230
+ return slices;
231
+ }
232
+
233
+ /**
234
+ * Trace execution chain starting from a declarative route.
235
+ */
236
+ public traceChainFromRoute(route: DiscoveredRoute, maxDepth: number = 5): ExecutionChainNode[] {
237
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
238
+ const chain: ExecutionChainNode[] = [];
239
+
240
+ // Stage 1: Ingress
241
+ chain.push({
242
+ stage: "ingress",
243
+ symbol: `${route.method} ${route.uri}`,
244
+ file: route.file,
245
+ line: route.line,
246
+ description: `HTTP Route Ingress: ${route.method} ${route.uri}`,
247
+ });
248
+
249
+ // Stage 2: Validation / Middleware
250
+ for (const mw of route.middlewareSymbols) {
251
+ const mwLoc = this.locateSymbol(mw, route.file);
252
+ chain.push({
253
+ stage: "validation",
254
+ symbol: mw,
255
+ file: mwLoc?.file,
256
+ line: mwLoc?.line,
257
+ description: `Request Validation / Middleware: ${mw}`,
258
+ });
259
+ }
260
+
261
+ // Stage 3: Controller / Handler
262
+ let controllerFile: FileRecord | undefined;
263
+ let actionMethod = route.handlerMethod || route.handlerSymbol || "handle";
264
+
265
+ if (route.handlerClass) {
266
+ const found = this.findFileBySymbolOrName(route.handlerClass, route.file);
267
+ if (found) {
268
+ controllerFile = found.file;
269
+ if (!route.handlerMethod && found.symbol) {
270
+ actionMethod = found.symbol.name;
271
+ }
272
+ }
273
+ } else if (route.handlerSymbol) {
274
+ const found = this.findFileBySymbolOrName(route.handlerSymbol, route.file);
275
+ if (found) {
276
+ controllerFile = found.file;
277
+ }
278
+ }
279
+
280
+ if (controllerFile) {
281
+ const syms = this.symbolsByFileId.get(controllerFile.id) || [];
282
+ const methodSym = syms.find(
283
+ (s) => s.name.toLowerCase() === actionMethod.toLowerCase()
284
+ );
285
+
286
+ const ctrlName =
287
+ syms.find((s) => s.kind === "class")?.name ||
288
+ controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
289
+ "Controller";
290
+
291
+ chain.push({
292
+ stage: "controller",
293
+ symbol: `${ctrlName}::${actionMethod}`,
294
+ file: controllerFile.path,
295
+ line: methodSym?.line_start || 1,
296
+ description: `Controller Action: ${ctrlName}::${actionMethod}`,
297
+ });
298
+
299
+ // Forward reachability BFS from controller
300
+ this.traverseOutboundDependencies(controllerFile, chain, effectiveMaxDepth);
301
+ }
302
+
303
+ return chain;
304
+ }
305
+
306
+ public static readonly MAX_CHAIN_NODES = 25;
307
+
308
+ /**
309
+ * Trace execution chain starting from a controller method.
310
+ */
311
+ public traceChainFromController(
312
+ controllerFile: FileRecord,
313
+ method: SymbolRecord,
314
+ maxDepth: number = 5
315
+ ): ExecutionChainNode[] {
316
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
317
+ const chain: ExecutionChainNode[] = [];
318
+ const syms = this.symbolsByFileId.get(controllerFile.id) || [];
319
+ const ctrlName =
320
+ syms.find((s) => s.kind === "class")?.name ||
321
+ controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
322
+ "Controller";
323
+
324
+ // Stage 1: Ingress (inferred)
325
+ const inferredUri = this.inferRouteUri(controllerFile.path, method.name);
326
+ const defaultMethod = /create|store|save|add/i.test(method.name)
327
+ ? "POST"
328
+ : /update|edit|patch/i.test(method.name)
329
+ ? "PUT"
330
+ : /delete|remove|destroy/i.test(method.name)
331
+ ? "DELETE"
332
+ : "GET";
333
+
334
+ chain.push({
335
+ stage: "ingress",
336
+ symbol: `${defaultMethod} ${inferredUri}`,
337
+ file: controllerFile.path,
338
+ line: method.line_start,
339
+ description: `Inferred Ingress: ${defaultMethod} ${inferredUri}`,
340
+ });
341
+
342
+ // Stage 3: Controller
343
+ chain.push({
344
+ stage: "controller",
345
+ symbol: `${ctrlName}::${method.name}`,
346
+ file: controllerFile.path,
347
+ line: method.line_start,
348
+ description: `Controller Action: ${ctrlName}::${method.name}`,
349
+ });
350
+
351
+ // Forward reachability BFS
352
+ this.traverseOutboundDependencies(controllerFile, chain, effectiveMaxDepth);
353
+
354
+ return chain;
355
+ }
356
+
357
+ /**
358
+ * Expand an existing slice execution chain starting from controllerFilePath up to maxDepth.
359
+ */
360
+ public expandChainFromFile(
361
+ controllerFilePath: string,
362
+ existingChain: ExecutionChainNode[],
363
+ maxDepth: number = 5
364
+ ): ExecutionChainNode[] {
365
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
366
+ if (this.fileMapByNormPath.size === 0) {
367
+ this.initMaps();
368
+ }
369
+ const startFile = this.fileMapByNormPath.get(this.normalizeFilePath(controllerFilePath));
370
+ if (!startFile) {
371
+ return existingChain.slice(0, CallGraphTracer.MAX_CHAIN_NODES);
372
+ }
373
+
374
+ const chain = [...existingChain];
375
+ this.traverseOutboundDependencies(startFile, chain, effectiveMaxDepth);
376
+ return chain;
377
+ }
378
+
379
+ /**
380
+ * Traverse outbound dependencies using BFS with cycle detection, max hop limit, and node ceiling.
381
+ */
382
+ public traverseOutboundDependencies(
383
+ startFile: FileRecord,
384
+ chain: ExecutionChainNode[],
385
+ maxDepth: number = 5
386
+ ): void {
387
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
388
+ const visitedFiles = new Set<string>();
389
+ visitedFiles.add(startFile.path);
390
+ const queue: Array<{ file: FileRecord; depth: number }> = [
391
+ { file: startFile, depth: 1 },
392
+ ];
393
+
394
+ while (queue.length > 0 && chain.length < CallGraphTracer.MAX_CHAIN_NODES) {
395
+ const current = queue.shift()!;
396
+ if (current.depth > effectiveMaxDepth) break;
397
+
398
+ const deps = this.dependenciesByFileId.get(current.file.id) || [];
399
+
400
+ for (const dep of deps) {
401
+ if (chain.length >= CallGraphTracer.MAX_CHAIN_NODES) break;
402
+ const resolvedFiles = this.repo.getMeta?.("workspace_root") ? this.resolveImportTargets(current.file.path, dep.target)
403
+ : dep.is_external ? [] : [this.resolveImportToFile(current.file.path, dep.target)].filter((file): file is FileRecord => !!file);
404
+ for (const resolvedFile of resolvedFiles) {
405
+ if (!resolvedFile || visitedFiles.has(resolvedFile.path)) continue;
406
+
407
+ visitedFiles.add(resolvedFile.path);
408
+
409
+ const stage = this.detectStage(resolvedFile.path, resolvedFile.archetype);
410
+ const fileSymbols = this.symbolsByFileId.get(resolvedFile.id) || [];
411
+ const mainSymbol =
412
+ fileSymbols.find((s) => s.kind === "class" || s.kind === "interface") ||
413
+ fileSymbols.find((s) => s.kind === "function") ||
414
+ fileSymbols[0];
415
+
416
+ const symbolDisplay = mainSymbol
417
+ ? mainSymbol.name
418
+ : resolvedFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") || "Module";
419
+
420
+ // Prevent adding duplicate stages if already present, or add as refinement
421
+ const existingStageNode = chain.find(
422
+ (c) => c.stage === stage && c.file === resolvedFile.path
423
+ );
424
+
425
+ if (!existingStageNode) {
426
+ chain.push({
427
+ stage,
428
+ symbol: symbolDisplay,
429
+ file: resolvedFile.path,
430
+ line: mainSymbol?.line_start || 1,
431
+ description: `${stage.toUpperCase()} (dependency, not a proven call): ${symbolDisplay}`,
432
+ relationship: { kind: "imports", derivation: "source", source: { file: current.file.path, line: dep.line_number, statement: dep.statement }, reason: "static import; stage classification is inferred" },
433
+ });
434
+ }
435
+
436
+ queue.push({ file: resolvedFile, depth: current.depth + 1 });
437
+ }
438
+ }
439
+ }
440
+
441
+ // Sort stages according to standard pipeline order
442
+ const stageOrder: Record<string, number> = {
443
+ ingress: 1,
444
+ validation: 2,
445
+ controller: 3,
446
+ orchestrator: 3,
447
+ use_case: 4,
448
+ service: 4,
449
+ domain: 5,
450
+ entity: 5,
451
+ egress: 6,
452
+ repository: 6,
453
+ };
454
+
455
+ chain.sort((a, b) => {
456
+ const orderA = stageOrder[a.stage] || 99;
457
+ const orderB = stageOrder[b.stage] || 99;
458
+ return orderA - orderB;
459
+ });
460
+
461
+ if (chain.length > CallGraphTracer.MAX_CHAIN_NODES) {
462
+ chain.length = CallGraphTracer.MAX_CHAIN_NODES;
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Detect generic pipeline stage from file path and archetype.
468
+ */
469
+ public detectStage(filePath: string, archetype: string): string {
470
+ const norm = filePath.toLowerCase();
471
+
472
+ if (
473
+ archetype === "validation" ||
474
+ archetype === "dto" ||
475
+ /validation|middleware|dto|request|schema/i.test(norm)
476
+ ) {
477
+ return "validation";
478
+ }
479
+
480
+ if (archetype === "controller" || /controller|handler/i.test(norm)) {
481
+ return "controller";
482
+ }
483
+
484
+ if (
485
+ archetype === "service" ||
486
+ archetype === "use_case" ||
487
+ /use-?cases?|interactor|application|workflow/i.test(norm)
488
+ ) {
489
+ return "use_case";
490
+ }
491
+
492
+ if (
493
+ archetype === "model" ||
494
+ archetype === "entity" ||
495
+ /domain|entities|entity|aggregate/i.test(norm)
496
+ ) {
497
+ return "entity";
498
+ }
499
+
500
+ if (
501
+ archetype === "repository" ||
502
+ /repositories|repository|database|persistence|egress|adapter/i.test(norm)
503
+ ) {
504
+ return "repository";
505
+ }
506
+
507
+ return "service";
508
+ }
509
+
510
+ /**
511
+ * Resolve an import target path (relative or alias) to a FileRecord in the catalog.
512
+ */
513
+ public resolveImportTargets(sourceFilePath: string, importTarget: string): FileRecord[] {
514
+ const evidence = this.importEvidence?.find(edge => edge.source.file === sourceFilePath && edge.resolution.source.target === importTarget);
515
+ if (evidence && (evidence.freshness !== "current" || evidence.index_coverage !== "complete")) return [];
516
+ const result = evidence?.resolution ?? new ImportResolver(this.projectRoot, this.repo.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(importTarget,sourceFilePath);
517
+ if (result.status !== "resolved" || result.coverage === "conditional") return [];
518
+ return result.targets.flatMap(target => target.files).flatMap(file => {
519
+ const indexed = this.fileMapByNormPath.get(this.normalizeFilePath(file));
520
+ return indexed ? [indexed] : [];
521
+ });
522
+ }
523
+
524
+ public resolveImportToFile(sourceFilePath: string, importTarget: string): FileRecord | undefined {
525
+ if (this.repo.getMeta?.("workspace_root")) {
526
+ const targets = this.resolveImportTargets(sourceFilePath,importTarget);
527
+ return targets.length === 1 ? targets[0] : undefined;
528
+ }
529
+ // 1. Relative import (./ or ../)
530
+ if (importTarget.startsWith(".")) {
531
+ const sourceDir = dirname(sourceFilePath);
532
+ const combined = normalize(join(sourceDir, importTarget)).replace(/\\/g, "/");
533
+
534
+ const candidates = [
535
+ combined,
536
+ `${combined}.ts`,
537
+ `${combined}.tsx`,
538
+ `${combined}.js`,
539
+ `${combined}.jsx`,
540
+ `${combined}/index.ts`,
541
+ `${combined}/index.js`,
542
+ ];
543
+
544
+ for (const cand of candidates) {
545
+ const found = this.fileMapByNormPath.get(this.normalizeFilePath(cand));
546
+ if (found) return found;
547
+ }
548
+ }
549
+
550
+ // 2. Alias import (@/... or src/...)
551
+ const cleanAlias = importTarget.replace(/^@\//, "src/");
552
+ const aliasCandidates = [
553
+ cleanAlias,
554
+ `${cleanAlias}.ts`,
555
+ `${cleanAlias}.tsx`,
556
+ `${cleanAlias}.js`,
557
+ `${cleanAlias}.jsx`,
558
+ `${cleanAlias}/index.ts`,
559
+ `${cleanAlias}/index.js`,
560
+ ];
561
+
562
+ for (const cand of aliasCandidates) {
563
+ const found = this.fileMapByNormPath.get(this.normalizeFilePath(cand));
564
+ if (found) return found;
565
+ }
566
+
567
+ // 3. Basename search fallback
568
+ const baseTarget = importTarget.split("/").pop()?.replace(/\.[^.]+$/, "");
569
+ if (baseTarget && baseTarget.length > 3) {
570
+ for (const [norm, file] of this.fileMapByNormPath.entries()) {
571
+ if (norm.includes(`/${baseTarget.toLowerCase()}.`) || norm.endsWith(`/${baseTarget.toLowerCase()}`)) {
572
+ return file;
573
+ }
574
+ }
575
+ }
576
+
577
+ return undefined;
578
+ }
579
+
580
+ /**
581
+ * Locate a symbol in the codebase or relative to a file.
582
+ */
583
+ private locateSymbol(
584
+ symbolName: string,
585
+ relativeToFile?: string
586
+ ): { file: string; line: number } | null {
587
+ const cleanSymbol = symbolName.replace(/[()]/g, "").trim();
588
+
589
+ // Check imports of relativeToFile first
590
+ if (relativeToFile) {
591
+ const file = this.fileMapByNormPath.get(this.normalizeFilePath(relativeToFile));
592
+ if (file) {
593
+ const deps = this.dependenciesByFileId.get(file.id) || [];
594
+ for (const dep of deps) {
595
+ if (dep.target.includes(cleanSymbol) || dep.statement.includes(cleanSymbol)) {
596
+ const targetFile = this.resolveImportToFile(relativeToFile, dep.target);
597
+ if (targetFile) {
598
+ const syms = this.symbolsByFileId.get(targetFile.id) || [];
599
+ const s = syms.find((sym) => sym.name === cleanSymbol);
600
+ return {
601
+ file: targetFile.path,
602
+ line: s?.line_start || 1,
603
+ };
604
+ }
605
+ }
606
+ }
607
+ }
608
+ }
609
+
610
+ // Global symbol search
611
+ for (const [fileId, syms] of this.symbolsByFileId.entries()) {
612
+ const match = syms.find((s) => s.name === cleanSymbol);
613
+ if (match) {
614
+ const file = this.fileMapById.get(fileId);
615
+ if (file) {
616
+ return { file: file.path, line: match.line_start };
617
+ }
618
+ }
619
+ }
620
+
621
+ return null;
622
+ }
623
+
624
+ /**
625
+ * Find FileRecord and Symbol by identifier or class name.
626
+ */
627
+ private findFileBySymbolOrName(
628
+ ident: string,
629
+ contextFile?: string,
630
+ visited = new Set<string>()
631
+ ): { file: FileRecord; symbol?: SymbolRecord } | null {
632
+ if (contextFile && visited.has(contextFile)) return null;
633
+ if (contextFile) visited.add(contextFile);
634
+ const cleanIdent = ident.replace(/controller$/i, "").toLowerCase();
635
+
636
+ // 1. Try imports of contextFile
637
+ if (contextFile) {
638
+ const srcFile = this.fileMapByNormPath.get(this.normalizeFilePath(contextFile));
639
+ if (srcFile) {
640
+ const deps = this.dependenciesByFileId.get(srcFile.id) || [];
641
+ for (const d of deps) {
642
+ if (d.statement.toLowerCase().includes(cleanIdent) || d.target.toLowerCase().includes(cleanIdent)) {
643
+ const resolved = this.resolveImportToFile(contextFile, d.target);
644
+ if (resolved) {
645
+ const syms = this.symbolsByFileId.get(resolved.id) || [];
646
+ const sym = syms.find(
647
+ (s) => s.name.toLowerCase() === ident.toLowerCase() || s.name.toLowerCase().includes(cleanIdent)
648
+ );
649
+ if (sym) {
650
+ return { file: resolved, symbol: sym };
651
+ }
652
+ if (visited.size < 5) {
653
+ const reExported = this.findFileBySymbolOrName(ident, resolved.path, visited);
654
+ if (reExported?.symbol) return reExported;
655
+ }
656
+ }
657
+ }
658
+ }
659
+ }
660
+ }
661
+
662
+ // 2. Try match file path
663
+ for (const [norm, file] of this.fileMapByNormPath.entries()) {
664
+ if (norm.toLowerCase().includes(cleanIdent) && norm.toLowerCase().includes("controller")) {
665
+ const syms = this.symbolsByFileId.get(file.id) || [];
666
+ return { file, symbol: syms.find((s) => s.kind === "class") };
667
+ }
668
+ }
669
+
670
+ return null;
671
+ }
672
+
673
+ /**
674
+ * Build a VerticalSliceRecord structure from an execution chain.
675
+ */
676
+ private buildSliceRecordFromChain(
677
+ httpMethod: string,
678
+ routeUri: string,
679
+ chain: ExecutionChainNode[],
680
+ architectureStyle: string = "clean"
681
+ ): Omit<VerticalSliceRecord, "id" | "created_at"> {
682
+ const controllerNode = chain.find((c) => c.stage === "controller" || c.stage === "orchestrator");
683
+
684
+ const ctrlParts = controllerNode?.symbol.split("::") || [];
685
+ const controllerClass = ctrlParts[0] || "Controller";
686
+ const actionName = ctrlParts[1] || "handle";
687
+
688
+ return {
689
+ domain_id: null,
690
+ feature_key: null,
691
+ http_method: httpMethod,
692
+ route_uri: routeUri,
693
+ route_name: `${httpMethod.toLowerCase()}.${routeUri.replace(/[^a-zA-Z0-9]/g, "_").replace(/^_+|_+$/g, "")}`,
694
+ controller_class: controllerClass,
695
+ action_name: actionName,
696
+ controller_file: controllerNode?.file || null,
697
+ controller_line: controllerNode?.line || 0,
698
+ architecture_style: architectureStyle,
699
+ entry_kind: "http_route",
700
+ execution_chain_json: JSON.stringify(chain),
701
+ };
702
+ }
703
+
704
+ private inferRouteUri(filePath: string, methodName: string): string {
705
+ const base = filePath
706
+ .split("/")
707
+ .pop()
708
+ ?.replace(/controller\.[^.]+$/i, "")
709
+ .replace(/\.[^.]+$/, "")
710
+ .toLowerCase();
711
+
712
+ const resource = base ? `/${base}s` : "/resource";
713
+ if (/store|create/i.test(methodName)) return resource;
714
+ if (/show|get|find/i.test(methodName)) return `${resource}/:id`;
715
+ if (/update|edit|patch/i.test(methodName)) return `${resource}/:id`;
716
+ if (/delete|destroy|remove/i.test(methodName)) return `${resource}/:id`;
717
+
718
+ return `${resource}/${methodName}`;
719
+ }
720
+
721
+ private normalizeFilePath(p: string): string {
722
+ return p.replace(/\\/g, "/").replace(/^\.\/?/, "").toLowerCase();
723
+ }
724
+ }