septum 0.1.3 → 0.1.4

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 (35) hide show
  1. package/README.md +5 -2
  2. package/package.json +1 -1
  3. package/src/cli/commands/slice.ts +4 -46
  4. package/src/cli/commands/topology.ts +119 -0
  5. package/src/cli/index.ts +11 -0
  6. package/src/core/database/repositories/environment.repository.ts +207 -0
  7. package/src/core/database/repositories/symbol.repository.ts +28 -9
  8. package/src/core/database/repository.ts +6 -1
  9. package/src/core/database/schema.ts +153 -120
  10. package/src/core/parser/behavioral-analyzer.ts +119 -0
  11. package/src/core/parser/boundary-tracker.ts +160 -0
  12. package/src/core/parser/extractors/base.ts +1 -0
  13. package/src/core/parser/extractors/blade.ts +158 -158
  14. package/src/core/parser/extractors/go.ts +5 -1
  15. package/src/core/parser/extractors/laravel-semantic.ts +320 -4
  16. package/src/core/parser/extractors/php.ts +5 -1
  17. package/src/core/parser/extractors/python.ts +3 -1
  18. package/src/core/parser/extractors/typescript.ts +5 -1
  19. package/src/core/parser/schema/providers/laravel-migration-provider.ts +215 -0
  20. package/src/core/parser/schema/providers/prisma-schema-provider.ts +89 -0
  21. package/src/core/parser/schema/schema-provider-registry.ts +43 -0
  22. package/src/core/parser/schema/schema-provider.interface.ts +33 -0
  23. package/src/core/resolver/path-resolver.ts +147 -147
  24. package/src/core/resolver/vertical-slice-tracer.ts +34 -1
  25. package/src/core/topology/environment-detector.ts +860 -0
  26. package/src/core/topology/types.ts +83 -0
  27. package/src/index.ts +3 -0
  28. package/src/mcp/schemas.ts +48 -0
  29. package/src/mcp/server.ts +62 -2
  30. package/src/mcp/tools/get-environment-topology.ts +141 -0
  31. package/src/mcp/tools/get-symbol-hotspots.ts +13 -3
  32. package/src/mcp/tools/register-domain.ts +1 -1
  33. package/src/mcp/tools/trace-vertical-slice.ts +9 -64
  34. package/src/types/index.ts +16 -0
  35. package/src/version.ts +3 -3
@@ -1,120 +1,153 @@
1
- import type { Database } from "bun:sqlite";
2
-
3
- export const CURRENT_SCHEMA_VERSION = 2;
4
-
5
- export const TABLE_STATEMENTS = [
6
- `CREATE TABLE IF NOT EXISTS domains (
7
- id INTEGER PRIMARY KEY AUTOINCREMENT,
8
- name TEXT NOT NULL UNIQUE,
9
- root_path TEXT NOT NULL,
10
- allowed_deps_json TEXT NOT NULL DEFAULT '[]',
11
- forbidden_deps_json TEXT NOT NULL DEFAULT '[]',
12
- archetypes_json TEXT NOT NULL DEFAULT '{}',
13
- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
14
- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
15
- );`,
16
-
17
- `CREATE TABLE IF NOT EXISTS files (
18
- id INTEGER PRIMARY KEY AUTOINCREMENT,
19
- domain_id INTEGER NOT NULL,
20
- path TEXT NOT NULL UNIQUE,
21
- archetype TEXT NOT NULL DEFAULT 'unknown',
22
- content_hash TEXT NOT NULL,
23
- line_count INTEGER NOT NULL DEFAULT 0,
24
- mtime_ms INTEGER NOT NULL DEFAULT 0,
25
- size_bytes INTEGER NOT NULL DEFAULT 0,
26
- last_scanned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
27
- FOREIGN KEY (domain_id) REFERENCES domains(id) ON DELETE CASCADE
28
- );`,
29
-
30
- `CREATE TABLE IF NOT EXISTS symbols (
31
- id INTEGER PRIMARY KEY AUTOINCREMENT,
32
- file_id INTEGER NOT NULL,
33
- name TEXT NOT NULL,
34
- kind TEXT NOT NULL,
35
- signature TEXT NOT NULL,
36
- visibility TEXT NOT NULL DEFAULT 'public',
37
- line_start INTEGER NOT NULL DEFAULT 0,
38
- line_end INTEGER NOT NULL DEFAULT 0,
39
- line_count INTEGER NOT NULL DEFAULT 1,
40
- FOREIGN KEY (file_id) REFERENCES files(id) ON DELETE CASCADE
41
- );`,
42
-
43
- `CREATE TABLE IF NOT EXISTS dependencies (
44
- id INTEGER PRIMARY KEY AUTOINCREMENT,
45
- source_file_id INTEGER NOT NULL,
46
- target_symbol_or_path TEXT NOT NULL,
47
- import_statement TEXT NOT NULL,
48
- line_number INTEGER NOT NULL DEFAULT 0,
49
- is_external BOOLEAN NOT NULL DEFAULT 0,
50
- FOREIGN KEY (source_file_id) REFERENCES files(id) ON DELETE CASCADE
51
- );`,
52
-
53
- `CREATE TABLE IF NOT EXISTS vertical_slices (
54
- id INTEGER PRIMARY KEY AUTOINCREMENT,
55
- domain_id INTEGER,
56
- feature_key TEXT,
57
- http_method TEXT NOT NULL,
58
- route_uri TEXT NOT NULL,
59
- route_name TEXT,
60
- controller_class TEXT NOT NULL,
61
- action_name TEXT NOT NULL,
62
- controller_file TEXT,
63
- controller_line INTEGER DEFAULT 0,
64
- architecture_style TEXT NOT NULL DEFAULT 'clean',
65
- entry_kind TEXT NOT NULL DEFAULT 'http_route',
66
- execution_chain_json TEXT NOT NULL,
67
- created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
68
- FOREIGN KEY (domain_id) REFERENCES domains(id) ON DELETE CASCADE
69
- );`,
70
-
71
- `CREATE TABLE IF NOT EXISTS repo_meta (
72
- key TEXT PRIMARY KEY,
73
- value TEXT NOT NULL,
74
- updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
75
- );`,
76
- ];
77
-
78
- export const INDEX_STATEMENTS = [
79
- "CREATE INDEX IF NOT EXISTS idx_domains_name ON domains(name);",
80
- "CREATE INDEX IF NOT EXISTS idx_files_domain_id ON files(domain_id);",
81
- "CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);",
82
- "CREATE INDEX IF NOT EXISTS idx_symbols_file_id ON symbols(file_id);",
83
- "CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);",
84
- "CREATE INDEX IF NOT EXISTS idx_symbols_kind ON symbols(kind);",
85
- "CREATE INDEX IF NOT EXISTS idx_symbols_line_count ON symbols(kind, line_count DESC);",
86
- "CREATE INDEX IF NOT EXISTS idx_dependencies_source ON dependencies(source_file_id);",
87
- "CREATE INDEX IF NOT EXISTS idx_dependencies_target ON dependencies(target_symbol_or_path);",
88
- "CREATE INDEX IF NOT EXISTS idx_slices_route_uri ON vertical_slices(route_uri);",
89
- "CREATE INDEX IF NOT EXISTS idx_slices_route_name ON vertical_slices(route_name);",
90
- "CREATE INDEX IF NOT EXISTS idx_slices_controller ON vertical_slices(controller_class, action_name);",
91
- ];
92
-
93
- const DROP_ALL_TABLES = `
94
- DROP TABLE IF EXISTS repo_meta;
95
- DROP TABLE IF EXISTS vertical_slices;
96
- DROP TABLE IF EXISTS dependencies;
97
- DROP TABLE IF EXISTS symbols;
98
- DROP TABLE IF EXISTS files;
99
- DROP TABLE IF EXISTS domains;
100
- `;
101
-
102
- export function initializeDatabaseSchema(db: Database): void {
103
- const versionRow = db.query<{ user_version: number }, []>("PRAGMA user_version;").get();
104
- const userVersion = versionRow?.user_version ?? 0;
105
-
106
- if (userVersion !== 0 && userVersion !== CURRENT_SCHEMA_VERSION) {
107
- // Zero-kludge cache invalidation: outdated schema versions are cleanly dropped and recreated
108
- db.run(DROP_ALL_TABLES);
109
- }
110
-
111
- for (const tableSql of TABLE_STATEMENTS) {
112
- db.run(tableSql);
113
- }
114
-
115
- for (const indexSql of INDEX_STATEMENTS) {
116
- db.run(indexSql);
117
- }
118
-
119
- db.run(`PRAGMA user_version = ${CURRENT_SCHEMA_VERSION};`);
120
- }
1
+ import type { Database } from "bun:sqlite";
2
+
3
+ export const CURRENT_SCHEMA_VERSION = 4;
4
+
5
+ export const TABLE_STATEMENTS = [
6
+ `CREATE TABLE IF NOT EXISTS domains (
7
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
8
+ name TEXT NOT NULL UNIQUE,
9
+ root_path TEXT NOT NULL,
10
+ allowed_deps_json TEXT NOT NULL DEFAULT '[]',
11
+ forbidden_deps_json TEXT NOT NULL DEFAULT '[]',
12
+ archetypes_json TEXT NOT NULL DEFAULT '{}',
13
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
14
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
15
+ );`,
16
+
17
+ `CREATE TABLE IF NOT EXISTS files (
18
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
19
+ domain_id INTEGER NOT NULL,
20
+ path TEXT NOT NULL UNIQUE,
21
+ archetype TEXT NOT NULL DEFAULT 'unknown',
22
+ content_hash TEXT NOT NULL,
23
+ line_count INTEGER NOT NULL DEFAULT 0,
24
+ mtime_ms INTEGER NOT NULL DEFAULT 0,
25
+ size_bytes INTEGER NOT NULL DEFAULT 0,
26
+ last_scanned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
27
+ FOREIGN KEY (domain_id) REFERENCES domains(id) ON DELETE CASCADE
28
+ );`,
29
+
30
+ `CREATE TABLE IF NOT EXISTS symbols (
31
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
32
+ file_id INTEGER NOT NULL,
33
+ name TEXT NOT NULL,
34
+ kind TEXT NOT NULL,
35
+ signature TEXT NOT NULL,
36
+ visibility TEXT NOT NULL DEFAULT 'public',
37
+ line_start INTEGER NOT NULL DEFAULT 0,
38
+ line_end INTEGER NOT NULL DEFAULT 0,
39
+ line_count INTEGER NOT NULL DEFAULT 1,
40
+ nesting_depth INTEGER NOT NULL DEFAULT 1,
41
+ FOREIGN KEY (file_id) REFERENCES files(id) ON DELETE CASCADE
42
+ );`,
43
+
44
+ `CREATE TABLE IF NOT EXISTS dependencies (
45
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
46
+ source_file_id INTEGER NOT NULL,
47
+ target_symbol_or_path TEXT NOT NULL,
48
+ import_statement TEXT NOT NULL,
49
+ line_number INTEGER NOT NULL DEFAULT 0,
50
+ is_external BOOLEAN NOT NULL DEFAULT 0,
51
+ FOREIGN KEY (source_file_id) REFERENCES files(id) ON DELETE CASCADE
52
+ );`,
53
+
54
+ `CREATE TABLE IF NOT EXISTS vertical_slices (
55
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
56
+ domain_id INTEGER,
57
+ feature_key TEXT,
58
+ http_method TEXT NOT NULL,
59
+ route_uri TEXT NOT NULL,
60
+ route_name TEXT,
61
+ controller_class TEXT NOT NULL,
62
+ action_name TEXT NOT NULL,
63
+ controller_file TEXT,
64
+ controller_line INTEGER DEFAULT 0,
65
+ architecture_style TEXT NOT NULL DEFAULT 'clean',
66
+ entry_kind TEXT NOT NULL DEFAULT 'http_route',
67
+ execution_chain_json TEXT NOT NULL,
68
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
69
+ FOREIGN KEY (domain_id) REFERENCES domains(id) ON DELETE CASCADE
70
+ );`,
71
+
72
+ `CREATE TABLE IF NOT EXISTS repo_meta (
73
+ key TEXT PRIMARY KEY,
74
+ value TEXT NOT NULL,
75
+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
76
+ );`,
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
+ ];
104
+
105
+ export const INDEX_STATEMENTS = [
106
+ "CREATE INDEX IF NOT EXISTS idx_domains_name ON domains(name);",
107
+ "CREATE INDEX IF NOT EXISTS idx_files_domain_id ON files(domain_id);",
108
+ "CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);",
109
+ "CREATE INDEX IF NOT EXISTS idx_symbols_file_id ON symbols(file_id);",
110
+ "CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);",
111
+ "CREATE INDEX IF NOT EXISTS idx_symbols_kind ON symbols(kind);",
112
+ "CREATE INDEX IF NOT EXISTS idx_symbols_line_count ON symbols(kind, line_count DESC);",
113
+ "CREATE INDEX IF NOT EXISTS idx_symbols_nesting_depth ON symbols(nesting_depth DESC);",
114
+ "CREATE INDEX IF NOT EXISTS idx_dependencies_source ON dependencies(source_file_id);",
115
+ "CREATE INDEX IF NOT EXISTS idx_dependencies_target ON dependencies(target_symbol_or_path);",
116
+ "CREATE INDEX IF NOT EXISTS idx_slices_route_uri ON vertical_slices(route_uri);",
117
+ "CREATE INDEX IF NOT EXISTS idx_slices_route_name ON vertical_slices(route_name);",
118
+ "CREATE INDEX IF NOT EXISTS idx_slices_controller ON vertical_slices(controller_class, action_name);",
119
+ "CREATE INDEX IF NOT EXISTS idx_env_topology_status ON environment_topology(status);",
120
+ "CREATE INDEX IF NOT EXISTS idx_env_nodes_layer ON environment_nodes(layer);",
121
+ "CREATE INDEX IF NOT EXISTS idx_env_nodes_status ON environment_nodes(status);",
122
+ ];
123
+
124
+ const DROP_ALL_TABLES = `
125
+ DROP TABLE IF EXISTS environment_nodes;
126
+ DROP TABLE IF EXISTS environment_topology;
127
+ DROP TABLE IF EXISTS repo_meta;
128
+ DROP TABLE IF EXISTS vertical_slices;
129
+ DROP TABLE IF EXISTS dependencies;
130
+ DROP TABLE IF EXISTS symbols;
131
+ DROP TABLE IF EXISTS files;
132
+ DROP TABLE IF EXISTS domains;
133
+ `;
134
+
135
+ export function initializeDatabaseSchema(db: Database): void {
136
+ const versionRow = db.query<{ user_version: number }, []>("PRAGMA user_version;").get();
137
+ const userVersion = versionRow?.user_version ?? 0;
138
+
139
+ if (userVersion !== 0 && userVersion !== CURRENT_SCHEMA_VERSION) {
140
+ // Zero-kludge cache invalidation: outdated schema versions are cleanly dropped and recreated
141
+ db.run(DROP_ALL_TABLES);
142
+ }
143
+
144
+ for (const tableSql of TABLE_STATEMENTS) {
145
+ db.run(tableSql);
146
+ }
147
+
148
+ for (const indexSql of INDEX_STATEMENTS) {
149
+ db.run(indexSql);
150
+ }
151
+
152
+ db.run(`PRAGMA user_version = ${CURRENT_SCHEMA_VERSION};`);
153
+ }
@@ -0,0 +1,119 @@
1
+ export interface MethodBehavioralSummary {
2
+ guards: string[];
3
+ hasTransaction: boolean;
4
+ emittedEvents: string[];
5
+ dispatchedJobs: string[];
6
+ mutations: string[];
7
+ }
8
+
9
+ export class BehavioralAnalyzer {
10
+ /**
11
+ * Analyzes the body of a method or function to extract semantic side-effects,
12
+ * authorization guards, database transactions, emitted events, and background job dispatches.
13
+ */
14
+ public static analyzeMethod(code: string): MethodBehavioralSummary {
15
+ const guards = new Set<string>();
16
+ let hasTransaction = false;
17
+ const emittedEvents = new Set<string>();
18
+ const dispatchedJobs = new Set<string>();
19
+ const mutations = new Set<string>();
20
+
21
+ const lines = code.split("\n");
22
+
23
+ for (const rawLine of lines) {
24
+ const line = rawLine.trim();
25
+ if (!line || line.startsWith("//") || line.startsWith("#")) continue;
26
+
27
+ // 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
+ ) {
34
+ hasTransaction = true;
35
+ }
36
+
37
+ // 2. Authorization Guards
38
+ // Laravel: $this->authorize('update', $order); or Gate::authorize(...)
39
+ const authMatch = line.match(/(?:\$this->authorize|Gate::authorize)\s*\(\s*['"]([^'"]+)['"]/);
40
+ if (authMatch) {
41
+ guards.add(authMatch[1]);
42
+ }
43
+ // Laravel: abort_if(!..., 403, '...');
44
+ if (line.includes("abort_if(") || line.includes("abort_unless(")) {
45
+ guards.add("abort_guard");
46
+ }
47
+ // TS / NestJS: @UseGuards(AuthGuard, RolesGuard)
48
+ const guardDecoratorMatch = line.match(/@UseGuards\s*\(([^)]+)\)/);
49
+ if (guardDecoratorMatch) {
50
+ const guardNames = guardDecoratorMatch[1].split(",").map((g) => g.trim());
51
+ for (const g of guardNames) guards.add(g);
52
+ }
53
+
54
+ // 3. Emitted Events
55
+ // Laravel: event(new OrderPlaced($order));
56
+ const eventNewMatch = line.match(/event\s*\(\s*new\s+([A-Za-z0-9_]+)/);
57
+ if (eventNewMatch) {
58
+ emittedEvents.add(eventNewMatch[1]);
59
+ }
60
+ // 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_]+)/);
62
+ if (eventDispatchMatch) {
63
+ emittedEvents.add(eventDispatchMatch[1]);
64
+ }
65
+ // Laravel: broadcast(new OrderUpdated($order));
66
+ const broadcastMatch = line.match(/broadcast\s*\(\s*new\s+([A-Za-z0-9_]+)/);
67
+ if (broadcastMatch) {
68
+ emittedEvents.add(broadcastMatch[1]);
69
+ }
70
+ // EventEmitter: this.eventEmitter.emit('order.created', ...)
71
+ const nodeEmitMatch = line.match(/(?:eventEmitter|\$emit)\.emit\s*\(\s*['"]([^'"]+)['"]/);
72
+ if (nodeEmitMatch) {
73
+ emittedEvents.add(nodeEmitMatch[1]);
74
+ }
75
+
76
+ // 4. Dispatched Background Jobs
77
+ // 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/);
79
+ if (jobDispatchStaticMatch) {
80
+ dispatchedJobs.add(jobDispatchStaticMatch[1]);
81
+ }
82
+ // Laravel: dispatch(new ProcessPayment($order));
83
+ const dispatchNewMatch = line.match(/dispatch\s*\(\s*new\s+([A-Za-z0-9_]+)/);
84
+ if (dispatchNewMatch) {
85
+ dispatchedJobs.add(dispatchNewMatch[1]);
86
+ }
87
+ // BullMQ / Queue: queue.add('process-payment', ...)
88
+ const queueAddMatch = line.match(/(?:queue|queueService)\.add\s*\(\s*['"]([^'"]+)['"]/);
89
+ if (queueAddMatch) {
90
+ dispatchedJobs.add(queueAddMatch[1]);
91
+ }
92
+
93
+ // 5. Model Mutations
94
+ // Laravel / ORM: $order->update([...]);
95
+ const updateMatch = line.match(/\$([a-zA-Z0-9_]+)->update\s*\(/);
96
+ if (updateMatch) {
97
+ mutations.add(`${updateMatch[1]}.update()`);
98
+ }
99
+ // Laravel / ORM: $order->delete();
100
+ const deleteMatch = line.match(/\$([a-zA-Z0-9_]+)->delete\s*\(/);
101
+ if (deleteMatch) {
102
+ mutations.add(`${deleteMatch[1]}.delete()`);
103
+ }
104
+ // Direct property assignment: $order->status = 'completed';
105
+ const assignMatch = line.match(/\$([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*=\s*([^;]+);/);
106
+ if (assignMatch && !["this", "request"].includes(assignMatch[1])) {
107
+ mutations.add(`${assignMatch[1]}.${assignMatch[2]}`);
108
+ }
109
+ }
110
+
111
+ return {
112
+ guards: Array.from(guards),
113
+ hasTransaction,
114
+ emittedEvents: Array.from(emittedEvents),
115
+ dispatchedJobs: Array.from(dispatchedJobs),
116
+ mutations: Array.from(mutations),
117
+ };
118
+ }
119
+ }
@@ -126,3 +126,163 @@ export function findPythonBlockEnd(lines: string[], startLineIndex: number): num
126
126
 
127
127
  return lastContentLine;
128
128
  }
129
+
130
+ /**
131
+ * Calculates the maximum control flow nesting depth within a code block (PHP, TS, JS, Go).
132
+ * Base depth is 1 (the function body itself).
133
+ * Nested control structures (if, else if, for, foreach, while, do, switch, try, catch)
134
+ * that open a block increase the active depth.
135
+ */
136
+ export function calculateControlFlowNesting(
137
+ lines: string[],
138
+ startLineIndex: number,
139
+ endLineIndex: number
140
+ ): number {
141
+ if (startLineIndex >= endLineIndex) return 1;
142
+
143
+ let maxDepth = 1;
144
+ let currentDepth = 1;
145
+ let inMultiLineComment = false;
146
+ let insideBody = false;
147
+
148
+ const controlStack: number[] = [];
149
+ let braceDepth = 0;
150
+ let pendingControl = false;
151
+
152
+ const controlRegex = /\b(if|else\s+if|else|for|foreach|while|do|switch|try|catch)\b/;
153
+
154
+ const startIdx = Math.max(0, startLineIndex);
155
+ const endIdx = Math.min(lines.length - 1, endLineIndex);
156
+
157
+ for (let i = startIdx; i <= endIdx; i++) {
158
+ const rawLine = lines[i];
159
+
160
+ let cleanLine = "";
161
+ let inSingleQuote = false;
162
+ let inDoubleQuote = false;
163
+ let inTemplateString = false;
164
+
165
+ for (let j = 0; j < rawLine.length; j++) {
166
+ const char = rawLine[j];
167
+ const prevChar = j > 0 ? rawLine[j - 1] : "";
168
+ const nextChar = j + 1 < rawLine.length ? rawLine[j + 1] : "";
169
+
170
+ if (inMultiLineComment) {
171
+ if (char === "*" && nextChar === "/") {
172
+ inMultiLineComment = false;
173
+ j++;
174
+ }
175
+ continue;
176
+ }
177
+
178
+ if (!inSingleQuote && !inDoubleQuote && !inTemplateString && char === "/" && nextChar === "*") {
179
+ inMultiLineComment = true;
180
+ j++;
181
+ continue;
182
+ }
183
+
184
+ if (!inSingleQuote && !inDoubleQuote && !inTemplateString && char === "/" && nextChar === "/") {
185
+ break; // Single line comment: ignore rest of line
186
+ }
187
+
188
+ if (char === "'" && !inDoubleQuote && !inTemplateString && prevChar !== "\\") {
189
+ inSingleQuote = !inSingleQuote;
190
+ continue;
191
+ }
192
+ if (char === '"' && !inSingleQuote && !inTemplateString && prevChar !== "\\") {
193
+ inDoubleQuote = !inDoubleQuote;
194
+ continue;
195
+ }
196
+ if (char === "`" && !inSingleQuote && !inDoubleQuote && prevChar !== "\\") {
197
+ inTemplateString = !inTemplateString;
198
+ continue;
199
+ }
200
+
201
+ if (inSingleQuote || inDoubleQuote || inTemplateString) {
202
+ continue;
203
+ }
204
+
205
+ cleanLine += char;
206
+ }
207
+
208
+ const trimmedClean = cleanLine.trim();
209
+ if (!trimmedClean) continue;
210
+
211
+ if (insideBody && controlRegex.test(trimmedClean)) {
212
+ pendingControl = true;
213
+ }
214
+
215
+ for (let j = 0; j < cleanLine.length; j++) {
216
+ const char = cleanLine[j];
217
+ if (char === "{") {
218
+ braceDepth++;
219
+ if (!insideBody) {
220
+ insideBody = true;
221
+ } else if (pendingControl) {
222
+ currentDepth++;
223
+ controlStack.push(braceDepth);
224
+ if (currentDepth > maxDepth) {
225
+ maxDepth = currentDepth;
226
+ }
227
+ pendingControl = false;
228
+ }
229
+ } else if (char === "}") {
230
+ if (controlStack.length > 0 && controlStack[controlStack.length - 1] === braceDepth) {
231
+ controlStack.pop();
232
+ currentDepth = Math.max(1, currentDepth - 1);
233
+ }
234
+ braceDepth = Math.max(0, braceDepth - 1);
235
+ }
236
+ }
237
+
238
+ if (trimmedClean.endsWith(";")) {
239
+ pendingControl = false;
240
+ }
241
+ }
242
+
243
+ return maxDepth;
244
+ }
245
+
246
+ /**
247
+ * Calculates the maximum control flow nesting depth in indentation-based languages (Python).
248
+ */
249
+ export function calculatePythonNesting(
250
+ lines: string[],
251
+ startLineIndex: number,
252
+ endLineIndex: number
253
+ ): number {
254
+ if (startLineIndex >= endLineIndex) return 1;
255
+
256
+ const startLine = lines[startLineIndex];
257
+ const baseIndentMatch = startLine.match(/^(\s*)/);
258
+ const baseIndent = baseIndentMatch ? baseIndentMatch[1].length : 0;
259
+
260
+ const controlRegex = /^\s*(if|elif|else|for|while|try|except|finally|match|case)\b/;
261
+ const indentStack: number[] = [baseIndent];
262
+ let maxDepth = 1;
263
+
264
+ const startIdx = Math.max(0, startLineIndex + 1);
265
+ const endIdx = Math.min(lines.length - 1, endLineIndex);
266
+
267
+ for (let i = startIdx; i <= endIdx; i++) {
268
+ const line = lines[i];
269
+ const trimmed = line.trim();
270
+ if (!trimmed || trimmed.startsWith("#")) continue;
271
+
272
+ const currentIndentMatch = line.match(/^(\s*)/);
273
+ const currentIndent = currentIndentMatch ? currentIndentMatch[1].length : 0;
274
+
275
+ while (indentStack.length > 1 && currentIndent <= indentStack[indentStack.length - 1]) {
276
+ indentStack.pop();
277
+ }
278
+
279
+ if (controlRegex.test(line)) {
280
+ indentStack.push(currentIndent);
281
+ if (indentStack.length > maxDepth) {
282
+ maxDepth = indentStack.length;
283
+ }
284
+ }
285
+ }
286
+
287
+ return maxDepth;
288
+ }
@@ -29,6 +29,7 @@ export function detectArchetype(filePath: string, archetypesMap: Record<string,
29
29
  if (lower.includes("request")) return "request";
30
30
  if (lower.includes("resource")) return "resource";
31
31
  if (lower.includes(".blade.php") || lower.includes("views/") || lower.includes("templates/")) return "view";
32
+ if (lower.includes("route") || lower.includes("router")) return "route";
32
33
  if (lower.includes("util") || lower.includes("helper")) return "util";
33
34
 
34
35
  return "unknown";