@dimassetoid/septum-mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +253 -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
@@ -0,0 +1,197 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import type { ExecutionChainNode, FileRecord, SymbolRecord } from "../../types/index.ts";
4
+ import { readOptionalSourceFile } from "../resources/source-files.ts";
5
+ import type { TracerDependency } from "./ast-method-tracer.ts";
6
+
7
+ export interface PolyglotSliceTracerContext {
8
+ projectRoot: string;
9
+ maxChainNodes: number;
10
+ hasWorkspaceRoot: boolean;
11
+ fileSymbols: (fileId: number) => SymbolRecord[];
12
+ fileDependencies: (fileId: number) => TracerDependency[];
13
+ extractImportedSymbolNames: (statement: string) => string[];
14
+ resolveImportTargets: (fromPath: string, target: string) => FileRecord[];
15
+ resolveImportToFile: (fromPath: string, target: string) => FileRecord | undefined;
16
+ resolveExecutableSymbol: (symbols: SymbolRecord[], preferredNames: string[]) => SymbolRecord | undefined;
17
+ isExecutableSymbol: (symbol: SymbolRecord) => boolean;
18
+ detectStage: (filePath: string, archetype: string) => string;
19
+ }
20
+
21
+ const IGNORED_LOCAL_CALL_NAMES = new Set(["constructor", "__init__", "new", "main", "get", "set"]);
22
+
23
+ function escapeRegExp(value: string): string {
24
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25
+ }
26
+
27
+ function isIdentifierReferencedInScope(scopeText: string, name: string): boolean {
28
+ if (!name) return false;
29
+ const check = (candidate: string) =>
30
+ new RegExp(`(?<![A-Za-z0-9_$])${escapeRegExp(candidate)}(?![A-Za-z0-9_$])`).test(scopeText);
31
+ if (check(name)) return true;
32
+ const camel = name.charAt(0).toLowerCase() + name.slice(1);
33
+ return camel !== name && check(camel);
34
+ }
35
+
36
+ function readLinesSafe(projectRoot: string, filePath: string): string[] | undefined {
37
+ const fullPath = resolve(projectRoot, filePath);
38
+ if (!existsSync(fullPath)) return undefined;
39
+ try {
40
+ return readOptionalSourceFile(fullPath, "utf-8").split(/\r?\n/);
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Polyglot method-scoped dependency traversal (Go, Python, PHP, Rust, Ruby, Java, C#).
48
+ * Bridges same-file local helper calls (up to 2 local hops) before matching imported collaborators
49
+ * so thin wrapper handlers expose the services/repositories called inside their local delegates.
50
+ */
51
+ export function traversePolyglotMethodDependencies(
52
+ ctx: PolyglotSliceTracerContext,
53
+ startFile: FileRecord,
54
+ methodBody: string,
55
+ methodSymbol: SymbolRecord,
56
+ chain: ExecutionChainNode[]
57
+ ): void {
58
+ const visitedFiles = new Set<string>([startFile.path]);
59
+ let scopeText = (methodSymbol.signature || "") + "\n" + methodBody;
60
+
61
+ // 1. Bridge same-file local helper calls (Go, Python, PHP, Rust, etc.)
62
+ const localSymbols = ctx.fileSymbols(startFile.id).filter((s) => ctx.isExecutableSymbol(s));
63
+ const fileLines = localSymbols.length > 1 ? readLinesSafe(ctx.projectRoot, startFile.path) : undefined;
64
+ if (fileLines) {
65
+ const visitedLocal = new Set<string>([`${methodSymbol.name}:${methodSymbol.line_start}`]);
66
+ const localQueue: Array<{ symbol: SymbolRecord; body: string; depth: number }> = [
67
+ { symbol: methodSymbol, body: methodBody, depth: 0 },
68
+ ];
69
+
70
+ while (localQueue.length > 0 && chain.length < ctx.maxChainNodes) {
71
+ const current = localQueue.shift()!;
72
+ if (current.depth >= 2) continue;
73
+
74
+ for (const candidate of localSymbols) {
75
+ if (chain.length >= ctx.maxChainNodes) break;
76
+ const candKey = `${candidate.name}:${candidate.line_start}`;
77
+ if (visitedLocal.has(candKey)) continue;
78
+ const shortName = candidate.name.split(/::|@|\./).pop() || candidate.name;
79
+ if (shortName.length < 2 || IGNORED_LOCAL_CALL_NAMES.has(shortName)) continue;
80
+
81
+ const callPattern = new RegExp(
82
+ `(?:\\b(?:self|this|\\$this|[a-zA-Z_]\\w*)\\s*(?:\\.|->|::)\\s*|\\b)${escapeRegExp(shortName)}\\s*\\(`
83
+ );
84
+ if (!callPattern.test(current.body)) continue;
85
+
86
+ visitedLocal.add(candKey);
87
+ const stage = ctx.detectStage(startFile.path, startFile.archetype);
88
+ if (!chain.some((c) => c.file === startFile.path && c.symbol === candidate.name)) {
89
+ chain.push({
90
+ stage,
91
+ symbol: candidate.name,
92
+ file: startFile.path,
93
+ line: candidate.line_start || 1,
94
+ description: `${stage.toUpperCase()} (local call): ${candidate.name}`,
95
+ relationship: {
96
+ kind: "calls",
97
+ derivation: "source",
98
+ source: { file: startFile.path, line: current.symbol.line_start || 1 },
99
+ reason: "local_call_site",
100
+ },
101
+ });
102
+ }
103
+
104
+ const start = Math.max(0, candidate.line_start - 1);
105
+ const end = Math.min(fileLines.length, candidate.line_end);
106
+ const candidateBody = fileLines.slice(start, end).join("\n");
107
+ if (candidateBody) {
108
+ scopeText += `\n${candidate.signature || ""}\n${candidateBody}`;
109
+ localQueue.push({ symbol: candidate, body: candidateBody, depth: current.depth + 1 });
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+ // 2. Match imported collaborators referenced in the method (and its bridged local helpers)
116
+ const deps = ctx.fileDependencies(startFile.id);
117
+ const emittedFileSymbols = new Set<string>();
118
+ for (const dep of deps) {
119
+ if (/^\s*(?:import|export)\s+type\b/.test(dep.statement)) continue;
120
+ if (chain.length >= ctx.maxChainNodes) break;
121
+ const importedNames = ctx.extractImportedSymbolNames(dep.statement);
122
+ const baseTarget = dep.target.split(/[\/\\]/).pop()?.replace(/\.[^.]+$/, "") || "";
123
+
124
+ const referencedNames = importedNames.filter((name) => isIdentifierReferencedInScope(scopeText, name));
125
+ const isReferenced =
126
+ importedNames.length > 0
127
+ ? referencedNames.length > 0
128
+ : baseTarget.length > 0 && isIdentifierReferencedInScope(scopeText, baseTarget);
129
+
130
+ if (!isReferenced) continue;
131
+
132
+ const resolvedFiles = ctx.hasWorkspaceRoot
133
+ ? ctx.resolveImportTargets(startFile.path, dep.target)
134
+ : dep.is_external
135
+ ? []
136
+ : [ctx.resolveImportToFile(startFile.path, dep.target)].filter((file): file is FileRecord => !!file);
137
+
138
+ for (const resolvedFile of resolvedFiles) {
139
+ if (!resolvedFile || resolvedFile.path === startFile.path) continue;
140
+
141
+ const stage = ctx.detectStage(resolvedFile.path, resolvedFile.archetype);
142
+ const fileSymbols = ctx.fileSymbols(resolvedFile.id);
143
+ const matchedSymbols: SymbolRecord[] = [];
144
+ if (referencedNames.length > 0) {
145
+ for (const refName of referencedNames) {
146
+ const direct = fileSymbols.find(
147
+ (s) =>
148
+ ctx.isExecutableSymbol(s) &&
149
+ (s.name === refName ||
150
+ s.name.endsWith(`::${refName}`) ||
151
+ s.name.endsWith(`@${refName}`) ||
152
+ s.name.endsWith(`.${refName}`))
153
+ );
154
+ const resolved = direct ?? ctx.resolveExecutableSymbol(fileSymbols, [refName]);
155
+ if (resolved && !matchedSymbols.some((m) => m.name === resolved.name && m.line_start === resolved.line_start)) {
156
+ matchedSymbols.push(resolved);
157
+ }
158
+ }
159
+ } else if (!visitedFiles.has(resolvedFile.path)) {
160
+ visitedFiles.add(resolvedFile.path);
161
+ const fallback = ctx.resolveExecutableSymbol(fileSymbols, []);
162
+ if (fallback) matchedSymbols.push(fallback);
163
+ }
164
+
165
+ for (const mainSymbol of matchedSymbols) {
166
+ if (chain.length >= ctx.maxChainNodes) break;
167
+ const emitKey = `${resolvedFile.path}\0${mainSymbol.name}`;
168
+ if (emittedFileSymbols.has(emitKey)) continue;
169
+ emittedFileSymbols.add(emitKey);
170
+
171
+ const symbolDisplay = mainSymbol.name;
172
+ const shortSymbolDisplay = symbolDisplay.split(/[\\:]/).pop();
173
+ const existingNode = chain.find(
174
+ (c) =>
175
+ c.file === resolvedFile.path &&
176
+ (c.symbol === symbolDisplay || c.symbol.split(/[\\:]/).pop() === shortSymbolDisplay)
177
+ );
178
+
179
+ if (!existingNode) {
180
+ chain.push({
181
+ stage,
182
+ symbol: symbolDisplay,
183
+ file: resolvedFile.path,
184
+ line: mainSymbol.line_start || 1,
185
+ description: `${stage.toUpperCase()} (referenced import): ${symbolDisplay}`,
186
+ relationship: {
187
+ kind: "imports",
188
+ derivation: "source",
189
+ source: { file: startFile.path, line: dep.line_number, statement: dep.statement },
190
+ reason: "import referenced in method scope; not proof of a call",
191
+ },
192
+ });
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
@@ -8,12 +8,14 @@ import { scanSourceFiles, type SourceInventory } from "../resources/source-inven
8
8
  import { collectSourceSkips, readSourceFile, SOURCE_READ_REVISION, sourceObservationsCurrent } from "../resources/source-files.ts";
9
9
  import { assertPathContained } from "./path-resolver.ts";
10
10
  import { CallGraphTracer } from "./call-graph-tracer.ts";
11
+ import { normalizeGraphQLEntrypoints } from "../parser/extractors/graphql-entrypoint.ts";
11
12
 
12
13
  interface CatalogOptions {
13
14
  ignorePatterns: string[];
14
15
  signal?: AbortSignal;
15
16
  semanticRevision?: string;
16
17
  inventoryRevision?: string;
18
+ inventory?: SourceInventory;
17
19
  }
18
20
 
19
21
  export function sliceInputsCurrent(repo: SeptumRepository, root: string, signal?: AbortSignal): boolean {
@@ -30,13 +32,28 @@ export function sliceInputsCurrent(repo: SeptumRepository, root: string, signal?
30
32
  } catch { signal?.throwIfAborted(); return false; }
31
33
  }
32
34
 
35
+ export async function refreshSliceCatalog(
36
+ repo: SeptumRepository,
37
+ root: string,
38
+ options: CatalogOptions & { verifyMembership: boolean },
39
+ ): Promise<void> {
40
+ const files = options.verifyMembership
41
+ ? scanSourceFiles(root, { ignorePatterns: options.ignorePatterns, signal: options.signal }).files
42
+ .map(file => relative(root, file).replace(/\\/g, "/"))
43
+ : undefined;
44
+ const membershipChanged = files !== undefined && JSON.stringify(files) !== repo.getMeta("semantic_catalog_files");
45
+ if (membershipChanged || !sliceInputsCurrent(repo, root, options.signal) || repo.getMeta("slices_dirty") === "1") {
46
+ await rebuildSliceCatalog(repo, root, options);
47
+ }
48
+ }
49
+
33
50
  /** Publish slices and their input evidence together; failed builds retain a dirty catalog. */
34
51
  export async function rebuildSliceCatalog(repo: SeptumRepository, root: string, options: CatalogOptions): Promise<void> {
35
52
  try {
36
53
  const reports: AdapterExtractionResult[] = [];
37
54
  let inventory: SourceInventory;
38
55
  const extracted = await collectSourceSkips(root, async () => {
39
- inventory = scanSourceFiles(root, { ignorePatterns: options.ignorePatterns, signal: options.signal });
56
+ inventory = options.inventory ?? scanSourceFiles(root, { ignorePatterns: options.ignorePatterns, signal: options.signal });
40
57
  const topology = TopologyDetector.detect(root);
41
58
  const slices = await SemanticSliceExtractorRegistry.extractAllSlices(root, topology.framework, undefined, options.signal, {
42
59
  ignorePatterns: options.ignorePatterns, inventory, onResult: result => reports.push(result),
@@ -49,10 +66,8 @@ export async function rebuildSliceCatalog(repo: SeptumRepository, root: string,
49
66
  const chain = JSON.parse(slice.execution_chain_json) as Array<{ stage?: string; file?: string }>;
50
67
  for (const node of chain) if (node.stage === "ingress" && node.file) coveredFiles.add(node.file);
51
68
  }
52
- const fallback = new CallGraphTracer(repo, root).traceAllSlices(8, {
53
- includeInferredControllers: slices.length === 0, excludeEntrypointFiles: coveredFiles,
54
- });
55
- return [...slices, ...fallback];
69
+ const fallback = new CallGraphTracer(repo, root).traceAllSlices(8, { excludeEntrypointFiles: coveredFiles });
70
+ return normalizeGraphQLEntrypoints([...slices, ...fallback]);
56
71
  });
57
72
  options.signal?.throwIfAborted();
58
73
  if (extracted.skipped.length) {
@@ -63,7 +78,7 @@ export async function rebuildSliceCatalog(repo: SeptumRepository, root: string,
63
78
  }
64
79
  repo.runInTransaction(() => {
65
80
  repo.clearVerticalSlices();
66
- for (const slice of extracted.value) repo.upsertVerticalSlice(slice);
81
+ repo.insertVerticalSlices(extracted.value);
67
82
  repo.setMeta("slices_dirty", "");
68
83
  repo.setMeta("semantic_extractor_revision", SEMANTIC_FINGERPRINT);
69
84
  repo.setMeta("semantic_inputs", JSON.stringify(extracted.inputs));
@@ -7,3 +7,16 @@ export function formatSliceNode(node: ExecutionChainNode): string {
7
7
  const relation = node.relationship;
8
8
  return `[${(node.stage || "stage").toUpperCase()}] ${node.symbol} [${relation?.kind ?? "unknown"}; ${relation?.derivation ?? "unknown"}]${node.semantic_analysis ? " [lexical heuristic]" : ""}`;
9
9
  }
10
+
11
+ export function parseSliceChain(serialized: string): ExecutionChainNode[] {
12
+ const chain: unknown = JSON.parse(serialized);
13
+ if (!Array.isArray(chain) || chain.some(node => !node || typeof node !== "object" ||
14
+ typeof node.stage !== "string" || typeof node.symbol !== "string" ||
15
+ (node.file !== undefined && typeof node.file !== "string") ||
16
+ (node.description !== undefined && typeof node.description !== "string") ||
17
+ ["guards", "mutations", "emits", "dispatches"].some(key => node[key] !== undefined &&
18
+ (!Array.isArray(node[key]) || node[key].some((value: unknown) => typeof value !== "string"))))) {
19
+ throw new Error("Invalid execution chain shape");
20
+ }
21
+ return chain;
22
+ }
@@ -0,0 +1,237 @@
1
+ import type { VerticalSliceRecord, VerticalSliceTraceResponse } from "../../types/index.ts";
2
+ import { parseSliceChain } from "./slice-format.ts";
3
+
4
+ interface SliceMatch {
5
+ query: string;
6
+ record: VerticalSliceRecord;
7
+ confidence: "exact" | "inferred";
8
+ alternatives?: VerticalSliceRecord[];
9
+ }
10
+
11
+ function match(query: string, record: VerticalSliceRecord, confidence: SliceMatch["confidence"], alternatives?: VerticalSliceRecord[]): SliceMatch {
12
+ return { query, record, confidence, alternatives };
13
+ }
14
+
15
+ export function selectSliceTarget(
16
+ records: VerticalSliceRecord[],
17
+ rawQuery: string,
18
+ effectiveMaxDepth: number,
19
+ controllerFile?: string,
20
+ ): SliceMatch | VerticalSliceTraceResponse {
21
+ const trimmed = rawQuery.trim();
22
+ const lowerTrimmed = trimmed.toLowerCase();
23
+ const allSlices = records.filter(slice => !controllerFile || slice.controller_file === controllerFile);
24
+
25
+ if (allSlices.length === 0) {
26
+ return {
27
+ query: trimmed,
28
+ found: false,
29
+ coverage: "partial",
30
+ max_depth_applied: effectiveMaxDepth,
31
+ 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.",
32
+ };
33
+ }
34
+
35
+ // 1. Exact HTTP Method + URI match: "POST /orders/{id}/status" or "POST /api/orders"
36
+ const methodUriMatch = trimmed.match(/^([A-Z][A-Z0-9-]*)\s+(\/[^\s]*)$/i);
37
+ if (methodUriMatch) {
38
+ const httpMethod = methodUriMatch[1].toUpperCase();
39
+ const uri = methodUriMatch[2];
40
+ const candidates = allSlices.filter((s) => {
41
+ const method = s.http_method.toUpperCase();
42
+ return (method === httpMethod || method === "ANY") && urisMatch(s.route_uri, uri);
43
+ });
44
+ const normUri = stripTrailingSlash(uri);
45
+ const literal = candidates.filter(s => stripTrailingSlash(s.route_uri) === normUri);
46
+ if (literal.length === 1) {
47
+ const confidence = literal[0].http_method.toUpperCase() === httpMethod ? "exact" : "inferred";
48
+ return match(trimmed, literal[0], confidence, undefined);
49
+ }
50
+ if (literal.length > 1 || candidates.length > 1) {
51
+ return ambiguousResponse(trimmed, literal.length ? literal : candidates, effectiveMaxDepth);
52
+ }
53
+ if (candidates.length === 1) {
54
+ return match(trimmed, candidates[0], "inferred", undefined);
55
+ }
56
+ return { query: trimmed, found: false, coverage: "partial", max_depth_applied: effectiveMaxDepth, message: `No vertical slice found matching query '${trimmed}'.` };
57
+ }
58
+
59
+ // 2. URI-only match: "/orders" or "orders/{id}"
60
+ const literalUriMatches = allSlices.filter((s) => s.route_uri === trimmed);
61
+ const uriMatches = literalUriMatches.length ? literalUriMatches : allSlices.filter((s) => urisMatch(s.route_uri, trimmed));
62
+ if (uriMatches.length > 0) {
63
+ const confidence = literalUriMatches.length ? "exact" : "inferred";
64
+ if (uriMatches.length === 1) {
65
+ return match(trimmed, uriMatches[0], confidence, undefined);
66
+ }
67
+ return ambiguousResponse(trimmed, uriMatches, effectiveMaxDepth);
68
+ }
69
+
70
+ // 3. Named Route match: "orders.status.update" or "admin.users.index"
71
+ const nameMatches = allSlices.filter(
72
+ (s) => s.route_name && s.route_name.toLowerCase() === lowerTrimmed
73
+ );
74
+ if (nameMatches.length) {
75
+ return nameMatches.length > 1 ? ambiguousResponse(trimmed, nameMatches, effectiveMaxDepth)
76
+ : match(trimmed, nameMatches[0], "exact", undefined);
77
+ }
78
+
79
+ // 3b. Omni-Trigger Match: "JOB ProcessOrderJob", "CLI command:check", "MCP tool:septum_symbol", "EVENT OrderPlacedListener"
80
+ const omniTriggerMatch = trimmed.match(/^(JOB|CLI|EVENT|MCP|RPC|QUEUE|CRON|WS)\s+([A-Za-z0-9_:\-\./]+)$/i);
81
+ if (omniTriggerMatch) {
82
+ const triggerKind = omniTriggerMatch[1].toUpperCase();
83
+ const targetName = omniTriggerMatch[2].toLowerCase();
84
+ const exact = allSlices.filter(
85
+ (s) =>
86
+ s.http_method.toUpperCase() === triggerKind &&
87
+ (s.controller_class.toLowerCase() === targetName ||
88
+ s.route_uri.toLowerCase() === targetName ||
89
+ s.route_uri.toLowerCase() === `${triggerKind.toLowerCase()}:${targetName}` ||
90
+ (s.route_name && s.route_name.toLowerCase() === targetName))
91
+ );
92
+ if (exact.length) {
93
+ return exact.length > 1 ? ambiguousResponse(trimmed, exact, effectiveMaxDepth)
94
+ : match(trimmed, exact[0], "exact", undefined);
95
+ }
96
+ }
97
+
98
+ // 4. Controller@Action match: "OrderController@updateStatus" or "OrderController"
99
+ const controllerActionMatch = trimmed.match(/^([A-Za-z0-9_\\/.]+?)(?:(?:@|::)([A-Za-z0-9_]+))?$/);
100
+ if (controllerActionMatch) {
101
+ const [, rawCtrl, act] = controllerActionMatch;
102
+ const ctrl = rawCtrl.split(/[\\/]/).pop()?.replace(/\.(php|ts|js)$/i, "") || rawCtrl;
103
+ const lowerCtrl = ctrl.toLowerCase();
104
+ const lowerAct = act ? act.toLowerCase() : undefined;
105
+
106
+ const exact = allSlices.filter((s) => {
107
+ const sCtrlLower = s.controller_class.toLowerCase();
108
+ const ctrlMatch =
109
+ sCtrlLower === lowerCtrl ||
110
+ sCtrlLower.endsWith(`\\${lowerCtrl}`) ||
111
+ sCtrlLower.endsWith(`/${lowerCtrl}`);
112
+ if (!ctrlMatch) return false;
113
+ if (lowerAct) return s.action_name.toLowerCase() === lowerAct;
114
+ if (!act && !lowerCtrl.endsWith("controller") && sCtrlLower !== lowerCtrl) {
115
+ return false;
116
+ }
117
+ return true;
118
+ });
119
+ if (exact.length) {
120
+ return exact.length > 1 ? ambiguousResponse(trimmed, exact, effectiveMaxDepth)
121
+ : match(trimmed, exact[0], "exact", undefined);
122
+ }
123
+ }
124
+
125
+ // 5. Symbol Match in Execution Chain or Action Name (e.g. "createOrder", "CreateOrderUseCase", "OrderController")
126
+ let invalidChains = false;
127
+ const symbolMatches = allSlices.filter((s) => {
128
+ if (s.action_name.toLowerCase() === lowerTrimmed) return true;
129
+ if (s.controller_class.toLowerCase() === lowerTrimmed) return true;
130
+ if (s.execution_chain_json) {
131
+ try {
132
+ const chain = parseSliceChain(s.execution_chain_json);
133
+ return chain.some(
134
+ (node) =>
135
+ node.symbol.toLowerCase() === lowerTrimmed ||
136
+ node.symbol.toLowerCase().includes(lowerTrimmed) ||
137
+ (node.file && node.file.toLowerCase().includes(lowerTrimmed))
138
+ );
139
+ } catch {
140
+ invalidChains = true;
141
+ return false;
142
+ }
143
+ }
144
+ return false;
145
+ });
146
+ if (symbolMatches.length) {
147
+ return symbolMatches.length > 1 ? ambiguousResponse(trimmed, symbolMatches, effectiveMaxDepth)
148
+ : match(trimmed, symbolMatches[0], "inferred", undefined);
149
+ }
150
+
151
+ // 6. Semantic / Token Scoring for Natural Language (e.g. "Ubah status order di dashboard")
152
+ const tokens = tokenize(trimmed);
153
+ const scoredSlices = allSlices
154
+ .map((slice) => {
155
+ let score = 0;
156
+ const textCorpus = [
157
+ slice.route_uri,
158
+ slice.route_name || "",
159
+ slice.controller_class,
160
+ slice.action_name,
161
+ slice.execution_chain_json || "",
162
+ ].join(" ").toLowerCase();
163
+
164
+ for (const token of tokens) {
165
+ if (textCorpus.includes(token)) {
166
+ score += 1;
167
+ if (slice.route_uri.toLowerCase().includes(token)) score += 2;
168
+ if (slice.action_name.toLowerCase().includes(token)) score += 2;
169
+ }
170
+ }
171
+ return { slice, score };
172
+ })
173
+ .filter((item) => item.score > 0)
174
+ .sort((a, b) => b.score - a.score);
175
+
176
+ if (scoredSlices.length > 0) {
177
+ const tied = scoredSlices.filter(item => item.score === scoredSlices[0].score);
178
+ if (tied.length > 1) return ambiguousResponse(trimmed, tied.map(item => item.slice), effectiveMaxDepth);
179
+ const primary = scoredSlices[0].slice;
180
+ const alternatives = scoredSlices.slice(1, 4).map((item) => item.slice);
181
+ return match(trimmed, primary, "inferred", alternatives);
182
+ }
183
+
184
+ return {
185
+ query: trimmed,
186
+ found: false,
187
+ coverage: "partial",
188
+ diagnostics: invalidChains ? ["invalid_execution_chain"] : undefined,
189
+ next: invalidChains ? ["Run septum sync to rebuild the catalog before relying on a negative symbol search."] : undefined,
190
+ max_depth_applied: effectiveMaxDepth,
191
+ alternatives: allSlices.slice(0, 5).map((s) => ({
192
+ method: s.http_method,
193
+ uri: s.route_uri,
194
+ controller: s.controller_class,
195
+ action: s.action_name,
196
+ })),
197
+ message: `No vertical slice found matching query '${trimmed}'.`,
198
+ };
199
+ }
200
+
201
+ function ambiguousResponse(query: string, candidates: VerticalSliceRecord[], maxDepth: number): VerticalSliceTraceResponse {
202
+ const alternatives = candidates.map(candidate => ({ method: candidate.http_method, uri: candidate.route_uri,
203
+ controller: candidate.controller_class, action: candidate.action_name, file: candidate.controller_file,
204
+ line: candidate.controller_line })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
205
+ return { query, found: false, coverage: "partial", diagnostics: ["ambiguous_target"],
206
+ max_depth_applied: maxDepth, alternatives: alternatives.slice(0, 20),
207
+ candidate_count: alternatives.length, alternatives_omitted: Math.max(0, alternatives.length - 20),
208
+ 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."],
209
+ message: "Multiple catalog targets match; no entrypoint or chain was selected." };
210
+ }
211
+
212
+ function stripTrailingSlash(uri: string): string {
213
+ return uri.length > 1 ? uri.replace(/\/+$/, "") : uri;
214
+ }
215
+
216
+ function urisMatch(uriA: string, uriB: string): boolean {
217
+ const normA = stripTrailingSlash(
218
+ uriA
219
+ .replace(/\{[^}]+\}/g, ":param")
220
+ .replace(/:[a-zA-Z0-9_]+/g, ":param")
221
+ );
222
+ const normB = stripTrailingSlash(
223
+ uriB
224
+ .replace(/\{[^}]+\}/g, ":param")
225
+ .replace(/:[a-zA-Z0-9_]+/g, ":param")
226
+ );
227
+ return normA === normB;
228
+ }
229
+
230
+ function tokenize(str: string): string[] {
231
+ return str
232
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
233
+ .toLowerCase()
234
+ .replace(/[^a-z0-9_]+/g, " ")
235
+ .split(/\s+/)
236
+ .filter((t) => t.length > 2 && !["ubah", "di", "dan", "yang", "the", "for", "and"].includes(t));
237
+ }
@@ -11,7 +11,7 @@ interface ImpactFacts {
11
11
  container: string;
12
12
  method: string;
13
13
  targets: SymbolSpan[];
14
- dependencies: Array<{ file: string; line_number: number; domain_name?: string | null }>;
14
+ dependencies: Array<{ file: string; line_number: number; domain_name?: string | null; import_statement?: string }>;
15
15
  samePackageFiles: Set<string>;
16
16
  symbolsByFile: Map<string, Array<{ name: string; kind: string; signature: string; line_start: number; line_end: number }>>;
17
17
  domainsByFile: Map<string, string>;
@@ -76,7 +76,15 @@ export function analyzeSymbolImpact(facts: ImpactFacts): GetSymbolImpactResponse
76
76
  for (const statement of source.statements) {
77
77
  if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly) continue;
78
78
  const resolution = new ImportResolver(options.workspaceRoot!).resolve(statement.moduleSpecifier.text, file);
79
- if (resolution.status !== "resolved" || !resolution.targets.some(target => target.files.some(path => definingFiles.has(path)))) continue;
79
+ const hitsDefiningOrBarrel = resolution.status === "resolved" && resolution.targets.some(target => target.files.some(path => {
80
+ if (definingFiles.has(path)) return true;
81
+ if (/\/index\.[cm]?[jt]sx?$/.test(path)) {
82
+ const barrelDir = path.replace(/\/index\.[cm]?[jt]sx?$/, "");
83
+ return Array.from(definingFiles).some(df => df.startsWith(barrelDir + "/"));
84
+ }
85
+ return false;
86
+ }));
87
+ if (!hitsDefiningOrBarrel) continue;
80
88
  const clause = statement.importClause;
81
89
  if (clause?.name && targetSymRows.some(row => row.signature?.includes("export default"))) { const binding = checker.getSymbolAtLocation(clause.name); if (binding) bindings.add(binding); }
82
90
  if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) for (const specifier of clause.namedBindings.elements) {
@@ -154,17 +162,100 @@ export function analyzeSymbolImpact(facts: ImpactFacts): GetSymbolImpactResponse
154
162
  })::${escapeRegExp(effectiveMethod)}\\s*\\(`
155
163
  )
156
164
  : null;
157
- const nonTsFnCallRegex =
158
- !effectiveMethod && targetSymRows.some((r) => r.kind === "function")
159
- ? new RegExp(`(?:^|[^.\\w$:]|\\.)\\b${escapeRegExp(targetContainer)}\\s*\\(`)
160
- : null;
165
+ // For standalone functions, match unqualified calls (`fn(...)`) and only allow qualified calls
166
+ // (`alias.fn(...)`) when `alias` is a module/namespace import binding (never `cls.fn`, `self.fn`, etc.).
167
+ const isFunctionTarget = !effectiveMethod && targetSymRows.some((r) => r.kind === "function");
168
+ const nonTsFnCallRegex = isFunctionTarget
169
+ ? new RegExp(`(?:^|[^.\\w$:])\\b${escapeRegExp(targetContainer)}\\s*\\(`)
170
+ : null;
161
171
  const nonTsFnDeclRegex = nonTsFnCallRegex
162
172
  ? new RegExp(`\\b(?:function|func|def|fn)\\s+${escapeRegExp(targetContainer)}\\b`)
163
173
  : null;
164
174
 
175
+ const definingStems = new Set(
176
+ Array.from(definingFiles).flatMap((df) => {
177
+ const stem = df.split("/").pop()?.replace(/\.[^.]+$/, "") ?? "";
178
+ const dir = df.split("/").slice(-2, -1)[0] ?? "";
179
+ return /\.go$/i.test(df) ? [stem, dir] : [stem];
180
+ }).filter(Boolean)
181
+ );
182
+ const moduleAliasesByFile = new Map<string, Set<string>>();
183
+ const directAliasesByFile = new Map<string, Set<string>>();
184
+ const filesWithImportStmts = new Set<string>();
185
+ if (isFunctionTarget) {
186
+ for (const row of depRows) {
187
+ const stmt = String(row.import_statement || "");
188
+ if (!stmt) continue;
189
+ filesWithImportStmts.add(row.file);
190
+ // Python: `from pkg import stem as alias` or `from pkg import stem`
191
+ const fromMatch = stmt.match(/^\s*from\s+([^\s]+)\s+import\s+([\s\S]+)$/);
192
+ if (fromMatch) {
193
+ const items = fromMatch[2]!.replace(/[()]/g, "").split(",");
194
+ for (const rawItem of items) {
195
+ const item = rawItem.trim();
196
+ if (!item) continue;
197
+ const asMatch = item.match(/^([A-Za-z_]\w*)\s+as\s+([A-Za-z_]\w*)$/);
198
+ const orig = asMatch ? asMatch[1]! : item.split(/\s+/)[0]!;
199
+ const bound = asMatch ? asMatch[2]! : orig;
200
+ if (orig === targetContainer && bound !== targetContainer) {
201
+ const set = directAliasesByFile.get(row.file) ?? new Set<string>();
202
+ set.add(bound);
203
+ directAliasesByFile.set(row.file, set);
204
+ } else if (definingStems.has(orig) && !["cls", "self", "this", "super"].includes(bound)) {
205
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
206
+ set.add(bound);
207
+ moduleAliasesByFile.set(row.file, set);
208
+ }
209
+ }
210
+ continue;
211
+ }
212
+ // Python: `import pkg.stem as alias` or `import pkg.stem`
213
+ const pyImportAs = stmt.match(/^\s*import\s+([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z_]\w*))?/);
214
+ if (pyImportAs) {
215
+ const modTail = pyImportAs[1]!.split(".").pop() ?? "";
216
+ const bound = pyImportAs[2] ?? modTail;
217
+ if (definingStems.has(modTail) && !["cls", "self", "this", "super"].includes(bound)) {
218
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
219
+ set.add(bound);
220
+ moduleAliasesByFile.set(row.file, set);
221
+ }
222
+ continue;
223
+ }
224
+ // Go: `import "pkg/dir"` or `import alias "pkg/dir"`
225
+ const goImport = stmt.match(/^\s*(?:import\s+)?(?:([A-Za-z_]\w*)\s+)?"([^"]+)"/);
226
+ if (goImport) {
227
+ const pkgTail = goImport[2]!.split("/").pop() ?? "";
228
+ const bound = goImport[1] ?? pkgTail;
229
+ if (definingStems.has(pkgTail)) {
230
+ const set = moduleAliasesByFile.get(row.file) ?? new Set<string>();
231
+ set.add(bound);
232
+ moduleAliasesByFile.set(row.file, set);
233
+ }
234
+ }
235
+ }
236
+ }
237
+
165
238
  if (effectiveMethod || nonTsFnCallRegex) {
166
239
  for (const filePath of uniqueCallerFiles) {
167
240
  if (nonTsFnCallRegex && /\.[cm]?[jt]sx?$/.test(filePath)) continue;
241
+ const moduleAliases = moduleAliasesByFile.get(filePath);
242
+ const directAliases = directAliasesByFile.get(filePath);
243
+ const fallbackPkgAliases = !filesWithImportStmts.has(filePath) && definingStems.size > 0
244
+ ? definingStems
245
+ : undefined;
246
+ const effectiveModuleAliases = moduleAliases && moduleAliases.size > 0 ? moduleAliases : fallbackPkgAliases;
247
+ const qualifiedFnRegex =
248
+ effectiveModuleAliases && effectiveModuleAliases.size > 0
249
+ ? new RegExp(
250
+ `\\b(?:${Array.from(effectiveModuleAliases).map(escapeRegExp).join("|")})\\.${escapeRegExp(targetContainer)}\\s*\\(`
251
+ )
252
+ : null;
253
+ const aliasedDirectFnRegex =
254
+ directAliases && directAliases.size > 0
255
+ ? new RegExp(
256
+ `(?:^|[^.\\w$:])\\b(?:${Array.from(directAliases).map(escapeRegExp).join("|")})\\s*\\(`
257
+ )
258
+ : null;
168
259
  try {
169
260
  const fullPath = options.workspaceRoot ? resolve(options.workspaceRoot, filePath) : filePath;
170
261
  if (options.workspaceRoot) assertPathContained(fullPath, options.workspaceRoot, "Inbound caller source");
@@ -185,7 +276,12 @@ export function analyzeSymbolImpact(facts: ImpactFacts): GetSymbolImpactResponse
185
276
  ? staticOwnerCallRegex.test(line)
186
277
  : line.includes(`::${effectiveMethod}(`)) ||
187
278
  (!isStaticPhpMethod && line.includes(`.${effectiveMethod}(`))
188
- : Boolean(nonTsFnCallRegex?.test(line) && !nonTsFnDeclRegex?.test(line));
279
+ : Boolean(
280
+ !nonTsFnDeclRegex?.test(line) &&
281
+ (nonTsFnCallRegex?.test(line) ||
282
+ qualifiedFnRegex?.test(line) ||
283
+ aliasedDirectFnRegex?.test(line))
284
+ );
189
285
  if (matched) {
190
286
  const lineNum = i + 1;
191
287
  const enclosing = findEnclosingSymbol(filePath, lineNum);
@@ -372,7 +468,7 @@ export function analyzeSymbolImpact(facts: ImpactFacts): GetSymbolImpactResponse
372
468
  found_in_index: foundInIndex,
373
469
  warning,
374
470
  impact_summary: {
375
- total_dependents: inboundCallers.length,
471
+ total_dependents: affectedFiles.size,
376
472
  risk_level: foundInIndex ? riskLevel : "unknown",
377
473
  affected_files_count: affectedFiles.size,
378
474
  },