@dimassetoid/septum-mcp 0.3.0 → 0.5.1

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 +255 -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,14 +1,47 @@
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";
6
+ import { SymbolLocator, type SymbolLocationResult } from "../../core/resolver/symbol-locator.ts";
7
+ import { isIgnoredDirectory } from "../../core/resources/ignore.ts";
8
8
  import { retrieveContext } from "../../core/retrieval/context.ts";
9
- import { symbolWorkspace } from "../../core/retrieval/symbol-evidence.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";
10
20
 
11
- 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
+ }
12
45
 
13
46
  export async function handleSymbolTool(
14
47
  repo: SeptumRepository,
@@ -19,24 +52,43 @@ export async function handleSymbolTool(
19
52
  signal?: AbortSignal
20
53
  ) {
21
54
  const action = args.action || "locate";
55
+ const format = args.format ?? "text";
22
56
 
23
57
  switch (action) {
24
58
  case "context":
25
59
  case "inspect": {
26
- const symbol = args.symbol_ref?.name || args.symbol || args.query || "";
27
- const candidates = repo.findSymbolsByName(symbol, {
28
- domain: args.domain, filePath: args.file_path, reference: args.symbol_ref,
29
- });
30
- const targetPath = candidates.length === 1 ? candidates[0]!.file_path : args.symbol_ref?.file_path || args.file_path;
31
- const bounded = args.context_mode === "source" || args.include_source !== undefined || args.source_start_line !== undefined || args.source_line_limit !== undefined;
32
- if (args.context_mode === "deep" || !bounded && (!targetPath || /\.(?:ts|mts|cts)$/.test(targetPath))) {
33
- return retrieveContext(repo, config, args, symbolWorkspace(repo, workspaceRoot || args.workspace_path), signal);
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
+ };
34
74
  }
35
- if (args.continuation !== undefined || args.budget_bytes !== undefined) {
36
- return { content: [{ type: "text" as const, text: JSON.stringify({
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 = {
37
81
  status: "invalid_context_options",
38
82
  message: "budget_bytes and continuation apply to deep TypeScript context. For bounded source use source_start_line and source_line_limit.",
39
- }) }] };
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
+ };
40
92
  }
41
93
  return handleGetSymbol(
42
94
  repo,
@@ -51,7 +103,9 @@ export async function handleSymbolTool(
51
103
  include_source: args.include_source ?? true,
52
104
  source_start_line: args.source_start_line,
53
105
  source_line_limit: args.source_line_limit,
106
+ budget_bytes: args.budget_bytes,
54
107
  semantic_depth: args.semantic_depth,
108
+ format,
55
109
  workspace_path: args.workspace_path,
56
110
  },
57
111
  workspaceRoot
@@ -69,6 +123,7 @@ export async function handleSymbolTool(
69
123
  domain: args.domain,
70
124
  file_path: args.file_path,
71
125
  symbol_ref: args.symbol_ref,
126
+ format,
72
127
  workspace_path: args.workspace_path,
73
128
  },
74
129
  workspaceRoot
@@ -86,6 +141,7 @@ export async function handleSymbolTool(
86
141
  file_path: args.file_path,
87
142
  symbol_ref: args.symbol_ref,
88
143
  limit: args.limit ?? 10,
144
+ format,
89
145
  workspace_path: args.workspace_path,
90
146
  },
91
147
  pipeline,
@@ -93,3 +149,399 @@ export async function handleSymbolTool(
93
149
  );
94
150
  }
95
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
+ }