@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,66 +1,41 @@
1
- import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
3
- import { parseWithTreeSitter } from "../wasm-loader.ts";
4
- import { ImportResolver } from "../../resolver/import-resolver.ts";
5
- import type Parser from "web-tree-sitter";
6
1
  import * as fs from "node:fs";
7
2
  import * as path from "node:path";
3
+ import ts from "typescript";
4
+ import type { ExecutionChainNode } from "../../../types/index.ts";
5
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
6
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
7
+ import { composeMountPrefixes } from "./route-prefixes.ts";
8
8
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
9
-
10
- const EXPRESS_VERBS = new Set([
11
- "get",
12
- "post",
13
- "put",
14
- "patch",
15
- "delete",
16
- "all",
17
- "head",
18
- "options",
19
- ]);
20
-
21
- interface RawRoute {
22
- file: string;
23
- relPath: string;
24
- routerVar: string;
25
- httpMethod: string;
26
- rawPath: string;
27
- middlewares: Array<{ symbol: string; line: number }>;
28
- handler: { symbol: string; line: number };
29
- routeLine: number;
30
- }
31
-
32
- interface RawMount {
33
- file: string;
34
- relPath: string;
35
- callerVar: string;
36
- prefix: string;
37
- targetVar: string;
38
- line: number;
9
+ import { lineOf, literal, TypeScriptBindings, visitRouteCalls } from "./typescript-bindings.ts";
10
+ import { isGraphQLRouteOrHandler } from "./graphql-entrypoint.ts";
11
+
12
+ const verbs = new Set(["get", "post", "put", "patch", "delete", "head", "options", "trace", "connect", "all"]);
13
+
14
+ type Receiver = { router: ts.CallExpression; paths?: string[] };
15
+ type Mount = { parent: ts.CallExpression; child: ts.CallExpression; prefix: string | undefined };
16
+ type Route = {
17
+ router: ts.CallExpression;
18
+ call: ts.CallExpression;
19
+ method: string;
20
+ paths: string[];
21
+ callbacks: ts.Expression[];
22
+ };
23
+
24
+ function stringPaths(value?: ts.Expression): string[] | undefined {
25
+ const single = literal(value);
26
+ if (single !== undefined) return [single];
27
+ if (!value || !ts.isArrayLiteralExpression(value)) return undefined;
28
+ const paths = value.elements.map(literal);
29
+ return paths.every((item): item is string => item !== undefined) ? paths : undefined;
39
30
  }
40
31
 
41
- interface ImportBinding {
42
- importedName: string;
43
- sourceSpecifier: string;
32
+ function flattenedArguments(argumentsList: readonly ts.Expression[]): ts.Expression[] {
33
+ return argumentsList.flatMap(arg => ts.isArrayLiteralExpression(arg) ? flattenedArguments(arg.elements) : [arg]);
44
34
  }
45
35
 
46
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
47
- if (!node) return undefined;
48
- if (node.type === "string" || node.type === "template_string") {
49
- const raw = node.text.trim();
50
- if (raw.includes("${")) return undefined;
51
- return raw.replace(/^['"`]|['"`]$/g, "");
52
- }
53
- return undefined;
54
- }
55
-
56
- function normalizeRouteUri(prefix: string, rawPath: string): string {
57
- const p = (prefix ?? "").trim().replace(/\/+$/, "");
58
- let r = (rawPath ?? "").trim();
59
- if (!r.startsWith("/")) r = "/" + r;
60
- if (r === "/" && p.length > 0) return p;
61
- if (r === "/" && p.length === 0) return "/";
62
- const joined = `${p}${r}`;
63
- return joined.startsWith("/") ? joined : `/${joined}`;
36
+ function normalizeUri(prefix: string, route: string): string {
37
+ const uri = prefix + (route === "/" && prefix ? "" : "/" + route.replace(/^\/+/, ""));
38
+ return uri || "/";
64
39
  }
65
40
 
66
41
  export class ExpressSemanticExtractor implements SemanticSliceExtractor {
@@ -69,361 +44,198 @@ export class ExpressSemanticExtractor implements SemanticSliceExtractor {
69
44
 
70
45
  public canHandle(projectRoot: string, framework?: string): boolean {
71
46
  if (framework === "express") return true;
72
-
73
- const pkgPath = path.join(projectRoot, "package.json");
74
- if (fs.existsSync(pkgPath)) {
47
+ const hasExpressInPkg = (manifestFile: string): boolean => {
48
+ if (probeSourcePath(manifestFile) !== "file") return false;
49
+ const manifest = readOptionalSourceFile(manifestFile, "utf-8");
50
+ if (!manifest) return false;
75
51
  try {
76
- const pkg = JSON.parse(readOptionalSourceFile(pkgPath, "utf-8"));
77
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
78
- if (deps["express"]) return true;
79
- } catch {}
52
+ const pkg = JSON.parse(manifest);
53
+ return !!(pkg.dependencies?.express || pkg.devDependencies?.express);
54
+ } catch {
55
+ return false;
56
+ }
57
+ };
58
+ if (hasExpressInPkg(path.join(projectRoot, "package.json"))) return true;
59
+ for (const sub of ["api", "server", "backend"]) {
60
+ if (hasExpressInPkg(path.join(projectRoot, sub, "package.json"))) return true;
61
+ }
62
+ for (const group of ["apps", "packages"]) {
63
+ const groupDir = path.join(projectRoot, group);
64
+ if (probeSourcePath(groupDir) === "directory") {
65
+ try {
66
+ for (const entry of fs.readdirSync(groupDir, { withFileTypes: true })) {
67
+ if (entry.isDirectory() && hasExpressInPkg(path.join(groupDir, entry.name, "package.json"))) {
68
+ return true;
69
+ }
70
+ }
71
+ } catch {
72
+ // Ignore unreadable sub-packages
73
+ }
74
+ }
80
75
  }
81
-
82
76
  return false;
83
77
  }
84
78
 
85
79
  public async extractSlices(
86
80
  projectRoot: string,
87
81
  domainId?: number,
88
- signal?: AbortSignal, inventory?: SourceInventory
82
+ signal?: AbortSignal,
83
+ inventory?: SourceInventory,
89
84
  ): Promise<VerticalSliceCandidate[]> {
90
- const slices: VerticalSliceCandidate[] = [];
91
- const sourceFiles = listSourceFiles(projectRoot, /\.(?:[cm]?[jt]sx?)$/, inventory).filter(file => !file.endsWith('.d.ts'));
92
- const resolver = new ImportResolver(projectRoot);
93
-
94
- const allRoutes: RawRoute[] = [];
95
- const allMounts: RawMount[] = [];
96
- const fileImports = new Map<string, Map<string, string>>(); // relPath -> (importedIdent -> targetRelPath)
97
-
98
- for (const file of sourceFiles) {
99
- if (signal?.aborted) throw new Error("semantic_extraction_cancelled");
100
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
101
- const content = readOptionalSourceFile(file, "utf-8");
102
- if (!content || (!content.includes(".get") && !content.includes(".post") && !content.includes(".use") && !content.includes(".route") && !content.includes("Router") && !content.includes("express"))) {
103
- continue;
85
+ const root = path.resolve(projectRoot);
86
+ const files = listSourceFiles(root, /\.[cm]?[jt]sx?$/, inventory).filter(file => !/\.d\.[cm]?ts$/.test(file));
87
+ const bindings = new TypeScriptBindings(root, new Set(files), signal);
88
+ const routes: Route[] = [];
89
+ const mounts: Mount[] = [];
90
+ const roots = new Map<ts.CallExpression, string>();
91
+ const receivers = new Map<ts.Expression, Receiver | undefined>();
92
+ const relative = (node: ts.Node) => path.relative(root, node.getSourceFile().fileName).replace(/\\/g, "/");
93
+
94
+ const receiverOf = (expression: ts.Expression): Receiver | undefined => {
95
+ const node = bindings.value(expression);
96
+ if (!node || !ts.isCallExpression(node) || node.questionDotToken) return undefined;
97
+ if (receivers.has(node)) return receivers.get(node);
98
+ receivers.set(node, undefined);
99
+
100
+ const binding = bindings.packageBinding(node.expression);
101
+ if (binding?.module === "express" && ["default", "Router", "*"].includes(binding.name)) {
102
+ const receiver = { router: node };
103
+ roots.set(node, "");
104
+ receivers.set(node, receiver);
105
+ return receiver;
104
106
  }
105
107
 
106
- const fileData = await parseWithTreeSitter(
107
- "typescript",
108
- content,
109
- (rootNode) => this.extractFileAst(file, relPath, rootNode, resolver)
110
- );
111
-
112
- if (fileData) {
113
- allRoutes.push(...fileData.routes);
114
- allMounts.push(...fileData.mounts);
115
- if (fileData.resolvedImports.size > 0) {
116
- fileImports.set(relPath, fileData.resolvedImports);
117
- }
118
- }
119
- }
120
-
121
- // Resolve Router Prefix Hierarchy
122
- const routerPrefixes = this.resolvePrefixHierarchy(allMounts, fileImports);
123
-
124
- // Build Vertical Slices
125
- for (const route of allRoutes) {
126
- const prefixes = routerPrefixes.get(`${route.relPath}#${route.routerVar}`) || [""];
127
-
128
- for (const prefix of prefixes) {
129
- const fullUri = normalizeRouteUri(prefix, route.rawPath);
130
- const actionSymbol = route.handler.symbol;
131
- const rootIdent = actionSymbol.includes(".") ? actionSymbol.split(".")[0] : actionSymbol;
132
- const imports = fileImports.get(route.relPath);
133
- const resolvedControllerFile = imports?.get(rootIdent) || route.relPath;
134
- const fileBase = path.basename(route.relPath).replace(/\.[^.]+$/, "");
135
- const controllerClass = actionSymbol.includes(".")
136
- ? actionSymbol.split(".")[0]
137
- : fileBase.charAt(0).toUpperCase() + fileBase.slice(1);
138
- const actionName = actionSymbol.includes(".") ? actionSymbol.split(".").pop()! : actionSymbol;
139
-
140
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
141
- {
142
- stage: "ingress",
143
- symbol: `${route.httpMethod} ${fullUri}`,
144
- file: route.relPath,
145
- line: route.routeLine,
146
- description: `Express Route: ${route.httpMethod} ${fullUri}`,
147
- },
148
- ];
149
-
150
- for (const mw of route.middlewares) {
151
- chain.push({
152
- stage: "middleware",
153
- symbol: mw.symbol,
154
- file: route.relPath,
155
- line: mw.line,
156
- description: `Express Middleware: ${mw.symbol}`,
157
- });
158
- }
159
-
160
- chain.push({
161
- stage: "controller",
162
- symbol: actionSymbol,
163
- file: resolvedControllerFile,
164
- line: route.handler.line,
165
- description: `Express Action Handler`,
166
- });
167
-
168
- slices.push({
169
- domain_id: domainId ?? null,
170
- feature_key: `express.${controllerClass.toLowerCase()}.${actionName}`,
171
- http_method: route.httpMethod,
172
- route_uri: fullUri,
173
- route_name: `${controllerClass}.${actionName}`,
174
- controller_class: controllerClass,
175
- action_name: actionName,
176
- controller_file: resolvedControllerFile,
177
- controller_line: route.handler.line,
178
- architecture_style: "mvc",
179
- entry_kind: "http_route",
180
- execution_chain_json: JSON.stringify(chain),
181
- });
182
- }
183
- }
184
-
185
- return slices;
186
- }
187
-
188
- private extractFileAst(
189
- _filePath: string,
190
- relPath: string,
191
- rootNode: Parser.SyntaxNode,
192
- resolver: ImportResolver
193
- ): { routes: RawRoute[]; mounts: RawMount[]; resolvedImports: Map<string, string> } {
194
- const routes: RawRoute[] = [];
195
- const mounts: RawMount[] = [];
196
- const resolvedImports = new Map<string, string>();
197
-
198
- // 1. Collect static imports
199
- for (const child of rootNode.namedChildren) {
200
- if (child.type === "import_statement") {
201
- const sourceNode =
202
- child.childForFieldName("source") ??
203
- child.namedChildren.find((c) => c.type === "string");
204
- const specifier = cleanLiteral(sourceNode);
205
- if (!specifier) continue;
206
-
207
- const res = resolver.resolve(specifier, relPath);
208
- const targetFile = res.status === "resolved" && res.targets[0]?.files[0] ? res.targets[0].files[0] : undefined;
209
- if (!targetFile) continue;
108
+ if (!ts.isPropertyAccessExpression(node.expression) || node.expression.questionDotToken) return undefined;
109
+ const name = node.expression.name.text;
110
+ const parent = receiverOf(node.expression.expression);
111
+ if (!parent) return undefined;
112
+ let receiver: Receiver | undefined;
113
+ if (name === "route" && parent.paths === undefined) {
114
+ const paths = stringPaths(node.arguments[0]);
115
+ if (paths) receiver = { router: parent.router, paths };
116
+ } else if (verbs.has(name) || name === "use" && parent.paths === undefined) receiver = parent;
117
+ receivers.set(node, receiver);
118
+ return receiver;
119
+ };
210
120
 
211
- // Default import
212
- const importClause = child.namedChildren.find((c) => c.type === "import_clause");
213
- if (importClause) {
214
- for (const ic of importClause.namedChildren) {
215
- if (ic.type === "identifier") {
216
- resolvedImports.set(ic.text.trim(), targetFile);
217
- } else if (ic.type === "namespace_import") {
218
- const identNode = ic.namedChildren.find((n) => n.type === "identifier");
219
- if (identNode) resolvedImports.set(identNode.text.trim(), targetFile);
220
- } else if (ic.type === "named_imports") {
221
- for (const spec of ic.namedChildren) {
222
- if (spec.type === "import_specifier") {
223
- const alias = spec.childForFieldName("alias");
224
- const name = spec.childForFieldName("name") ?? spec.namedChildren[0];
225
- const ident = alias ? alias.text.trim() : name ? name.text.trim() : "";
226
- if (ident) resolvedImports.set(ident, targetFile);
227
- }
228
- }
121
+ const routeCallHint = /\.(?:use|get|post|put|patch|delete|head|options|trace|connect|all|route)\s*\(/;
122
+ for (const file of files) {
123
+ signal?.throwIfAborted();
124
+ if (!bindings.matches(file, routeCallHint)) continue;
125
+ const unit = bindings.load(file);
126
+ if (!unit) continue;
127
+ visitRouteCalls(unit.source, call => {
128
+ signal?.throwIfAborted();
129
+ const member = call.expression;
130
+ if (call.questionDotToken || !ts.isPropertyAccessExpression(member) || member.questionDotToken) return;
131
+ const name = member.name.text;
132
+ if (name !== "use" && !verbs.has(name)) return;
133
+ const receiver = receiverOf(member.expression);
134
+ if (!receiver) return;
135
+
136
+ if (name === "use") {
137
+ if (receiver.paths !== undefined || !call.arguments.length) return;
138
+ const first = call.arguments[0]!;
139
+ const knownPaths = stringPaths(first);
140
+ const allCallbacks = flattenedArguments(call.arguments);
141
+ const firstRouter = receiverOf(first);
142
+ const implicitPath = firstRouter || bindings.handler(first) ||
143
+ ts.isArrayLiteralExpression(first) && first.elements.some(element => receiverOf(element) || bindings.handler(element));
144
+ const prefixes = knownPaths ? knownPaths.map(value => value.replace(/\/+$/, "")) :
145
+ [implicitPath ? "" : undefined];
146
+ const callbacks = knownPaths ? flattenedArguments(call.arguments.slice(1)) : allCallbacks;
147
+ const nonRouterCallbacks: ts.Expression[] = [];
148
+ for (const argument of callbacks) {
149
+ const child = receiverOf(argument);
150
+ if (!child || child.paths !== undefined || child.router === receiver.router) {
151
+ nonRouterCallbacks.push(argument);
152
+ continue;
229
153
  }
154
+ for (const prefix of prefixes) mounts.push({ parent: receiver.router, child: child.router, prefix });
230
155
  }
231
- }
232
- }
233
- }
234
-
235
- // 2. Walk call expressions for routes and mounts
236
- const walkCalls = (node: Parser.SyntaxNode): void => {
237
- if (node.type === "call_expression") {
238
- const fnNode = node.childForFieldName("function");
239
- if (fnNode && fnNode.type === "member_expression") {
240
- const objNode = fnNode.childForFieldName("object");
241
- const propNode = fnNode.childForFieldName("property");
242
- const argsNode = node.childForFieldName("arguments");
243
-
244
- if (objNode && propNode && argsNode) {
245
- const callerVar = objNode.text.trim();
246
- const methodName = propNode.text.trim().toLowerCase();
247
- const args = argsNode.namedChildren;
248
-
249
- // Route Mount: app.use('/api', apiRouter) or router.use('/sub', subRouter)
250
- if (methodName === "use") {
251
- if (args.length >= 1) {
252
- const firstLit = cleanLiteral(args[0]);
253
- const hasPath = firstLit !== undefined;
254
- const prefix = hasPath ? firstLit : "";
255
- const targetArg = hasPath ? args[1] : args[0];
256
-
257
- if (targetArg && targetArg.type === "identifier") {
258
- mounts.push({
259
- file: relPath,
260
- relPath,
261
- callerVar,
262
- prefix,
263
- targetVar: targetArg.text.trim(),
264
- line: node.startPosition.row + 1,
265
- });
266
- }
267
- }
268
- } else if (EXPRESS_VERBS.has(methodName)) {
269
- // Direct HTTP Route: app.get('/path', ...middlewares, handler)
270
- if (args.length >= 2) {
271
- const rawPath = cleanLiteral(args[0]);
272
- if (rawPath !== undefined) {
273
- const middlewareNodes = args.slice(1, args.length - 1);
274
- const handlerNode = args[args.length - 1];
275
-
276
- const middlewares = this.extractHandlers(middlewareNodes);
277
- const handler = this.extractSingleHandler(handlerNode);
278
-
279
- routes.push({
280
- file: relPath,
281
- relPath,
282
- routerVar: callerVar,
283
- httpMethod: methodName.toUpperCase(),
284
- rawPath,
285
- middlewares,
286
- handler,
287
- routeLine: node.startPosition.row + 1,
288
- });
289
- }
290
- }
156
+ if (knownPaths?.length && nonRouterCallbacks.length) {
157
+ const gql = nonRouterCallbacks.some((arg) =>
158
+ isGraphQLRouteOrHandler({ uri: knownPaths[0], handlerName: arg.getText() })
159
+ );
160
+ if (gql) {
161
+ routes.push({ router: receiver.router, call, paths: knownPaths, callbacks: nonRouterCallbacks, method: "ANY" });
291
162
  }
292
163
  }
164
+ return;
293
165
  }
294
- }
295
-
296
- for (const child of node.namedChildren) {
297
- walkCalls(child);
298
- }
299
- };
300
-
301
- walkCalls(rootNode);
302
- return { routes, mounts, resolvedImports };
303
- }
304
-
305
- private extractSingleHandler(node: Parser.SyntaxNode): { symbol: string; line: number } {
306
- const line = node.startPosition.row + 1;
307
- if (node.type === "identifier" || node.type === "member_expression") {
308
- return { symbol: node.text.trim(), line };
309
- }
310
- if (node.type === "arrow_function" || node.type === "function_expression" || node.type === "function") {
311
- const nameNode = node.childForFieldName("name");
312
- const name = nameNode ? nameNode.text.trim() : "closure";
313
- return { symbol: name, line };
314
- }
315
- return { symbol: "closure", line };
316
- }
317
-
318
- private extractHandlers(nodes: Parser.SyntaxNode[]): Array<{ symbol: string; line: number }> {
319
- const list: Array<{ symbol: string; line: number }> = [];
320
- for (const node of nodes) {
321
- if (node.type === "array") {
322
- for (const el of node.namedChildren) {
323
- list.push(this.extractSingleHandler(el));
324
- }
325
- } else {
326
- list.push(this.extractSingleHandler(node));
327
- }
328
- }
329
- return list;
330
- }
331
-
332
- private resolvePrefixHierarchy(
333
- mounts: RawMount[],
334
- fileImports: Map<string, Map<string, string>>
335
- ): Map<string, string[]> {
336
- // Map: (relPath#varName) -> array of prefixes
337
- const prefixes = new Map<string, Set<string>>();
338
-
339
- const getPrefixes = (key: string): Set<string> => {
340
- let set = prefixes.get(key);
341
- if (!set) {
342
- set = new Set<string>();
343
- prefixes.set(key, set);
344
- }
345
- return set;
346
- };
347
166
 
348
- // 1. Identify root app variables (e.g. app in app.ts) which start with root prefix ""
349
- // Also identify top-level callers that are not targets of any mount
350
- const targetedCallers = new Set<string>();
351
- for (const mount of mounts) {
352
- const fileMap = fileImports.get(mount.relPath);
353
- const importedFile = fileMap?.get(mount.targetVar);
354
- if (importedFile) {
355
- targetedCallers.add(`${importedFile}#router`);
356
- targetedCallers.add(`${importedFile}#default`);
357
- targetedCallers.add(`${importedFile}#${mount.targetVar}`);
358
- for (const m of mounts) {
359
- if (m.relPath === importedFile) {
360
- targetedCallers.add(`${importedFile}#${m.callerVar}`);
361
- }
167
+ const paths = receiver.paths ?? stringPaths(call.arguments[0]);
168
+ const callbacks = flattenedArguments(receiver.paths !== undefined ? call.arguments : call.arguments.slice(1));
169
+ if (paths?.length && callbacks.length) {
170
+ routes.push({ router: receiver.router, call, paths, callbacks, method: name === "all" ? "ANY" : name.toUpperCase() });
362
171
  }
363
- } else {
364
- targetedCallers.add(`${mount.relPath}#${mount.targetVar}`);
365
- }
172
+ });
366
173
  }
367
174
 
368
- for (const mount of mounts) {
369
- const callerKey = `${mount.relPath}#${mount.callerVar}`;
370
- if (mount.callerVar === "app" || mount.callerVar === "server" || !targetedCallers.has(callerKey)) {
371
- getPrefixes(callerKey).add("");
372
- }
373
- }
374
-
375
- // 2. Propagate mounts
376
- let changed = true;
377
- let iterations = 0;
378
-
379
- while (changed && iterations < 10) {
380
- changed = false;
381
- iterations++;
382
-
383
- for (const mount of mounts) {
384
- const callerKey = `${mount.relPath}#${mount.callerVar}`;
385
- const callerPrefixes = getPrefixes(callerKey);
386
- if (callerPrefixes.size === 0) continue;
387
- const basePrefixes = Array.from(callerPrefixes);
388
-
389
- // Check if targetVar is imported from another file
390
- const fileMap = fileImports.get(mount.relPath);
391
- const importedFile = fileMap?.get(mount.targetVar);
392
-
393
- const targetKeys: string[] = [];
394
- if (importedFile) {
395
- // Cross-file mount: target router in importedFile
396
- targetKeys.push(`${importedFile}#router`, `${importedFile}#default`, `${importedFile}#${mount.targetVar}`);
397
- // Also any router variable in importedFile
398
- for (const m of mounts) {
399
- if (m.relPath === importedFile) {
400
- targetKeys.push(`${importedFile}#${m.callerVar}`);
175
+ const prefixesByRouter = composeMountPrefixes(roots, mounts, signal);
176
+ const slices: VerticalSliceCandidate[] = [];
177
+ for (const route of routes) {
178
+ signal?.throwIfAborted();
179
+ const prefixes = prefixesByRouter.get(route.router) ?? [];
180
+ const registrationFile = relative(route.call);
181
+ const registrationLine = lineOf(route.call);
182
+ const primaryIndex = (() => {
183
+ if (route.callbacks.length > 1) {
184
+ const last = route.callbacks.at(-1)!;
185
+ if (ts.isIdentifier(last) && /^(?:respond|send|finish)$/i.test(last.text)) {
186
+ for (let idx = route.callbacks.length - 2; idx >= 0; idx--) {
187
+ if (bindings.handler(route.callbacks[idx])) return idx;
401
188
  }
402
189
  }
403
- } else {
404
- // Local mount in same file
405
- targetKeys.push(`${mount.relPath}#${mount.targetVar}`);
406
190
  }
191
+ return route.callbacks.length - 1;
192
+ })();
193
+ const expression = route.callbacks[primaryIndex]!;
194
+ const handler = bindings.handler(expression);
195
+ const controllerFile = handler ? relative(handler.node) : null;
196
+ const controllerLine = handler ? lineOf(handler.node) : 0;
197
+ const actionName = handler ? (handler.name === "callback" ? "closure" : handler.name) : expression.getText();
198
+ const registrationName = ts.isIdentifier(expression) || ts.isPropertyAccessExpression(expression)
199
+ ? expression.getText() : actionName;
200
+ const controllerClass = ts.isPropertyAccessExpression(expression) ? expression.expression.getText() :
201
+ path.basename(controllerFile ?? registrationFile).replace(/\.[^.]+$/, "");
202
+ const middlewares: ExecutionChainNode[] = route.callbacks
203
+ .filter((_, idx) => idx !== primaryIndex)
204
+ .map(callback => ({
205
+ stage: "middleware", symbol: callback.getText(), file: relative(callback), line: lineOf(callback),
206
+ description: "Express Middleware Argument",
207
+ }));
407
208
 
408
- for (const targetKey of targetKeys) {
409
- const targetSet = getPrefixes(targetKey);
410
- for (const baseP of basePrefixes) {
411
- const combined = normalizeRouteUri(baseP, mount.prefix);
412
- if (!targetSet.has(combined)) {
413
- targetSet.add(combined);
414
- changed = true;
415
- }
209
+ for (const prefix of prefixes) {
210
+ for (const localPath of route.paths) {
211
+ const uri = normalizeUri(prefix, localPath);
212
+ const chain: ExecutionChainNode[] = [{
213
+ stage: "ingress", symbol: route.method + " " + uri, file: registrationFile, line: registrationLine,
214
+ description: "Express Route Registration",
215
+ }, ...middlewares];
216
+ if (handler && controllerFile) {
217
+ chain.push({
218
+ stage: "controller", symbol: registrationName, file: controllerFile, line: controllerLine,
219
+ description: "Express Action Handler",
220
+ });
416
221
  }
222
+ slices.push({
223
+ domain_id: domainId ?? null,
224
+ feature_key: `express.${controllerClass.toLowerCase()}.${actionName}`,
225
+ http_method: route.method,
226
+ route_uri: uri,
227
+ route_name: `${controllerClass}.${actionName}`,
228
+ controller_class: controllerClass,
229
+ action_name: actionName,
230
+ controller_file: controllerFile,
231
+ controller_line: controllerLine,
232
+ architecture_style: "mvc",
233
+ entry_kind: "http_route",
234
+ execution_chain_json: JSON.stringify(chain),
235
+ });
417
236
  }
418
237
  }
419
238
  }
420
-
421
- // Convert Set to Array
422
- const result = new Map<string, string[]>();
423
- for (const [k, set] of prefixes.entries()) {
424
- result.set(k, Array.from(set));
425
- }
426
- return result;
239
+ return slices;
427
240
  }
428
241
  }
429
-