@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,21 +1,28 @@
1
+ import { composeMountPrefixes } from "./route-prefixes.ts";
1
2
  import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
3
  import { readPythonStaticString as cleanLiteral } from "../static-string.ts";
3
4
  import type Parser from "web-tree-sitter";
5
+ import {
6
+ pythonCallArgument, pythonCallUsesUnpacking, pythonLiteralMethods, resolvePythonRouterTarget,
7
+ visitPythonRouterModule, type PythonImport, type PythonRouterTarget,
8
+ } from "./python-route-ast.ts";
4
9
  import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
5
10
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
6
11
  import { ImportResolver } from "../../resolver/import-resolver.ts";
7
12
  import * as fs from "node:fs";
8
13
  import * as path from "node:path";
14
+ import { anyFileContains } from "./manifest-helpers.ts";
9
15
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
10
16
 
11
17
  interface ExtractedRoute {
12
18
  file: string;
13
19
  relPath: string;
14
20
  routerVar: string;
21
+ routerKey: string;
22
+ name?: string;
15
23
  httpMethod: string;
16
24
  rawPath: string;
17
25
  actionName: string;
18
- params: string;
19
26
  lineIndex: number;
20
27
  actionLine: number;
21
28
  validationSchema?: string;
@@ -28,22 +35,28 @@ interface ExtractedRoute {
28
35
 
29
36
  interface ExtractedInclusion {
30
37
  file: string;
31
- relPath: string;
32
- parentVar: string;
33
- targetExpr: string;
38
+ parentKey: string;
39
+ target: PythonRouterTarget;
34
40
  prefix: string | undefined;
35
- line: number;
36
41
  }
37
42
 
38
- interface ImportBinding {
39
- module: string;
40
- symbol?: string;
41
- }
43
+ type Router = { prefix: string | undefined; isApp: boolean; guards: string[]; dependencies: string[] };
44
+ type Node = Parser.SyntaxNode;
45
+
46
+ const verbs = /^(get|post|put|patch|delete|options|head|trace)$/;
42
47
 
48
+ function routeMethods(call: Node, method: string): string[] {
49
+ if (verbs.test(method)) return [method.toUpperCase()];
50
+ const methods = pythonCallArgument(call, "methods");
51
+ if (!methods || methods.type === "none") return ["GET"];
52
+ const literal = pythonLiteralMethods(methods);
53
+ return literal?.length === 0 ? ["GET"] : literal ?? [];
54
+ }
43
55
 
44
56
  function normalizeRouteUri(prefix: string, rawPath: string): string {
45
57
  const p = (prefix ?? "").trim().replace(/\/+$/, "");
46
58
  let r = (rawPath ?? "").trim();
59
+ if (!r) return p || "/";
47
60
  if (!r.startsWith("/")) r = "/" + r;
48
61
  if (r === "/" && p.length > 0) return p + "/";
49
62
  if (r === "/" && p.length === 0) return "/";
@@ -86,31 +99,15 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
86
99
  public canHandle(projectRoot: string, framework?: string): boolean {
87
100
  if (framework === "fastapi") return true;
88
101
 
89
- // Check configuration manifests
90
- for (const manifest of ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"]) {
91
- const fullPath = path.join(projectRoot, manifest);
92
- if (fs.existsSync(fullPath)) {
93
- try {
94
- const content = fs.readFileSync(fullPath, "utf-8").toLowerCase();
95
- if (content.includes("fastapi")) return true;
96
- } catch {}
97
- }
102
+ if (anyFileContains(projectRoot, ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"], ["fastapi"], true)) {
103
+ return true;
98
104
  }
99
105
 
100
- // Check entrypoint files
101
- for (const entry of ["main.py", "app.py", "api.py", "src/main.py", "app/main.py"]) {
102
- const fullPath = path.join(projectRoot, entry);
103
- if (fs.existsSync(fullPath)) {
104
- try {
105
- const content = fs.readFileSync(fullPath, "utf-8");
106
- if (content.includes("from fastapi") || content.includes("import fastapi")) {
107
- return true;
108
- }
109
- } catch {}
110
- }
111
- }
112
-
113
- return false;
106
+ return anyFileContains(
107
+ projectRoot,
108
+ ["main.py", "app.py", "api.py", "src/main.py", "app/main.py"],
109
+ ["from fastapi", "import fastapi"]
110
+ );
114
111
  }
115
112
 
116
113
  public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): Promise<VerticalSliceCandidate[]> {
@@ -120,262 +117,180 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
120
117
 
121
118
  const allRoutes: ExtractedRoute[] = [];
122
119
  const allInclusions: ExtractedInclusion[] = [];
123
- const localRouters = new Map<
124
- string,
125
- { prefix: string | undefined; isApp: boolean; guards?: string[]; dependencies?: string[] }
126
- >();
127
- const fileImports = new Map<string, Map<string, ImportBinding>>();
120
+ const localRouters = new Map<string, Router>();
121
+ const fileRouters = new Map<string, Map<string, string>>();
122
+ const fileImports = new Map<string, Map<string, PythonImport>>();
128
123
 
129
124
  for (const file of pyFiles) {
130
125
  signal?.throwIfAborted();
131
126
  const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
132
127
  const content = readOptionalSourceFile(file, "utf-8");
133
- if (!content || (!content.includes("@") && !content.includes("include_router") && !content.includes("APIRouter") && !content.includes("FastAPI"))) {
128
+ if (!content || !/@\s*[A-Za-z_]\w*\.(?:get|post|put|patch|delete|options|head|trace|api_route|route|websocket)\b|include_router|APIRouter|FastAPI|add_api_route/.test(content)) {
134
129
  continue;
135
130
  }
136
131
 
137
- const importsInFile = new Map<string, ImportBinding>();
138
- fileImports.set(relPath, importsInFile);
139
-
140
132
  const parsed = await parseSourceWithTreeSitter("python", content, (root) => {
141
133
  const walk = (node: Parser.SyntaxNode, visit: (node: Parser.SyntaxNode) => void) => {
142
134
  visit(node);
143
135
  for (const child of node.namedChildren) walk(child, visit);
144
136
  };
145
137
 
146
- // 1. Collect import statements
147
- walk(root, (node) => {
148
- if (node.type === "import_statement") {
149
- for (const child of node.namedChildren) {
150
- if (child.type === "dotted_name") {
151
- const mod = child.text.trim();
152
- const alias = mod.split(".").pop() || mod;
153
- importsInFile.set(alias, { module: mod });
154
- } else if (child.type === "aliased_import") {
155
- const orig = child.childForFieldName("name")?.text?.trim();
156
- const alias = child.childForFieldName("alias")?.text?.trim();
157
- if (orig && alias) {
158
- importsInFile.set(alias, { module: orig });
138
+ const readRoute = (call: Node, method: string, receiver: string, routerKey: string, fn: Node, line: number) => {
139
+ if (pythonCallUsesUnpacking(call)) return;
140
+ const rawPath = cleanLiteral(pythonCallArgument(call, "path", 0));
141
+ const methods = routeMethods(call, method);
142
+ const actionName = fn.childForFieldName("name")?.text;
143
+ if (rawPath === undefined || !methods.length || !actionName) return;
144
+ const name = cleanLiteral(pythonCallArgument(call, "name"));
145
+ const args = call.childForFieldName("arguments")?.namedChildren ?? [];
146
+ const paramsText = fn.childForFieldName("parameters")?.text ?? "";
147
+
148
+ // Extract Pydantic validation schema from typed parameters
149
+ let validationSchema: string | undefined;
150
+ const paramsNode = fn.childForFieldName("parameters");
151
+ if (paramsNode) {
152
+ for (const param of paramsNode.namedChildren) {
153
+ if (param.type === "typed_parameter" || param.type === "typed_default_parameter") {
154
+ const typeNode = param.childForFieldName("type");
155
+ if (typeNode) {
156
+ const detected = extractSchemaType(typeNode.text);
157
+ if (detected && !validationSchema) {
158
+ validationSchema = detected;
159
+ }
159
160
  }
160
161
  }
161
162
  }
162
- } else if (node.type === "import_from_statement") {
163
- const moduleName = node.childForFieldName("module_name")?.text?.trim() || "";
164
- for (const child of node.namedChildren) {
165
- if (child === node.childForFieldName("module_name")) continue;
166
- if (child.type === "dotted_name") {
167
- const sym = child.text.trim();
168
- importsInFile.set(sym, { module: moduleName || sym, symbol: sym });
169
- } else if (child.type === "aliased_import") {
170
- const orig = child.childForFieldName("name")?.text?.trim();
171
- const alias = child.childForFieldName("alias")?.text?.trim();
172
- if (orig && alias) {
173
- importsInFile.set(alias, { module: moduleName || orig, symbol: orig });
163
+ }
164
+
165
+ // Fallback schema regex
166
+ if (!validationSchema) {
167
+ const schemaMatch = paramsText.match(
168
+ /[a-zA-Z0-9_]+\s*:\s*([A-Z][a-zA-Z0-9_]*(?:Schema|In|Request|Create|Update|DTO|Body))/
169
+ );
170
+ if (schemaMatch) validationSchema = schemaMatch[1];
171
+ }
172
+
173
+ // Extract guards and dependencies from Depends(...)
174
+ let guardSymbol: string | undefined;
175
+ const inboundDeps: string[] = [];
176
+ if (paramsNode) {
177
+ for (const param of paramsNode.namedChildren) {
178
+ let valNode: Parser.SyntaxNode | null = null;
179
+ if (param.type === "typed_default_parameter" || param.type === "default_parameter") {
180
+ valNode = param.childForFieldName("value");
181
+ }
182
+ if (valNode?.type === "call" && /Depends$/.test(valNode.childForFieldName("function")?.text ?? "")) {
183
+ const depArg = valNode.childForFieldName("arguments")?.namedChildren[0];
184
+ const sym = depArg?.text?.trim();
185
+ if (sym) {
186
+ if (/auth|user|token|permission|guard|role|credential/i.test(sym)) {
187
+ guardSymbol = sym;
188
+ } else {
189
+ inboundDeps.push(sym);
190
+ }
174
191
  }
175
192
  }
176
193
  }
177
194
  }
178
- });
179
-
180
- // 2. Collect router & app definitions
181
- walk(root, (node) => {
182
- if (node.type !== "assignment" || node.parent?.parent?.type !== "module") return;
183
- const leftName = node.childForFieldName("left")?.text ?? "";
184
- const call = node.childForFieldName("right");
185
- if (call?.type !== "call") return;
186
- const fnText = call.childForFieldName("function")?.text ?? "";
187
- const isRouter = /APIRouter$/.test(fnText);
188
- const isApp = /FastAPI$/.test(fnText);
189
- if (!isRouter && !isApp) return;
190
195
 
191
- const args = call.childForFieldName("arguments")?.namedChildren ?? [];
192
- const keyword = args.find(
193
- (child) => child.type === "keyword_argument" && child.childForFieldName("name")?.text === "prefix"
194
- );
195
- const prefix = keyword ? cleanLiteral(keyword.childForFieldName("value")) : "";
196
+ // Fallback guard regex
197
+ if (!guardSymbol) {
198
+ const guardMatch = paramsText.match(
199
+ /Depends\s*\(\s*([a-zA-Z0-9_]*(?:auth|user|token|permission|guard)[a-zA-Z0-9_]*)\s*\)/i
200
+ );
201
+ if (guardMatch) guardSymbol = guardMatch[1];
202
+ }
196
203
 
197
- // Router-level dependencies: router = APIRouter(dependencies=[Depends(...)])
198
- const depsKw = args.find(
199
- (child) => child.type === "keyword_argument" && child.childForFieldName("name")?.text === "dependencies"
204
+ // Extract dependencies from decorator: @router.get("/", dependencies=[Depends(...)])
205
+ const decDepsKw = args.find(
206
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "dependencies"
200
207
  );
201
- const routerGuards: string[] = [];
202
- const routerDeps: string[] = [];
203
- if (depsKw) {
204
- const extracted: Array<{ symbol: string; isGuard: boolean }> = [];
205
- extractDependsFromNode(depsKw.childForFieldName("value"), extracted);
206
- for (const item of extracted) {
207
- if (item.isGuard) routerGuards.push(item.symbol);
208
- else routerDeps.push(item.symbol);
208
+ if (decDepsKw) {
209
+ const decExtracted: Array<{ symbol: string; isGuard: boolean }> = [];
210
+ extractDependsFromNode(decDepsKw.childForFieldName("value"), decExtracted);
211
+ for (const item of decExtracted) {
212
+ if (item.isGuard && !guardSymbol) guardSymbol = item.symbol;
213
+ else inboundDeps.push(item.symbol);
209
214
  }
210
215
  }
211
216
 
212
- localRouters.set(`${relPath}#${leftName}`, {
213
- prefix: prefix?.replace(/\/+$/, ""),
214
- isApp,
215
- guards: routerGuards,
216
- dependencies: routerDeps,
217
- });
218
- });
219
-
220
- // 3. Collect include_router calls
221
- walk(root, (node) => {
222
- if (node.type !== "call") return;
223
- const fn = node.childForFieldName("function");
224
- if (fn?.type !== "attribute" || fn.childForFieldName("attribute")?.text !== "include_router") return;
225
- const parentVar = fn.childForFieldName("object")?.text ?? "";
226
- const args = node.childForFieldName("arguments")?.namedChildren ?? [];
227
- const firstArg = args[0];
228
- if (!firstArg || firstArg.type === "keyword_argument") return;
229
-
230
- const targetExpr = firstArg.text.trim();
231
- const prefixKw = args.find(
232
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "prefix"
217
+ // Extract response_model
218
+ const rmKw = args.find(
219
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "response_model"
233
220
  );
234
- const incPrefix = prefixKw ? cleanLiteral(prefixKw.childForFieldName("value")) : "";
235
- allInclusions.push({
221
+ const responseModel = rmKw?.childForFieldName("value")?.text?.trim();
222
+
223
+ const route: Omit<ExtractedRoute, "httpMethod"> = {
236
224
  file,
237
225
  relPath,
238
- parentVar,
239
- targetExpr,
240
- prefix: incPrefix?.replace(/\/+$/, ""),
241
- line: node.startPosition.row + 1,
242
- });
243
- });
244
-
245
- // 4. Collect route handler definitions
246
- walk(root, (node) => {
247
- if (node.type !== "decorated_definition" || node.parent?.type !== "module") return;
248
- const fn = node.childForFieldName("definition");
249
- if (fn?.type !== "function_definition") return;
250
-
251
- for (const decorator of node.namedChildren.filter((child) => child.type === "decorator")) {
252
- const call = decorator.namedChildren[0];
253
- const attr = call?.childForFieldName("function");
254
- if (call?.type !== "call" || attr?.type !== "attribute") continue;
255
- const method = attr.childForFieldName("attribute")?.text ?? "";
256
- if (!/^(get|post|put|patch|delete|options|head)$/.test(method)) continue;
257
-
258
- const args = call.childForFieldName("arguments")?.namedChildren ?? [];
259
- const rawPath = cleanLiteral(args[0]);
260
- if (rawPath === undefined) continue;
261
-
262
- const routerVar = attr.childForFieldName("object")?.text ?? "";
263
- const actionName = fn.childForFieldName("name")?.text ?? "";
264
- const paramsText = fn.childForFieldName("parameters")?.text ?? "";
265
-
266
- // Extract Pydantic validation schema from typed parameters
267
- let validationSchema: string | undefined;
268
- const paramsNode = fn.childForFieldName("parameters");
269
- if (paramsNode) {
270
- for (const param of paramsNode.namedChildren) {
271
- if (param.type === "typed_parameter" || param.type === "typed_default_parameter") {
272
- const typeNode = param.childForFieldName("type");
273
- if (typeNode) {
274
- const detected = extractSchemaType(typeNode.text);
275
- if (detected && !validationSchema) {
276
- validationSchema = detected;
277
- }
278
- }
279
- }
226
+ routerVar: receiver,
227
+ routerKey,
228
+ name,
229
+ rawPath,
230
+ actionName,
231
+ lineIndex: line,
232
+ actionLine: fn.startPosition.row + 1,
233
+ validationSchema,
234
+ guardSymbol,
235
+ dependencies: inboundDeps,
236
+ responseModel,
237
+ };
238
+
239
+ const body = fn.childForFieldName("body");
240
+ if (body) {
241
+ walk(body, (child) => {
242
+ if (child.type !== "call") return;
243
+ const called = child.childForFieldName("function")?.text ?? "";
244
+ const service = called.match(/^([a-zA-Z0-9_]+_service|[A-Z][a-zA-Z0-9_]*Service)\.([a-zA-Z0-9_]+)$/);
245
+ if (service && !route.service) {
246
+ route.service = { symbol: `${service[1]}::${service[2]}`, line: child.startPosition.row + 1 };
280
247
  }
281
- }
282
-
283
- // Fallback schema regex
284
- if (!validationSchema) {
285
- const schemaMatch = paramsText.match(
286
- /[a-zA-Z0-9_]+\s*:\s*([A-Z][a-zA-Z0-9_]*(?:Schema|In|Request|Create|Update|DTO|Body))/
287
- );
288
- if (schemaMatch) validationSchema = schemaMatch[1];
289
- }
290
-
291
- // Extract guards and dependencies from Depends(...)
292
- let guardSymbol: string | undefined;
293
- const inboundDeps: string[] = [];
294
- if (paramsNode) {
295
- for (const param of paramsNode.namedChildren) {
296
- let valNode: Parser.SyntaxNode | null = null;
297
- if (param.type === "typed_default_parameter" || param.type === "default_parameter") {
298
- valNode = param.childForFieldName("value");
299
- }
300
- if (valNode?.type === "call" && /Depends$/.test(valNode.childForFieldName("function")?.text ?? "")) {
301
- const depArg = valNode.childForFieldName("arguments")?.namedChildren[0];
302
- const sym = depArg?.text?.trim();
303
- if (sym) {
304
- if (/auth|user|token|permission|guard|role|credential/i.test(sym)) {
305
- guardSymbol = sym;
306
- } else {
307
- inboundDeps.push(sym);
308
- }
309
- }
248
+ if (/^(db\.(add|query)|session\.query)$/.test(called)) {
249
+ const argument = child.childForFieldName("arguments")?.namedChildren[0];
250
+ if (argument?.type === "identifier" && /^[A-Z]/.test(argument.text)) {
251
+ route.model = argument.text;
310
252
  }
311
253
  }
312
- }
313
-
314
- // Fallback guard regex
315
- if (!guardSymbol) {
316
- const guardMatch = paramsText.match(
317
- /Depends\s*\(\s*([a-zA-Z0-9_]*(?:auth|user|token|permission|guard)[a-zA-Z0-9_]*)\s*\)/i
318
- );
319
- if (guardMatch) guardSymbol = guardMatch[1];
320
- }
254
+ });
255
+ }
321
256
 
322
- // Extract dependencies from decorator: @router.get("/", dependencies=[Depends(...)])
323
- const decDepsKw = args.find(
324
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "dependencies"
325
- );
326
- if (decDepsKw) {
327
- const decExtracted: Array<{ symbol: string; isGuard: boolean }> = [];
328
- extractDependsFromNode(decDepsKw.childForFieldName("value"), decExtracted);
329
- for (const item of decExtracted) {
330
- if (item.isGuard && !guardSymbol) guardSymbol = item.symbol;
331
- else inboundDeps.push(item.symbol);
332
- }
333
- }
257
+ for (const httpMethod of methods) allRoutes.push({ ...route, httpMethod });
258
+ };
334
259
 
335
- // Extract response_model
336
- const rmKw = args.find(
337
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "response_model"
338
- );
339
- const responseModel = rmKw?.childForFieldName("value")?.text?.trim();
340
-
341
- const route: ExtractedRoute = {
342
- file,
343
- relPath,
344
- routerVar,
345
- httpMethod: method.toUpperCase(),
346
- rawPath,
347
- actionName,
348
- params: paramsText,
349
- lineIndex: decorator.startPosition.row + 1,
350
- actionLine: fn.startPosition.row + 1,
351
- validationSchema,
352
- guardSymbol,
353
- dependencies: inboundDeps,
354
- responseModel,
355
- };
356
-
357
- const body = fn.childForFieldName("body");
358
- if (body) {
359
- walk(body, (child) => {
360
- if (child.type !== "call") return;
361
- const called = child.childForFieldName("function")?.text ?? "";
362
- const service = called.match(/^([a-zA-Z0-9_]+_service|[A-Z][a-zA-Z0-9_]*Service)\.([a-zA-Z0-9_]+)$/);
363
- if (service && !route.service) {
364
- route.service = { symbol: `${service[1]}::${service[2]}`, line: child.startPosition.row + 1 };
365
- }
366
- if (/^(db\.(add|query)|session\.query)$/.test(called)) {
367
- const argument = child.childForFieldName("arguments")?.namedChildren[0];
368
- if (argument?.type === "identifier" && /^[A-Z]/.test(argument.text)) {
369
- route.model = argument.text;
370
- }
371
- }
372
- });
260
+ const module = visitPythonRouterModule(root, relPath, {
261
+ constructorCall(key, _name, constructor, call) {
262
+ if (!/^(?:fastapi(?:\.routing|\.applications)?\.)?(?:APIRouter|FastAPI)$/.test(constructor)) return false;
263
+ const isApp = constructor.endsWith("FastAPI");
264
+ const prefixArg = isApp ? undefined : pythonCallArgument(call, "prefix");
265
+ const prefix = !isApp && pythonCallUsesUnpacking(call) ? undefined : prefixArg ? cleanLiteral(prefixArg) : "";
266
+ const dependencies: Array<{ symbol: string; isGuard: boolean }> = [];
267
+ extractDependsFromNode(pythonCallArgument(call, "dependencies"), dependencies);
268
+ localRouters.set(key, {
269
+ prefix: prefix?.replace(/\/+$/, ""),
270
+ isApp,
271
+ guards: dependencies.filter(item => item.isGuard).map(item => item.symbol),
272
+ dependencies: dependencies.filter(item => !item.isGuard).map(item => item.symbol),
273
+ });
274
+ return true;
275
+ },
276
+ routerCall({ call, key, receiver, method, line }, targets) {
277
+ if (method === "add_api_route") {
278
+ const handler = targets.function(pythonCallArgument(call, "endpoint", 1)?.text ?? "");
279
+ if (handler) readRoute(call, method, receiver, key, handler, line);
280
+ } else if (method === "include_router") {
281
+ const target = targets.router(pythonCallArgument(call, "router", 0)?.text ?? "");
282
+ if (!target) return;
283
+ const pref = pythonCallArgument(call, "prefix");
284
+ const prefix = pythonCallUsesUnpacking(call) ? undefined : pref ? cleanLiteral(pref) : "";
285
+ allInclusions.push({ file, parentKey: key, target, prefix: prefix?.replace(/\/+$/, "") });
373
286
  }
374
-
375
- allRoutes.push(route);
376
- }
377
- });
378
-
287
+ },
288
+ decorator({ call, key, receiver, method, line }, handler) {
289
+ if (method === "api_route" || verbs.test(method)) readRoute(call, method, receiver, key, handler, line);
290
+ },
291
+ }, signal);
292
+ fileRouters.set(relPath, module.routers);
293
+ fileImports.set(relPath, module.imports);
379
294
  return { symbols: [], dependencies: [] };
380
295
  });
381
296
 
@@ -384,115 +299,17 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
384
299
  }
385
300
  }
386
301
 
387
- // 5. Build Inclusion Graph and Resolve Cross-File Router Targets
388
- // Adjacency: parentKey -> Array<{ childKey: string; prefix: string | undefined }>
389
- const routerChildren = new Map<string, Array<{ childKey: string; prefix: string | undefined }>>();
390
- const incomingInclusions = new Map<string, Array<{ parentKey: string; prefix: string | undefined }>>();
391
-
392
- for (const inc of allInclusions) {
393
- const parentKey = `${inc.relPath}#${inc.parentVar}`;
394
- const importsInFile = fileImports.get(inc.relPath) ?? new Map<string, ImportBinding>();
395
-
396
- let targetKey: string | undefined;
397
-
398
- if (inc.targetExpr.includes(".")) {
399
- const [objName, propName] = inc.targetExpr.split(".");
400
- const binding = importsInFile.get(objName);
401
- if (binding) {
402
- // Try resolving submodule target first: e.g. from app.routers import orders -> orders.router
403
- const subTarget = binding.module ? `${binding.module}.${binding.symbol || objName}` : objName;
404
- let res = resolver.resolve(subTarget, inc.file);
405
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
406
- targetKey = `${res.targets[0].files[0]}#${propName}`;
407
- } else if (binding.module) {
408
- res = resolver.resolve(binding.module, inc.file);
409
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
410
- targetKey = `${res.targets[0].files[0]}#${propName}`;
411
- }
412
- }
413
- }
414
- } else {
415
- const binding = importsInFile.get(inc.targetExpr);
416
- if (binding) {
417
- // Try resolving submoduleTarget first (binding.module + "." + binding.symbol)
418
- const subTarget = binding.module && binding.symbol ? `${binding.module}.${binding.symbol}` : (binding.module || binding.symbol!);
419
- let res = resolver.resolve(subTarget, inc.file);
420
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
421
- targetKey = `${res.targets[0].files[0]}#router`;
422
- } else if (binding.module) {
423
- res = resolver.resolve(binding.module, inc.file);
424
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
425
- targetKey = `${res.targets[0].files[0]}#${binding.symbol || "router"}`;
426
- }
427
- }
428
- } else {
429
- // Local router inside same file
430
- const candidate = `${inc.relPath}#${inc.targetExpr}`;
431
- if (localRouters.has(candidate)) {
432
- targetKey = candidate;
433
- }
434
- }
435
- }
436
-
437
- if (targetKey) {
438
- if (!routerChildren.has(parentKey)) routerChildren.set(parentKey, []);
439
- routerChildren.get(parentKey)!.push({ childKey: targetKey, prefix: inc.prefix });
440
-
441
- if (!incomingInclusions.has(targetKey)) incomingInclusions.set(targetKey, []);
442
- incomingInclusions.get(targetKey)!.push({ parentKey, prefix: inc.prefix });
443
- }
444
- }
445
-
446
- // 6. Compute Effective Prefixes for Each Router
447
- // A router is a root if it has no incoming inclusions or is an explicit FastAPI app
448
- const effectivePrefixesByRouter = new Map<string, string[]>();
449
-
450
- const allRouterKeys = new Set<string>([
451
- ...localRouters.keys(),
452
- ...allRoutes.map((r) => `${r.relPath}#${r.routerVar}`),
453
- ]);
454
-
455
- // Find root routers
456
- for (const routerKey of allRouterKeys) {
457
- const incoming = incomingInclusions.get(routerKey);
458
- if (!incoming || incoming.length === 0) {
459
- const local = localRouters.get(routerKey);
460
- effectivePrefixesByRouter.set(routerKey, local && local.prefix === undefined ? [] : [local?.prefix ?? ""]);
461
- }
462
- }
463
-
464
- // Propagate prefixes along inclusion edges
465
- const queue = Array.from(effectivePrefixesByRouter.keys());
466
- const visitedEdges = new Set<string>();
467
-
468
- while (queue.length > 0) {
469
- const current = queue.shift()!;
470
- const currentPrefixes = effectivePrefixesByRouter.get(current) ?? [""];
471
- const children = routerChildren.get(current) ?? [];
472
-
473
- for (const child of children) {
474
- const edgeKey = `${current}->${child.childKey}:${child.prefix}`;
475
- if (visitedEdges.has(edgeKey)) continue;
476
- visitedEdges.add(edgeKey);
477
-
478
- const childMeta = localRouters.get(child.childKey);
479
- const childLocal = childMeta?.prefix ?? "";
480
- const nextPrefixes = child.prefix === undefined || childMeta && childMeta.prefix === undefined ? [] : currentPrefixes.map((p) => {
481
- const combined = `${p ? (p.startsWith("/") ? p : `/${p}`) : ""}${child.prefix ? (child.prefix.startsWith("/") ? child.prefix : `/${child.prefix}`) : ""}${childLocal ? (childLocal.startsWith("/") ? childLocal : `/${childLocal}`) : ""}`;
482
- return combined.replace(/\/+/g, "/").replace(/\/+$/, "");
483
- });
484
-
485
- const existing = effectivePrefixesByRouter.get(child.childKey) ?? [];
486
- const merged = Array.from(new Set([...existing, ...nextPrefixes]));
487
- effectivePrefixesByRouter.set(child.childKey, merged);
488
- queue.push(child.childKey);
489
- }
490
- }
302
+ const roots = new Map([...localRouters].map(([key, router]) => [key, router.prefix]));
303
+ const mounts = allInclusions.flatMap(({ file, parentKey, target, prefix }) => {
304
+ const child = resolvePythonRouterTarget(target, file, resolver, fileRouters);
305
+ const router = child ? localRouters.get(child) : undefined;
306
+ if (!child || !router || router.isApp) return [];
307
+ return [{ parent: parentKey, child, prefix: prefix === undefined || router.prefix === undefined ? undefined : prefix + router.prefix }];
308
+ });
309
+ const prefixesByRouter = composeMountPrefixes(roots, mounts, signal);
491
310
 
492
- // 7. Generate Vertical Slices
493
311
  for (const route of allRoutes) {
494
- const routerKey = `${route.relPath}#${route.routerVar}`;
495
- const prefixes = effectivePrefixesByRouter.get(routerKey) ?? [];
312
+ const prefixes = prefixesByRouter.get(route.routerKey) ?? [];
496
313
 
497
314
  for (const prefix of prefixes) {
498
315
  const fullUri = normalizeRouteUri(prefix, route.rawPath);
@@ -507,7 +324,7 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
507
324
  },
508
325
  ];
509
326
 
510
- const routerMeta = localRouters.get(routerKey);
327
+ const routerMeta = localRouters.get(route.routerKey);
511
328
  const effectiveGuards = Array.from(new Set([
512
329
  ...(route.guardSymbol ? [route.guardSymbol] : []),
513
330
  ...(routerMeta?.guards ?? []),
@@ -684,7 +501,7 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
684
501
  feature_key: null,
685
502
  http_method: route.httpMethod,
686
503
  route_uri: fullUri,
687
- route_name: `${route.routerVar}.${route.actionName}`,
504
+ route_name: route.name ?? `${route.routerVar}.${route.actionName}`,
688
505
  controller_class: path.basename(route.file, ".py"),
689
506
  action_name: route.actionName,
690
507
  controller_file: route.relPath,