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