@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
@@ -16,6 +16,8 @@ export interface SuggestionMatch {
16
16
  signature: string;
17
17
  line_start: number;
18
18
  line_end: number;
19
+ start_line?: number;
20
+ end_line?: number;
19
21
  similarity_score: number; // 0.0 - 1.0
20
22
  file_path?: string;
21
23
  }
@@ -36,6 +38,8 @@ export interface SymbolLocationResult {
36
38
  visibility: string;
37
39
  line_start: number;
38
40
  line_end: number;
41
+ start_line?: number;
42
+ end_line?: number;
39
43
  };
40
44
  sibling_methods?: string[];
41
45
  suggestions: SuggestionMatch[];
@@ -156,7 +160,7 @@ export class SymbolLocator {
156
160
  return {
157
161
  ...base, found: true, file_path: exact.file_path, container_name: exact.symbol_ref.container,
158
162
  symbol_ref: exact.symbol_ref,
159
- exact_symbol: { name: exact.name, kind: exact.kind, signature: exact.signature, visibility: exact.visibility, line_start: exact.line_start, line_end: exact.line_end },
163
+ exact_symbol: { name: exact.name, kind: exact.kind, signature: exact.signature, visibility: exact.visibility, line_start: exact.line_start, line_end: exact.line_end, start_line: exact.line_start, end_line: exact.line_end },
160
164
  sibling_methods: details?.sibling_methods,
161
165
  message: `Found exact symbol '${exact.name}' in ${exact.file_path}:${exact.line_start}`,
162
166
  };
@@ -166,19 +170,68 @@ export class SymbolLocator {
166
170
  .filter(s => ["class", "interface", "trait", "struct", "enum"].includes(s.kind)) : [];
167
171
  const owner = owners.length === 1 ? owners[0] : undefined;
168
172
  const siblings = owner ? this.repo.getSymbolDetails(owner.name, { ...selection, reference: owner.symbol_ref, includeDependencies: false })?.sibling_methods : undefined;
173
+ const domainId = selection.domain ? this.repo.getAllDomains().find(d => d.name.toLowerCase() === selection.domain!.toLowerCase())?.id : undefined;
169
174
  const searchable = owner ? this.repo.getSymbolsByFileId(owner.file_id)
170
175
  .filter(s => s.kind === "method" && symbolReference({ ...s, file_path: owner.file_path, indexed_content_hash: owner.indexed_content_hash }).container === owner.name)
171
- .map(s => ({ ...s, file_path: owner.file_path })) : this.repo.getAllSymbolsWithFiles();
172
- const domainId = selection.domain ? this.repo.getAllDomains().find(d => d.name.toLowerCase() === selection.domain!.toLowerCase())?.id : undefined;
173
- const suggestions = searchable
174
- .filter(s => !selection.filePath || s.file_path === selection.filePath)
175
- .filter(s => !selection.domain || this.repo.getFileByPath(s.file_path)?.domain_id === domainId)
176
- .map(s => ({
177
- name: owner ? s.name.split(/::|[.#]/).pop()! : s.name, kind: s.kind, signature: s.signature, line_start: s.line_start, line_end: s.line_end, file_path: s.file_path,
178
- similarity_score: Math.round(Math.max(calculateSimilarity(target, s.name.split(/::|[.#]/).pop()!), calculateSimilarity(parsed.raw, s.name)) * 100) / 100,
179
- }))
180
- .filter(s => s.similarity_score >= 0.3)
181
- .sort((a, b) => b.similarity_score - a.similarity_score).slice(0, 10);
176
+ .map(s => ({ ...s, file_path: owner.file_path }))
177
+ : selection.domain && domainId === undefined
178
+ ? []
179
+ : typeof this.repo.findFuzzySymbolCandidates === "function"
180
+ ? this.repo.findFuzzySymbolCandidates(target, {
181
+ ...(selection.filePath ? { filePath: selection.filePath } : {}),
182
+ ...(domainId !== undefined ? { domainId } : {}),
183
+ limit: 500,
184
+ })
185
+ : this.repo.getAllSymbolsWithFiles({
186
+ ...(selection.filePath ? { filePath: selection.filePath } : {}),
187
+ ...(domainId !== undefined ? { domainId } : {}),
188
+ });
189
+ const charBitmask = (str: string): number => {
190
+ let mask = 0;
191
+ for (let i = 0; i < str.length; i++) {
192
+ const c = str.charCodeAt(i) | 32;
193
+ if (c >= 97 && c <= 122) mask |= 1 << (c - 97);
194
+ }
195
+ return mask;
196
+ };
197
+ const popcount = (n: number): number => {
198
+ let x = n;
199
+ let count = 0;
200
+ while (x) { x &= x - 1; count++; }
201
+ return count;
202
+ };
203
+ const targetMask = charBitmask(target);
204
+ const rawMask = charBitmask(parsed.raw);
205
+ const minOverlap = target.length >= 4 && searchable.length > 500 ? Math.min(2, popcount(targetMask)) : 0;
206
+ const seenNames = new Set<string>();
207
+ const scored: Array<{
208
+ name: string; kind: (typeof searchable)[number]["kind"]; signature: string;
209
+ line_start: number; line_end: number; start_line: number; end_line: number;
210
+ file_path: string; similarity_score: number;
211
+ }> = [];
212
+ for (const s of searchable) {
213
+ if (selection.filePath && s.file_path !== selection.filePath) continue;
214
+ if (minOverlap > 0) {
215
+ const candMask = charBitmask(s.name);
216
+ if (popcount(targetMask & candMask) < minOverlap && popcount(rawMask & candMask) < minOverlap) continue;
217
+ }
218
+ const leaf = s.name.split(/::|[.#]/).pop()!;
219
+ const score = Math.round(Math.max(calculateSimilarity(target, leaf), calculateSimilarity(parsed.raw, s.name)) * 100) / 100;
220
+ if (score < 0.3) continue;
221
+ scored.push({
222
+ name: owner ? leaf : s.name, kind: s.kind, signature: s.signature,
223
+ line_start: s.line_start, line_end: s.line_end, start_line: s.line_start, end_line: s.line_end,
224
+ file_path: s.file_path, similarity_score: score,
225
+ });
226
+ }
227
+ scored.sort((a, b) => b.similarity_score - a.similarity_score);
228
+ const suggestions = [];
229
+ for (const s of scored) {
230
+ if (seenNames.has(s.name)) continue;
231
+ seenNames.add(s.name);
232
+ suggestions.push(s);
233
+ if (suggestions.length >= 10) break;
234
+ }
182
235
  return { ...base, file_path: owner?.file_path, container_name: owner?.name, sibling_methods: siblings, suggestions, message: `Symbol '${parsed.raw}' not found.${suggestions.length ? ` Did you mean '${suggestions[0]!.name}'?` : ""}` };
183
236
  }
184
237
 
@@ -223,13 +276,19 @@ export function calculateSimilarity(source: string, target: string): number {
223
276
  const t1 = tokenize(source);
224
277
  const t2 = tokenize(target);
225
278
  let tokenBonus = 0;
279
+ let sharedTokenCount = 0;
280
+ let exactTokenMatchCount = 0;
226
281
  if (t1.length > 0 && t2.length > 0) {
282
+ const exactTokens = t1.filter((token) => t2.includes(token));
283
+ exactTokenMatchCount = exactTokens.length;
227
284
  const sharedTokens = t1.filter((token) =>
228
285
  t2.some((t) => t.includes(token) || token.includes(t))
229
286
  );
287
+ sharedTokenCount = sharedTokens.length;
230
288
  const allUniqueTokens = new Set([...t1, ...t2]);
231
289
  const jaccard = sharedTokens.length / (allUniqueTokens.size || 1);
232
- tokenBonus = jaccard * 0.35;
290
+ const exactCoverage = exactTokens.length / t1.length;
291
+ tokenBonus = jaccard * 0.35 + (exactTokens.length > 0 ? 0.25 + exactCoverage * 0.2 : 0);
233
292
  }
234
293
 
235
294
  // Damerau-Levenshtein Matrix
@@ -269,8 +328,16 @@ export function calculateSimilarity(source: string, target: string): number {
269
328
 
270
329
  const distance = matrix[len1][len2];
271
330
  const maxLen = Math.max(len1, len2);
272
- const rawSimilarity = 1.0 - distance / maxLen;
331
+ let rawSimilarity = 1.0 - distance / maxLen;
332
+
333
+ // Dampen accidental subsequence matches for short unrelated words against multi-token queries
334
+ if (t1.length > 1 && t2.length > 0 && sharedTokenCount === 0 && !s2.includes(s1) && !s1.includes(s2) && Math.min(len1, len2) / maxLen < 0.65) {
335
+ rawSimilarity *= 0.55;
336
+ }
273
337
 
274
- const totalScore = rawSimilarity + prefixBonus + substringBonus + tokenBonus;
338
+ // Boost exact word-boundary token matches (e.g. "Store" -> "SymbolDetailsStore") above edit-distance noise ("Scope", "close")
339
+ const totalScore = exactTokenMatchCount > 0
340
+ ? Math.max(rawSimilarity + prefixBonus + substringBonus + tokenBonus, 0.72 + (exactTokenMatchCount / t2.length) * 0.2)
341
+ : rawSimilarity + prefixBonus + substringBonus + tokenBonus;
275
342
  return Math.min(1.0, Math.max(0.0, totalScore));
276
343
  }
@@ -1,6 +1,5 @@
1
- import { rebuildSliceCatalog, sliceInputsCurrent } from "./slice-catalog.ts";
2
- import { scanSourceFiles } from "../resources/source-inventory.ts";
3
- import { relative } from "node:path";
1
+ import { refreshSliceCatalog } from "./slice-catalog.ts";
2
+ import { selectSliceTarget } from "./slice-selection.ts";
4
3
  import type {
5
4
  ExecutionChainNode,
6
5
  VerticalSliceRecord,
@@ -8,7 +7,7 @@ import type {
8
7
  } from "../../types/index.ts";
9
8
  import type { SeptumRepository } from "../database/repository.ts";
10
9
  import { CallGraphTracer } from "./call-graph-tracer.ts";
11
- import { formatSliceNode, SLICE_RELATIONSHIP_LIMITS } from "./slice-format.ts";
10
+ import { formatSliceNode, parseSliceChain, SLICE_RELATIONSHIP_LIMITS } from "./slice-format.ts";
12
11
 
13
12
  export class VerticalSliceTracer {
14
13
  constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd(), private ignorePatterns: string[] = [], private verifyMembership = true) {}
@@ -18,18 +17,17 @@ export class VerticalSliceTracer {
18
17
  if (this.repo.getMeta("sync_state") === "error" || this.repo.getMeta("sync_state") === "running") {
19
18
  return { query: rawQuery, found: false, coverage: "partial", diagnostics: ["index_incomplete"], message: "Workspace synchronization is incomplete." };
20
19
  }
21
- const inventory = this.verifyMembership ? scanSourceFiles(this.projectRoot, { ignorePatterns: this.ignorePatterns, signal }) : undefined;
22
- const files = inventory?.files.map(file => relative(this.projectRoot, file).replace(/\\/g, "/"));
23
- const membershipChanged = files !== undefined && JSON.stringify(files) !== this.repo.getMeta("semantic_catalog_files");
24
- if (membershipChanged || !sliceInputsCurrent(this.repo, this.projectRoot, signal) || this.repo.getMeta("slices_dirty") === "1") {
25
- try {
26
- await rebuildSliceCatalog(this.repo, this.projectRoot, { ignorePatterns: this.ignorePatterns, signal });
27
- } catch (error) {
28
- signal?.throwIfAborted();
29
- return { query: rawQuery, found: false, coverage: "partial", diagnostics: [error instanceof Error ? error.message : String(error)], message: "Semantic extraction failed; no complete catalog was published." };
30
- }
20
+ try {
21
+ await refreshSliceCatalog(this.repo, this.projectRoot, {
22
+ ignorePatterns: this.ignorePatterns,
23
+ signal,
24
+ verifyMembership: this.verifyMembership,
25
+ });
26
+ } catch (error) {
27
+ signal?.throwIfAborted();
28
+ return { query: rawQuery, found: false, coverage: "partial", diagnostics: [error instanceof Error ? error.message : String(error)], message: "Semantic extraction failed; no complete catalog was published." };
31
29
  }
32
- return this.trace(rawQuery,maxDepth,controllerFile);
30
+ return this.trace(rawQuery, maxDepth, controllerFile);
33
31
  }
34
32
 
35
33
 
@@ -47,221 +45,23 @@ export class VerticalSliceTracer {
47
45
  // Synchronous compatibility API reads persisted slices only; use traceAsync for on-demand extraction.
48
46
  public trace(rawQuery: string, maxDepth: number = 5, controllerFile?: string): VerticalSliceTraceResponse {
49
47
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
50
- const trimmed = rawQuery.trim();
51
- const lowerTrimmed = trimmed.toLowerCase();
52
- const allSlices = this.repo.getAllVerticalSlices().filter(slice => !controllerFile || slice.controller_file === controllerFile);
53
-
54
- if (allSlices.length === 0) {
55
- return {
56
- query: trimmed,
57
- found: false,
58
- coverage: "partial",
59
- max_depth_applied: effectiveMaxDepth,
60
- message: controllerFile ? "No catalog target matches controller_file. Copy an exact file from the candidates or omit the filter." : "No vertical slices cataloged. Run 'septum sync' to extract framework routes and MVC slices.",
61
- };
62
- }
63
-
64
- // 1. Exact HTTP Method + URI match: "POST /orders/{id}/status" or "POST /api/orders"
65
- const methodUriMatch = trimmed.match(/^(GET|POST|PUT|PATCH|DELETE)\s+(\/[^\s]+)$/i);
66
- if (methodUriMatch) {
67
- const httpMethod = methodUriMatch[1].toUpperCase();
68
- const uri = methodUriMatch[2];
69
- const candidates = allSlices.filter((s) => s.http_method.toUpperCase() === httpMethod && this.urisMatch(s.route_uri, uri));
70
- const literal = candidates.filter(s => s.route_uri === uri);
71
- if (literal.length === 1) {
72
- return this.formatSuccessResponse(trimmed, literal[0], "exact", undefined, effectiveMaxDepth);
73
- }
74
- if (literal.length > 1 || candidates.length > 1) {
75
- return this.ambiguousResponse(trimmed, literal.length ? literal : candidates, effectiveMaxDepth);
76
- }
77
- if (candidates.length === 1) {
78
- return this.formatSuccessResponse(trimmed, candidates[0], "inferred", undefined, effectiveMaxDepth);
79
- }
80
- return { query: trimmed, found: false, coverage: "partial", max_depth_applied: effectiveMaxDepth, message: `No vertical slice found matching query '${trimmed}'.` };
81
- }
82
-
83
- // 2. URI-only match: "/orders" or "orders/{id}"
84
- const literalUriMatches = allSlices.filter((s) => s.route_uri === trimmed);
85
- const uriMatches = literalUriMatches.length ? literalUriMatches : allSlices.filter((s) => this.urisMatch(s.route_uri, trimmed));
86
- if (uriMatches.length > 0) {
87
- const confidence = literalUriMatches.length ? "exact" : "inferred";
88
- if (uriMatches.length === 1) {
89
- return this.formatSuccessResponse(trimmed, uriMatches[0], confidence, undefined, effectiveMaxDepth);
90
- }
91
- return this.ambiguousResponse(trimmed, uriMatches, effectiveMaxDepth);
92
- }
93
-
94
- // 3. Named Route match: "orders.status.update" or "admin.users.index"
95
- const nameMatches = allSlices.filter(
96
- (s) => s.route_name && s.route_name.toLowerCase() === lowerTrimmed
97
- );
98
- if (nameMatches.length) {
99
- return nameMatches.length > 1 ? this.ambiguousResponse(trimmed, nameMatches, effectiveMaxDepth)
100
- : this.formatSuccessResponse(trimmed, nameMatches[0], "exact", undefined, effectiveMaxDepth);
101
- }
102
-
103
- // 3b. Omni-Trigger Match: "JOB ProcessOrderJob", "job:ProcessOrderJob", "CLI order:cleanup", "EVENT OrderPlacedListener"
104
- const omniTriggerMatch = trimmed.match(/^(JOB|CLI|EVENT)\s+([A-Za-z0-9_:\-]+)$/i);
105
- if (omniTriggerMatch) {
106
- const triggerKind = omniTriggerMatch[1].toUpperCase();
107
- const targetName = omniTriggerMatch[2].toLowerCase();
108
- const exact = allSlices.filter(
109
- (s) =>
110
- s.http_method.toUpperCase() === triggerKind &&
111
- (s.controller_class.toLowerCase() === targetName ||
112
- s.route_uri.toLowerCase() === targetName ||
113
- s.route_uri.toLowerCase() === `${triggerKind.toLowerCase()}:${targetName}`)
114
- );
115
- if (exact.length) {
116
- return exact.length > 1 ? this.ambiguousResponse(trimmed, exact, effectiveMaxDepth)
117
- : this.formatSuccessResponse(trimmed, exact[0], "exact", undefined, effectiveMaxDepth);
118
- }
119
- }
120
-
121
- // 4. Controller@Action match: "OrderController@updateStatus" or "OrderController"
122
- const controllerActionMatch = trimmed.match(/^([A-Za-z0-9_\\/.]+?)(?:(?:@|::)([A-Za-z0-9_]+))?$/);
123
- if (controllerActionMatch) {
124
- const [, rawCtrl, act] = controllerActionMatch;
125
- const ctrl = rawCtrl.split(/[\\/]/).pop()?.replace(/\.(php|ts|js)$/i, "") || rawCtrl;
126
- const lowerCtrl = ctrl.toLowerCase();
127
- const lowerAct = act ? act.toLowerCase() : undefined;
128
-
129
- const exact = allSlices.filter((s) => {
130
- const sCtrlLower = s.controller_class.toLowerCase();
131
- const ctrlMatch =
132
- sCtrlLower === lowerCtrl ||
133
- sCtrlLower.endsWith(`\\${lowerCtrl}`) ||
134
- sCtrlLower.endsWith(`/${lowerCtrl}`);
135
- if (!ctrlMatch) return false;
136
- if (lowerAct) return s.action_name.toLowerCase() === lowerAct;
137
- if (!act && !lowerCtrl.endsWith("controller") && sCtrlLower !== lowerCtrl) {
138
- return false;
139
- }
140
- return true;
141
- });
142
- if (exact.length) {
143
- return exact.length > 1 ? this.ambiguousResponse(trimmed, exact, effectiveMaxDepth)
144
- : this.formatSuccessResponse(trimmed, exact[0], "exact", undefined, effectiveMaxDepth);
145
- }
48
+ const exactCandidates = typeof this.repo.findExactVerticalSlices === "function"
49
+ ? this.repo.findExactVerticalSlices(rawQuery, controllerFile)
50
+ : [];
51
+ const indexedCandidates = exactCandidates.length > 0
52
+ ? exactCandidates
53
+ : typeof this.repo.findVerticalSlices === "function"
54
+ ? this.repo.findVerticalSlices(rawQuery)
55
+ : [];
56
+ const filteredIndexed = controllerFile
57
+ ? indexedCandidates.filter(s => s.controller_file === controllerFile)
58
+ : indexedCandidates;
59
+ const slices = filteredIndexed.length > 0 ? filteredIndexed : this.repo.getAllVerticalSlices();
60
+ const selection = selectSliceTarget(slices, rawQuery, effectiveMaxDepth, controllerFile);
61
+ if ("record" in selection) {
62
+ return this.formatSuccessResponse(selection.query, selection.record, selection.confidence, selection.alternatives, effectiveMaxDepth);
146
63
  }
147
-
148
- // 5. Symbol Match in Execution Chain or Action Name (e.g. "createOrder", "CreateOrderUseCase", "OrderController")
149
- let invalidChains = false;
150
- const symbolMatches = allSlices.filter((s) => {
151
- if (s.action_name.toLowerCase() === lowerTrimmed) return true;
152
- if (s.controller_class.toLowerCase() === lowerTrimmed) return true;
153
- if (s.execution_chain_json) {
154
- try {
155
- const chain = this.parseChain(s.execution_chain_json);
156
- return chain.some(
157
- (node) =>
158
- node.symbol.toLowerCase() === lowerTrimmed ||
159
- node.symbol.toLowerCase().includes(lowerTrimmed) ||
160
- (node.file && node.file.toLowerCase().includes(lowerTrimmed))
161
- );
162
- } catch {
163
- invalidChains = true;
164
- return false;
165
- }
166
- }
167
- return false;
168
- });
169
- if (symbolMatches.length) {
170
- return symbolMatches.length > 1 ? this.ambiguousResponse(trimmed, symbolMatches, effectiveMaxDepth)
171
- : this.formatSuccessResponse(trimmed, symbolMatches[0], "inferred", undefined, effectiveMaxDepth);
172
- }
173
-
174
- // 6. Semantic / Token Scoring for Natural Language (e.g. "Ubah status order di dashboard")
175
- const tokens = this.tokenize(trimmed);
176
- const scoredSlices = allSlices
177
- .map((slice) => {
178
- let score = 0;
179
- const textCorpus = [
180
- slice.route_uri,
181
- slice.route_name || "",
182
- slice.controller_class,
183
- slice.action_name,
184
- slice.execution_chain_json || "",
185
- ].join(" ").toLowerCase();
186
-
187
- for (const token of tokens) {
188
- if (textCorpus.includes(token)) {
189
- score += 1;
190
- if (slice.route_uri.toLowerCase().includes(token)) score += 2;
191
- if (slice.action_name.toLowerCase().includes(token)) score += 2;
192
- }
193
- }
194
- return { slice, score };
195
- })
196
- .filter((item) => item.score > 0)
197
- .sort((a, b) => b.score - a.score);
198
-
199
- if (scoredSlices.length > 0) {
200
- const tied = scoredSlices.filter(item => item.score === scoredSlices[0].score);
201
- if (tied.length > 1) return this.ambiguousResponse(trimmed, tied.map(item => item.slice), effectiveMaxDepth);
202
- const primary = scoredSlices[0].slice;
203
- const alternatives = scoredSlices.slice(1, 4).map((item) => item.slice);
204
- return this.formatSuccessResponse(trimmed, primary, "inferred", alternatives, effectiveMaxDepth);
205
- }
206
-
207
- return {
208
- query: trimmed,
209
- found: false,
210
- coverage: "partial",
211
- diagnostics: invalidChains ? ["invalid_execution_chain"] : undefined,
212
- next: invalidChains ? ["Run septum sync to rebuild the catalog before relying on a negative symbol search."] : undefined,
213
- max_depth_applied: effectiveMaxDepth,
214
- alternatives: allSlices.slice(0, 5).map((s) => ({
215
- method: s.http_method,
216
- uri: s.route_uri,
217
- controller: s.controller_class,
218
- action: s.action_name,
219
- })),
220
- message: `No vertical slice found matching query '${trimmed}'.`,
221
- };
222
- }
223
-
224
- private ambiguousResponse(query: string, candidates: VerticalSliceRecord[], maxDepth: number): VerticalSliceTraceResponse {
225
- const alternatives = candidates.map(candidate => ({ method: candidate.http_method, uri: candidate.route_uri,
226
- controller: candidate.controller_class, action: candidate.action_name, file: candidate.controller_file,
227
- line: candidate.controller_line })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
228
- return { query, found: false, coverage: "partial", diagnostics: ["ambiguous_target"],
229
- max_depth_applied: maxDepth, alternatives: alternatives.slice(0, 20),
230
- candidate_count: alternatives.length, alternatives_omitted: Math.max(0, alternatives.length - 20),
231
- next: ["Narrow the query to METHOD /route or Controller@action and controller_file copied from a candidate. If candidates remain identical, inspect their source declarations."],
232
- message: "Multiple catalog targets match; no entrypoint or chain was selected." };
233
- }
234
-
235
- private parseChain(serialized: string): ExecutionChainNode[] {
236
- const chain: unknown = JSON.parse(serialized);
237
- if (!Array.isArray(chain) || chain.some(node => !node || typeof node !== "object" ||
238
- typeof node.stage !== "string" || typeof node.symbol !== "string" ||
239
- (node.file !== undefined && typeof node.file !== "string") ||
240
- (node.description !== undefined && typeof node.description !== "string") ||
241
- ["guards", "mutations", "emits", "dispatches"].some(key => node[key] !== undefined &&
242
- (!Array.isArray(node[key]) || node[key].some((value: unknown) => typeof value !== "string"))))) {
243
- throw new Error("Invalid execution chain shape");
244
- }
245
- return chain;
246
- }
247
-
248
- private urisMatch(uriA: string, uriB: string): boolean {
249
- const normA = uriA
250
- .replace(/\{[^}]+\}/g, ":param")
251
- .replace(/:[a-zA-Z0-9_]+/g, ":param");
252
- const normB = uriB
253
- .replace(/\{[^}]+\}/g, ":param")
254
- .replace(/:[a-zA-Z0-9_]+/g, ":param");
255
- return normA === normB;
256
- }
257
-
258
- private tokenize(str: string): string[] {
259
- return str
260
- .replace(/([a-z])([A-Z])/g, "$1 $2")
261
- .toLowerCase()
262
- .replace(/[^a-z0-9_]+/g, " ")
263
- .split(/\s+/)
264
- .filter((t) => t.length > 2 && !["ubah", "di", "dan", "yang", "the", "for", "and"].includes(t));
64
+ return selection;
265
65
  }
266
66
 
267
67
  private formatSuccessResponse(
@@ -274,7 +74,7 @@ export class VerticalSliceTracer {
274
74
  let chain: ExecutionChainNode[] = [];
275
75
  const diagnostics: string[] = [];
276
76
  try {
277
- chain = this.parseChain(record.execution_chain_json);
77
+ chain = parseSliceChain(record.execution_chain_json);
278
78
  } catch {
279
79
  diagnostics.push("invalid_execution_chain");
280
80
  }
@@ -305,6 +105,7 @@ export class VerticalSliceTracer {
305
105
  }
306
106
  }
307
107
 
108
+ if (chain.some(node => node.stage === "ingress" && node.relationship?.derivation === "inferred")) confidence = "inferred";
308
109
  let message = `Vertical slice target match (${confidence}): ${record.http_method} ${record.route_uri} -> ${record.controller_class}@${record.action_name} (${chain.length} node(s)).`;
309
110
  if (record.architecture_style === "go-http") {
310
111
  message += " Go package import expansion is omitted; extracted handler/service relationships remain lexical and partial.";
@@ -5,7 +5,6 @@ export const DEFAULT_IGNORED_DIRECTORIES: ReadonlySet<string> = new Set([
5
5
  "bower_components",
6
6
  "jspm_packages",
7
7
  "deps",
8
- "packages",
9
8
  ".bundle",
10
9
  ".cargo",
11
10
  ".gradle",
@@ -1,7 +1,7 @@
1
1
  export const RESOURCE_LIMITS = Object.freeze({
2
2
  workspaces: 4,
3
3
  workspaceIdleMs: 10 * 60_000,
4
- watches: 2048,
4
+ watches: 8192,
5
5
  pendingPaths: 1000,
6
6
  debounceMs: 300,
7
7
  pollMs: 5000,
@@ -10,5 +10,6 @@ export const RESOURCE_LIMITS = Object.freeze({
10
10
  batchFiles: 50,
11
11
  batchBytes: 1024 * 1024,
12
12
  maxQueuePending: 50,
13
+ requestTimeoutMs: 120_000,
13
14
  shutdownMs: 5000,
14
15
  });
@@ -1,7 +1,14 @@
1
+ import { WorkspaceBusyError } from "../errors.ts";
1
2
  import { RESOURCE_LIMITS } from "./limits.ts";
2
3
 
4
+ export interface WorkQueue {
5
+ readonly pendingCount: number;
6
+ run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T>;
7
+ drain(): Promise<void>;
8
+ }
9
+
3
10
  /** One mutation/parse lane per server; failures do not poison later work. */
4
- export class SerialWorkQueue {
11
+ export class SerialWorkQueue implements WorkQueue {
5
12
  private tail: Promise<void> = Promise.resolve();
6
13
  private pending = 0;
7
14
  private readonly maxPending: number;
@@ -20,9 +27,9 @@ export class SerialWorkQueue {
20
27
  }
21
28
 
22
29
  if (this.pending >= this.maxPending) {
23
- const busyError = new Error(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`);
24
- (busyError as any).code = "SERVER_BUSY";
25
- return Promise.reject(busyError);
30
+ return Promise.reject(
31
+ new WorkspaceBusyError(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`)
32
+ );
26
33
  }
27
34
 
28
35
  this.pending++;
@@ -72,3 +79,159 @@ export class SerialWorkQueue {
72
79
  return this.tail;
73
80
  }
74
81
  }
82
+
83
+ /** Per-workspace reader/writer queue: concurrent readers, exclusive writers, FIFO fairness. */
84
+ export class ReadWriteWorkQueue implements WorkQueue {
85
+ private activeReaders = 0;
86
+ private activeWriter = false;
87
+ private waiters: Array<{ mode: "read" | "write"; start: () => void }> = [];
88
+ private drainResolvers: Array<() => void> = [];
89
+ private readonly maxPending: number;
90
+
91
+ constructor(maxPending = RESOURCE_LIMITS.maxQueuePending) {
92
+ this.maxPending = maxPending;
93
+ }
94
+
95
+ get pendingCount(): number {
96
+ return this.waiters.length + this.activeReaders + (this.activeWriter ? 1 : 0);
97
+ }
98
+
99
+ run<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
100
+ return this.runWrite(work, signal);
101
+ }
102
+
103
+ runRead<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
104
+ return this.enqueue("read", work, signal);
105
+ }
106
+
107
+ runWrite<T>(work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
108
+ return this.enqueue("write", work, signal);
109
+ }
110
+
111
+ private enqueue<T>(mode: "read" | "write", work: () => Promise<T>, signal?: AbortSignal): Promise<T> {
112
+ if (signal?.aborted) {
113
+ return Promise.reject(signal.reason ?? new Error("Request was cancelled before queueing"));
114
+ }
115
+
116
+ if (this.pendingCount >= this.maxPending) {
117
+ return Promise.reject(
118
+ new WorkspaceBusyError(`Server is busy: request admission limit (${this.maxPending}) exceeded. Retry after current tasks finish.`)
119
+ );
120
+ }
121
+
122
+ return new Promise<T>((resolve, reject) => {
123
+ let settled = false;
124
+ let started = false;
125
+
126
+ const execute = async () => {
127
+ started = true;
128
+ if (signal) {
129
+ signal.removeEventListener("abort", abortHandler);
130
+ }
131
+ if (settled || signal?.aborted) {
132
+ if (!settled) {
133
+ settled = true;
134
+ reject(signal?.reason ?? new Error("Request was cancelled before execution"));
135
+ }
136
+ this.release(mode);
137
+ return;
138
+ }
139
+ try {
140
+ const res = await work();
141
+ if (!settled) {
142
+ settled = true;
143
+ resolve(res);
144
+ }
145
+ } catch (err) {
146
+ if (!settled) {
147
+ settled = true;
148
+ reject(err);
149
+ }
150
+ } finally {
151
+ this.release(mode);
152
+ }
153
+ };
154
+
155
+ const waiter = { mode, start: () => { void execute(); } };
156
+
157
+ const abortHandler = () => {
158
+ if (started || settled) return;
159
+ settled = true;
160
+ const idx = this.waiters.indexOf(waiter);
161
+ if (idx !== -1) this.waiters.splice(idx, 1);
162
+ reject(signal?.reason ?? new Error("Request was cancelled while queued"));
163
+ this.scheduleNext();
164
+ };
165
+
166
+ if (signal) {
167
+ signal.addEventListener("abort", abortHandler, { once: true });
168
+ }
169
+
170
+ if (mode === "read" && !this.activeWriter && this.waiters.length === 0) {
171
+ this.activeReaders++;
172
+ void execute();
173
+ } else if (mode === "write" && !this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
174
+ this.activeWriter = true;
175
+ void execute();
176
+ } else {
177
+ this.waiters.push(waiter);
178
+ }
179
+ });
180
+ }
181
+
182
+ private release(mode: "read" | "write"): void {
183
+ if (mode === "read") {
184
+ this.activeReaders = Math.max(0, this.activeReaders - 1);
185
+ } else {
186
+ this.activeWriter = false;
187
+ }
188
+ this.scheduleNext();
189
+ }
190
+
191
+ private scheduleNext(): void {
192
+ if (!this.activeWriter && this.waiters.length > 0) {
193
+ if (this.waiters[0]!.mode === "write") {
194
+ if (this.activeReaders === 0) {
195
+ const next = this.waiters.shift()!;
196
+ this.activeWriter = true;
197
+ next.start();
198
+ }
199
+ } else {
200
+ while (this.waiters.length > 0 && this.waiters[0]!.mode === "read") {
201
+ const next = this.waiters.shift()!;
202
+ this.activeReaders++;
203
+ next.start();
204
+ }
205
+ }
206
+ }
207
+
208
+ if (!this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
209
+ const resolvers = this.drainResolvers.splice(0);
210
+ for (const resolve of resolvers) resolve();
211
+ }
212
+ }
213
+
214
+ drain(): Promise<void> {
215
+ if (!this.activeWriter && this.activeReaders === 0 && this.waiters.length === 0) {
216
+ return Promise.resolve();
217
+ }
218
+ return new Promise<void>((resolve) => {
219
+ this.drainResolvers.push(resolve);
220
+ });
221
+ }
222
+ }
223
+
224
+ // A requester can stop waiting without cancelling work owned by a workspace.
225
+ export function waitForSharedWork<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
226
+ if (!signal) return work;
227
+ return new Promise<T>((resolve, reject) => {
228
+ const abort = () => {
229
+ detach();
230
+ reject(signal.reason);
231
+ };
232
+ const detach = () => signal.removeEventListener("abort", abort);
233
+ work.then(value => { detach(); resolve(value); }, error => { detach(); reject(error); });
234
+ if (signal.aborted) abort();
235
+ else signal.addEventListener("abort", abort, { once: true });
236
+ });
237
+ }