@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -117,9 +117,12 @@ export function findProjectRoot(fromPath: string): string {
117
117
  */
118
118
  export function resolveWorkspaceRoot(pathHint?: string): string {
119
119
  if (pathHint && typeof pathHint === "string" && pathHint.trim()) {
120
- const trimmed = pathHint.trim().replace(/^['"]|['"]$/g, "");
121
- const absHint = resolve(trimmed);
122
- const candidate = existsSync(absHint) && statSync(absHint).isDirectory() ? canonicalizePath(absHint) : findProjectRoot(trimmed);
120
+ const trimmed = pathHint.trim();
121
+ const unquoted = trimmed.replace(/^['"]|['"]$/g, "");
122
+ const literalPath = resolve(trimmed);
123
+ // Keep an existing literal path before accepting shell-style quoting.
124
+ const absHint = unquoted !== trimmed && !existsSync(literalPath) ? resolve(unquoted) : literalPath;
125
+ const candidate = existsSync(absHint) && statSync(absHint).isDirectory() ? canonicalizePath(absHint) : findProjectRoot(absHint);
123
126
  if (candidate && existsSync(candidate) && !isAppHostDirectory(candidate)) {
124
127
  setLastKnownProjectRoot(candidate);
125
128
  return candidate;
@@ -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
+ }
@@ -0,0 +1,94 @@
1
+ import { relative, resolve } from "node:path";
2
+ import type { SeptumRepository } from "../database/repository.ts";
3
+ import { computeContentHash } from "../ingestion/hasher.ts";
4
+ import { TopologyDetector } from "../discovery/topology-detector.ts";
5
+ import { SemanticSliceExtractorRegistry, type AdapterExtractionResult } from "../parser/extractors/registry.ts";
6
+ import { SEMANTIC_FINGERPRINT } from "../parser/semantic-revision.ts";
7
+ import { scanSourceFiles, type SourceInventory } from "../resources/source-inventory.ts";
8
+ import { collectSourceSkips, readSourceFile, SOURCE_READ_REVISION, sourceObservationsCurrent } from "../resources/source-files.ts";
9
+ import { assertPathContained } from "./path-resolver.ts";
10
+ import { CallGraphTracer } from "./call-graph-tracer.ts";
11
+ import { normalizeGraphQLEntrypoints } from "../parser/extractors/graphql-entrypoint.ts";
12
+
13
+ interface CatalogOptions {
14
+ ignorePatterns: string[];
15
+ signal?: AbortSignal;
16
+ semanticRevision?: string;
17
+ inventoryRevision?: string;
18
+ inventory?: SourceInventory;
19
+ }
20
+
21
+ export function sliceInputsCurrent(repo: SeptumRepository, root: string, signal?: AbortSignal): boolean {
22
+ try {
23
+ if (repo.getMeta("semantic_extractor_revision") !== SEMANTIC_FINGERPRINT ||
24
+ (!!repo.getMeta("semantic_inputs") && repo.getMeta("semantic_input_revision") !== SOURCE_READ_REVISION) ||
25
+ !sourceObservationsCurrent(root, JSON.parse(repo.getMeta("semantic_observations") || '{"paths":[],"directories":[]}'))) return false;
26
+ const inputs = JSON.parse(repo.getMeta("semantic_inputs") || "[]") as Array<{ path: string; hash: string }>;
27
+ return inputs.every(input => {
28
+ signal?.throwIfAborted();
29
+ assertPathContained(input.path, root, "Semantic source");
30
+ return computeContentHash(readSourceFile(resolve(root, input.path))) === input.hash;
31
+ });
32
+ } catch { signal?.throwIfAborted(); return false; }
33
+ }
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
+
50
+ /** Publish slices and their input evidence together; failed builds retain a dirty catalog. */
51
+ export async function rebuildSliceCatalog(repo: SeptumRepository, root: string, options: CatalogOptions): Promise<void> {
52
+ try {
53
+ const reports: AdapterExtractionResult[] = [];
54
+ let inventory: SourceInventory;
55
+ const extracted = await collectSourceSkips(root, async () => {
56
+ inventory = options.inventory ?? scanSourceFiles(root, { ignorePatterns: options.ignorePatterns, signal: options.signal });
57
+ const topology = TopologyDetector.detect(root);
58
+ const slices = await SemanticSliceExtractorRegistry.extractAllSlices(root, topology.framework, undefined, options.signal, {
59
+ ignorePatterns: options.ignorePatterns, inventory, onResult: result => reports.push(result),
60
+ });
61
+ // Complement uncovered files only. Reinterpreting an adapter's router file
62
+ // could invent unprefixed routes from mounted framework routers.
63
+ const coveredFiles = new Set<string>();
64
+ for (const slice of slices) {
65
+ if (slice.controller_file) coveredFiles.add(slice.controller_file);
66
+ const chain = JSON.parse(slice.execution_chain_json) as Array<{ stage?: string; file?: string }>;
67
+ for (const node of chain) if (node.stage === "ingress" && node.file) coveredFiles.add(node.file);
68
+ }
69
+ const fallback = new CallGraphTracer(repo, root).traceAllSlices(8, { excludeEntrypointFiles: coveredFiles });
70
+ return normalizeGraphQLEntrypoints([...slices, ...fallback]);
71
+ });
72
+ options.signal?.throwIfAborted();
73
+ if (extracted.skipped.length) {
74
+ repo.setMeta("semantic_skipped_files", JSON.stringify(extracted.skipped));
75
+ const skipped = JSON.parse(repo.getMeta("skipped_files") || "[]") as Array<{ path: string; reason: string }>;
76
+ repo.setMeta("skipped_files", JSON.stringify([...new Map([...skipped, ...extracted.skipped].map(file => [file.path, file])).values()]));
77
+ throw new Error("Semantic extraction incomplete: source read limit exceeded.");
78
+ }
79
+ repo.runInTransaction(() => {
80
+ repo.clearVerticalSlices();
81
+ repo.insertVerticalSlices(extracted.value);
82
+ repo.setMeta("slices_dirty", "");
83
+ repo.setMeta("semantic_extractor_revision", SEMANTIC_FINGERPRINT);
84
+ repo.setMeta("semantic_inputs", JSON.stringify(extracted.inputs));
85
+ repo.setMeta("semantic_observations", JSON.stringify(extracted.observations));
86
+ repo.setMeta("semantic_input_revision", SOURCE_READ_REVISION);
87
+ repo.setMeta("semantic_skipped_files", "[]");
88
+ repo.setMeta("semantic_adapter_results", JSON.stringify(reports));
89
+ if (options.semanticRevision !== undefined) repo.setMeta("semantic_revision", options.semanticRevision);
90
+ if (options.inventoryRevision !== undefined) repo.setMeta("semantic_inventory", options.inventoryRevision);
91
+ repo.setMeta("semantic_catalog_files", JSON.stringify(inventory.files.map(file => relative(root, file).replace(/\\/g, "/"))));
92
+ });
93
+ } catch (error) { repo.setMeta("slices_dirty", "1"); throw error; }
94
+ }
@@ -0,0 +1,22 @@
1
+ import type { ExecutionChainNode } from "../../types/index.ts";
2
+
3
+ export const SLICE_RELATIONSHIP_LIMITS =
4
+ "Static, partial context. Relation labels describe evidence attached to nodes, not a proven sequential execution path. Imports do not prove calls; static calls do not prove runtime execution. Missing relationship metadata is unknown.";
5
+
6
+ export function formatSliceNode(node: ExecutionChainNode): string {
7
+ const relation = node.relationship;
8
+ return `[${(node.stage || "stage").toUpperCase()}] ${node.symbol} [${relation?.kind ?? "unknown"}; ${relation?.derivation ?? "unknown"}]${node.semantic_analysis ? " [lexical heuristic]" : ""}`;
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
+ }