@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,276 @@
1
+ import { symbolReference } from "./symbol-reference.ts";
2
+ import type { SymbolReference, SymbolSelectionOptions } from "../../types/index.ts";
3
+ import type { SymbolKind } from "../database/repository.ts";
4
+ import type { SeptumRepository } from "../database/repository.ts";
5
+
6
+ export interface ParsedSymbolQuery {
7
+ raw: string;
8
+ container?: string; // e.g. "OrderController" or "App\\Http\\Controllers\\OrderController"
9
+ member?: string; // e.g. "calculateTotal"
10
+ kind?: SymbolKind;
11
+ }
12
+
13
+ export interface SuggestionMatch {
14
+ name: string;
15
+ kind: string;
16
+ signature: string;
17
+ line_start: number;
18
+ line_end: number;
19
+ similarity_score: number; // 0.0 - 1.0
20
+ file_path?: string;
21
+ }
22
+
23
+ export interface SymbolLocationResult {
24
+ query: string;
25
+ parsed: ParsedSymbolQuery;
26
+ found: boolean;
27
+ status?: "ambiguous" | "stale_reference";
28
+ candidates?: Array<{ name: string; file_path: string; signature: string; symbol_ref: SymbolReference }>;
29
+ symbol_ref?: SymbolReference;
30
+ file_path?: string;
31
+ container_name?: string;
32
+ exact_symbol?: {
33
+ name: string;
34
+ kind: string;
35
+ signature: string;
36
+ visibility: string;
37
+ line_start: number;
38
+ line_end: number;
39
+ };
40
+ sibling_methods?: string[];
41
+ suggestions: SuggestionMatch[];
42
+ message: string;
43
+ }
44
+
45
+ export class SymbolLocator {
46
+ constructor(private repo: SeptumRepository) {}
47
+
48
+ /**
49
+ * Parse error log strings, method call syntax, or symbol names into container & member.
50
+ * Examples:
51
+ * - "Method OrderController::calculateTotal() does not exist"
52
+ * - "Call to undefined method App\\Http\\Controllers\\OrderController::calculateTotal()"
53
+ * - "OrderController->calculateTotal()"
54
+ * - "OrderController.calculateTotal"
55
+ * - "OrderController"
56
+ * - "calculateTotal"
57
+ */
58
+ public parseQuery(rawQuery: string): ParsedSymbolQuery {
59
+ const trimmed = rawQuery.trim();
60
+
61
+ // 1. Error string matching: "Method X::y() does not exist" or "Call to undefined method X::y()"
62
+ const methodNotExistMatch = trimmed.match(/(?:Method|method)\s+([A-Za-z0-9_\\\/\.]+)::([A-Za-z0-9_]+)\s*\(\)?/i);
63
+ if (methodNotExistMatch) {
64
+ return {
65
+ raw: trimmed,
66
+ container: methodNotExistMatch[1],
67
+ member: methodNotExistMatch[2],
68
+ kind: "method",
69
+ };
70
+ }
71
+
72
+ // 2. Python / JS error: "'X' object has no attribute 'y'"
73
+ const pyAttrMatch = trimmed.match(/['"]?([A-Za-z0-9_]+)['"]?\s+object has no attribute\s+['"]?([A-Za-z0-9_]+)['"]?/i);
74
+ if (pyAttrMatch) {
75
+ return {
76
+ raw: trimmed,
77
+ container: pyAttrMatch[1],
78
+ member: pyAttrMatch[2],
79
+ };
80
+ }
81
+
82
+ // 3. Class::member or Class->member or Class.member
83
+ const staticCallMatch = trimmed.match(/^([A-Za-z0-9_\\\/\.]+)::([A-Za-z0-9_]+)(?:\(\))?$/);
84
+ if (staticCallMatch) {
85
+ return {
86
+ raw: trimmed,
87
+ container: staticCallMatch[1],
88
+ member: staticCallMatch[2],
89
+ kind: "method",
90
+ };
91
+ }
92
+
93
+ const arrowCallMatch = trimmed.match(/^([A-Za-z0-9_\\\/\.]+)->([A-Za-z0-9_]+)(?:\(\))?$/);
94
+ if (arrowCallMatch) {
95
+ return {
96
+ raw: trimmed,
97
+ container: arrowCallMatch[1],
98
+ member: arrowCallMatch[2],
99
+ kind: "method",
100
+ };
101
+ }
102
+
103
+ const dotCallMatch = trimmed.match(/^([A-Za-z0-9_]+)\.([A-Za-z0-9_]+)(?:\(\))?$/);
104
+ if (dotCallMatch) {
105
+ return {
106
+ raw: trimmed,
107
+ container: dotCallMatch[1],
108
+ member: dotCallMatch[2],
109
+ };
110
+ }
111
+
112
+ // 4. Function call: "calculateTotal()"
113
+ const funcMatch = trimmed.match(/^([A-Za-z0-9_]+)\(\)$/);
114
+ if (funcMatch) {
115
+ return {
116
+ raw: trimmed,
117
+ member: funcMatch[1],
118
+ kind: "function",
119
+ };
120
+ }
121
+
122
+ // 5. Bare word: could be class or function
123
+ return {
124
+ raw: trimmed,
125
+ member: trimmed,
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Locate the symbol or diagnostic resolution in the database.
131
+ */
132
+ public locate(rawQuery: string, domainFilter?: string, options: SymbolSelectionOptions = {}): SymbolLocationResult {
133
+ const parsed = this.parseQuery(rawQuery);
134
+ const selection = { ...options, domain: domainFilter ?? options.domain };
135
+ const base = { query: parsed.raw, parsed, found: false, suggestions: [] };
136
+ if (selection.reference) {
137
+ const file = this.repo.getFileByPath(selection.reference.file_path);
138
+ if (!file || file.content_hash !== selection.reference.indexed_content_hash) {
139
+ return { ...base, status: "stale_reference", message: "Declaration reference is stale; locate the symbol again." };
140
+ }
141
+ }
142
+ const container = parsed.container?.split(/\\|\//).pop();
143
+ const qualified = parsed.raw === `${parsed.container}.${parsed.member}` ? parsed.raw : `${container}::${parsed.member}`;
144
+ const query = selection.reference?.name ?? (container ? qualified : parsed.member ?? parsed.raw);
145
+ const candidates = this.repo.findSymbolsByName(query, selection);
146
+ if (candidates.length > 1) {
147
+ return {
148
+ ...base, status: "ambiguous",
149
+ candidates: candidates.map(c => ({ name: c.name, file_path: c.file_path, signature: c.signature, symbol_ref: c.symbol_ref })),
150
+ message: "Multiple matching declarations; select a candidate with symbol_ref.",
151
+ };
152
+ }
153
+ if (candidates.length === 1) {
154
+ const exact = candidates[0]!;
155
+ const details = this.repo.getSymbolDetails(exact.name, { ...selection, reference: exact.symbol_ref, includeDependencies: false });
156
+ return {
157
+ ...base, found: true, file_path: exact.file_path, container_name: exact.symbol_ref.container,
158
+ symbol_ref: exact.symbol_ref,
159
+ exact_symbol: { name: exact.name, kind: exact.kind, signature: exact.signature, visibility: exact.visibility, line_start: exact.line_start, line_end: exact.line_end },
160
+ sibling_methods: details?.sibling_methods,
161
+ message: `Found exact symbol '${exact.name}' in ${exact.file_path}:${exact.line_start}`,
162
+ };
163
+ }
164
+ const target = parsed.member ?? parsed.raw;
165
+ const owners = container ? this.repo.findSymbolsByName(container, selection)
166
+ .filter(s => ["class", "interface", "trait", "struct", "enum"].includes(s.kind)) : [];
167
+ const owner = owners.length === 1 ? owners[0] : undefined;
168
+ const siblings = owner ? this.repo.getSymbolDetails(owner.name, { ...selection, reference: owner.symbol_ref, includeDependencies: false })?.sibling_methods : undefined;
169
+ const searchable = owner ? this.repo.getSymbolsByFileId(owner.file_id)
170
+ .filter(s => s.kind === "method" && symbolReference({ ...s, file_path: owner.file_path, indexed_content_hash: owner.indexed_content_hash }).container === owner.name)
171
+ .map(s => ({ ...s, file_path: owner.file_path })) : this.repo.getAllSymbolsWithFiles();
172
+ const domainId = selection.domain ? this.repo.getAllDomains().find(d => d.name.toLowerCase() === selection.domain!.toLowerCase())?.id : undefined;
173
+ const suggestions = searchable
174
+ .filter(s => !selection.filePath || s.file_path === selection.filePath)
175
+ .filter(s => !selection.domain || this.repo.getFileByPath(s.file_path)?.domain_id === domainId)
176
+ .map(s => ({
177
+ name: owner ? s.name.split(/::|[.#]/).pop()! : s.name, kind: s.kind, signature: s.signature, line_start: s.line_start, line_end: s.line_end, file_path: s.file_path,
178
+ similarity_score: Math.round(Math.max(calculateSimilarity(target, s.name.split(/::|[.#]/).pop()!), calculateSimilarity(parsed.raw, s.name)) * 100) / 100,
179
+ }))
180
+ .filter(s => s.similarity_score >= 0.3)
181
+ .sort((a, b) => b.similarity_score - a.similarity_score).slice(0, 10);
182
+ return { ...base, file_path: owner?.file_path, container_name: owner?.name, sibling_methods: siblings, suggestions, message: `Symbol '${parsed.raw}' not found.${suggestions.length ? ` Did you mean '${suggestions[0]!.name}'?` : ""}` };
183
+ }
184
+
185
+ }
186
+
187
+ /**
188
+ * Enhanced similarity matching:
189
+ * Combines Damerau-Levenshtein distance (handling typos & transpositions),
190
+ * prefix/suffix matching, substring inclusion, and token Jaccard similarity.
191
+ */
192
+ export function calculateSimilarity(source: string, target: string): number {
193
+ const s1 = source.toLowerCase();
194
+ const s2 = target.toLowerCase();
195
+
196
+ if (s1 === s2) return 1.0;
197
+ if (!s1 || !s2) return 0.0;
198
+
199
+ // Prefix bonus: highly relevant for autocomplete-style / partial searches
200
+ let prefixBonus = 0;
201
+ if (s2.startsWith(s1) || s1.startsWith(s2)) {
202
+ const minLen = Math.min(s1.length, s2.length);
203
+ const maxLen = Math.max(s1.length, s2.length);
204
+ prefixBonus = 0.25 * (minLen / maxLen);
205
+ }
206
+
207
+ // Substring inclusion bonus
208
+ let substringBonus = 0;
209
+ if (s2.includes(s1) || s1.includes(s2)) {
210
+ const minLen = Math.min(s1.length, s2.length);
211
+ const maxLen = Math.max(s1.length, s2.length);
212
+ substringBonus = 0.3 * (minLen / maxLen);
213
+ }
214
+
215
+ // Token-based matching (CamelCase, snake_case, kebab-case, namespaces)
216
+ const tokenize = (str: string) =>
217
+ str
218
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
219
+ .toLowerCase()
220
+ .split(/[\s_\-\.\:\/\\]+/)
221
+ .filter((t) => t.length > 1);
222
+
223
+ const t1 = tokenize(source);
224
+ const t2 = tokenize(target);
225
+ let tokenBonus = 0;
226
+ if (t1.length > 0 && t2.length > 0) {
227
+ const sharedTokens = t1.filter((token) =>
228
+ t2.some((t) => t.includes(token) || token.includes(t))
229
+ );
230
+ const allUniqueTokens = new Set([...t1, ...t2]);
231
+ const jaccard = sharedTokens.length / (allUniqueTokens.size || 1);
232
+ tokenBonus = jaccard * 0.35;
233
+ }
234
+
235
+ // Damerau-Levenshtein Matrix
236
+ const len1 = s1.length;
237
+ const len2 = s2.length;
238
+ const matrix: number[][] = [];
239
+
240
+ for (let i = 0; i <= len1; i++) {
241
+ matrix[i] = [i];
242
+ }
243
+ for (let j = 0; j <= len2; j++) {
244
+ matrix[0][j] = j;
245
+ }
246
+
247
+ for (let i = 1; i <= len1; i++) {
248
+ for (let j = 1; j <= len2; j++) {
249
+ const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
250
+ let minCost = Math.min(
251
+ matrix[i - 1][j] + 1, // deletion
252
+ matrix[i][j - 1] + 1, // insertion
253
+ matrix[i - 1][j - 1] + cost // substitution
254
+ );
255
+
256
+ // Transposition check (Damerau)
257
+ if (
258
+ i > 1 &&
259
+ j > 1 &&
260
+ s1[i - 1] === s2[j - 2] &&
261
+ s1[i - 2] === s2[j - 1]
262
+ ) {
263
+ minCost = Math.min(minCost, matrix[i - 2][j - 2] + 1);
264
+ }
265
+
266
+ matrix[i][j] = minCost;
267
+ }
268
+ }
269
+
270
+ const distance = matrix[len1][len2];
271
+ const maxLen = Math.max(len1, len2);
272
+ const rawSimilarity = 1.0 - distance / maxLen;
273
+
274
+ const totalScore = rawSimilarity + prefixBonus + substringBonus + tokenBonus;
275
+ return Math.min(1.0, Math.max(0.0, totalScore));
276
+ }
@@ -0,0 +1,53 @@
1
+ import type { SymbolRecord, SymbolReference } from "../../types/index.ts";
2
+ import { getLanguageCapability } from "../parser/language-capabilities.ts";
3
+
4
+ type IndexedSymbol = SymbolRecord & { file_path: string; indexed_content_hash: string };
5
+
6
+ export function symbolReference(symbol: IndexedSymbol): SymbolReference {
7
+ const language = getLanguageCapability(symbol.file_path)?.id ?? "unknown";
8
+ let receiver: string | undefined;
9
+ let container = symbol.name.match(/^(.*)(?:::|[.#])[^:.#]+$/)?.[1];
10
+ if (language === "go" && symbol.kind === "method") {
11
+ const receiverClause = symbol.signature.match(/^\s*func\s*\(([^)]+)\)/)?.[1]?.trim();
12
+ if (receiverClause) {
13
+ const typeMatch = receiverClause.match(/^(?:[a-zA-Z0-9_]+\s+)?(\*?[a-zA-Z0-9_]+(?:\[[^\]]*\])?)$/);
14
+ if (typeMatch) {
15
+ receiver = typeMatch[1];
16
+ } else {
17
+ const spaceIdx = receiverClause.indexOf(" ");
18
+ receiver = spaceIdx !== -1 ? receiverClause.slice(spaceIdx + 1).trim() : receiverClause;
19
+ }
20
+ container = receiver?.replace(/^\*/, "").replace(/\[.*\]$/, "");
21
+ }
22
+ }
23
+ return {
24
+ file_path: symbol.file_path, language, name: symbol.name, kind: symbol.kind,
25
+ signature: symbol.signature, start_line: symbol.line_start, end_line: symbol.line_end,
26
+ indexed_content_hash: symbol.indexed_content_hash,
27
+ ...(container ? { container } : {}), ...(receiver ? { receiver } : {}),
28
+ };
29
+ }
30
+
31
+ export function matchesSymbolName(symbol: IndexedSymbol, query: string): boolean {
32
+ const ref = symbolReference(symbol);
33
+ const normalize = (name: string) => {
34
+ const plain = name.replace(/\(\)$/, "");
35
+ return ref.language === "ruby" ? plain : plain.replace(/->|[.#]/g, "::");
36
+ };
37
+ const target = normalize(query);
38
+ const name = normalize(symbol.name);
39
+ if (name === target || name.endsWith(`::${target}`) || name.endsWith(`\\${target}`)) return true;
40
+ if (!/::|[.#\\]/.test(target) && name.split(/::|[.#\\]/).pop() === target) return true;
41
+ if (ref.receiver && ref.container) {
42
+ if (`${ref.container}::${name}` === target) return true;
43
+ if (`${ref.receiver}::${name}` === target || `(${ref.receiver})::${name}` === target) return true;
44
+ }
45
+ return false;
46
+ }
47
+
48
+ // shortcut: identical signatures/ranges on one line remain ambiguous; add persisted columns when exact column selection is needed.
49
+ export function matchesSymbolReference(actual: SymbolReference, expected: SymbolReference): boolean {
50
+ return actual.file_path === expected.file_path && actual.name === expected.name && actual.kind === expected.kind
51
+ && actual.signature === expected.signature && actual.start_line === expected.start_line && actual.end_line === expected.end_line
52
+ && actual.indexed_content_hash === expected.indexed_content_hash && actual.language === expected.language;
53
+ }
@@ -0,0 +1,344 @@
1
+ import { rebuildSliceCatalog, sliceInputsCurrent } from "./slice-catalog.ts";
2
+ import { scanSourceFiles } from "../resources/source-inventory.ts";
3
+ import { relative } from "node:path";
4
+ import type {
5
+ ExecutionChainNode,
6
+ VerticalSliceRecord,
7
+ VerticalSliceTraceResponse,
8
+ } from "../../types/index.ts";
9
+ import type { SeptumRepository } from "../database/repository.ts";
10
+ import { CallGraphTracer } from "./call-graph-tracer.ts";
11
+ import { formatSliceNode, SLICE_RELATIONSHIP_LIMITS } from "./slice-format.ts";
12
+
13
+ export class VerticalSliceTracer {
14
+ constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd(), private ignorePatterns: string[] = [], private verifyMembership = true) {}
15
+
16
+ public async traceAsync(rawQuery: string, maxDepth = 5, signal?: AbortSignal, controllerFile?: string): Promise<VerticalSliceTraceResponse> {
17
+ signal?.throwIfAborted();
18
+ if (this.repo.getMeta("sync_state") === "error" || this.repo.getMeta("sync_state") === "running") {
19
+ return { query: rawQuery, found: false, coverage: "partial", diagnostics: ["index_incomplete"], message: "Workspace synchronization is incomplete." };
20
+ }
21
+ const inventory = this.verifyMembership ? scanSourceFiles(this.projectRoot, { ignorePatterns: this.ignorePatterns, signal }) : undefined;
22
+ const files = inventory?.files.map(file => relative(this.projectRoot, file).replace(/\\/g, "/"));
23
+ const membershipChanged = files !== undefined && JSON.stringify(files) !== this.repo.getMeta("semantic_catalog_files");
24
+ if (membershipChanged || !sliceInputsCurrent(this.repo, this.projectRoot, signal) || this.repo.getMeta("slices_dirty") === "1") {
25
+ try {
26
+ await rebuildSliceCatalog(this.repo, this.projectRoot, { ignorePatterns: this.ignorePatterns, signal });
27
+ } catch (error) {
28
+ signal?.throwIfAborted();
29
+ return { query: rawQuery, found: false, coverage: "partial", diagnostics: [error instanceof Error ? error.message : String(error)], message: "Semantic extraction failed; no complete catalog was published." };
30
+ }
31
+ }
32
+ return this.trace(rawQuery,maxDepth,controllerFile);
33
+ }
34
+
35
+
36
+ /**
37
+ * Trace an end-to-end vertical slice from route/action/intent query.
38
+ * Examples of queries:
39
+ * - "POST /orders/{id}/status"
40
+ * - "/orders/{id}/status"
41
+ * - "OrderController@updateStatus"
42
+ * - "OrderController::updateStatus"
43
+ * - "orders.update_status"
44
+ * - "createOrder"
45
+ * - "Ubah status order di dashboard"
46
+ */
47
+ // Synchronous compatibility API reads persisted slices only; use traceAsync for on-demand extraction.
48
+ public trace(rawQuery: string, maxDepth: number = 5, controllerFile?: string): VerticalSliceTraceResponse {
49
+ const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
50
+ const trimmed = rawQuery.trim();
51
+ const lowerTrimmed = trimmed.toLowerCase();
52
+ const allSlices = this.repo.getAllVerticalSlices().filter(slice => !controllerFile || slice.controller_file === controllerFile);
53
+
54
+ if (allSlices.length === 0) {
55
+ return {
56
+ query: trimmed,
57
+ found: false,
58
+ coverage: "partial",
59
+ max_depth_applied: effectiveMaxDepth,
60
+ message: controllerFile ? "No catalog target matches controller_file. Copy an exact file from the candidates or omit the filter." : "No vertical slices cataloged. Run 'septum sync' to extract framework routes and MVC slices.",
61
+ };
62
+ }
63
+
64
+ // 1. Exact HTTP Method + URI match: "POST /orders/{id}/status" or "POST /api/orders"
65
+ const methodUriMatch = trimmed.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(\/[^\s]+)$/i);
66
+ if (methodUriMatch) {
67
+ const httpMethod = methodUriMatch[1].toUpperCase();
68
+ const uri = methodUriMatch[2];
69
+ const candidates = allSlices.filter((s) => s.http_method.toUpperCase() === httpMethod && this.urisMatch(s.route_uri, uri));
70
+ const literal = candidates.filter(s => s.route_uri === uri);
71
+ if (literal.length === 1) {
72
+ return this.formatSuccessResponse(trimmed, literal[0], "exact", undefined, effectiveMaxDepth);
73
+ }
74
+ if (literal.length > 1 || candidates.length > 1) {
75
+ return this.ambiguousResponse(trimmed, literal.length ? literal : candidates, effectiveMaxDepth);
76
+ }
77
+ if (candidates.length === 1) {
78
+ return this.formatSuccessResponse(trimmed, candidates[0], "inferred", undefined, effectiveMaxDepth);
79
+ }
80
+ return { query: trimmed, found: false, coverage: "partial", max_depth_applied: effectiveMaxDepth, message: `No vertical slice found matching query '${trimmed}'.` };
81
+ }
82
+
83
+ // 2. URI-only match: "/orders" or "orders/{id}"
84
+ const literalUriMatches = allSlices.filter((s) => s.route_uri === trimmed);
85
+ const uriMatches = literalUriMatches.length ? literalUriMatches : allSlices.filter((s) => this.urisMatch(s.route_uri, trimmed));
86
+ if (uriMatches.length > 0) {
87
+ const confidence = literalUriMatches.length ? "exact" : "inferred";
88
+ if (uriMatches.length === 1) {
89
+ return this.formatSuccessResponse(trimmed, uriMatches[0], confidence, undefined, effectiveMaxDepth);
90
+ }
91
+ return this.ambiguousResponse(trimmed, uriMatches, effectiveMaxDepth);
92
+ }
93
+
94
+ // 3. Named Route match: "orders.status.update" or "admin.users.index"
95
+ const nameMatches = allSlices.filter(
96
+ (s) => s.route_name && s.route_name.toLowerCase() === lowerTrimmed
97
+ );
98
+ if (nameMatches.length) {
99
+ return nameMatches.length > 1 ? this.ambiguousResponse(trimmed, nameMatches, effectiveMaxDepth)
100
+ : this.formatSuccessResponse(trimmed, nameMatches[0], "exact", undefined, effectiveMaxDepth);
101
+ }
102
+
103
+ // 3b. Omni-Trigger Match: "JOB ProcessOrderJob", "job:ProcessOrderJob", "CLI order:cleanup", "EVENT OrderPlacedListener"
104
+ const omniTriggerMatch = trimmed.match(/^(JOB|CLI|EVENT)\s+([A-Za-z0-9_:\-]+)$/i);
105
+ if (omniTriggerMatch) {
106
+ const triggerKind = omniTriggerMatch[1].toUpperCase();
107
+ const targetName = omniTriggerMatch[2].toLowerCase();
108
+ const exact = allSlices.filter(
109
+ (s) =>
110
+ s.http_method.toUpperCase() === triggerKind &&
111
+ (s.controller_class.toLowerCase() === targetName ||
112
+ s.route_uri.toLowerCase() === targetName ||
113
+ s.route_uri.toLowerCase() === `${triggerKind.toLowerCase()}:${targetName}`)
114
+ );
115
+ if (exact.length) {
116
+ return exact.length > 1 ? this.ambiguousResponse(trimmed, exact, effectiveMaxDepth)
117
+ : this.formatSuccessResponse(trimmed, exact[0], "exact", undefined, effectiveMaxDepth);
118
+ }
119
+ }
120
+
121
+ // 4. Controller@Action match: "OrderController@updateStatus" or "OrderController"
122
+ const controllerActionMatch = trimmed.match(/^([A-Za-z0-9_\\/.]+?)(?:(?:@|::)([A-Za-z0-9_]+))?$/);
123
+ if (controllerActionMatch) {
124
+ const [, rawCtrl, act] = controllerActionMatch;
125
+ const ctrl = rawCtrl.split(/[\\/]/).pop()?.replace(/\.(php|ts|js)$/i, "") || rawCtrl;
126
+ const lowerCtrl = ctrl.toLowerCase();
127
+ const lowerAct = act ? act.toLowerCase() : undefined;
128
+
129
+ const exact = allSlices.filter((s) => {
130
+ const sCtrlLower = s.controller_class.toLowerCase();
131
+ const ctrlMatch =
132
+ sCtrlLower === lowerCtrl ||
133
+ sCtrlLower.endsWith(`\\${lowerCtrl}`) ||
134
+ sCtrlLower.endsWith(`/${lowerCtrl}`);
135
+ if (!ctrlMatch) return false;
136
+ if (lowerAct) return s.action_name.toLowerCase() === lowerAct;
137
+ if (!act && !lowerCtrl.endsWith("controller") && sCtrlLower !== lowerCtrl) {
138
+ return false;
139
+ }
140
+ return true;
141
+ });
142
+ if (exact.length) {
143
+ return exact.length > 1 ? this.ambiguousResponse(trimmed, exact, effectiveMaxDepth)
144
+ : this.formatSuccessResponse(trimmed, exact[0], "exact", undefined, effectiveMaxDepth);
145
+ }
146
+ }
147
+
148
+ // 5. Symbol Match in Execution Chain or Action Name (e.g. "createOrder", "CreateOrderUseCase", "OrderController")
149
+ let invalidChains = false;
150
+ const symbolMatches = allSlices.filter((s) => {
151
+ if (s.action_name.toLowerCase() === lowerTrimmed) return true;
152
+ if (s.controller_class.toLowerCase() === lowerTrimmed) return true;
153
+ if (s.execution_chain_json) {
154
+ try {
155
+ const chain = this.parseChain(s.execution_chain_json);
156
+ return chain.some(
157
+ (node) =>
158
+ node.symbol.toLowerCase() === lowerTrimmed ||
159
+ node.symbol.toLowerCase().includes(lowerTrimmed) ||
160
+ (node.file && node.file.toLowerCase().includes(lowerTrimmed))
161
+ );
162
+ } catch {
163
+ invalidChains = true;
164
+ return false;
165
+ }
166
+ }
167
+ return false;
168
+ });
169
+ if (symbolMatches.length) {
170
+ return symbolMatches.length > 1 ? this.ambiguousResponse(trimmed, symbolMatches, effectiveMaxDepth)
171
+ : this.formatSuccessResponse(trimmed, symbolMatches[0], "inferred", undefined, effectiveMaxDepth);
172
+ }
173
+
174
+ // 6. Semantic / Token Scoring for Natural Language (e.g. "Ubah status order di dashboard")
175
+ const tokens = this.tokenize(trimmed);
176
+ const scoredSlices = allSlices
177
+ .map((slice) => {
178
+ let score = 0;
179
+ const textCorpus = [
180
+ slice.route_uri,
181
+ slice.route_name || "",
182
+ slice.controller_class,
183
+ slice.action_name,
184
+ slice.execution_chain_json || "",
185
+ ].join(" ").toLowerCase();
186
+
187
+ for (const token of tokens) {
188
+ if (textCorpus.includes(token)) {
189
+ score += 1;
190
+ if (slice.route_uri.toLowerCase().includes(token)) score += 2;
191
+ if (slice.action_name.toLowerCase().includes(token)) score += 2;
192
+ }
193
+ }
194
+ return { slice, score };
195
+ })
196
+ .filter((item) => item.score > 0)
197
+ .sort((a, b) => b.score - a.score);
198
+
199
+ if (scoredSlices.length > 0) {
200
+ const tied = scoredSlices.filter(item => item.score === scoredSlices[0].score);
201
+ if (tied.length > 1) return this.ambiguousResponse(trimmed, tied.map(item => item.slice), effectiveMaxDepth);
202
+ const primary = scoredSlices[0].slice;
203
+ const alternatives = scoredSlices.slice(1, 4).map((item) => item.slice);
204
+ return this.formatSuccessResponse(trimmed, primary, "inferred", alternatives, effectiveMaxDepth);
205
+ }
206
+
207
+ return {
208
+ query: trimmed,
209
+ found: false,
210
+ coverage: "partial",
211
+ diagnostics: invalidChains ? ["invalid_execution_chain"] : undefined,
212
+ next: invalidChains ? ["Run septum sync to rebuild the catalog before relying on a negative symbol search."] : undefined,
213
+ max_depth_applied: effectiveMaxDepth,
214
+ alternatives: allSlices.slice(0, 5).map((s) => ({
215
+ method: s.http_method,
216
+ uri: s.route_uri,
217
+ controller: s.controller_class,
218
+ action: s.action_name,
219
+ })),
220
+ message: `No vertical slice found matching query '${trimmed}'.`,
221
+ };
222
+ }
223
+
224
+ private ambiguousResponse(query: string, candidates: VerticalSliceRecord[], maxDepth: number): VerticalSliceTraceResponse {
225
+ const alternatives = candidates.map(candidate => ({ method: candidate.http_method, uri: candidate.route_uri,
226
+ controller: candidate.controller_class, action: candidate.action_name, file: candidate.controller_file,
227
+ line: candidate.controller_line })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
228
+ return { query, found: false, coverage: "partial", diagnostics: ["ambiguous_target"],
229
+ max_depth_applied: maxDepth, alternatives: alternatives.slice(0, 20),
230
+ candidate_count: alternatives.length, alternatives_omitted: Math.max(0, alternatives.length - 20),
231
+ next: ["Narrow the query to METHOD /route or Controller@action and controller_file copied from a candidate. If candidates remain identical, inspect their source declarations."],
232
+ message: "Multiple catalog targets match; no entrypoint or chain was selected." };
233
+ }
234
+
235
+ private parseChain(serialized: string): ExecutionChainNode[] {
236
+ const chain: unknown = JSON.parse(serialized);
237
+ if (!Array.isArray(chain) || chain.some(node => !node || typeof node !== "object" ||
238
+ typeof node.stage !== "string" || typeof node.symbol !== "string" ||
239
+ (node.file !== undefined && typeof node.file !== "string") ||
240
+ (node.description !== undefined && typeof node.description !== "string") ||
241
+ ["guards", "mutations", "emits", "dispatches"].some(key => node[key] !== undefined &&
242
+ (!Array.isArray(node[key]) || node[key].some((value: unknown) => typeof value !== "string"))))) {
243
+ throw new Error("Invalid execution chain shape");
244
+ }
245
+ return chain;
246
+ }
247
+
248
+ private urisMatch(uriA: string, uriB: string): boolean {
249
+ const normA = uriA
250
+ .replace(/\{[^}]+\}/g, ":param")
251
+ .replace(/:[a-zA-Z0-9_]+/g, ":param");
252
+ const normB = uriB
253
+ .replace(/\{[^}]+\}/g, ":param")
254
+ .replace(/:[a-zA-Z0-9_]+/g, ":param");
255
+ return normA === normB;
256
+ }
257
+
258
+ private tokenize(str: string): string[] {
259
+ return str
260
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
261
+ .toLowerCase()
262
+ .replace(/[^a-z0-9_]+/g, " ")
263
+ .split(/\s+/)
264
+ .filter((t) => t.length > 2 && !["ubah", "di", "dan", "yang", "the", "for", "and"].includes(t));
265
+ }
266
+
267
+ private formatSuccessResponse(
268
+ query: string,
269
+ record: VerticalSliceRecord,
270
+ confidence: "exact" | "inferred" = "exact",
271
+ alternatives?: VerticalSliceRecord[],
272
+ effectiveMaxDepth: number = 5
273
+ ): VerticalSliceTraceResponse {
274
+ let chain: ExecutionChainNode[] = [];
275
+ const diagnostics: string[] = [];
276
+ try {
277
+ chain = this.parseChain(record.execution_chain_json);
278
+ } catch {
279
+ diagnostics.push("invalid_execution_chain");
280
+ }
281
+
282
+ // Import expansion is derived per request, so cached depth cannot override the requested hop limit.
283
+ chain = chain.filter(node => node.relationship?.kind !== "imports" && !node.description?.includes("(dependency)"));
284
+ // Go imports resolve whole packages; expanding them injects unrelated handlers/services.
285
+ if (
286
+ record.architecture_style !== "go-http" && !diagnostics.length && record.controller_file &&
287
+ typeof (this.repo as any).getAllFiles === "function"
288
+ ) {
289
+ try {
290
+ const callGraphTracer = new CallGraphTracer(this.repo, this.projectRoot);
291
+ chain = record.action_name
292
+ ? callGraphTracer.expandChainFromMethod(
293
+ record.controller_file,
294
+ record.action_name,
295
+ chain,
296
+ effectiveMaxDepth
297
+ )
298
+ : callGraphTracer.expandChainFromFile(
299
+ record.controller_file,
300
+ chain,
301
+ effectiveMaxDepth
302
+ );
303
+ } catch {
304
+ diagnostics.push("dependency_expansion_failed");
305
+ }
306
+ }
307
+
308
+ let message = `Vertical slice target match (${confidence}): ${record.http_method} ${record.route_uri} -> ${record.controller_class}@${record.action_name} (${chain.length} node(s)).`;
309
+ if (record.architecture_style === "go-http") {
310
+ message += " Go package import expansion is omitted; extracted handler/service relationships remain lexical and partial.";
311
+ }
312
+ if (diagnostics.length) message += ` Analysis incomplete: ${diagnostics.join(", ")}. Run septum sync and retry; inspect source if it persists.`;
313
+
314
+ return {
315
+ query,
316
+ found: true,
317
+ coverage: "partial",
318
+ diagnostics: diagnostics.length ? diagnostics : undefined,
319
+ next: diagnostics.length ? ["Run septum sync to rebuild analysis; retry the query. Inspect source directly if the diagnostic persists."] : undefined,
320
+ confidence,
321
+ is_exact_match: confidence === "exact",
322
+ architecture_style: record.architecture_style,
323
+ max_depth_applied: effectiveMaxDepth,
324
+ entrypoint: {
325
+ method: record.http_method,
326
+ uri: record.route_uri,
327
+ name: record.route_name,
328
+ controller: record.controller_class,
329
+ action: record.action_name,
330
+ file: record.controller_file,
331
+ line: record.controller_line,
332
+ },
333
+ chain,
334
+ slice: chain,
335
+ alternatives: alternatives?.map((a) => ({
336
+ method: a.http_method,
337
+ uri: a.route_uri,
338
+ controller: a.controller_class,
339
+ action: a.action_name,
340
+ })),
341
+ message,
342
+ };
343
+ }
344
+ }