@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,527 +1,271 @@
1
- import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
3
- import { parseWithTreeSitter } from "../wasm-loader.ts";
4
- import { ImportResolver } from "../../resolver/import-resolver.ts";
5
- import type Parser from "web-tree-sitter";
6
- import * as fs from "node:fs";
7
1
  import * as path from "node:path";
2
+ import ts from "typescript";
3
+ import type { ExecutionChainNode } from "../../../types/index.ts";
4
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
5
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
8
6
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
9
-
10
- const NEST_HTTP_METHODS: Record<string, string> = {
11
- Get: "GET",
12
- Post: "POST",
13
- Put: "PUT",
14
- Patch: "PATCH",
15
- Delete: "DELETE",
16
- All: "ALL",
17
- Head: "HEAD",
18
- Options: "OPTIONS",
19
- };
20
-
21
- interface ParsedDecorator {
22
- name: string;
23
- args: string[];
24
- startLine: number;
7
+ import { lineOf, literal, nameText, nodes, objectMember, TypeScriptBindings } from "./typescript-bindings.ts";
8
+
9
+ const methodDecorators = new Map([
10
+ ["Get", "GET"], ["Post", "POST"], ["Put", "PUT"], ["Patch", "PATCH"], ["Delete", "DELETE"],
11
+ ["All", "ANY"], ["Head", "HEAD"], ["Options", "OPTIONS"], ["Search", "SEARCH"], ["Propfind", "PROPFIND"],
12
+ ["Proppatch", "PROPPATCH"], ["Mkcol", "MKCOL"], ["Copy", "COPY"], ["Move", "MOVE"], ["Lock", "LOCK"], ["Unlock", "UNLOCK"],
13
+ ]);
14
+
15
+ type Decorator = { name: string; site: ts.Decorator; args: readonly ts.Expression[] };
16
+ type FileOf = (node: ts.Node) => string;
17
+
18
+ function decorators(node: ts.Node, bindings: TypeScriptBindings, owner = "@nestjs/common"): Decorator[] {
19
+ if (!ts.canHaveDecorators(node)) return [];
20
+ return (ts.getDecorators(node) ?? []).flatMap(site => {
21
+ const call = site.expression;
22
+ if (!ts.isCallExpression(call)) return [];
23
+ const binding = bindings.packageBinding(call.expression);
24
+ if (binding?.module !== owner && !binding?.module.startsWith(owner + "/")) return [];
25
+ return [{ name: binding.name, site, args: call.arguments }];
26
+ });
25
27
  }
26
28
 
27
- export class NestJsSemanticExtractor implements SemanticSliceExtractor {
28
- public readonly id = "nestjs";
29
- public readonly name = "NestJS Modular Semantic Extractor";
30
-
31
- public canHandle(projectRoot: string, framework?: string): boolean {
32
- if (framework === "nestjs") return true;
29
+ function paths(value?: ts.Expression, emptyArrayMeansRoot = false): string[] | undefined {
30
+ if (!value) return [""];
31
+ const values = ts.isArrayLiteralExpression(value) ? value.elements.map(literal) : [literal(value)];
32
+ if (!values.every((item): item is string => item !== undefined)) return undefined;
33
+ return !values.length && emptyArrayMeansRoot ? [""] : [...new Set(values)];
34
+ }
33
35
 
34
- if (fs.existsSync(path.join(projectRoot, "nest-cli.json"))) return true;
36
+ function option(object: ts.ObjectLiteralExpression, key: string): ts.Expression | "unknown" | undefined {
37
+ const value = objectMember(object, key);
38
+ if (value) return ts.isMethodDeclaration(value) ? "unknown" : value;
39
+ if (object.properties.some(prop => ts.isSpreadAssignment(prop) ||
40
+ (prop.name && (ts.isComputedPropertyName(prop.name) || nameText(prop.name) === key)))) return "unknown";
41
+ return undefined;
42
+ }
35
43
 
36
- const pkgPath = path.join(projectRoot, "package.json");
37
- if (fs.existsSync(pkgPath)) {
38
- try {
39
- const pkg = JSON.parse(readOptionalSourceFile(pkgPath, "utf-8"));
40
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
41
- if (deps["@nestjs/core"] || deps["@nestjs/common"]) return true;
42
- } catch {}
43
- }
44
+ function controllerPaths(decorator: Decorator, bindings: TypeScriptBindings): string[] | undefined {
45
+ const value = bindings.value(decorator.args[0]);
46
+ if (!value || !ts.isObjectLiteralExpression(value)) return paths(value);
47
+ const pathValue = option(value, "path");
48
+ return pathValue === "unknown" ? undefined : paths(bindings.value(pathValue));
49
+ }
44
50
 
45
- return false;
51
+ function handlerRoute(decorator: Decorator, bindings: TypeScriptBindings) {
52
+ const value = bindings.value(decorator.args[0]);
53
+ if (decorator.name !== "RequestMapping") {
54
+ return { method: methodDecorators.get(decorator.name), paths: paths(value, true) };
46
55
  }
56
+ if (!value) return { method: "GET", paths: [""] };
57
+ if (!ts.isObjectLiteralExpression(value)) return undefined;
58
+ const pathValue = option(value, "path");
59
+ const methodValue = option(value, "method");
60
+ if (pathValue === "unknown" || methodValue === "unknown") return undefined;
61
+ const request = bindings.value(methodValue);
62
+ if (!request) return { method: "GET", paths: paths(bindings.value(pathValue), true) };
63
+ if (!ts.isPropertyAccessExpression(request)) return undefined;
64
+ const binding = bindings.packageBinding(request.expression);
65
+ if (binding?.name !== "RequestMethod" ||
66
+ !(binding.module === "@nestjs/common" || binding.module.startsWith("@nestjs/common/"))) return undefined;
67
+ const method = request.name.text === "ALL" ? "ANY" : request.name.text;
68
+ if (![...methodDecorators.values()].includes(method)) return undefined;
69
+ return { method, paths: paths(bindings.value(pathValue), true) };
70
+ }
47
71
 
48
- public async extractSlices(
49
- projectRoot: string,
50
- domainId?: number,
51
- signal?: AbortSignal, inventory?: SourceInventory
52
- ): Promise<VerticalSliceCandidate[]> {
53
- const slices: VerticalSliceCandidate[] = [];
54
- const srcDir = path.join(projectRoot, "src");
55
- if (!fs.existsSync(srcDir)) return slices;
56
-
57
- const resolver = new ImportResolver(projectRoot);
58
- const controllerFiles = listSourceFiles(srcDir, /\.controller\.(ts|js)$/, inventory);
59
-
60
- for (const file of controllerFiles) {
61
- if (signal?.aborted) throw new Error("semantic_extraction_cancelled");
62
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
63
- const content = readOptionalSourceFile(file, "utf-8");
64
- if (!content.trim()) continue;
65
-
66
- const fileSlices = await parseWithTreeSitter(
67
- "typescript",
68
- content,
69
- (rootNode) => this.extractFromAst(file, relPath, content, rootNode, projectRoot, resolver, domainId)
70
- );
71
-
72
- if (fileSlices && fileSlices.length > 0) {
73
- slices.push(...fileSlices);
72
+ function parameterProperties(node: ts.ClassLikeDeclaration): Map<string, ts.ParameterDeclaration> {
73
+ const result = new Map<string, ts.ParameterDeclaration>();
74
+ for (const member of node.members) {
75
+ if (!ts.isConstructorDeclaration(member)) continue;
76
+ for (const parameter of member.parameters) {
77
+ if (ts.isIdentifier(parameter.name) && ts.isParameterPropertyDeclaration(parameter, member)) {
78
+ result.set(parameter.name.text, parameter);
74
79
  }
75
80
  }
76
-
77
- return slices;
78
81
  }
82
+ return result;
83
+ }
79
84
 
80
- private extractFromAst(
81
- _filePath: string,
82
- relPath: string,
83
- content: string,
84
- rootNode: Parser.SyntaxNode,
85
- projectRoot: string,
86
- resolver: ImportResolver,
87
- domainId?: number
88
- ): VerticalSliceCandidate[] {
89
- const slices: VerticalSliceCandidate[] = [];
90
- const lines = content.split("\n");
85
+ function thisMember(node: ts.Expression): string | undefined {
86
+ return ts.isPropertyAccessExpression(node) && node.expression.kind === ts.SyntaxKind.ThisKeyword ? node.name.text : undefined;
87
+ }
91
88
 
92
- // Collect imports in controller file
93
- const importsMap = new Map<string, string>();
94
- for (const child of rootNode.namedChildren) {
95
- if (child.type === "import_statement") {
96
- const sourceNode = child.childForFieldName("source");
97
- const specifier = sourceNode ? sourceNode.text.replace(/^['"]|['"]$/g, "") : "";
98
- if (!specifier) continue;
99
- const importClause = child.namedChildren.find((c) => c.type === "import_clause");
100
- if (importClause) {
101
- for (const ic of importClause.namedChildren) {
102
- if (ic.type === "identifier") {
103
- importsMap.set(ic.text.trim(), specifier);
104
- } else if (ic.type === "namespace_import") {
105
- const idNode = ic.namedChildren.find((n) => n.type === "identifier");
106
- if (idNode) importsMap.set(idNode.text.trim(), specifier);
107
- } else if (ic.type === "named_imports") {
108
- for (const spec of ic.namedChildren) {
109
- if (spec.type === "import_specifier") {
110
- const alias = spec.childForFieldName("alias");
111
- const name = spec.childForFieldName("name") ?? spec.namedChildren[0];
112
- const ident = alias ? alias.text.trim() : name ? name.text.trim() : "";
113
- if (ident) importsMap.set(ident, specifier);
114
- }
115
- }
116
- }
117
- }
118
- }
89
+ function persistenceHints(
90
+ service: ts.ClassLikeDeclaration,
91
+ method: ts.MethodDeclaration,
92
+ bindings: TypeScriptBindings,
93
+ fileOf: FileOf,
94
+ ): ExecutionChainNode[] {
95
+ if (!method.body) return [];
96
+ const parameters = parameterProperties(service);
97
+ for (const call of nodes(method.body, true).filter(ts.isCallExpression)) {
98
+ const callee = call.expression;
99
+ if (!ts.isPropertyAccessExpression(callee) || !/^(find|save|create|update|delete|upsert|remove|insert)/.test(callee.name.text)) continue;
100
+ const receiver = callee.expression;
101
+ const repoName = thisMember(receiver);
102
+ const repository = repoName && parameters.get(repoName);
103
+ let entity: string | undefined;
104
+ let entitySource: ts.Node | undefined;
105
+ if (repository) {
106
+ const injection = [...decorators(repository, bindings, "@nestjs/typeorm"),
107
+ ...decorators(repository, bindings, "@nestjs/mongoose")].find(item => ["InjectRepository", "InjectModel"].includes(item.name));
108
+ const type = repository.type;
109
+ const generic = type && ts.isTypeReferenceNode(type) && /^(Repository|Model)$/.test(type.typeName.getText())
110
+ ? type.typeArguments?.[0] : undefined;
111
+ const entityExpression = injection?.args[0] ?? (generic && ts.isTypeReferenceNode(generic) && ts.isIdentifier(generic.typeName)
112
+ ? generic.typeName : undefined);
113
+ if (entityExpression) {
114
+ entity = nameText(entityExpression);
115
+ entitySource = bindings.definition(entityExpression);
119
116
  }
120
- }
121
-
122
- const walkForClasses = (node: Parser.SyntaxNode): void => {
123
- let classNode: Parser.SyntaxNode | null = null;
124
- let classDecorators: ParsedDecorator[] = [];
125
-
126
- if (node.type === "class_declaration") {
127
- classNode = node;
128
- classDecorators = node.namedChildren
129
- .filter((c) => c.type === "decorator")
130
- .map((c) => this.parseDecorator(c))
131
- .filter(Boolean) as ParsedDecorator[];
132
- } else if (node.type === "export_statement") {
133
- classDecorators = node.namedChildren
134
- .filter((c) => c.type === "decorator")
135
- .map((c) => this.parseDecorator(c))
136
- .filter(Boolean) as ParsedDecorator[];
137
- const innerClass = node.namedChildren.find((c) => c.type === "class_declaration");
138
- if (innerClass) {
139
- classNode = innerClass;
140
- const innerDecorators = innerClass.namedChildren
141
- .filter((c) => c.type === "decorator")
142
- .map((c) => this.parseDecorator(c))
143
- .filter(Boolean) as ParsedDecorator[];
144
- classDecorators.push(...innerDecorators);
145
- }
117
+ } else if (ts.isPropertyAccessExpression(receiver) && thisMember(receiver.expression) === "prisma") {
118
+ const model = receiver.name.text;
119
+ entity = model[0]!.toUpperCase() + model.slice(1);
120
+ } else if (ts.isIdentifier(receiver) && /^[A-Z]/.test(receiver.text)) {
121
+ const declaration = bindings.definition(receiver);
122
+ if (declaration && ts.isClassLike(declaration) && declaration !== service) {
123
+ entity = receiver.text;
124
+ entitySource = declaration;
146
125
  }
126
+ }
127
+ if (!entity) continue;
128
+ const origin = entitySource ?? call;
129
+ return [{
130
+ stage: "repository", symbol: entity + "Repository", file: fileOf(call), line: lineOf(call),
131
+ description: "Persistence call on a repository or model candidate",
132
+ }, {
133
+ stage: "entity", symbol: entity, file: fileOf(origin), line: lineOf(origin),
134
+ description: "Entity inferred from service source",
135
+ }];
136
+ }
137
+ return [];
138
+ }
147
139
 
148
- if (classNode) {
149
- const controllerDec = classDecorators.find((d) => d.name === "Controller");
150
- if (controllerDec) {
151
- const rawPrefix = controllerDec.args[0] ?? "";
152
- const routePrefix = rawPrefix ? `/${rawPrefix.replace(/^\/+|\/+$/g, "")}` : "";
153
- const nameNode = classNode.namedChildren.find((c) => c.type === "type_identifier" || c.type === "identifier");
154
- const controllerClass = nameNode ? nameNode.text.trim() : "AnonymousController";
155
- const classGuards = classDecorators.filter((d) => d.name === "UseGuards").flatMap((d) => d.args);
156
-
157
- this.processControllerClass(
158
- classNode,
159
- controllerClass,
160
- routePrefix,
161
- classGuards,
162
- relPath,
163
- lines,
164
- slices,
165
- importsMap,
166
- projectRoot,
167
- resolver,
168
- domainId
169
- );
170
- }
171
- return;
172
- }
140
+ function serviceHints(
141
+ action: ts.MethodDeclaration,
142
+ injections: ReadonlyMap<string, ts.ParameterDeclaration>,
143
+ bindings: TypeScriptBindings,
144
+ fileOf: FileOf,
145
+ ): ExecutionChainNode[] {
146
+ if (!action.body) return [];
147
+ const hints: ExecutionChainNode[] = [];
148
+ for (const call of nodes(action.body, true).filter(ts.isCallExpression)) {
149
+ const callee = call.expression;
150
+ if (!ts.isPropertyAccessExpression(callee)) continue;
151
+ const property = thisMember(callee.expression);
152
+ const injection = property && injections.get(property);
153
+ const type = injection ? injection.type : undefined;
154
+ if (!type || !ts.isTypeReferenceNode(type) || !ts.isIdentifier(type.typeName)) continue;
155
+ const service = bindings.definition(type.typeName);
156
+ const method = service && ts.isClassLike(service) && service.members.find(member =>
157
+ ts.isMethodDeclaration(member) && nameText(member.name) === callee.name.text && !!member.body,
158
+ );
159
+ const origin = method || call;
160
+ hints.push({
161
+ stage: "service", symbol: type.typeName.text + "::" + callee.name.text,
162
+ file: fileOf(origin), line: lineOf(origin), description: "Injected Service Call",
163
+ });
164
+ if (method && ts.isMethodDeclaration(method) && service && ts.isClassLike(service)) {
165
+ hints.push(...persistenceHints(service, method, bindings, fileOf));
166
+ }
167
+ }
168
+ return hints;
169
+ }
173
170
 
174
- for (const child of node.namedChildren) {
175
- walkForClasses(child);
176
- }
177
- };
171
+ export class NestJsSemanticExtractor implements SemanticSliceExtractor {
172
+ public readonly id = "nestjs";
173
+ public readonly name = "NestJS Modular Semantic Extractor";
178
174
 
179
- walkForClasses(rootNode);
180
- return slices;
175
+ public canHandle(projectRoot: string, framework?: string): boolean {
176
+ if (framework === "nestjs" || probeSourcePath(path.join(projectRoot, "nest-cli.json")) === "file") return true;
177
+ const manifest = path.join(projectRoot, "package.json");
178
+ if (probeSourcePath(manifest) !== "file") return false;
179
+ try {
180
+ const pkg = JSON.parse(readOptionalSourceFile(manifest, "utf-8"));
181
+ const dependencies = { ...pkg.dependencies, ...pkg.devDependencies };
182
+ return !!(dependencies["@nestjs/common"] || dependencies["@nestjs/core"]);
183
+ } catch { return false; }
181
184
  }
182
185
 
183
- private processControllerClass(
184
- classNode: Parser.SyntaxNode,
185
- controllerClass: string,
186
- routePrefix: string,
187
- classGuards: string[],
188
- relPath: string,
189
- _lines: string[],
190
- slices: VerticalSliceCandidate[],
191
- importsMap: Map<string, string>,
186
+ public async extractSlices(
192
187
  projectRoot: string,
193
- resolver: ImportResolver,
194
- domainId?: number
195
- ): void {
196
- const bodyNode =
197
- classNode.childForFieldName("body") ?? classNode.namedChildren.find((c) => c.type === "class_body");
198
- if (!bodyNode) return;
199
-
200
- // 1. Identify injected services from constructor
201
- const injectedServices = new Map<string, { type: string; line: number }>();
188
+ domainId?: number,
189
+ signal?: AbortSignal,
190
+ inventory?: SourceInventory,
191
+ ): Promise<VerticalSliceCandidate[]> {
192
+ const root = path.resolve(projectRoot);
193
+ const files = listSourceFiles(root, /\.[cm]?[jt]sx?$/, inventory).filter(file => !/\.d\.[cm]?ts$/.test(file));
194
+ const bindings = new TypeScriptBindings(root, new Set(files), signal);
195
+ const fileOf = (node: ts.Node) => path.relative(root, node.getSourceFile().fileName).replace(/\\/g, "/");
196
+ const slices: VerticalSliceCandidate[] = [];
202
197
 
203
- for (const member of bodyNode.namedChildren) {
204
- if (member.type === "method_definition") {
205
- const nameNode =
206
- member.childForFieldName("name") ??
207
- member.namedChildren.find((c) => c.type === "property_identifier" || c.type === "identifier");
208
- if (nameNode?.text === "constructor") {
209
- const paramsNode =
210
- member.childForFieldName("parameters") ??
211
- member.namedChildren.find((c) => c.type === "formal_parameters");
212
- if (paramsNode) {
213
- for (const param of paramsNode.namedChildren) {
214
- if (param.type === "required_parameter" || param.type === "optional_parameter") {
215
- const hasAccessibility = param.namedChildren.some((c) => c.type === "accessibility_modifier");
216
- const hasReadonly = param.namedChildren.some((c) => c.type === "readonly");
217
- if (hasAccessibility || hasReadonly) {
218
- const paramIdNode =
219
- param.childForFieldName("pattern") ??
220
- param.childForFieldName("name") ??
221
- param.namedChildren.find((c) => c.type === "identifier");
222
- const typeNode =
223
- param.childForFieldName("type") ??
224
- param.namedChildren.find((c) => c.type === "type_annotation");
225
- if (paramIdNode && typeNode) {
226
- const rawType = typeNode.text.replace(/^:\s*/, "").trim().split(/[<[{]/)[0].trim();
227
- if (rawType && /^[A-Z]/.test(rawType)) {
228
- injectedServices.set(paramIdNode.text.trim(), {
229
- type: rawType,
230
- line: param.startPosition.row + 1,
231
- });
232
- }
233
- }
234
- }
235
- }
236
- }
198
+ const controllerHint = /@[\s\S]*\bController\b|\bController\b[\s\S]*@/;
199
+ for (const file of files) {
200
+ signal?.throwIfAborted();
201
+ if (!bindings.matches(file, controllerHint)) continue;
202
+ const unit = bindings.load(file);
203
+ if (!unit) continue;
204
+ const relPath = fileOf(unit.source);
205
+ for (const node of unit.source.statements) {
206
+ if (!ts.isClassDeclaration(node) || node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.AbstractKeyword)) continue;
207
+ const declared = decorators(node, bindings);
208
+ const controller = declared.find(item => item.name === "Controller");
209
+ if (!controller) continue;
210
+ const prefixes = controllerPaths(controller, bindings);
211
+ if (!prefixes?.length) continue;
212
+ const controllerClass = nameText(node.name) ?? "AnonymousController";
213
+ const classGuards = declared.filter(item => item.name === "UseGuards");
214
+ const injections = parameterProperties(node);
215
+
216
+ for (const member of node.members) {
217
+ signal?.throwIfAborted();
218
+ if (!ts.isMethodDeclaration(member) || !member.body ||
219
+ member.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.StaticKeyword)) continue;
220
+ const action = nameText(member.name);
221
+ if (!action) continue;
222
+ const declared = decorators(member, bindings);
223
+ const registration = declared.find(item => methodDecorators.has(item.name) || item.name === "RequestMapping");
224
+ if (!registration) continue;
225
+ const route = handlerRoute(registration, bindings);
226
+ if (!route?.method || !route.paths?.length) continue;
227
+
228
+ const actionLine = lineOf(member.name);
229
+ const chain: ExecutionChainNode[] = [];
230
+ const guards = new Map<string, ts.Expression>();
231
+ for (const dec of [...classGuards, ...declared.filter(item => item.name === "UseGuards")]) {
232
+ for (const guard of dec.args) guards.set(guard.getText(), guard);
237
233
  }
238
- }
239
- }
240
- }
241
-
242
- // 2. Extract controller route actions with preceding decorators
243
- let pendingDecorators: ParsedDecorator[] = [];
244
-
245
- for (const member of bodyNode.namedChildren) {
246
- if (member.type === "decorator") {
247
- const dec = this.parseDecorator(member);
248
- if (dec) pendingDecorators.push(dec);
249
- continue;
250
- }
251
-
252
- if (member.type !== "method_definition") {
253
- pendingDecorators = [];
254
- continue;
255
- }
256
-
257
- const nameNode =
258
- member.childForFieldName("name") ??
259
- member.namedChildren.find((c) => c.type === "property_identifier" || c.type === "identifier");
260
- if (!nameNode || nameNode.text === "constructor") {
261
- pendingDecorators = [];
262
- continue;
263
- }
264
-
265
- const actionName = nameNode.text.trim();
266
- const actionLine = member.startPosition.row + 1;
267
-
268
- // Combine decorators attached to member and preceding decorators in class_body
269
- const memberAttachedDecorators = member.namedChildren
270
- .filter((c) => c.type === "decorator")
271
- .map((c) => this.parseDecorator(c))
272
- .filter(Boolean) as ParsedDecorator[];
273
- const methodDecorators = [...pendingDecorators, ...memberAttachedDecorators];
274
- pendingDecorators = [];
275
-
276
- const httpDec = methodDecorators.find((d) => NEST_HTTP_METHODS[d.name]);
277
- if (!httpDec) continue;
278
-
279
- const httpMethod = NEST_HTTP_METHODS[httpDec.name]!;
280
- const rawSub = httpDec.args[0] ?? "";
281
- const cleanSub = rawSub ? `/${rawSub.replace(/^\/+|\/+$/g, "")}` : "";
282
- const fullUri = `${routePrefix}${cleanSub}` || "/";
283
- const decoratorLine = httpDec.startLine || actionLine;
284
-
285
- // Method guards
286
- const methodGuards = methodDecorators.filter((d) => d.name === "UseGuards").flatMap((d) => d.args);
287
- const allGuards = Array.from(new Set([...classGuards, ...methodGuards]));
288
-
289
- // Extract DTO from @Body() parameter
290
- let validationDto: string | null = null;
291
- const paramsNode =
292
- member.childForFieldName("parameters") ??
293
- member.namedChildren.find((c) => c.type === "formal_parameters");
294
- if (paramsNode) {
295
- for (const param of paramsNode.namedChildren) {
296
- if (param.type === "required_parameter" || param.type === "optional_parameter") {
297
- const paramDecorators = param.namedChildren
298
- .filter((c) => c.type === "decorator")
299
- .map((c) => this.parseDecorator(c))
300
- .filter(Boolean) as ParsedDecorator[];
301
- if (paramDecorators.some((d) => d.name === "Body")) {
302
- const typeNode =
303
- param.childForFieldName("type") ?? param.namedChildren.find((c) => c.type === "type_annotation");
304
- if (typeNode) {
305
- const typeStr = typeNode.text.replace(/^:\s*/, "").trim().split(/[<[{]/)[0].trim();
306
- const primitiveTypes = new Set(["string", "number", "boolean", "any", "unknown", "object", "Record"]);
307
- if (typeStr && !primitiveTypes.has(typeStr)) {
308
- validationDto = typeStr;
309
- }
310
- }
311
- }
234
+ for (const [symbol, guard] of guards) {
235
+ chain.push({ stage: "guard", symbol, file: relPath, line: lineOf(guard), description: "NestJS Guard Argument" });
312
236
  }
313
- }
314
- }
315
-
316
- // 3. Trace explicit service calls in method body
317
- interface ExplicitServiceCall {
318
- symbol: string;
319
- file: string;
320
- line: number;
321
- persistenceNodes: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }>;
322
- }
323
- const explicitCalls: ExplicitServiceCall[] = [];
324
- const methodBody =
325
- member.childForFieldName("body") ?? member.namedChildren.find((c) => c.type === "statement_block");
326
- if (methodBody) {
327
- const walkCalls = (bNode: Parser.SyntaxNode): void => {
328
- if (bNode.type === "call_expression") {
329
- const fnNode =
330
- bNode.childForFieldName("function") ??
331
- bNode.namedChildren.find((c) => c.type === "member_expression");
332
- if (fnNode && fnNode.type === "member_expression") {
333
- const objNode = fnNode.childForFieldName("object") ?? fnNode.namedChildren[0];
334
- const propNode = fnNode.childForFieldName("property") ?? fnNode.namedChildren[1];
335
- if (objNode && objNode.type === "member_expression") {
336
- const subObj = objNode.childForFieldName("object") ?? objNode.namedChildren[0];
337
- const subProp = objNode.childForFieldName("property") ?? objNode.namedChildren[1];
338
- if (subObj?.text === "this" && subProp && injectedServices.has(subProp.text)) {
339
- const svc = injectedServices.get(subProp.text)!;
340
- const callMethod = propNode ? propNode.text.trim() : "action";
341
- let serviceFile: string | undefined;
342
- let serviceLine = bNode.startPosition.row + 1;
343
- const persistenceNodes: Array<{
344
- stage: string;
345
- symbol: string;
346
- file?: string;
347
- line?: number;
348
- description?: string;
349
- }> = [];
350
-
351
- const importSpec = importsMap.get(svc.type);
352
- if (importSpec) {
353
- const res = resolver.resolve(importSpec, path.resolve(projectRoot, relPath));
354
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
355
- serviceFile = res.targets[0].files[0];
356
- const fullServicePath = path.resolve(projectRoot, serviceFile);
357
- const serviceContent = readOptionalSourceFile(fullServicePath, "utf-8");
358
- if (serviceContent) {
359
- const mMatch = new RegExp(`(?:async\\s+)?(?:public\\s+)?\\b${callMethod}\\s*\\(`).exec(serviceContent);
360
- if (mMatch) {
361
- serviceLine = serviceContent.slice(0, mMatch.index).split("\n").length;
362
- }
363
-
364
- // Inspect for TypeORM / Prisma / Mongoose persistence
365
- const typeOrmMatch = serviceContent.match(
366
- /@InjectRepository\s*\(\s*([A-Za-z0-9_]+)\s*\)|Repository<\s*([A-Za-z0-9_]+)\s*>/
367
- );
368
- const prismaMatch = serviceContent.match(
369
- /this\.prisma\.([a-zA-Z0-9_]+)\.(?:find|create|update|delete|upsert)/
370
- );
371
- const mongooseMatch = serviceContent.match(/@InjectModel\s*\(\s*([A-Za-z0-9_]+)/);
372
- const arMatch = serviceContent.match(
373
- /\b([A-Z][a-zA-Z0-9_]+)\.(?:save|find|findOne|create|update|delete)\s*\(/
374
- );
375
-
376
- const entityName =
377
- typeOrmMatch ? (typeOrmMatch[1] || typeOrmMatch[2]) :
378
- prismaMatch ? (prismaMatch[1].charAt(0).toUpperCase() + prismaMatch[1].slice(1)) :
379
- mongooseMatch ? mongooseMatch[1] :
380
- arMatch && arMatch[1] !== svc.type ? arMatch[1] : undefined;
381
-
382
- if (entityName) {
383
- let entityFile: string | undefined;
384
- const entImportMatch = serviceContent.match(
385
- new RegExp(
386
- `import\\s+(?:{[^}]*\\b${entityName}\\b[^}]*}|\\b${entityName}\\b)\\s+from\\s+['"]([^'"]+)['"]`
387
- )
388
- );
389
- if (entImportMatch) {
390
- const eRes = resolver.resolve(entImportMatch[1], fullServicePath);
391
- if (eRes.status === "resolved" && eRes.targets[0]?.files?.[0]) {
392
- entityFile = eRes.targets[0].files[0];
393
- }
394
- }
395
-
396
- persistenceNodes.push({
397
- stage: "repository",
398
- symbol: `${entityName}Repository`,
399
- file: serviceFile,
400
- description: "TypeORM / Persistence Repository",
401
- });
402
- persistenceNodes.push({
403
- stage: "entity",
404
- symbol: entityName,
405
- file: entityFile || serviceFile,
406
- description: "Database Entity / Persistence Layer",
407
- });
408
- }
409
- }
410
- }
411
- }
412
-
413
- explicitCalls.push({
414
- symbol: `${svc.type}::${callMethod}`,
415
- file: serviceFile || relPath,
416
- line: serviceFile ? serviceLine : bNode.startPosition.row + 1,
417
- persistenceNodes,
418
- });
419
- }
420
- }
237
+ for (const param of member.parameters) {
238
+ if (!decorators(param, bindings).some(item => item.name === "Body")) continue;
239
+ const type = param.type;
240
+ if (type && ts.isTypeReferenceNode(type) && !["Record", "Array", "Promise"].includes(type.typeName.getText())) {
241
+ chain.push({ stage: "validation", symbol: type.typeName.getText(), description: "DTO Validation" });
421
242
  }
422
243
  }
423
- for (const c of bNode.namedChildren) {
424
- walkCalls(c);
425
- }
426
- };
427
- walkCalls(methodBody);
428
- }
429
-
430
- // 4. Construct execution chain
431
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
432
- {
433
- stage: "ingress",
434
- symbol: `${httpMethod} ${fullUri}`,
435
- file: relPath,
436
- line: decoratorLine,
437
- description: `NestJS Route: ${httpMethod} ${fullUri}`,
438
- },
439
- ];
440
-
441
- for (const guard of allGuards) {
442
- chain.push({
443
- stage: "guard",
444
- symbol: guard,
445
- file: relPath,
446
- line: actionLine,
447
- description: `NestJS Guard: ${guard}`,
448
- });
449
- }
450
-
451
- if (validationDto) {
452
- chain.push({
453
- stage: "validation",
454
- symbol: validationDto,
455
- description: "DTO Validation",
456
- });
457
- }
458
-
459
- chain.push({
460
- stage: "controller",
461
- symbol: `${controllerClass}::${actionName}`,
462
- file: relPath,
463
- line: actionLine,
464
- description: `NestJS Controller Action`,
465
- });
466
-
467
- for (const call of explicitCalls) {
468
- chain.push({
469
- stage: "service",
470
- symbol: call.symbol,
471
- file: call.file,
472
- line: call.line,
473
- description: `Injected Service Call`,
474
- });
475
- for (const pNode of call.persistenceNodes) {
476
- chain.push(pNode);
477
- }
478
- }
479
-
480
- slices.push({
481
- domain_id: domainId ?? null,
482
- feature_key: `nest.${controllerClass.toLowerCase().replace("controller", "")}.${actionName}`,
483
- http_method: httpMethod,
484
- route_uri: fullUri,
485
- route_name: `${controllerClass}.${actionName}`,
486
- controller_class: controllerClass,
487
- action_name: actionName,
488
- controller_file: relPath,
489
- controller_line: actionLine,
490
- architecture_style: "mvc",
491
- entry_kind: "http_route",
492
- execution_chain_json: JSON.stringify(chain),
493
- });
494
- }
495
- }
496
-
497
- private parseDecorator(node: Parser.SyntaxNode): ParsedDecorator | null {
498
- if (node.type !== "decorator") return null;
499
- const startLine = node.startPosition.row + 1;
500
- const first = node.namedChildren[0];
501
- if (!first) return null;
502
-
503
- if (first.type === "identifier") {
504
- return { name: first.text.trim(), args: [], startLine };
505
- }
506
-
507
- if (first.type === "call_expression") {
508
- const fnNode = first.childForFieldName("function") ?? first.namedChildren[0];
509
- const name = fnNode ? fnNode.text.trim() : "";
510
- const argsNode = first.childForFieldName("arguments") ?? first.namedChildren.find((c) => c.type === "arguments");
511
- const args: string[] = [];
512
-
513
- if (argsNode) {
514
- for (const arg of argsNode.namedChildren) {
515
- if (arg.type === "string" || arg.type === "template_string") {
516
- args.push(arg.text.replace(/^['"`]|['"`]$/g, "").trim());
517
- } else {
518
- args.push(arg.text.trim());
244
+ chain.push({
245
+ stage: "controller", symbol: controllerClass + "::" + action, file: relPath, line: actionLine,
246
+ description: "NestJS Controller Action",
247
+ }, ...serviceHints(member, injections, bindings, fileOf));
248
+
249
+ const routes = new Set(prefixes.flatMap(prefix => route.paths!.map(subpath =>
250
+ "/" + [prefix, subpath].map(value => value.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/"),
251
+ )));
252
+ for (const uri of routes) {
253
+ const ingress: ExecutionChainNode = {
254
+ stage: "ingress", symbol: route.method + " " + uri, file: relPath, line: lineOf(registration.site),
255
+ description: "NestJS Route Decorator",
256
+ };
257
+ slices.push({
258
+ domain_id: domainId ?? null,
259
+ feature_key: `nest.${controllerClass.toLowerCase().replace("controller", "")}.${action}`,
260
+ http_method: route.method, route_uri: uri, route_name: `${controllerClass}.${action}`,
261
+ controller_class: controllerClass, action_name: action, controller_file: relPath,
262
+ controller_line: actionLine, architecture_style: "mvc", entry_kind: "http_route",
263
+ execution_chain_json: JSON.stringify([ingress, ...chain]),
264
+ });
519
265
  }
520
266
  }
521
267
  }
522
- return { name, args, startLine };
523
268
  }
524
-
525
- return null;
269
+ return slices;
526
270
  }
527
271
  }