@dimassetoid/septum-mcp 0.0.0-stage → 0.2.1

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +122 -0
  7. package/src/cli/commands/hook.ts +268 -0
  8. package/src/cli/commands/init.ts +553 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +41 -0
  11. package/src/cli/commands/topology.ts +161 -0
  12. package/src/cli/index.ts +167 -0
  13. package/src/cli/scaffold/harness-config.ts +621 -0
  14. package/src/cli/templates/hooks.ts +75 -0
  15. package/src/cli/templates/rules.ts +50 -0
  16. package/src/cli/templates/skill.ts +51 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +442 -0
  19. package/src/core/boundary/staged-auditor.ts +58 -0
  20. package/src/core/config/loader.ts +122 -0
  21. package/src/core/config/schema.ts +69 -0
  22. package/src/core/database/client.ts +60 -0
  23. package/src/core/database/repositories/dependency.repository.ts +712 -0
  24. package/src/core/database/repositories/domain.repository.ts +330 -0
  25. package/src/core/database/repositories/environment.repository.ts +207 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +508 -0
  29. package/src/core/database/repository.ts +303 -0
  30. package/src/core/database/schema.ts +154 -0
  31. package/src/core/discovery/topology-detector.ts +805 -0
  32. package/src/core/ingestion/hasher.ts +5 -0
  33. package/src/core/ingestion/pipeline.ts +623 -0
  34. package/src/core/parser/behavioral-analyzer.ts +119 -0
  35. package/src/core/parser/boundary-tracker.ts +443 -0
  36. package/src/core/parser/extractors/base.ts +67 -0
  37. package/src/core/parser/extractors/blade.ts +159 -0
  38. package/src/core/parser/extractors/csharp.ts +244 -0
  39. package/src/core/parser/extractors/django-semantic.ts +687 -0
  40. package/src/core/parser/extractors/elysia-semantic.ts +538 -0
  41. package/src/core/parser/extractors/express-semantic.ts +444 -0
  42. package/src/core/parser/extractors/fastapi-semantic.ts +736 -0
  43. package/src/core/parser/extractors/fastify-semantic.ts +774 -0
  44. package/src/core/parser/extractors/flask-semantic.ts +515 -0
  45. package/src/core/parser/extractors/frontend.ts +149 -0
  46. package/src/core/parser/extractors/go-semantic.ts +611 -0
  47. package/src/core/parser/extractors/go.ts +491 -0
  48. package/src/core/parser/extractors/hono-semantic.ts +567 -0
  49. package/src/core/parser/extractors/java.ts +225 -0
  50. package/src/core/parser/extractors/laravel-semantic.ts +1122 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +368 -0
  52. package/src/core/parser/extractors/nestjs-semantic.ts +543 -0
  53. package/src/core/parser/extractors/php.ts +569 -0
  54. package/src/core/parser/extractors/python.ts +498 -0
  55. package/src/core/parser/extractors/registry.ts +78 -0
  56. package/src/core/parser/extractors/ruby.ts +234 -0
  57. package/src/core/parser/extractors/rust.ts +286 -0
  58. package/src/core/parser/extractors/semantic-extractor.interface.ts +22 -0
  59. package/src/core/parser/extractors/symfony-semantic.ts +354 -0
  60. package/src/core/parser/extractors/typescript.ts +826 -0
  61. package/src/core/parser/language-capabilities.ts +71 -0
  62. package/src/core/parser/schema/providers/laravel-migration-provider.ts +216 -0
  63. package/src/core/parser/schema/providers/prisma-schema-provider.ts +90 -0
  64. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  65. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  66. package/src/core/parser/tree-sitter.ts +63 -0
  67. package/src/core/parser/wasm-assets.ts +25 -0
  68. package/src/core/parser/wasm-loader.ts +274 -0
  69. package/src/core/resolver/call-graph-tracer.ts +724 -0
  70. package/src/core/resolver/import-resolver.ts +437 -0
  71. package/src/core/resolver/module-resolver.ts +482 -0
  72. package/src/core/resolver/path-resolver.ts +200 -0
  73. package/src/core/resolver/symbol-locator.ts +276 -0
  74. package/src/core/resolver/symbol-reference.ts +53 -0
  75. package/src/core/resolver/vertical-slice-tracer.ts +366 -0
  76. package/src/core/resources/ignore.ts +123 -0
  77. package/src/core/resources/limits.ts +14 -0
  78. package/src/core/resources/source-files.ts +62 -0
  79. package/src/core/resources/work-queue.ts +74 -0
  80. package/src/core/session/session-manager.ts +107 -0
  81. package/src/core/telemetry/telemetry.ts +97 -0
  82. package/src/core/topology/environment-detector.ts +973 -0
  83. package/src/core/topology/types.ts +83 -0
  84. package/src/index.ts +21 -0
  85. package/src/mcp/schemas.ts +1105 -0
  86. package/src/mcp/server.ts +774 -0
  87. package/src/mcp/tools/boundary.ts +17 -0
  88. package/src/mcp/tools/check-boundary.ts +387 -0
  89. package/src/mcp/tools/domain.ts +40 -0
  90. package/src/mcp/tools/feature.ts +67 -0
  91. package/src/mcp/tools/get-domain-catalog.ts +226 -0
  92. package/src/mcp/tools/get-environment-topology.ts +138 -0
  93. package/src/mcp/tools/get-feature-context.ts +224 -0
  94. package/src/mcp/tools/get-symbol-hotspots.ts +54 -0
  95. package/src/mcp/tools/get-symbol-impact.ts +64 -0
  96. package/src/mcp/tools/get-symbol.ts +175 -0
  97. package/src/mcp/tools/locate-symbol.ts +196 -0
  98. package/src/mcp/tools/register-domain.ts +75 -0
  99. package/src/mcp/tools/register-feature.ts +110 -0
  100. package/src/mcp/tools/slice.ts +16 -0
  101. package/src/mcp/tools/symbol.ts +93 -0
  102. package/src/mcp/tools/trace-vertical-slice.ts +80 -0
  103. package/src/mcp/workspace-manager.ts +159 -0
  104. package/src/mcp/workspace-watcher.ts +202 -0
  105. package/src/types/index.ts +456 -0
  106. package/src/types/wasm.d.ts +4 -0
  107. package/src/utils/version-check.ts +209 -0
  108. package/src/version.ts +1 -0
@@ -0,0 +1,515 @@
1
+ import type Parser from "web-tree-sitter";
2
+ import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
3
+ import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
+ import { isIgnoredDirectory } from "../../resources/ignore.ts";
5
+ import { ImportResolver } from "../../resolver/import-resolver.ts";
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
9
+
10
+ interface ExtractedFlaskRoute {
11
+ file: string;
12
+ relPath: string;
13
+ routerVar: string;
14
+ httpMethods: string[];
15
+ rawPath: string;
16
+ actionName: string;
17
+ endpoint?: string;
18
+ lineIndex: number;
19
+ actionLine: number;
20
+ templateEgress?: string;
21
+ }
22
+
23
+ interface ExtractedBlueprintRegistration {
24
+ file: string;
25
+ relPath: string;
26
+ parentVar: string;
27
+ targetExpr: string;
28
+ prefix: string;
29
+ line: number;
30
+ }
31
+
32
+ interface ImportBinding {
33
+ module: string;
34
+ symbol?: string;
35
+ }
36
+
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;
46
+ }
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}`;
56
+ }
57
+
58
+ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
59
+ public readonly id = "flask";
60
+ public readonly name = "Flask Semantic Slice Extractor";
61
+
62
+ public canHandle(projectRoot: string, framework?: string): boolean {
63
+ if (framework === "flask") return true;
64
+
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
+ }
87
+ }
88
+
89
+ return false;
90
+ }
91
+
92
+ public async extractSlices(
93
+ projectRoot: string,
94
+ domainId?: number,
95
+ signal?: AbortSignal
96
+ ): Promise<VerticalSliceCandidate[]> {
97
+ const slices: VerticalSliceCandidate[] = [];
98
+ const pyFiles = this.findPythonFiles(projectRoot);
99
+ const resolver = new ImportResolver(projectRoot);
100
+
101
+ const allRoutes: ExtractedFlaskRoute[] = [];
102
+ 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>>();
108
+
109
+ for (const file of pyFiles) {
110
+ signal?.throwIfAborted();
111
+ const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
112
+ 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"
216
+ );
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,
225
+ });
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"));
278
+
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
+ });
295
+ }
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
+
312
+ return { symbols: [], dependencies: [] };
313
+ });
314
+
315
+ if (parsed?.status !== "parsed") {
316
+ throw new Error(`Flask AST parsing degraded in file: ${relPath}`);
317
+ }
318
+ }
319
+
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[]>();
379
+
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
+ 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");
433
+
434
+ for (const prefix of prefixes) {
435
+ const fullUri = normalizeRouteUri(prefix, route.rawPath);
436
+
437
+ for (const httpMethod of route.httpMethods) {
438
+ const chain: Array<{
439
+ stage: string;
440
+ symbol: string;
441
+ file?: string;
442
+ line?: number;
443
+ description?: string;
444
+ }> = [
445
+ {
446
+ stage: "ingress",
447
+ symbol: `${httpMethod} ${fullUri}`,
448
+ file: route.relPath,
449
+ line: route.lineIndex,
450
+ description: `Flask Route: ${httpMethod} ${fullUri}`,
451
+ },
452
+ {
453
+ stage: "controller",
454
+ symbol: `${controllerClass}::${route.actionName}`,
455
+ file: route.relPath,
456
+ line: route.actionLine,
457
+ description: `Flask View Handler: ${route.actionName}`,
458
+ },
459
+ ];
460
+
461
+ if (route.templateEgress) {
462
+ chain.push({
463
+ stage: "egress",
464
+ symbol: route.templateEgress,
465
+ description: "Flask Template Render",
466
+ });
467
+ }
468
+
469
+ const routeName = route.endpoint || (bpMeta ? `${bpMeta.bpName}.${route.actionName}` : route.actionName);
470
+
471
+ slices.push({
472
+ domain_id: domainId ?? null,
473
+ feature_key: null,
474
+ http_method: httpMethod,
475
+ route_uri: fullUri,
476
+ route_name: routeName,
477
+ controller_class: controllerClass,
478
+ action_name: route.actionName,
479
+ controller_file: route.relPath,
480
+ controller_line: route.actionLine,
481
+ architecture_style: "flask",
482
+ entry_kind: "http_route",
483
+ execution_chain_json: JSON.stringify(chain),
484
+ });
485
+ }
486
+ }
487
+ }
488
+
489
+ return slices;
490
+ }
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
+ }
515
+
@@ -0,0 +1,149 @@
1
+ import { getLanguageCapability } from "../language-capabilities.ts";
2
+ import type {
3
+ ExtractedDependency,
4
+ ExtractedSymbol,
5
+ ParsedFileAST,
6
+ } from "../../../types/index.ts";
7
+ import type { CodeExtractor } from "./base.ts";
8
+ import { TypeScriptExtractor } from "./typescript.ts";
9
+
10
+ export class FrontendExtractor implements CodeExtractor {
11
+ private readonly tsExtractor = new TypeScriptExtractor();
12
+
13
+ public canHandle(filePath: string): boolean {
14
+ return getLanguageCapability(filePath)?.extractor === "frontend";
15
+ }
16
+
17
+ public async extract(filePath: string, content: string): Promise<ParsedFileAST> {
18
+ const symbols: ExtractedSymbol[] = [];
19
+ const dependencies: ExtractedDependency[] = [];
20
+
21
+ const isVue = /\.vue$/i.test(filePath);
22
+ const isAstro = /\.astro$/i.test(filePath);
23
+ const isSvelte = /\.svelte$/i.test(filePath);
24
+
25
+ if (isVue) {
26
+ await this.extractVue(content, symbols, dependencies);
27
+ } else if (isAstro) {
28
+ await this.extractAstro(content, symbols, dependencies);
29
+ } else if (isSvelte) {
30
+ await this.extractSvelte(content, symbols, dependencies);
31
+ }
32
+
33
+ return { symbols, dependencies };
34
+ }
35
+
36
+ private async extractVue(
37
+ content: string,
38
+ symbols: ExtractedSymbol[],
39
+ dependencies: ExtractedDependency[]
40
+ ): Promise<void> {
41
+ const scriptRegex = /<script(\s+[^>]*?)?>([\s\S]*?)<\/script>/gi;
42
+ let match: RegExpExecArray | null;
43
+
44
+ while ((match = scriptRegex.exec(content)) !== null) {
45
+ const fullMatch = match[0];
46
+ const attributes = match[1] || "";
47
+ const scriptBody = match[2];
48
+ const isSetup = /\bsetup\b/i.test(attributes);
49
+
50
+ const tagOpenMatch = fullMatch.match(/<script(\s+[^>]*?)?>/i);
51
+ const tagOpenLen = tagOpenMatch ? tagOpenMatch[0].length : 0;
52
+ const scriptStartOffset = match.index + tagOpenLen;
53
+ const startLine = content.slice(0, scriptStartOffset).split("\n").length;
54
+
55
+ await this.extractScriptContent(scriptBody, startLine, symbols, dependencies);
56
+
57
+ if (isSetup) {
58
+ const scriptLines = scriptBody.split("\n").length;
59
+ symbols.push({
60
+ name: "<script setup>",
61
+ kind: "method",
62
+ signature: "script setup",
63
+ visibility: "public",
64
+ line_start: startLine,
65
+ line_end: startLine + scriptLines - 1,
66
+ line_count: Math.max(1, scriptLines),
67
+ });
68
+ }
69
+ }
70
+
71
+ const definePropsMatch = content.match(/defineProps\s*<([^>]+)>/);
72
+ if (definePropsMatch) {
73
+ const line = content.slice(0, content.indexOf(definePropsMatch[0])).split("\n").length;
74
+ const propLines = definePropsMatch[0].split("\n").length;
75
+ symbols.push({
76
+ name: "Props",
77
+ kind: "interface",
78
+ signature: `defineProps<${definePropsMatch[1]}>`,
79
+ visibility: "public",
80
+ line_start: line,
81
+ line_end: line + propLines - 1,
82
+ line_count: Math.max(1, propLines),
83
+ });
84
+ }
85
+ }
86
+
87
+ private async extractAstro(
88
+ content: string,
89
+ symbols: ExtractedSymbol[],
90
+ dependencies: ExtractedDependency[]
91
+ ): Promise<void> {
92
+ const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
93
+ if (frontmatterMatch) {
94
+ const scriptBody = frontmatterMatch[1];
95
+ const startLine = 2;
96
+ await this.extractScriptContent(scriptBody, startLine, symbols, dependencies);
97
+ }
98
+ }
99
+
100
+ private async extractSvelte(
101
+ content: string,
102
+ symbols: ExtractedSymbol[],
103
+ dependencies: ExtractedDependency[]
104
+ ): Promise<void> {
105
+ const scriptRegex = /<script(\s+[^>]*?)?>([\s\S]*?)<\/script>/gi;
106
+ let match: RegExpExecArray | null;
107
+
108
+ while ((match = scriptRegex.exec(content)) !== null) {
109
+ const fullMatch = match[0];
110
+ const scriptBody = match[2];
111
+ const tagOpenMatch = fullMatch.match(/<script(\s+[^>]*?)?>/i);
112
+ const tagOpenLen = tagOpenMatch ? tagOpenMatch[0].length : 0;
113
+ const scriptStartOffset = match.index + tagOpenLen;
114
+ const startLine = content.slice(0, scriptStartOffset).split("\n").length;
115
+
116
+ await this.extractScriptContent(scriptBody, startLine, symbols, dependencies);
117
+ }
118
+ }
119
+
120
+ private async extractScriptContent(
121
+ scriptContent: string,
122
+ startLine: number,
123
+ symbols: ExtractedSymbol[],
124
+ dependencies: ExtractedDependency[]
125
+ ): Promise<void> {
126
+ const parsed = await this.tsExtractor.extract("component-script.ts", scriptContent);
127
+ if (parsed.status === "degraded") throw new Error("Cannot reliably parse component script.");
128
+ const delta = Math.max(0, startLine - 1);
129
+
130
+ for (const dep of parsed.dependencies) {
131
+ dependencies.push({
132
+ ...dep,
133
+ line_number: dep.line_number + delta,
134
+ });
135
+ }
136
+
137
+ for (const sym of parsed.symbols) {
138
+ const shiftedStart = sym.line_start + delta;
139
+ const shiftedEnd = Math.max(shiftedStart, sym.line_end + delta);
140
+ symbols.push({
141
+ ...sym,
142
+ line_start: shiftedStart,
143
+ line_end: shiftedEnd,
144
+ line_count: Math.max(1, shiftedEnd - shiftedStart + 1),
145
+ });
146
+ }
147
+ }
148
+ }
149
+