@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,655 @@
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 ViewMethodInfo {
12
+ method: string;
13
+ action: string;
14
+ line: number;
15
+ isCustomAction?: boolean;
16
+ isDetail?: boolean;
17
+ }
18
+
19
+ interface ViewInfo {
20
+ file: string;
21
+ relPath: string;
22
+ line: number;
23
+ kind: "cbv" | "fbv" | "viewset";
24
+ serializer?: string;
25
+ model?: string;
26
+ methods: ViewMethodInfo[];
27
+ }
28
+
29
+ interface RouterRegistration {
30
+ urlFile: string;
31
+ prefix: string;
32
+ viewName: string;
33
+ basename?: string;
34
+ line: number;
35
+ }
36
+
37
+ interface PathRoute {
38
+ urlFile: string;
39
+ pattern: string;
40
+ viewName: string;
41
+ isAsView: boolean;
42
+ routeName?: string;
43
+ line: number;
44
+ }
45
+
46
+ interface UrlInclusion {
47
+ parentUrlFile: string;
48
+ pattern: string;
49
+ targetModule: string;
50
+ line: number;
51
+ }
52
+
53
+
54
+ function normalizeUri(prefix: string, sub: string): string {
55
+ const p = (prefix ?? "").trim().replace(/^\/+|\/+$/g, "");
56
+ const s = (sub ?? "").trim().replace(/^\/+|\/+$/g, "");
57
+ if (!p && !s) return "/";
58
+ if (!p) return `/${s}`;
59
+ if (!s) return `/${p}`;
60
+ return `/${p}/${s}`;
61
+ }
62
+
63
+ function cleanRoutePattern(raw: string): string {
64
+ return raw
65
+ .replace(/^\^+|\$+$/g, "")
66
+ .replace(/\(\?P<([a-zA-Z0-9_]+)>[^)]+\)/g, "{$1}")
67
+ .replace(/<([a-zA-Z0-9_]+:[a-zA-Z0-9_]+)>/g, (_match, p) => `{${p.split(":").pop()}}`)
68
+ .replace(/<([a-zA-Z0-9_]+)>/g, "{$1}");
69
+ }
70
+
71
+ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
72
+ public readonly id = "django";
73
+ public readonly name = "Django / DRF Semantic Slice Extractor";
74
+
75
+ public canHandle(projectRoot: string, framework?: string): boolean {
76
+ if (framework === "django") return true;
77
+
78
+ if (
79
+ fs.existsSync(path.join(projectRoot, "manage.py")) ||
80
+ fs.existsSync(path.join(projectRoot, "wsgi.py")) ||
81
+ fs.existsSync(path.join(projectRoot, "asgi.py"))
82
+ ) {
83
+ return true;
84
+ }
85
+
86
+ for (const manifest of ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"]) {
87
+ const fullPath = path.join(projectRoot, manifest);
88
+ if (fs.existsSync(fullPath)) {
89
+ try {
90
+ const content = fs.readFileSync(fullPath, "utf-8").toLowerCase();
91
+ if (content.includes("django")) return true;
92
+ } catch {}
93
+ }
94
+ }
95
+
96
+ return false;
97
+ }
98
+
99
+ public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): Promise<VerticalSliceCandidate[]> {
100
+ const slices: VerticalSliceCandidate[] = [];
101
+ const pyFiles = listSourceFiles(projectRoot, /\.py$/, inventory);
102
+ const resolver = new ImportResolver(projectRoot);
103
+
104
+ const viewsMap = new Map<string, ViewInfo>();
105
+ const routerRegistrations: RouterRegistration[] = [];
106
+ const pathRoutes: PathRoute[] = [];
107
+ const urlInclusions: UrlInclusion[] = [];
108
+
109
+ // 1. Locate and parse all views across Python files using Tree-sitter AST
110
+ for (const file of pyFiles) {
111
+ signal?.throwIfAborted();
112
+ const fileName = path.basename(file);
113
+ const isCandidate =
114
+ fileName.includes("view") ||
115
+ fileName.includes("api") ||
116
+ fileName.includes("urls");
117
+
118
+ const content = readOptionalSourceFile(file, "utf-8");
119
+ if (!content) continue;
120
+
121
+ const hasViewClues =
122
+ content.includes("ViewSet") ||
123
+ content.includes("APIView") ||
124
+ content.includes("View") ||
125
+ content.includes("api_view") ||
126
+ content.includes("router.register") ||
127
+ content.includes("urlpatterns");
128
+
129
+ if (!isCandidate && !hasViewClues) continue;
130
+
131
+ const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
132
+
133
+ const parsed = await parseSourceWithTreeSitter("python", content, (root) => {
134
+ const walk = (node: Parser.SyntaxNode, visit: (node: Parser.SyntaxNode) => void) => {
135
+ visit(node);
136
+ for (const child of node.namedChildren) walk(child, visit);
137
+ };
138
+
139
+ // A. Class-Based Views and ViewSets
140
+ walk(root, (node) => {
141
+ if (node.type !== "class_definition") return;
142
+ const nameNode = node.childForFieldName("name");
143
+ if (!nameNode) return;
144
+ const className = nameNode.text.trim();
145
+ const classLine = node.startPosition.row + 1;
146
+
147
+ const superNode = node.childForFieldName("superclasses");
148
+ const baseClasses: string[] = [];
149
+ if (superNode) {
150
+ for (const child of superNode.namedChildren) {
151
+ baseClasses.push(child.text.trim());
152
+ }
153
+ }
154
+
155
+ const isViewSet = baseClasses.some((b) => /ViewSet/i.test(b));
156
+ const isCbv = isViewSet || baseClasses.some((b) => /View/i.test(b));
157
+
158
+ let serializer: string | undefined;
159
+ let model: string | undefined;
160
+ const explicitMethods: Array<{
161
+ method: string;
162
+ action: string;
163
+ line: number;
164
+ isCustomAction?: boolean;
165
+ isDetail?: boolean;
166
+ }> = [];
167
+
168
+ const body = node.childForFieldName("body");
169
+ if (body) {
170
+ for (const child of body.namedChildren) {
171
+ if (child.type === "expression_statement") {
172
+ const assign = child.namedChildren[0];
173
+ if (assign?.type === "assignment") {
174
+ const left = assign.childForFieldName("left")?.text?.trim();
175
+ const right = assign.childForFieldName("right");
176
+ if (left === "serializer_class") {
177
+ serializer = right?.text?.trim();
178
+ } else if (left === "model") {
179
+ model = right?.text?.trim();
180
+ } else if (left === "queryset" && right) {
181
+ let cur = right.type === "call" ? right.childForFieldName("function") : right;
182
+ while (cur?.type === "attribute") {
183
+ cur = cur.childForFieldName("object");
184
+ }
185
+ if (cur?.type === "identifier" && /^[A-Z]/.test(cur.text)) {
186
+ model = cur.text;
187
+ }
188
+ }
189
+ }
190
+ } else if (child.type === "function_definition") {
191
+ const fnName = child.childForFieldName("name")?.text?.trim();
192
+ const fnLine = child.startPosition.row + 1;
193
+ if (!fnName) continue;
194
+
195
+ if (isViewSet) {
196
+ const actionMap: Record<string, string> = {
197
+ list: "GET",
198
+ create: "POST",
199
+ retrieve: "GET",
200
+ update: "PUT",
201
+ partial_update: "PATCH",
202
+ destroy: "DELETE",
203
+ };
204
+ if (actionMap[fnName]) {
205
+ explicitMethods.push({ method: actionMap[fnName], action: fnName, line: fnLine });
206
+ }
207
+ } else {
208
+ if (/^(get|post|put|patch|delete|options|head)$/.test(fnName)) {
209
+ explicitMethods.push({ method: fnName.toUpperCase(), action: fnName, line: fnLine });
210
+ }
211
+ }
212
+ } else if (child.type === "decorated_definition") {
213
+ const defNode = child.childForFieldName("definition");
214
+ if (defNode?.type === "function_definition") {
215
+ const fnName = defNode.childForFieldName("name")?.text?.trim();
216
+ const fnLine = defNode.startPosition.row + 1;
217
+ if (fnName && isViewSet) {
218
+ for (const dec of child.namedChildren.filter((c) => c.type === "decorator")) {
219
+ const decCall = dec.namedChildren[0];
220
+ if (decCall?.type === "call" && decCall.childForFieldName("function")?.text?.endsWith("action")) {
221
+ const args = decCall.childForFieldName("arguments")?.namedChildren ?? [];
222
+ const detailKw = args.find(
223
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "detail"
224
+ );
225
+ const isDetail = detailKw?.childForFieldName("value")?.text?.toLowerCase() === "true";
226
+ const methodsKw = args.find(
227
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "methods"
228
+ );
229
+ const actMethods: string[] = [];
230
+ if (methodsKw) {
231
+ const val = methodsKw.childForFieldName("value");
232
+ if (val?.type === "list") {
233
+ for (const m of val.namedChildren) {
234
+ const lit = cleanLiteral(m)?.toUpperCase();
235
+ if (lit) actMethods.push(lit);
236
+ }
237
+ }
238
+ }
239
+ if (actMethods.length === 0) actMethods.push("GET");
240
+ for (const method of actMethods) {
241
+ explicitMethods.push({ method, action: fnName, line: fnLine, isCustomAction: true, isDetail });
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+ }
249
+ }
250
+
251
+ const methods: ViewMethodInfo[] = [];
252
+
253
+ if (isViewSet) {
254
+ const fullCrud = baseClasses.some((b) => /\bModelViewSet\b/.test(b));
255
+ const readOnly = baseClasses.some((b) => /\bReadOnlyModelViewSet\b/.test(b));
256
+ const hasListMixin = baseClasses.some((b) => /\bListModelMixin\b/.test(b));
257
+ const hasCreateMixin = baseClasses.some((b) => /\bCreateModelMixin\b/.test(b));
258
+ const hasRetrieveMixin = baseClasses.some((b) => /\bRetrieveModelMixin\b/.test(b));
259
+ const hasUpdateMixin = baseClasses.some((b) => /\bUpdateModelMixin\b/.test(b));
260
+ const hasDestroyMixin = baseClasses.some((b) => /\bDestroyModelMixin\b/.test(b));
261
+
262
+ const defaultActions: Array<[string, string, boolean]> = [
263
+ ["GET", "list", fullCrud || readOnly || hasListMixin],
264
+ ["POST", "create", fullCrud || hasCreateMixin],
265
+ ["GET", "retrieve", fullCrud || readOnly || hasRetrieveMixin],
266
+ ["PUT", "update", fullCrud || hasUpdateMixin],
267
+ ["PATCH", "partial_update", fullCrud || hasUpdateMixin],
268
+ ["DELETE", "destroy", fullCrud || hasDestroyMixin],
269
+ ];
270
+
271
+ for (const [method, action, allowed] of defaultActions) {
272
+ const explicit = explicitMethods.find((m) => m.action === action && !m.isCustomAction);
273
+ if (explicit) {
274
+ methods.push(explicit);
275
+ } else if (allowed) {
276
+ methods.push({ method, action, line: classLine });
277
+ }
278
+ }
279
+
280
+ for (const custom of explicitMethods.filter((m) => m.isCustomAction)) {
281
+ methods.push(custom);
282
+ }
283
+ } else {
284
+ methods.push(...explicitMethods);
285
+ }
286
+
287
+ if (methods.length > 0 || isViewSet || serializer || model || isCbv) {
288
+ viewsMap.set(className, {
289
+ file,
290
+ relPath,
291
+ line: classLine,
292
+ kind: isViewSet ? "viewset" : "cbv",
293
+ serializer,
294
+ model,
295
+ methods,
296
+ });
297
+ }
298
+ });
299
+
300
+ // B. Function-Based Views with @api_view
301
+ walk(root, (node) => {
302
+ if (node.type !== "decorated_definition") return;
303
+ const fn = node.childForFieldName("definition");
304
+ if (fn?.type !== "function_definition") return;
305
+ const fnName = fn.childForFieldName("name")?.text?.trim();
306
+ if (!fnName) return;
307
+ const fnLine = fn.startPosition.row + 1;
308
+
309
+ for (const decorator of node.namedChildren.filter((c) => c.type === "decorator")) {
310
+ const call = decorator.namedChildren[0];
311
+ if (call?.type !== "call") continue;
312
+ const fnExpr = call.childForFieldName("function")?.text?.trim();
313
+ if (fnExpr !== "api_view" && fnExpr !== "rest_framework.decorators.api_view") continue;
314
+
315
+ const listArg = call.childForFieldName("arguments")?.namedChildren[0];
316
+ const httpMethods: string[] = [];
317
+ if (listArg?.type === "list") {
318
+ for (const item of listArg.namedChildren) {
319
+ const m = cleanLiteral(item)?.toUpperCase();
320
+ if (m) httpMethods.push(m);
321
+ }
322
+ }
323
+
324
+ if (httpMethods.length > 0) {
325
+ viewsMap.set(fnName, {
326
+ file,
327
+ relPath,
328
+ line: fnLine,
329
+ kind: "fbv",
330
+ methods: httpMethods.map((m) => ({ method: m, action: fnName, line: fnLine })),
331
+ });
332
+ }
333
+ }
334
+ });
335
+
336
+ // C. URLConf: router.register, path(), and re_path()
337
+ walk(root, (node) => {
338
+ if (node.type !== "call") return;
339
+ const fn = node.childForFieldName("function");
340
+ const args = node.childForFieldName("arguments")?.namedChildren ?? [];
341
+
342
+ // router.register(r'orders', OrderViewSet, basename='order')
343
+ if (fn?.type === "attribute" && fn.childForFieldName("attribute")?.text === "register") {
344
+ const firstArg = args[0];
345
+ const secondArg = args[1];
346
+ if (firstArg && secondArg) {
347
+ const prefix = cleanLiteral(firstArg);
348
+ if (prefix !== undefined) {
349
+ const viewName = secondArg.text.trim().split(".").pop() || secondArg.text.trim();
350
+ const bnKw = args.find(
351
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "basename"
352
+ );
353
+ const basename = cleanLiteral(bnKw?.childForFieldName("value"));
354
+ routerRegistrations.push({
355
+ urlFile: relPath,
356
+ prefix,
357
+ viewName,
358
+ basename,
359
+ line: node.startPosition.row + 1,
360
+ });
361
+ }
362
+ }
363
+ return;
364
+ }
365
+
366
+ // path('api/checkout/', CheckoutView.as_view(), name='checkout')
367
+ // path('api/', include('orders.urls'))
368
+ const fnName = fn?.text?.trim();
369
+ if (fnName === "path" || fnName === "re_path") {
370
+ const firstArg = args[0];
371
+ const secondArg = args[1];
372
+ if (!firstArg || !secondArg) return;
373
+
374
+ const pattern = cleanLiteral(firstArg);
375
+ if (pattern === undefined) return;
376
+
377
+ const nameKw = args.find(
378
+ (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "name"
379
+ );
380
+ const routeName = cleanLiteral(nameKw?.childForFieldName("value"));
381
+
382
+ // Check if secondArg is include(...)
383
+ if (secondArg.type === "call" && secondArg.childForFieldName("function")?.text?.endsWith("include")) {
384
+ const incArgs = secondArg.childForFieldName("arguments")?.namedChildren ?? [];
385
+ let incTarget: string | undefined;
386
+ if (incArgs[0]?.type === "string") {
387
+ incTarget = cleanLiteral(incArgs[0]);
388
+ } else if (incArgs[0]?.type === "tuple" || incArgs[0]?.type === "list") {
389
+ incTarget = cleanLiteral(incArgs[0].namedChildren[0]);
390
+ }
391
+ if (incTarget) {
392
+ urlInclusions.push({
393
+ parentUrlFile: relPath,
394
+ pattern,
395
+ targetModule: incTarget,
396
+ line: node.startPosition.row + 1,
397
+ });
398
+ }
399
+ return;
400
+ }
401
+
402
+ // Check if secondArg is View.as_view() or FBV
403
+ let isAsView = false;
404
+ let targetView = secondArg.text.trim();
405
+ if (secondArg.type === "call") {
406
+ const callFn = secondArg.childForFieldName("function");
407
+ if (callFn?.type === "attribute" && callFn.childForFieldName("attribute")?.text === "as_view") {
408
+ isAsView = true;
409
+ targetView = callFn.childForFieldName("object")?.text?.trim() || targetView;
410
+ }
411
+ }
412
+ targetView = targetView.split(".").pop() || targetView;
413
+
414
+ pathRoutes.push({
415
+ urlFile: relPath,
416
+ pattern,
417
+ viewName: targetView,
418
+ isAsView,
419
+ routeName,
420
+ line: node.startPosition.row + 1,
421
+ });
422
+ }
423
+ });
424
+
425
+ return { symbols: [], dependencies: [] };
426
+ });
427
+
428
+ if (parsed?.status !== "parsed") {
429
+ throw new Error(`Django AST unavailable or degraded: ${relPath}`);
430
+ }
431
+ }
432
+
433
+ // 2. Resolve Multi-file URLConf Inclusions (path('api/', include('orders.urls')))
434
+ const urlParentMap = new Map<string, Array<{ parentFile: string; prefix: string }>>();
435
+ for (const inc of urlInclusions) {
436
+ const parentAbs = path.resolve(projectRoot, inc.parentUrlFile);
437
+ const res = resolver.resolve(inc.targetModule, parentAbs);
438
+ if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
439
+ const targetRel = res.targets[0].files[0];
440
+ if (!urlParentMap.has(targetRel)) urlParentMap.set(targetRel, []);
441
+ urlParentMap.get(targetRel)!.push({ parentFile: inc.parentUrlFile, prefix: inc.pattern });
442
+ }
443
+ }
444
+
445
+ // Compute effective prefix for each urls.py file
446
+ const urlPrefixesByFile = new Map<string, string[]>();
447
+ const allUrlFiles = new Set<string>([
448
+ ...routerRegistrations.map((r) => r.urlFile),
449
+ ...pathRoutes.map((p) => p.urlFile),
450
+ ...urlInclusions.map((i) => i.parentUrlFile),
451
+ ]);
452
+
453
+ for (const uFile of allUrlFiles) {
454
+ const parents = urlParentMap.get(uFile);
455
+ if (!parents || parents.length === 0) {
456
+ urlPrefixesByFile.set(uFile, [""]);
457
+ }
458
+ }
459
+
460
+ const queue = Array.from(urlPrefixesByFile.keys());
461
+ const visitedIncs = new Set<string>();
462
+
463
+ while (queue.length > 0) {
464
+ const currentFile = queue.shift()!;
465
+ const currentPrefixes = urlPrefixesByFile.get(currentFile) ?? [""];
466
+
467
+ // Check children included by currentFile
468
+ for (const [targetFile, parents] of urlParentMap.entries()) {
469
+ for (const p of parents) {
470
+ if (p.parentFile === currentFile) {
471
+ const edgeKey = `${currentFile}->${targetFile}:${p.prefix}`;
472
+ if (visitedIncs.has(edgeKey)) continue;
473
+ visitedIncs.add(edgeKey);
474
+
475
+ const nextPrefixes = currentPrefixes.map((cp) => normalizeUri(cp, p.prefix));
476
+ const existing = urlPrefixesByFile.get(targetFile) ?? [];
477
+ const merged = Array.from(new Set([...existing, ...nextPrefixes]));
478
+ urlPrefixesByFile.set(targetFile, merged);
479
+ queue.push(targetFile);
480
+ }
481
+ }
482
+ }
483
+ }
484
+
485
+ // 3. Generate Vertical Slices from DRF Router Registrations
486
+ for (const reg of routerRegistrations) {
487
+ const prefixes = urlPrefixesByFile.get(reg.urlFile) ?? [""];
488
+ const viewInfo = viewsMap.get(reg.viewName);
489
+ if (!viewInfo) continue;
490
+
491
+ for (const pfx of prefixes) {
492
+ const routePrefix = normalizeUri(pfx, reg.prefix);
493
+
494
+ for (const m of viewInfo.methods) {
495
+ const uriSuffix = m.isCustomAction
496
+ ? (m.isDetail ? `/{id}/${m.action}` : `/${m.action}`)
497
+ : (m.action === "list" || m.action === "create" ? "" : "/{id}");
498
+ const fullUri = `${routePrefix === "/" ? "" : routePrefix}${uriSuffix}` || "/";
499
+
500
+ const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
501
+ {
502
+ stage: "ingress",
503
+ symbol: `${m.method} ${fullUri}`,
504
+ file: reg.urlFile,
505
+ line: reg.line,
506
+ description: `Django / DRF Route: ${m.method} ${fullUri}`,
507
+ },
508
+ ];
509
+
510
+ if (viewInfo.serializer) {
511
+ chain.push({
512
+ stage: "validation",
513
+ symbol: viewInfo.serializer,
514
+ description: "DRF Serializer Validation",
515
+ });
516
+ }
517
+
518
+ chain.push({
519
+ stage: "controller",
520
+ symbol: `${reg.viewName}::${m.action}`,
521
+ file: viewInfo.relPath,
522
+ line: m.line,
523
+ description:
524
+ m.isCustomAction
525
+ ? "DRF ViewSet Custom Action"
526
+ : m.line === viewInfo.line
527
+ ? "Inherited DRF action (inferred from base class or mixin; line points to class)"
528
+ : "DRF ViewSet Action",
529
+ });
530
+
531
+ if (viewInfo.model) {
532
+ chain.push({
533
+ stage: "model",
534
+ symbol: viewInfo.model,
535
+ description: "Django ORM Model",
536
+ });
537
+ }
538
+
539
+ const evidencedChain = chain.map((node) => ({
540
+ ...node,
541
+ relationship: {
542
+ kind:
543
+ node.stage === "ingress" || node.stage === "controller"
544
+ ? "route_binding"
545
+ : node.stage === "validation" || node.stage === "model"
546
+ ? "schema_binding"
547
+ : "calls",
548
+ derivation: node.file && node.line ? "source" : "inferred",
549
+ source: node.file && node.line ? { file: node.file, line: node.line } : undefined,
550
+ reason: node.description ?? "static adapter evidence",
551
+ },
552
+ }));
553
+
554
+ slices.push({
555
+ domain_id: domainId ?? null,
556
+ feature_key: null,
557
+ http_method: m.method,
558
+ route_uri: fullUri,
559
+ route_name: `${reg.viewName}.${m.action}`,
560
+ controller_class: reg.viewName,
561
+ action_name: m.action,
562
+ controller_file: viewInfo.relPath,
563
+ controller_line: m.line,
564
+ architecture_style: "django-drf",
565
+ entry_kind: "http_route",
566
+ execution_chain_json: JSON.stringify(evidencedChain),
567
+ });
568
+ }
569
+ }
570
+ }
571
+
572
+ // 4. Generate Vertical Slices from path() & re_path() Routes
573
+ for (const route of pathRoutes) {
574
+ const prefixes = urlPrefixesByFile.get(route.urlFile) ?? [""];
575
+ const viewInfo = viewsMap.get(route.viewName);
576
+ if (!viewInfo || viewInfo.methods.length === 0) continue;
577
+
578
+ for (const pfx of prefixes) {
579
+ const fullUri = normalizeUri(pfx, cleanRoutePattern(route.pattern));
580
+
581
+ for (const m of viewInfo.methods) {
582
+ const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
583
+ {
584
+ stage: "ingress",
585
+ symbol: `${m.method} ${fullUri}`,
586
+ file: route.urlFile,
587
+ line: route.line,
588
+ description: `Django Route: ${m.method} ${fullUri}`,
589
+ },
590
+ ];
591
+
592
+ if (viewInfo.serializer) {
593
+ chain.push({
594
+ stage: "validation",
595
+ symbol: viewInfo.serializer,
596
+ description: "Serializer Validation",
597
+ });
598
+ }
599
+
600
+ chain.push({
601
+ stage: "controller",
602
+ symbol: `${route.viewName}::${m.action}`,
603
+ file: viewInfo.relPath,
604
+ line: m.line,
605
+ description:
606
+ viewInfo.kind === "viewset" && m.line === viewInfo.line
607
+ ? "Inherited DRF action (inferred from base class or mixin; line points to class)"
608
+ : "Django View Handler",
609
+ });
610
+
611
+ if (viewInfo.model) {
612
+ chain.push({
613
+ stage: "model",
614
+ symbol: viewInfo.model,
615
+ description: "Django Model",
616
+ });
617
+ }
618
+
619
+ const evidencedChain = chain.map((node) => ({
620
+ ...node,
621
+ relationship: {
622
+ kind:
623
+ node.stage === "ingress" || node.stage === "controller"
624
+ ? "route_binding"
625
+ : node.stage === "validation" || node.stage === "model"
626
+ ? "schema_binding"
627
+ : "calls",
628
+ derivation: node.file && node.line ? "source" : "inferred",
629
+ source: node.file && node.line ? { file: node.file, line: node.line } : undefined,
630
+ reason: node.description ?? "static adapter evidence",
631
+ },
632
+ }));
633
+
634
+ slices.push({
635
+ domain_id: domainId ?? null,
636
+ feature_key: null,
637
+ http_method: m.method,
638
+ route_uri: fullUri,
639
+ route_name: route.routeName || `${route.viewName}.${m.action}`,
640
+ controller_class: route.viewName,
641
+ action_name: m.action,
642
+ controller_file: viewInfo.relPath,
643
+ controller_line: m.line,
644
+ architecture_style: "django-mvc",
645
+ entry_kind: "http_route",
646
+ execution_chain_json: JSON.stringify(evidencedChain),
647
+ });
648
+ }
649
+ }
650
+ }
651
+
652
+ return slices;
653
+ }
654
+ }
655
+