@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,12 +1,29 @@
1
1
  import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
2
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
3
+ import type Parser from "web-tree-sitter";
4
+ import { parseWithTreeSitter } from "../wasm-loader.ts";
5
+ import { blankCommentsAndStrings } from "../boundary-tracker.ts";
6
+ import { goImports, goKey, goRouteUris, GoRouting, type GoRoute, type GoType } from "./go-routing.ts";
7
+ import type { ExecutionChainNode } from "../../../types/index.ts";
3
8
  import * as fs from "node:fs";
4
9
  import * as path from "node:path";
10
+ import { warnIfUnexpectedParserError } from "./manifest-helpers.ts";
5
11
  import type { SemanticSliceExtractor, VerticalSliceCandidate } from "./semantic-extractor.interface.ts";
6
12
 
13
+ type GoDeclaration = {
14
+ owner: string;
15
+ relPath: string;
16
+ line: number;
17
+ receiver?: string;
18
+ receiverVar?: string;
19
+ body: string;
20
+ params: string;
21
+ };
22
+ type GoStruct = { relPath: string; line: number; fields: Map<string, GoType> };
23
+
7
24
  export class GoSemanticExtractor implements SemanticSliceExtractor {
8
25
  public readonly id = "golang";
9
- public readonly name = "Go HTTP Semantic Slice Extractor (Gin, Echo, Chi)";
26
+ public readonly name = "Go HTTP Semantic Slice Extractor (net/http, Gin, Echo, Chi, Fiber)";
10
27
 
11
28
  public canHandle(projectRoot: string, framework?: string): boolean {
12
29
  if (
@@ -40,595 +57,227 @@ export class GoSemanticExtractor implements SemanticSliceExtractor {
40
57
  ) {
41
58
  return true;
42
59
  }
43
- } catch {}
60
+ } catch (err: unknown) {
61
+ warnIfUnexpectedParserError(`Failed to inspect Go file ${file}`, err);
62
+ }
44
63
  }
45
64
 
46
65
  return false;
47
66
  }
48
67
 
49
- public extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): VerticalSliceCandidate[] {
68
+ public async extractSlices(
69
+ projectRoot: string,
70
+ domainId?: number,
71
+ signal?: AbortSignal,
72
+ inventory?: SourceInventory,
73
+ ): Promise<VerticalSliceCandidate[]> {
50
74
  const slices: VerticalSliceCandidate[] = [];
51
- const goFiles = listSourceFiles(projectRoot, /\.go$/, inventory).filter(file => !file.endsWith('_test.go'));
52
-
53
- interface HandlerInfo {
54
- name: string;
55
- receiver?: string;
56
- file: string;
57
- relPath: string;
58
- line: number;
59
- boundDto?: string;
60
- serviceCall?: string;
61
- repoCall?: string;
62
- receiverVar?: string;
63
- body: string;
64
- }
65
-
66
- interface GoStructInfo {
67
- name: string;
68
- file: string;
69
- relPath: string;
70
- line: number;
71
- fields: Map<string, string>;
72
- }
73
-
74
- interface GoMethodInfo {
75
- receiver?: string;
76
- name: string;
77
- file: string;
78
- relPath: string;
79
- line: number;
80
- body: string;
81
- params?: string;
82
- receiverVar?: string;
83
- }
84
-
85
- // 1. Catalog all handler functions & methods across .go files
86
- const handlers = new Map<string, HandlerInfo>();
87
- const goStructs = new Map<string, GoStructInfo>();
88
- const goMethods = new Map<string, GoMethodInfo>();
89
- const constructors = new Map<string, string>();
90
- const rootGoMod = path.join(projectRoot, "go.mod");
91
- const discoveredGoMods = fs.existsSync(rootGoMod) ? [rootGoMod] : listSourceFiles(projectRoot, /(?:^|[\\/])go\.mod$/, inventory);
92
- const goModPath = discoveredGoMods[0];
93
- const moduleRoot = goModPath ? path.dirname(goModPath) : projectRoot;
94
- const moduleName = goModPath && fs.existsSync(goModPath)
95
- ? readOptionalSourceFile(goModPath, "utf-8").match(/^module\s+(\S+)/m)?.[1]
96
- : undefined;
97
-
98
- for (const file of goFiles) {
99
- const content = readOptionalSourceFile(file, "utf-8");
100
- if (!content) continue;
101
-
102
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
103
-
104
- // Match Go functions and methods:
105
- // func (h *OrderHandler) CreateOrder(c *gin.Context)
106
- // func (h OrderHandler) CreateOrder(c echo.Context) error
107
- // func CreateOrder(w http.ResponseWriter, r *http.Request)
108
- const funcRegex =
109
- /func\s*(?:\(\s*[a-zA-Z0-9_]+\s+\*?(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]+)\s*\)\s*)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)(?:[^{]*)\{/g;
110
- let fMatch: RegExpExecArray | null;
111
-
112
- while ((fMatch = funcRegex.exec(content)) !== null) {
113
- const receiver = fMatch[1];
114
- const fnName = fMatch[2];
115
- const params = fMatch[3];
116
-
117
- // Only catalog HTTP handlers (takes *gin.Context, echo.Context, http.ResponseWriter, *fiber.Ctx)
118
- const isHttpHandler =
119
- params.includes("gin.Context") ||
120
- params.includes("echo.Context") ||
121
- params.includes("http.ResponseWriter") ||
122
- params.includes("fiber.Ctx") ||
123
- params.includes("*http.Request");
124
-
125
- if (!isHttpHandler) continue;
126
-
127
- const fnLine = content.slice(0, fMatch.index).split("\n").length;
128
- const bodyStart = fMatch.index + fMatch[0].length;
129
- const bodyEnd = this.findGoBraceBlockEnd(content, bodyStart - 1);
130
- const fnBody = content.slice(bodyStart, bodyEnd);
131
-
132
- // Detect DTO binding: ShouldBindJSON(&req), c.Bind(&req), Decode(&req), c.BodyParser(&req)
133
- let boundDto: string | undefined;
134
- const bindMatch = fnBody.match(/(?:ShouldBind(?:JSON|Query|URI|XML|YAML|Header)?|Bind(?:JSON)?|Decode|(?:Body|Params|Query)Parser)\s*\(\s*&([a-zA-Z0-9_]+)\s*\)/);
135
- if (bindMatch) {
136
- const varName = bindMatch[1];
137
- // Look for explicit type declaration:
138
- // var req CreateOrderRequest
139
- // var req models.CreateOrderRequest
140
- // req := CreateOrderRequest{}
141
- // req := &CreateOrderRequest{}
142
- // req := new(CreateOrderRequest)
143
- const typeRegex = new RegExp(
144
- `(?:var\\s+${varName}\\s+(?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)|` +
145
- `${varName}\\s*:=\\s*&?(?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)\\s*\\{|` +
146
- `${varName}\\s*:=\\s*new\\s*\\((?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)\\))`
147
- );
148
- const typeMatch = fnBody.match(typeRegex);
149
- if (typeMatch) {
150
- boundDto = typeMatch[1] || typeMatch[2] || typeMatch[3];
151
- }
152
- // Note: If no type matched, do NOT synthesize a fake name (strict evidence invariant)
153
- }
154
-
155
- // Detect service calls: h.orderService.Process(...) or s.service.Create(...)
156
- let serviceCall: string | undefined;
157
- const sMatch = fnBody.match(/([a-zA-Z0-9_]+(?:Service|Usecase|UC))\s*\.\s*([A-Z][a-zA-Z0-9_]+)/i);
158
- if (sMatch) {
159
- serviceCall = `${sMatch[1]}::${sMatch[2]}`;
160
- }
161
-
162
- // Detect repo/db calls: h.repo.Save(...) or db.Create(&order)
163
- let repoCall: string | undefined;
164
- const rMatch = fnBody.match(/(?:([a-zA-Z0-9_]+(?:Repo|Repository))\s*\.\s*([A-Z][a-zA-Z0-9_]+)\s*\(|db\s*\.\s*(?:Create|Save|Find|First|Update|Delete)\s*\(\s*&?([A-Z][a-zA-Z0-9_]+)\s*\))/i);
165
- if (rMatch) {
166
- repoCall = rMatch[1] ? `${rMatch[1]}::${rMatch[2]}` : `DB::${rMatch[3]}`;
167
- }
168
-
169
- const info: HandlerInfo = {
170
- name: fnName,
171
- receiver,
172
- file,
173
- relPath,
174
- line: fnLine,
175
- boundDto,
176
- serviceCall,
177
- repoCall,
178
- receiverVar: fMatch[0].match(/^func\s*\(\s*(\w+)/)?.[1],
179
- body: fnBody,
180
- };
181
-
182
- if (receiver) {
183
- handlers.set(`${receiver}.${fnName}`, info);
184
- } else {
185
- handlers.set(fnName, info);
186
- }
187
- }
188
-
189
- // Catalog struct definitions
190
- const structRegex = /type\s+([A-Z][a-zA-Z0-9_]+)\s+(?:struct|interface)\s*\{/g;
191
- let sDeclMatch: RegExpExecArray | null;
192
- while ((sDeclMatch = structRegex.exec(content)) !== null) {
193
- const sName = sDeclMatch[1];
194
- const sLine = content.slice(0, sDeclMatch.index).split("\n").length;
195
- const sBodyStart = sDeclMatch.index + sDeclMatch[0].length;
196
- const sBodyEnd = this.findGoBraceBlockEnd(content, sBodyStart - 1);
197
- const sBody = content.slice(sBodyStart, sBodyEnd);
198
-
199
- const fields = new Map<string, string>();
200
- const fieldRegex = /^\s*([a-zA-Z0-9_]+)\s+\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)/gm;
201
- let fldMatch: RegExpExecArray | null;
202
- while ((fldMatch = fieldRegex.exec(sBody)) !== null) {
203
- fields.set(fldMatch[1], fldMatch[2]);
204
- }
205
-
206
- goStructs.set(sName, { name: sName, file, relPath, line: sLine, fields });
207
- }
208
-
209
- // Catalog all methods & functions for call resolution
210
- const allFuncRegex =
211
- /func\s*(?:\(\s*[a-zA-Z0-9_]+\s+\*?(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]+)\s*\)\s*)?([A-Z][a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)(?:[^{]*)\{/g;
212
- let afMatch: RegExpExecArray | null;
213
- while ((afMatch = allFuncRegex.exec(content)) !== null) {
214
- const rcv = afMatch[1];
215
- const fn = afMatch[2];
216
- const fLine = content.slice(0, afMatch.index).split("\n").length;
217
- const bStart = afMatch.index + afMatch[0].length;
218
- const bEnd = this.findGoBraceBlockEnd(content, bStart - 1);
219
- const bText = content.slice(bStart, bEnd);
220
- const params = afMatch[3];
221
- const returnType = afMatch[0].match(/\)\s+\*?([A-Z][a-zA-Z0-9_]*)\s*\{$/)?.[1];
222
- if (!rcv && returnType) {
223
- constructors.set(`${path.dirname(file)}:${fn}`, returnType);
224
- }
225
- if (rcv) {
226
- goMethods.set(`${rcv}.${fn}`, { receiver: rcv, name: fn, file, relPath, line: fLine, body: bText, params,
227
- receiverVar: afMatch[0].match(/^func\s*\(\s*(\w+)/)?.[1] });
228
- } else {
229
- goMethods.set(fn, { name: fn, file, relPath, line: fLine, body: bText, params });
230
- }
231
- }
232
- }
233
-
234
- // Resolve calls through declared fields, regardless of the field's local name.
235
- for (const handler of handlers.values()) {
236
- if (!handler.receiver || !handler.receiverVar) continue;
237
- const fields = goStructs.get(handler.receiver)?.fields;
238
- const calls = /\b([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\s*\.\s*([A-Z][a-zA-Z0-9_]*)\s*\(/g;
239
- for (const call of handler.body.matchAll(calls)) {
240
- const fieldType = fields?.get(call[2]);
241
- if (call[1] === handler.receiverVar && fieldType && /(?:Service|Usecase|UC)$/i.test(fieldType)) {
242
- handler.serviceCall = `${call[2]}::${call[3]}`;
243
- break;
244
- }
245
- }
246
- }
247
-
248
- // Collect Chi r.Route("/prefix", func(sub chi.Router) { helper(sub, ...) }) delegations across package files
249
- const delegatedRoutePrefixes = new Map<string, string>();
250
- for (const file of goFiles) {
251
- const content = readOptionalSourceFile(file, "utf-8");
252
- if (!content) continue;
253
- const chiBlockRegex = /([a-zA-Z0-9_]+)\.Route\s*\(\s*["']([^"']*)["']\s*,\s*func\s*\(\s*([a-zA-Z0-9_]+)\s+chi\.Router\s*\)\s*\{/g;
254
- let cbMatch: RegExpExecArray | null;
255
- while ((cbMatch = chiBlockRegex.exec(content)) !== null) {
256
- const prefixRaw = cbMatch[2].replace(/\/+$/, "");
257
- const prefix = prefixRaw ? (prefixRaw.startsWith("/") ? prefixRaw : `/${prefixRaw}`) : "";
258
- const subRouter = cbMatch[3];
259
- const blockStart = cbMatch.index + cbMatch[0].length;
260
- const blockEnd = this.findGoBraceBlockEnd(content, blockStart - 1);
261
- const blockBody = content.slice(blockStart, blockEnd);
262
- const callRegex = new RegExp(`\\b([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(\\s*${subRouter}\\b`, "g");
263
- for (const call of blockBody.matchAll(callRegex)) {
264
- delegatedRoutePrefixes.set(`${path.dirname(file)}:${call[1]}`, prefix);
265
- }
75
+ const files = listSourceFiles(projectRoot, /\.go$/, inventory).filter(file => !file.endsWith("_test.go"));
76
+ const visitedDirectories = new Set<string>();
77
+ const manifestFiles = new Set<string>();
78
+ for (const file of files) {
79
+ for (let directory = path.dirname(file); !visitedDirectories.has(directory); directory = path.dirname(directory)) {
80
+ visitedDirectories.add(directory);
81
+ const manifest = path.join(directory, "go.mod");
82
+ if (probeSourcePath(manifest) === "file") manifestFiles.add(manifest);
83
+ if (directory === path.resolve(projectRoot)) break;
266
84
  }
267
85
  }
268
-
269
- // 2. Extract route registrations per file with lexical block scoping
270
- for (const file of goFiles) {
271
- const content = readOptionalSourceFile(file, "utf-8");
272
- if (!content) continue;
273
-
274
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
275
- const importedPackages = new Map<string, string>();
276
- for (const spec of content.matchAll(/^\s*(?:import\s+)?(?:(\w+)\s+)?"([^"\n]+)"/gm)) {
277
- if (moduleName && spec[2].startsWith(`${moduleName}/`)) {
278
- importedPackages.set(spec[1] || path.basename(spec[2]), path.join(moduleRoot, spec[2].slice(moduleName.length + 1)));
279
- }
86
+ const modules = [...manifestFiles]
87
+ .flatMap(file => {
88
+ const module = readOptionalSourceFile(file, "utf-8").match(/^module\s+(\S+)/m)?.[1];
89
+ return module ? [{ module, directory: path.dirname(file) }] : [];
90
+ })
91
+ .sort((a, b) => b.module.length - a.module.length);
92
+ const routing = new GoRouting(target => {
93
+ const match = modules.find(({ module }) => target === module || target.startsWith(module + "/"));
94
+ return match && path.join(match.directory, target.slice(match.module.length));
95
+ });
96
+ const handlers = new Map<string, GoDeclaration>();
97
+ const structs = new Map<string, GoStruct>();
98
+ const fileContents = new Map<string, string>();
99
+ const readCached = (file: string): string | undefined => {
100
+ if (!fileContents.has(file)) {
101
+ fileContents.set(file, readOptionalSourceFile(file, "utf-8") ?? "");
280
102
  }
281
-
282
- // Find router/setup functions and methods to scope groups and variable types
283
- const setupFuncRegex =
284
- /func\s*(?:\(\s*([a-zA-Z0-9_]+)\s+\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)\s*\)\s*)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)(?:[^{]*)\{/g;
285
- let funcMatch: RegExpExecArray | null;
286
-
287
- while ((funcMatch = setupFuncRegex.exec(content)) !== null) {
288
- const receiverVar = funcMatch[1];
289
- const receiverType = funcMatch[2];
290
- const funcName = funcMatch[3];
291
- const funcParams = funcMatch[4];
292
- const funcStart = funcMatch.index;
293
- const bodyStart = funcStart + funcMatch[0].length;
294
- const bodyEnd = this.findGoBraceBlockEnd(content, bodyStart - 1);
295
- const funcBody = content.slice(bodyStart, bodyEnd);
296
- const funcOffset = content.slice(0, bodyStart).split("\n").length - 1;
297
-
298
- // Scoped variable -> receiver type mapping (e.g. h -> OrderHandler, s -> Server)
299
- const scopedVarReceivers = new Map<string, string>();
300
- if (receiverVar && receiverType) {
301
- scopedVarReceivers.set(receiverVar, receiverType);
302
- }
303
-
304
- // Map parameter variables: (h *http.OrderHandler, u *UserHandler)
305
- const paramRegex = /([a-zA-Z0-9_]+)\s+\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)/g;
306
- let pMatch: RegExpExecArray | null;
307
- while ((pMatch = paramRegex.exec(funcParams)) !== null) {
308
- scopedVarReceivers.set(pMatch[1], pMatch[2]);
309
- }
310
-
311
- // Map local variable instantiations: h := &OrderHandler{} or var h OrderHandler
312
- const localInstRegex = /(?:([a-zA-Z0-9_]+)\s*:=\s*(?:&|new\s*\()?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)|var\s+([a-zA-Z0-9_]+)\s+(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+))/g;
313
- let lMatch: RegExpExecArray | null;
314
- while ((lMatch = localInstRegex.exec(funcBody)) !== null) {
315
- const varName = lMatch[1] || lMatch[3];
316
- const typeName = lMatch[2] || lMatch[4];
317
- if (varName && typeName) {
318
- scopedVarReceivers.set(varName, typeName);
103
+ const content = fileContents.get(file);
104
+ return content || undefined;
105
+ };
106
+ const parse = async <T>(file: string, visitor: (root: Parser.SyntaxNode) => T): Promise<T | undefined> => {
107
+ signal?.throwIfAborted();
108
+ const content = readCached(file);
109
+ if (!content) return undefined;
110
+ let reason: string | undefined;
111
+ const result = await parseWithTreeSitter("go", content, visitor, diagnostic => { reason = diagnostic.message; });
112
+ signal?.throwIfAborted();
113
+ if (result === null) throw new Error(`Could not extract Go AST from '${path.relative(projectRoot, file)}': ${reason}`);
114
+ return result;
115
+ };
116
+ const relative = (file: string) => path.relative(projectRoot, file).replace(/\\/g, "/");
117
+
118
+ for (const file of files) {
119
+ const content = readCached(file);
120
+ if (!content || !/\b(?:type|func)\b/.test(content)) continue;
121
+ const owner = path.dirname(file);
122
+ const relPath = relative(file);
123
+ await parse(file, root => {
124
+ const imports = goImports(root);
125
+ for (const node of root.namedChildren) {
126
+ if (node.hasError) continue;
127
+ if (node.type === "type_declaration") {
128
+ for (const spec of node.namedChildren) {
129
+ const name = spec.childForFieldName("name")?.text;
130
+ const type = spec.childForFieldName("type");
131
+ if (!name || !type || !["struct_type", "interface_type"].includes(type.type)) continue;
132
+ const key = goKey(owner, name);
133
+ const fields = new Map<string, GoType>();
134
+ for (const field of type.descendantsOfType("field_declaration")) {
135
+ const fieldType = routing.readType(field.childForFieldName("type"), imports, owner);
136
+ if (!fieldType) continue;
137
+ for (const id of field.childrenForFieldName("name")) fields.set(id.text, fieldType);
138
+ }
139
+ structs.set(key, { relPath, line: spec.startPosition.row + 1, fields });
140
+ routing.fields.set(key, fields);
141
+ }
319
142
  }
320
- }
321
-
322
- // A factory call is typed by its declared return, never by the function name.
323
- for (const call of funcBody.matchAll(/\b(\w+)\s*:=\s*(?:(\w+)\.)?([A-Z]\w*)\s*\(/g)) {
324
- const directory = call[2] ? importedPackages.get(call[2]) : path.dirname(file);
325
- const typeName = directory && constructors.get(`${directory}:${call[3]}`);
326
- scopedVarReceivers.delete(call[1]);
327
- if (typeName) scopedVarReceivers.set(call[1], typeName);
328
- }
329
-
330
- // Scoped router groups: groupVar -> accumulatedPrefix
331
- const scopedGroupPrefixes = new Map<string, string>();
332
- const delegatedPrefix = delegatedRoutePrefixes.get(`${path.dirname(file)}:${funcName}`);
333
- if (delegatedPrefix) {
334
- const chiParamMatch = funcParams.match(/\b([a-zA-Z0-9_]+)\s+chi\.Router\b/);
335
- if (chiParamMatch) {
336
- scopedGroupPrefixes.set(chiParamMatch[1], delegatedPrefix);
143
+ if (!["function_declaration", "method_declaration"].includes(node.type)) continue;
144
+ const name = node.childForFieldName("name")?.text;
145
+ const receiver = node.childForFieldName("receiver")?.namedChild(0);
146
+ const type = routing.readType(receiver?.childForFieldName("type") ?? null, imports, owner);
147
+ const body = node.childForFieldName("body");
148
+ if (!name || !body || (receiver && !type)) continue;
149
+ const key = goKey(owner, type ? `${type.name}.${name}` : name);
150
+ const duplicate = routing.functions.has(key);
151
+ routing.registerFunction(key, node, imports, owner);
152
+ if (duplicate) {
153
+ handlers.delete(key);
154
+ continue;
337
155
  }
156
+ handlers.set(key, {
157
+ owner, relPath, line: node.startPosition.row + 1, receiver: type?.name,
158
+ receiverVar: receiver?.childForFieldName("name")?.text,
159
+ params: node.childForFieldName("parameters")?.text ?? "",
160
+ body: blankCommentsAndStrings(body.text),
161
+ });
338
162
  }
163
+ return true;
164
+ });
165
+ }
339
166
 
340
- // Gin / Echo groups: v1 := r.Group("/api/v1")
341
- const groupRegex = /([a-zA-Z0-9_]+)\s*:=\s*([a-zA-Z0-9_]+)\.Group\s*\(\s*["']([^"']*)["']/g;
342
- let gMatch: RegExpExecArray | null;
343
- while ((gMatch = groupRegex.exec(funcBody)) !== null) {
344
- const newGroup = gMatch[1];
345
- const parentGroup = gMatch[2];
346
- const subPrefix = gMatch[3].replace(/\/+$/, "");
347
-
348
- const parentPrefix = scopedGroupPrefixes.get(parentGroup) || "";
349
- const cleanSub = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
350
- scopedGroupPrefixes.set(newGroup, `${parentPrefix}${cleanSub}`);
351
- }
352
-
353
- // Chi subrouter Route: r.Route("/articles", func(r chi.Router) { ... })
354
- const chiRouteRegex = /([a-zA-Z0-9_]+)\.Route\s*\(\s*["']([^"']*)["']\s*,\s*func\s*\(\s*([a-zA-Z0-9_]+)\s+chi\.Router\s*\)/g;
355
- let cMatch: RegExpExecArray | null;
356
- while ((cMatch = chiRouteRegex.exec(funcBody)) !== null) {
357
- const parentRouter = cMatch[1];
358
- const subPrefix = cMatch[2].replace(/\/+$/, "");
359
- const subRouter = cMatch[3];
360
-
361
- const parentPrefix = scopedGroupPrefixes.get(parentRouter) || "";
362
- const cleanSub = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
363
- scopedGroupPrefixes.set(subRouter, `${parentPrefix}${cleanSub}`);
364
- }
365
-
366
- // 3. Extract route registrations within this function scope
367
- // Method 1: Gin / Echo / Chi HTTP method calls: r.GET("/ping", pingHandler), v1.POST("/orders", h.CreateOrder), r.With(mw).Get("/x", h.Get)
368
- const routeRegex =
369
- /([a-zA-Z0-9_]+)(?:\s*\.\s*With\s*\([^)]*\))*\s*\.\s*(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|Get|Post|Put|Patch|Delete|Options|Head)\s*\(\s*["']([^"']*)["']\s*,\s*(?:[a-zA-Z0-9_.]+\s*,\s*)*(?:func\s*\([^)]*\)|([a-zA-Z0-9_.]+))/g;
370
- let rMatch: RegExpExecArray | null;
371
-
372
- while ((rMatch = routeRegex.exec(funcBody)) !== null) {
373
- const routerVar = rMatch[1];
374
- const httpMethod = rMatch[2].toUpperCase();
375
- const rawUri = rMatch[3];
376
- const handlerTarget = (rMatch[4] && rMatch[4] !== "func") ? rMatch[4] : "closure";
377
- const routeLine = funcOffset + funcBody.slice(0, rMatch.index).split("\n").length;
378
-
379
- const groupPrefix = scopedGroupPrefixes.get(routerVar) || "";
380
- const cleanSub = rawUri ? (rawUri.startsWith("/") ? rawUri : `/${rawUri}`) : "";
381
- const fullUri = `${groupPrefix}${cleanSub}` || "/";
382
-
383
- this.pushSlice(
384
- slices,
385
- projectRoot,
386
- relPath,
387
- routeLine,
388
- httpMethod,
389
- fullUri,
390
- handlerTarget,
391
- handlers,
392
- scopedVarReceivers,
393
- goStructs,
394
- goMethods,
395
- domainId
396
- );
397
- }
398
-
399
- // Method 2: Standard net/http HandleFunc and Handle:
400
- // http.HandleFunc("/ping", pingHandler)
401
- // mux.HandleFunc("GET /users", h.GetUsers)
402
- // mux.HandleFunc("POST /users", h.CreateUser)
403
- // mux.Handle("/orders", h)
404
- const netHttpRegex =
405
- /(?:([a-zA-Z0-9_]+|http)\.)?(?:HandleFunc|Handle)\s*\(\s*["']([^"']*)["']\s*,\s*(?:func\s*\([^)]*\)|([a-zA-Z0-9_.]+))/g;
406
- let nhMatch: RegExpExecArray | null;
407
-
408
- while ((nhMatch = netHttpRegex.exec(funcBody)) !== null) {
409
- const pattern = nhMatch[2].trim();
410
- const handlerTarget = (nhMatch[3] && nhMatch[3] !== "func") ? nhMatch[3] : "closure";
411
- const routeLine = funcOffset + funcBody.slice(0, nhMatch.index).split("\n").length;
412
-
413
- // Parse Go 1.22+ pattern with optional method: "GET /path" or just "/path"
414
- const patternMatch = pattern.match(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s+(.*)$/);
415
- let httpMethod = "ANY";
416
- let rawUri = pattern;
417
-
418
- if (patternMatch) {
419
- httpMethod = patternMatch[1];
420
- rawUri = patternMatch[2].trim();
421
- }
422
-
423
- const cleanUri = rawUri.startsWith("/") ? rawUri : `/${rawUri}`;
424
-
425
- this.pushSlice(
426
- slices,
427
- projectRoot,
428
- relPath,
429
- routeLine,
430
- httpMethod,
431
- cleanUri,
432
- handlerTarget,
433
- handlers,
434
- scopedVarReceivers,
435
- goStructs,
436
- goMethods,
437
- domainId
438
- );
439
- }
167
+ const routes: Array<{ file: string; route: GoRoute }> = [];
168
+ const goRouteHint = /\.(?:get|post|put|patch|delete|options|head|connect|trace|any|all|handle|handlefunc|group|route|mount)\s*\(/i;
169
+ for (const file of files) {
170
+ const content = readCached(file);
171
+ if (!content || !goRouteHint.test(content)) continue;
172
+ const found = await parse(file, root => routing.collect(root, goImports(root), path.dirname(file), signal));
173
+ for (const route of found ?? []) routes.push({ file, route });
174
+ }
175
+ for (const { file, route } of routes) {
176
+ const handler = route.handler.key ? handlers.get(route.handler.key) : undefined;
177
+ for (const uri of goRouteUris(route)) {
178
+ this.pushSlice(slices, relative(file), uri, route, handler, structs, handlers, domainId);
440
179
  }
441
180
  }
442
-
443
181
  return slices;
444
182
  }
445
183
 
446
184
  private pushSlice(
447
185
  slices: VerticalSliceCandidate[],
448
- projectRoot: string,
449
186
  relPath: string,
450
- routeLine: number,
451
- httpMethod: string,
452
187
  fullUri: string,
453
- handlerTarget: string,
454
- handlers: Map<string, any>,
455
- scopedVarReceivers: Map<string, string>,
456
- goStructs: Map<string, any>,
457
- goMethods: Map<string, any>,
458
- domainId?: number
188
+ route: GoRoute,
189
+ handler: GoDeclaration | undefined,
190
+ structs: Map<string, GoStruct>,
191
+ declarations: Map<string, GoDeclaration>,
192
+ domainId?: number,
459
193
  ): void {
460
- let handlerInfo: any = undefined;
461
- let controllerClass = path.basename(relPath, ".go");
462
- let actionName = handlerTarget;
463
-
464
- if (handlerTarget.includes(".")) {
465
- const parts = handlerTarget.split(".");
466
- const varName = parts[0];
467
- const memberName = parts[1];
468
- actionName = memberName;
469
-
470
- // Look up variable receiver type
471
- const receiverType = scopedVarReceivers.get(varName);
472
- if (receiverType) {
473
- controllerClass = receiverType;
474
- handlerInfo = handlers.get(`${receiverType}.${memberName}`);
475
- } else {
476
- handlerInfo = handlers.get(handlerTarget);
477
- if (handlerInfo?.receiver) {
478
- controllerClass = handlerInfo.receiver;
479
- }
480
- }
481
- } else {
482
- handlerInfo = handlers.get(handlerTarget);
483
- if (handlerInfo?.receiver) {
484
- controllerClass = handlerInfo.receiver;
485
- }
486
- }
487
-
488
- const controllerFile = handlerInfo?.relPath || relPath;
489
- const controllerLine = handlerInfo?.line || routeLine;
490
-
491
- const chain: Array<{ stage: string; symbol: string; file?: string; line?: number; description?: string }> = [
194
+ const { line: routeLine, method: httpMethod } = route;
195
+ const actionName = route.handler.name;
196
+ const controllerClass = handler?.receiver ?? route.handler.receiver ?? path.basename(handler?.relPath ?? relPath, ".go");
197
+ const controllerFile = handler?.relPath ?? relPath;
198
+ const controllerLine = handler?.line ?? route.handler.line ?? routeLine;
199
+
200
+ const handlerStruct = handler?.receiver ? structs.get(goKey(handler.owner, handler.receiver)) : undefined;
201
+ const body = handler?.body ?? "";
202
+ const boundVar = body.match(/(?:ShouldBind(?:JSON|Query|URI|XML|YAML|Header)?|Bind(?:JSON)?|Decode|(?:Body|Params|Query)Parser)\s*\(\s*&(\w+)\s*\)/)?.[1];
203
+ const dto = boundVar && new RegExp(
204
+ `(?:var\\s+${boundVar}\\s+(?:\\w+\\.)?([A-Z]\\w*)|` +
205
+ `\\b${boundVar}\\s*:=\\s*&?(?:\\w+\\.)?([A-Z]\\w*)\\s*\\{|` +
206
+ `\\b${boundVar}\\s*:=\\s*new\\s*\\((?:\\w+\\.)?([A-Z]\\w*)\\))`
207
+ ).exec(body);
208
+ const boundType = dto && (dto[1] ?? dto[2] ?? dto[3]);
209
+ const serviceCall = handler && this.findFieldCall(handler, handlerStruct, /(?:Service|Usecase|UC)$/i);
210
+ const repositoryCall = handler && this.findFieldCall(handler, handlerStruct, /(?:Repo|Repository)$/i);
211
+
212
+ const registration = { file: relPath, line: routeLine };
213
+ const chain: ExecutionChainNode[] = [
492
214
  {
493
215
  stage: "ingress",
494
216
  symbol: `${httpMethod} ${fullUri}`,
495
217
  file: relPath,
496
218
  line: routeLine,
497
219
  description: `Go Route: ${httpMethod} ${fullUri}`,
220
+ relationship: { kind: "declares", derivation: "source", source: registration, reason: "Go router call" },
498
221
  },
499
222
  ];
500
223
 
501
- if (handlerInfo?.boundDto) {
502
- chain.push({
503
- stage: "validation",
504
- symbol: handlerInfo.boundDto,
505
- description: `Request DTO Binding: ${handlerInfo.boundDto}`,
506
- });
224
+ if (boundType) {
225
+ chain.push({ stage: "validation", symbol: boundType, description: `Request DTO Binding: ${boundType}` });
507
226
  }
508
227
 
509
- chain.push({
510
- stage: "controller",
511
- symbol: `${controllerClass}::${actionName}`,
512
- file: controllerFile,
513
- line: controllerLine,
514
- description: `Go Route Handler: ${actionName}`,
515
- });
516
-
517
- let serviceFile: string | undefined;
518
- let serviceLine: number | undefined;
519
- let repoCall = handlerInfo?.repoCall;
520
- let repoFile: string | undefined;
521
- let repoLine: number | undefined;
522
- let entityName: string | undefined;
523
- let entityFile: string | undefined;
524
- let entityLine: number | undefined;
525
-
526
- let targetMethod: any = undefined;
527
- let targetStruct: any = undefined;
528
-
529
- if (handlerInfo?.serviceCall) {
530
- const parts = handlerInfo.serviceCall.split("::");
531
- const callVar = parts[0];
532
- const callMethod = parts[1];
533
-
534
- const handlerStruct = goStructs.get(controllerClass);
535
- const svcType = handlerStruct?.fields.get(callVar) || callVar;
536
- targetMethod = goMethods.get(`${svcType}.${callMethod}`) || goMethods.get(`${callVar}.${callMethod}`);
537
- targetStruct = goStructs.get(svcType);
538
-
539
- serviceFile = targetMethod?.relPath || targetStruct?.relPath;
540
- serviceLine = targetMethod?.line || targetStruct?.line;
541
-
542
- // Scan service body for repo or DB persistence
543
- if (targetMethod?.body) {
544
- const rMatch = targetMethod.body.match(
545
- /(?:(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]*(?:repo|repository))\s*\.\s*([A-Z][a-zA-Z0-9_]+)\s*\(|db\s*\.\s*(?:Create|Save|Find|First|Update|Delete)\s*\(\s*&?([A-Z][a-zA-Z0-9_]+)\s*\))/i
546
- );
547
- if (rMatch && !repoCall) {
548
- repoCall = rMatch[1] ? `${rMatch[1]}::${rMatch[2]}` : `DB::${rMatch[3]}`;
549
- }
550
- for (const call of targetMethod.body.matchAll(/\b(\w+)\.(\w+)\s*\.\s*([A-Z]\w*)\s*\(/g)) {
551
- const fieldType = targetStruct?.fields.get(call[2]);
552
- if (call[1] === targetMethod.receiverVar && fieldType && /(?:Repo|Repository)$/i.test(fieldType)) {
553
- repoCall = `${call[2]}::${call[3]}`;
554
- break;
555
- }
556
- }
557
- }
558
- }
559
-
560
- if (repoCall) {
561
- const rParts = repoCall.split("::");
562
- const rVar = rParts[0];
563
- const rMethod = rParts[1];
564
-
565
- let rType = rVar;
566
- const handlerStruct = goStructs.get(controllerClass);
567
- if (handlerStruct?.fields?.has(rVar)) {
568
- rType = handlerStruct.fields.get(rVar)!;
569
- } else if (targetStruct?.fields?.has(rVar)) {
570
- rType = targetStruct.fields.get(rVar)!;
571
- }
572
- rType = rType.replace(/^\*?(?:[a-zA-Z0-9_]+\.)?/, "");
573
-
574
- const rMethodInfo = goMethods.get(`${rType}.${rMethod}`) || goMethods.get(`${rVar}.${rMethod}`);
575
- const rStructInfo = goStructs.get(rType);
576
- repoFile = rMethodInfo?.relPath || rStructInfo?.relPath;
577
- repoLine = rMethodInfo?.line || rStructInfo?.line;
578
-
579
- if (rVar === "DB" && rMethod) {
580
- entityName = rMethod;
581
- } else if (rMethodInfo?.body) {
582
- const entMatch = rMethodInfo.body.match(/&?([A-Z][a-zA-Z0-9_]+)\s*\{/);
583
- if (entMatch) entityName = entMatch[1];
584
- }
585
- if (!entityName && rMethodInfo?.params) {
586
- const pMatch = rMethodInfo.params.match(/\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)\b/);
587
- if (pMatch && goStructs.has(pMatch[1])) entityName = pMatch[1];
588
- }
589
- if (!entityName && targetMethod?.params) {
590
- const pMatch = targetMethod.params.match(/\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)\b/);
591
- if (pMatch && goStructs.has(pMatch[1])) entityName = pMatch[1];
592
- }
593
- }
594
-
595
- if (!entityName && handlerInfo?.boundDto) {
596
- const candidate = handlerInfo.boundDto.replace(/(?:Request|Req|DTO|Dto)$/, "");
597
- if (candidate && goStructs.has(candidate)) {
598
- entityName = candidate;
599
- }
600
- }
601
-
602
- if (entityName && goStructs.has(entityName)) {
603
- const entInfo = goStructs.get(entityName)!;
604
- entityFile = entInfo.relPath;
605
- entityLine = entInfo.line;
228
+ if (handler || route.handler.line !== undefined) {
229
+ chain.push({
230
+ stage: "controller",
231
+ symbol: `${controllerClass}::${actionName}`,
232
+ file: controllerFile,
233
+ line: controllerLine,
234
+ description: `Go Route Handler: ${actionName}`,
235
+ relationship: { kind: "route_binding", derivation: "source", source: registration, reason: "Go registration argument" },
236
+ });
606
237
  }
607
238
 
608
- if (handlerInfo?.serviceCall) {
239
+ const service = serviceCall && declarations.get(goKey(serviceCall.type.owner, `${serviceCall.type.name}.${serviceCall.method}`));
240
+ if (serviceCall) {
609
241
  chain.push({
610
- stage: "service",
611
- symbol: handlerInfo.serviceCall,
612
- ...(serviceFile ? { file: serviceFile, line: serviceLine } : {}),
613
- description: serviceFile ? "Go Service / Business Logic" : `Service / Business Logic`,
242
+ stage: "service", symbol: `${serviceCall.field}::${serviceCall.method}`,
243
+ ...(service ? { file: service.relPath, line: service.line } : {}),
244
+ description: "Go Service / Business Logic",
614
245
  });
615
246
  }
616
247
 
617
- if (repoCall) {
248
+ const serviceStruct = service?.receiver ? structs.get(goKey(service.owner, service.receiver)) : undefined;
249
+ const persistence = repositoryCall ?? (service && this.findFieldCall(service, serviceStruct, /(?:Repo|Repository)$/i));
250
+ const databaseCall = persistence ? undefined : [body, service?.body ?? ""]
251
+ .map(text => text.match(/\bdb\s*\.\s*(?:Create|Save|Find|First|Update|Delete)\s*\(\s*&?([A-Z]\w*)\s*\)/)?.[1])
252
+ .find(Boolean);
253
+ const repository = persistence && declarations.get(goKey(persistence.type.owner, `${persistence.type.name}.${persistence.method}`));
254
+ const repoStruct = persistence && structs.get(goKey(persistence.type.owner, persistence.type.name));
255
+ if (persistence) {
256
+ const location = repository ?? repoStruct;
257
+ chain.push({
258
+ stage: "repository", symbol: `${persistence.field}::${persistence.method}`,
259
+ ...(location ? { file: location.relPath, line: location.line } : {}),
260
+ description: "Go Repository / Persistence Layer",
261
+ });
262
+ } else if (databaseCall) {
618
263
  chain.push({
619
- stage: "repository",
620
- symbol: repoCall,
621
- ...(repoFile ? { file: repoFile, line: repoLine } : {}),
622
- description: repoFile ? "Go Repository / Persistence Layer" : `Persistence / Database Operation`,
264
+ stage: "repository", symbol: "DB::" + databaseCall, description: "Persistence / Database Operation",
265
+ relationship: { kind: "calls", derivation: "inferred", reason: "Go database call pattern" },
623
266
  });
624
267
  }
625
268
 
626
- if (entityName) {
269
+ const entity = databaseCall ?? (repository?.body.match(/&?([A-Z]\w*)\s*\{/) ?? repository?.params.match(/(?:^|[\s*])(?:\w+\.)?([A-Z]\w*)\b/))?.[1]
270
+ ?? boundType?.replace(/(?:Request|Req|DTO|Dto)$/, "");
271
+ const entityOwners = [repository?.owner, handler?.owner];
272
+ const entityLocations = entity
273
+ ? [...new Set([...structs].filter(([key]) => key.endsWith("\0" + entity)).map(([, location]) => location))]
274
+ : [];
275
+ const entityLocation = entity && (entityOwners.map(owner => owner && structs.get(goKey(owner, entity))).find(Boolean) ||
276
+ (entityLocations.length === 1 ? entityLocations[0] : undefined));
277
+ if (entity && entityLocation) {
627
278
  chain.push({
628
- stage: "entity",
629
- symbol: entityName,
630
- ...(entityFile ? { file: entityFile, line: entityLine } : {}),
631
- description: entityFile ? "Go Database / Domain Entity" : `Domain Entity`,
279
+ stage: "entity", symbol: entity, file: entityLocation.relPath, line: entityLocation.line,
280
+ description: "Go Database / Domain Entity",
632
281
  });
633
282
  }
634
283
 
@@ -648,23 +297,17 @@ export class GoSemanticExtractor implements SemanticSliceExtractor {
648
297
  });
649
298
  }
650
299
 
651
- private findGoBraceBlockEnd(content: string, startIndex: number): number {
652
- let depth = 0;
653
- let started = false;
654
-
655
- for (let i = startIndex; i < content.length; i++) {
656
- const char = content[i];
657
- if (char === "{") {
658
- depth++;
659
- started = true;
660
- } else if (char === "}") {
661
- depth--;
662
- if (started && depth === 0) {
663
- return i;
664
- }
300
+ private findFieldCall(
301
+ declaration: GoDeclaration,
302
+ struct: GoStruct | undefined,
303
+ suffix: RegExp,
304
+ ): { field: string; method: string; type: GoType } | undefined {
305
+ for (const call of declaration.body.matchAll(/\b(\w+)\.(\w+)\s*\.\s*([A-Z]\w*)\s*\(/g)) {
306
+ const type = struct?.fields.get(call[2]!);
307
+ if (call[1] === declaration.receiverVar && type && suffix.test(type.name)) {
308
+ return { field: call[2]!, method: call[3]!, type };
665
309
  }
666
310
  }
667
-
668
- return content.length;
311
+ return undefined;
669
312
  }
670
313
  }