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