@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
@@ -9,6 +9,8 @@ import type {
9
9
  SymbolRecord,
10
10
  } from "../../../types/index.ts";
11
11
  import { DependencyRepository } from "./dependency.repository.ts";
12
+ import { buildDomainFileConnections } from "../../resolver/dependency-analysis.ts";
13
+ import { domainNameKey, domainRootIdentity, DomainRootConflictError } from "../../config/domain-ownership.ts";
12
14
 
13
15
  const CONTAINER_KINDS = new Set<SymbolKind>([
14
16
  "class",
@@ -21,9 +23,19 @@ const CONTAINER_KINDS = new Set<SymbolKind>([
21
23
  export class DomainRepository {
22
24
  constructor(private db: Database) {}
23
25
 
24
- public upsertDomain(name: string, config: DomainConfig): number {
26
+ public upsertDomain(name: string, config: DomainConfig, workspaceRoot?: string): number {
25
27
  return this.db.transaction(() => {
26
28
  const normalizedName = name.trim();
29
+ const root = workspaceRoot ?? this.db.query<{ value: string }, []>("SELECT value FROM repo_meta WHERE key='workspace_root'").get()?.value ?? process.cwd();
30
+ const claims = Object.fromEntries(this.getAllDomains()
31
+ .filter(domain => domainNameKey(domain.name) !== domainNameKey(normalizedName))
32
+ .map(domain => [domain.name, { root: domain.root_path }]));
33
+ // Validate the proposed root inside the same immediate transaction as the write.
34
+ // Unrelated legacy conflicts can be repaired one domain at a time.
35
+ const proposed = domainRootIdentity(config.root, root);
36
+ for (const [owner, claim] of Object.entries(claims)) {
37
+ if (domainRootIdentity(claim.root, root) === proposed) throw new DomainRootConflictError(owner, normalizedName, proposed);
38
+ }
27
39
  let existing = this.getDomainByName(normalizedName);
28
40
 
29
41
  // MCP-13: If duplicates exist with different casing, consolidate into canonical primary row
@@ -131,6 +143,27 @@ export class DomainRepository {
131
143
  return this.db.query<DomainRecord, []>("SELECT * FROM domains ORDER BY name ASC").all();
132
144
  }
133
145
 
146
+ /** Delete domains not present in activeNames (case-insensitive) and return removed counts. */
147
+ public pruneDomainsNotIn(activeNames: string[]): { prunedDomains: number; removedFiles: number } {
148
+ const activeSet = new Set(activeNames.map((n) => n.trim().toLowerCase()));
149
+ return this.db.transaction(() => {
150
+ const existing = this.getAllDomains();
151
+ const stale = existing.filter((d) => !activeSet.has(d.name.trim().toLowerCase()));
152
+ if (stale.length === 0) return { prunedDomains: 0, removedFiles: 0 };
153
+
154
+ let removedFiles = 0;
155
+ const countFilesStmt = this.db.query<{ cnt: number }, [number]>(
156
+ "SELECT COUNT(*) AS cnt FROM files WHERE domain_id = ?"
157
+ );
158
+ const deleteDomainStmt = this.db.query("DELETE FROM domains WHERE id = ?");
159
+ for (const domain of stale) {
160
+ removedFiles += countFilesStmt.get(domain.id)?.cnt ?? 0;
161
+ deleteDomainStmt.run(domain.id);
162
+ }
163
+ return { prunedDomains: stale.length, removedFiles };
164
+ }).immediate();
165
+ }
166
+
134
167
  public getDomainCatalog(
135
168
  domainName: string,
136
169
  archetypeFilter?: string,
@@ -191,7 +224,7 @@ export class DomainRepository {
191
224
 
192
225
  // Batch compute file connections for the domain (zero N+1)
193
226
  const depRepo = new DependencyRepository(this.db);
194
- const connectionsByPath = depRepo.getDomainFileConnections(domain.id,options?.workspaceRoot);
227
+ const connectionsByPath = buildDomainFileConnections(depRepo, domain.id, options?.workspaceRoot);
195
228
 
196
229
  for (const file of files) {
197
230
  const symbols = symbolsByFileId.get(file.id) ?? [];
@@ -282,13 +315,24 @@ export class DomainRepository {
282
315
  imported_by_count: rawConn?.imported_by_count ?? 0,
283
316
  };
284
317
 
318
+ const allMappedSymbols = Array.from(symbolMap.values());
319
+ const isCompact = detailLevel === "compact";
320
+ const MAX_COMPACT_SYMBOLS = 25;
321
+ const symbolsToDisplay = isCompact && allMappedSymbols.length > MAX_COMPACT_SYMBOLS
322
+ ? allMappedSymbols.slice(0, MAX_COMPACT_SYMBOLS)
323
+ : allMappedSymbols;
324
+ const symbolsOmitted = isCompact && allMappedSymbols.length > MAX_COMPACT_SYMBOLS
325
+ ? allMappedSymbols.length - MAX_COMPACT_SYMBOLS
326
+ : undefined;
327
+
285
328
  catalogFiles.push({
286
329
  ...(detailLevel === "full" ? { declarations: symbols.map(sym => symbolReference({ ...sym, file_path: file.path, indexed_content_hash: file.content_hash })) } : {}),
287
330
  path: file.path,
288
331
  archetype: file.archetype,
289
332
  line_count: file.line_count,
290
333
  connections: fileConnections,
291
- symbols: Array.from(symbolMap.values()).map((s) => {
334
+ ...(symbolsOmitted !== undefined ? { symbols_omitted: symbolsOmitted } : {}),
335
+ symbols: symbolsToDisplay.map((s) => {
292
336
  if (detailLevel === "compact") {
293
337
  return {
294
338
  name: s.name,
@@ -323,7 +367,7 @@ export class DomainRepository {
323
367
  files: catalogFiles,
324
368
  agent_hint:
325
369
  detailLevel === "compact"
326
- ? "Compact view (<400 tokens). Use septum_symbol({ action: 'inspect', query: symbol }) for exact method signatures, or septum_domain({ action: 'catalog', domain, detail_level: 'full', file_filter: '<path>' }) for full member lists."
370
+ ? "Compact declaration catalog. Use septum_symbol({ action: 'context', query: symbol, file_path: '<path>' }) for declaration details. septum_map provides navigation rather than member inventories."
327
371
  : undefined,
328
372
  };
329
373
  }
@@ -114,4 +114,14 @@ export class FileRepository {
114
114
 
115
115
  return { file, domain };
116
116
  }
117
+
118
+ public rebindFilesToDomain(rootPrefix: string, domainId: number): number {
119
+ const normalized = rootPrefix.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
120
+ if (!normalized || normalized === ".") return 0;
121
+ const result = this.db.run(
122
+ "UPDATE files SET domain_id = ? WHERE (path = ? OR path LIKE ? || '/%')",
123
+ [domainId, normalized, normalized]
124
+ );
125
+ return result.changes;
126
+ }
117
127
  }
@@ -1,21 +1,13 @@
1
1
  import { symbolReference, matchesSymbolName, matchesSymbolReference } from "../../resolver/symbol-reference.ts";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
2
  import type { Database } from "bun:sqlite";
5
3
  import type {
6
- DomainRecord,
7
4
  ExtractedSymbol,
8
5
  FileRecord,
9
- GetSymbolDetailsResponse,
10
- FileConnectionsSummary,
11
- ResolvedOutboundCall,
12
- SymbolComplexitySmell,
13
6
  SymbolKind,
14
7
  SymbolRecord,
15
8
  SymbolCandidate,
16
9
  SymbolSelectionOptions,
17
10
  } from "../../../types/index.ts";
18
- import { DependencyRepository } from "./dependency.repository.ts";
19
11
 
20
12
  const SQL_KEYWORD_BLACKLIST = new Set([
21
13
  "VALUES",
@@ -36,6 +28,11 @@ function stripCommentsAndStrings(source: string): string {
36
28
  .replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, '""');
37
29
  }
38
30
 
31
+ export function computeSymbolLeafName(name: string): string {
32
+ const trimmed = name.trim().replace(/\(\)$/, "");
33
+ return trimmed.split(/::|->|[.#/\\]/).pop() ?? trimmed;
34
+ }
35
+
39
36
  export class SymbolRepository {
40
37
  constructor(private db: Database) {}
41
38
 
@@ -44,8 +41,8 @@ export class SymbolRepository {
44
41
  if (symbols.length === 0) return;
45
42
 
46
43
  const stmt = this.db.query(
47
- `INSERT INTO symbols (file_id, name, kind, signature, visibility, line_start, line_end, line_count, nesting_depth)
48
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
44
+ `INSERT INTO symbols (file_id, name, leaf_name, kind, signature, visibility, line_start, line_end, line_count, nesting_depth)
45
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
49
46
  );
50
47
 
51
48
  for (const sym of symbols) {
@@ -54,6 +51,7 @@ export class SymbolRepository {
54
51
  stmt.run(
55
52
  fileId,
56
53
  sym.name,
54
+ computeSymbolLeafName(sym.name),
57
55
  sym.kind,
58
56
  sym.signature,
59
57
  sym.visibility,
@@ -78,11 +76,12 @@ export class SymbolRepository {
78
76
  options: SymbolSelectionOptions = {}
79
77
  ): SymbolCandidate[] {
80
78
  const target = name.trim().replace(/\(\)$/, "");
81
- const leaf = target.split(/::|->|[.#\\]/).pop() ?? target;
79
+ if (!target) return [];
80
+ const leaf = computeSymbolLeafName(target);
82
81
  let query = `SELECT s.*, f.path AS file_path, f.content_hash AS indexed_content_hash, d.name AS domain_name
83
82
  FROM symbols s JOIN files f ON s.file_id = f.id JOIN domains d ON f.domain_id = d.id
84
- WHERE (s.name = ? OR substr(s.name, -length(?)) = ?)`;
85
- const params: string[] = [target, leaf, leaf];
83
+ WHERE (s.name = ? OR s.leaf_name = ?)`;
84
+ const params: string[] = [target, leaf];
86
85
  if (options.domain) { query += " AND d.name = ?"; params.push(options.domain); }
87
86
  const filePath = options.filePath ?? options.reference?.file_path;
88
87
  if (filePath) { query += " AND f.path = ?"; params.push(filePath); }
@@ -151,15 +150,76 @@ export class SymbolRepository {
151
150
  return files.map((file) => ({ file }));
152
151
  }
153
152
 
154
- public getAllSymbolsWithFiles(): Array<SymbolRecord & { file_path: string }> {
153
+ public findFuzzySymbolCandidates(
154
+ queryStr: string,
155
+ options?: { domainId?: number; filePath?: string; limit?: number }
156
+ ): Array<SymbolRecord & { file_path: string }> {
157
+ const targetLeaf = computeSymbolLeafName(queryStr);
158
+ const clauses = [
159
+ "s.kind IN ('class', 'interface', 'trait', 'struct', 'enum', 'type', 'method', 'function', 'constant')",
160
+ ];
161
+ const params: Array<string | number> = [];
162
+ if (options?.filePath) {
163
+ clauses.push("f.path = ?");
164
+ params.push(options.filePath);
165
+ }
166
+ if (options?.domainId !== undefined) {
167
+ clauses.push("f.domain_id = ?");
168
+ params.push(options.domainId);
169
+ }
170
+ if (targetLeaf.length >= 2) {
171
+ const minLen = Math.max(1, Math.floor(targetLeaf.length * 0.4));
172
+ const maxLen = Math.max(targetLeaf.length + 12, Math.ceil(targetLeaf.length * 2.5));
173
+ clauses.push("length(s.leaf_name) BETWEEN ? AND ?");
174
+ params.push(minLen, maxLen);
175
+ }
176
+ if (targetLeaf.length >= 4) {
177
+ const lower = targetLeaf.toLowerCase().replace(/[^a-z0-9]/g, "");
178
+ const distinct: string[] = [];
179
+ for (const ch of lower) {
180
+ if (!distinct.includes(ch)) {
181
+ distinct.push(ch);
182
+ if (distinct.length >= 4) break;
183
+ }
184
+ }
185
+ if (distinct.length > 0) {
186
+ const charClauses = distinct.map(() => "instr(lower(s.leaf_name), ?) > 0");
187
+ clauses.push(`(${charClauses.join(" OR ")})`);
188
+ params.push(...distinct);
189
+ }
190
+ }
191
+ const limit = Math.max(1, options?.limit ?? 500);
192
+ params.push(targetLeaf.length, limit);
193
+ const query = `
194
+ SELECT s.*, f.path AS file_path
195
+ FROM symbols s
196
+ JOIN files f ON s.file_id = f.id
197
+ WHERE ${clauses.join(" AND ")}
198
+ ORDER BY abs(length(s.leaf_name) - ?) ASC, s.line_start ASC
199
+ LIMIT ?
200
+ `;
201
+ return this.db.query<SymbolRecord & { file_path: string }, Array<string | number>>(query).all(...params);
202
+ }
203
+
204
+ public getAllSymbolsWithFiles(filter?: { domainId?: number; filePath?: string }): Array<SymbolRecord & { file_path: string }> {
205
+ const clauses = ["s.kind IN ('class', 'interface', 'trait', 'struct', 'enum', 'type', 'method', 'function', 'constant')"];
206
+ const params: Array<string | number> = [];
207
+ if (filter?.filePath) {
208
+ clauses.push("f.path = ?");
209
+ params.push(filter.filePath);
210
+ }
211
+ if (filter?.domainId !== undefined) {
212
+ clauses.push("f.domain_id = ?");
213
+ params.push(filter.domainId);
214
+ }
155
215
  const query = `
156
216
  SELECT s.*, f.path AS file_path
157
217
  FROM symbols s
158
218
  JOIN files f ON s.file_id = f.id
159
- WHERE s.kind IN ('class', 'method', 'function')
160
- ORDER BY s.name ASC
219
+ WHERE ${clauses.join(" AND ")}
220
+ ORDER BY s.line_start ASC, s.name ASC
161
221
  `;
162
- return this.db.query<SymbolRecord & { file_path: string }, []>(query).all();
222
+ return this.db.query<SymbolRecord & { file_path: string }, Array<string | number>>(query).all(...params);
163
223
  }
164
224
 
165
225
  public findSymbolWithDomain(symbolName: string): {
@@ -260,249 +320,27 @@ export class SymbolRepository {
260
320
  return this.db.query<any, [string]>(query).get(filePath) ?? null;
261
321
  }
262
322
 
263
- public getHotspotSymbols(options: {
264
- minLines?: number;
265
- minNesting?: number;
266
- kind?: SymbolKind;
267
- domain?: string;
268
- limit?: number;
269
- sortBy?: "lines" | "nesting" | "risk_score";
270
- } = {}): Array<SymbolRecord & { file_path: string; domain_name: string; risk_score: number }> {
271
- const minLines = options.minLines ?? 0;
272
- const minNesting = options.minNesting ?? 1;
273
- const limit = options.limit ?? 50;
274
- const sortBy = options.sortBy ?? "risk_score";
275
-
276
- let sql = `
277
- SELECT
278
- s.id,
279
- s.file_id,
280
- s.name,
281
- s.kind,
282
- s.signature,
283
- s.visibility,
284
- s.line_start,
285
- s.line_end,
286
- s.line_count,
287
- s.nesting_depth,
288
- f.path AS file_path,
289
- d.name AS domain_name
290
- FROM symbols s
291
- JOIN files f ON s.file_id = f.id
292
- JOIN domains d ON f.domain_id = d.id
293
- WHERE s.line_count >= ? AND s.nesting_depth >= ?
294
- `;
295
-
296
- const params: any[] = [minLines, minNesting];
297
-
298
- if (options.kind) {
299
- sql += " AND s.kind = ?";
300
- params.push(options.kind);
301
- }
302
-
303
- if (options.domain) {
304
- sql += " AND d.name = ?";
305
- params.push(options.domain);
306
- }
307
-
308
- if (sortBy === "nesting") {
309
- sql += " ORDER BY s.nesting_depth DESC, s.line_count DESC, s.name ASC LIMIT ?";
310
- } else if (sortBy === "lines") {
311
- sql += " ORDER BY s.line_count DESC, s.nesting_depth DESC, s.name ASC LIMIT ?";
312
- } else {
313
- sql += " ORDER BY (s.line_count * (1.0 + s.nesting_depth * 0.3)) DESC, s.nesting_depth DESC, s.name ASC LIMIT ?";
314
- }
315
- params.push(limit);
316
-
317
- const rows = this.db.query<any, any[]>(sql).all(...params);
318
- return rows.map((r) => ({
319
- ...r,
320
- nesting_depth: r.nesting_depth ?? 1,
321
- risk_score: Math.round((r.line_count ?? 1) * (1.0 + (r.nesting_depth ?? 1) * 0.3)),
322
- }));
323
+ public findConstructorSignature(fileId: number, classOwner: string): string | null {
324
+ const ctor = this.db
325
+ .query<{ signature: string }, [number, string, string, string, string]>(
326
+ "SELECT signature FROM symbols WHERE file_id = ? AND (name = ? OR name = ? OR name = ? OR name LIKE ?) LIMIT 1"
327
+ )
328
+ .get(
329
+ fileId,
330
+ `${classOwner}::__construct`,
331
+ `${classOwner}::constructor`,
332
+ `${classOwner}::__init__`,
333
+ `%::__construct`
334
+ );
335
+ return ctor?.signature ?? null;
323
336
  }
324
337
 
325
- public getSymbolDetails(
326
- symbolQuery: string,
327
- options: SymbolSelectionOptions & { includeDependencies?: boolean; workspaceRoot?: string } = {}
328
- ): GetSymbolDetailsResponse | null {
329
- const trimmed = symbolQuery.trim();
330
- if (!trimmed) return null;
331
-
332
- const candidates = this.findSymbolsByName(trimmed, options);
333
- if (candidates.length !== 1) return null;
334
- const row = candidates[0]!;
335
-
336
- // 1. Sibling methods
337
- const isRust = /\.rs$/i.test(row.file_path);
338
- const containerName = row.symbol_ref.container ?? "";
339
- const owner = ["class", "interface", "trait", "struct", "enum"].includes(row.kind) ? row.name
340
- : row.kind === "method" ? containerName : "";
341
- let siblingMethods: string[] = owner ? this.getSymbolsByFileId(row.file_id)
342
- .filter(s => s.kind === "method" && s.id !== row.id)
343
- .filter(s => symbolReference({ ...s, file_path: row.file_path, indexed_content_hash: row.indexed_content_hash }).container === owner)
344
- .map(s => s.name.split(/::|[.#]/).pop()!) : [];
345
-
346
- siblingMethods = Array.from(new Set(siblingMethods)).filter(
347
- (m) => !SQL_KEYWORD_BLACKLIST.has(m.toUpperCase())
348
- );
349
-
350
- // 2. Dependencies Injected (from signature type-hints and constructor)
351
- const dependenciesInjected = new Set<string>();
352
- const outboundCalls = new Set<string>();
353
- const resolvedOutboundCalls: ResolvedOutboundCall[] = [];
354
- let connectedFiles: FileConnectionsSummary = { imports_from: [], imported_by_count: 0 };
355
-
356
- const shouldIncludeDeps = options.includeDependencies !== false;
357
-
358
- if (shouldIncludeDeps) {
359
- const extractTypeHints = (sig: string) => {
360
- const paramMatch = sig.match(/\(([^)]*)\)/);
361
- if (paramMatch && paramMatch[1]) {
362
- const params = paramMatch[1].split(",");
363
- const primitiveTypes = new Set([
364
- "int", "string", "bool", "boolean", "float", "array", "iterable",
365
- "callable", "void", "mixed", "object", "null", "never", "any", "number", "unknown"
366
- ]);
367
- for (const p of params) {
368
- const parts = p.trim().replace(/^\?/, "").split(/\s+/);
369
- if (parts.length >= 2) {
370
- const rawType = parts[0].replace(/\[\]$/, "").replace(/^[\\$]/, "");
371
- if (rawType && !primitiveTypes.has(rawType.toLowerCase()) && !rawType.startsWith("$")) {
372
- dependenciesInjected.add(rawType);
373
- }
374
- }
375
- }
376
- }
377
- };
378
-
379
- // Rust parameter types do not establish a dependency injection binding.
380
- if (!isRust) extractTypeHints(row.signature);
381
-
382
- // Also check constructor injection if this is a method
383
- if (containerName && !isRust) {
384
- const ctor = this.db
385
- .query<{ signature: string }, [number, string, string]>(
386
- "SELECT signature FROM symbols WHERE file_id = ? AND (name = ? OR name LIKE ?) LIMIT 1"
387
- )
388
- .get(row.file_id, `${containerName}::__construct`, `%::__construct`);
389
- if (ctor) {
390
- extractTypeHints(ctor.signature);
391
- }
392
- }
393
-
394
- // 3. Outbound Calls (inspected from physical source file lines if accessible)
395
- try {
396
- const fullPath = options.workspaceRoot
397
- ? path.resolve(options.workspaceRoot, row.file_path)
398
- : row.file_path;
399
- if (fs.existsSync(fullPath)) {
400
- const fileContent = fs.readFileSync(fullPath, "utf-8");
401
- const lines = fileContent.split(/\r?\n/);
402
- const start = Math.max(0, row.line_start - 1);
403
- const end = Math.min(lines.length, row.line_end);
404
- const rawSlice = lines.slice(start, end).join("\n");
405
- const sanitizedSlice = stripCommentsAndStrings(rawSlice);
406
-
407
- // Match Static invocations: ClassName::methodName(
408
- const staticCalls = sanitizedSlice.matchAll(/([A-Z][a-zA-Z0-9_]+)::([a-zA-Z0-9_]+)\s*\(/g);
409
- for (const m of staticCalls) {
410
- if (m[1] !== "self" && m[1] !== "parent" && m[1] !== "static") {
411
- outboundCalls.add(`${m[1]}::${m[2]}`);
412
- }
413
- }
414
-
415
- // Match PHP property calls: $this->property->method(
416
- const propCalls = sanitizedSlice.matchAll(/\$this->([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*\(/g);
417
- for (const m of propCalls) {
418
- const propName = m[1];
419
- const methodName = m[2];
420
- const inferredClass = propName.charAt(0).toUpperCase() + propName.slice(1);
421
- outboundCalls.add(`${inferredClass}::${methodName}`);
422
- }
423
-
424
- // Match TS/JS property calls: this.property.method(
425
- const tsPropCalls = sanitizedSlice.matchAll(/\bthis\.([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)\s*\(/g);
426
- for (const m of tsPropCalls) {
427
- const propName = m[1];
428
- const methodName = m[2];
429
- if (propName !== "db") {
430
- const inferredClass = propName.charAt(0).toUpperCase() + propName.slice(1);
431
- outboundCalls.add(`${inferredClass}::${methodName}`);
432
- }
433
- }
434
- }
435
- } catch {
436
- // Graceful fallback if file not physically accessible
437
- }
438
-
439
- const depRepo = new DependencyRepository(this.db);
440
- connectedFiles = depRepo.getFileConnections(row.file_path,options.workspaceRoot);
441
-
442
- // 4. Resolve Outbound Calls to target symbol line ranges
443
- for (const call of outboundCalls) {
444
- try {
445
- const matches = this.findSymbolsByName(call);
446
- const target = matches.length === 1 ? matches[0] : undefined;
447
- if (target) {
448
- resolvedOutboundCalls.push({
449
- symbol: call,
450
- target_file: target.file_path,
451
- target_range: {
452
- start_line: target.line_start,
453
- end_line: target.line_end,
454
- total_lines: target.line_count,
455
- },
456
- domain: target.domain_name,
457
- is_resolved: true,
458
- });
459
- } else {
460
- resolvedOutboundCalls.push({
461
- symbol: call,
462
- is_resolved: false,
463
- });
464
- }
465
- } catch {
466
- resolvedOutboundCalls.push({
467
- symbol: call,
468
- is_resolved: false,
469
- });
470
- }
471
- }
472
- }
473
-
474
- const complexitySmell: SymbolComplexitySmell | undefined =
475
- row.line_count > 300
476
- ? {
477
- is_high_complexity: true,
478
- threshold: 300,
479
- total_lines: row.line_count,
480
- warning: `Symbol '${row.name}' spans ${row.line_count} lines (exceeds 300-line threshold). Candidate for decomposition/refactoring.`,
481
- }
482
- : undefined;
483
-
484
- return {
485
- symbol_ref: row.symbol_ref,
486
- visibility_semantics: "legacy_normalized",
487
- symbol: row.name,
488
- kind: row.kind,
489
- file_path: row.file_path,
490
- domain: row.domain_name,
491
- exact_range: {
492
- start_line: row.line_start,
493
- end_line: row.line_end,
494
- total_lines: row.line_count,
495
- },
496
- signature: row.signature,
497
- visibility: row.visibility,
498
- dependencies_injected: Array.from(dependenciesInjected),
499
- outbound_calls: Array.from(outboundCalls),
500
- resolved_outbound_calls: resolvedOutboundCalls.length > 0 ? resolvedOutboundCalls.map(call => ({ ...call, derivation: "inferred" as const })) : undefined,
501
- complexity_smell: complexitySmell,
502
- sibling_methods: siblingMethods.length > 0 ? siblingMethods : undefined,
503
- connected_files: connectedFiles,
504
- ...(shouldIncludeDeps ? { relationships: new DependencyRepository(this.db).getImportRelationships(options.workspaceRoot).filter(edge => edge.source.file === row.file_path) } : {}),
505
- };
338
+ public getInternalImportStatements(fileId: number): string[] {
339
+ return this.db
340
+ .query<{ import_statement: string }, [number]>(
341
+ "SELECT import_statement FROM dependencies WHERE source_file_id = ? AND is_external = 0"
342
+ )
343
+ .all(fileId)
344
+ .map((dep) => dep.import_statement || "");
506
345
  }
507
-
508
346
  }