@dimassetoid/septum-mcp 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  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 +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +255 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -1,11 +1,18 @@
1
+ import { composeMountPrefixes } from "./route-prefixes.ts";
1
2
  import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
3
  import { readPythonStaticString as cleanLiteral } from "../static-string.ts";
3
- import type Parser from "web-tree-sitter";
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";
4
8
  import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
5
9
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
6
10
  import { ImportResolver } from "../../resolver/import-resolver.ts";
7
11
  import * as fs from "node:fs";
8
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";
9
16
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
10
17
 
11
18
  interface ViewMethodInfo {
@@ -14,50 +21,22 @@ interface ViewMethodInfo {
14
21
  line: number;
15
22
  isCustomAction?: boolean;
16
23
  isDetail?: boolean;
24
+ urlPath?: string;
17
25
  }
18
26
 
19
27
  interface ViewInfo {
20
- file: string;
28
+ name: string;
21
29
  relPath: string;
22
30
  line: number;
23
31
  kind: "cbv" | "fbv" | "viewset";
32
+ baseClasses?: string[];
24
33
  serializer?: string;
25
34
  model?: string;
26
35
  methods: ViewMethodInfo[];
27
36
  }
28
37
 
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}`;
38
+ function normalizeUri(value: string): string {
39
+ return "/" + value.trim().replace(/^\/+|\/+$/g, "");
61
40
  }
62
41
 
63
42
  function cleanRoutePattern(raw: string): string {
@@ -83,17 +62,12 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
83
62
  return true;
84
63
  }
85
64
 
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;
65
+ return anyFileContains(
66
+ projectRoot,
67
+ ["requirements.txt", "pyproject.toml", "Pipfile", "setup.py"],
68
+ ["django"],
69
+ true
70
+ );
97
71
  }
98
72
 
99
73
  public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): Promise<VerticalSliceCandidate[]> {
@@ -102,46 +76,81 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
102
76
  const resolver = new ImportResolver(projectRoot);
103
77
 
104
78
  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) {
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);
111
92
  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, "/");
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, "/");
132
96
 
133
97
  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;
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
+ }
142
150
  const nameNode = node.childForFieldName("name");
143
- if (!nameNode) return;
151
+ if (!nameNode) continue;
144
152
  const className = nameNode.text.trim();
153
+ imports.delete(className);
145
154
  const classLine = node.startPosition.row + 1;
146
155
 
147
156
  const superNode = node.childForFieldName("superclasses");
@@ -152,18 +161,15 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
152
161
  }
153
162
  }
154
163
 
155
- const isViewSet = baseClasses.some((b) => /ViewSet/i.test(b));
156
- 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
+ });
157
168
 
158
169
  let serializer: string | undefined;
159
170
  let model: string | undefined;
160
- const explicitMethods: Array<{
161
- method: string;
162
- action: string;
163
- line: number;
164
- isCustomAction?: boolean;
165
- isDetail?: boolean;
166
- }> = [];
171
+ let dispatchLine: number | undefined;
172
+ const explicitMethods: ViewMethodInfo[] = [];
167
173
 
168
174
  const body = node.childForFieldName("body");
169
175
  if (body) {
@@ -187,63 +193,46 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
187
193
  }
188
194
  }
189
195
  }
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 });
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;
210
208
  }
209
+ continue;
211
210
  }
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
- }
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
+ });
245
228
  }
246
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
+ }
247
236
  }
248
237
  }
249
238
  }
@@ -251,13 +240,14 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
251
240
  const methods: ViewMethodInfo[] = [];
252
241
 
253
242
  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));
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));
261
251
 
262
252
  const defaultActions: Array<[string, string, boolean]> = [
263
253
  ["GET", "list", fullCrud || readOnly || hasListMixin],
@@ -281,372 +271,298 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
281
271
  methods.push(custom);
282
272
  }
283
273
  } 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);
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 });
321
285
  }
322
286
  }
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
287
  }
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
288
 
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
- });
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
+ }
424
295
 
296
+ if (extractUrlconf) {
297
+ const routes = readDjangoUrlconf(root, signal);
298
+ if (routes.length) urlConfs.set(relPath, routes);
299
+ }
425
300
  return { symbols: [], dependencies: [] };
426
301
  });
427
302
 
428
303
  if (parsed?.status !== "parsed") {
429
304
  throw new Error(`Django AST unavailable or degraded: ${relPath}`);
430
305
  }
431
- }
306
+ };
432
307
 
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
- }
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);
443
315
  }
444
316
 
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, [""]);
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
+ }
457
332
  }
458
333
  }
459
334
 
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
- }
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);
481
345
  }
482
346
  }
483
347
  }
484
348
 
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",
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) });
358
+ }
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
+ };
367
+
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 }] : [];
515
385
  });
516
- }
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
+ }
517
400
 
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
- });
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
+ }
530
438
 
531
- 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";
532
442
  chain.push({
533
- stage: "model",
534
- symbol: viewInfo.model,
535
- description: "Django ORM 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),
536
469
  });
537
470
  }
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
471
  }
569
472
  }
570
473
  }
571
474
 
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
- });
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
+ });
610
481
 
611
- if (viewInfo.model) {
612
- chain.push({
613
- stage: "model",
614
- symbol: viewInfo.model,
615
- description: "Django Model",
616
- });
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
+ }
617
510
  }
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
- });
511
+ commandInfo = { classLine, handleLine, hasHandle };
512
+ break;
648
513
  }
649
- }
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
+ });
650
566
  }
651
567
 
652
568
  return slices;