@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,12 +1,29 @@
1
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
2
- import { isIgnoredDirectory } from "../../resources/ignore.ts";
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.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 (
@@ -22,12 +39,12 @@ export class GoSemanticExtractor implements SemanticSliceExtractor {
22
39
  }
23
40
 
24
41
  const goMod = path.join(projectRoot, "go.mod");
25
- if (fs.existsSync(goMod)) {
42
+ if (fs.existsSync(goMod) || listSourceFiles(projectRoot, /(?:^|[\\/])go\.mod$/).length > 0) {
26
43
  return true;
27
44
  }
28
45
 
29
46
  // Check Go source files for HTTP framework or standard library imports
30
- const goFiles = this.findGoFiles(projectRoot, 3);
47
+ const goFiles = listSourceFiles(projectRoot, /\.go$/).filter(file => !file.endsWith('_test.go'));
31
48
  for (const file of goFiles) {
32
49
  try {
33
50
  const content = fs.readFileSync(file, "utf-8");
@@ -40,513 +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): 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 = this.findGoFiles(projectRoot);
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
- }
63
-
64
- interface GoStructInfo {
65
- name: string;
66
- file: string;
67
- relPath: string;
68
- line: number;
69
- fields: Map<string, string>;
70
- }
71
-
72
- interface GoMethodInfo {
73
- receiver?: string;
74
- name: string;
75
- file: string;
76
- relPath: string;
77
- line: number;
78
- body: string;
79
- params?: string;
80
- }
81
-
82
- // 1. Catalog all handler functions & methods across .go files
83
- const handlers = new Map<string, HandlerInfo>();
84
- const goStructs = new Map<string, GoStructInfo>();
85
- const goMethods = new Map<string, GoMethodInfo>();
86
-
87
- for (const file of goFiles) {
88
- const content = readOptionalSourceFile(file, "utf-8");
89
- if (!content) continue;
90
-
91
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
92
-
93
- // Match Go functions and methods:
94
- // func (h *OrderHandler) CreateOrder(c *gin.Context)
95
- // func (h OrderHandler) CreateOrder(c echo.Context) error
96
- // func CreateOrder(w http.ResponseWriter, r *http.Request)
97
- const funcRegex =
98
- /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;
99
- let fMatch: RegExpExecArray | null;
100
-
101
- while ((fMatch = funcRegex.exec(content)) !== null) {
102
- const receiver = fMatch[1];
103
- const fnName = fMatch[2];
104
- const params = fMatch[3];
105
-
106
- // Only catalog HTTP handlers (takes *gin.Context, echo.Context, http.ResponseWriter, *fiber.Ctx)
107
- const isHttpHandler =
108
- params.includes("gin.Context") ||
109
- params.includes("echo.Context") ||
110
- params.includes("http.ResponseWriter") ||
111
- params.includes("fiber.Ctx") ||
112
- params.includes("*http.Request");
113
-
114
- if (!isHttpHandler) continue;
115
-
116
- const fnLine = content.slice(0, fMatch.index).split("\n").length;
117
- const bodyStart = fMatch.index + fMatch[0].length;
118
- const bodyEnd = this.findGoBraceBlockEnd(content, bodyStart - 1);
119
- const fnBody = content.slice(bodyStart, bodyEnd);
120
-
121
- // Detect DTO binding: ShouldBindJSON(&req), c.Bind(&req), Decode(&req), c.BodyParser(&req)
122
- let boundDto: string | undefined;
123
- 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*\)/);
124
- if (bindMatch) {
125
- const varName = bindMatch[1];
126
- // Look for explicit type declaration:
127
- // var req CreateOrderRequest
128
- // var req models.CreateOrderRequest
129
- // req := CreateOrderRequest{}
130
- // req := &CreateOrderRequest{}
131
- // req := new(CreateOrderRequest)
132
- const typeRegex = new RegExp(
133
- `(?:var\\s+${varName}\\s+(?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)|` +
134
- `${varName}\\s*:=\\s*&?(?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)\\s*\\{|` +
135
- `${varName}\\s*:=\\s*new\\s*\\((?:[a-zA-Z0-9_]+\\.)?([A-Z][a-zA-Z0-9_]+)\\))`
136
- );
137
- const typeMatch = fnBody.match(typeRegex);
138
- if (typeMatch) {
139
- boundDto = typeMatch[1] || typeMatch[2] || typeMatch[3];
140
- }
141
- // Note: If no type matched, do NOT synthesize a fake name (strict evidence invariant)
142
- }
143
-
144
- // Detect service calls: h.orderService.Process(...) or s.service.Create(...)
145
- let serviceCall: string | undefined;
146
- const sMatch = fnBody.match(/([a-zA-Z0-9_]+(?:Service|Usecase|UC))\s*\.\s*([A-Z][a-zA-Z0-9_]+)/i);
147
- if (sMatch) {
148
- serviceCall = `${sMatch[1]}::${sMatch[2]}`;
149
- }
150
-
151
- // Detect repo/db calls: h.repo.Save(...) or db.Create(&order)
152
- let repoCall: string | undefined;
153
- const rMatch = fnBody.match(/(?:([a-zA-Z0-9_]+(?:Repo|Repository))\s*\.\s*([A-Z][a-zA-Z0-9_]+)|db\s*\.\s*(?:Create|Save|Find|First|Update|Delete)\s*\(\s*&?([A-Z][a-zA-Z0-9_]+)\s*\))/i);
154
- if (rMatch) {
155
- repoCall = rMatch[1] ? `${rMatch[1]}::${rMatch[2]}` : `DB::${rMatch[3]}`;
156
- }
157
-
158
- const info: HandlerInfo = {
159
- name: fnName,
160
- receiver,
161
- file,
162
- relPath,
163
- line: fnLine,
164
- boundDto,
165
- serviceCall,
166
- repoCall,
167
- };
168
-
169
- if (receiver) {
170
- handlers.set(`${receiver}.${fnName}`, info);
171
- } else {
172
- handlers.set(fnName, info);
173
- }
174
- }
175
-
176
- // Catalog struct definitions
177
- const structRegex = /type\s+([A-Z][a-zA-Z0-9_]+)\s+(?:struct|interface)\s*\{/g;
178
- let sDeclMatch: RegExpExecArray | null;
179
- while ((sDeclMatch = structRegex.exec(content)) !== null) {
180
- const sName = sDeclMatch[1];
181
- const sLine = content.slice(0, sDeclMatch.index).split("\n").length;
182
- const sBodyStart = sDeclMatch.index + sDeclMatch[0].length;
183
- const sBodyEnd = this.findGoBraceBlockEnd(content, sBodyStart - 1);
184
- const sBody = content.slice(sBodyStart, sBodyEnd);
185
-
186
- const fields = new Map<string, string>();
187
- const fieldRegex = /^\s*([a-zA-Z0-9_]+)\s+\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)/gm;
188
- let fldMatch: RegExpExecArray | null;
189
- while ((fldMatch = fieldRegex.exec(sBody)) !== null) {
190
- fields.set(fldMatch[1], fldMatch[2]);
191
- }
192
-
193
- goStructs.set(sName, { name: sName, file, relPath, line: sLine, fields });
194
- }
195
-
196
- // Catalog all methods & functions for call resolution
197
- const allFuncRegex =
198
- /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;
199
- let afMatch: RegExpExecArray | null;
200
- while ((afMatch = allFuncRegex.exec(content)) !== null) {
201
- const rcv = afMatch[1];
202
- const fn = afMatch[2];
203
- const fLine = content.slice(0, afMatch.index).split("\n").length;
204
- const bStart = afMatch.index + afMatch[0].length;
205
- const bEnd = this.findGoBraceBlockEnd(content, bStart - 1);
206
- const bText = content.slice(bStart, bEnd);
207
- const params = afMatch[3];
208
- if (rcv) {
209
- goMethods.set(`${rcv}.${fn}`, { receiver: rcv, name: fn, file, relPath, line: fLine, body: bText, params });
210
- } else {
211
- goMethods.set(fn, { name: fn, file, relPath, line: fLine, body: bText, params });
212
- }
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;
213
84
  }
214
85
  }
215
-
216
- // 2. Extract route registrations per file with lexical block scoping
217
- for (const file of goFiles) {
218
- const content = readOptionalSourceFile(file, "utf-8");
219
- if (!content) continue;
220
-
221
- const relPath = path.relative(projectRoot, file).replace(/\\/g, "/");
222
-
223
- // Find router/setup functions and methods to scope groups and variable types
224
- const setupFuncRegex =
225
- /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;
226
- let funcMatch: RegExpExecArray | null;
227
-
228
- while ((funcMatch = setupFuncRegex.exec(content)) !== null) {
229
- const receiverVar = funcMatch[1];
230
- const receiverType = funcMatch[2];
231
- const funcParams = funcMatch[4];
232
- const funcStart = funcMatch.index;
233
- const bodyStart = funcStart + funcMatch[0].length;
234
- const bodyEnd = this.findGoBraceBlockEnd(content, bodyStart - 1);
235
- const funcBody = content.slice(bodyStart, bodyEnd);
236
- const funcOffset = content.slice(0, bodyStart).split("\n").length - 1;
237
-
238
- // Scoped variable -> receiver type mapping (e.g. h -> OrderHandler, s -> Server)
239
- const scopedVarReceivers = new Map<string, string>();
240
- if (receiverVar && receiverType) {
241
- scopedVarReceivers.set(receiverVar, receiverType);
242
- }
243
-
244
- // Map parameter variables: (h *http.OrderHandler, u *UserHandler)
245
- const paramRegex = /([a-zA-Z0-9_]+)\s+\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)/g;
246
- let pMatch: RegExpExecArray | null;
247
- while ((pMatch = paramRegex.exec(funcParams)) !== null) {
248
- scopedVarReceivers.set(pMatch[1], pMatch[2]);
249
- }
250
-
251
- // Map local variable instantiations: h := &OrderHandler{} or var h OrderHandler
252
- 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;
253
- let lMatch: RegExpExecArray | null;
254
- while ((lMatch = localInstRegex.exec(funcBody)) !== null) {
255
- const varName = lMatch[1] || lMatch[3];
256
- const typeName = lMatch[2] || lMatch[4];
257
- if (varName && typeName) {
258
- scopedVarReceivers.set(varName, typeName);
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") ?? "");
102
+ }
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
+ }
259
142
  }
260
- }
261
-
262
- // Scoped router groups: groupVar -> accumulatedPrefix
263
- const scopedGroupPrefixes = new Map<string, string>();
264
-
265
- // Gin / Echo groups: v1 := r.Group("/api/v1")
266
- const groupRegex = /([a-zA-Z0-9_]+)\s*:=\s*([a-zA-Z0-9_]+)\.Group\s*\(\s*["']([^"']*)["']/g;
267
- let gMatch: RegExpExecArray | null;
268
- while ((gMatch = groupRegex.exec(funcBody)) !== null) {
269
- const newGroup = gMatch[1];
270
- const parentGroup = gMatch[2];
271
- const subPrefix = gMatch[3].replace(/\/+$/, "");
272
-
273
- const parentPrefix = scopedGroupPrefixes.get(parentGroup) || "";
274
- const cleanSub = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
275
- scopedGroupPrefixes.set(newGroup, `${parentPrefix}${cleanSub}`);
276
- }
277
-
278
- // Chi subrouter Route: r.Route("/articles", func(r chi.Router) { ... })
279
- const chiRouteRegex = /([a-zA-Z0-9_]+)\.Route\s*\(\s*["']([^"']*)["']\s*,\s*func\s*\(\s*([a-zA-Z0-9_]+)\s+chi\.Router\s*\)/g;
280
- let cMatch: RegExpExecArray | null;
281
- while ((cMatch = chiRouteRegex.exec(funcBody)) !== null) {
282
- const parentRouter = cMatch[1];
283
- const subPrefix = cMatch[2].replace(/\/+$/, "");
284
- const subRouter = cMatch[3];
285
-
286
- const parentPrefix = scopedGroupPrefixes.get(parentRouter) || "";
287
- const cleanSub = subPrefix.startsWith("/") ? subPrefix : `/${subPrefix}`;
288
- scopedGroupPrefixes.set(subRouter, `${parentPrefix}${cleanSub}`);
289
- }
290
-
291
- // 3. Extract route registrations within this function scope
292
- // Method 1: Gin / Echo / Chi HTTP method calls: r.GET("/ping", pingHandler), v1.POST("/orders", h.CreateOrder)
293
- const routeRegex =
294
- /([a-zA-Z0-9_]+)\.(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;
295
- let rMatch: RegExpExecArray | null;
296
-
297
- while ((rMatch = routeRegex.exec(funcBody)) !== null) {
298
- const routerVar = rMatch[1];
299
- const httpMethod = rMatch[2].toUpperCase();
300
- const rawUri = rMatch[3];
301
- const handlerTarget = (rMatch[4] && rMatch[4] !== "func") ? rMatch[4] : "closure";
302
- const routeLine = funcOffset + funcBody.slice(0, rMatch.index).split("\n").length;
303
-
304
- const groupPrefix = scopedGroupPrefixes.get(routerVar) || "";
305
- const cleanSub = rawUri ? (rawUri.startsWith("/") ? rawUri : `/${rawUri}`) : "";
306
- const fullUri = `${groupPrefix}${cleanSub}` || "/";
307
-
308
- this.pushSlice(
309
- slices,
310
- projectRoot,
311
- relPath,
312
- routeLine,
313
- httpMethod,
314
- fullUri,
315
- handlerTarget,
316
- handlers,
317
- scopedVarReceivers,
318
- goStructs,
319
- goMethods,
320
- domainId
321
- );
322
- }
323
-
324
- // Method 2: Standard net/http HandleFunc and Handle:
325
- // http.HandleFunc("/ping", pingHandler)
326
- // mux.HandleFunc("GET /users", h.GetUsers)
327
- // mux.HandleFunc("POST /users", h.CreateUser)
328
- // mux.Handle("/orders", h)
329
- const netHttpRegex =
330
- /(?:([a-zA-Z0-9_]+|http)\.)?(?:HandleFunc|Handle)\s*\(\s*["']([^"']*)["']\s*,\s*(?:func\s*\([^)]*\)|([a-zA-Z0-9_.]+))/g;
331
- let nhMatch: RegExpExecArray | null;
332
-
333
- while ((nhMatch = netHttpRegex.exec(funcBody)) !== null) {
334
- const pattern = nhMatch[2].trim();
335
- const handlerTarget = (nhMatch[3] && nhMatch[3] !== "func") ? nhMatch[3] : "closure";
336
- const routeLine = funcOffset + funcBody.slice(0, nhMatch.index).split("\n").length;
337
-
338
- // Parse Go 1.22+ pattern with optional method: "GET /path" or just "/path"
339
- const patternMatch = pattern.match(/^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s+(.*)$/);
340
- let httpMethod = "ANY";
341
- let rawUri = pattern;
342
-
343
- if (patternMatch) {
344
- httpMethod = patternMatch[1];
345
- rawUri = patternMatch[2].trim();
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;
346
155
  }
347
-
348
- const cleanUri = rawUri.startsWith("/") ? rawUri : `/${rawUri}`;
349
-
350
- this.pushSlice(
351
- slices,
352
- projectRoot,
353
- relPath,
354
- routeLine,
355
- httpMethod,
356
- cleanUri,
357
- handlerTarget,
358
- handlers,
359
- scopedVarReceivers,
360
- goStructs,
361
- goMethods,
362
- domainId
363
- );
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
+ });
364
162
  }
365
- }
163
+ return true;
164
+ });
366
165
  }
367
166
 
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);
179
+ }
180
+ }
368
181
  return slices;
369
182
  }
370
183
 
371
184
  private pushSlice(
372
185
  slices: VerticalSliceCandidate[],
373
- projectRoot: string,
374
186
  relPath: string,
375
- routeLine: number,
376
- httpMethod: string,
377
187
  fullUri: string,
378
- handlerTarget: string,
379
- handlers: Map<string, any>,
380
- scopedVarReceivers: Map<string, string>,
381
- goStructs: Map<string, any>,
382
- goMethods: Map<string, any>,
383
- domainId?: number
188
+ route: GoRoute,
189
+ handler: GoDeclaration | undefined,
190
+ structs: Map<string, GoStruct>,
191
+ declarations: Map<string, GoDeclaration>,
192
+ domainId?: number,
384
193
  ): void {
385
- let handlerInfo: any = undefined;
386
- let controllerClass = path.basename(relPath, ".go");
387
- let actionName = handlerTarget;
388
-
389
- if (handlerTarget.includes(".")) {
390
- const parts = handlerTarget.split(".");
391
- const varName = parts[0];
392
- const memberName = parts[1];
393
- actionName = memberName;
394
-
395
- // Look up variable receiver type
396
- const receiverType = scopedVarReceivers.get(varName);
397
- if (receiverType) {
398
- controllerClass = receiverType;
399
- handlerInfo = handlers.get(`${receiverType}.${memberName}`);
400
- } else {
401
- handlerInfo = handlers.get(handlerTarget);
402
- if (handlerInfo?.receiver) {
403
- controllerClass = handlerInfo.receiver;
404
- }
405
- }
406
- } else {
407
- handlerInfo = handlers.get(handlerTarget);
408
- if (handlerInfo?.receiver) {
409
- controllerClass = handlerInfo.receiver;
410
- }
411
- }
412
-
413
- const controllerFile = handlerInfo?.relPath || relPath;
414
- const controllerLine = handlerInfo?.line || routeLine;
415
-
416
- 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[] = [
417
214
  {
418
215
  stage: "ingress",
419
216
  symbol: `${httpMethod} ${fullUri}`,
420
217
  file: relPath,
421
218
  line: routeLine,
422
219
  description: `Go Route: ${httpMethod} ${fullUri}`,
220
+ relationship: { kind: "declares", derivation: "source", source: registration, reason: "Go router call" },
423
221
  },
424
222
  ];
425
223
 
426
- if (handlerInfo?.boundDto) {
427
- chain.push({
428
- stage: "validation",
429
- symbol: handlerInfo.boundDto,
430
- description: `Request DTO Binding: ${handlerInfo.boundDto}`,
431
- });
224
+ if (boundType) {
225
+ chain.push({ stage: "validation", symbol: boundType, description: `Request DTO Binding: ${boundType}` });
432
226
  }
433
227
 
434
- chain.push({
435
- stage: "controller",
436
- symbol: `${controllerClass}::${actionName}`,
437
- file: controllerFile,
438
- line: controllerLine,
439
- description: `Go Route Handler: ${actionName}`,
440
- });
441
-
442
- let serviceFile: string | undefined;
443
- let serviceLine: number | undefined;
444
- let repoCall = handlerInfo?.repoCall;
445
- let repoFile: string | undefined;
446
- let repoLine: number | undefined;
447
- let entityName: string | undefined;
448
- let entityFile: string | undefined;
449
- let entityLine: number | undefined;
450
-
451
- let targetMethod: any = undefined;
452
- let targetStruct: any = undefined;
453
-
454
- if (handlerInfo?.serviceCall) {
455
- const parts = handlerInfo.serviceCall.split("::");
456
- const callVar = parts[0];
457
- const callMethod = parts[1];
458
-
459
- const handlerStruct = goStructs.get(controllerClass);
460
- const svcType = handlerStruct?.fields.get(callVar) || callVar;
461
- targetMethod = goMethods.get(`${svcType}.${callMethod}`) || goMethods.get(`${callVar}.${callMethod}`);
462
- targetStruct = goStructs.get(svcType);
463
-
464
- serviceFile = targetMethod?.relPath || targetStruct?.relPath;
465
- serviceLine = targetMethod?.line || targetStruct?.line;
466
-
467
- // Scan service body for repo or DB persistence
468
- if (targetMethod?.body) {
469
- const rMatch = targetMethod.body.match(
470
- /(?:(?:[a-zA-Z0-9_]+\.)?([a-zA-Z0-9_]*(?:repo|repository))\s*\.\s*([A-Z][a-zA-Z0-9_]+)|db\s*\.\s*(?:Create|Save|Find|First|Update|Delete)\s*\(\s*&?([A-Z][a-zA-Z0-9_]+)\s*\))/i
471
- );
472
- if (rMatch && !repoCall) {
473
- repoCall = rMatch[1] ? `${rMatch[1]}::${rMatch[2]}` : `DB::${rMatch[3]}`;
474
- }
475
- }
476
- }
477
-
478
- if (repoCall) {
479
- const rParts = repoCall.split("::");
480
- const rVar = rParts[0];
481
- const rMethod = rParts[1];
482
-
483
- let rType = rVar;
484
- const handlerStruct = goStructs.get(controllerClass);
485
- if (handlerStruct?.fields?.has(rVar)) {
486
- rType = handlerStruct.fields.get(rVar)!;
487
- } else if (targetStruct?.fields?.has(rVar)) {
488
- rType = targetStruct.fields.get(rVar)!;
489
- }
490
- rType = rType.replace(/^\*?(?:[a-zA-Z0-9_]+\.)?/, "");
491
-
492
- const rMethodInfo = goMethods.get(`${rType}.${rMethod}`) || goMethods.get(`${rVar}.${rMethod}`);
493
- const rStructInfo = goStructs.get(rType);
494
- repoFile = rMethodInfo?.relPath || rStructInfo?.relPath;
495
- repoLine = rMethodInfo?.line || rStructInfo?.line;
496
-
497
- if (rVar === "DB" && rMethod) {
498
- entityName = rMethod;
499
- } else if (rMethodInfo?.body) {
500
- const entMatch = rMethodInfo.body.match(/&?([A-Z][a-zA-Z0-9_]+)\s*\{/);
501
- if (entMatch) entityName = entMatch[1];
502
- }
503
- if (!entityName && rMethodInfo?.params) {
504
- const pMatch = rMethodInfo.params.match(/\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)\b/);
505
- if (pMatch && goStructs.has(pMatch[1])) entityName = pMatch[1];
506
- }
507
- if (!entityName && targetMethod?.params) {
508
- const pMatch = targetMethod.params.match(/\*?(?:[a-zA-Z0-9_]+\.)?([A-Z][a-zA-Z0-9_]+)\b/);
509
- if (pMatch && goStructs.has(pMatch[1])) entityName = pMatch[1];
510
- }
511
- }
512
-
513
- if (!entityName && handlerInfo?.boundDto) {
514
- const candidate = handlerInfo.boundDto.replace(/(?:Request|Req|DTO|Dto)$/, "");
515
- if (candidate && goStructs.has(candidate)) {
516
- entityName = candidate;
517
- }
518
- }
519
-
520
- if (entityName && goStructs.has(entityName)) {
521
- const entInfo = goStructs.get(entityName)!;
522
- entityFile = entInfo.relPath;
523
- 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
+ });
524
237
  }
525
238
 
526
- if (handlerInfo?.serviceCall) {
239
+ const service = serviceCall && declarations.get(goKey(serviceCall.type.owner, `${serviceCall.type.name}.${serviceCall.method}`));
240
+ if (serviceCall) {
527
241
  chain.push({
528
- stage: "service",
529
- symbol: handlerInfo.serviceCall,
530
- ...(serviceFile ? { file: serviceFile, line: serviceLine } : {}),
531
- 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",
532
245
  });
533
246
  }
534
247
 
535
- 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) {
536
263
  chain.push({
537
- stage: "repository",
538
- symbol: repoCall,
539
- ...(repoFile ? { file: repoFile, line: repoLine } : {}),
540
- 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" },
541
266
  });
542
267
  }
543
268
 
544
- 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) {
545
278
  chain.push({
546
- stage: "entity",
547
- symbol: entityName,
548
- ...(entityFile ? { file: entityFile, line: entityLine } : {}),
549
- 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",
550
281
  });
551
282
  }
552
283
 
@@ -566,46 +297,17 @@ export class GoSemanticExtractor implements SemanticSliceExtractor {
566
297
  });
567
298
  }
568
299
 
569
- private findGoBraceBlockEnd(content: string, startIndex: number): number {
570
- let depth = 0;
571
- let started = false;
572
-
573
- for (let i = startIndex; i < content.length; i++) {
574
- const char = content[i];
575
- if (char === "{") {
576
- depth++;
577
- started = true;
578
- } else if (char === "}") {
579
- depth--;
580
- if (started && depth === 0) {
581
- return i;
582
- }
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 };
583
309
  }
584
310
  }
585
-
586
- return content.length;
587
- }
588
-
589
- private findGoFiles(dir: string, maxDepth: number = 10): string[] {
590
- const results: string[] = [];
591
- const traverse = (currentDir: string, currentDepth: number) => {
592
- if (currentDepth > maxDepth || !fs.existsSync(currentDir)) return;
593
- try {
594
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
595
- for (const entry of entries) {
596
- if (isIgnoredDirectory(entry.name)) continue;
597
-
598
- const fullPath = path.join(currentDir, entry.name);
599
- if (entry.isDirectory()) {
600
- traverse(fullPath, currentDepth + 1);
601
- } else if (entry.isFile() && entry.name.endsWith(".go") && !entry.name.endsWith("_test.go")) {
602
- results.push(fullPath);
603
- }
604
- }
605
- } catch {}
606
- };
607
-
608
- traverse(dir, 0);
609
- return results;
311
+ return undefined;
610
312
  }
611
313
  }