@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,9 +1,12 @@
1
1
  import type { Database } from "bun:sqlite";
2
+ import { createHash } from "node:crypto";
2
3
  import type {
3
4
  ArchetypeKind,
4
5
  DomainCatalogResponse,
5
6
  DomainConfig,
6
7
  DomainRecord,
8
+ NavigationFile,
9
+ NavigationEntrypoint,
7
10
  ExtractedDependency,
8
11
  ExtractedSymbol,
9
12
  FileRecord,
@@ -35,20 +38,29 @@ export type {
35
38
  } from "../../types/index.ts";
36
39
  import { DependencyRepository } from "./repositories/dependency.repository.ts";
37
40
  import { DomainRepository } from "./repositories/domain.repository.ts";
38
- import { EnvironmentRepository } from "./repositories/environment.repository.ts";
39
41
  import { FileRepository } from "./repositories/file.repository.ts";
40
42
  import { MetaRepository } from "./repositories/meta.repository.ts";
41
43
  import { SymbolRepository } from "./repositories/symbol.repository.ts";
44
+ import {
45
+ buildDomainFileConnections,
46
+ buildFileConnections,
47
+ buildFileInboundImpact,
48
+ buildImportEvidence,
49
+ buildImportRelationships,
50
+ buildScopedImportRelationships,
51
+ buildSymbolImpact,
52
+ } from "../resolver/dependency-analysis.ts";
53
+ import { buildSymbolDetails } from "../retrieval/symbol-details.ts";
42
54
 
43
55
  export type DatabaseRepository = SeptumRepository;
44
56
 
45
57
  export class SeptumRepository {
58
+ private indexIdentityCache?: { stamp: string; digest: string };
46
59
  public readonly domains: DomainRepository;
47
60
  public readonly files: FileRepository;
48
61
  public readonly symbols: SymbolRepository;
49
62
  public readonly dependencies: DependencyRepository;
50
63
  public readonly meta: MetaRepository;
51
- public readonly environment: EnvironmentRepository;
52
64
 
53
65
  constructor(private db: Database) {
54
66
  this.domains = new DomainRepository(db);
@@ -56,7 +68,6 @@ export class SeptumRepository {
56
68
  this.symbols = new SymbolRepository(db);
57
69
  this.dependencies = new DependencyRepository(db);
58
70
  this.meta = new MetaRepository(db);
59
- this.environment = new EnvironmentRepository(db);
60
71
  }
61
72
 
62
73
  public runInTransaction<T>(fn: () => T, immediate = false): T {
@@ -72,9 +83,63 @@ export class SeptumRepository {
72
83
  }
73
84
  }
74
85
 
86
+ public getNavigationFiles(): NavigationFile[] {
87
+ return this.db.query<NavigationFile, []>(`
88
+ SELECT f.path, d.name AS domain, f.archetype, COUNT(s.id) AS symbol_count,
89
+ (SELECT name FROM symbols WHERE file_id = f.id AND kind IN ('function','class','struct','interface') ORDER BY line_start, name LIMIT 1) AS anchor
90
+ FROM files f JOIN domains d ON d.id = f.domain_id
91
+ LEFT JOIN symbols s ON s.file_id = f.id
92
+ GROUP BY f.id ORDER BY f.path
93
+ `).all();
94
+ }
95
+
96
+ public getNavigationEntrypoints(): NavigationEntrypoint[] {
97
+ return this.db.query<NavigationEntrypoint, []>(`
98
+ SELECT DISTINCT http_method AS method, route_uri AS target,
99
+ controller_file AS file, action_name AS handler
100
+ FROM vertical_slices ORDER BY controller_file, http_method, route_uri, action_name
101
+ `).all();
102
+ }
103
+
104
+ /** Stable content identity without materializing/sorting the index in JS.
105
+ * SQLite counters invalidate the cache for local writes and other connections;
106
+ * the digest excludes insertion IDs and operational timestamps.
107
+ */
108
+ public getIndexIdentity(): string {
109
+ // total_changes does not rewind on rollback. Never publish a digest of
110
+ // uncommitted facts into the connection cache.
111
+ const cacheable = !this.db.inTransaction;
112
+ return this.runInTransaction(() => {
113
+ const stamp = JSON.stringify([
114
+ this.db.query("PRAGMA data_version").get(),
115
+ this.db.query("SELECT total_changes() AS changes").get(),
116
+ this.db.query("PRAGMA schema_version").get(),
117
+ ]);
118
+ if (cacheable && this.indexIdentityCache?.stamp === stamp) return this.indexIdentityCache.digest;
119
+ const hash = createHash("sha256");
120
+ for (const sql of [
121
+ `SELECT json_array(name, root_path, allowed_deps_json, forbidden_deps_json, archetypes_json) AS fact
122
+ FROM domains ORDER BY fact`,
123
+ `SELECT json_array(f.path, f.content_hash, d.name) AS fact
124
+ FROM files f JOIN domains d ON d.id = f.domain_id ORDER BY fact`,
125
+ `SELECT json_array(f.path, s.name, s.kind, s.signature, s.visibility, s.line_start, s.line_end, s.line_count, s.nesting_depth) AS fact
126
+ FROM symbols s JOIN files f ON f.id = s.file_id ORDER BY fact`,
127
+ `SELECT json_array(f.path, d.name, dep.target_symbol_or_path, dep.import_statement, dep.line_number, dep.is_external) AS fact
128
+ FROM dependencies dep JOIN files f ON f.id = dep.source_file_id JOIN domains d ON d.id = f.domain_id ORDER BY fact`,
129
+ `SELECT json_array(key, value) AS fact FROM repo_meta WHERE key IN ('sync_state', 'parser_revision') ORDER BY key`,
130
+ ]) {
131
+ hash.update("\0");
132
+ for (const { fact } of this.db.query<{ fact: string }, []>(sql).iterate()) hash.update(fact + "\n");
133
+ }
134
+ const digest = hash.digest("hex");
135
+ if (cacheable) this.indexIdentityCache = { stamp, digest };
136
+ return digest;
137
+ });
138
+ }
139
+
75
140
  // --- Domain Methods ---
76
- public upsertDomain(name: string, config: DomainConfig): number {
77
- return this.domains.upsertDomain(name, config);
141
+ public upsertDomain(name: string, config: DomainConfig, workspaceRoot?: string): number {
142
+ return this.domains.upsertDomain(name, config, workspaceRoot);
78
143
  }
79
144
 
80
145
  public getDomainByName(name: string): DomainRecord | null {
@@ -85,6 +150,10 @@ export class SeptumRepository {
85
150
  return this.domains.getAllDomains();
86
151
  }
87
152
 
153
+ public pruneDomainsNotIn(activeNames: string[]): { prunedDomains: number; removedFiles: number } {
154
+ return this.domains.pruneDomainsNotIn(activeNames);
155
+ }
156
+
88
157
  // --- File Methods ---
89
158
  public getFileByPath(path: string): FileRecord | null {
90
159
  return this.files.getFileByPath(path);
@@ -130,6 +199,10 @@ export class SeptumRepository {
130
199
  return this.files.deleteFilesNotInPaths(domainId, validPaths);
131
200
  }
132
201
 
202
+ public rebindFilesToDomain(rootPrefix: string, domainId: number): number {
203
+ return this.files.rebindFilesToDomain(rootPrefix, domainId);
204
+ }
205
+
133
206
  public deleteFile(path: string): void {
134
207
  this.files.deleteFile(path);
135
208
  }
@@ -147,6 +220,13 @@ export class SeptumRepository {
147
220
  }
148
221
 
149
222
  // --- Symbol Methods ---
223
+ public getDependenciesByFileId(fileId: number): ExtractedDependency[] {
224
+ return this.db.query<ExtractedDependency, [number]>(`
225
+ SELECT target_symbol_or_path AS target, import_statement AS statement,
226
+ line_number, is_external FROM dependencies WHERE source_file_id = ? ORDER BY id
227
+ `).all(fileId);
228
+ }
229
+
150
230
  public replaceFileSymbols(fileId: number, symbols: ExtractedSymbol[]): void {
151
231
  this.symbols.replaceFileSymbols(fileId, symbols);
152
232
  }
@@ -168,8 +248,15 @@ export class SeptumRepository {
168
248
  return this.symbols.findContainers(containerName);
169
249
  }
170
250
 
171
- public getAllSymbolsWithFiles(): Array<SymbolRecord & { file_path: string }> {
172
- return this.symbols.getAllSymbolsWithFiles();
251
+ public findFuzzySymbolCandidates(
252
+ query: string,
253
+ options?: { domainId?: number; filePath?: string; limit?: number }
254
+ ): Array<SymbolRecord & { file_path: string }> {
255
+ return this.symbols.findFuzzySymbolCandidates(query, options);
256
+ }
257
+
258
+ public getAllSymbolsWithFiles(filter?: { domainId?: number; filePath?: string }): Array<SymbolRecord & { file_path: string }> {
259
+ return this.symbols.getAllSymbolsWithFiles(filter);
173
260
  }
174
261
 
175
262
  // --- Dependency & Slice Methods ---
@@ -183,6 +270,14 @@ export class SeptumRepository {
183
270
  this.dependencies.upsertVerticalSlice(slice);
184
271
  }
185
272
 
273
+ public insertVerticalSlice(slice: Omit<VerticalSliceRecord, "id" | "created_at">): void {
274
+ this.dependencies.insertVerticalSlice(slice);
275
+ }
276
+
277
+ public insertVerticalSlices(slices: ReadonlyArray<Omit<VerticalSliceRecord, "id" | "created_at">>): void {
278
+ this.dependencies.insertVerticalSlices(slices);
279
+ }
280
+
186
281
  public findVerticalSlices(searchTerm: string): VerticalSliceRecord[] {
187
282
  return this.dependencies.findVerticalSlices(searchTerm);
188
283
  }
@@ -191,6 +286,10 @@ export class SeptumRepository {
191
286
  return this.dependencies.getAllVerticalSlices();
192
287
  }
193
288
 
289
+ public findExactVerticalSlices(rawQuery: string, controllerFile?: string): VerticalSliceRecord[] {
290
+ return this.dependencies.findExactVerticalSlices(rawQuery, controllerFile);
291
+ }
292
+
194
293
  public countVerticalSlices(): number {
195
294
  return this.dependencies.countVerticalSlices();
196
295
  }
@@ -199,16 +298,31 @@ export class SeptumRepository {
199
298
  this.dependencies.clearVerticalSlices(domainId);
200
299
  }
201
300
 
202
- public getImportRelationships(workspaceRoot?: string) {
203
- return this.dependencies.getImportRelationships(workspaceRoot);
301
+ public getImportEvidence(workspaceRoot: string, verifyFile?: (file: string) => boolean) {
302
+ return buildImportEvidence(this.dependencies, workspaceRoot, undefined, verifyFile);
303
+ }
304
+
305
+ public getImportRelationships(workspaceRoot?: string, sourceFile?: string) {
306
+ return buildImportRelationships(this.dependencies, workspaceRoot, sourceFile);
307
+ }
308
+
309
+ public getScopedImportRelationships(
310
+ workspaceRoot?: string,
311
+ options: {
312
+ sourceFiles?: ReadonlySet<string>;
313
+ targetCandidateFiles?: ReadonlySet<string>;
314
+ sourceOrTargetPaths?: ReadonlySet<string>;
315
+ } = {}
316
+ ) {
317
+ return buildScopedImportRelationships(this.dependencies, workspaceRoot, options);
204
318
  }
205
319
 
206
320
  public getDomainFileConnections(domainId?: number, workspaceRoot?: string) {
207
- return this.dependencies.getDomainFileConnections(domainId,workspaceRoot);
321
+ return buildDomainFileConnections(this.dependencies, domainId, workspaceRoot);
208
322
  }
209
323
 
210
324
  public getFileConnections(filePath: string, workspaceRoot?: string) {
211
- return this.dependencies.getFileConnections(filePath,workspaceRoot);
325
+ return buildFileConnections(this.dependencies, filePath, workspaceRoot);
212
326
  }
213
327
 
214
328
  public getAllDependenciesWithDomains(): Array<{
@@ -253,38 +367,38 @@ export class SeptumRepository {
253
367
  return this.symbols.getFileWithDomain(filePath);
254
368
  }
255
369
 
256
- public getHotspotSymbols(options: {
257
- minLines?: number;
258
- minNesting?: number;
259
- kind?: SymbolKind;
260
- domain?: string;
261
- limit?: number;
262
- sortBy?: "lines" | "nesting" | "risk_score";
263
- } = {}): Array<SymbolRecord & { file_path: string; domain_name: string; risk_score: number }> {
264
- return this.symbols.getHotspotSymbols(options);
370
+ public findConstructorSignature(fileId: number, classOwner: string): string | null {
371
+ return this.symbols.findConstructorSignature(fileId, classOwner);
372
+ }
373
+
374
+ public getInternalImportStatements(fileId: number): string[] {
375
+ return this.symbols.getInternalImportStatements(fileId);
265
376
  }
266
377
 
267
378
  public getSymbolDetails(
268
379
  symbolQuery: string,
269
380
  options: SymbolSelectionOptions & { includeDependencies?: boolean; workspaceRoot?: string } = {}
270
381
  ): GetSymbolDetailsResponse | null {
271
- return this.symbols.getSymbolDetails(symbolQuery, options);
382
+ return buildSymbolDetails(this, symbolQuery, options);
272
383
  }
273
384
 
274
385
  public getSymbolImpact(
275
386
  symbolName: string,
276
387
  options: { domain?: string; workspaceRoot?: string; filePath?: string; reference?: SymbolReference } = {}
277
388
  ): GetSymbolImpactResponse {
278
- return this.dependencies.getSymbolImpact(symbolName, options);
389
+ return buildSymbolImpact(this.dependencies, symbolName, options);
279
390
  }
280
391
 
281
- public getFileInboundImpact(filePath: string): {
392
+ public getFileInboundImpact(
393
+ filePath: string,
394
+ precomputedRelationships?: ReturnType<SeptumRepository["getImportRelationships"]>
395
+ ): {
282
396
  direct_dependents_count: number;
283
397
  top_consumers: string[];
284
398
  symbols_count: number;
285
399
  risk_level: "low" | "medium" | "high";
286
400
  } {
287
- return this.dependencies.getFileInboundImpact(filePath);
401
+ return buildFileInboundImpact(this.dependencies, filePath, precomputedRelationships);
288
402
  }
289
403
 
290
404
  // --- Metadata Methods ---
@@ -1,6 +1,7 @@
1
1
  import type { Database } from "bun:sqlite";
2
+ import { computeSymbolLeafName } from "./repositories/symbol.repository.ts";
2
3
 
3
- export const CURRENT_SCHEMA_VERSION = 4;
4
+ export const CURRENT_SCHEMA_VERSION = 5;
4
5
 
5
6
  export const TABLE_STATEMENTS = [
6
7
  `CREATE TABLE IF NOT EXISTS domains (
@@ -31,6 +32,7 @@ export const TABLE_STATEMENTS = [
31
32
  id INTEGER PRIMARY KEY AUTOINCREMENT,
32
33
  file_id INTEGER NOT NULL,
33
34
  name TEXT NOT NULL,
35
+ leaf_name TEXT NOT NULL DEFAULT '',
34
36
  kind TEXT NOT NULL,
35
37
  signature TEXT NOT NULL,
36
38
  visibility TEXT NOT NULL DEFAULT 'public',
@@ -48,6 +50,7 @@ export const TABLE_STATEMENTS = [
48
50
  import_statement TEXT NOT NULL,
49
51
  line_number INTEGER NOT NULL DEFAULT 0,
50
52
  is_external BOOLEAN NOT NULL DEFAULT 0,
53
+ resolved_target_file TEXT,
51
54
  FOREIGN KEY (source_file_id) REFERENCES files(id) ON DELETE CASCADE
52
55
  );`,
53
56
 
@@ -74,32 +77,6 @@ export const TABLE_STATEMENTS = [
74
77
  value TEXT NOT NULL,
75
78
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
76
79
  );`,
77
-
78
- `CREATE TABLE IF NOT EXISTS environment_topology (
79
- layer TEXT PRIMARY KEY,
80
- platform TEXT,
81
- status TEXT NOT NULL,
82
- detected_from_json TEXT NOT NULL DEFAULT '[]',
83
- constraints_json TEXT NOT NULL DEFAULT '[]',
84
- unresolved_inquiry TEXT,
85
- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
86
- );`,
87
-
88
- `CREATE TABLE IF NOT EXISTS environment_nodes (
89
- id TEXT PRIMARY KEY,
90
- layer TEXT NOT NULL,
91
- name TEXT NOT NULL,
92
- platform TEXT NOT NULL,
93
- canonical_tag TEXT NOT NULL DEFAULT 'unspecified',
94
- domain_or_ip TEXT,
95
- role TEXT,
96
- status TEXT NOT NULL,
97
- detected_from_json TEXT NOT NULL DEFAULT '[]',
98
- constraints_json TEXT NOT NULL DEFAULT '[]',
99
- connected_to_json TEXT NOT NULL DEFAULT '[]',
100
- unresolved_inquiry TEXT,
101
- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
102
- );`,
103
80
  ];
104
81
 
105
82
  export const INDEX_STATEMENTS = [
@@ -109,17 +86,14 @@ export const INDEX_STATEMENTS = [
109
86
  "CREATE INDEX IF NOT EXISTS idx_symbols_file_id ON symbols(file_id);",
110
87
  "CREATE INDEX IF NOT EXISTS idx_symbols_file_lines ON symbols(file_id, line_start, line_end);",
111
88
  "CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);",
89
+ "CREATE INDEX IF NOT EXISTS idx_symbols_leaf_name ON symbols(leaf_name);",
112
90
  "CREATE INDEX IF NOT EXISTS idx_symbols_kind ON symbols(kind);",
113
- "CREATE INDEX IF NOT EXISTS idx_symbols_line_count ON symbols(kind, line_count DESC);",
114
- "CREATE INDEX IF NOT EXISTS idx_symbols_nesting_depth ON symbols(nesting_depth DESC);",
115
91
  "CREATE INDEX IF NOT EXISTS idx_dependencies_source ON dependencies(source_file_id);",
116
92
  "CREATE INDEX IF NOT EXISTS idx_dependencies_target ON dependencies(target_symbol_or_path);",
93
+ "CREATE INDEX IF NOT EXISTS idx_dependencies_resolved_target ON dependencies(resolved_target_file);",
117
94
  "CREATE INDEX IF NOT EXISTS idx_slices_route_uri ON vertical_slices(route_uri);",
118
95
  "CREATE INDEX IF NOT EXISTS idx_slices_route_name ON vertical_slices(route_name);",
119
96
  "CREATE INDEX IF NOT EXISTS idx_slices_controller ON vertical_slices(controller_class, action_name);",
120
- "CREATE INDEX IF NOT EXISTS idx_env_topology_status ON environment_topology(status);",
121
- "CREATE INDEX IF NOT EXISTS idx_env_nodes_layer ON environment_nodes(layer, id);",
122
- "CREATE INDEX IF NOT EXISTS idx_env_nodes_status ON environment_nodes(status);",
123
97
  ];
124
98
 
125
99
  const DROP_ALL_TABLES = `
@@ -138,7 +112,7 @@ export function initializeDatabaseSchema(db: Database): void {
138
112
  const userVersion = versionRow?.user_version ?? 0;
139
113
 
140
114
  if (userVersion !== 0 && userVersion !== CURRENT_SCHEMA_VERSION) {
141
- // Zero-kludge cache invalidation: outdated schema versions are cleanly dropped and recreated
115
+ // Outdated schema versions are cleanly dropped and recreated
142
116
  db.run(DROP_ALL_TABLES);
143
117
  }
144
118
 
@@ -146,6 +120,27 @@ export function initializeDatabaseSchema(db: Database): void {
146
120
  db.run(tableSql);
147
121
  }
148
122
 
123
+ // Additive migration for existing v5 databases without resolved_target_file column
124
+ const depCols = db.query<{ name: string }, []>("PRAGMA table_info(dependencies);").all();
125
+ if (!depCols.some(col => col.name === "resolved_target_file")) {
126
+ db.run("ALTER TABLE dependencies ADD COLUMN resolved_target_file TEXT;");
127
+ }
128
+
129
+ // Additive migration for existing v5 databases without symbols.leaf_name column
130
+ const symCols = db.query<{ name: string }, []>("PRAGMA table_info(symbols);").all();
131
+ if (!symCols.some(col => col.name === "leaf_name")) {
132
+ db.run("ALTER TABLE symbols ADD COLUMN leaf_name TEXT NOT NULL DEFAULT '';");
133
+ const rows = db.query<{ id: number; name: string }, []>("SELECT id, name FROM symbols WHERE leaf_name = ''").all();
134
+ if (rows.length > 0) {
135
+ const updateStmt = db.query("UPDATE symbols SET leaf_name = ? WHERE id = ?");
136
+ db.transaction(() => {
137
+ for (const row of rows) {
138
+ updateStmt.run(computeSymbolLeafName(row.name), row.id);
139
+ }
140
+ })();
141
+ }
142
+ }
143
+
149
144
  for (const indexSql of INDEX_STATEMENTS) {
150
145
  db.run(indexSql);
151
146
  }
@@ -0,0 +1,69 @@
1
+ import ts from "typescript";
2
+ import { resolve } from "node:path";
3
+ import { bindContextFile } from "../retrieval/typescript-references.ts";
4
+ import { lineOf, visitRouteCalls } from "../parser/extractors/typescript-bindings.ts";
5
+ import { readOptionalSourceFile } from "../resources/source-files.ts";
6
+ import type { FileRecord } from "../../types/index.ts";
7
+
8
+ export interface DiscoveredRoute {
9
+ method: string;
10
+ uri: string;
11
+ file: string;
12
+ line: number;
13
+ middlewareSymbols: string[];
14
+ handlerSymbol?: string;
15
+ handlerClass?: string;
16
+ handlerMethod?: string;
17
+ }
18
+
19
+ /** Discover declarative ambient router calls (app/router/server/api.get/post/...) in JS/TS route modules. */
20
+ export function discoverDeclarativeRoutesFromFiles(
21
+ projectRoot: string,
22
+ filesByNormPath: ReadonlyMap<string, FileRecord>,
23
+ excluded?: ReadonlySet<string>
24
+ ): DiscoveredRoute[] {
25
+ const routes: DiscoveredRoute[] = [];
26
+ for (const [key, file] of filesByNormPath) {
27
+ if (
28
+ excluded?.has(file.path) ||
29
+ !/\.[cm]?[jt]sx?$/.test(key) ||
30
+ (file.archetype !== "route" && !/routes?|router|endpoints?/.test(key))
31
+ ) {
32
+ continue;
33
+ }
34
+ const absolute = resolve(projectRoot, file.path);
35
+ const source = readOptionalSourceFile(absolute, "utf-8");
36
+ if (!source) continue;
37
+ const unit = bindContextFile(absolute, source);
38
+ if (unit.hasErrors) continue;
39
+
40
+ visitRouteCalls(unit.source, (call) => {
41
+ const member = call.expression;
42
+ if (
43
+ !ts.isPropertyAccessExpression(member) ||
44
+ !ts.isIdentifier(member.expression) ||
45
+ !/^(app|router|server|api)$/.test(member.expression.text) ||
46
+ unit.checker.getSymbolAtLocation(member.expression) ||
47
+ !/^(get|post|put|patch|delete|options|head)$/.test(member.name.text)
48
+ ) {
49
+ return;
50
+ }
51
+ const uri = call.arguments[0];
52
+ const handler = call.arguments.at(-1);
53
+ if (!uri || !ts.isStringLiteralLike(uri) || call.arguments.length < 2 || !handler) return;
54
+ routes.push({
55
+ method: member.name.text.toUpperCase(),
56
+ uri: uri.text,
57
+ file: file.path,
58
+ line: lineOf(call),
59
+ middlewareSymbols: call.arguments.slice(1, -1).map((arg) => arg.getText()),
60
+ handlerSymbol: handler.getText(),
61
+ ...(ts.isPropertyAccessExpression(handler) && {
62
+ handlerClass: handler.expression.getText(),
63
+ handlerMethod: handler.name.text,
64
+ }),
65
+ });
66
+ });
67
+ }
68
+ return routes;
69
+ }
@@ -0,0 +1,149 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ export type DetectedLanguage = "typescript" | "javascript" | "php" | "python" | "go" | "generic";
5
+
6
+ function warnIfUnexpectedError(context: string, err: unknown): void {
7
+ const errno = (err as NodeJS.ErrnoException | undefined)?.code;
8
+ if (errno === "ENOENT" || errno === "ENOTDIR") return;
9
+ const msg = err instanceof Error ? err.message : String(err);
10
+ console.warn(`[Septum Topology] ${context}: ${msg}`);
11
+ }
12
+
13
+ /**
14
+ * Reads compilerOptions.paths from tsconfig.json or jsconfig.json.
15
+ */
16
+ export function readTsConfigPaths(projectRoot: string): Record<string, string[]> {
17
+ for (const file of ["tsconfig.json", "jsconfig.json"]) {
18
+ const fullPath = path.join(projectRoot, file);
19
+ if (fs.existsSync(fullPath)) {
20
+ try {
21
+ const raw = fs.readFileSync(fullPath, "utf-8");
22
+ const stripped = raw.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
23
+ const parsed = JSON.parse(stripped);
24
+ if (parsed.compilerOptions?.paths) {
25
+ return parsed.compilerOptions.paths;
26
+ }
27
+ } catch (err: unknown) {
28
+ warnIfUnexpectedError(`Failed to parse ${fullPath}`, err);
29
+ }
30
+ }
31
+ }
32
+ return {};
33
+ }
34
+
35
+ export function detectProjectLanguage(projectRoot: string): DetectedLanguage {
36
+ if (
37
+ fs.existsSync(path.join(projectRoot, "composer.json")) ||
38
+ fs.existsSync(path.join(projectRoot, "artisan"))
39
+ ) {
40
+ return "php";
41
+ }
42
+ if (fs.existsSync(path.join(projectRoot, "go.mod"))) return "go";
43
+ if (
44
+ fs.existsSync(path.join(projectRoot, "pyproject.toml")) ||
45
+ fs.existsSync(path.join(projectRoot, "requirements.txt"))
46
+ ) {
47
+ return "python";
48
+ }
49
+ if (
50
+ fs.existsSync(path.join(projectRoot, "tsconfig.json")) ||
51
+ fs.existsSync(path.join(projectRoot, "package.json"))
52
+ ) {
53
+ return "typescript";
54
+ }
55
+ return "generic";
56
+ }
57
+
58
+ export function detectProjectFramework(
59
+ projectRoot: string,
60
+ language: DetectedLanguage
61
+ ): string {
62
+ if (language === "php") {
63
+ if (fs.existsSync(path.join(projectRoot, "artisan"))) return "laravel";
64
+ if (
65
+ fs.existsSync(path.join(projectRoot, "bin/console")) ||
66
+ fs.existsSync(path.join(projectRoot, "symfony.lock"))
67
+ ) {
68
+ return "symfony";
69
+ }
70
+ const composerJson = path.join(projectRoot, "composer.json");
71
+ if (fs.existsSync(composerJson)) {
72
+ try {
73
+ const composer = JSON.parse(fs.readFileSync(composerJson, "utf-8"));
74
+ const reqs = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
75
+ if (reqs["symfony/framework-bundle"] || reqs["symfony/symfony"]) {
76
+ return "symfony";
77
+ }
78
+ } catch (err: unknown) {
79
+ warnIfUnexpectedError(`Failed to parse ${composerJson}`, err);
80
+ }
81
+ }
82
+ return "generic-php";
83
+ }
84
+ if (language === "typescript" || language === "javascript") {
85
+ const pkgJson = path.join(projectRoot, "package.json");
86
+ try {
87
+ if (fs.existsSync(pkgJson)) {
88
+ const pkg = JSON.parse(fs.readFileSync(pkgJson, "utf-8"));
89
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
90
+ if (allDeps.next) return "nextjs";
91
+ if (allDeps.nuxt) return "nuxt";
92
+ if (allDeps.astro) return "astro";
93
+ if (allDeps.vue) return "vue";
94
+ if (allDeps["@nestjs/core"]) return "nestjs";
95
+ if (allDeps.express) return "express";
96
+ if (allDeps.fastify) return "fastify";
97
+ if (allDeps.hono) return "hono";
98
+ if (allDeps.elysia) return "elysia";
99
+ if (allDeps["@modelcontextprotocol/sdk"]) return "mcp-server";
100
+ }
101
+ } catch (err: unknown) {
102
+ warnIfUnexpectedError(`Failed to inspect dependencies in ${pkgJson}`, err);
103
+ }
104
+ return "generic-node";
105
+ }
106
+ if (language === "python") {
107
+ if (
108
+ fs.existsSync(path.join(projectRoot, "manage.py")) ||
109
+ fs.existsSync(path.join(projectRoot, "wsgi.py")) ||
110
+ fs.existsSync(path.join(projectRoot, "asgi.py"))
111
+ ) {
112
+ return "django";
113
+ }
114
+ const readSafe = (p: string) => {
115
+ try {
116
+ return fs.existsSync(p) ? fs.readFileSync(p, "utf-8").toLowerCase() : "";
117
+ } catch (err: unknown) {
118
+ warnIfUnexpectedError(`Failed to read ${p}`, err);
119
+ return "";
120
+ }
121
+ };
122
+ const deps =
123
+ readSafe(path.join(projectRoot, "requirements.txt")) +
124
+ " " +
125
+ readSafe(path.join(projectRoot, "pyproject.toml")) +
126
+ " " +
127
+ readSafe(path.join(projectRoot, "Pipfile"));
128
+ if (deps.includes("fastapi")) return "fastapi";
129
+ if (deps.includes("django")) return "django";
130
+ if (deps.includes("flask")) return "flask";
131
+ return "generic-python";
132
+ }
133
+ if (language === "go") {
134
+ const goModPath = path.join(projectRoot, "go.mod");
135
+ if (fs.existsSync(goModPath)) {
136
+ try {
137
+ const modContent = fs.readFileSync(goModPath, "utf-8").toLowerCase();
138
+ if (modContent.includes("github.com/gin-gonic/gin")) return "gin";
139
+ if (modContent.includes("github.com/labstack/echo")) return "echo";
140
+ if (modContent.includes("github.com/go-chi/chi")) return "chi";
141
+ if (modContent.includes("github.com/gofiber/fiber")) return "fiber";
142
+ } catch (err: unknown) {
143
+ warnIfUnexpectedError(`Failed to inspect ${goModPath}`, err);
144
+ }
145
+ }
146
+ return "generic-go";
147
+ }
148
+ return "generic";
149
+ }