@dimassetoid/septum-mcp 0.3.0 → 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 (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 +253 -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,52 +1,28 @@
1
- import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
- import type Parser from "web-tree-sitter";
3
- import { parseWithTreeSitter } from "../wasm-loader.ts";
4
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
5
- import { ImportResolver } from "../../resolver/import-resolver.ts";
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";
6
+ import { hasPackageJsonDependency } from "./manifest-helpers.ts";
8
7
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
9
-
10
- const HONO_VERBS = new Set(["get", "post", "put", "patch", "delete", "all"]);
11
-
12
- interface ExtractedRoute {
13
- file: string;
14
- relPath: string;
15
- routerVar: string;
16
- httpMethods: string[];
17
- rawPath: string;
18
- middlewares: Array<{ symbol: string; line: number }>;
19
- validationSchema?: { symbol: string; file?: string; line?: number };
20
- handler: { symbol: string; line: number; node?: Parser.SyntaxNode };
21
- routeLine: number;
22
- }
23
-
24
- interface ExtractedMount {
25
- file: string;
26
- relPath: string;
27
- callerVar: string;
28
- prefix: string;
29
- targetVar: string;
30
- line: number;
31
- }
32
-
33
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
34
- if (!node) return undefined;
35
- if (node.type === "string") {
36
- const raw = node.text.trim();
37
- return raw.replace(/^['"`]|['"`]$/g, "");
38
- }
39
- return undefined;
8
+ import { lineOf, literal, TypeScriptBindings, visitRouteCalls } from "./typescript-bindings.ts";
9
+ import { routeContext } from "./typescript-route-context.ts";
10
+
11
+ const verbs = new Set(["get", "post", "put", "patch", "delete", "options", "head", "all"]);
12
+ const instanceMethods = new Set([...verbs, "on", "use", "route", "onError", "notFound", "mount"]);
13
+ type Receiver = { root: ts.NewExpression; base: string | undefined };
14
+ type Route = { method: string; uri: string; registration: ts.CallExpression; handlers: readonly ts.Expression[] };
15
+
16
+ function literals(expression?: ts.Expression): string[] {
17
+ if (!expression) return [];
18
+ const values = ts.isArrayLiteralExpression(expression) ? expression.elements.map(literal) : [literal(expression)];
19
+ return values.every((value): value is string => value !== undefined) ? values : [];
40
20
  }
41
21
 
42
- function normalizeRouteUri(prefix: string, rawPath: string): string {
43
- const p = (prefix ?? "").trim().replace(/\/+$/, "");
44
- let r = (rawPath ?? "").trim();
45
- if (!r.startsWith("/")) r = "/" + r;
46
- if (r === "/" && p.length > 0) return `${p}/`;
47
- if (r === "/" && p.length === 0) return "/";
48
- const joined = `${p}${r}`;
49
- return joined.startsWith("/") ? joined : `/${joined}`;
22
+ function join(base: string, sub: string): string {
23
+ if (sub === "/") return base;
24
+ const separator = base.endsWith("/") ? "" : "/";
25
+ return base + separator + (sub.startsWith("/") ? sub.slice(1) : sub);
50
26
  }
51
27
 
52
28
  export class HonoSemanticExtractor implements SemanticSliceExtractor {
@@ -55,492 +31,139 @@ export class HonoSemanticExtractor implements SemanticSliceExtractor {
55
31
 
56
32
  public canHandle(projectRoot: string, framework?: string): boolean {
57
33
  if (framework === "hono") return true;
58
-
59
- const pkgPath = path.join(projectRoot, "package.json");
60
- if (fs.existsSync(pkgPath)) {
61
- try {
62
- const pkg = JSON.parse(readOptionalSourceFile(pkgPath, "utf-8"));
63
- const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
64
- if (deps.hono) return true;
65
- } catch {}
66
- }
67
-
68
- // Check entrypoint source code
34
+ if (hasPackageJsonDependency(projectRoot, ["hono"])) return true;
69
35
  for (const entry of ["src/index.ts", "src/app.ts", "index.ts", "app.ts", "src/server.ts"]) {
70
- const full = path.join(projectRoot, entry);
71
- if (fs.existsSync(full)) {
72
- try {
73
- const content = readOptionalSourceFile(full, "utf-8");
74
- if (content.includes("from \"hono\"") || content.includes("from 'hono'") || content.includes("require(\"hono\")")) {
75
- return true;
76
- }
77
- } catch {}
36
+ const file = path.join(projectRoot, entry);
37
+ if (probeSourcePath(file) === "file" && /(?:from\s*|require\(\s*)['"]hono['"]/.test(readOptionalSourceFile(file))) {
38
+ return true;
78
39
  }
79
40
  }
80
-
81
41
  return false;
82
42
  }
83
43
 
84
44
  public async extractSlices(
85
45
  projectRoot: string,
86
46
  domainId?: number,
87
- signal?: AbortSignal, inventory?: SourceInventory
47
+ signal?: AbortSignal,
48
+ inventory?: SourceInventory,
88
49
  ): Promise<VerticalSliceCandidate[]> {
89
- const slices: VerticalSliceCandidate[] = [];
90
- const sourceFiles = listSourceFiles(projectRoot, /\.(?:[cm]?[jt]sx?)$/, inventory).filter(file => !file.endsWith('.d.ts'));
91
- const resolver = new ImportResolver(projectRoot);
92
-
93
- const allRoutes: ExtractedRoute[] = [];
94
- const allMounts: ExtractedMount[] = [];
95
- const fileImports = new Map<string, Map<string, string>>(); // relPath -> (ident -> targetRelPath)
96
-
97
- for (const file of sourceFiles) {
98
- if (signal?.aborted) throw new Error("semantic_extraction_cancelled");
99
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
100
- const content = readOptionalSourceFile(file, "utf-8");
101
- if (!content.trim()) continue;
102
-
103
- const fileData = await parseWithTreeSitter(
104
- "typescript",
105
- content,
106
- (rootNode) => this.extractFileAst(file, relPath, rootNode, resolver, projectRoot)
107
- );
108
-
109
- if (fileData) {
110
- allRoutes.push(...fileData.routes);
111
- allMounts.push(...fileData.mounts);
112
- if (fileData.resolvedImports.size > 0) {
113
- fileImports.set(relPath, fileData.resolvedImports);
50
+ const root = path.resolve(projectRoot);
51
+ const files = listSourceFiles(root, /\.[cm]?[jt]sx?$/, inventory).filter(file => !/\.d\.[cm]?ts$/.test(file));
52
+ const bindings = new TypeScriptBindings(root, new Set(files), signal);
53
+ const tables = new Map<ts.NewExpression, Route[]>();
54
+ const mounted = new Set<ts.NewExpression>();
55
+ const receivers = new Map<ts.Expression, Receiver | undefined>();
56
+ const fileOf = (node: ts.Node) => path.relative(root, node.getSourceFile().fileName).replace(/\\/g, "/");
57
+ const receiverOf = (expression: ts.Expression): Receiver | undefined => {
58
+ const node = bindings.value(expression);
59
+ if (!node) return undefined;
60
+ if (receivers.has(node)) return receivers.get(node);
61
+ receivers.set(node, undefined);
62
+ let receiver: Receiver | undefined;
63
+ if (ts.isNewExpression(node)) {
64
+ const type = bindings.packageBinding(node.expression);
65
+ if (type && /^(?:hono)(?:\/(?:quick|tiny))?$/.test(type.module) && type.name === "Hono") {
66
+ tables.set(node, []);
67
+ receiver = { root: node, base: "/" };
114
68
  }
69
+ } else if (ts.isCallExpression(node) && !node.questionDotToken && ts.isPropertyAccessExpression(node.expression) &&
70
+ !node.expression.questionDotToken) {
71
+ const method = node.expression.name.text;
72
+ const parent = receiverOf(node.expression.expression);
73
+ if (parent && method === "basePath") {
74
+ const sub = literal(node.arguments[0]);
75
+ receiver = { root: parent.root, base: sub === undefined || parent.base === undefined ? undefined : join(parent.base, sub) };
76
+ } else if (parent && instanceMethods.has(method)) receiver = parent;
115
77
  }
116
- }
117
-
118
- // Resolve Router Prefix Hierarchy
119
- const routerPrefixes = this.resolvePrefixHierarchy(allMounts, fileImports);
120
-
121
- // Build Vertical Slices (Level 0 – Level 5)
122
- for (const route of allRoutes) {
123
- const prefixes = routerPrefixes.get(`${route.relPath}#${route.routerVar}`) || [""];
124
-
125
- for (const prefix of prefixes) {
126
- for (const httpMethod of route.httpMethods) {
127
- const fullUri = normalizeRouteUri(prefix, route.rawPath);
128
- const actionSymbol = route.handler.symbol;
129
- const rootIdent = actionSymbol.includes(".") ? actionSymbol.split(".")[0] : actionSymbol;
130
- const imports = fileImports.get(route.relPath);
131
- const resolvedControllerFile = imports?.get(rootIdent) || route.relPath;
132
- const fileBase = path.basename(route.relPath).replace(/\.[^.]+$/, "");
133
- const controllerClass = actionSymbol.includes(".")
134
- ? actionSymbol.split(".")[0]
135
- : fileBase.charAt(0).toUpperCase() + fileBase.slice(1);
136
- const actionName = actionSymbol.includes(".") ? actionSymbol.split(".").pop()! : actionSymbol;
137
-
138
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
139
- {
140
- stage: "ingress",
141
- symbol: `${httpMethod} ${fullUri}`,
142
- file: route.relPath,
143
- line: route.routeLine,
144
- description: `Hono Route: ${httpMethod} ${fullUri}`,
145
- },
146
- ];
147
-
148
- // L2: Validation schema
149
- if (route.validationSchema) {
150
- chain.push({
151
- stage: "validation",
152
- symbol: route.validationSchema.symbol,
153
- file: route.validationSchema.file || route.relPath,
154
- line: route.validationSchema.line,
155
- description: `Hono Validator: ${route.validationSchema.symbol}`,
156
- });
157
- }
158
-
159
- // Middlewares
160
- for (const mw of route.middlewares) {
161
- chain.push({
162
- stage: "middleware",
163
- symbol: mw.symbol,
164
- file: route.relPath,
165
- line: mw.line,
166
- description: `Hono Middleware: ${mw.symbol}`,
167
- });
168
- }
169
-
170
- // L3: Controller Action
171
- chain.push({
172
- stage: "controller",
173
- symbol: actionSymbol,
174
- file: resolvedControllerFile,
175
- line: route.handler.line,
176
- description: `Hono Action Handler`,
177
- });
178
-
179
- // L4–L5: Tracing Service & Persistence from handler or imported controller
180
- const scanFile = resolvedControllerFile !== route.relPath ? resolvedControllerFile : route.relPath;
181
- const fullScanPath = path.resolve(projectRoot, scanFile);
182
- const scanContent = readOptionalSourceFile(fullScanPath, "utf-8");
183
-
184
- if (scanContent) {
185
- // Check service calls: orderService.create(...) or OrderService.process(...)
186
- const sMatch = scanContent.match(/\b([a-zA-Z0-9_]+(?:Service|Usecase))\s*\.\s*([A-Za-z0-9_]+)\s*\(/i);
187
- let serviceFile: string | undefined;
188
- if (sMatch) {
189
- const svcIdent = sMatch[1];
190
- const svcMethod = sMatch[2];
191
- const imports = fileImports.get(scanFile);
192
- let svcImport = imports?.get(svcIdent);
193
- if (!svcImport && imports) {
194
- const pascal = svcIdent.charAt(0).toUpperCase() + svcIdent.slice(1);
195
- svcImport = imports.get(pascal);
196
- if (!svcImport) {
197
- const instMatch = scanContent.match(new RegExp(`\\b(?:const|let|var)\\s+${svcIdent}\\s*=\\s*new\\s+([a-zA-Z0-9_]+)`));
198
- if (instMatch) {
199
- svcImport = imports.get(instMatch[1]);
200
- }
201
- }
202
- }
203
- serviceFile = svcImport;
204
-
205
- chain.push({
206
- stage: "service",
207
- symbol: `${svcIdent}::${svcMethod}`,
208
- ...(serviceFile ? { file: serviceFile } : {}),
209
- description: `Hono Service Call: ${svcIdent}::${svcMethod}`,
210
- });
211
- }
212
-
213
- // Check Prisma / Drizzle / TypeORM persistence in scanFile or serviceFile
214
- const filesToInspect = [fullScanPath];
215
- if (serviceFile) filesToInspect.push(path.resolve(projectRoot, serviceFile));
216
-
217
- for (const inspectPath of filesToInspect) {
218
- const contentToInspect = readOptionalSourceFile(inspectPath, "utf-8");
219
- if (!contentToInspect) continue;
220
-
221
- const prismaMatch = contentToInspect.match(/prisma\.([a-zA-Z0-9_]+)\.(?:find|create|update|delete|upsert)/);
222
- const drizzleMatch = contentToInspect.match(/db\.(?:insert|select|update|delete)\s*\(\s*([a-zA-Z0-9_]+)\s*\)/);
223
-
224
- const entityName =
225
- prismaMatch ? (prismaMatch[1].charAt(0).toUpperCase() + prismaMatch[1].slice(1)) :
226
- drizzleMatch ? (drizzleMatch[1].charAt(0).toUpperCase() + drizzleMatch[1].slice(1)) : undefined;
227
-
228
- if (entityName && !chain.some((n) => n.stage === "entity")) {
229
- const inspectRel = path.relative(projectRoot, inspectPath).replace(/\\/g, "/");
230
- const entImport = fileImports.get(inspectRel)?.get(entityName);
231
-
232
- chain.push({
233
- stage: "repository",
234
- symbol: `${entityName}Repository`,
235
- file: inspectRel,
236
- description: prismaMatch ? "Prisma ORM Client" : "Drizzle ORM Query",
237
- });
238
-
239
- chain.push({
240
- stage: "entity",
241
- symbol: entityName,
242
- ...(entImport ? { file: entImport } : { file: inspectRel }),
243
- description: "Database Entity / Schema Model",
244
- });
245
- }
246
- }
247
- }
248
-
249
- slices.push({
250
- domain_id: domainId ?? null,
251
- feature_key: `hono.${controllerClass.toLowerCase()}.${actionName}`,
252
- http_method: httpMethod,
253
- route_uri: fullUri,
254
- route_name: `${controllerClass}.${actionName}`,
255
- controller_class: controllerClass,
256
- action_name: actionName,
257
- controller_file: resolvedControllerFile,
258
- controller_line: route.handler.line,
259
- architecture_style: "mvc",
260
- entry_kind: "http_route",
261
- execution_chain_json: JSON.stringify(chain),
262
- });
263
- }
264
- }
265
- }
266
-
267
- return slices;
268
- }
269
-
270
- private extractFileAst(
271
- file: string,
272
- relPath: string,
273
- rootNode: Parser.SyntaxNode,
274
- resolver: ImportResolver,
275
- projectRoot: string
276
- ): {
277
- routes: ExtractedRoute[];
278
- mounts: ExtractedMount[];
279
- resolvedImports: Map<string, string>;
280
- } {
281
- const routes: ExtractedRoute[] = [];
282
- const mounts: ExtractedMount[] = [];
283
- const resolvedImports = new Map<string, string>();
284
-
285
- // 1. Collect import statements
286
- for (const child of rootNode.namedChildren) {
287
- if (child.type === "import_statement") {
288
- const sourceNode = child.childForFieldName("source");
289
- const specifier = cleanLiteral(sourceNode);
290
- if (!specifier) continue;
291
-
292
- const res = resolver.resolve(specifier, relPath);
293
- const targetFile = res.status === "resolved" && res.targets[0]?.files[0] ? res.targets[0].files[0] : undefined;
294
- if (!targetFile) continue;
78
+ receivers.set(node, receiver);
79
+ return receiver;
80
+ };
295
81
 
296
- const importClause = child.namedChildren.find((c) => c.type === "import_clause");
297
- if (importClause) {
298
- for (const ic of importClause.namedChildren) {
299
- if (ic.type === "identifier") {
300
- resolvedImports.set(ic.text.trim(), targetFile);
301
- } else if (ic.type === "namespace_import") {
302
- const identNode = ic.namedChildren.find((n) => n.type === "identifier");
303
- if (identNode) resolvedImports.set(identNode.text.trim(), targetFile);
304
- } else if (ic.type === "named_imports") {
305
- for (const spec of ic.namedChildren) {
306
- if (spec.type === "import_specifier") {
307
- const alias = spec.childForFieldName("alias");
308
- const name = spec.childForFieldName("name") ?? spec.namedChildren[0];
309
- const ident = alias ? alias.text.trim() : name ? name.text.trim() : "";
310
- if (ident) resolvedImports.set(ident, targetFile);
311
- }
312
- }
313
- }
314
- }
82
+ const honoRouteHint = /\.(?:route|on|basePath|get|post|put|patch|delete|head|options|trace|connect|all)\s*\(|\bnew\s+Hono\b/;
83
+ bindings.visitModules(files, unit => visitRouteCalls(unit.source, call => {
84
+ signal?.throwIfAborted();
85
+ const member = call.expression;
86
+ if (call.questionDotToken || !ts.isPropertyAccessExpression(member) || member.questionDotToken) return;
87
+ const method = member.name.text;
88
+ if (method !== "route" && method !== "on" && !verbs.has(method)) return;
89
+ const receiver = receiverOf(member.expression);
90
+ if (!receiver) return;
91
+ const routes = tables.get(receiver.root)!;
92
+
93
+ if (method === "route") {
94
+ const sub = call.arguments[1] && receiverOf(call.arguments[1]);
95
+ if (!sub || sub.root === receiver.root) return;
96
+ mounted.add(sub.root);
97
+ const mount = literal(call.arguments[0]);
98
+ if (mount === undefined || receiver.base === undefined) return;
99
+ const base = join(receiver.base, mount);
100
+ for (const route of tables.get(sub.root) ?? []) {
101
+ routes.push({ ...route, uri: join(base, route.uri) });
315
102
  }
103
+ return;
316
104
  }
317
- }
318
-
319
- // 2. Walk call expressions for routes and sub-route mounts
320
- const walkCalls = (node: Parser.SyntaxNode): void => {
321
- if (node.type === "call_expression") {
322
- const fnNode = node.childForFieldName("function");
323
- if (fnNode && fnNode.type === "member_expression") {
324
- const objNode = fnNode.childForFieldName("object");
325
- const propNode = fnNode.childForFieldName("property");
326
- const argsNode = node.childForFieldName("arguments");
327
-
328
- if (objNode && propNode && argsNode) {
329
- const callerVar = objNode.text.trim();
330
- const methodName = propNode.text.trim();
331
- const lowerMethod = methodName.toLowerCase();
332
- const args = argsNode.namedChildren;
333
-
334
- // Route Mount: app.route('/prefix', subRouter)
335
- if (lowerMethod === "route") {
336
- if (args.length >= 2) {
337
- const prefixLit = cleanLiteral(args[0]);
338
- const targetArg = args[1];
339
- if (prefixLit !== undefined && targetArg.type === "identifier") {
340
- mounts.push({
341
- file,
342
- relPath,
343
- callerVar,
344
- prefix: prefixLit,
345
- targetVar: targetArg.text.trim(),
346
- line: node.startPosition.row + 1,
347
- });
348
- }
349
- }
350
- } else if (HONO_VERBS.has(lowerMethod)) {
351
- // Direct route: app.get('/path', ...middlewares, handler)
352
- if (args.length >= 2) {
353
- const rawPath = cleanLiteral(args[0]);
354
- if (rawPath !== undefined) {
355
- const middleNodes = args.slice(1, args.length - 1);
356
- const handlerNode = args[args.length - 1];
357
-
358
- const { middlewares, validationSchema } = this.extractMiddlewaresAndValidation(
359
- middleNodes,
360
- resolvedImports,
361
- projectRoot
362
- );
363
- const handler = this.extractSingleHandler(handlerNode);
364
-
365
- routes.push({
366
- file,
367
- relPath,
368
- routerVar: callerVar,
369
- httpMethods: lowerMethod === "all" ? ["GET", "POST", "PUT", "DELETE"] : [lowerMethod.toUpperCase()],
370
- rawPath,
371
- middlewares,
372
- validationSchema,
373
- handler,
374
- routeLine: node.startPosition.row + 1,
375
- });
376
- }
377
- }
378
- } else if (lowerMethod === "on") {
379
- // Multi-method route: app.on(['GET', 'POST'], '/path', handler)
380
- if (args.length >= 3) {
381
- const methodsNode = args[0];
382
- const rawPath = cleanLiteral(args[1]);
383
- if (rawPath !== undefined) {
384
- const httpMethods: string[] = [];
385
- if (methodsNode.type === "array") {
386
- for (const el of methodsNode.namedChildren) {
387
- const lit = cleanLiteral(el);
388
- if (lit) httpMethods.push(lit.toUpperCase());
389
- }
390
- } else {
391
- const lit = cleanLiteral(methodsNode);
392
- if (lit) httpMethods.push(lit.toUpperCase());
393
- }
394
-
395
- const middleNodes = args.slice(2, args.length - 1);
396
- const handlerNode = args[args.length - 1];
397
- const { middlewares, validationSchema } = this.extractMiddlewaresAndValidation(
398
- middleNodes,
399
- resolvedImports,
400
- projectRoot
401
- );
402
- const handler = this.extractSingleHandler(handlerNode);
403
-
404
- routes.push({
405
- file,
406
- relPath,
407
- routerVar: callerVar,
408
- httpMethods: httpMethods.length > 0 ? httpMethods : ["GET"],
409
- rawPath,
410
- middlewares,
411
- validationSchema,
412
- handler,
413
- routeLine: node.startPosition.row + 1,
414
- });
415
- }
416
- }
417
- }
418
- }
105
+ if (receiver.base === undefined) return;
106
+ const methods = method === "on" ? literals(call.arguments[0]).map(value => value.toUpperCase().replace(/^ALL$/, "ANY")) :
107
+ [method === "all" ? "ANY" : method.toUpperCase()];
108
+ const paths = method === "on" ? literals(call.arguments[1]) : [literal(call.arguments[0])];
109
+ const handlers = call.arguments.slice(method === "on" ? 2 : 1);
110
+ if (!handlers.length) return;
111
+ for (const m of new Set(methods)) {
112
+ if (!/^[A-Z][A-Z0-9-]*$/.test(m)) continue;
113
+ for (const localPath of new Set(paths)) {
114
+ if (localPath !== undefined) routes.push({ method: m, uri: join(receiver.base, localPath), registration: call, handlers });
419
115
  }
420
116
  }
117
+ }), honoRouteHint);
421
118
 
422
- for (const child of node.namedChildren) {
423
- walkCalls(child);
424
- }
425
- };
426
-
427
- walkCalls(rootNode);
428
- return { routes, mounts, resolvedImports };
429
- }
430
-
431
- private extractMiddlewaresAndValidation(
432
- nodes: Parser.SyntaxNode[],
433
- resolvedImports: Map<string, string>,
434
- projectRoot: string
435
- ): {
436
- middlewares: Array<{ symbol: string; line: number }>;
437
- validationSchema?: { symbol: string; file?: string; line?: number };
438
- } {
439
- const middlewares: Array<{ symbol: string; line: number }> = [];
440
- let validationSchema: { symbol: string; file?: string; line?: number } | undefined;
441
-
442
- for (const node of nodes) {
443
- if (node.type === "call_expression") {
444
- const fnNode = node.childForFieldName("function");
445
- const fnName = fnNode ? fnNode.text.trim() : "";
446
-
447
- // Detect validator middleware: zValidator('json', createOrderSchema)
448
- if (fnName === "zValidator" || fnName === "validator" || fnName === "vValidator") {
449
- const args = node.childForFieldName("arguments")?.namedChildren ?? [];
450
- if (args.length >= 2) {
451
- const schemaArg = args[1];
452
- const schemaSymbol = schemaArg.text.trim();
453
- const schemaFile = resolvedImports.get(schemaSymbol);
454
- validationSchema = {
455
- symbol: schemaSymbol,
456
- file: schemaFile,
457
- line: node.startPosition.row + 1,
458
- };
459
- continue;
119
+ const slices: VerticalSliceCandidate[] = [];
120
+ for (const [instance, routes] of tables) {
121
+ if (mounted.has(instance)) continue;
122
+ for (const route of routes) {
123
+ signal?.throwIfAborted();
124
+ const routeFile = fileOf(route.registration);
125
+ const routeLine = lineOf(route.registration);
126
+ const target = route.handlers.at(-1)!;
127
+ const handler = bindings.handler(target);
128
+ const action = handler ? (handler.name === "callback" ? "closure" : handler.name) : target.getText();
129
+ const controllerFile = handler ? fileOf(handler.node) : null;
130
+ const controllerLine = handler ? lineOf(handler.node) : 0;
131
+ const controller = path.basename(controllerFile ?? routeFile).replace(/\.[^.]+$/, "");
132
+ const chain: ExecutionChainNode[] = [{
133
+ stage: "ingress", symbol: route.method + " " + route.uri, file: routeFile, line: routeLine,
134
+ description: "Hono Route Registration",
135
+ }];
136
+ for (const mw of route.handlers.slice(0, -1)) {
137
+ const validator = ts.isCallExpression(mw) ? bindings.packageBinding(mw.expression) : undefined;
138
+ if (validator && ["@hono/zod-validator", "@hono/valibot-validator", "hono/validator"].includes(validator.module) &&
139
+ ts.isCallExpression(mw) && mw.arguments[1]) {
140
+ const schema = mw.arguments[1];
141
+ const declaration = bindings.definition(schema) ?? schema;
142
+ chain.push({
143
+ stage: "validation", symbol: schema.getText(), file: fileOf(declaration), line: lineOf(declaration),
144
+ description: "Hono Validator Argument",
145
+ });
460
146
  }
147
+ chain.push({
148
+ stage: "middleware", symbol: mw.getText(), file: fileOf(mw), line: lineOf(mw),
149
+ description: "Hono Middleware Argument",
150
+ });
461
151
  }
462
- }
463
-
464
- const line = node.startPosition.row + 1;
465
- if (node.type === "identifier" || node.type === "member_expression") {
466
- middlewares.push({ symbol: node.text.trim(), line });
467
- }
468
- }
469
-
470
- return { middlewares, validationSchema };
471
- }
472
-
473
- private extractSingleHandler(node: Parser.SyntaxNode): { symbol: string; line: number; node: Parser.SyntaxNode } {
474
- const line = node.startPosition.row + 1;
475
- if (node.type === "identifier" || node.type === "member_expression") {
476
- return { symbol: node.text.trim(), line, node };
477
- }
478
- if (node.type === "arrow_function" || node.type === "function_expression" || node.type === "function") {
479
- const nameNode = node.childForFieldName("name");
480
- const name = nameNode ? nameNode.text.trim() : "closure";
481
- return { symbol: name, line, node };
482
- }
483
- return { symbol: "closure", line, node };
484
- }
485
-
486
- private resolvePrefixHierarchy(
487
- allMounts: ExtractedMount[],
488
- fileImports: Map<string, Map<string, string>>
489
- ): Map<string, string[]> {
490
- const parentMap = new Map<string, Array<{ parentKey: string; prefix: string }>>();
491
- const allRouterKeys = new Set<string>();
492
-
493
- for (const m of allMounts) {
494
- const parentKey = `${m.relPath}#${m.callerVar}`;
495
- allRouterKeys.add(parentKey);
496
-
497
- let targetKey: string | undefined;
498
- const importedFile = fileImports.get(m.relPath)?.get(m.targetVar);
499
- if (importedFile) {
500
- targetKey = `${importedFile}#${m.targetVar}`;
501
- } else {
502
- targetKey = `${m.relPath}#${m.targetVar}`;
503
- }
504
-
505
- allRouterKeys.add(targetKey);
506
- if (!parentMap.has(targetKey)) parentMap.set(targetKey, []);
507
- parentMap.get(targetKey)!.push({ parentKey, prefix: m.prefix });
508
- }
509
-
510
- const prefixesByRouter = new Map<string, string[]>();
511
-
512
- for (const rKey of allRouterKeys) {
513
- const parents = parentMap.get(rKey);
514
- if (!parents || parents.length === 0) {
515
- prefixesByRouter.set(rKey, [""]);
516
- }
517
- }
518
-
519
- const queue = Array.from(prefixesByRouter.keys());
520
- const visitedEdges = new Set<string>();
521
-
522
- while (queue.length > 0) {
523
- const current = queue.shift()!;
524
- const currentPrefixes = prefixesByRouter.get(current) ?? [""];
525
-
526
- for (const [targetKey, parents] of parentMap.entries()) {
527
- for (const p of parents) {
528
- if (p.parentKey === current) {
529
- const edgeKey = `${current}->${targetKey}:${p.prefix}`;
530
- if (visitedEdges.has(edgeKey)) continue;
531
- visitedEdges.add(edgeKey);
532
-
533
- const nextPrefixes = currentPrefixes.map((cp) => normalizeRouteUri(cp, p.prefix));
534
- const existing = prefixesByRouter.get(targetKey) ?? [];
535
- const merged = Array.from(new Set([...existing, ...nextPrefixes]));
536
- prefixesByRouter.set(targetKey, merged);
537
- queue.push(targetKey);
538
- }
152
+ if (handler && controllerFile) {
153
+ chain.push({
154
+ stage: "controller", symbol: action, file: controllerFile, line: controllerLine,
155
+ description: "Hono Action Handler",
156
+ }, ...routeContext(handler, bindings, fileOf));
539
157
  }
158
+ slices.push({
159
+ domain_id: domainId ?? null, feature_key: `hono.${controller.toLowerCase()}.${action}`,
160
+ http_method: route.method, route_uri: route.uri, route_name: `${controller}.${action}`,
161
+ controller_class: controller, action_name: action, controller_file: controllerFile,
162
+ controller_line: controllerLine, architecture_style: "mvc", entry_kind: "http_route",
163
+ execution_chain_json: JSON.stringify(chain),
164
+ });
540
165
  }
541
166
  }
542
-
543
- return prefixesByRouter;
167
+ return slices;
544
168
  }
545
169
  }
546
-