@dimassetoid/septum-mcp 0.3.0 → 0.5.1

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 +255 -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
@@ -1,25 +1,12 @@
1
- import { analyzeSymbolImpact } from "../../resolver/symbol-impact.ts";
2
- import { assertPathContained } from "../../resolver/path-resolver.ts";
3
- import { ImportResolver } from "../../resolver/import-resolver.ts";
4
- import { readSourceFile } from "../../resources/source-files.ts";
5
- import { computeContentHash } from "../../ingestion/hasher.ts";
6
- import { getLanguageCapability } from "../../parser/language-capabilities.ts";
7
- import type { ImportRelationship } from "../../../types/index.ts";
8
- import { posix, resolve, sep } from "node:path";
9
1
  import type { Database } from "bun:sqlite";
2
+ import type { DependencyQueryStore } from "../../resolver/dependency-analysis.ts";
3
+ import type { IndexedDependency } from "../../resolver/import-evidence.ts";
10
4
  import type {
11
5
  ExtractedDependency,
12
- FileConnectionsSummary,
13
- GetSymbolImpactResponse,
14
- SymbolReference,
15
6
  VerticalSliceRecord,
16
7
  } from "../../../types/index.ts";
17
8
 
18
- function escapeRegExp(str: string): string {
19
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
20
- }
21
-
22
- export class DependencyRepository {
9
+ export class DependencyRepository implements DependencyQueryStore {
23
10
  constructor(private db: Database) {}
24
11
 
25
12
  public replaceFileDependencies(fileId: number, deps: ExtractedDependency[]): void {
@@ -70,53 +57,128 @@ export class DependencyRepository {
70
57
  existing.id
71
58
  );
72
59
  } else {
73
- this.db
74
- .query(
75
- `INSERT INTO vertical_slices (
76
- domain_id, feature_key, http_method, route_uri, route_name,
77
- controller_class, action_name, controller_file, controller_line,
78
- architecture_style, entry_kind, execution_chain_json
79
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
80
- )
81
- .run(
82
- slice.domain_id,
83
- slice.feature_key,
84
- slice.http_method,
85
- slice.route_uri,
86
- slice.route_name,
87
- slice.controller_class,
88
- slice.action_name,
89
- slice.controller_file,
90
- slice.controller_line,
91
- slice.architecture_style ?? "clean",
92
- slice.entry_kind ?? "http_route",
93
- slice.execution_chain_json
94
- );
60
+ this.insertVerticalSlice(slice);
61
+ }
62
+ }
63
+
64
+ public insertVerticalSlice(slice: Omit<VerticalSliceRecord, "id" | "created_at">): void {
65
+ this.insertVerticalSlices([slice]);
66
+ }
67
+
68
+ public insertVerticalSlices(slices: ReadonlyArray<Omit<VerticalSliceRecord, "id" | "created_at">>): void {
69
+ if (slices.length === 0) return;
70
+ const stmt = this.db.query(
71
+ `INSERT INTO vertical_slices (
72
+ domain_id, feature_key, http_method, route_uri, route_name,
73
+ controller_class, action_name, controller_file, controller_line,
74
+ architecture_style, entry_kind, execution_chain_json
75
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
76
+ );
77
+ for (const slice of slices) {
78
+ stmt.run(
79
+ slice.domain_id,
80
+ slice.feature_key,
81
+ slice.http_method,
82
+ slice.route_uri,
83
+ slice.route_name,
84
+ slice.controller_class,
85
+ slice.action_name,
86
+ slice.controller_file,
87
+ slice.controller_line,
88
+ slice.architecture_style ?? "clean",
89
+ slice.entry_kind ?? "http_route",
90
+ slice.execution_chain_json
91
+ );
95
92
  }
96
93
  }
97
94
 
98
95
  public findVerticalSlices(searchTerm: string): VerticalSliceRecord[] {
99
96
  const term = searchTerm.trim();
100
- const wild = `%${term}%`;
101
- const query = `
102
- SELECT * FROM vertical_slices
103
- WHERE route_uri LIKE ?
104
- OR route_name LIKE ?
105
- OR controller_class LIKE ?
106
- OR action_name LIKE ?
107
- OR feature_key LIKE ?
108
- OR execution_chain_json LIKE ?
109
- ORDER BY id ASC
110
- `;
111
- return this.db.query<VerticalSliceRecord, [string, string, string, string, string, string]>(query).all(
112
- wild, wild, wild, wild, wild, wild
113
- );
97
+ const runQuery = (candidate: string) => {
98
+ const wild = `%${candidate}%`;
99
+ const metadataQuery = `
100
+ SELECT * FROM vertical_slices
101
+ WHERE route_uri LIKE ?
102
+ OR route_name LIKE ?
103
+ OR controller_class LIKE ?
104
+ OR action_name LIKE ?
105
+ OR feature_key LIKE ?
106
+ ORDER BY id ASC
107
+ `;
108
+ const metaRows = this.db
109
+ .query<VerticalSliceRecord, [string, string, string, string, string]>(metadataQuery)
110
+ .all(wild, wild, wild, wild, wild);
111
+ if (metaRows.length > 0) return metaRows;
112
+
113
+ const chainQuery = `
114
+ SELECT * FROM vertical_slices
115
+ WHERE execution_chain_json LIKE ?
116
+ ORDER BY id ASC
117
+ `;
118
+ return this.db.query<VerticalSliceRecord, [string]>(chainQuery).all(wild);
119
+ };
120
+
121
+ const direct = runQuery(term);
122
+ if (direct.length > 0 || !term || term.includes("_")) return direct;
123
+
124
+ // Normalize PascalCase / camelCase queries (e.g. AppSetActive -> app_set_active)
125
+ const snake = term
126
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
127
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
128
+ .toLowerCase();
129
+ if (snake !== term.toLowerCase()) {
130
+ return runQuery(snake);
131
+ }
132
+ return direct;
114
133
  }
115
134
 
116
135
  public getAllVerticalSlices(): VerticalSliceRecord[] {
117
136
  return this.db.query<VerticalSliceRecord, []>("SELECT * FROM vertical_slices ORDER BY id ASC").all();
118
137
  }
119
138
 
139
+ public findExactVerticalSlices(rawQuery: string, controllerFile?: string): VerticalSliceRecord[] {
140
+ const trimmed = rawQuery.trim();
141
+ if (!trimmed) return [];
142
+ const fileFilter = controllerFile ? " AND controller_file = ?" : "";
143
+ const fileParams = controllerFile ? [controllerFile] : [];
144
+
145
+ const methodUri = trimmed.match(/^([A-Z][A-Z0-9-]*)\s+(\/[^\s]*)$/i);
146
+ if (methodUri) {
147
+ const httpMethod = methodUri[1]!.toUpperCase();
148
+ const uri = methodUri[2]!;
149
+ return this.db
150
+ .query<VerticalSliceRecord, string[]>(
151
+ `SELECT * FROM vertical_slices
152
+ WHERE route_uri = ? AND (UPPER(http_method) = ? OR UPPER(http_method) = 'ANY')${fileFilter}
153
+ ORDER BY id ASC`
154
+ )
155
+ .all(uri, httpMethod, ...fileParams);
156
+ }
157
+
158
+ if (trimmed.startsWith("/")) {
159
+ return this.db
160
+ .query<VerticalSliceRecord, string[]>(
161
+ `SELECT * FROM vertical_slices WHERE route_uri = ?${fileFilter} ORDER BY id ASC`
162
+ )
163
+ .all(trimmed, ...fileParams);
164
+ }
165
+
166
+ const ctrlAction = trimmed.match(/^([A-Za-z0-9_\\]+)(?:@|::)([A-Za-z0-9_]+)$/);
167
+ if (ctrlAction) {
168
+ return this.db
169
+ .query<VerticalSliceRecord, string[]>(
170
+ `SELECT * FROM vertical_slices WHERE controller_class = ? AND action_name = ?${fileFilter} ORDER BY id ASC`
171
+ )
172
+ .all(ctrlAction[1]!, ctrlAction[2]!, ...fileParams);
173
+ }
174
+
175
+ return this.db
176
+ .query<VerticalSliceRecord, string[]>(
177
+ `SELECT * FROM vertical_slices WHERE route_name = ?${fileFilter} ORDER BY id ASC`
178
+ )
179
+ .all(trimmed, ...fileParams);
180
+ }
181
+
120
182
  public countVerticalSlices(): number {
121
183
  const row = this.db
122
184
  .query<{ cnt: number }, []>("SELECT COUNT(*) as cnt FROM vertical_slices")
@@ -132,14 +194,7 @@ export class DependencyRepository {
132
194
  }
133
195
  }
134
196
 
135
- public getAllDependenciesWithDomains(sourceFile?: string): Array<{
136
- source_file: string;
137
- source_domain: string;
138
- line_number: number;
139
- target: string;
140
- statement: string;
141
- is_external: boolean;
142
- }> {
197
+ public getAllDependenciesWithDomains(sourceFile?: string): Array<IndexedDependency & { resolved_target_file?: string | null }> {
143
198
  const query = `
144
199
  SELECT
145
200
  f.path AS source_file,
@@ -147,348 +202,181 @@ export class DependencyRepository {
147
202
  dep.line_number,
148
203
  dep.target_symbol_or_path AS target,
149
204
  dep.import_statement AS statement,
150
- dep.is_external
205
+ dep.is_external,
206
+ dep.resolved_target_file
151
207
  FROM dependencies dep
152
208
  JOIN files f ON dep.source_file_id = f.id
153
209
  JOIN domains d ON f.domain_id = d.id
154
210
  ${sourceFile === undefined ? "" : "WHERE f.path = ?"}
155
211
  ORDER BY d.name, f.path, dep.line_number
156
212
  `;
157
- return this.db.query<any, string[]>(query).all(...(sourceFile === undefined ? [] : [sourceFile]));
213
+ return this.db
214
+ .query<IndexedDependency & { resolved_target_file?: string | null }, string[]>(query)
215
+ .all(...(sourceFile === undefined ? [] : [sourceFile]));
158
216
  }
159
217
 
160
- public getImportRelationships(workspaceRoot?: string, sourceFile?: string): ImportRelationship[] {
161
- const root = workspaceRoot ?? this.db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get("workspace_root")?.value;
162
- if (!root) return [];
163
- const files = this.db.query<{ path: string; content_hash: string; domain_id: number }, string[]>(
164
- `SELECT path, content_hash, domain_id FROM files ${sourceFile === undefined ? "" : "WHERE path = ?"}`
165
- ).all(...(sourceFile === undefined ? [] : [sourceFile]));
166
- const domains = this.db.query<{ name: string; root_path: string }, []>("SELECT name, root_path FROM domains").all().sort((a,b)=>b.root_path.length-a.root_path.length);
167
- const resolver = new ImportResolver(root, domains.map(domain => domain.root_path));
168
- const freshness = new Map<string, ImportRelationship["freshness"]>();
169
- const hashes = new Map(files.map(f => [f.path, f.content_hash]));
170
- return this.getAllDependenciesWithDomains(sourceFile).map(dep => {
171
- if (!freshness.has(dep.source_file)) {
172
- try { assertPathContained(dep.source_file, root, "Import source"); freshness.set(dep.source_file, computeContentHash(readSourceFile(resolve(root,dep.source_file))) === hashes.get(dep.source_file) ? "current" : "stale"); }
173
- catch { freshness.set(dep.source_file,"unavailable"); }
174
- }
175
- const resolution = resolver.resolve(dep.target,dep.source_file,dep.statement);
176
- const current = freshness.get(dep.source_file)!;
177
- if (current !== "current") { resolution.status = "unresolved"; resolution.reason = `source_${current}`; resolution.targets = []; }
178
- const targetDomains = resolution.targets.flatMap(target => target.files.map(file => domains.find(domain => {
179
- const targetPath = resolve(root,file), domainPath = resolve(root,domain.root_path);
180
- return targetPath === domainPath || targetPath.startsWith(domainPath + sep);
181
- })?.name).filter((name): name is string => !!name));
182
- return {
183
- kind: "imports", derivation: "source",
184
- source: { file: dep.source_file, line: dep.line_number, statement: dep.statement, indexed_content_hash: hashes.get(dep.source_file) ?? "" },
185
- resolution, target_domains: [...new Set(targetDomains)], freshness: current,
186
- index_coverage: resolution.targets.every(target => target.files.every(file => hashes.has(file) ||
187
- (sourceFile !== undefined && !!this.db.query("SELECT 1 FROM files WHERE path = ?").get(file)) || !getLanguageCapability(file))) ? "complete" : "partial",
188
- ...(dep.source_file.endsWith(".go") ? { import_binding: (() => {
189
- const alias = dep.statement.replace(/^\s*import\s+/, "").match(/^\s*([A-Za-z_]\w*|\.)\s+["`]/)?.[1];
190
- return { kind: alias === "_" ? "blank" : alias === "." ? "dot" : alias ? "named" : "default", alias };
191
- })() } : {}),
192
- ...(dep.source_file.endsWith(".py") ? { import_binding: (() => {
193
- if (/^\s*from\s+.*\s+import\s+\*/.test(dep.statement)) return { kind: "star" };
194
- const asMatch = dep.statement.match(/\bas\s+([A-Za-z_]\w*)\s*$/);
195
- return { kind: asMatch ? "named" : "default", alias: asMatch?.[1] };
196
- })() } : {}),
197
- };
198
- });
199
- }
200
-
201
- public getDomainFileConnections(domainId?: number, workspaceRoot?: string): Map<string, FileConnectionsSummary> {
202
- const root = workspaceRoot ?? this.db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get("workspace_root")?.value;
203
- if (root) {
204
- const files = this.db.query<{ path: string; domain_id: number }, []>("SELECT path, domain_id FROM files").all();
205
- const edges = this.getImportRelationships(root);
206
- return new Map(files.filter(f => domainId === undefined || f.domain_id === domainId).map(file => {
207
- const imports = edges.filter(edge => edge.source.file === file.path && edge.resolution.status === "resolved").flatMap(edge => edge.resolution.targets.flatMap(target => target.files));
208
- const inbound = edges.filter(edge => edge.resolution.status === "resolved" && edge.resolution.targets.some(target => target.files.includes(file.path))).map(edge => edge.source.file);
209
- return [file.path, { imports_from: [...new Set(imports)].sort(), imported_by: [...new Set(inbound)].sort(), imported_by_count: new Set(inbound).size }];
210
- }));
218
+ public getDependenciesForFiles(filePaths: string[]): IndexedDependency[] {
219
+ if (filePaths.length === 0) return [];
220
+ const results: IndexedDependency[] = [];
221
+ for (let i = 0; i < filePaths.length; i += 400) {
222
+ const chunk = filePaths.slice(i, i + 400);
223
+ const placeholders = chunk.map(() => "?").join(",");
224
+ const rows = this.db
225
+ .query<IndexedDependency, string[]>(
226
+ `SELECT
227
+ f.path AS source_file,
228
+ d.name AS source_domain,
229
+ dep.line_number,
230
+ dep.target_symbol_or_path AS target,
231
+ dep.import_statement AS statement,
232
+ dep.is_external
233
+ FROM dependencies dep
234
+ JOIN files f ON dep.source_file_id = f.id
235
+ JOIN domains d ON f.domain_id = d.id
236
+ WHERE f.path IN (${placeholders})
237
+ ORDER BY d.name, f.path, dep.line_number`
238
+ )
239
+ .all(...chunk);
240
+ results.push(...rows);
211
241
  }
212
- const allFiles = this.db
213
- .query<{ id: number; domain_id: number; path: string }, []>(
214
- "SELECT id, domain_id, path FROM files ORDER BY path ASC"
215
- )
216
- .all();
242
+ return results;
243
+ }
217
244
 
218
- const fileById = new Map<number, { id: number; domain_id: number; path: string }>();
219
- const fileByNormPath = new Map<string, string>();
220
- const fileByNoExtPath = new Map<string, string>();
221
-
222
- for (const f of allFiles) {
223
- const norm = f.path.replace(/\\/g, "/").replace(/^\.\//, "");
224
- fileById.set(f.id, { ...f, path: norm });
225
- fileByNormPath.set(norm.toLowerCase(), f.path);
226
- const noExt = norm.replace(/\.[^/.]+$/, "").toLowerCase();
227
- fileByNoExtPath.set(noExt, f.path);
228
- if (noExt.endsWith("/index")) {
229
- fileByNoExtPath.set(noExt.slice(0, -"/index".length), f.path);
230
- }
245
+ public getIndexedFilesByPaths(filePaths: string[]): Array<{ path: string; content_hash: string; domain_id: number }> {
246
+ if (filePaths.length === 0) return [];
247
+ const results: Array<{ path: string; content_hash: string; domain_id: number }> = [];
248
+ for (let i = 0; i < filePaths.length; i += 400) {
249
+ const chunk = filePaths.slice(i, i + 400);
250
+ const placeholders = chunk.map(() => "?").join(",");
251
+ const rows = this.db
252
+ .query<{ path: string; content_hash: string; domain_id: number }, string[]>(
253
+ `SELECT path, content_hash, domain_id FROM files WHERE path IN (${placeholders}) ORDER BY path ASC`
254
+ )
255
+ .all(...chunk);
256
+ results.push(...rows);
231
257
  }
258
+ return results;
259
+ }
232
260
 
233
- const resolveInternalTarget = (sourcePath: string, rawTarget: string): string | null => {
234
- const cleaned = rawTarget.trim().replace(/^['"]|['"]$/g, "").replace(/\\/g, "/");
235
- if (!cleaned) return null;
261
+ public getWorkspaceRootMeta(): string | undefined {
262
+ return this.db.query<{ value: string }, [string]>("SELECT value FROM repo_meta WHERE key = ?").get("workspace_root")?.value;
263
+ }
236
264
 
237
- if (cleaned.startsWith(".")) {
238
- const srcDir = posix.dirname(sourcePath.replace(/\\/g, "/"));
239
- const joined = posix.normalize(posix.join(srcDir, cleaned)).replace(/^\.\//, "");
240
- const lowerJoined = joined.toLowerCase();
241
- const exact = fileByNormPath.get(lowerJoined) ?? fileByNoExtPath.get(lowerJoined.replace(/\.[^/.]+$/, ""));
242
- if (exact) return exact;
243
- }
265
+ public getIndexedFilesForEvidence(sourceFile?: string): Array<{ path: string; content_hash: string; domain_id: number }> {
266
+ return this.db
267
+ .query<{ path: string; content_hash: string; domain_id: number }, string[]>(
268
+ `SELECT path, content_hash, domain_id FROM files ${sourceFile === undefined ? "" : "WHERE path = ?"} ORDER BY path ASC`
269
+ )
270
+ .all(...(sourceFile === undefined ? [] : [sourceFile]));
271
+ }
244
272
 
245
- const aliasClean = cleaned.replace(/^@\//, "src/").replace(/^\.\//, "");
246
- const lowerAlias = aliasClean.toLowerCase();
247
- const byAlias = fileByNormPath.get(lowerAlias) ?? fileByNoExtPath.get(lowerAlias.replace(/\.[^/.]+$/, ""));
248
- if (byAlias) return byAlias;
273
+ public getDomainsForEvidence(): Array<{ name: string; root_path: string }> {
274
+ return this.db.query<{ name: string; root_path: string }, []>("SELECT name, root_path FROM domains").all();
275
+ }
249
276
 
250
- for (const [noExt, origPath] of fileByNoExtPath.entries()) {
251
- if (noExt.endsWith(`/${lowerAlias}`)) {
252
- return origPath;
253
- }
254
- }
255
- return null;
256
- };
277
+ public hasIndexedFile(path: string): boolean {
278
+ return Boolean(this.db.query("SELECT 1 FROM files WHERE path = ?").get(path));
279
+ }
257
280
 
258
- const importsFromMap = new Map<string, Set<string>>();
259
- const importedByMap = new Map<string, Set<string>>();
260
- for (const f of allFiles) {
261
- importsFromMap.set(f.path, new Set());
262
- importedByMap.set(f.path, new Set());
263
- }
281
+ public getAllFileSummaries(): Array<{ id: number; domain_id: number; path: string }> {
282
+ return this.db
283
+ .query<{ id: number; domain_id: number; path: string }, []>("SELECT id, domain_id, path FROM files ORDER BY path ASC")
284
+ .all();
285
+ }
264
286
 
265
- const allInternalDeps = this.db
287
+ public getAllInternalDependencyTargets(): Array<{ source_file_id: number; target_symbol_or_path: string }> {
288
+ return this.db
266
289
  .query<{ source_file_id: number; target_symbol_or_path: string }, []>(
267
290
  "SELECT source_file_id, target_symbol_or_path FROM dependencies WHERE is_external = 0"
268
291
  )
269
292
  .all();
270
-
271
- for (const dep of allInternalDeps) {
272
- const srcFile = fileById.get(dep.source_file_id);
273
- if (!srcFile) continue;
274
- const resolvedTarget = resolveInternalTarget(srcFile.path, dep.target_symbol_or_path);
275
- if (resolvedTarget && resolvedTarget !== srcFile.path) {
276
- importsFromMap.get(srcFile.path)?.add(resolvedTarget);
277
- if (!importedByMap.has(resolvedTarget)) {
278
- importedByMap.set(resolvedTarget, new Set());
279
- }
280
- importedByMap.get(resolvedTarget)?.add(srcFile.path);
281
- }
282
- }
283
-
284
- const result = new Map<string, FileConnectionsSummary>();
285
- for (const f of allFiles) {
286
- if (domainId !== undefined && f.domain_id !== domainId) continue;
287
- const importsFrom = Array.from(importsFromMap.get(f.path) ?? []).sort();
288
- const importedBy = Array.from(importedByMap.get(f.path) ?? []).sort();
289
- result.set(f.path, {
290
- imports_from: importsFrom,
291
- imported_by_count: importedBy.length,
292
- imported_by: importedBy,
293
- });
294
- }
295
-
296
- return result;
297
- }
298
-
299
- public getFileConnections(filePath: string, workspaceRoot?: string): FileConnectionsSummary {
300
- const clean = filePath.replace(/\\/g, "/").replace(/^\.\//, "");
301
- const allConns = this.getDomainFileConnections(undefined,workspaceRoot);
302
- return (
303
- allConns.get(clean) ??
304
- allConns.get(filePath) ?? {
305
- imports_from: [],
306
- imported_by_count: 0,
307
- imported_by: [],
308
- }
309
- );
310
293
  }
311
294
 
312
- public getSymbolImpact(
313
- symbolQuery: string,
314
- options: { domain?: string; workspaceRoot?: string; filePath?: string; reference?: SymbolReference } = {}
315
- ): GetSymbolImpactResponse {
316
- const trimmed = symbolQuery.trim();
317
- if (!trimmed) {
318
- return {
319
- target_symbol: symbolQuery,
320
- found_in_index: false,
321
- warning: "Empty symbol query provided.",
322
- impact_summary: {
323
- total_dependents: 0,
324
- risk_level: "unknown",
325
- affected_files_count: 0,
326
- },
327
- inbound_callers: [],
328
- };
329
- }
330
-
331
- let targetContainer = trimmed;
332
- let targetMethod = "";
333
- if (trimmed.includes("::")) {
334
- const parts = trimmed.split("::");
335
- targetContainer = parts[0];
336
- targetMethod = parts[1];
337
- } else if (trimmed.includes("@")) {
338
- const parts = trimmed.split("@");
339
- targetContainer = parts[0];
340
- targetMethod = parts[1];
341
- }
342
-
343
- // 1. Look up target symbol in symbols joined with files and optionally domains
344
- let targetSymRows: Array<{
345
- name: string;
346
- kind: string;
347
- line_start: number;
348
- line_end: number;
349
- file_path: string;
350
- domain_name?: string | null;
351
- }>;
352
- if (targetMethod) {
353
- let methodSql = `
354
- SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
355
- FROM symbols s
356
- JOIN files f ON s.file_id = f.id
357
- LEFT JOIN domains dom ON f.domain_id = dom.id
358
- `;
359
- const methodParams: any[] = [];
360
- if (options.domain) {
361
- methodSql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
362
- methodParams.push(options.domain);
363
- } else {
364
- methodSql += ` WHERE `;
365
- }
366
- methodSql += ` (s.name = ? OR s.name = ? OR (s.name = ? AND s.kind = 'method')) `;
367
- methodParams.push(trimmed, `${targetContainer}::${targetMethod}`, targetMethod);
368
- targetSymRows = this.db
369
- .query<
370
- {
371
- name: string;
372
- kind: string;
373
- signature: string;
374
- line_start: number;
375
- line_end: number;
376
- file_path: string;
377
- domain_name?: string | null;
378
- },
379
- any[]
380
- >(methodSql)
381
- .all(...methodParams)
382
- .filter(row => {
383
- if (row.name !== targetMethod) return true;
384
- // Go indexes bare method names; the receiver in its signature proves identity.
385
- const receiver = row.signature.match(/^func\s*\(\s*(?:[A-Za-z_]\w*\s+)?\*?([A-Za-z_]\w*)(?:\[[^\]]+\])?\s*\)/);
386
- return receiver?.[1] === targetContainer;
387
- });
388
-
389
- if (targetSymRows.length === 0) {
390
- return {
391
- target_symbol: trimmed,
392
- found_in_index: false,
393
- warning: `Symbol '${trimmed}' was not found in Septum index${options.domain ? ` for domain '${options.domain}'` : ""}. Method does not exist.`,
394
- impact_summary: {
395
- total_dependents: 0,
396
- risk_level: "unknown",
397
- affected_files_count: 0,
398
- },
399
- inbound_callers: [],
400
- };
401
- }
295
+ public findImpactMethodCandidates(
296
+ trimmed: string,
297
+ container: string,
298
+ method: string,
299
+ domain?: string
300
+ ): Array<{
301
+ name: string;
302
+ kind: string;
303
+ signature: string;
304
+ line_start: number;
305
+ line_end: number;
306
+ file_path: string;
307
+ domain_name?: string | null;
308
+ }> {
309
+ let sql = `
310
+ SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
311
+ FROM symbols s
312
+ JOIN files f ON s.file_id = f.id
313
+ LEFT JOIN domains dom ON f.domain_id = dom.id
314
+ `;
315
+ const params: any[] = [];
316
+ if (domain) {
317
+ sql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
318
+ params.push(domain);
402
319
  } else {
403
- let containerSql = `
404
- SELECT s.name, s.kind, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
405
- FROM symbols s
406
- JOIN files f ON s.file_id = f.id
407
- LEFT JOIN domains dom ON f.domain_id = dom.id
408
- `;
409
- const containerParams: any[] = [];
410
- if (options.domain) {
411
- containerSql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
412
- containerParams.push(options.domain);
413
- } else {
414
- containerSql += ` WHERE `;
415
- }
416
- containerSql += ` (s.name = ? OR s.name = ? OR s.name LIKE ? OR s.name LIKE ?) `;
417
- containerParams.push(trimmed, targetContainer, `${targetContainer}::%`, `%::${targetContainer}`);
418
- targetSymRows = this.db
419
- .query<
420
- {
421
- name: string;
422
- kind: string;
423
- line_start: number;
424
- line_end: number;
425
- file_path: string;
426
- domain_name?: string | null;
427
- },
428
- any[]
429
- >(containerSql)
430
- .all(...containerParams);
431
-
432
- if (targetSymRows.length === 0) {
433
- return {
434
- target_symbol: trimmed,
435
- found_in_index: false,
436
- warning: `Symbol '${trimmed}' was not found in Septum index${options.domain ? ` for domain '${options.domain}'` : ""}.`,
437
- impact_summary: {
438
- total_dependents: 0,
439
- risk_level: "unknown",
440
- affected_files_count: 0,
441
- },
442
- inbound_callers: [],
443
- };
444
- }
320
+ sql += ` WHERE `;
445
321
  }
322
+ sql += ` (s.name = ? OR s.name = ? OR (s.name = ? AND s.kind = 'method')) `;
323
+ params.push(trimmed, `${container}::${method}`, method);
324
+ return this.db.query<any, any[]>(sql).all(...params);
325
+ }
446
326
 
447
- const targetFilePath = (options.filePath ?? options.reference?.file_path)?.replace(/\\/g, "/");
448
- if (targetFilePath) {
449
- targetSymRows = targetSymRows.filter((r) => r.file_path.replace(/\\/g, "/") === targetFilePath);
450
- if (targetSymRows.length === 0) {
451
- return {
452
- target_symbol: trimmed,
453
- found_in_index: false,
454
- warning: `Symbol '${trimmed}' was not found in Septum index for file '${targetFilePath}'${options.domain ? ` in domain '${options.domain}'` : ""}.`,
455
- impact_summary: {
456
- total_dependents: 0,
457
- risk_level: "unknown",
458
- affected_files_count: 0,
459
- },
460
- inbound_callers: [],
461
- };
462
- }
327
+ public findImpactContainerCandidates(
328
+ trimmed: string,
329
+ container: string,
330
+ domain?: string
331
+ ): Array<{
332
+ name: string;
333
+ kind: string;
334
+ line_start: number;
335
+ line_end: number;
336
+ file_path: string;
337
+ domain_name?: string | null;
338
+ }> {
339
+ let sql = `
340
+ SELECT s.name, s.kind, s.line_start, s.line_end, f.path AS file_path, dom.name AS domain_name
341
+ FROM symbols s
342
+ JOIN files f ON s.file_id = f.id
343
+ LEFT JOIN domains dom ON f.domain_id = dom.id
344
+ `;
345
+ const params: any[] = [];
346
+ if (domain) {
347
+ sql += ` WHERE LOWER(dom.name) = LOWER(?) AND `;
348
+ params.push(domain);
349
+ } else {
350
+ sql += ` WHERE `;
463
351
  }
352
+ sql += ` (s.name = ? OR s.name = ? OR s.name LIKE ? OR s.name LIKE ?) `;
353
+ params.push(trimmed, container, `${container}::%`, `%::${container}`);
354
+ return this.db.query<any, any[]>(sql).all(...params);
355
+ }
464
356
 
465
- const definingFiles = new Set<string>(
466
- targetSymRows.map((r) => r.file_path.replace(/\\/g, "/"))
467
- );
468
- const domainByFile = new Map<string, string>();
469
- for (const row of targetSymRows) if (row.domain_name) domainByFile.set(row.file_path.replace(/\\/g, "/"), row.domain_name);
470
-
471
- const definingFileStems = Array.from(
472
- new Set(
473
- Array.from(definingFiles)
474
- .map((p) => p.split("/").pop()?.replace(/\.[^.]+$/, "") || "")
475
- .filter((s) => s.length >= 2)
476
- )
477
- );
478
-
479
- // 2. Query dependencies matching targetContainer, trimmed, import_statement, or defining file stem
357
+ public queryDependenciesForImpact(patterns: {
358
+ container: string;
359
+ trimmed: string;
360
+ stems: string[];
361
+ }): Array<{
362
+ file: string;
363
+ line_number: number;
364
+ target_symbol_or_path: string;
365
+ import_statement: string;
366
+ domain_name?: string | null;
367
+ }> {
480
368
  const whereClauses: string[] = [
481
369
  "d.target_symbol_or_path LIKE ?",
482
370
  "d.import_statement LIKE ?",
483
371
  "d.target_symbol_or_path LIKE ?",
484
372
  ];
485
373
  const queryParams: string[] = [
486
- `%${targetContainer}%`,
487
- `%${targetContainer}%`,
488
- `%${trimmed}%`,
374
+ `%${patterns.container}%`,
375
+ `%${patterns.container}%`,
376
+ `%${patterns.trimmed}%`,
489
377
  ];
490
378
 
491
- for (const stem of definingFileStems) {
379
+ for (const stem of patterns.stems) {
492
380
  whereClauses.push("d.target_symbol_or_path LIKE ?");
493
381
  queryParams.push(`%${stem}%`);
494
382
  }
@@ -506,228 +394,102 @@ export class DependencyRepository {
506
394
  WHERE ${whereClauses.join(" OR ")}
507
395
  ORDER BY f.path ASC, d.line_number ASC
508
396
  `;
509
- const rawDepRows = this.db.query<any, string[]>(depSql).all(...queryParams);
510
-
511
- const isTargetedFile = Boolean(targetFilePath);
512
- const matchesDefiningFile = (df: string, stmt: string, target: string): boolean => {
513
- const normStmt = stmt.replace(/\\/g, "/");
514
- const normTarget = target.replace(/\\/g, "/");
515
- const clean = df.replace(/\.[^.]+$/, "");
516
- const parts = clean.split("/");
517
- const suffixes: string[] = [];
518
- for (let i = 0; i < parts.length; i++) {
519
- suffixes.push(parts.slice(i).join("/"));
520
- }
521
- return suffixes.some((s) => {
522
- const escaped = escapeRegExp(s);
523
- const r = new RegExp(`(?:^|[\\\\/\"\x27.@:])(?:${escaped})(?:$|[\\\\/\"\x27;:.()\\s]|\\.[^\\\\/]+)`, "i");
524
- return r.test(normStmt) || r.test(normTarget);
525
- });
526
- };
527
-
528
- const containerWordRegex = new RegExp(`\\b${escapeRegExp(targetContainer)}\\b`);
529
- const depRows = rawDepRows.filter((row) => {
530
- const normCallerFile = String(row.file).replace(/\\/g, "/");
531
- if (row.domain_name) domainByFile.set(normCallerFile, String(row.domain_name));
532
- if (definingFiles.has(normCallerFile)) return false;
533
-
534
- const stmt = String(row.import_statement || "");
535
- const target = String(row.target_symbol_or_path || "");
536
-
537
- if (containerWordRegex.test(stmt) || containerWordRegex.test(target)) {
538
- if (isTargetedFile) {
539
- const matchesDefining = Array.from(definingFiles).some((df) => matchesDefiningFile(df, stmt, target));
540
- if (!matchesDefining) {
541
- return false;
542
- }
543
- }
544
- return true;
545
- }
546
-
547
- // If no named specifier braces are present, accept path match against defining file stem
548
- if (!stmt.includes("{")) {
549
- for (const stem of definingFileStems) {
550
- const stemRegex = new RegExp(`(?:^|[\\\\/])${escapeRegExp(stem)}(?:\\.[^\\\\/]+)?$`);
551
- if (stemRegex.test(target)) {
552
- return true;
553
- }
554
- }
555
- }
556
-
557
- return false;
558
- });
559
-
560
- // 2b. Discover same-directory / same-package files for languages with implicit package/namespace resolution (.go, .php, .java, .cs)
561
- const implicitPackageFiles = new Set<string>();
562
- const implicitLangDirs = new Set<string>();
563
- for (const df of definingFiles) {
564
- if (/\.(go|php|java|cs)$/i.test(df)) {
565
- const dir = posix.dirname(df);
566
- implicitLangDirs.add(dir === "." ? "" : dir);
567
- }
568
- }
569
- if (implicitLangDirs.size > 0) {
570
- const dirClauses: string[] = [];
571
- const dirParams: string[] = [];
572
- for (const dir of implicitLangDirs) {
573
- if (dir === "") {
574
- dirClauses.push("f.path NOT LIKE '%/%'");
575
- } else {
576
- dirClauses.push("(f.path LIKE ? AND SUBSTR(f.path, LENGTH(?) + 2) NOT LIKE '%/%')");
577
- dirParams.push(`${dir}/%`, dir);
578
- }
579
- }
580
- const pkgRows = this.db
581
- .query<{ path: string; domain_name: string | null }, string[]>(
582
- `SELECT f.path, dom.name AS domain_name
583
- FROM files f
584
- LEFT JOIN domains dom ON f.domain_id = dom.id
585
- WHERE ${dirClauses.join(" OR ")}`
586
- )
587
- .all(...dirParams);
588
- for (const r of pkgRows) {
589
- const norm = r.path.replace(/\\/g, "/");
590
- if (r.domain_name) domainByFile.set(norm, r.domain_name);
591
- if (!definingFiles.has(norm) && /\.(go|php|java|cs)$/i.test(norm)) {
592
- implicitPackageFiles.add(norm);
593
- }
594
- }
595
- }
596
-
597
- // 3. Batch-load all symbols for candidate caller files in ONE query (zero N+1)
598
- const uniqueCallerFiles = Array.from(new Set(depRows.map((r) => String(r.file))));
599
- const allSymbolLookupFiles = Array.from(
600
- new Set([...uniqueCallerFiles, ...definingFiles, ...implicitPackageFiles])
601
- );
602
- const callerSymbolsByFile = new Map<
603
- string,
604
- Array<{ name: string; kind: string; signature: string; line_start: number; line_end: number }>
605
- >();
606
-
607
- if (allSymbolLookupFiles.length > 0) {
608
- const placeholders = allSymbolLookupFiles.map(() => "?").join(",");
609
- const allCallerSyms = this.db
610
- .query<
611
- { name: string; kind: string; signature: string; line_start: number; line_end: number; path: string },
612
- string[]
613
- >(
614
- `SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path
615
- FROM symbols s
616
- JOIN files f ON s.file_id = f.id
617
- WHERE f.path IN (${placeholders})
618
- ORDER BY (s.line_end - s.line_start) ASC`
619
- )
620
- .all(...allSymbolLookupFiles);
397
+ return this.db.query<any, string[]>(depSql).all(...queryParams);
398
+ }
621
399
 
622
- for (const sym of allCallerSyms) {
623
- const list = callerSymbolsByFile.get(sym.path) || [];
624
- list.push(sym);
625
- callerSymbolsByFile.set(sym.path, list);
400
+ public findSameDirectoryPackageFiles(dirs: string[]): Array<{ path: string; domain_name: string | null }> {
401
+ if (dirs.length === 0) return [];
402
+ const dirClauses: string[] = [];
403
+ const dirParams: string[] = [];
404
+ for (const dir of dirs) {
405
+ if (dir === "") {
406
+ dirClauses.push("f.path NOT LIKE '%/%'");
407
+ } else {
408
+ dirClauses.push("(f.path LIKE ? AND SUBSTR(f.path, LENGTH(?) + 2) NOT LIKE '%/%')");
409
+ dirParams.push(`${dir}/%`, dir);
626
410
  }
627
411
  }
628
-
629
- return analyzeSymbolImpact({
630
- query: trimmed, container: targetContainer, method: targetMethod,
631
- targets: targetSymRows, dependencies: depRows, samePackageFiles: implicitPackageFiles,
632
- symbolsByFile: callerSymbolsByFile, domainsByFile: domainByFile, workspaceRoot: options.workspaceRoot,
633
- });
412
+ return this.db
413
+ .query<{ path: string; domain_name: string | null }, string[]>(
414
+ `SELECT f.path, dom.name AS domain_name
415
+ FROM files f
416
+ LEFT JOIN domains dom ON f.domain_id = dom.id
417
+ WHERE ${dirClauses.join(" OR ")}`
418
+ )
419
+ .all(...dirParams);
634
420
  }
635
421
 
636
- public getFileInboundImpact(filePath: string): {
637
- direct_dependents_count: number;
638
- top_consumers: string[];
639
- symbols_count: number;
640
- risk_level: "low" | "medium" | "high";
641
- } {
642
- const cleanPath = filePath.replace(/\\/g, "/");
643
- const baseName = cleanPath.split("/").pop()?.replace(/\.[^.]+$/, "") || "";
422
+ public findSymbolsForFiles(filePaths: string[]): Array<{
423
+ name: string;
424
+ kind: string;
425
+ signature: string;
426
+ line_start: number;
427
+ line_end: number;
428
+ path: string;
429
+ }> {
430
+ if (filePaths.length === 0) return [];
431
+ const placeholders = filePaths.map(() => "?").join(",");
432
+ return this.db
433
+ .query<
434
+ { name: string; kind: string; signature: string; line_start: number; line_end: number; path: string },
435
+ string[]
436
+ >(
437
+ `SELECT s.name, s.kind, s.signature, s.line_start, s.line_end, f.path
438
+ FROM symbols s
439
+ JOIN files f ON s.file_id = f.id
440
+ WHERE f.path IN (${placeholders})
441
+ ORDER BY (s.line_end - s.line_start) ASC`
442
+ )
443
+ .all(...filePaths);
444
+ }
644
445
 
645
- const symbols = this.db
446
+ public findFileSymbolNames(cleanPath: string): string[] {
447
+ return this.db
646
448
  .query<{ name: string }, [string, string]>(
647
449
  `SELECT s.name
648
450
  FROM symbols s
649
451
  JOIN files f ON s.file_id = f.id
650
452
  WHERE f.path = ? OR f.path LIKE ?`
651
453
  )
652
- .all(cleanPath, `%${cleanPath}`);
653
-
654
- const matchedFiles = new Set<string>();
655
- const relationships = this.getImportRelationships();
656
- if (relationships.length > 0) {
657
- for (const edge of relationships) {
658
- if (edge.freshness !== "current" || edge.resolution.status !== "resolved") continue;
659
- if (edge.source.file === cleanPath) continue;
660
- if (edge.resolution.targets.some((t) => t.files.includes(cleanPath))) {
661
- matchedFiles.add(edge.source.file);
662
- }
663
- }
664
- } else {
665
- const orConditions: string[] = [];
666
- const params: string[] = [];
667
-
668
- if (baseName.length >= 3) {
669
- orConditions.push("d.target_symbol_or_path LIKE ?");
670
- params.push(`%${cleanPath}%`);
671
- orConditions.push("d.target_symbol_or_path LIKE ?");
672
- params.push(`%${baseName}%`);
673
- }
674
-
675
- for (const sym of symbols.slice(0, 8)) {
676
- const symName = sym.name.split("::").pop() || sym.name;
677
- if (symName.length >= 4) {
678
- orConditions.push("d.target_symbol_or_path LIKE ?");
679
- params.push(`%${symName}%`);
680
- orConditions.push("d.import_statement LIKE ?");
681
- params.push(`%${symName}%`);
682
- }
683
- }
454
+ .all(cleanPath, `%${cleanPath}`)
455
+ .map((s) => s.name);
456
+ }
684
457
 
685
- if (orConditions.length > 0) {
686
- params.push(`%${cleanPath}`);
687
- const depRows = this.db
688
- .query<{ file: string; target: string; stmt: string }, string[]>(
689
- `SELECT DISTINCT f.path AS file, d.target_symbol_or_path AS target, d.import_statement AS stmt
690
- FROM dependencies d
691
- JOIN files f ON d.source_file_id = f.id
692
- WHERE (${orConditions.join(" OR ")})
693
- AND f.path NOT LIKE ?`
694
- )
695
- .all(...params);
696
-
697
- const baseBoundary = baseName.length >= 3
698
- ? new RegExp(`(?:^|[\\/\\\\.])${escapeRegExp(baseName)}(?:\\.[^.\\/\\\\]+)?$`, "i")
699
- : null;
700
- const symNames = symbols
701
- .slice(0, 8)
702
- .map((s) => s.name.split("::").pop() || s.name)
703
- .filter((n) => n.length >= 4)
704
- .map((n) => new RegExp(`\\b${escapeRegExp(n)}\\b`));
705
-
706
- for (const row of depRows) {
707
- const targetMatches =
708
- row.target.includes(cleanPath) ||
709
- (baseBoundary !== null && baseBoundary.test(row.target)) ||
710
- symNames.some((re) => re.test(row.target) || re.test(row.stmt));
711
- if (targetMatches) {
712
- matchedFiles.add(row.file);
713
- }
714
- }
715
- }
458
+ public queryDependenciesForFileInbound(
459
+ cleanPath: string,
460
+ baseName: string,
461
+ symbolNames: string[]
462
+ ): Array<{ file: string; target: string; stmt: string }> {
463
+ const orConditions: string[] = [];
464
+ const params: string[] = [];
465
+
466
+ if (baseName.length >= 3) {
467
+ orConditions.push("d.target_symbol_or_path LIKE ?");
468
+ params.push(`%${cleanPath}%`);
469
+ orConditions.push("d.target_symbol_or_path LIKE ?");
470
+ params.push(`%${baseName}%`);
716
471
  }
717
472
 
718
- const consumerList = Array.from(matchedFiles);
719
- let riskLevel: "low" | "medium" | "high" = "low";
720
- if (consumerList.length >= 5) {
721
- riskLevel = "high";
722
- } else if (consumerList.length >= 2) {
723
- riskLevel = "medium";
473
+ for (const sym of symbolNames.slice(0, 8)) {
474
+ const symName = sym.split("::").pop() || sym;
475
+ if (symName.length >= 4) {
476
+ orConditions.push("d.target_symbol_or_path LIKE ?");
477
+ params.push(`%${symName}%`);
478
+ orConditions.push("d.import_statement LIKE ?");
479
+ params.push(`%${symName}%`);
480
+ }
724
481
  }
725
482
 
726
- return {
727
- direct_dependents_count: consumerList.length,
728
- top_consumers: consumerList.slice(0, 5),
729
- symbols_count: symbols.length,
730
- risk_level: riskLevel,
731
- };
483
+ if (orConditions.length === 0) return [];
484
+ params.push(`%${cleanPath}`);
485
+ return this.db
486
+ .query<{ file: string; target: string; stmt: string }, string[]>(
487
+ `SELECT DISTINCT f.path AS file, d.target_symbol_or_path AS target, d.import_statement AS stmt
488
+ FROM dependencies d
489
+ JOIN files f ON d.source_file_id = f.id
490
+ WHERE (${orConditions.join(" OR ")})
491
+ AND f.path NOT LIKE ?`
492
+ )
493
+ .all(...params);
732
494
  }
733
495
  }