@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
@@ -1,64 +0,0 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { SeptumRepository } from "../../core/database/repository.ts";
3
- import type { GetSymbolImpactArgs } from "../../types/index.ts";
4
-
5
- export function handleGetSymbolImpact(
6
- repo: SeptumRepository,
7
- _config: ValidatedSeptumConfig,
8
- args: GetSymbolImpactArgs,
9
- workspaceRoot?: string
10
- ) {
11
- const symbol = (args.symbol_ref?.name || args.symbol || (args as unknown as Record<string, unknown>).query || "").toString().trim();
12
- if (!symbol) {
13
- throw new Error(
14
- "Missing required argument: 'symbol' (e.g. 'OrderService::cancelOrder', 'OrderService', or 'cancelOrder')"
15
- );
16
- }
17
-
18
- if (args.symbol_ref) {
19
- const file = repo.getFileByPath(args.symbol_ref.file_path);
20
- if (!file || file.content_hash !== args.symbol_ref.indexed_content_hash) {
21
- return { content: [{ type: "text" as const, text: JSON.stringify({
22
- target_symbol: symbol, status: "stale_reference", found_in_index: false,
23
- message: "Declaration reference is stale; locate the symbol again.",
24
- }) }] };
25
- }
26
- }
27
-
28
- const candidates = repo.findSymbolsByName(symbol, {
29
- domain: args.domain,
30
- filePath: args.file_path,
31
- reference: args.symbol_ref,
32
- });
33
- if (candidates.length > 1) {
34
- return { content: [{ type: "text" as const, text: JSON.stringify({
35
- status: "ambiguous", target_symbol: symbol, found_in_index: false,
36
- candidates: candidates.map(candidate => ({ name: candidate.name, file_path: candidate.file_path, symbol_ref: candidate.symbol_ref })),
37
- message: "Multiple declarations match; select a candidate with symbol_ref or narrow with file_path.",
38
- }, null, 2) }] };
39
- }
40
- const selectedCandidate = candidates[0];
41
- const impact = repo.getSymbolImpact(symbol, {
42
- domain: args.domain,
43
- filePath: args.file_path || selectedCandidate?.file_path,
44
- reference: args.symbol_ref || selectedCandidate?.symbol_ref,
45
- workspaceRoot: workspaceRoot || args.workspace_path,
46
- });
47
-
48
- const relationships = repo.getImportRelationships(workspaceRoot || args.workspace_path);
49
- const targetFiles = candidates.map(candidate => candidate.file_path);
50
- const importDependents = relationships.filter(edge => edge.resolution.status === "resolved" && edge.resolution.targets.some(target => target.files.some(file => targetFiles.includes(file))));
51
- const payload = { ...impact, coverage: "partial", inbound_callers_complete: false,
52
- relationship_limits: "Legacy inbound caller hints are inferred; import dependencies are reported separately and do not prove executed calls.",
53
- import_dependents: importDependents,
54
- resolution_warnings: relationships.filter(edge => !["resolved","external"].includes(edge.resolution.status) || edge.resolution.coverage === "conditional"),
55
- };
56
- return {
57
- content: [
58
- {
59
- type: "text" as const,
60
- text: JSON.stringify(payload, null, 2),
61
- },
62
- ],
63
- };
64
- }
@@ -1,175 +0,0 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { SeptumRepository } from "../../core/database/repository.ts";
3
- import { resolve } from "node:path";
4
- import { computeContentHash } from "../../core/ingestion/hasher.ts";
5
- import { isPathContained } from "../../core/resolver/path-resolver.ts";
6
- import { readSourceFile } from "../../core/resources/source-files.ts";
7
- import { SymbolLocator } from "../../core/resolver/symbol-locator.ts";
8
- import type { GetSymbolArgs } from "../../types/index.ts";
9
-
10
- export function handleGetSymbol(
11
- repo: SeptumRepository,
12
- _config: ValidatedSeptumConfig,
13
- args: GetSymbolArgs,
14
- workspaceRoot?: string
15
- ) {
16
- const symbol = (args.symbol_ref?.name || args.symbol || (args as unknown as Record<string, unknown>).query || "").toString().trim();
17
- if (!symbol) {
18
- throw new Error(
19
- "Missing required argument: 'symbol' (e.g. 'OrderController::cancelOrder', 'OrderService', or 'cancelOrder')"
20
- );
21
- }
22
-
23
- if (args.symbol_ref) {
24
- const file = repo.getFileByPath(args.symbol_ref.file_path);
25
- if (!file || file.content_hash !== args.symbol_ref.indexed_content_hash) {
26
- return { content: [{ type: "text" as const, text: JSON.stringify({
27
- symbol, status: "stale_reference", found: false,
28
- message: "Declaration reference is stale; locate the symbol again.",
29
- ...(args.include_source ? { source_slice: { status: "stale", reason: "stale_reference" } } : {}),
30
- }) }] };
31
- }
32
- }
33
- const selectedCandidates = repo.findSymbolsByName(symbol, {
34
- domain: args.domain, filePath: args.file_path, reference: args.symbol_ref,
35
- });
36
- if (selectedCandidates.length > 1) {
37
- const candidates = selectedCandidates.map(candidate => ({
38
- name: candidate.name, file_path: candidate.file_path, kind: candidate.kind, signature: candidate.signature,
39
- start_line: candidate.line_start, end_line: candidate.line_end, symbol_ref: candidate.symbol_ref,
40
- }));
41
- return { content: [{ type: "text" as const, text: JSON.stringify({
42
- symbol, status: "ambiguous", found: false, candidates,
43
- ...(args.include_source ? { source_slice: { status: "ambiguous", candidates } } : {}),
44
- message: "Multiple matching declarations; select a candidate with symbol_ref or narrow with file_path.",
45
- }, null, 2) }] };
46
- }
47
-
48
- const details = repo.getSymbolDetails(symbol, {
49
- domain: args.domain,
50
- filePath: args.file_path,
51
- reference: args.symbol_ref,
52
- // This inspection path reads the complete file for outbound-call inference; keep source requests bounded.
53
- includeDependencies: args.include_source ? false : args.include_dependencies,
54
- workspaceRoot: workspaceRoot || args.workspace_path,
55
- });
56
-
57
- if (details) {
58
- const payload: Record<string, unknown> = { ...details };
59
- if (args.include_source) {
60
- delete payload.dependencies_injected;
61
- delete payload.outbound_calls;
62
- delete payload.resolved_outbound_calls;
63
- delete payload.connected_files;
64
- const root = resolve(workspaceRoot || args.workspace_path || process.cwd());
65
- const file = repo.getFileByPath(details.file_path);
66
- const fullPath = resolve(root, details.file_path);
67
- if (!file) {
68
- payload.source_slice = { status: "unavailable", file_path: details.file_path, reason: "file_not_indexed" };
69
- } else if (!isPathContained(fullPath, root)) {
70
- payload.source_slice = { status: "out_of_scope", file_path: details.file_path };
71
- } else {
72
- try {
73
- const source = readSourceFile(fullPath);
74
- const currentHash = computeContentHash(source);
75
- if (currentHash !== file.content_hash) {
76
- payload.source_slice = {
77
- status: "stale",
78
- file_path: details.file_path,
79
- indexed_content_hash: file.content_hash,
80
- current_content_hash: currentHash,
81
- message: "File has been modified on disk since last indexed. Run 'septum sync' to synchronize AST coordinates.",
82
- action_required: "septum sync",
83
- };
84
- } else {
85
- const lineStarts = [0];
86
- const lineEnds: number[] = [];
87
- for (const match of source.matchAll(/\r\n|\n|\r/g)) {
88
- const offset = match.index!;
89
- lineEnds.push(offset);
90
- lineStarts.push(offset + match[0].length);
91
- }
92
- lineEnds.push(source.length);
93
- const startLine = args.source_start_line ?? details.exact_range.start_line;
94
- const limit = Math.min(args.source_line_limit ?? 120, 200);
95
- if (
96
- startLine < details.exact_range.start_line ||
97
- startLine > details.exact_range.end_line ||
98
- startLine > lineStarts.length
99
- ) {
100
- payload.source_slice = {
101
- status: "invalid_range",
102
- file_path: details.file_path,
103
- allowed_start_line: details.exact_range.start_line,
104
- allowed_end_line: details.exact_range.end_line,
105
- };
106
- } else {
107
- const endLine = Math.min(details.exact_range.end_line, startLine + limit - 1, lineStarts.length);
108
- const truncated = endLine < details.exact_range.end_line;
109
- payload.source_slice = {
110
- status: "current",
111
- file_path: details.file_path,
112
- indexed_content_hash: file.content_hash,
113
- current_content_hash: currentHash,
114
- start_line: startLine,
115
- end_line: endLine,
116
- text: source.slice(lineStarts[startLine - 1], lineEnds[endLine - 1]),
117
- truncated,
118
- related_dependency_analysis: "omitted_to_keep_source_read_bounded",
119
- ...(truncated ? { next_start_line: endLine + 1 } : {}),
120
- };
121
- }
122
- }
123
- } catch (error) {
124
- payload.source_slice = {
125
- status: "unavailable",
126
- file_path: details.file_path,
127
- reason: error instanceof Error && error.name === "SourceFileLimitError"
128
- ? "source_exceeds_read_limit"
129
- : "source_unavailable",
130
- };
131
- }
132
- }
133
- }
134
- return {
135
- content: [
136
- {
137
- type: "text" as const,
138
- text: JSON.stringify(payload, null, 2),
139
- },
140
- ],
141
- };
142
- }
143
-
144
- // Fallback to fuzzy SymbolLocator to provide actionable hints
145
- const locator = new SymbolLocator(repo);
146
- const fallback = locator.locate(symbol, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
147
-
148
- const payload = {
149
- symbol,
150
- found: false,
151
- message: `Symbol '${symbol}' was not found in the deterministic catalog.`,
152
- suggestions: fallback.suggestions.map((s) => ({
153
- name: s.name,
154
- similarity_score: Math.round(s.similarity_score * 100) / 100,
155
- exact_range: {
156
- start_line: s.line_start,
157
- end_line: s.line_end,
158
- total_lines: s.line_end - s.line_start + 1,
159
- },
160
- signature: s.signature,
161
- file_path: s.file_path,
162
- })),
163
- sibling_methods: fallback.sibling_methods,
164
- ...(args.include_source ? { source_slice: { status: "unavailable", reason: "symbol_not_found" } } : {}),
165
- };
166
-
167
- return {
168
- content: [
169
- {
170
- type: "text" as const,
171
- text: JSON.stringify(payload, null, 2),
172
- },
173
- ],
174
- };
175
- }
@@ -1,196 +0,0 @@
1
- import { existsSync, readdirSync } from "node:fs";
2
- import { isAbsolute, join } from "node:path";
3
- import { isIgnoredDirectory } from "../../core/resources/ignore.ts";
4
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
5
- import type { SeptumRepository } from "../../core/database/repository.ts";
6
- import type { IngestionPipeline } from "../../core/ingestion/pipeline.ts";
7
- import {
8
- SymbolLocator,
9
- type SymbolLocationResult,
10
- } from "../../core/resolver/symbol-locator.ts";
11
- import type { LocateSymbolArgs } from "../schemas.ts";
12
-
13
- export type { LocateSymbolArgs } from "../schemas.ts";
14
-
15
- export async function handleLocateSymbol(
16
- repo: SeptumRepository,
17
- config: ValidatedSeptumConfig,
18
- args: Partial<LocateSymbolArgs>,
19
- pipeline?: IngestionPipeline,
20
- workspaceRoot?: string
21
- ) {
22
- const query = (args.query || args.symbol || args.symbol_ref?.name || "").toString().trim();
23
- if (!query) {
24
- throw new Error(
25
- "Missing required argument: 'query' (e.g. 'OrderController::calculateTotal' or error log snippet)"
26
- );
27
- }
28
-
29
- const root = workspaceRoot || args.workspace_path || process.cwd();
30
- const limit = args.limit ?? 10;
31
-
32
- // 1. Guarded Lazy Ingestion on Empty Catalog / Cold Start
33
- if (repo.countFiles() === 0 && pipeline) {
34
- try {
35
- await pipeline.run(config);
36
- } catch {
37
- // Ingestion fallback
38
- }
39
-
40
- if (repo.countFiles() === 0) {
41
- const diagnostic = {
42
- status: "NOT_INDEXED",
43
- found: false,
44
- query,
45
- message: `Workspace '${root}' belum terindeks dalam Septum catalog.`,
46
- suggested_action: {
47
- tool: "septum_domain",
48
- params: { action: "register", name: "core", root: "src", ingest_now: true },
49
- },
50
- agent_guidance:
51
- "Panggil tool 'septum_domain(action: \"register\", name: \"core\", root: \"src\", ingest_now: true)' untuk mendaftarkan dan mengindeks codebase ini, atau jalankan 'septum init' di terminal workspace.",
52
- };
53
-
54
- return {
55
- content: [
56
- {
57
- type: "text",
58
- text: JSON.stringify(diagnostic, null, 2),
59
- },
60
- ],
61
- metadata: diagnostic,
62
- };
63
- }
64
- }
65
-
66
- const locator = new SymbolLocator(repo);
67
- let result: SymbolLocationResult = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
68
-
69
- // 2. JIT Delta Sync: Check if located file has changed on disk since last ingest
70
- if (result.found && result.file_path && pipeline) {
71
- const fullPath = isAbsolute(result.file_path)
72
- ? result.file_path
73
- : join(root, result.file_path);
74
- try {
75
- const reindexed = await pipeline.ingestFile(fullPath, config);
76
- if (reindexed) {
77
- result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
78
- }
79
- } catch {
80
- // Silently fall back to existing result
81
- }
82
- }
83
-
84
- // 3. Fallback on Cache Miss: Search for candidate source files matching the query terms
85
- if (!result.found && pipeline) {
86
- try {
87
- const cleanTerm = query.replace(/[^a-zA-Z0-9_]/g, " ").trim().split(/\s+/)[0] || "";
88
- if (cleanTerm.length >= 3) {
89
- const candidateFiles = findCandidateFiles(root, cleanTerm);
90
- let anyReindexed = false;
91
- for (const candidate of candidateFiles) {
92
- const reindexed = await pipeline.ingestFile(candidate, config);
93
- if (reindexed) anyReindexed = true;
94
- }
95
- if (anyReindexed) {
96
- result = locator.locate(query, args.domain, { filePath: args.file_path, reference: args.symbol_ref });
97
- }
98
- }
99
- } catch {
100
- // Ignore candidate scan errors
101
- }
102
- }
103
-
104
- const exactLineCount = result.exact_symbol
105
- ? result.exact_symbol.line_end - result.exact_symbol.line_start + 1
106
- : 0;
107
- const complexitySmell =
108
- exactLineCount > 300
109
- ? {
110
- is_high_complexity: true,
111
- threshold: 300,
112
- total_lines: exactLineCount,
113
- warning: `Symbol '${result.exact_symbol?.name}' spans ${exactLineCount} lines (exceeds 300-line threshold). Candidate for decomposition/refactoring.`,
114
- }
115
- : undefined;
116
-
117
- const suggestions = (result.suggestions || []).slice(0, limit);
118
- let summary = result.found
119
- ? `[FOUND] ${result.exact_symbol?.name || query} in ${result.file_path} (lines ${result.exact_symbol?.line_start}-${result.exact_symbol?.line_end})`
120
- : `[NOT FOUND] Symbol '${query}' not found. ${suggestions.length > 0 ? `Top suggestions: ${suggestions.map((s) => s.name).slice(0, 3).join(", ")}` : "No close suggestions."}`;
121
-
122
- if (complexitySmell) {
123
- summary += ` | ⚠️ High-Complexity Smell: spans ${exactLineCount} lines (> 300L)`;
124
- }
125
-
126
- const payload = {
127
- status: result.status ?? (result.found ? "success" : "not_found"),
128
- candidates: result.candidates,
129
- symbol_ref: result.symbol_ref,
130
- visibility_semantics: "legacy_normalized",
131
- found: result.found,
132
- query,
133
- file_path: result.file_path || null,
134
- container_name: result.container_name || null,
135
- exact_symbol: result.exact_symbol
136
- ? {
137
- ...result.exact_symbol,
138
- total_lines: exactLineCount,
139
- }
140
- : null,
141
- complexity_smell: complexitySmell,
142
- sibling_methods: result.sibling_methods || [],
143
- suggestions,
144
- summary,
145
- message: result.message || summary,
146
- };
147
-
148
- return {
149
- content: [
150
- {
151
- type: "text" as const,
152
- text: JSON.stringify(payload, null, 2),
153
- },
154
- ],
155
- metadata: payload,
156
- };
157
- }
158
-
159
- /**
160
- * Searches for potential candidate files whose names resemble parts of the query term.
161
- */
162
- function findCandidateFiles(root: string, term: string): string[] {
163
- const matched: string[] = [];
164
- const lowerTerm = term.toLowerCase().replace(/_/g, "");
165
- const searchDirs = ["src", "app", "lib"].map((d) => join(root, d)).filter((d) => existsSync(d));
166
-
167
- function scan(dir: string, depth: number = 0) {
168
- if (depth > 4) return;
169
- try {
170
- const entries = readdirSync(dir, { withFileTypes: true });
171
- for (const e of entries) {
172
- if (isIgnoredDirectory(e.name)) continue;
173
- const full = join(dir, e.name);
174
- if (e.isDirectory()) {
175
- scan(full, depth + 1);
176
- } else if (e.isFile() && /\.(ts|tsx|js|jsx|php|py|go)$/i.test(e.name)) {
177
- const lowerName = e.name.toLowerCase().replace(/[-_.]/g, "");
178
- if (lowerName.includes(lowerTerm) || lowerTerm.includes(lowerName.replace(/\.[^.]+$/, ""))) {
179
- matched.push(full);
180
- if (matched.length >= 5) return;
181
- }
182
- }
183
- }
184
- } catch {
185
- // Ignore
186
- }
187
- }
188
-
189
- for (const sDir of searchDirs) {
190
- scan(sDir);
191
- if (matched.length >= 5) break;
192
- }
193
-
194
- return matched;
195
- }
196
-
@@ -1,75 +0,0 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { SeptumRepository } from "../../core/database/repository.ts";
3
- import { IngestionPipeline, type IngestionMetrics } from "../../core/ingestion/pipeline.ts";
4
- import { assertPathContained } from "../../core/resolver/path-resolver.ts";
5
- import type { RegisterDomainArgs } from "../schemas.ts";
6
-
7
- export type { RegisterDomainArgs } from "../schemas.ts";
8
-
9
- export async function handleRegisterDomain(
10
- repo: SeptumRepository,
11
- config: ValidatedSeptumConfig,
12
- args: Partial<RegisterDomainArgs>,
13
- workspaceRoot: string = process.cwd(),
14
- signal?: AbortSignal
15
- ) {
16
- signal?.throwIfAborted();
17
- const domainName = (args.domain || args.name || "").trim();
18
- if (!domainName || !args.root) {
19
- throw new Error("Missing required arguments: 'domain' (or 'name') and 'root' are required.");
20
- }
21
-
22
- // SV-02: Enforce workspace containment (reject traversal/absolute/symlink escape)
23
- assertPathContained(args.root, workspaceRoot, "Domain root");
24
- signal?.throwIfAborted();
25
-
26
- const domainConfig = {
27
- root: args.root,
28
- description: args.description || `Domain: ${domainName}`,
29
- allowed_dependencies: args.allowed_dependencies,
30
- forbidden_dependencies: args.forbidden_dependencies,
31
- archetypes: args.archetypes,
32
- };
33
-
34
- const domainId = repo.domains.upsertDomain(domainName, domainConfig);
35
- const stored = repo.domains.getDomainByName(domainName);
36
- const canonicalName = stored?.name || domainName;
37
- const finalConfig = {
38
- root: stored?.root_path || domainConfig.root,
39
- description: domainConfig.description,
40
- allowed_dependencies: stored ? JSON.parse(stored.allowed_deps_json || "[]") : (domainConfig.allowed_dependencies || []),
41
- forbidden_dependencies: stored ? JSON.parse(stored.forbidden_deps_json || "[]") : (domainConfig.forbidden_dependencies || []),
42
- archetypes: stored ? JSON.parse(stored.archetypes_json || "{}") : (domainConfig.archetypes || {}),
43
- };
44
-
45
- config.domains[canonicalName] = finalConfig;
46
-
47
- let ingestionMetrics: IngestionMetrics | null = null;
48
- if (args.ingest_now) {
49
- const pipeline = new IngestionPipeline(repo, workspaceRoot);
50
- ingestionMetrics = await pipeline.run(config);
51
- }
52
-
53
- return {
54
- content: [
55
- {
56
- type: "text" as const,
57
- text: JSON.stringify(
58
- {
59
- status: "success",
60
- message: `Domain '${canonicalName}' successfully registered in SQLite SSOT.${
61
- args.ingest_now ? " Initial ingestion completed." : ""
62
- }`,
63
- domain_id: domainId,
64
- domain: canonicalName,
65
- name: canonicalName,
66
- config: finalConfig,
67
- ...(ingestionMetrics ? { ingestion_metrics: ingestionMetrics } : {}),
68
- },
69
- null,
70
- 2
71
- ),
72
- },
73
- ],
74
- };
75
- }
@@ -1,110 +0,0 @@
1
- import type { ValidatedSeptumConfig } from "../../core/config/schema.ts";
2
- import type { SeptumRepository } from "../../core/database/repository.ts";
3
- import { SessionManager } from "../../core/session/session-manager.ts";
4
- import type { RegisterFeatureArgs } from "../schemas.ts";
5
-
6
- export type { RegisterFeatureArgs } from "../schemas.ts";
7
-
8
- export async function handleRegisterFeature(
9
- repo: SeptumRepository,
10
- config: ValidatedSeptumConfig,
11
- args: Partial<RegisterFeatureArgs>,
12
- workspaceRoot: string = process.cwd()
13
- ) {
14
- const featureKey = (args.feature_key || args.feature || "").toString().trim();
15
- const domain = (args.domain || args.domain_name || "").toString().trim();
16
-
17
- if (!featureKey || !domain) {
18
- throw new Error("Missing required arguments: 'feature_key' and 'domain' are required.");
19
- }
20
-
21
- // MCP-15: Validate domain is registered in DB or config
22
- const registeredDomain = repo.getDomainByName(domain);
23
- const configDomain = Object.keys(config.domains || {}).find(
24
- (d) => d.toLowerCase() === domain.toLowerCase()
25
- );
26
- if (!registeredDomain && !configDomain) {
27
- throw new Error(`Domain '${domain}' is not registered. Cannot lock feature to an unknown domain.`);
28
- }
29
- const canonicalDomain = registeredDomain?.name || configDomain || domain;
30
-
31
- const rawTouchpoints = args.allowed_touchpoints ?? [];
32
- const allowedTouchpoints = Array.isArray(rawTouchpoints)
33
- ? rawTouchpoints
34
- : typeof rawTouchpoints === "string"
35
- ? [rawTouchpoints]
36
- : [];
37
-
38
- // MCP-15: Validate supported touchpoint glob patterns (exact, /*, /**)
39
- for (const tp of allowedTouchpoints) {
40
- const normalized = tp.replace(/\\/g, "/");
41
- if (normalized.includes("*")) {
42
- if (!normalized.endsWith("/*") && !normalized.endsWith("/**") && normalized !== "*" && normalized !== "**") {
43
- throw new Error(
44
- `Unsupported touchpoint glob pattern '${tp}'. Septum touchpoints support exact paths, '/*', and '/**'.`
45
- );
46
- }
47
- }
48
- }
49
-
50
- const rawReuse = args.reuse_symbols;
51
- const reuseSymbols: string[] = Array.isArray(rawReuse)
52
- ? rawReuse
53
- : typeof rawReuse === "string"
54
- ? [rawReuse]
55
- : [];
56
-
57
- const featureConfig = {
58
- domain: canonicalDomain,
59
- description: args.description || `Feature: ${featureKey}`,
60
- allowed_touchpoints: allowedTouchpoints,
61
- reuse_symbols: reuseSymbols,
62
- input_contract: args.input_contract || {},
63
- output_contract: args.output_contract || {},
64
- };
65
-
66
- SessionManager.saveActiveSession(workspaceRoot, {
67
- feature_key: featureKey,
68
- domain: canonicalDomain,
69
- touchpoints: featureConfig.allowed_touchpoints,
70
- locked_at: new Date().toISOString(),
71
- }, SessionManager.getOwnerId(), {
72
- repo,
73
- save: () => {
74
- const existingRaw = repo.getMeta("features_json");
75
- const featuresMap = existingRaw ? JSON.parse(existingRaw) : {};
76
- featuresMap[featureKey] = featureConfig;
77
- repo.setMeta("features_json", JSON.stringify(featuresMap));
78
- },
79
- });
80
-
81
- // 3. Update in-memory config only after both SQLite and session lease succeeded
82
- if (!config.features) {
83
- config.features = {};
84
- }
85
- config.features[featureKey] = featureConfig;
86
-
87
-
88
-
89
- return {
90
- content: [
91
- {
92
- type: "text" as const,
93
- text: JSON.stringify(
94
- {
95
- status: "success",
96
- message: `Feature '${featureKey}' successfully registered in SQLite SSOT and session lease established.`,
97
- feature_key: featureKey,
98
- feature: featureKey,
99
- domain: canonicalDomain,
100
- touchpoints: featureConfig.allowed_touchpoints,
101
- reuse_symbols: featureConfig.reuse_symbols,
102
- },
103
- null,
104
- 2
105
- ),
106
- },
107
- ],
108
- };
109
- }
110
-