@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,26 +1,95 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
1
3
  import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
4
  import type { SeptumRepository } from "../../core/database/repository.ts";
3
5
  import type { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
4
- import type { SymbolToolArgs } from "../schemas.ts";
5
- import { handleLocateSymbol } from "./locate-symbol.ts";
6
- import { handleGetSymbol } from "./get-symbol.ts";
7
- import { handleGetSymbolImpact } from "./get-symbol-impact.ts";
8
- import { handleGetSymbolHotspots } from "./get-symbol-hotspots.ts";
6
+ import { SymbolLocator, type SymbolLocationResult } from "../../core/resolver/symbol-locator.ts";
7
+ import { isIgnoredDirectory } from "../../core/resources/ignore.ts";
8
+ import { retrieveContext } from "../../core/retrieval/context.ts";
9
+ import { partitionResolutionWarnings } from "../../core/retrieval/resolution-warnings.ts";
10
+ import { inspectSourceContext, selectSymbolContextMode } from "../../core/retrieval/source-context.ts";
11
+ import { symbolWorkspace, withSymbolEvidence } from "../../core/retrieval/symbol-evidence.ts";
12
+ import type { GetSymbolArgs, GetSymbolImpactArgs } from "../../types/index.ts";
13
+ import {
14
+ formatDeepContextAsText,
15
+ formatImpactAsText,
16
+ formatLocateAsText,
17
+ formatSourceContextAsText,
18
+ } from "../formatters/compact-text.ts";
19
+ import type { LocateSymbolArgs, SymbolToolArgs } from "../schemas.ts";
9
20
 
10
- export type { SymbolToolArgs };
21
+ export type { LocateSymbolArgs, SymbolToolArgs };
22
+
23
+ function applySymbolFormat<T extends { content: Array<{ type: "text"; text: string }>; metadata?: unknown; structuredContent?: unknown }>(
24
+ result: T,
25
+ format: "json" | "text" | undefined,
26
+ formatter: (payload: Record<string, any>) => string
27
+ ): T {
28
+ const effective = format ?? "text";
29
+ if (effective === "json") return result;
30
+ try {
31
+ const payload = JSON.parse(result.content[0]!.text) as Record<string, any>;
32
+ return {
33
+ ...result,
34
+ content: [{ type: "text" as const, text: formatter(payload) }, ...result.content.slice(1)],
35
+ structuredContent: result.structuredContent ?? payload,
36
+ metadata: result.metadata ?? {
37
+ status: payload.status,
38
+ found: payload.found ?? payload.found_in_index,
39
+ },
40
+ };
41
+ } catch {
42
+ return result;
43
+ }
44
+ }
11
45
 
12
46
  export async function handleSymbolTool(
13
47
  repo: SeptumRepository,
14
48
  config: ValidatedSeptumConfig,
15
49
  args: SymbolToolArgs,
16
50
  pipeline?: IngestionPipeline,
17
- workspaceRoot?: string
51
+ workspaceRoot?: string,
52
+ signal?: AbortSignal
18
53
  ) {
19
54
  const action = args.action || "locate";
55
+ const format = args.format ?? "text";
20
56
 
21
57
  switch (action) {
58
+ case "context":
22
59
  case "inspect": {
23
- const symbol = args.symbol || args.query || "";
60
+ const { mode, symbol } = selectSymbolContextMode(repo, args);
61
+ if (mode === "invalid_query") {
62
+ const err = {
63
+ status: "invalid_query",
64
+ message: "Choose a target with query, symbol or symbol_ref.",
65
+ };
66
+ return {
67
+ content: [{
68
+ type: "text" as const,
69
+ text: format === "json" ? JSON.stringify(err) : formatSourceContextAsText(err),
70
+ }],
71
+ structuredContent: err,
72
+ metadata: err,
73
+ };
74
+ }
75
+ if (mode === "deep") {
76
+ const res = await retrieveContext(repo, config, args, symbolWorkspace(repo, workspaceRoot || args.workspace_path), signal);
77
+ return applySymbolFormat(res, format, formatDeepContextAsText);
78
+ }
79
+ if (mode === "invalid_options") {
80
+ const err = {
81
+ status: "invalid_context_options",
82
+ message: "budget_bytes and continuation apply to deep TypeScript context. For bounded source use source_start_line and source_line_limit.",
83
+ };
84
+ return {
85
+ content: [{
86
+ type: "text" as const,
87
+ text: format === "json" ? JSON.stringify(err) : formatSourceContextAsText(err),
88
+ }],
89
+ structuredContent: err,
90
+ metadata: err,
91
+ };
92
+ }
24
93
  return handleGetSymbol(
25
94
  repo,
26
95
  config,
@@ -31,9 +100,12 @@ export async function handleSymbolTool(
31
100
  file_path: args.file_path,
32
101
  symbol_ref: args.symbol_ref,
33
102
  include_dependencies: args.include_dependencies,
34
- include_source: args.include_source,
103
+ include_source: args.include_source ?? true,
35
104
  source_start_line: args.source_start_line,
36
105
  source_line_limit: args.source_line_limit,
106
+ budget_bytes: args.budget_bytes,
107
+ semantic_depth: args.semantic_depth,
108
+ format,
37
109
  workspace_path: args.workspace_path,
38
110
  },
39
111
  workspaceRoot
@@ -41,7 +113,7 @@ export async function handleSymbolTool(
41
113
  }
42
114
 
43
115
  case "impact": {
44
- const symbol = args.symbol || args.query || "";
116
+ const symbol = args.symbol || args.query || args.symbol_ref?.name || "";
45
117
  return handleGetSymbolImpact(
46
118
  repo,
47
119
  config,
@@ -51,28 +123,13 @@ export async function handleSymbolTool(
51
123
  domain: args.domain,
52
124
  file_path: args.file_path,
53
125
  symbol_ref: args.symbol_ref,
126
+ format,
54
127
  workspace_path: args.workspace_path,
55
128
  },
56
129
  workspaceRoot
57
130
  );
58
131
  }
59
132
 
60
- case "hotspots":
61
- return handleGetSymbolHotspots(
62
- repo,
63
- config,
64
- {
65
- min_lines: args.min_lines,
66
- min_nesting: args.min_nesting,
67
- kind: args.kind,
68
- domain: args.domain,
69
- limit: args.limit ?? 30,
70
- sort_by: (args.sort_by === "line_count" ? "lines" : args.sort_by) as any,
71
- workspace_path: args.workspace_path,
72
- },
73
- workspaceRoot
74
- );
75
-
76
133
  case "locate":
77
134
  default:
78
135
  return await handleLocateSymbol(
@@ -84,6 +141,7 @@ export async function handleSymbolTool(
84
141
  file_path: args.file_path,
85
142
  symbol_ref: args.symbol_ref,
86
143
  limit: args.limit ?? 10,
144
+ format,
87
145
  workspace_path: args.workspace_path,
88
146
  },
89
147
  pipeline,
@@ -91,3 +149,399 @@ export async function handleSymbolTool(
91
149
  );
92
150
  }
93
151
  }
152
+
153
+ export function handleGetSymbol(
154
+ repo: SeptumRepository,
155
+ config: ValidatedSeptumConfig,
156
+ args: GetSymbolArgs,
157
+ workspaceRoot?: string
158
+ ) {
159
+ const root = symbolWorkspace(repo, workspaceRoot || args.workspace_path);
160
+ const res = withSymbolEvidence(repo, root, { operation: "inspect", requested: args.symbol_ref }, () => {
161
+ const payload = inspectSourceContext(repo, config, args, root);
162
+ return {
163
+ content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
164
+ };
165
+ });
166
+ return applySymbolFormat(res, args.format, formatSourceContextAsText);
167
+ }
168
+
169
+ export function handleGetSymbolImpact(
170
+ repo: SeptumRepository,
171
+ config: ValidatedSeptumConfig,
172
+ args: GetSymbolImpactArgs,
173
+ workspaceRoot?: string
174
+ ) {
175
+ const root = symbolWorkspace(repo, workspaceRoot || args.workspace_path);
176
+ const res = withSymbolEvidence(repo, root, { operation: "impact", requested: args.symbol_ref },
177
+ () => inspectImpact(repo, config, args, root));
178
+ return applySymbolFormat(res, args.format, formatImpactAsText);
179
+ }
180
+
181
+ function inspectImpact(
182
+ repo: SeptumRepository,
183
+ _config: ValidatedSeptumConfig,
184
+ args: GetSymbolImpactArgs,
185
+ workspaceRoot?: string
186
+ ) {
187
+ const symbol = (args.symbol_ref?.name || args.symbol || (args as unknown as Record<string, unknown>).query || "").toString().trim();
188
+ if (!symbol) {
189
+ throw new Error(
190
+ "Missing required argument: 'symbol' (e.g. 'OrderService::cancelOrder', 'OrderService', or 'cancelOrder')"
191
+ );
192
+ }
193
+
194
+ if (args.symbol_ref) {
195
+ const file = repo.getFileByPath(args.symbol_ref.file_path);
196
+ if (!file || file.content_hash !== args.symbol_ref.indexed_content_hash) {
197
+ return {
198
+ content: [{
199
+ type: "text" as const,
200
+ text: JSON.stringify({
201
+ target_symbol: symbol,
202
+ status: "stale_reference",
203
+ found_in_index: false,
204
+ message: "Declaration reference is stale; locate the symbol again.",
205
+ }),
206
+ }],
207
+ };
208
+ }
209
+ }
210
+
211
+ const candidates = repo.findSymbolsByName(symbol, {
212
+ domain: args.domain,
213
+ filePath: args.file_path,
214
+ reference: args.symbol_ref,
215
+ });
216
+ if (candidates.length > 1) {
217
+ return {
218
+ content: [{
219
+ type: "text" as const,
220
+ text: JSON.stringify({
221
+ status: "ambiguous",
222
+ target_symbol: symbol,
223
+ found_in_index: false,
224
+ candidates: candidates.map(c => ({ name: c.name, file_path: c.file_path, symbol_ref: c.symbol_ref })),
225
+ message: "Multiple declarations match; select a candidate with symbol_ref or narrow with file_path.",
226
+ }, null, 2),
227
+ }],
228
+ };
229
+ }
230
+
231
+ const selectedCandidate = candidates[0];
232
+ const resolvedSymbol = selectedCandidate?.name ?? symbol;
233
+ let suggestions: string[] | undefined;
234
+ if (!selectedCandidate && args.file_path) {
235
+ const normalizedPath = args.file_path.replace(/\\/g, "/").replace(/^\.\//, "");
236
+ const file = repo.getFileByPath(normalizedPath);
237
+ if (file) {
238
+ const fileSymbols = repo.getSymbolsByFileId(file.id);
239
+ if (fileSymbols.length > 0) {
240
+ const lower = symbol.toLowerCase();
241
+ const ranked = [...fileSymbols].sort((a, b) => {
242
+ const aMatch = a.name.toLowerCase().includes(lower) ? 0 : 1;
243
+ const bMatch = b.name.toLowerCase().includes(lower) ? 0 : 1;
244
+ return aMatch - bMatch || a.line_start - b.line_start;
245
+ });
246
+ suggestions = ranked.slice(0, 10).map((s) => s.name);
247
+ }
248
+ }
249
+ }
250
+
251
+ const impact = repo.getSymbolImpact(resolvedSymbol, {
252
+ domain: args.domain,
253
+ filePath: args.file_path || selectedCandidate?.file_path,
254
+ reference: args.symbol_ref || selectedCandidate?.symbol_ref,
255
+ workspaceRoot: workspaceRoot || args.workspace_path,
256
+ });
257
+
258
+ const targetFiles = candidates.map(c => c.file_path);
259
+ const targetFileSet = new Set(targetFiles);
260
+ const relationships = targetFileSet.size > 0
261
+ ? repo.getScopedImportRelationships(workspaceRoot || args.workspace_path, {
262
+ targetCandidateFiles: targetFileSet,
263
+ })
264
+ : [];
265
+ const importDependents = relationships.filter(edge =>
266
+ edge.resolution.status === "resolved" &&
267
+ edge.resolution.targets.some(t => t.files.some(f => targetFileSet.has(f)))
268
+ );
269
+ const warnings = partitionResolutionWarnings(relationships, targetFiles);
270
+ const callSites = impact.inbound_callers.filter(
271
+ caller => caller.kind === "call" || caller.kind === "instantiation" || caller.kind === "heritage"
272
+ );
273
+ const firstResolution = importDependents[0]?.resolution;
274
+ const isTypeOnlyStmt = (stmt: string) => /^\s*(?:import|export)\s+type\b/.test(stmt);
275
+ const fileDomainMap = new Map<string, string>();
276
+ for (const c of impact.inbound_callers) {
277
+ if (c.domain) fileDomainMap.set(c.file, c.domain);
278
+ }
279
+ const runtimeImports: Array<{ file: string; line: number; domain?: string; statement: string }> = [];
280
+ const typeOnlyImports: Array<{ file: string; line: number; domain?: string; statement: string }> = [];
281
+ for (const edge of importDependents) {
282
+ const entry = {
283
+ file: edge.source.file,
284
+ line: edge.source.line,
285
+ ...(fileDomainMap.get(edge.source.file) ? { domain: fileDomainMap.get(edge.source.file) } : {}),
286
+ statement: edge.source.statement,
287
+ };
288
+ if (isTypeOnlyStmt(edge.source.statement)) typeOnlyImports.push(entry);
289
+ else runtimeImports.push(entry);
290
+ }
291
+ const compactImportDependents = importDependents.map(edge => ({
292
+ source: { file: edge.source.file, line: edge.source.line, statement: edge.source.statement },
293
+ target_domains: edge.target_domains,
294
+ is_type_only: isTypeOnlyStmt(edge.source.statement),
295
+ resolution: { status: edge.resolution.status, reason: edge.resolution.reason, targets: edge.resolution.targets },
296
+ }));
297
+
298
+ const payload = {
299
+ ...impact,
300
+ impact_summary: {
301
+ ...impact.impact_summary,
302
+ call_sites_count: callSites.length,
303
+ runtime_imports_count: runtimeImports.length,
304
+ type_only_imports_count: typeOnlyImports.length,
305
+ },
306
+ symbol_ref: selectedCandidate?.symbol_ref,
307
+ ...(suggestions ? { suggestions } : {}),
308
+ coverage: "partial",
309
+ inbound_callers_complete: false,
310
+ call_sites: callSites,
311
+ runtime_imports: runtimeImports,
312
+ type_only_imports: typeOnlyImports,
313
+ risk_scope: "advisory; incomplete static consumer evidence",
314
+ relationship_limits: "Imports do not prove executed calls; runtime dispatch and unindexed callers are omitted.",
315
+ ...(firstResolution ? { resolution_metadata: { resolver_revision: firstResolution.resolver_revision, config_revision: firstResolution.config_revision } } : {}),
316
+ import_dependents: compactImportDependents,
317
+ resolution_warnings: warnings.relevant.slice(0, 25),
318
+ ...(warnings.relevant.length > 25 ? { resolution_warnings_omitted: warnings.relevant.length - 25 } : {}),
319
+ workspace_resolution_diagnostics: {
320
+ count: warnings.workspace.length,
321
+ returned_details: 0,
322
+ omitted_details: warnings.workspace.length,
323
+ reason: "Resolved unrelated workspace imports omitted; unresolved/stale items stay in resolution_warnings.",
324
+ },
325
+ diagnostic_accounting: {
326
+ total: warnings.relevant.length + warnings.workspace.length,
327
+ target_or_possible_target: warnings.relevant.length,
328
+ unrelated_workspace: warnings.workspace.length,
329
+ },
330
+ };
331
+
332
+ return {
333
+ content: [{ type: "text" as const, text: JSON.stringify(payload) }],
334
+ };
335
+ }
336
+
337
+ export async function handleLocateSymbol(
338
+ repo: SeptumRepository,
339
+ config: ValidatedSeptumConfig,
340
+ args: Partial<LocateSymbolArgs>,
341
+ pipeline?: IngestionPipeline,
342
+ workspaceRoot?: string
343
+ ) {
344
+ const query = (args.query || args.symbol || args.symbol_ref?.name || "").toString().trim();
345
+ const root = symbolWorkspace(repo, workspaceRoot || args.workspace_path);
346
+ const diagnostics: string[] = [];
347
+ const limit = args.limit ?? 10;
348
+
349
+ if (!query || query === "*") {
350
+ if (args.file_path) {
351
+ const normalizedPath = args.file_path.replace(/\\/g, "/").replace(/^\.\//, "");
352
+ const file = repo.getFileByPath(normalizedPath);
353
+ const allSymbols = file ? repo.getSymbolsByFileId(file.id) : [];
354
+ const sliced = allSymbols.slice(0, limit).map((s) => ({
355
+ name: s.name,
356
+ file_path: normalizedPath,
357
+ kind: s.kind,
358
+ signature: s.signature,
359
+ start_line: s.line_start,
360
+ end_line: s.line_end,
361
+ }));
362
+ const filePayload = {
363
+ status: sliced.length > 0 ? "success" : "not_found",
364
+ found: sliced.length > 0,
365
+ query: query || null,
366
+ file_path: normalizedPath,
367
+ candidates: sliced,
368
+ total_candidates: allSymbols.length,
369
+ omitted_candidates: Math.max(0, allSymbols.length - sliced.length),
370
+ summary: sliced.length > 0
371
+ ? `[FOUND] Listed ${sliced.length} of ${allSymbols.length} declarations in ${normalizedPath}.`
372
+ : `[NOT FOUND] No indexed declarations found in '${normalizedPath}'.`,
373
+ };
374
+ const res = withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
375
+ content: [{ type: "text" as const, text: JSON.stringify(filePayload, null, 2) }],
376
+ metadata: filePayload,
377
+ }));
378
+ return applySymbolFormat(res, args.format, formatLocateAsText);
379
+ }
380
+ throw new Error(
381
+ "Missing required argument: 'query' (e.g. 'OrderController::calculateTotal' or error log snippet)"
382
+ );
383
+ }
384
+
385
+ if (repo.countFiles() === 0 && pipeline) {
386
+ try {
387
+ await pipeline.run(config);
388
+ } catch {
389
+ diagnostics.push("initial_index_refresh_failed");
390
+ }
391
+
392
+ if (repo.countFiles() === 0) {
393
+ const diagnostic = {
394
+ status: "NOT_INDEXED",
395
+ found: false,
396
+ query,
397
+ message: `Workspace '${root}' belum terindeks dalam Septum catalog.`,
398
+ suggested_action: {
399
+ tool: "septum_map",
400
+ params: { action: "register", name: "core", root: "src", ingest_now: true },
401
+ },
402
+ agent_guidance:
403
+ "Panggil tool 'septum_map(action: \"register\", name: \"core\", root: \"src\", ingest_now: true)' untuk mendaftarkan dan mengindeks codebase ini, atau jalankan 'septum init' di terminal workspace.",
404
+ };
405
+
406
+ const res = withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
407
+ content: [{ type: "text" as const, text: JSON.stringify(diagnostic, null, 2) }],
408
+ metadata: diagnostic,
409
+ }));
410
+ return applySymbolFormat(res, args.format, formatLocateAsText);
411
+ }
412
+ }
413
+
414
+ const locator = new SymbolLocator(repo);
415
+ let result: SymbolLocationResult = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
416
+
417
+ if (result.found && result.file_path && pipeline) {
418
+ const fullPath = isAbsolute(result.file_path) ? result.file_path : join(root, result.file_path);
419
+ try {
420
+ const reindexed = await pipeline.ingestFile(fullPath, config);
421
+ if (reindexed) {
422
+ result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
423
+ }
424
+ } catch {
425
+ diagnostics.push("target_index_refresh_failed");
426
+ }
427
+ }
428
+
429
+ if (!result.found && pipeline) {
430
+ try {
431
+ const cleanTerm = query.replace(/[^a-zA-Z0-9_]/g, " ").trim().split(/\s+/)[0] || "";
432
+ if (cleanTerm.length >= 3) {
433
+ const candidateFiles = findCandidateFiles(root, cleanTerm);
434
+ let anyReindexed = false;
435
+ for (const candidate of candidateFiles) {
436
+ const reindexed = await pipeline.ingestFile(candidate, config);
437
+ if (reindexed) anyReindexed = true;
438
+ }
439
+ if (anyReindexed) {
440
+ result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
441
+ }
442
+ }
443
+ } catch {
444
+ diagnostics.push("candidate_refresh_failed");
445
+ }
446
+ }
447
+
448
+ const exactLineCount = result.exact_symbol
449
+ ? result.exact_symbol.line_end - result.exact_symbol.line_start + 1
450
+ : 0;
451
+ const complexitySmell = exactLineCount > 300
452
+ ? {
453
+ is_high_complexity: true,
454
+ threshold: 300,
455
+ total_lines: exactLineCount,
456
+ warning: `Symbol '${result.exact_symbol?.name}' spans ${exactLineCount} lines (exceeds 300-line threshold). Candidate for decomposition/refactoring.`,
457
+ }
458
+ : undefined;
459
+
460
+ const suggestions = (result.suggestions || []).slice(0, limit);
461
+ let summary = result.status === "ambiguous"
462
+ ? `[AMBIGUOUS] Multiple declarations match '${query}'; select a candidate with symbol_ref or file_path.`
463
+ : result.status === "stale_reference"
464
+ ? `[STALE REFERENCE] Locate '${query}' again before using its indexed coordinates.`
465
+ : result.found
466
+ ? `[FOUND] ${result.exact_symbol?.name || query} in ${result.file_path} (lines ${result.exact_symbol?.line_start}-${result.exact_symbol?.line_end})`
467
+ : `[NOT FOUND] Symbol '${query}' not found. ${suggestions.length > 0 ? `Top suggestions: ${suggestions.map((s) => s.name).slice(0, 3).join(", ")}` : "No close suggestions."}`;
468
+
469
+ if (complexitySmell) {
470
+ summary += ` | ⚠️ High-Complexity Smell: spans ${exactLineCount} lines (> 300L)`;
471
+ }
472
+
473
+ const allCandidates = result.candidates || [];
474
+ const boundedCandidates = allCandidates.slice(0, limit);
475
+ const payload = {
476
+ status: result.status ?? (result.found ? "success" : "not_found"),
477
+ candidates: result.candidates ? boundedCandidates : undefined,
478
+ ...(allCandidates.length > boundedCandidates.length
479
+ ? { total_candidates: allCandidates.length, omitted_candidates: allCandidates.length - boundedCandidates.length }
480
+ : {}),
481
+ symbol_ref: result.symbol_ref,
482
+ visibility_semantics: "legacy_normalized",
483
+ found: result.found,
484
+ query,
485
+ file_path: result.file_path || null,
486
+ container_name: result.container_name || null,
487
+ exact_symbol: result.exact_symbol
488
+ ? {
489
+ name: result.exact_symbol.name,
490
+ kind: result.exact_symbol.kind,
491
+ ...(result.symbol_ref ? {} : { signature: result.exact_symbol.signature }),
492
+ visibility: result.exact_symbol.visibility,
493
+ line_start: result.exact_symbol.line_start,
494
+ line_end: result.exact_symbol.line_end,
495
+ start_line: result.exact_symbol.start_line,
496
+ end_line: result.exact_symbol.end_line,
497
+ total_lines: exactLineCount,
498
+ }
499
+ : null,
500
+ complexity_smell: complexitySmell,
501
+ sibling_methods: result.sibling_methods || [],
502
+ suggestions,
503
+ summary,
504
+ message: result.message || summary,
505
+ };
506
+
507
+ const res = withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
508
+ content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
509
+ metadata: payload,
510
+ }));
511
+ return applySymbolFormat(res, args.format, formatLocateAsText);
512
+ }
513
+
514
+ function findCandidateFiles(root: string, term: string): string[] {
515
+ const matched: string[] = [];
516
+ const lowerTerm = term.toLowerCase().replace(/_/g, "");
517
+ const searchDirs = ["src", "app", "lib"].map((d) => join(root, d)).filter((d) => existsSync(d));
518
+
519
+ function scan(dir: string, depth: number = 0) {
520
+ if (depth > 4) return;
521
+ try {
522
+ const entries = readdirSync(dir, { withFileTypes: true });
523
+ for (const e of entries) {
524
+ if (isIgnoredDirectory(e.name)) continue;
525
+ const full = join(dir, e.name);
526
+ if (e.isDirectory()) {
527
+ scan(full, depth + 1);
528
+ } else if (e.isFile() && /\.(ts|tsx|js|jsx|php|py|go)$/i.test(e.name)) {
529
+ const lowerName = e.name.toLowerCase().replace(/[-_.]/g, "");
530
+ if (lowerName.includes(lowerTerm) || lowerTerm.includes(lowerName.replace(/\.[^.]+$/, ""))) {
531
+ matched.push(full);
532
+ if (matched.length >= 5) return;
533
+ }
534
+ }
535
+ }
536
+ } catch {
537
+ // Ignore
538
+ }
539
+ }
540
+
541
+ for (const sDir of searchDirs) {
542
+ scan(sDir);
543
+ if (matched.length >= 5) break;
544
+ }
545
+
546
+ return matched;
547
+ }