@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,52 +1,28 @@
1
- import type Parser from "web-tree-sitter";
2
- import { parseWithTreeSitter } from "../wasm-loader.ts";
3
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
- import { isIgnoredDirectory } from "../../resources/ignore.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,513 +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
47
+ signal?: AbortSignal,
48
+ inventory?: SourceInventory,
88
49
  ): Promise<VerticalSliceCandidate[]> {
89
- const slices: VerticalSliceCandidate[] = [];
90
- const sourceFiles = this.findSourceFiles(projectRoot);
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);
114
- }
115
- }
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
- });
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: "/" };
263
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;
264
77
  }
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;
544
- }
545
-
546
- private findSourceFiles(dir: string): string[] {
547
- const results: string[] = [];
548
- const traverse = (current: string) => {
549
- if (!fs.existsSync(current)) return;
550
- try {
551
- const entries = fs.readdirSync(current, { withFileTypes: true });
552
- for (const entry of entries) {
553
- if (isIgnoredDirectory(entry.name)) continue;
554
- const full = path.join(current, entry.name);
555
- if (entry.isDirectory()) {
556
- traverse(full);
557
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
558
- results.push(full);
559
- }
560
- }
561
- } catch {}
562
- };
563
- traverse(dir);
564
- return results;
167
+ return slices;
565
168
  }
566
169
  }
567
-