@dimassetoid/septum-mcp 0.2.1 → 0.3.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 (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
@@ -1,4 +1,6 @@
1
+ import { blankCommentsAndStrings } from "./boundary-tracker.ts";
1
2
  export interface MethodBehavioralSummary {
3
+ analysis: "lexical_heuristic";
2
4
  guards: string[];
3
5
  hasTransaction: boolean;
4
6
  emittedEvents: string[];
@@ -18,34 +20,35 @@ export class BehavioralAnalyzer {
18
20
  const dispatchedJobs = new Set<string>();
19
21
  const mutations = new Set<string>();
20
22
 
21
- const lines = code.split("\n");
23
+ const originalLines = code.split("\n");
24
+ const lines = blankCommentsAndStrings(code, { hashComments: true }).split("\n");
22
25
 
23
- for (const rawLine of lines) {
24
- const line = rawLine.trim();
26
+ for (const [index, line] of lines.entries()) {
27
+ const rawLine = originalLines[index]!;
28
+ // Only recover literal arguments after the executable prefix matched the mask.
29
+ const matchCode = (pattern: RegExp) => {
30
+ const match = pattern.exec(line);
31
+ return match ? pattern.exec(rawLine.slice(match.index)) : null;
32
+ };
25
33
  if (!line || line.startsWith("//") || line.startsWith("#")) continue;
26
34
 
27
35
  // 1. Transaction Boundaries
28
- if (
29
- line.includes("DB::transaction") ||
30
- line.includes("DB::beginTransaction") ||
31
- line.includes("this.db.transaction") ||
32
- line.includes(".transaction(")
33
- ) {
36
+ if (/(?:\bDB::(?:transaction|beginTransaction)|\bthis\.db\.transaction|\.transaction)\s*\(/.test(line)) {
34
37
  hasTransaction = true;
35
38
  }
36
39
 
37
40
  // 2. Authorization Guards
38
41
  // Laravel: $this->authorize('update', $order); or Gate::authorize(...)
39
- const authMatch = line.match(/(?:\$this->authorize|Gate::authorize)\s*\(\s*['"]([^'"]+)['"]/);
42
+ const authMatch = matchCode(/(?:\$this->authorize|Gate::authorize)\s*\(\s*['"]([^'"]+)['"]/);
40
43
  if (authMatch) {
41
44
  guards.add(authMatch[1]);
42
45
  }
43
46
  // Laravel: abort_if(!..., 403, '...');
44
- if (line.includes("abort_if(") || line.includes("abort_unless(")) {
47
+ if (/\b(?:abort_if|abort_unless)\s*\(/.test(line)) {
45
48
  guards.add("abort_guard");
46
49
  }
47
50
  // TS / NestJS: @UseGuards(AuthGuard, RolesGuard)
48
- const guardDecoratorMatch = line.match(/@UseGuards\s*\(([^)]+)\)/);
51
+ const guardDecoratorMatch = matchCode(/@UseGuards\s*\(([^)]+)\)/);
49
52
  if (guardDecoratorMatch) {
50
53
  const guardNames = guardDecoratorMatch[1].split(",").map((g) => g.trim());
51
54
  for (const g of guardNames) guards.add(g);
@@ -53,62 +56,63 @@ export class BehavioralAnalyzer {
53
56
 
54
57
  // 3. Emitted Events
55
58
  // Laravel: event(new OrderPlaced($order));
56
- const eventNewMatch = line.match(/event\s*\(\s*new\s+([A-Za-z0-9_]+)/);
59
+ const eventNewMatch = matchCode(/\bevent\s*\(\s*new\s+([A-Za-z0-9_]+)/);
57
60
  if (eventNewMatch) {
58
61
  emittedEvents.add(eventNewMatch[1]);
59
62
  }
60
63
  // Laravel: Event::dispatch(new OrderPlaced($order)); or Event::dispatch('name');
61
- const eventDispatchMatch = line.match(/Event::dispatch\s*\(\s*(?:new\s+)?([A-Za-z0-9_]+)/);
64
+ const eventDispatchMatch = matchCode(/\bEvent::dispatch\s*\(\s*(?:new\s+)?([A-Za-z0-9_]+)/);
62
65
  if (eventDispatchMatch) {
63
66
  emittedEvents.add(eventDispatchMatch[1]);
64
67
  }
65
68
  // Laravel: broadcast(new OrderUpdated($order));
66
- const broadcastMatch = line.match(/broadcast\s*\(\s*new\s+([A-Za-z0-9_]+)/);
69
+ const broadcastMatch = matchCode(/\bbroadcast\s*\(\s*new\s+([A-Za-z0-9_]+)/);
67
70
  if (broadcastMatch) {
68
71
  emittedEvents.add(broadcastMatch[1]);
69
72
  }
70
73
  // EventEmitter: this.eventEmitter.emit('order.created', ...)
71
- const nodeEmitMatch = line.match(/(?:eventEmitter|\$emit)\.emit\s*\(\s*['"]([^'"]+)['"]/);
74
+ const nodeEmitMatch = matchCode(/(?:eventEmitter|\$emit)\.emit\s*\(\s*['"]([^'"]+)['"]/);
72
75
  if (nodeEmitMatch) {
73
76
  emittedEvents.add(nodeEmitMatch[1]);
74
77
  }
75
78
 
76
79
  // 4. Dispatched Background Jobs
77
80
  // Laravel: ProcessPaymentJob::dispatch($order); or ProcessPayment::dispatchSync(...)
78
- const jobDispatchStaticMatch = line.match(/([A-Z][a-zA-Z0-9_]*(?:Job|Queue|Task|Process)[a-zA-Z0-9_]*)::dispatch/);
81
+ const jobDispatchStaticMatch = matchCode(/\b([A-Z][a-zA-Z0-9_]*(?:Job|Queue|Task|Process)[a-zA-Z0-9_]*)::dispatch/);
79
82
  if (jobDispatchStaticMatch) {
80
83
  dispatchedJobs.add(jobDispatchStaticMatch[1]);
81
84
  }
82
85
  // Laravel: dispatch(new ProcessPayment($order));
83
- const dispatchNewMatch = line.match(/dispatch\s*\(\s*new\s+([A-Za-z0-9_]+)/);
86
+ const dispatchNewMatch = matchCode(/\bdispatch\s*\(\s*new\s+([A-Za-z0-9_]+)/);
84
87
  if (dispatchNewMatch) {
85
88
  dispatchedJobs.add(dispatchNewMatch[1]);
86
89
  }
87
90
  // BullMQ / Queue: queue.add('process-payment', ...)
88
- const queueAddMatch = line.match(/(?:queue|queueService)\.add\s*\(\s*['"]([^'"]+)['"]/);
91
+ const queueAddMatch = matchCode(/(?:queue|queueService)\.add\s*\(\s*['"]([^'"]+)['"]/);
89
92
  if (queueAddMatch) {
90
93
  dispatchedJobs.add(queueAddMatch[1]);
91
94
  }
92
95
 
93
96
  // 5. Model Mutations
94
97
  // Laravel / ORM: $order->update([...]);
95
- const updateMatch = line.match(/\$([a-zA-Z0-9_]+)->update\s*\(/);
98
+ const updateMatch = matchCode(/\$([a-zA-Z0-9_]+)->update\s*\(/);
96
99
  if (updateMatch) {
97
100
  mutations.add(`${updateMatch[1]}.update()`);
98
101
  }
99
102
  // Laravel / ORM: $order->delete();
100
- const deleteMatch = line.match(/\$([a-zA-Z0-9_]+)->delete\s*\(/);
103
+ const deleteMatch = matchCode(/\$([a-zA-Z0-9_]+)->delete\s*\(/);
101
104
  if (deleteMatch) {
102
105
  mutations.add(`${deleteMatch[1]}.delete()`);
103
106
  }
104
107
  // Direct property assignment: $order->status = 'completed';
105
- const assignMatch = line.match(/\$([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*=\s*([^;]+);/);
108
+ const assignMatch = matchCode(/\$([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*=(?![=>])\s*([^;]+);/);
106
109
  if (assignMatch && !["this", "request"].includes(assignMatch[1])) {
107
110
  mutations.add(`${assignMatch[1]}.${assignMatch[2]}`);
108
111
  }
109
112
  }
110
113
 
111
114
  return {
115
+ analysis: "lexical_heuristic",
112
116
  guards: Array.from(guards),
113
117
  hasTransaction,
114
118
  emittedEvents: Array.from(emittedEvents),
@@ -393,6 +393,21 @@ export function blankCommentsAndStrings(
393
393
  continue;
394
394
  }
395
395
 
396
+ // PHP heredoc/nowdoc is non-code, including quotes and comment-like text.
397
+ if (ch === "<" && content.slice(i, i + 3) === "<<<") {
398
+ const header = /^<<<[ \t]*['"]?([A-Za-z_]\w*)['"]?[ \t]*\r?\n/.exec(content.slice(i));
399
+ if (header) {
400
+ const rest = content.slice(i + header[0].length);
401
+ const ending = new RegExp(`^[ \\t]*${header[1]}\\b`, "m").exec(rest);
402
+ const end = ending ? i + header[0].length + ending.index + ending[0].length : len;
403
+ while (i < end) {
404
+ if (out[i] !== "\n" && out[i] !== "\r") out[i] = " ";
405
+ i++;
406
+ }
407
+ continue;
408
+ }
409
+ }
410
+
396
411
  // Normal code state
397
412
  if (ch === "/" && next === "/") {
398
413
  out[i] = " ";
@@ -17,12 +17,16 @@ export function detectArchetype(filePath: string, archetypesMap: Record<string,
17
17
 
18
18
  // Built-in convention heuristics
19
19
  const lower = normalized.toLowerCase();
20
- if (lower.includes("controller")) return "controller";
20
+ if (/(?:^|\/)(?:tests?|__tests__)\/|(?:\.test\.|\.spec\.|_test\.go$|Test\.php$)/i.test(normalized)) {
21
+ return "unknown";
22
+ }
23
+ if (lower.includes("controller") || /(?:^|\/)handlers?\/|handler\.(?:go|ts|js|py|php)$/i.test(lower)) return "controller";
21
24
  if (lower.endsWith("views.py") || (lower.includes("views/") && lower.endsWith(".py"))) return "controller";
25
+ if (/(?:^|\/)(?:console\/)?commands?\//i.test(lower)) return "action";
26
+ if (/(?:^|\/)models?\/|entities|entity/.test(lower) || /model\.(?:php|ts|js|py|go)$/i.test(lower)) return "model";
22
27
  if (lower.includes("service")) return "service";
23
28
  if (lower.includes("repository") || lower.includes("repo")) return "repository";
24
- if (lower.includes("model") || lower.includes("entities") || lower.includes("entity")) return "model";
25
- if (lower.includes("action")) return "action";
29
+ if (/(?:^|\/)actions?\/|action\.(?:php|ts|js|py|go)$/i.test(lower)) return "action";
26
30
  if (lower.includes("job") || lower.includes("queue")) return "job";
27
31
  if (lower.includes("event")) return "event";
28
32
  if (lower.includes("listener")) return "listener";
@@ -101,7 +101,8 @@ export class CSharpExtractor implements CodeExtractor {
101
101
  member.type === "class_declaration" ||
102
102
  member.type === "interface_declaration" ||
103
103
  member.type === "struct_declaration" ||
104
- member.type === "record_declaration"
104
+ member.type === "record_declaration" ||
105
+ member.type === "enum_declaration"
105
106
  ) {
106
107
  processNode(member, typeName);
107
108
  }
@@ -123,7 +124,8 @@ export class CSharpExtractor implements CodeExtractor {
123
124
  statement: (lines[node.startPosition.row] ?? node.text).trim().replace(/;$/, ""),
124
125
  line_number: node.startPosition.row + 1,
125
126
  is_external: this.isExternalUsing(rawUsing),
126
- imported_symbols: [leafSymbol],
127
+ imported_symbols: [...new Set([leafSymbol, ...node.namedChildren
128
+ .filter(c => c.type === "name_equals").map(c => c.firstNamedChild?.text).filter((name): name is string => !!name)])],
127
129
  });
128
130
  return;
129
131
  }
@@ -132,12 +134,14 @@ export class CSharpExtractor implements CodeExtractor {
132
134
  node.type === "namespace_declaration" ||
133
135
  node.type === "file_scoped_namespace_declaration"
134
136
  ) {
137
+ const name = node.childForFieldName("name")?.text;
138
+ const namespaceScope = name ? (parentScope ? `${parentScope}.${name}` : name) : parentScope;
135
139
  const body =
136
140
  node.childForFieldName("body") ??
137
141
  node.namedChildren.find((c) => c.type === "declaration_list") ??
138
142
  node;
139
143
  for (const child of body.namedChildren) {
140
- processNode(child, parentScope);
144
+ processNode(child, namespaceScope);
141
145
  }
142
146
  return;
143
147
  }
@@ -1,7 +1,8 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
+ import { readPythonStaticString as cleanLiteral } from "../static-string.ts";
1
3
  import type Parser from "web-tree-sitter";
2
4
  import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
3
5
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
- import { isIgnoredDirectory } from "../../resources/ignore.ts";
5
6
  import { ImportResolver } from "../../resolver/import-resolver.ts";
6
7
  import * as fs from "node:fs";
7
8
  import * as path from "node:path";
@@ -49,16 +50,6 @@ interface UrlInclusion {
49
50
  line: number;
50
51
  }
51
52
 
52
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
53
- if (!node) return undefined;
54
- if (node.type === "string") {
55
- const raw = node.text.trim();
56
- const match = raw.match(/^[rRbBuU]*('''|"""|'|")([\s\S]*?)\1$/);
57
- if (match) return match[2];
58
- return raw.replace(/^[rRbBuU]*['"]|['"]$/g, "");
59
- }
60
- return undefined;
61
- }
62
53
 
63
54
  function normalizeUri(prefix: string, sub: string): string {
64
55
  const p = (prefix ?? "").trim().replace(/^\/+|\/+$/g, "");
@@ -105,9 +96,9 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
105
96
  return false;
106
97
  }
107
98
 
108
- public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal): Promise<VerticalSliceCandidate[]> {
99
+ public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): Promise<VerticalSliceCandidate[]> {
109
100
  const slices: VerticalSliceCandidate[] = [];
110
- const pyFiles = this.findPythonFiles(projectRoot);
101
+ const pyFiles = listSourceFiles(projectRoot, /\.py$/, inventory);
111
102
  const resolver = new ImportResolver(projectRoot);
112
103
 
113
104
  const viewsMap = new Map<string, ViewInfo>();
@@ -660,28 +651,5 @@ export class DjangoSemanticExtractor implements SemanticSliceExtractor {
660
651
 
661
652
  return slices;
662
653
  }
663
-
664
- private findPythonFiles(dir: string): string[] {
665
- const results: string[] = [];
666
- const traverse = (currentDir: string) => {
667
- if (!fs.existsSync(currentDir)) return;
668
- try {
669
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
670
- for (const entry of entries) {
671
- if (isIgnoredDirectory(entry.name)) continue;
672
-
673
- const fullPath = path.join(currentDir, entry.name);
674
- if (entry.isDirectory()) {
675
- traverse(fullPath);
676
- } else if (entry.isFile() && entry.name.endsWith(".py")) {
677
- results.push(fullPath);
678
- }
679
- }
680
- } catch {}
681
- };
682
-
683
- traverse(dir);
684
- return results;
685
- }
686
654
  }
687
655
 
@@ -1,7 +1,7 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
1
2
  import type Parser from "web-tree-sitter";
2
3
  import { parseWithTreeSitter } from "../wasm-loader.ts";
3
4
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
- import { isIgnoredDirectory } from "../../resources/ignore.ts";
5
5
  import { ImportResolver } from "../../resolver/import-resolver.ts";
6
6
  import * as fs from "node:fs";
7
7
  import * as path from "node:path";
@@ -83,10 +83,10 @@ export class ElysiaSemanticExtractor implements SemanticSliceExtractor {
83
83
  public async extractSlices(
84
84
  projectRoot: string,
85
85
  domainId?: number,
86
- signal?: AbortSignal
86
+ signal?: AbortSignal, inventory?: SourceInventory
87
87
  ): Promise<VerticalSliceCandidate[]> {
88
88
  const slices: VerticalSliceCandidate[] = [];
89
- const sourceFiles = this.findSourceFiles(projectRoot);
89
+ const sourceFiles = listSourceFiles(projectRoot, /\.(?:[cm]?[jt]sx?)$/, inventory).filter(file => !file.endsWith('.d.ts'));
90
90
  const resolver = new ImportResolver(projectRoot);
91
91
 
92
92
  const allRoutes: ExtractedRoute[] = [];
@@ -513,26 +513,5 @@ export class ElysiaSemanticExtractor implements SemanticSliceExtractor {
513
513
 
514
514
  return prefixesByRouter;
515
515
  }
516
-
517
- private findSourceFiles(dir: string): string[] {
518
- const results: string[] = [];
519
- const traverse = (current: string) => {
520
- if (!fs.existsSync(current)) return;
521
- try {
522
- const entries = fs.readdirSync(current, { withFileTypes: true });
523
- for (const entry of entries) {
524
- if (isIgnoredDirectory(entry.name)) continue;
525
- const full = path.join(current, entry.name);
526
- if (entry.isDirectory()) {
527
- traverse(full);
528
- } else if (entry.isFile() && /\.(ts|js|tsx|jsx)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
529
- results.push(full);
530
- }
531
- }
532
- } catch {}
533
- };
534
- traverse(dir);
535
- return results;
536
- }
537
516
  }
538
517
 
@@ -1,3 +1,4 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
1
2
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
2
3
  import { parseWithTreeSitter } from "../wasm-loader.ts";
3
4
  import { ImportResolver } from "../../resolver/import-resolver.ts";
@@ -84,10 +85,10 @@ export class ExpressSemanticExtractor implements SemanticSliceExtractor {
84
85
  public async extractSlices(
85
86
  projectRoot: string,
86
87
  domainId?: number,
87
- signal?: AbortSignal
88
+ signal?: AbortSignal, inventory?: SourceInventory
88
89
  ): Promise<VerticalSliceCandidate[]> {
89
90
  const slices: VerticalSliceCandidate[] = [];
90
- const sourceFiles = this.findSourceFiles(projectRoot);
91
+ const sourceFiles = listSourceFiles(projectRoot, /\.(?:[cm]?[jt]sx?)$/, inventory).filter(file => !file.endsWith('.d.ts'));
91
92
  const resolver = new ImportResolver(projectRoot);
92
93
 
93
94
  const allRoutes: RawRoute[] = [];
@@ -424,21 +425,5 @@ export class ExpressSemanticExtractor implements SemanticSliceExtractor {
424
425
  }
425
426
  return result;
426
427
  }
427
-
428
- private findSourceFiles(dir: string): string[] {
429
- const results: string[] = [];
430
- try {
431
- const entries = fs.readdirSync(dir, { withFileTypes: true });
432
- for (const entry of entries) {
433
- const full = path.join(dir, entry.name);
434
- if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules" && entry.name !== "dist") {
435
- results.push(...this.findSourceFiles(full));
436
- } else if (entry.isFile() && /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
437
- results.push(full);
438
- }
439
- }
440
- } catch {}
441
- return results;
442
- }
443
428
  }
444
429
 
@@ -1,7 +1,8 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
+ import { readPythonStaticString as cleanLiteral } from "../static-string.ts";
1
3
  import type Parser from "web-tree-sitter";
2
4
  import { parseSourceWithTreeSitter } from "../wasm-loader.ts";
3
5
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
4
- import { isIgnoredDirectory } from "../../resources/ignore.ts";
5
6
  import { ImportResolver } from "../../resolver/import-resolver.ts";
6
7
  import * as fs from "node:fs";
7
8
  import * as path from "node:path";
@@ -30,7 +31,7 @@ interface ExtractedInclusion {
30
31
  relPath: string;
31
32
  parentVar: string;
32
33
  targetExpr: string;
33
- prefix: string;
34
+ prefix: string | undefined;
34
35
  line: number;
35
36
  }
36
37
 
@@ -39,16 +40,6 @@ interface ImportBinding {
39
40
  symbol?: string;
40
41
  }
41
42
 
42
- function cleanLiteral(node: Parser.SyntaxNode | null | undefined): string | undefined {
43
- if (!node) return undefined;
44
- if (node.type === "string") {
45
- const raw = node.text.trim();
46
- const match = raw.match(/^[rRbBuU]*('''|"""|'|")([\s\S]*?)\1$/);
47
- if (match) return match[2];
48
- return raw.replace(/^[rRbBuU]*['"]|['"]$/g, "");
49
- }
50
- return undefined;
51
- }
52
43
 
53
44
  function normalizeRouteUri(prefix: string, rawPath: string): string {
54
45
  const p = (prefix ?? "").trim().replace(/\/+$/, "");
@@ -122,16 +113,16 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
122
113
  return false;
123
114
  }
124
115
 
125
- public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal): Promise<VerticalSliceCandidate[]> {
116
+ public async extractSlices(projectRoot: string, domainId?: number, signal?: AbortSignal, inventory?: SourceInventory): Promise<VerticalSliceCandidate[]> {
126
117
  const slices: VerticalSliceCandidate[] = [];
127
- const pyFiles = this.findPythonFiles(projectRoot);
118
+ const pyFiles = listSourceFiles(projectRoot, /\.py$/, inventory);
128
119
  const resolver = new ImportResolver(projectRoot);
129
120
 
130
121
  const allRoutes: ExtractedRoute[] = [];
131
122
  const allInclusions: ExtractedInclusion[] = [];
132
123
  const localRouters = new Map<
133
124
  string,
134
- { prefix: string; isApp: boolean; guards?: string[]; dependencies?: string[] }
125
+ { prefix: string | undefined; isApp: boolean; guards?: string[]; dependencies?: string[] }
135
126
  >();
136
127
  const fileImports = new Map<string, Map<string, ImportBinding>>();
137
128
 
@@ -201,7 +192,7 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
201
192
  const keyword = args.find(
202
193
  (child) => child.type === "keyword_argument" && child.childForFieldName("name")?.text === "prefix"
203
194
  );
204
- const prefix = cleanLiteral(keyword?.childForFieldName("value")) ?? "";
195
+ const prefix = keyword ? cleanLiteral(keyword.childForFieldName("value")) : "";
205
196
 
206
197
  // Router-level dependencies: router = APIRouter(dependencies=[Depends(...)])
207
198
  const depsKw = args.find(
@@ -219,7 +210,7 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
219
210
  }
220
211
 
221
212
  localRouters.set(`${relPath}#${leftName}`, {
222
- prefix: prefix.replace(/\/+$/, ""),
213
+ prefix: prefix?.replace(/\/+$/, ""),
223
214
  isApp,
224
215
  guards: routerGuards,
225
216
  dependencies: routerDeps,
@@ -240,13 +231,13 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
240
231
  const prefixKw = args.find(
241
232
  (c) => c.type === "keyword_argument" && c.childForFieldName("name")?.text === "prefix"
242
233
  );
243
- const incPrefix = cleanLiteral(prefixKw?.childForFieldName("value")) ?? "";
234
+ const incPrefix = prefixKw ? cleanLiteral(prefixKw.childForFieldName("value")) : "";
244
235
  allInclusions.push({
245
236
  file,
246
237
  relPath,
247
238
  parentVar,
248
239
  targetExpr,
249
- prefix: incPrefix.replace(/\/+$/, ""),
240
+ prefix: incPrefix?.replace(/\/+$/, ""),
250
241
  line: node.startPosition.row + 1,
251
242
  });
252
243
  });
@@ -394,9 +385,9 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
394
385
  }
395
386
 
396
387
  // 5. Build Inclusion Graph and Resolve Cross-File Router Targets
397
- // Adjacency: parentKey -> Array<{ childKey: string; prefix: string }>
398
- const routerChildren = new Map<string, Array<{ childKey: string; prefix: string }>>();
399
- const incomingInclusions = new Map<string, Array<{ parentKey: string; prefix: string }>>();
388
+ // Adjacency: parentKey -> Array<{ childKey: string; prefix: string | undefined }>
389
+ const routerChildren = new Map<string, Array<{ childKey: string; prefix: string | undefined }>>();
390
+ const incomingInclusions = new Map<string, Array<{ parentKey: string; prefix: string | undefined }>>();
400
391
 
401
392
  for (const inc of allInclusions) {
402
393
  const parentKey = `${inc.relPath}#${inc.parentVar}`;
@@ -465,8 +456,8 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
465
456
  for (const routerKey of allRouterKeys) {
466
457
  const incoming = incomingInclusions.get(routerKey);
467
458
  if (!incoming || incoming.length === 0) {
468
- const local = localRouters.get(routerKey)?.prefix ?? "";
469
- effectivePrefixesByRouter.set(routerKey, [local]);
459
+ const local = localRouters.get(routerKey);
460
+ effectivePrefixesByRouter.set(routerKey, local && local.prefix === undefined ? [] : [local?.prefix ?? ""]);
470
461
  }
471
462
  }
472
463
 
@@ -484,8 +475,9 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
484
475
  if (visitedEdges.has(edgeKey)) continue;
485
476
  visitedEdges.add(edgeKey);
486
477
 
487
- const childLocal = localRouters.get(child.childKey)?.prefix ?? "";
488
- const nextPrefixes = currentPrefixes.map((p) => {
478
+ const childMeta = localRouters.get(child.childKey);
479
+ const childLocal = childMeta?.prefix ?? "";
480
+ const nextPrefixes = child.prefix === undefined || childMeta && childMeta.prefix === undefined ? [] : currentPrefixes.map((p) => {
489
481
  const combined = `${p ? (p.startsWith("/") ? p : `/${p}`) : ""}${child.prefix ? (child.prefix.startsWith("/") ? child.prefix : `/${child.prefix}`) : ""}${childLocal ? (childLocal.startsWith("/") ? childLocal : `/${childLocal}`) : ""}`;
490
482
  return combined.replace(/\/+/g, "/").replace(/\/+$/, "");
491
483
  });
@@ -500,10 +492,7 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
500
492
  // 7. Generate Vertical Slices
501
493
  for (const route of allRoutes) {
502
494
  const routerKey = `${route.relPath}#${route.routerVar}`;
503
- let prefixes = effectivePrefixesByRouter.get(routerKey);
504
- if (!prefixes || prefixes.length === 0) {
505
- prefixes = [localRouters.get(routerKey)?.prefix ?? ""];
506
- }
495
+ const prefixes = effectivePrefixesByRouter.get(routerKey) ?? [];
507
496
 
508
497
  for (const prefix of prefixes) {
509
498
  const fullUri = normalizeRouteUri(prefix, route.rawPath);
@@ -709,28 +698,5 @@ export class FastApiSemanticExtractor implements SemanticSliceExtractor {
709
698
 
710
699
  return slices;
711
700
  }
712
-
713
- private findPythonFiles(dir: string): string[] {
714
- const results: string[] = [];
715
- const traverse = (currentDir: string) => {
716
- if (!fs.existsSync(currentDir)) return;
717
- try {
718
- const entries = fs.readdirSync(currentDir, { withFileTypes: true });
719
- for (const entry of entries) {
720
- if (isIgnoredDirectory(entry.name)) continue;
721
-
722
- const fullPath = path.join(currentDir, entry.name);
723
- if (entry.isDirectory()) {
724
- traverse(fullPath);
725
- } else if (entry.isFile() && entry.name.endsWith(".py")) {
726
- results.push(fullPath);
727
- }
728
- }
729
- } catch {}
730
- };
731
-
732
- traverse(dir);
733
- return results;
734
- }
735
701
  }
736
702
 
@@ -1,3 +1,4 @@
1
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
1
2
  import { readOptionalSourceFile } from "../../resources/source-files.ts";
2
3
  import { parseWithTreeSitter } from "../wasm-loader.ts";
3
4
  import { ImportResolver } from "../../resolver/import-resolver.ts";
@@ -88,10 +89,10 @@ export class FastifySemanticExtractor implements SemanticSliceExtractor {
88
89
  public async extractSlices(
89
90
  projectRoot: string,
90
91
  domainId?: number,
91
- signal?: AbortSignal
92
+ signal?: AbortSignal, inventory?: SourceInventory
92
93
  ): Promise<VerticalSliceCandidate[]> {
93
94
  const slices: VerticalSliceCandidate[] = [];
94
- const sourceFiles = this.findSourceFiles(projectRoot);
95
+ const sourceFiles = listSourceFiles(projectRoot, /\.(?:[cm]?[jt]sx?)$/, inventory).filter(file => !file.endsWith('.d.ts'));
95
96
  const resolver = new ImportResolver(projectRoot);
96
97
 
97
98
  const allRoutes: RawFastifyRoute[] = [];
@@ -754,21 +755,5 @@ export class FastifySemanticExtractor implements SemanticSliceExtractor {
754
755
  }
755
756
  return result;
756
757
  }
757
-
758
- private findSourceFiles(dir: string): string[] {
759
- const results: string[] = [];
760
- try {
761
- const entries = fs.readdirSync(dir, { withFileTypes: true });
762
- for (const entry of entries) {
763
- const full = path.join(dir, entry.name);
764
- if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules" && entry.name !== "dist") {
765
- results.push(...this.findSourceFiles(full));
766
- } else if (entry.isFile() && /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
767
- results.push(full);
768
- }
769
- }
770
- } catch {}
771
- return results;
772
- }
773
758
  }
774
759