@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,65 +1,41 @@
1
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
2
- import { parseWithTreeSitter } from "../wasm-loader.ts";
3
- import { ImportResolver } from "../../resolver/import-resolver.ts";
4
- import type Parser from "web-tree-sitter";
5
1
  import * as fs from "node:fs";
6
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";
7
8
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
8
-
9
- const EXPRESS_VERBS = new Set([
10
- "get",
11
- "post",
12
- "put",
13
- "patch",
14
- "delete",
15
- "all",
16
- "head",
17
- "options",
18
- ]);
19
-
20
- interface RawRoute {
21
- file: string;
22
- relPath: string;
23
- routerVar: string;
24
- httpMethod: string;
25
- rawPath: string;
26
- middlewares: Array<{ symbol: string; line: number }>;
27
- handler: { symbol: string; line: number };
28
- routeLine: number;
29
- }
30
-
31
- interface RawMount {
32
- file: string;
33
- relPath: string;
34
- callerVar: string;
35
- prefix: string;
36
- targetVar: string;
37
- line: number;
38
- }
39
-
40
- interface ImportBinding {
41
- importedName: string;
42
- sourceSpecifier: string;
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;
43
30
  }
44
31
 
45
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
46
- if (!node) return undefined;
47
- if (node.type === "string" || node.type === "template_string") {
48
- const raw = node.text.trim();
49
- if (raw.includes("${")) return undefined;
50
- return raw.replace(/^['"`]|['"`]$/g, "");
51
- }
52
- return undefined;
32
+ function flattenedArguments(argumentsList: readonly ts.Expression[]): ts.Expression[] {
33
+ return argumentsList.flatMap(arg => ts.isArrayLiteralExpression(arg) ? flattenedArguments(arg.elements) : [arg]);
53
34
  }
54
35
 
55
- function normalizeRouteUri(prefix: string, rawPath: string): string {
56
- const p = (prefix ?? "").trim().replace(/\/+$/, "");
57
- let r = (rawPath ?? "").trim();
58
- if (!r.startsWith("/")) r = "/" + r;
59
- if (r === "/" && p.length > 0) return p;
60
- if (r === "/" && p.length === 0) return "/";
61
- const joined = `${p}${r}`;
62
- return joined.startsWith("/") ? joined : `/${joined}`;
36
+ function normalizeUri(prefix: string, route: string): string {
37
+ const uri = prefix + (route === "/" && prefix ? "" : "/" + route.replace(/^\/+/, ""));
38
+ return uri || "/";
63
39
  }
64
40
 
65
41
  export class ExpressSemanticExtractor implements SemanticSliceExtractor {
@@ -68,377 +44,198 @@ export class ExpressSemanticExtractor implements SemanticSliceExtractor {
68
44
 
69
45
  public canHandle(projectRoot: string, framework?: string): boolean {
70
46
  if (framework === "express") return true;
71
-
72
- const pkgPath = path.join(projectRoot, "package.json");
73
- 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;
74
51
  try {
75
- const pkg = JSON.parse(readOptionalSourceFile(pkgPath, "utf-8"));
76
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
77
- if (deps["express"]) return true;
78
- } 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
+ }
79
75
  }
80
-
81
76
  return false;
82
77
  }
83
78
 
84
79
  public async extractSlices(
85
80
  projectRoot: string,
86
81
  domainId?: number,
87
- signal?: AbortSignal
82
+ signal?: AbortSignal,
83
+ inventory?: SourceInventory,
88
84
  ): Promise<VerticalSliceCandidate[]> {
89
- const slices: VerticalSliceCandidate[] = [];
90
- const sourceFiles = this.findSourceFiles(projectRoot);
91
- const resolver = new ImportResolver(projectRoot);
92
-
93
- const allRoutes: RawRoute[] = [];
94
- const allMounts: RawMount[] = [];
95
- const fileImports = new Map<string, Map<string, string>>(); // relPath -> (importedIdent -> targetRelPath)
96
-
97
- for (const file of sourceFiles) {
98
- if (signal?.aborted) throw new Error("semantic_extraction_cancelled");
99
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
100
- const content = readOptionalSourceFile(file, "utf-8");
101
- if (!content || (!content.includes(".get") && !content.includes(".post") && !content.includes(".use") && !content.includes(".route") && !content.includes("Router") && !content.includes("express"))) {
102
- continue;
103
- }
104
-
105
- const fileData = await parseWithTreeSitter(
106
- "typescript",
107
- content,
108
- (rootNode) => this.extractFileAst(file, relPath, rootNode, resolver)
109
- );
110
-
111
- if (fileData) {
112
- allRoutes.push(...fileData.routes);
113
- allMounts.push(...fileData.mounts);
114
- if (fileData.resolvedImports.size > 0) {
115
- fileImports.set(relPath, fileData.resolvedImports);
116
- }
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;
117
106
  }
118
- }
119
-
120
- // Resolve Router Prefix Hierarchy
121
- const routerPrefixes = this.resolvePrefixHierarchy(allMounts, fileImports);
122
-
123
- // Build Vertical Slices
124
- for (const route of allRoutes) {
125
- const prefixes = routerPrefixes.get(`${route.relPath}#${route.routerVar}`) || [""];
126
-
127
- for (const prefix of prefixes) {
128
- const fullUri = normalizeRouteUri(prefix, route.rawPath);
129
- const actionSymbol = route.handler.symbol;
130
- const rootIdent = actionSymbol.includes(".") ? actionSymbol.split(".")[0] : actionSymbol;
131
- const imports = fileImports.get(route.relPath);
132
- const resolvedControllerFile = imports?.get(rootIdent) || route.relPath;
133
- const fileBase = path.basename(route.relPath).replace(/\.[^.]+$/, "");
134
- const controllerClass = actionSymbol.includes(".")
135
- ? actionSymbol.split(".")[0]
136
- : fileBase.charAt(0).toUpperCase() + fileBase.slice(1);
137
- const actionName = actionSymbol.includes(".") ? actionSymbol.split(".").pop()! : actionSymbol;
138
-
139
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
140
- {
141
- stage: "ingress",
142
- symbol: `${route.httpMethod} ${fullUri}`,
143
- file: route.relPath,
144
- line: route.routeLine,
145
- description: `Express Route: ${route.httpMethod} ${fullUri}`,
146
- },
147
- ];
148
107
 
149
- for (const mw of route.middlewares) {
150
- chain.push({
151
- stage: "middleware",
152
- symbol: mw.symbol,
153
- file: route.relPath,
154
- line: mw.line,
155
- description: `Express Middleware: ${mw.symbol}`,
156
- });
157
- }
158
-
159
- chain.push({
160
- stage: "controller",
161
- symbol: actionSymbol,
162
- file: resolvedControllerFile,
163
- line: route.handler.line,
164
- description: `Express Action Handler`,
165
- });
166
-
167
- slices.push({
168
- domain_id: domainId ?? null,
169
- feature_key: `express.${controllerClass.toLowerCase()}.${actionName}`,
170
- http_method: route.httpMethod,
171
- route_uri: fullUri,
172
- route_name: `${controllerClass}.${actionName}`,
173
- controller_class: controllerClass,
174
- action_name: actionName,
175
- controller_file: resolvedControllerFile,
176
- controller_line: route.handler.line,
177
- architecture_style: "mvc",
178
- entry_kind: "http_route",
179
- execution_chain_json: JSON.stringify(chain),
180
- });
181
- }
182
- }
183
-
184
- return slices;
185
- }
186
-
187
- private extractFileAst(
188
- _filePath: string,
189
- relPath: string,
190
- rootNode: Parser.SyntaxNode,
191
- resolver: ImportResolver
192
- ): { routes: RawRoute[]; mounts: RawMount[]; resolvedImports: Map<string, string> } {
193
- const routes: RawRoute[] = [];
194
- const mounts: RawMount[] = [];
195
- const resolvedImports = new Map<string, string>();
196
-
197
- // 1. Collect static imports
198
- for (const child of rootNode.namedChildren) {
199
- if (child.type === "import_statement") {
200
- const sourceNode =
201
- child.childForFieldName("source") ??
202
- child.namedChildren.find((c) => c.type === "string");
203
- const specifier = cleanLiteral(sourceNode);
204
- if (!specifier) continue;
205
-
206
- const res = resolver.resolve(specifier, relPath);
207
- const targetFile = res.status === "resolved" && res.targets[0]?.files[0] ? res.targets[0].files[0] : undefined;
208
- 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
+ };
209
120
 
210
- // Default import
211
- const importClause = child.namedChildren.find((c) => c.type === "import_clause");
212
- if (importClause) {
213
- for (const ic of importClause.namedChildren) {
214
- if (ic.type === "identifier") {
215
- resolvedImports.set(ic.text.trim(), targetFile);
216
- } else if (ic.type === "namespace_import") {
217
- const identNode = ic.namedChildren.find((n) => n.type === "identifier");
218
- if (identNode) resolvedImports.set(identNode.text.trim(), targetFile);
219
- } else if (ic.type === "named_imports") {
220
- for (const spec of ic.namedChildren) {
221
- if (spec.type === "import_specifier") {
222
- const alias = spec.childForFieldName("alias");
223
- const name = spec.childForFieldName("name") ?? spec.namedChildren[0];
224
- const ident = alias ? alias.text.trim() : name ? name.text.trim() : "";
225
- if (ident) resolvedImports.set(ident, targetFile);
226
- }
227
- }
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;
228
153
  }
154
+ for (const prefix of prefixes) mounts.push({ parent: receiver.router, child: child.router, prefix });
229
155
  }
230
- }
231
- }
232
- }
233
-
234
- // 2. Walk call expressions for routes and mounts
235
- const walkCalls = (node: Parser.SyntaxNode): void => {
236
- if (node.type === "call_expression") {
237
- const fnNode = node.childForFieldName("function");
238
- if (fnNode && fnNode.type === "member_expression") {
239
- const objNode = fnNode.childForFieldName("object");
240
- const propNode = fnNode.childForFieldName("property");
241
- const argsNode = node.childForFieldName("arguments");
242
-
243
- if (objNode && propNode && argsNode) {
244
- const callerVar = objNode.text.trim();
245
- const methodName = propNode.text.trim().toLowerCase();
246
- const args = argsNode.namedChildren;
247
-
248
- // Route Mount: app.use('/api', apiRouter) or router.use('/sub', subRouter)
249
- if (methodName === "use") {
250
- if (args.length >= 1) {
251
- const firstLit = cleanLiteral(args[0]);
252
- const hasPath = firstLit !== undefined;
253
- const prefix = hasPath ? firstLit : "";
254
- const targetArg = hasPath ? args[1] : args[0];
255
-
256
- if (targetArg && targetArg.type === "identifier") {
257
- mounts.push({
258
- file: relPath,
259
- relPath,
260
- callerVar,
261
- prefix,
262
- targetVar: targetArg.text.trim(),
263
- line: node.startPosition.row + 1,
264
- });
265
- }
266
- }
267
- } else if (EXPRESS_VERBS.has(methodName)) {
268
- // Direct HTTP Route: app.get('/path', ...middlewares, handler)
269
- if (args.length >= 2) {
270
- const rawPath = cleanLiteral(args[0]);
271
- if (rawPath !== undefined) {
272
- const middlewareNodes = args.slice(1, args.length - 1);
273
- const handlerNode = args[args.length - 1];
274
-
275
- const middlewares = this.extractHandlers(middlewareNodes);
276
- const handler = this.extractSingleHandler(handlerNode);
277
-
278
- routes.push({
279
- file: relPath,
280
- relPath,
281
- routerVar: callerVar,
282
- httpMethod: methodName.toUpperCase(),
283
- rawPath,
284
- middlewares,
285
- handler,
286
- routeLine: node.startPosition.row + 1,
287
- });
288
- }
289
- }
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" });
290
162
  }
291
163
  }
164
+ return;
292
165
  }
293
- }
294
166
 
295
- for (const child of node.namedChildren) {
296
- walkCalls(child);
297
- }
298
- };
299
-
300
- walkCalls(rootNode);
301
- return { routes, mounts, resolvedImports };
302
- }
303
-
304
- private extractSingleHandler(node: Parser.SyntaxNode): { symbol: string; line: number } {
305
- const line = node.startPosition.row + 1;
306
- if (node.type === "identifier" || node.type === "member_expression") {
307
- return { symbol: node.text.trim(), line };
308
- }
309
- if (node.type === "arrow_function" || node.type === "function_expression" || node.type === "function") {
310
- const nameNode = node.childForFieldName("name");
311
- const name = nameNode ? nameNode.text.trim() : "closure";
312
- return { symbol: name, line };
313
- }
314
- return { symbol: "closure", line };
315
- }
316
-
317
- private extractHandlers(nodes: Parser.SyntaxNode[]): Array<{ symbol: string; line: number }> {
318
- const list: Array<{ symbol: string; line: number }> = [];
319
- for (const node of nodes) {
320
- if (node.type === "array") {
321
- for (const el of node.namedChildren) {
322
- list.push(this.extractSingleHandler(el));
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() });
323
171
  }
324
- } else {
325
- list.push(this.extractSingleHandler(node));
326
- }
172
+ });
327
173
  }
328
- return list;
329
- }
330
-
331
- private resolvePrefixHierarchy(
332
- mounts: RawMount[],
333
- fileImports: Map<string, Map<string, string>>
334
- ): Map<string, string[]> {
335
- // Map: (relPath#varName) -> array of prefixes
336
- const prefixes = new Map<string, Set<string>>();
337
174
 
338
- const getPrefixes = (key: string): Set<string> => {
339
- let set = prefixes.get(key);
340
- if (!set) {
341
- set = new Set<string>();
342
- prefixes.set(key, set);
343
- }
344
- return set;
345
- };
346
-
347
- // 1. Identify root app variables (e.g. app in app.ts) which start with root prefix ""
348
- // Also identify top-level callers that are not targets of any mount
349
- const targetedCallers = new Set<string>();
350
- for (const mount of mounts) {
351
- const fileMap = fileImports.get(mount.relPath);
352
- const importedFile = fileMap?.get(mount.targetVar);
353
- if (importedFile) {
354
- targetedCallers.add(`${importedFile}#router`);
355
- targetedCallers.add(`${importedFile}#default`);
356
- targetedCallers.add(`${importedFile}#${mount.targetVar}`);
357
- for (const m of mounts) {
358
- if (m.relPath === importedFile) {
359
- targetedCallers.add(`${importedFile}#${m.callerVar}`);
360
- }
361
- }
362
- } else {
363
- targetedCallers.add(`${mount.relPath}#${mount.targetVar}`);
364
- }
365
- }
366
-
367
- for (const mount of mounts) {
368
- const callerKey = `${mount.relPath}#${mount.callerVar}`;
369
- if (mount.callerVar === "app" || mount.callerVar === "server" || !targetedCallers.has(callerKey)) {
370
- getPrefixes(callerKey).add("");
371
- }
372
- }
373
-
374
- // 2. Propagate mounts
375
- let changed = true;
376
- let iterations = 0;
377
-
378
- while (changed && iterations < 10) {
379
- changed = false;
380
- iterations++;
381
-
382
- for (const mount of mounts) {
383
- const callerKey = `${mount.relPath}#${mount.callerVar}`;
384
- const callerPrefixes = getPrefixes(callerKey);
385
- if (callerPrefixes.size === 0) continue;
386
- const basePrefixes = Array.from(callerPrefixes);
387
-
388
- // Check if targetVar is imported from another file
389
- const fileMap = fileImports.get(mount.relPath);
390
- const importedFile = fileMap?.get(mount.targetVar);
391
-
392
- const targetKeys: string[] = [];
393
- if (importedFile) {
394
- // Cross-file mount: target router in importedFile
395
- targetKeys.push(`${importedFile}#router`, `${importedFile}#default`, `${importedFile}#${mount.targetVar}`);
396
- // Also any router variable in importedFile
397
- for (const m of mounts) {
398
- if (m.relPath === importedFile) {
399
- 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;
400
188
  }
401
189
  }
402
- } else {
403
- // Local mount in same file
404
- targetKeys.push(`${mount.relPath}#${mount.targetVar}`);
405
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
+ }));
406
208
 
407
- for (const targetKey of targetKeys) {
408
- const targetSet = getPrefixes(targetKey);
409
- for (const baseP of basePrefixes) {
410
- const combined = normalizeRouteUri(baseP, mount.prefix);
411
- if (!targetSet.has(combined)) {
412
- targetSet.add(combined);
413
- changed = true;
414
- }
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
+ });
415
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
+ });
416
236
  }
417
237
  }
418
238
  }
419
-
420
- // Convert Set to Array
421
- const result = new Map<string, string[]>();
422
- for (const [k, set] of prefixes.entries()) {
423
- result.set(k, Array.from(set));
424
- }
425
- return result;
426
- }
427
-
428
- private findSourceFiles(dir: string): string[] {
429
- const results: string[] = [];
430
- try {
431
- const entries = fs.readdirSync(dir, { withFileTypes: true });
432
- for (const entry of entries) {
433
- const full = path.join(dir, entry.name);
434
- if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules" && entry.name !== "dist") {
435
- results.push(...this.findSourceFiles(full));
436
- } else if (entry.isFile() && /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
437
- results.push(full);
438
- }
439
- }
440
- } catch {}
441
- return results;
239
+ return slices;
442
240
  }
443
241
  }
444
-