@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,16 +1,23 @@
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 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 ExtractedFlaskRoute {
11
18
  file: string;
12
19
  relPath: string;
13
- routerVar: string;
20
+ routerKey: string;
14
21
  httpMethods: string[];
15
22
  rawPath: string;
16
23
  actionName: string;
@@ -22,37 +29,25 @@ interface ExtractedFlaskRoute {
22
29
 
23
30
  interface ExtractedBlueprintRegistration {
24
31
  file: string;
25
- relPath: string;
26
- parentVar: string;
27
- targetExpr: string;
28
- prefix: string;
29
- line: number;
32
+ parent: string;
33
+ target: PythonRouterTarget;
34
+ // null represents a supplied prefix whose value is unknown. Undefined uses the blueprint default.
35
+ prefix: string | null | undefined;
30
36
  }
31
37
 
32
- interface ImportBinding {
33
- module: string;
34
- symbol?: string;
35
- }
38
+ type Blueprint = { name: string; prefix: string | undefined; isApp: boolean };
39
+ type Node = Parser.SyntaxNode;
40
+ const verbs = /^(get|post|put|patch|delete|options|head)$/;
36
41
 
37
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
38
- if (!node) return undefined;
39
- if (node.type === "string") {
40
- const raw = node.text.trim();
41
- const match = raw.match(/^[rRbBuU]*('''|"""|'|")([\s\S]*?)\1$/);
42
- if (match) return match[2];
43
- return raw.replace(/^[rRbBuU]*['"]|['"]$/g, "");
44
- }
45
- return undefined;
42
+ function routeMethods(call: Node, method: string): string[] {
43
+ if (verbs.test(method)) return [method.toUpperCase()];
44
+ const value = pythonCallArgument(call, "methods");
45
+ return !value || value.type === "none" ? ["GET"] : pythonLiteralMethods(value) ?? [];
46
46
  }
47
47
 
48
- function normalizeRouteUri(prefix: string, rawPath: string): string {
49
- const p = (prefix ?? "").trim().replace(/\/+$/, "");
50
- let r = (rawPath ?? "").trim();
51
- if (!r.startsWith("/")) r = "/" + r;
52
- if (r === "/" && p.length > 0) return p + "/";
53
- if (r === "/" && p.length === 0) return "/";
54
- const joined = `${p}${r}`;
55
- return joined.startsWith("/") ? joined : `/${joined}`;
48
+ function normalizeRouteUri(prefix: string, path: string): string {
49
+ if (!path) return prefix || "/";
50
+ return prefix + "/" + path.replace(/^\/+/, "");
56
51
  }
57
52
 
58
53
  export class FlaskSemanticExtractor implements SemanticSliceExtractor {
@@ -62,253 +57,85 @@ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
62
57
  public canHandle(projectRoot: string, framework?: string): boolean {
63
58
  if (framework === "flask") return true;
64
59
 
65
- // Check configuration manifests
66
- for (const manifest of ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"]) {
67
- const fullPath = path.join(projectRoot, manifest);
68
- if (fs.existsSync(fullPath)) {
69
- try {
70
- const content = fs.readFileSync(fullPath, "utf-8").toLowerCase();
71
- if (content.includes("flask")) return true;
72
- } catch {}
73
- }
74
- }
75
-
76
- // Check entrypoint files
77
- for (const entry of ["app.py", "main.py", "wsgi.py", "run.py", "server.py", "src/app.py", "app/__init__.py"]) {
78
- const fullPath = path.join(projectRoot, entry);
79
- if (fs.existsSync(fullPath)) {
80
- try {
81
- const content = fs.readFileSync(fullPath, "utf-8");
82
- if (content.includes("from flask") || content.includes("import flask")) {
83
- return true;
84
- }
85
- } catch {}
86
- }
60
+ if (anyFileContains(projectRoot, ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"], ["flask"], true)) {
61
+ return true;
87
62
  }
88
63
 
89
- return false;
64
+ return anyFileContains(
65
+ projectRoot,
66
+ ["app.py", "main.py", "wsgi.py", "run.py", "server.py", "src/app.py", "app/__init__.py"],
67
+ ["from flask", "import flask"]
68
+ );
90
69
  }
91
70
 
92
71
  public async extractSlices(
93
72
  projectRoot: string,
94
73
  domainId?: number,
95
- signal?: AbortSignal
74
+ signal?: AbortSignal, inventory?: SourceInventory
96
75
  ): Promise<VerticalSliceCandidate[]> {
97
76
  const slices: VerticalSliceCandidate[] = [];
98
- const pyFiles = this.findPythonFiles(projectRoot);
77
+ const pyFiles = listSourceFiles(projectRoot, /\.py$/, inventory);
99
78
  const resolver = new ImportResolver(projectRoot);
100
79
 
101
80
  const allRoutes: ExtractedFlaskRoute[] = [];
102
81
  const allRegistrations: ExtractedBlueprintRegistration[] = [];
103
- const localBlueprints = new Map<
104
- string,
105
- { bpName: string; prefix: string; isApp: boolean }
106
- >();
107
- const fileImports = new Map<string, Map<string, ImportBinding>>();
82
+ const blueprints = new Map<string, Blueprint>();
83
+ const fileRouters = new Map<string, Map<string, string>>();
108
84
 
109
85
  for (const file of pyFiles) {
110
86
  signal?.throwIfAborted();
111
87
  const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
112
88
  const content = readOptionalSourceFile(file, "utf-8");
113
- if (
114
- !content ||
115
- (!content.includes("@") &&
116
- !content.includes("register_blueprint") &&
117
- !content.includes("Blueprint") &&
118
- !content.includes("Flask"))
119
- ) {
120
- continue;
121
- }
122
-
123
- const importsInFile = new Map<string, ImportBinding>();
124
- fileImports.set(relPath, importsInFile);
125
-
126
- const parsed = await parseSourceWithTreeSitter("python", content, (root) => {
127
- const walk = (node: Parser.SyntaxNode, visit: (node: Parser.SyntaxNode) => void) => {
128
- visit(node);
129
- for (const child of node.namedChildren) walk(child, visit);
130
- };
131
-
132
- // 1. Collect import statements
133
- walk(root, (node) => {
134
- if (node.type === "import_statement") {
135
- for (const child of node.namedChildren) {
136
- if (child.type === "dotted_name") {
137
- const mod = child.text.trim();
138
- const alias = mod.split(".").pop() || mod;
139
- importsInFile.set(alias, { module: mod });
140
- } else if (child.type === "aliased_import") {
141
- const orig = child.childForFieldName("name")?.text?.trim();
142
- const alias = child.childForFieldName("alias")?.text?.trim();
143
- if (orig && alias) {
144
- importsInFile.set(alias, { module: orig });
145
- }
146
- }
147
- }
148
- } else if (node.type === "import_from_statement") {
149
- const moduleName = node.childForFieldName("module_name")?.text?.trim() || "";
150
- for (const child of node.namedChildren) {
151
- if (child === node.childForFieldName("module_name")) continue;
152
- if (child.type === "dotted_name") {
153
- const sym = child.text.trim();
154
- importsInFile.set(sym, { module: moduleName || sym, symbol: sym });
155
- } else if (child.type === "aliased_import") {
156
- const orig = child.childForFieldName("name")?.text?.trim();
157
- const alias = child.childForFieldName("alias")?.text?.trim();
158
- if (orig && alias) {
159
- importsInFile.set(alias, { module: moduleName || orig, symbol: orig });
160
- }
161
- }
162
- }
163
- }
164
- });
165
-
166
- // 2. Collect Flask App and Blueprint instantiations
167
- walk(root, (node) => {
168
- if (node.type !== "assignment" || node.parent?.parent?.type !== "module") return;
169
- const leftName = node.childForFieldName("left")?.text ?? "";
170
- const call = node.childForFieldName("right");
171
- if (call?.type !== "call") return;
172
- const fnText = call.childForFieldName("function")?.text ?? "";
173
- const isBlueprint = /Blueprint$/.test(fnText);
174
- const isApp = /Flask$/.test(fnText);
175
- if (!isBlueprint && !isApp) return;
176
-
177
- const args = call.childForFieldName("arguments")?.namedChildren ?? [];
178
- let bpName = leftName;
179
- let prefix = "";
180
-
181
- if (isBlueprint && args.length > 0) {
182
- const firstArg = args[0];
183
- if (firstArg.type !== "keyword_argument") {
184
- const lit = cleanLiteral(firstArg);
185
- if (lit) bpName = lit;
186
- }
187
- }
188
-
189
- const prefixKw = args.find(
190
- (child) => child.type === "keyword_argument" && child.childForFieldName("name")?.text === "url_prefix"
191
- );
192
- if (prefixKw) {
193
- prefix = cleanLiteral(prefixKw.childForFieldName("value")) ?? "";
194
- }
195
-
196
- localBlueprints.set(`${relPath}#${leftName}`, {
197
- bpName,
198
- prefix: prefix.replace(/\/+$/, ""),
199
- isApp,
200
- });
201
- });
202
-
203
- // 3. Collect register_blueprint calls
204
- walk(root, (node) => {
205
- if (node.type !== "call") return;
206
- const fn = node.childForFieldName("function");
207
- if (fn?.type !== "attribute" || fn.childForFieldName("attribute")?.text !== "register_blueprint") return;
208
- const parentVar = fn.childForFieldName("object")?.text ?? "";
209
- const args = node.childForFieldName("arguments")?.namedChildren ?? [];
210
- const firstArg = args[0];
211
- if (!firstArg || firstArg.type === "keyword_argument") return;
212
-
213
- const targetExpr = firstArg.text.trim();
214
- const prefixKw = args.find(
215
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "url_prefix"
89
+ if (!content || !/@\s*[A-Za-z_]\w*\.(?:route|get|post|put|patch|delete|options|head|trace)\b|register_blueprint|add_url_rule|Blueprint|Flask/.test(content)) continue;
90
+
91
+ const parsed = await parseSourceWithTreeSitter("python", content, root => {
92
+ const readRoute = (key: string, call: Node, method: string, handler: Node, line: number) => {
93
+ if (pythonCallUsesUnpacking(call)) return;
94
+ const rawPath = cleanLiteral(pythonCallArgument(call, "rule", 0));
95
+ const httpMethods = routeMethods(call, method);
96
+ const actionName = handler.childForFieldName("name")?.text;
97
+ if (rawPath === undefined || !httpMethods.length || !actionName) return;
98
+
99
+ const endpoint = cleanLiteral(pythonCallArgument(call, "endpoint", method === "add_url_rule" ? 1 : undefined));
100
+ const template = handler.childForFieldName("body")?.descendantsOfType("call").find(node =>
101
+ node.childForFieldName("function")?.text === "render_template",
216
102
  );
217
- const incPrefix = cleanLiteral(prefixKw?.childForFieldName("value")) ?? "";
218
- allRegistrations.push({
219
- file,
220
- relPath,
221
- parentVar,
222
- targetExpr,
223
- prefix: incPrefix.replace(/\/+$/, ""),
224
- line: node.startPosition.row + 1,
103
+ allRoutes.push({
104
+ file, relPath, routerKey: key, httpMethods, rawPath, actionName, endpoint,
105
+ lineIndex: line, actionLine: handler.startPosition.row + 1,
106
+ templateEgress: template ? cleanLiteral(pythonCallArgument(template, "template_name_or_list", 0)) : undefined,
225
107
  });
226
- });
227
-
228
- // 4. Collect route handler definitions
229
- walk(root, (node) => {
230
- if (node.type !== "decorated_definition" || node.parent?.type !== "module") return;
231
- const fn = node.childForFieldName("definition");
232
- if (fn?.type !== "function_definition") return;
233
-
234
- for (const decorator of node.namedChildren.filter((child) => child.type === "decorator")) {
235
- const call = decorator.namedChildren[0];
236
- const attr = call?.childForFieldName("function");
237
- if (call?.type !== "call" || attr?.type !== "attribute") continue;
238
-
239
- const decoratorMethod = attr.childForFieldName("attribute")?.text ?? "";
240
- const isRoute = decoratorMethod === "route";
241
- const isShorthand = /^(get|post|put|patch|delete|options|head)$/i.test(decoratorMethod);
242
- if (!isRoute && !isShorthand) continue;
243
-
244
- const args = call.childForFieldName("arguments")?.namedChildren ?? [];
245
- const rawPath = cleanLiteral(args[0]);
246
- if (rawPath === undefined) continue;
247
-
248
- const routerVar = attr.childForFieldName("object")?.text ?? "";
249
- const actionName = fn.childForFieldName("name")?.text ?? "";
250
-
251
- // Determine HTTP methods
252
- let httpMethods: string[] = [];
253
- if (isRoute) {
254
- const methodsKw = args.find(
255
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "methods"
256
- );
257
- if (methodsKw) {
258
- const val = methodsKw.childForFieldName("value");
259
- if (val && (val.type === "list" || val.type === "tuple")) {
260
- for (const m of val.namedChildren) {
261
- const lit = cleanLiteral(m)?.toUpperCase();
262
- if (lit) httpMethods.push(lit);
263
- }
264
- }
265
- }
266
- if (httpMethods.length === 0) {
267
- httpMethods = ["GET"];
268
- }
269
- } else {
270
- httpMethods = [decoratorMethod.toUpperCase()];
271
- }
272
-
273
- // Extract optional endpoint
274
- const endpointKw = args.find(
275
- (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "endpoint"
276
- );
277
- const endpoint = cleanLiteral(endpointKw?.childForFieldName("value"));
108
+ };
278
109
 
279
- // Check function body for template render egress
280
- let templateEgress: string | undefined;
281
- const body = fn.childForFieldName("body");
282
- if (body) {
283
- walk(body, (child) => {
284
- if (child.type === "call") {
285
- const calledFn = child.childForFieldName("function")?.text ?? "";
286
- if (calledFn === "render_template") {
287
- const tmplArg = child.childForFieldName("arguments")?.namedChildren[0];
288
- const tmpl = cleanLiteral(tmplArg);
289
- if (tmpl && !templateEgress) {
290
- templateEgress = tmpl;
291
- }
292
- }
293
- }
294
- });
110
+ const module = visitPythonRouterModule(root, relPath, {
111
+ constructorCall(key, name, constructor, call) {
112
+ if (!/^(?:flask(?:\.app|\.blueprints)?\.)?(?:Flask|Blueprint)$/.test(constructor)) return false;
113
+ const isApp = constructor.endsWith("Flask");
114
+ const declaredName = isApp ? name : cleanLiteral(pythonCallArgument(call, "name", 0)) ?? name;
115
+ const prefixArg = isApp ? undefined : pythonCallArgument(call, "url_prefix", 5);
116
+ const prefix = !isApp && pythonCallUsesUnpacking(call) ? undefined :
117
+ prefixArg && prefixArg.type !== "none" ? cleanLiteral(prefixArg) : "";
118
+ blueprints.set(key, { name: declaredName, prefix: prefix?.replace(/\/+$/, ""), isApp });
119
+ return true;
120
+ },
121
+ routerCall({ key, call, method, line }, targets) {
122
+ if (method === "add_url_rule") {
123
+ const handler = targets.function(pythonCallArgument(call, "view_func", 2)?.text ?? "");
124
+ if (handler) readRoute(key, call, method, handler, line);
125
+ } else if (method === "register_blueprint") {
126
+ const target = targets.router(pythonCallArgument(call, "blueprint", 0)?.text ?? "");
127
+ if (!target) return;
128
+ const prefixArg = pythonCallArgument(call, "url_prefix");
129
+ const prefix = pythonCallUsesUnpacking(call) ? null :
130
+ prefixArg && prefixArg.type !== "none" ? cleanLiteral(prefixArg)?.replace(/\/+$/, "") ?? null : undefined;
131
+ allRegistrations.push({ file, parent: key, target, prefix });
295
132
  }
296
-
297
- allRoutes.push({
298
- file,
299
- relPath,
300
- routerVar,
301
- httpMethods,
302
- rawPath,
303
- actionName,
304
- endpoint,
305
- lineIndex: decorator.startPosition.row + 1,
306
- actionLine: fn.startPosition.row + 1,
307
- templateEgress,
308
- });
309
- }
310
- });
311
-
133
+ },
134
+ decorator({ key, call, method, line }, handler) {
135
+ if (method === "route" || verbs.test(method)) readRoute(key, call, method, handler, line);
136
+ },
137
+ }, signal);
138
+ fileRouters.set(relPath, module.routers);
312
139
  return { symbols: [], dependencies: [] };
313
140
  });
314
141
 
@@ -317,119 +144,19 @@ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
317
144
  }
318
145
  }
319
146
 
320
- // 5. Build Inclusion Graph and Resolve Cross-File Blueprint Targets
321
- const routerChildren = new Map<string, Array<{ childKey: string; prefix: string }>>();
322
- const incomingRegistrations = new Map<string, Array<{ parentKey: string; prefix: string }>>();
323
-
324
- for (const reg of allRegistrations) {
325
- const parentKey = `${reg.relPath}#${reg.parentVar}`;
326
- const importsInFile = fileImports.get(reg.relPath) ?? new Map<string, ImportBinding>();
327
-
328
- let targetKey: string | undefined;
329
-
330
- if (reg.targetExpr.includes(".")) {
331
- const [objName, propName] = reg.targetExpr.split(".");
332
- const binding = importsInFile.get(objName);
333
- if (binding) {
334
- const subTarget = binding.module ? `${binding.module}.${binding.symbol || objName}` : objName;
335
- let res = resolver.resolve(subTarget, reg.file);
336
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
337
- targetKey = `${res.targets[0].files[0]}#${propName}`;
338
- } else if (binding.module) {
339
- res = resolver.resolve(binding.module, reg.file);
340
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
341
- targetKey = `${res.targets[0].files[0]}#${propName}`;
342
- }
343
- }
344
- }
345
- } else {
346
- const binding = importsInFile.get(reg.targetExpr);
347
- if (binding) {
348
- const subTarget =
349
- binding.module && binding.symbol ? `${binding.module}.${binding.symbol}` : binding.module || binding.symbol!;
350
- let res = resolver.resolve(subTarget, reg.file);
351
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
352
- targetKey = `${res.targets[0].files[0]}#${binding.symbol || reg.targetExpr}`;
353
- } else if (binding.module) {
354
- res = resolver.resolve(binding.module, reg.file);
355
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
356
- targetKey = `${res.targets[0].files[0]}#${binding.symbol || reg.targetExpr}`;
357
- }
358
- }
359
- } else {
360
- // Local blueprint inside same file
361
- const candidate = `${reg.relPath}#${reg.targetExpr}`;
362
- if (localBlueprints.has(candidate)) {
363
- targetKey = candidate;
364
- }
365
- }
366
- }
367
-
368
- if (targetKey) {
369
- if (!routerChildren.has(parentKey)) routerChildren.set(parentKey, []);
370
- routerChildren.get(parentKey)!.push({ childKey: targetKey, prefix: reg.prefix });
371
-
372
- if (!incomingRegistrations.has(targetKey)) incomingRegistrations.set(targetKey, []);
373
- incomingRegistrations.get(targetKey)!.push({ parentKey, prefix: reg.prefix });
374
- }
375
- }
376
-
377
- // 6. Compute Effective Prefixes for Each Router/Blueprint
378
- const effectivePrefixesByRouter = new Map<string, string[]>();
147
+ const roots = new Map([...blueprints].map(([key, blueprint]) => [key, blueprint.prefix]));
148
+ const mounts = allRegistrations.flatMap(({ file, parent, target, prefix }) => {
149
+ const child = resolvePythonRouterTarget(target, file, resolver, fileRouters);
150
+ const blueprint = child ? blueprints.get(child) : undefined;
151
+ if (!child || !blueprint || blueprint.isApp) return [];
152
+ return [{ parent, child, prefix: prefix === undefined ? blueprint.prefix : prefix ?? undefined }];
153
+ });
154
+ const prefixesByRouter = composeMountPrefixes(roots, mounts, signal);
379
155
 
380
- const allRouterKeys = new Set<string>([
381
- ...localBlueprints.keys(),
382
- ...allRoutes.map((r) => `${r.relPath}#${r.routerVar}`),
383
- ]);
384
-
385
- // Find root routers
386
- for (const routerKey of allRouterKeys) {
387
- const incoming = incomingRegistrations.get(routerKey);
388
- if (!incoming || incoming.length === 0) {
389
- const local = localBlueprints.get(routerKey)?.prefix ?? "";
390
- effectivePrefixesByRouter.set(routerKey, [local]);
391
- }
392
- }
393
-
394
- // Propagate prefixes along registration edges via BFS
395
- const queue = Array.from(effectivePrefixesByRouter.keys());
396
- const visitedEdges = new Set<string>();
397
-
398
- while (queue.length > 0) {
399
- const current = queue.shift()!;
400
- const currentPrefixes = effectivePrefixesByRouter.get(current) ?? [""];
401
- const children = routerChildren.get(current) ?? [];
402
-
403
- for (const child of children) {
404
- const edgeKey = `${current}->${child.childKey}:${child.prefix}`;
405
- if (visitedEdges.has(edgeKey)) continue;
406
- visitedEdges.add(edgeKey);
407
-
408
- const childLocal = localBlueprints.get(child.childKey)?.prefix ?? "";
409
- const nextPrefixes = currentPrefixes.map((p) => {
410
- const combined = `${p ? (p.startsWith("/") ? p : `/${p}`) : ""}${
411
- child.prefix ? (child.prefix.startsWith("/") ? child.prefix : `/${child.prefix}`) : ""
412
- }${childLocal ? (childLocal.startsWith("/") ? childLocal : `/${childLocal}`) : ""}`;
413
- return combined.replace(/\/+/g, "/").replace(/\/+$/, "");
414
- });
415
-
416
- const existing = effectivePrefixesByRouter.get(child.childKey) ?? [];
417
- const merged = Array.from(new Set([...existing, ...nextPrefixes]));
418
- effectivePrefixesByRouter.set(child.childKey, merged);
419
- queue.push(child.childKey);
420
- }
421
- }
422
-
423
- // 7. Generate Vertical Slices (Level 0 – Level 3)
424
156
  for (const route of allRoutes) {
425
- const routerKey = `${route.relPath}#${route.routerVar}`;
426
- let prefixes = effectivePrefixesByRouter.get(routerKey);
427
- if (!prefixes || prefixes.length === 0) {
428
- prefixes = [localBlueprints.get(routerKey)?.prefix ?? ""];
429
- }
430
-
431
- const bpMeta = localBlueprints.get(routerKey);
432
- const controllerClass = bpMeta?.bpName || path.basename(route.file, ".py");
157
+ const prefixes = prefixesByRouter.get(route.routerKey) ?? [];
158
+ const bpMeta = blueprints.get(route.routerKey);
159
+ const controllerClass = bpMeta?.name || path.basename(route.file, ".py");
433
160
 
434
161
  for (const prefix of prefixes) {
435
162
  const fullUri = normalizeRouteUri(prefix, route.rawPath);
@@ -466,7 +193,7 @@ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
466
193
  });
467
194
  }
468
195
 
469
- const routeName = route.endpoint || (bpMeta ? `${bpMeta.bpName}.${route.actionName}` : route.actionName);
196
+ const routeName = route.endpoint || (bpMeta ? `${bpMeta.name}.${route.actionName}` : route.actionName);
470
197
 
471
198
  slices.push({
472
199
  domain_id: domainId ?? null,
@@ -488,28 +215,5 @@ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
488
215
 
489
216
  return slices;
490
217
  }
491
-
492
- private findPythonFiles(dir: string): string[] {
493
- const results: string[] = [];
494
- const traverse = (currentDir: string) => {
495
- if (!fs.existsSync(currentDir)) return;
496
- try {
497
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
498
- for (const entry of entries) {
499
- if (isIgnoredDirectory(entry.name)) continue;
500
-
501
- const fullPath = path.join(currentDir, entry.name);
502
- if (entry.isDirectory()) {
503
- traverse(fullPath);
504
- } else if (entry.isFile() && entry.name.endsWith(".py")) {
505
- results.push(fullPath);
506
- }
507
- }
508
- } catch {}
509
- };
510
-
511
- traverse(dir);
512
- return results;
513
- }
514
218
  }
515
219