@dimassetoid/septum-mcp 0.0.0-stage → 0.3.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -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 +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -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 +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,482 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
+ import { readPythonStaticString as cleanLiteral } from "../static-string.ts";
3
+ import type Parser from "web-tree-sitter";
4
+ import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
5
+ import { readOptionalSourceFile } from "../../resources/source-files.ts";
6
+ import { ImportResolver } from "../../resolver/import-resolver.ts";
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
10
+
11
+ interface ExtractedFlaskRoute {
12
+ file: string;
13
+ relPath: string;
14
+ routerVar: string;
15
+ httpMethods: string[];
16
+ rawPath: string;
17
+ actionName: string;
18
+ endpoint?: string;
19
+ lineIndex: number;
20
+ actionLine: number;
21
+ templateEgress?: string;
22
+ }
23
+
24
+ interface ExtractedBlueprintRegistration {
25
+ file: string;
26
+ relPath: string;
27
+ parentVar: string;
28
+ targetExpr: string;
29
+ prefix: string | null | undefined; // undefined: no override; null: unresolved expression.
30
+ line: number;
31
+ }
32
+
33
+ interface ImportBinding {
34
+ module: string;
35
+ symbol?: string;
36
+ }
37
+
38
+
39
+ function normalizeRouteUri(prefix: string, rawPath: string): string {
40
+ const p = (prefix ?? "").trim().replace(/\/+$/, "");
41
+ let r = (rawPath ?? "").trim();
42
+ if (!r.startsWith("/")) r = "/" + r;
43
+ if (r === "/" && p.length > 0) return p + "/";
44
+ if (r === "/" && p.length === 0) return "/";
45
+ const joined = `${p}${r}`;
46
+ return joined.startsWith("/") ? joined : `/${joined}`;
47
+ }
48
+
49
+ export class FlaskSemanticExtractor implements SemanticSliceExtractor {
50
+ public readonly id = "flask";
51
+ public readonly name = "Flask Semantic Slice Extractor";
52
+
53
+ public canHandle(projectRoot: string, framework?: string): boolean {
54
+ if (framework === "flask") return true;
55
+
56
+ // Check configuration manifests
57
+ for (const manifest of ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"]) {
58
+ const fullPath = path.join(projectRoot, manifest);
59
+ if (fs.existsSync(fullPath)) {
60
+ try {
61
+ const content = fs.readFileSync(fullPath, "utf-8").toLowerCase();
62
+ if (content.includes("flask")) return true;
63
+ } catch {}
64
+ }
65
+ }
66
+
67
+ // Check entrypoint files
68
+ for (const entry of ["app.py", "main.py", "wsgi.py", "run.py", "server.py", "src/app.py", "app/__init__.py"]) {
69
+ const fullPath = path.join(projectRoot, entry);
70
+ if (fs.existsSync(fullPath)) {
71
+ try {
72
+ const content = fs.readFileSync(fullPath, "utf-8");
73
+ if (content.includes("from flask") || content.includes("import flask")) {
74
+ return true;
75
+ }
76
+ } catch {}
77
+ }
78
+ }
79
+
80
+ return false;
81
+ }
82
+
83
+ public async extractSlices(
84
+ projectRoot: string,
85
+ domainId?: number,
86
+ signal?: AbortSignal, inventory?: SourceInventory
87
+ ): Promise<VerticalSliceCandidate[]> {
88
+ const slices: VerticalSliceCandidate[] = [];
89
+ const pyFiles = listSourceFiles(projectRoot, /\.py$/, inventory);
90
+ const resolver = new ImportResolver(projectRoot);
91
+
92
+ const allRoutes: ExtractedFlaskRoute[] = [];
93
+ const allRegistrations: ExtractedBlueprintRegistration[] = [];
94
+ const localBlueprints = new Map<
95
+ string,
96
+ { bpName: string; prefix: string | null; isApp: boolean }
97
+ >();
98
+ const fileImports = new Map<string, Map<string, ImportBinding>>();
99
+
100
+ for (const file of pyFiles) {
101
+ signal?.throwIfAborted();
102
+ const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
103
+ const content = readOptionalSourceFile(file, "utf-8");
104
+ if (
105
+ !content ||
106
+ (!content.includes("@") &&
107
+ !content.includes("register_blueprint") &&
108
+ !content.includes("Blueprint") &&
109
+ !content.includes("Flask"))
110
+ ) {
111
+ continue;
112
+ }
113
+
114
+ const importsInFile = new Map<string, ImportBinding>();
115
+ fileImports.set(relPath, importsInFile);
116
+
117
+ const parsed = await parseSourceWithTreeSitter("python", content, (root) => {
118
+ const walk = (node: Parser.SyntaxNode, visit: (node: Parser.SyntaxNode) => void) => {
119
+ visit(node);
120
+ for (const child of node.namedChildren) walk(child, visit);
121
+ };
122
+
123
+ // 1. Collect import statements
124
+ walk(root, (node) => {
125
+ if (node.type === "import_statement") {
126
+ for (const child of node.namedChildren) {
127
+ if (child.type === "dotted_name") {
128
+ const mod = child.text.trim();
129
+ const alias = mod.split(".").pop() || mod;
130
+ importsInFile.set(alias, { module: mod });
131
+ } else if (child.type === "aliased_import") {
132
+ const orig = child.childForFieldName("name")?.text?.trim();
133
+ const alias = child.childForFieldName("alias")?.text?.trim();
134
+ if (orig && alias) {
135
+ importsInFile.set(alias, { module: orig });
136
+ }
137
+ }
138
+ }
139
+ } else if (node.type === "import_from_statement") {
140
+ const moduleName = node.childForFieldName("module_name")?.text?.trim() || "";
141
+ for (const child of node.namedChildren) {
142
+ if (child === node.childForFieldName("module_name")) continue;
143
+ if (child.type === "dotted_name") {
144
+ const sym = child.text.trim();
145
+ importsInFile.set(sym, { module: moduleName || sym, symbol: sym });
146
+ } else if (child.type === "aliased_import") {
147
+ const orig = child.childForFieldName("name")?.text?.trim();
148
+ const alias = child.childForFieldName("alias")?.text?.trim();
149
+ if (orig && alias) {
150
+ importsInFile.set(alias, { module: moduleName || orig, symbol: orig });
151
+ }
152
+ }
153
+ }
154
+ }
155
+ });
156
+
157
+ // 2. Collect Flask App and Blueprint instantiations
158
+ walk(root, (node) => {
159
+ if (node.type !== "assignment" || node.parent?.parent?.type !== "module") return;
160
+ const leftName = node.childForFieldName("left")?.text ?? "";
161
+ const call = node.childForFieldName("right");
162
+ if (call?.type !== "call") return;
163
+ const fnText = call.childForFieldName("function")?.text ?? "";
164
+ const isBlueprint = /Blueprint$/.test(fnText);
165
+ const isApp = /Flask$/.test(fnText);
166
+ if (!isBlueprint && !isApp) return;
167
+
168
+ const args = call.childForFieldName("arguments")?.namedChildren ?? [];
169
+ let bpName = leftName;
170
+ let prefix: string | null = "";
171
+
172
+ if (isBlueprint && args.length > 0) {
173
+ const firstArg = args[0];
174
+ if (firstArg.type !== "keyword_argument") {
175
+ const lit = cleanLiteral(firstArg);
176
+ if (lit) bpName = lit;
177
+ }
178
+ }
179
+
180
+ const prefixKw = args.find(
181
+ (child) => child.type === "keyword_argument" && child.childForFieldName("name")?.text === "url_prefix"
182
+ );
183
+ if (prefixKw) {
184
+ const value = prefixKw.childForFieldName("value");
185
+ prefix = value?.type === "none" ? "" : cleanLiteral(value) ?? null;
186
+ }
187
+
188
+ localBlueprints.set(`${relPath}#${leftName}`, {
189
+ bpName,
190
+ prefix: prefix?.replace(/\/+$/, "") ?? null,
191
+ isApp,
192
+ });
193
+ });
194
+
195
+ // 3. Collect register_blueprint calls
196
+ walk(root, (node) => {
197
+ if (node.type !== "call") return;
198
+ const fn = node.childForFieldName("function");
199
+ if (fn?.type !== "attribute" || fn.childForFieldName("attribute")?.text !== "register_blueprint") return;
200
+ const parentVar = fn.childForFieldName("object")?.text ?? "";
201
+ const args = node.childForFieldName("arguments")?.namedChildren ?? [];
202
+ const firstArg = args[0];
203
+ if (!firstArg || firstArg.type === "keyword_argument") return;
204
+
205
+ const targetExpr = firstArg.text.trim();
206
+ const prefixKw = args.find(
207
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "url_prefix"
208
+ );
209
+ const prefixValue = prefixKw?.childForFieldName("value");
210
+ const incPrefix = !prefixKw || prefixValue?.type === "none" ? undefined : cleanLiteral(prefixValue) ?? null;
211
+ allRegistrations.push({
212
+ file,
213
+ relPath,
214
+ parentVar,
215
+ targetExpr,
216
+ prefix: incPrefix === undefined ? undefined : incPrefix?.replace(/\/+$/, "") ?? null,
217
+ line: node.startPosition.row + 1,
218
+ });
219
+ });
220
+
221
+ // 4. Collect route handler definitions
222
+ walk(root, (node) => {
223
+ if (node.type !== "decorated_definition" || node.parent?.type !== "module") return;
224
+ const fn = node.childForFieldName("definition");
225
+ if (fn?.type !== "function_definition") return;
226
+
227
+ for (const decorator of node.namedChildren.filter((child) => child.type === "decorator")) {
228
+ const call = decorator.namedChildren[0];
229
+ const attr = call?.childForFieldName("function");
230
+ if (call?.type !== "call" || attr?.type !== "attribute") continue;
231
+
232
+ const decoratorMethod = attr.childForFieldName("attribute")?.text ?? "";
233
+ const isRoute = decoratorMethod === "route";
234
+ const isShorthand = /^(get|post|put|patch|delete|options|head)$/i.test(decoratorMethod);
235
+ if (!isRoute && !isShorthand) continue;
236
+
237
+ const args = call.childForFieldName("arguments")?.namedChildren ?? [];
238
+ const rawPath = cleanLiteral(args[0]);
239
+ if (rawPath === undefined) continue;
240
+
241
+ const routerVar = attr.childForFieldName("object")?.text ?? "";
242
+ const actionName = fn.childForFieldName("name")?.text ?? "";
243
+
244
+ // Determine HTTP methods
245
+ let httpMethods: string[] = [];
246
+ if (isRoute) {
247
+ const methodsKw = args.find(
248
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "methods"
249
+ );
250
+ if (methodsKw) {
251
+ const val = methodsKw.childForFieldName("value");
252
+ if (val && (val.type === "list" || val.type === "tuple")) {
253
+ for (const m of val.namedChildren) {
254
+ const lit = cleanLiteral(m)?.toUpperCase();
255
+ if (lit) httpMethods.push(lit);
256
+ }
257
+ }
258
+ }
259
+ if (httpMethods.length === 0) {
260
+ httpMethods = ["GET"];
261
+ }
262
+ } else {
263
+ httpMethods = [decoratorMethod.toUpperCase()];
264
+ }
265
+
266
+ // Extract optional endpoint
267
+ const endpointKw = args.find(
268
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "endpoint"
269
+ );
270
+ const endpoint = cleanLiteral(endpointKw?.childForFieldName("value"));
271
+
272
+ // Check function body for template render egress
273
+ let templateEgress: string | undefined;
274
+ const body = fn.childForFieldName("body");
275
+ if (body) {
276
+ walk(body, (child) => {
277
+ if (child.type === "call") {
278
+ const calledFn = child.childForFieldName("function")?.text ?? "";
279
+ if (calledFn === "render_template") {
280
+ const tmplArg = child.childForFieldName("arguments")?.namedChildren[0];
281
+ const tmpl = cleanLiteral(tmplArg);
282
+ if (tmpl && !templateEgress) {
283
+ templateEgress = tmpl;
284
+ }
285
+ }
286
+ }
287
+ });
288
+ }
289
+
290
+ allRoutes.push({
291
+ file,
292
+ relPath,
293
+ routerVar,
294
+ httpMethods,
295
+ rawPath,
296
+ actionName,
297
+ endpoint,
298
+ lineIndex: decorator.startPosition.row + 1,
299
+ actionLine: fn.startPosition.row + 1,
300
+ templateEgress,
301
+ });
302
+ }
303
+ });
304
+
305
+ return { symbols: [], dependencies: [] };
306
+ });
307
+
308
+ if (parsed?.status !== "parsed") {
309
+ throw new Error(`Flask AST parsing degraded in file: ${relPath}`);
310
+ }
311
+ }
312
+
313
+ // 5. Build Inclusion Graph and Resolve Cross-File Blueprint Targets
314
+ const routerChildren = new Map<string, Array<{ childKey: string; prefix: string | null | undefined }>>();
315
+ const incomingRegistrations = new Map<string, Array<{ parentKey: string; prefix: string | null | undefined }>>();
316
+
317
+ for (const reg of allRegistrations) {
318
+ const parentKey = `${reg.relPath}#${reg.parentVar}`;
319
+ const importsInFile = fileImports.get(reg.relPath) ?? new Map<string, ImportBinding>();
320
+
321
+ let targetKey: string | undefined;
322
+
323
+ if (reg.targetExpr.includes(".")) {
324
+ const [objName, propName] = reg.targetExpr.split(".");
325
+ const binding = importsInFile.get(objName);
326
+ if (binding) {
327
+ const subTarget = binding.module ? `${binding.module}.${binding.symbol || objName}` : objName;
328
+ let res = resolver.resolve(subTarget, reg.file);
329
+ if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
330
+ targetKey = `${res.targets[0].files[0]}#${propName}`;
331
+ } else if (binding.module) {
332
+ res = resolver.resolve(binding.module, reg.file);
333
+ if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
334
+ targetKey = `${res.targets[0].files[0]}#${propName}`;
335
+ }
336
+ }
337
+ }
338
+ } else {
339
+ const binding = importsInFile.get(reg.targetExpr);
340
+ if (binding) {
341
+ const subTarget =
342
+ binding.module && binding.symbol ? `${binding.module}.${binding.symbol}` : binding.module || binding.symbol!;
343
+ let res = resolver.resolve(subTarget, reg.file);
344
+ if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
345
+ targetKey = `${res.targets[0].files[0]}#${binding.symbol || reg.targetExpr}`;
346
+ } else if (binding.module) {
347
+ res = resolver.resolve(binding.module, reg.file);
348
+ if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
349
+ targetKey = `${res.targets[0].files[0]}#${binding.symbol || reg.targetExpr}`;
350
+ }
351
+ }
352
+ } else {
353
+ // Local blueprint inside same file
354
+ const candidate = `${reg.relPath}#${reg.targetExpr}`;
355
+ if (localBlueprints.has(candidate)) {
356
+ targetKey = candidate;
357
+ }
358
+ }
359
+ }
360
+
361
+ if (targetKey) {
362
+ if (!routerChildren.has(parentKey)) routerChildren.set(parentKey, []);
363
+ routerChildren.get(parentKey)!.push({ childKey: targetKey, prefix: reg.prefix });
364
+
365
+ if (!incomingRegistrations.has(targetKey)) incomingRegistrations.set(targetKey, []);
366
+ incomingRegistrations.get(targetKey)!.push({ parentKey, prefix: reg.prefix });
367
+ }
368
+ }
369
+
370
+ // 6. Compute Effective Prefixes for Each Router/Blueprint
371
+ const effectivePrefixesByRouter = new Map<string, string[]>();
372
+
373
+ const allRouterKeys = new Set<string>([
374
+ ...localBlueprints.keys(),
375
+ ...allRoutes.map((r) => `${r.relPath}#${r.routerVar}`),
376
+ ]);
377
+
378
+ // Find root routers
379
+ for (const routerKey of allRouterKeys) {
380
+ const incoming = incomingRegistrations.get(routerKey);
381
+ if (!incoming || incoming.length === 0) {
382
+ const local = localBlueprints.get(routerKey);
383
+ effectivePrefixesByRouter.set(routerKey, local?.prefix === null ? [] : [local?.prefix ?? ""]);
384
+ }
385
+ }
386
+
387
+ // Propagate prefixes along registration edges via BFS
388
+ const queue = Array.from(effectivePrefixesByRouter.keys());
389
+ const visitedEdges = new Set<string>();
390
+
391
+ while (queue.length > 0) {
392
+ const current = queue.shift()!;
393
+ const currentPrefixes = effectivePrefixesByRouter.get(current) ?? [""];
394
+ const children = routerChildren.get(current) ?? [];
395
+
396
+ for (const child of children) {
397
+ const edgeKey = `${current}->${child.childKey}:${child.prefix}`;
398
+ if (visitedEdges.has(edgeKey)) continue;
399
+ visitedEdges.add(edgeKey);
400
+
401
+ const childPrefix = child.prefix === undefined ? localBlueprints.get(child.childKey)?.prefix ?? null : child.prefix;
402
+ const nextPrefixes = childPrefix === null ? [] : currentPrefixes.map((p) => {
403
+ const combined = `${p ? (p.startsWith("/") ? p : `/${p}`) : ""}${
404
+ childPrefix ? (childPrefix.startsWith("/") ? childPrefix : `/${childPrefix}`) : ""
405
+ }`;
406
+ return combined.replace(/\/+/g, "/").replace(/\/+$/, "");
407
+ });
408
+
409
+ const existing = effectivePrefixesByRouter.get(child.childKey) ?? [];
410
+ const merged = Array.from(new Set([...existing, ...nextPrefixes]));
411
+ effectivePrefixesByRouter.set(child.childKey, merged);
412
+ queue.push(child.childKey);
413
+ }
414
+ }
415
+
416
+ // 7. Generate Vertical Slices (Level 0 – Level 3)
417
+ for (const route of allRoutes) {
418
+ const routerKey = `${route.relPath}#${route.routerVar}`;
419
+ const prefixes = effectivePrefixesByRouter.get(routerKey) ?? [];
420
+
421
+ const bpMeta = localBlueprints.get(routerKey);
422
+ const controllerClass = bpMeta?.bpName || path.basename(route.file, ".py");
423
+
424
+ for (const prefix of prefixes) {
425
+ const fullUri = normalizeRouteUri(prefix, route.rawPath);
426
+
427
+ for (const httpMethod of route.httpMethods) {
428
+ const chain: Array<{
429
+ stage: string;
430
+ symbol: string;
431
+ file?: string;
432
+ line?: number;
433
+ description?: string;
434
+ }> = [
435
+ {
436
+ stage: "ingress",
437
+ symbol: `${httpMethod} ${fullUri}`,
438
+ file: route.relPath,
439
+ line: route.lineIndex,
440
+ description: `Flask Route: ${httpMethod} ${fullUri}`,
441
+ },
442
+ {
443
+ stage: "controller",
444
+ symbol: `${controllerClass}::${route.actionName}`,
445
+ file: route.relPath,
446
+ line: route.actionLine,
447
+ description: `Flask View Handler: ${route.actionName}`,
448
+ },
449
+ ];
450
+
451
+ if (route.templateEgress) {
452
+ chain.push({
453
+ stage: "egress",
454
+ symbol: route.templateEgress,
455
+ description: "Flask Template Render",
456
+ });
457
+ }
458
+
459
+ const routeName = route.endpoint || (bpMeta ? `${bpMeta.bpName}.${route.actionName}` : route.actionName);
460
+
461
+ slices.push({
462
+ domain_id: domainId ?? null,
463
+ feature_key: null,
464
+ http_method: httpMethod,
465
+ route_uri: fullUri,
466
+ route_name: routeName,
467
+ controller_class: controllerClass,
468
+ action_name: route.actionName,
469
+ controller_file: route.relPath,
470
+ controller_line: route.actionLine,
471
+ architecture_style: "flask",
472
+ entry_kind: "http_route",
473
+ execution_chain_json: JSON.stringify(chain),
474
+ });
475
+ }
476
+ }
477
+ }
478
+
479
+ return slices;
480
+ }
481
+ }
482
+
@@ -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
+