@dimassetoid/septum-mcp 0.0.0-stage → 0.3.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,399 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import { existsSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { computeContentHash } from "../../core/ingestion/hasher.ts";
6
+ import { isPathContained } from "../../core/resolver/path-resolver.ts";
7
+ import { readSourceFile } from "../../core/resources/source-files.ts";
8
+ import { SymbolLocator } from "../../core/resolver/symbol-locator.ts";
9
+ import type { GetSymbolArgs } from "../../types/index.ts";
10
+ import { symbolWorkspace, withSymbolEvidence } from "../../core/retrieval/symbol-evidence.ts";
11
+
12
+ export function handleGetSymbol(
13
+ repo: SeptumRepository,
14
+ config: ValidatedSeptumConfig,
15
+ args: GetSymbolArgs,
16
+ workspaceRoot?: string
17
+ ) {
18
+ const root = symbolWorkspace(repo, workspaceRoot || args.workspace_path);
19
+ return withSymbolEvidence(repo, root, { operation: "inspect", requested: args.symbol_ref },
20
+ () => inspectSymbol(repo, config, args, root));
21
+ }
22
+
23
+ function inspectSymbol(
24
+ repo: SeptumRepository,
25
+ _config: ValidatedSeptumConfig,
26
+ args: GetSymbolArgs,
27
+ workspaceRoot?: string
28
+ ) {
29
+ const symbol = (args.symbol_ref?.name || args.symbol || (args as unknown as Record<string, unknown>).query || "").toString().trim();
30
+ if (!symbol) {
31
+ throw new Error(
32
+ "Missing required argument: 'symbol' (e.g. 'OrderController::cancelOrder', 'OrderService', or 'cancelOrder')"
33
+ );
34
+ }
35
+
36
+ if (args.symbol_ref) {
37
+ const file = repo.getFileByPath(args.symbol_ref.file_path);
38
+ if (!file || file.content_hash !== args.symbol_ref.indexed_content_hash) {
39
+ return { content: [{ type: "text" as const, text: JSON.stringify({
40
+ symbol, status: "stale_reference", found: false,
41
+ message: "Declaration reference is stale; locate the symbol again.",
42
+ ...(args.include_source ? { source_slice: { status: "stale", reason: "stale_reference" } } : {}),
43
+ }) }] };
44
+ }
45
+ }
46
+ const selectedCandidates = repo.findSymbolsByName(symbol, {
47
+ domain: args.domain, filePath: args.file_path, reference: args.symbol_ref,
48
+ });
49
+ if (selectedCandidates.length > 1) {
50
+ const candidates = selectedCandidates.map(candidate => ({
51
+ name: candidate.name, file_path: candidate.file_path, kind: candidate.kind, signature: candidate.signature,
52
+ start_line: candidate.line_start, end_line: candidate.line_end, symbol_ref: candidate.symbol_ref,
53
+ }));
54
+ return { content: [{ type: "text" as const, text: JSON.stringify({
55
+ symbol, status: "ambiguous", found: false, candidates,
56
+ ...(args.include_source ? { source_slice: { status: "ambiguous", candidates } } : {}),
57
+ message: "Multiple matching declarations; select a candidate with symbol_ref or narrow with file_path.",
58
+ }, null, 2) }] };
59
+ }
60
+
61
+ const details = repo.getSymbolDetails(symbol, {
62
+ domain: args.domain,
63
+ filePath: args.file_path,
64
+ reference: args.symbol_ref,
65
+ // This inspection path reads the complete file for outbound-call inference; keep source requests bounded.
66
+ includeDependencies: args.include_source ? false : args.include_dependencies,
67
+ workspaceRoot: workspaceRoot || args.workspace_path,
68
+ });
69
+
70
+ if (details) {
71
+ const payload: Record<string, unknown> = { ...details, context_mode: "source" };
72
+ if (args.include_source === false) {
73
+ if (Array.isArray(payload.relationships)) {
74
+ const allRels = payload.relationships as Array<any>;
75
+ const maxRels = 20;
76
+ payload.relationships = allRels.slice(0, maxRels).map((edge) => ({
77
+ target: edge?.resolution?.source?.target ?? edge?.target,
78
+ line: edge?.source?.line ?? edge?.line,
79
+ status: edge?.resolution?.status,
80
+ reason: edge?.resolution?.reason,
81
+ resolved_files: Array.isArray(edge?.resolution?.targets)
82
+ ? edge.resolution.targets.flatMap((t: any) => t.files ?? [])
83
+ : [],
84
+ }));
85
+ if (allRels.length > maxRels) {
86
+ payload.relationships_omitted = allRels.length - maxRels;
87
+ }
88
+ }
89
+ if (Array.isArray(payload.connected_files) && payload.connected_files.length > 20) {
90
+ payload.connected_files_omitted = payload.connected_files.length - 20;
91
+ payload.connected_files = payload.connected_files.slice(0, 20);
92
+ }
93
+ }
94
+ if (args.include_source) {
95
+ delete payload.dependencies_injected;
96
+ delete payload.outbound_calls;
97
+ delete payload.resolved_outbound_calls;
98
+ delete payload.connected_files;
99
+ const root = resolve(workspaceRoot || args.workspace_path || process.cwd());
100
+ const file = repo.getFileByPath(details.file_path);
101
+ const fullPath = resolve(root, details.file_path);
102
+ if (!file) {
103
+ payload.source_slice = { status: "unavailable", file_path: details.file_path, reason: "file_not_indexed" };
104
+ } else if (!isPathContained(fullPath, root)) {
105
+ payload.source_slice = { status: "out_of_scope", file_path: details.file_path };
106
+ } else {
107
+ try {
108
+ const source = readSourceFile(fullPath);
109
+ const currentHash = computeContentHash(source);
110
+ if (currentHash !== file.content_hash) {
111
+ payload.source_slice = {
112
+ status: "stale",
113
+ file_path: details.file_path,
114
+ indexed_content_hash: file.content_hash,
115
+ current_content_hash: currentHash,
116
+ message: "File has been modified on disk since last indexed. Run 'septum sync' to synchronize AST coordinates.",
117
+ action_required: "septum sync",
118
+ };
119
+ } else {
120
+ const lineStarts = [0];
121
+ const lineEnds: number[] = [];
122
+ for (const match of source.matchAll(/\r\n|\n|\r/g)) {
123
+ const offset = match.index!;
124
+ lineEnds.push(offset);
125
+ lineStarts.push(offset + match[0].length);
126
+ }
127
+ lineEnds.push(source.length);
128
+ const startLine = args.source_start_line ?? details.exact_range.start_line;
129
+ const limit = Math.min(args.source_line_limit ?? 120, 200);
130
+ if (
131
+ startLine < details.exact_range.start_line ||
132
+ startLine > details.exact_range.end_line ||
133
+ startLine > lineStarts.length
134
+ ) {
135
+ payload.source_slice = {
136
+ status: "invalid_range",
137
+ file_path: details.file_path,
138
+ allowed_start_line: details.exact_range.start_line,
139
+ allowed_end_line: details.exact_range.end_line,
140
+ };
141
+ } else {
142
+ const endLine = Math.min(details.exact_range.end_line, startLine + limit - 1, lineStarts.length);
143
+ const truncated = endLine < details.exact_range.end_line;
144
+ const sliceText = source.slice(lineStarts[startLine - 1], lineEnds[endLine - 1]);
145
+ const lineCount = endLine - startLine + 1;
146
+
147
+ // 1-hop Transitive Delegator Expansion (Hollow Slicing Prevention)
148
+ let delegatedImpl: {
149
+ symbol: string;
150
+ file_path: string;
151
+ start_line: number;
152
+ end_line: number;
153
+ text: string;
154
+ } | undefined;
155
+
156
+ if (lineCount <= 15 || args.semantic_depth === 2) {
157
+ delegatedImpl = resolveDelegatorImplementation(
158
+ repo,
159
+ root,
160
+ source,
161
+ sliceText,
162
+ details
163
+ );
164
+ }
165
+
166
+ payload.source_slice = {
167
+ status: "current",
168
+ file_path: details.file_path,
169
+ indexed_content_hash: file.content_hash,
170
+ current_content_hash: currentHash,
171
+ start_line: startLine,
172
+ end_line: endLine,
173
+ text: sliceText,
174
+ truncated,
175
+ related_dependency_analysis: delegatedImpl ? "delegated_implementation_expanded" : "omitted_to_keep_source_read_bounded",
176
+ ...(delegatedImpl ? { delegated_implementation: delegatedImpl } : {}),
177
+ ...(truncated ? { next_start_line: endLine + 1 } : {}),
178
+ };
179
+ }
180
+ }
181
+ } catch (error) {
182
+ payload.source_slice = {
183
+ status: "unavailable",
184
+ file_path: details.file_path,
185
+ reason: error instanceof Error && error.name === "SourceFileLimitError"
186
+ ? "source_exceeds_read_limit"
187
+ : "source_unavailable",
188
+ };
189
+ }
190
+ }
191
+ }
192
+ return {
193
+ content: [
194
+ {
195
+ type: "text" as const,
196
+ text: JSON.stringify(payload, null, 2),
197
+ },
198
+ ],
199
+ };
200
+ }
201
+
202
+ // Fallback to fuzzy SymbolLocator to provide actionable hints
203
+ const locator = new SymbolLocator(repo);
204
+ const fallback = locator.locate(symbol, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
205
+
206
+ const payload = {
207
+ symbol,
208
+ found: false,
209
+ message: `Symbol '${symbol}' was not found in the deterministic catalog.`,
210
+ suggestions: fallback.suggestions.map((s) => ({
211
+ name: s.name,
212
+ similarity_score: Math.round(s.similarity_score * 100) / 100,
213
+ exact_range: {
214
+ start_line: s.line_start,
215
+ end_line: s.line_end,
216
+ total_lines: s.line_end - s.line_start + 1,
217
+ },
218
+ signature: s.signature,
219
+ file_path: s.file_path,
220
+ })),
221
+ sibling_methods: fallback.sibling_methods,
222
+ ...(args.include_source ? { source_slice: { status: "unavailable", reason: "symbol_not_found" } } : {}),
223
+ };
224
+
225
+ return {
226
+ content: [
227
+ {
228
+ type: "text" as const,
229
+ text: JSON.stringify(payload, null, 2),
230
+ },
231
+ ],
232
+ };
233
+ }
234
+
235
+ function toPascalCase(identifier: string): string {
236
+ return identifier
237
+ .split("_")
238
+ .filter(Boolean)
239
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
240
+ .join("");
241
+ }
242
+
243
+ function resolveDelegatorImplementation(
244
+ repo: SeptumRepository,
245
+ root: string,
246
+ sourceCode: string,
247
+ sliceText: string,
248
+ details: any
249
+ ): { symbol: string; file_path: string; start_line: number; end_line: number; text: string } | undefined {
250
+ // 1. Check for PHP/TS/Python/Go delegator call patterns:
251
+ // $this->property->execute(...) or ->handle(...)
252
+ // this.property.execute(...) or .handle(...)
253
+ // self.property.execute(...) (Python)
254
+ // receiver.property.Execute(...) (Go)
255
+ // ClassName::execute(...) or ClassName::handle(...)
256
+ const phpPropMatch = /\$this->([a-zA-Z0-9_]+)\s*->\s*([a-zA-Z0-9_]+)\s*\(/i.exec(sliceText);
257
+ const tsPropMatch = /\bthis\.([a-zA-Z0-9_]+)\s*\.\s*([a-zA-Z0-9_]+)\s*\(/i.exec(sliceText);
258
+ const pySelfMatch = /\bself\.([a-zA-Z0-9_]+)\s*\.\s*([a-zA-Z0-9_]+)\s*\(/i.exec(sliceText);
259
+ const staticMatch = /([A-Z][a-zA-Z0-9_]*(?:Action|Service|Handler|UseCase))::([a-zA-Z0-9_]+)\s*\(/i.exec(sliceText);
260
+ const goRecvSigMatch = /^func\s*\(\s*([a-zA-Z_]\w*)\s+\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)/m.exec(
261
+ details?.signature || sliceText
262
+ );
263
+
264
+ let targetClassName: string | undefined;
265
+ let targetMethodName: string | undefined;
266
+
267
+ if (phpPropMatch) {
268
+ const propName = phpPropMatch[1];
269
+ targetMethodName = phpPropMatch[2];
270
+
271
+ const ctorPropRegex = new RegExp(
272
+ `(?:protected|private|public)\\s+(?:readonly\\s+)?(?:\\\\?[A-Za-z0-9_\\\\]+\\\\)?([A-Z][A-Za-z0-9_]*)\\s+\\\$${propName}\\b`,
273
+ "i"
274
+ );
275
+ const ctorMatch = ctorPropRegex.exec(sourceCode);
276
+ if (ctorMatch) {
277
+ targetClassName = ctorMatch[1];
278
+ } else {
279
+ targetClassName = toPascalCase(propName);
280
+ }
281
+ } else if (tsPropMatch) {
282
+ const propName = tsPropMatch[1];
283
+ targetMethodName = tsPropMatch[2];
284
+ const tsPropRegex = new RegExp(`(?:private|protected|public|readonly)\\s+${propName}\\s*:\\s*([A-Z][A-Za-z0-9_]*)`, "i");
285
+ const tsMatch = tsPropRegex.exec(sourceCode);
286
+ if (tsMatch) {
287
+ targetClassName = tsMatch[1];
288
+ } else {
289
+ targetClassName = toPascalCase(propName);
290
+ }
291
+ } else if (pySelfMatch) {
292
+ const propName = pySelfMatch[1];
293
+ targetMethodName = pySelfMatch[2];
294
+ // Check `self.prop = param` in `__init__` or direct `prop: TypeName` type annotation
295
+ const assignMatch = new RegExp(`\\bself\\.${propName}\\s*=\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\b`).exec(sourceCode);
296
+ const paramName = assignMatch ? assignMatch[1] : propName;
297
+ const typeHintRegex = new RegExp(`\\b(?:self\\.)?${paramName}\\s*:\\s*(?:[a-zA-Z0-9_]+\\.)?([A-Z][A-Za-z0-9_]*)\\b`);
298
+ const pyMatch = typeHintRegex.exec(sourceCode);
299
+ if (pyMatch) {
300
+ targetClassName = pyMatch[1];
301
+ } else {
302
+ targetClassName = toPascalCase(propName);
303
+ }
304
+ } else if (goRecvSigMatch) {
305
+ const recvVar = goRecvSigMatch[1];
306
+ const goPropRegex = new RegExp(`\\b${recvVar}\\.([a-zA-Z_]\\w*)\\s*\\.\\s*([a-zA-Z_]\\w*)\\s*\\(`);
307
+ const goCallMatch = goPropRegex.exec(sliceText);
308
+ if (goCallMatch) {
309
+ const propName = goCallMatch[1];
310
+ targetMethodName = goCallMatch[2];
311
+ const fieldTypeRegex = new RegExp(`\\b${propName}\\s+\\*?(?:[a-zA-Z0-9_]+\\.)?([A-Z][A-Za-z0-9_]*)\\b`);
312
+ const fieldMatch = fieldTypeRegex.exec(sourceCode);
313
+ if (fieldMatch) {
314
+ targetClassName = fieldMatch[1];
315
+ } else {
316
+ targetClassName = toPascalCase(propName);
317
+ }
318
+ }
319
+ } else if (staticMatch) {
320
+ targetClassName = staticMatch[1];
321
+ targetMethodName = staticMatch[2];
322
+ }
323
+
324
+ if (!targetClassName || !targetMethodName) return undefined;
325
+
326
+ const candidateQueries = [
327
+ `${targetClassName}::${targetMethodName}`,
328
+ `${targetClassName}@${targetMethodName}`,
329
+ targetMethodName,
330
+ ];
331
+
332
+ let targetSymbol: any = undefined;
333
+ for (const q of candidateQueries) {
334
+ const matches = repo.findSymbolsByName(q);
335
+ const exact = matches.find(
336
+ (m) =>
337
+ (m.name.includes(targetClassName!) ||
338
+ m.symbol_ref?.container === targetClassName ||
339
+ m.symbol_ref?.receiver === targetClassName) &&
340
+ (m.name.endsWith(`::${targetMethodName}`) ||
341
+ m.name.endsWith(`@${targetMethodName}`) ||
342
+ m.name === targetMethodName)
343
+ );
344
+ if (exact) {
345
+ targetSymbol = exact;
346
+ break;
347
+ }
348
+ if (q !== targetMethodName && matches.length === 1) {
349
+ targetSymbol = matches[0];
350
+ break;
351
+ }
352
+ }
353
+
354
+ if (!targetSymbol) {
355
+ const classMatches = repo.findSymbolsByName(targetClassName);
356
+ if (classMatches.length >= 1) {
357
+ const cls = classMatches[0];
358
+ const fileSymbols = repo.getSymbolsByFileId(cls.file_id);
359
+ const methodSym = fileSymbols.find(s => s.kind === "method" && (s.name.endsWith(`::${targetMethodName}`) || s.name.endsWith(`@${targetMethodName}`) || s.name === targetMethodName));
360
+ if (methodSym) {
361
+ targetSymbol = { ...methodSym, file_path: cls.file_path };
362
+ }
363
+ }
364
+ }
365
+
366
+ if (!targetSymbol || !targetSymbol.file_path) return undefined;
367
+
368
+ if (targetSymbol.file_path === details.file_path && targetSymbol.line_start === details.exact_range.start_line) {
369
+ return undefined;
370
+ }
371
+
372
+ try {
373
+ const targetFullPath = resolve(root, targetSymbol.file_path);
374
+ if (!existsSync(targetFullPath)) return undefined;
375
+ const targetSource = readSourceFile(targetFullPath);
376
+ const targetStarts = [0];
377
+ const targetEnds: number[] = [];
378
+ for (const match of targetSource.matchAll(/\r\n|\n|\r/g)) {
379
+ targetEnds.push(match.index!);
380
+ targetStarts.push(match.index! + match[0].length);
381
+ }
382
+ targetEnds.push(targetSource.length);
383
+
384
+ const tStart = targetSymbol.line_start;
385
+ const tEnd = Math.min(targetSymbol.line_end, targetStarts.length);
386
+ if (tStart > targetStarts.length || tEnd < tStart) return undefined;
387
+
388
+ const targetText = targetSource.slice(targetStarts[tStart - 1], targetEnds[tEnd - 1]);
389
+ return {
390
+ symbol: targetSymbol.name,
391
+ file_path: targetSymbol.file_path,
392
+ start_line: tStart,
393
+ end_line: tEnd,
394
+ text: targetText,
395
+ };
396
+ } catch {
397
+ return undefined;
398
+ }
399
+ }
@@ -0,0 +1,236 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { isIgnoredDirectory } from "../../core/resources/ignore.ts";
4
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
5
+ import type { SeptumRepository } from "../../core/database/repository.ts";
6
+ import type { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
7
+ import {
8
+ SymbolLocator,
9
+ type SymbolLocationResult,
10
+ } from "../../core/resolver/symbol-locator.ts";
11
+ import type { LocateSymbolArgs } from "../schemas.ts";
12
+ import { symbolWorkspace, withSymbolEvidence } from "../../core/retrieval/symbol-evidence.ts";
13
+
14
+ export type { LocateSymbolArgs } from "../schemas.ts";
15
+
16
+ export async function handleLocateSymbol(
17
+ repo: SeptumRepository,
18
+ config: ValidatedSeptumConfig,
19
+ args: Partial<LocateSymbolArgs>,
20
+ pipeline?: IngestionPipeline,
21
+ workspaceRoot?: string
22
+ ) {
23
+ const query = (args.query || args.symbol || args.symbol_ref?.name || "").toString().trim();
24
+ const root = symbolWorkspace(repo, workspaceRoot || args.workspace_path);
25
+ const diagnostics: string[] = [];
26
+ const limit = args.limit ?? 10;
27
+
28
+ if (!query) {
29
+ if (args.file_path) {
30
+ const normalizedPath = args.file_path.replace(/\\/g, "/").replace(/^\.\//, "");
31
+ const file = repo.getFileByPath(normalizedPath);
32
+ const allSymbols = file ? repo.getSymbolsByFileId(file.id) : [];
33
+ const sliced = allSymbols.slice(0, limit).map((s) => ({
34
+ name: s.name,
35
+ file_path: normalizedPath,
36
+ kind: s.kind,
37
+ signature: s.signature,
38
+ start_line: s.line_start,
39
+ end_line: s.line_end,
40
+ }));
41
+ const filePayload = {
42
+ status: sliced.length > 0 ? "success" : "not_found",
43
+ found: sliced.length > 0,
44
+ query: null,
45
+ file_path: normalizedPath,
46
+ candidates: sliced,
47
+ total_candidates: allSymbols.length,
48
+ omitted_candidates: Math.max(0, allSymbols.length - sliced.length),
49
+ summary: sliced.length > 0
50
+ ? `[FOUND] Listed ${sliced.length} of ${allSymbols.length} declarations in ${normalizedPath}.`
51
+ : `[NOT FOUND] No indexed declarations found in '${normalizedPath}'.`,
52
+ };
53
+ return withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
54
+ content: [{ type: "text" as const, text: JSON.stringify(filePayload, null, 2) }],
55
+ metadata: filePayload,
56
+ }));
57
+ }
58
+ throw new Error(
59
+ "Missing required argument: 'query' (e.g. 'OrderController::calculateTotal' or error log snippet)"
60
+ );
61
+ }
62
+
63
+ // 1. Guarded Lazy Ingestion on Empty Catalog / Cold Start
64
+ if (repo.countFiles() === 0 && pipeline) {
65
+ try {
66
+ await pipeline.run(config);
67
+ } catch {
68
+ diagnostics.push("initial_index_refresh_failed");
69
+ }
70
+
71
+ if (repo.countFiles() === 0) {
72
+ const diagnostic = {
73
+ status: "NOT_INDEXED",
74
+ found: false,
75
+ query,
76
+ message: `Workspace '${root}' belum terindeks dalam Septum catalog.`,
77
+ suggested_action: {
78
+ tool: "septum_map",
79
+ params: { action: "register", name: "core", root: "src", ingest_now: true },
80
+ },
81
+ agent_guidance:
82
+ "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.",
83
+ };
84
+
85
+ return withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
86
+ content: [
87
+ {
88
+ type: "text",
89
+ text: JSON.stringify(diagnostic, null, 2),
90
+ },
91
+ ],
92
+ metadata: diagnostic,
93
+ }));
94
+ }
95
+ }
96
+
97
+ const locator = new SymbolLocator(repo);
98
+ let result: SymbolLocationResult = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
99
+
100
+ // 2. JIT Delta Sync: Check if located file has changed on disk since last ingest
101
+ if (result.found && result.file_path && pipeline) {
102
+ const fullPath = isAbsolute(result.file_path)
103
+ ? result.file_path
104
+ : join(root, result.file_path);
105
+ try {
106
+ const reindexed = await pipeline.ingestFile(fullPath, config);
107
+ if (reindexed) {
108
+ result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
109
+ }
110
+ } catch {
111
+ diagnostics.push("target_index_refresh_failed");
112
+ }
113
+ }
114
+
115
+ // 3. Fallback on Cache Miss: Search for candidate source files matching the query terms
116
+ if (!result.found && pipeline) {
117
+ try {
118
+ const cleanTerm = query.replace(/[^a-zA-Z0-9_]/g, " ").trim().split(/\s+/)[0] || "";
119
+ if (cleanTerm.length >= 3) {
120
+ const candidateFiles = findCandidateFiles(root, cleanTerm);
121
+ let anyReindexed = false;
122
+ for (const candidate of candidateFiles) {
123
+ const reindexed = await pipeline.ingestFile(candidate, config);
124
+ if (reindexed) anyReindexed = true;
125
+ }
126
+ if (anyReindexed) {
127
+ result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
128
+ }
129
+ }
130
+ } catch {
131
+ diagnostics.push("candidate_refresh_failed");
132
+ }
133
+ }
134
+
135
+ const exactLineCount = result.exact_symbol
136
+ ? result.exact_symbol.line_end - result.exact_symbol.line_start + 1
137
+ : 0;
138
+ const complexitySmell =
139
+ exactLineCount > 300
140
+ ? {
141
+ is_high_complexity: true,
142
+ threshold: 300,
143
+ total_lines: exactLineCount,
144
+ warning: `Symbol '${result.exact_symbol?.name}' spans ${exactLineCount} lines (exceeds 300-line threshold). Candidate for decomposition/refactoring.`,
145
+ }
146
+ : undefined;
147
+
148
+ const suggestions = (result.suggestions || []).slice(0, limit);
149
+ let summary = result.status === "ambiguous"
150
+ ? `[AMBIGUOUS] Multiple declarations match '${query}'; select a candidate with symbol_ref or file_path.`
151
+ : result.status === "stale_reference"
152
+ ? `[STALE REFERENCE] Locate '${query}' again before using its indexed coordinates.`
153
+ : result.found
154
+ ? `[FOUND] ${result.exact_symbol?.name || query} in ${result.file_path} (lines ${result.exact_symbol?.line_start}-${result.exact_symbol?.line_end})`
155
+ : `[NOT FOUND] Symbol '${query}' not found. ${suggestions.length > 0 ? `Top suggestions: ${suggestions.map((s) => s.name).slice(0, 3).join(", ")}` : "No close suggestions."}`;
156
+
157
+ if (complexitySmell) {
158
+ summary += ` | ⚠️ High-Complexity Smell: spans ${exactLineCount} lines (> 300L)`;
159
+ }
160
+
161
+ const allCandidates = result.candidates || [];
162
+ const boundedCandidates = allCandidates.slice(0, limit);
163
+ const payload = {
164
+ status: result.status ?? (result.found ? "success" : "not_found"),
165
+ candidates: result.candidates ? boundedCandidates : undefined,
166
+ ...(allCandidates.length > boundedCandidates.length
167
+ ? { total_candidates: allCandidates.length, omitted_candidates: allCandidates.length - boundedCandidates.length }
168
+ : {}),
169
+ symbol_ref: result.symbol_ref,
170
+ visibility_semantics: "legacy_normalized",
171
+ found: result.found,
172
+ query,
173
+ file_path: result.file_path || null,
174
+ container_name: result.container_name || null,
175
+ exact_symbol: result.exact_symbol
176
+ ? {
177
+ ...result.exact_symbol,
178
+ total_lines: exactLineCount,
179
+ }
180
+ : null,
181
+ complexity_smell: complexitySmell,
182
+ sibling_methods: result.sibling_methods || [],
183
+ suggestions,
184
+ summary,
185
+ message: result.message || summary,
186
+ };
187
+
188
+ return withSymbolEvidence(repo, root, { operation: "locate", requested: args.symbol_ref, diagnostics }, () => ({
189
+ content: [
190
+ {
191
+ type: "text" as const,
192
+ text: JSON.stringify(payload, null, 2),
193
+ },
194
+ ],
195
+ metadata: payload,
196
+ }));
197
+ }
198
+
199
+ /**
200
+ * Searches for potential candidate files whose names resemble parts of the query term.
201
+ */
202
+ function findCandidateFiles(root: string, term: string): string[] {
203
+ const matched: string[] = [];
204
+ const lowerTerm = term.toLowerCase().replace(/_/g, "");
205
+ const searchDirs = ["src", "app", "lib"].map((d) => join(root, d)).filter((d) => existsSync(d));
206
+
207
+ function scan(dir: string, depth: number = 0) {
208
+ if (depth > 4) return;
209
+ try {
210
+ const entries = readdirSync(dir, { withFileTypes: true });
211
+ for (const e of entries) {
212
+ if (isIgnoredDirectory(e.name)) continue;
213
+ const full = join(dir, e.name);
214
+ if (e.isDirectory()) {
215
+ scan(full, depth + 1);
216
+ } else if (e.isFile() && /\.(ts|tsx|js|jsx|php|py|go)$/i.test(e.name)) {
217
+ const lowerName = e.name.toLowerCase().replace(/[-_.]/g, "");
218
+ if (lowerName.includes(lowerTerm) || lowerTerm.includes(lowerName.replace(/\.[^.]+$/, ""))) {
219
+ matched.push(full);
220
+ if (matched.length >= 5) return;
221
+ }
222
+ }
223
+ }
224
+ } catch {
225
+ // Ignore
226
+ }
227
+ }
228
+
229
+ for (const sDir of searchDirs) {
230
+ scan(sDir);
231
+ if (matched.length >= 5) break;
232
+ }
233
+
234
+ return matched;
235
+ }
236
+
@@ -0,0 +1,26 @@
1
+ import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
+ import type { SeptumRepository } from "../../core/database/repository.ts";
3
+ import type { MapToolArgs } from "../schemas.ts";
4
+ import { handleGetDomainCatalog } from "./get-domain-catalog.ts";
5
+ import { handleRegisterDomain } from "./register-domain.ts";
6
+
7
+ export type { MapToolArgs };
8
+
9
+ export async function handleMapTool(
10
+ repo: SeptumRepository,
11
+ config: ValidatedSeptumConfig,
12
+ args: MapToolArgs,
13
+ workspaceRoot?: string,
14
+ signal?: AbortSignal
15
+ ) {
16
+ const action = args.action || "catalog";
17
+
18
+ switch (action) {
19
+ case "register":
20
+ return await handleRegisterDomain(repo, config, args, workspaceRoot, signal);
21
+
22
+ case "catalog":
23
+ default:
24
+ return handleGetDomainCatalog(repo, config, args, workspaceRoot);
25
+ }
26
+ }