@dimassetoid/septum-mcp 0.0.0-stage → 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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/bin/septum.ts +4 -0
  4. package/package.json +70 -4
  5. package/scripts/postinstall.ts +25 -0
  6. package/src/cli/commands/check.ts +133 -0
  7. package/src/cli/commands/hook.ts +205 -0
  8. package/src/cli/commands/init.ts +570 -0
  9. package/src/cli/commands/serve.ts +5 -0
  10. package/src/cli/commands/sync.ts +39 -0
  11. package/src/cli/hook-payload.ts +43 -0
  12. package/src/cli/index.ts +124 -0
  13. package/src/cli/scaffold/harness-config.ts +661 -0
  14. package/src/cli/templates/hooks.ts +110 -0
  15. package/src/cli/templates/rules.ts +35 -0
  16. package/src/cli/templates/skill.ts +55 -0
  17. package/src/cli/ui/prompts.ts +122 -0
  18. package/src/core/boundary/evaluator.ts +426 -0
  19. package/src/core/boundary/staged-auditor.ts +120 -0
  20. package/src/core/config/domain-ownership.ts +45 -0
  21. package/src/core/config/loader.ts +174 -0
  22. package/src/core/config/schema.ts +59 -0
  23. package/src/core/database/client.ts +60 -0
  24. package/src/core/database/repositories/dependency.repository.ts +733 -0
  25. package/src/core/database/repositories/domain.repository.ts +373 -0
  26. package/src/core/database/repositories/file.repository.ts +117 -0
  27. package/src/core/database/repositories/meta.repository.ts +33 -0
  28. package/src/core/database/repositories/symbol.repository.ts +647 -0
  29. package/src/core/database/repository.ts +358 -0
  30. package/src/core/database/schema.ts +123 -0
  31. package/src/core/discovery/navigation.ts +105 -0
  32. package/src/core/discovery/topology-detector.ts +863 -0
  33. package/src/core/ingestion/hasher.ts +5 -0
  34. package/src/core/ingestion/pipeline.ts +590 -0
  35. package/src/core/parser/behavioral-analyzer.ts +123 -0
  36. package/src/core/parser/boundary-tracker.ts +458 -0
  37. package/src/core/parser/extractors/base.ts +71 -0
  38. package/src/core/parser/extractors/blade.ts +159 -0
  39. package/src/core/parser/extractors/csharp.ts +248 -0
  40. package/src/core/parser/extractors/django-semantic.ts +655 -0
  41. package/src/core/parser/extractors/elysia-semantic.ts +517 -0
  42. package/src/core/parser/extractors/express-semantic.ts +429 -0
  43. package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
  44. package/src/core/parser/extractors/fastify-semantic.ts +759 -0
  45. package/src/core/parser/extractors/flask-semantic.ts +482 -0
  46. package/src/core/parser/extractors/frontend.ts +149 -0
  47. package/src/core/parser/extractors/go-semantic.ts +670 -0
  48. package/src/core/parser/extractors/go.ts +491 -0
  49. package/src/core/parser/extractors/hono-semantic.ts +546 -0
  50. package/src/core/parser/extractors/java.ts +227 -0
  51. package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
  52. package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
  53. package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
  54. package/src/core/parser/extractors/php.ts +585 -0
  55. package/src/core/parser/extractors/python.ts +503 -0
  56. package/src/core/parser/extractors/registry.ts +99 -0
  57. package/src/core/parser/extractors/ruby.ts +237 -0
  58. package/src/core/parser/extractors/rust.ts +304 -0
  59. package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
  60. package/src/core/parser/extractors/symfony-semantic.ts +321 -0
  61. package/src/core/parser/extractors/typescript.ts +839 -0
  62. package/src/core/parser/implementation-fingerprint.ts +97 -0
  63. package/src/core/parser/language-capabilities.ts +87 -0
  64. package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
  65. package/src/core/parser/schema/schema-provider-registry.ts +41 -0
  66. package/src/core/parser/schema/schema-provider.interface.ts +34 -0
  67. package/src/core/parser/semantic-revision.ts +3 -0
  68. package/src/core/parser/static-string.ts +51 -0
  69. package/src/core/parser/tree-sitter.ts +63 -0
  70. package/src/core/parser/wasm-assets.ts +25 -0
  71. package/src/core/parser/wasm-loader.ts +274 -0
  72. package/src/core/resolver/call-graph-tracer.ts +1033 -0
  73. package/src/core/resolver/import-resolver.ts +365 -0
  74. package/src/core/resolver/interpretation-inputs.ts +7 -0
  75. package/src/core/resolver/languages/go.ts +103 -0
  76. package/src/core/resolver/languages/managed.ts +200 -0
  77. package/src/core/resolver/languages/python.ts +115 -0
  78. package/src/core/resolver/languages/ruby.ts +40 -0
  79. package/src/core/resolver/languages/rust.ts +127 -0
  80. package/src/core/resolver/languages/shared.ts +71 -0
  81. package/src/core/resolver/module-resolver.ts +486 -0
  82. package/src/core/resolver/path-resolver.ts +200 -0
  83. package/src/core/resolver/slice-catalog.ts +79 -0
  84. package/src/core/resolver/slice-format.ts +9 -0
  85. package/src/core/resolver/symbol-impact.ts +381 -0
  86. package/src/core/resolver/symbol-locator.ts +276 -0
  87. package/src/core/resolver/symbol-reference.ts +53 -0
  88. package/src/core/resolver/vertical-slice-tracer.ts +344 -0
  89. package/src/core/resources/ignore.ts +144 -0
  90. package/src/core/resources/limits.ts +14 -0
  91. package/src/core/resources/source-files.ts +185 -0
  92. package/src/core/resources/source-inventory.ts +55 -0
  93. package/src/core/resources/work-queue.ts +74 -0
  94. package/src/core/retrieval/context-page.ts +109 -0
  95. package/src/core/retrieval/context.ts +320 -0
  96. package/src/core/retrieval/resolution-warnings.ts +21 -0
  97. package/src/core/retrieval/symbol-evidence.ts +97 -0
  98. package/src/core/retrieval/typescript-references.ts +262 -0
  99. package/src/core/telemetry/telemetry.ts +142 -0
  100. package/src/index.ts +18 -0
  101. package/src/mcp/schemas.ts +746 -0
  102. package/src/mcp/server.ts +600 -0
  103. package/src/mcp/tools/boundary.ts +17 -0
  104. package/src/mcp/tools/check-boundary.ts +382 -0
  105. package/src/mcp/tools/get-domain-catalog.ts +39 -0
  106. package/src/mcp/tools/get-symbol-impact.ts +104 -0
  107. package/src/mcp/tools/get-symbol.ts +399 -0
  108. package/src/mcp/tools/locate-symbol.ts +236 -0
  109. package/src/mcp/tools/map.ts +26 -0
  110. package/src/mcp/tools/register-domain.ts +113 -0
  111. package/src/mcp/tools/slice.ts +16 -0
  112. package/src/mcp/tools/symbol.ts +95 -0
  113. package/src/mcp/tools/trace-vertical-slice.ts +106 -0
  114. package/src/mcp/workspace-manager.ts +170 -0
  115. package/src/mcp/workspace-watcher.ts +202 -0
  116. package/src/types/index.ts +438 -0
  117. package/src/types/wasm.d.ts +4 -0
  118. package/src/utils/version-check.ts +209 -0
  119. package/src/version.ts +1 -0
@@ -0,0 +1,123 @@
1
+ import { blankCommentsAndStrings } from "./boundary-tracker.ts";
2
+ export interface MethodBehavioralSummary {
3
+ analysis: "lexical_heuristic";
4
+ guards: string[];
5
+ hasTransaction: boolean;
6
+ emittedEvents: string[];
7
+ dispatchedJobs: string[];
8
+ mutations: string[];
9
+ }
10
+
11
+ export class BehavioralAnalyzer {
12
+ /**
13
+ * Analyzes the body of a method or function to extract semantic side-effects,
14
+ * authorization guards, database transactions, emitted events, and background job dispatches.
15
+ */
16
+ public static analyzeMethod(code: string): MethodBehavioralSummary {
17
+ const guards = new Set<string>();
18
+ let hasTransaction = false;
19
+ const emittedEvents = new Set<string>();
20
+ const dispatchedJobs = new Set<string>();
21
+ const mutations = new Set<string>();
22
+
23
+ const originalLines = code.split("\n");
24
+ const lines = blankCommentsAndStrings(code, { hashComments: true }).split("\n");
25
+
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
+ };
33
+ if (!line || line.startsWith("//") || line.startsWith("#")) continue;
34
+
35
+ // 1. Transaction Boundaries
36
+ if (/(?:\bDB::(?:transaction|beginTransaction)|\bthis\.db\.transaction|\.transaction)\s*\(/.test(line)) {
37
+ hasTransaction = true;
38
+ }
39
+
40
+ // 2. Authorization Guards
41
+ // Laravel: $this->authorize('update', $order); or Gate::authorize(...)
42
+ const authMatch = matchCode(/(?:\$this->authorize|Gate::authorize)\s*\(\s*['"]([^'"]+)['"]/);
43
+ if (authMatch) {
44
+ guards.add(authMatch[1]);
45
+ }
46
+ // Laravel: abort_if(!..., 403, '...');
47
+ if (/\b(?:abort_if|abort_unless)\s*\(/.test(line)) {
48
+ guards.add("abort_guard");
49
+ }
50
+ // TS / NestJS: @UseGuards(AuthGuard, RolesGuard)
51
+ const guardDecoratorMatch = matchCode(/@UseGuards\s*\(([^)]+)\)/);
52
+ if (guardDecoratorMatch) {
53
+ const guardNames = guardDecoratorMatch[1].split(",").map((g) => g.trim());
54
+ for (const g of guardNames) guards.add(g);
55
+ }
56
+
57
+ // 3. Emitted Events
58
+ // Laravel: event(new OrderPlaced($order));
59
+ const eventNewMatch = matchCode(/\bevent\s*\(\s*new\s+([A-Za-z0-9_]+)/);
60
+ if (eventNewMatch) {
61
+ emittedEvents.add(eventNewMatch[1]);
62
+ }
63
+ // Laravel: Event::dispatch(new OrderPlaced($order)); or Event::dispatch('name');
64
+ const eventDispatchMatch = matchCode(/\bEvent::dispatch\s*\(\s*(?:new\s+)?([A-Za-z0-9_]+)/);
65
+ if (eventDispatchMatch) {
66
+ emittedEvents.add(eventDispatchMatch[1]);
67
+ }
68
+ // Laravel: broadcast(new OrderUpdated($order));
69
+ const broadcastMatch = matchCode(/\bbroadcast\s*\(\s*new\s+([A-Za-z0-9_]+)/);
70
+ if (broadcastMatch) {
71
+ emittedEvents.add(broadcastMatch[1]);
72
+ }
73
+ // EventEmitter: this.eventEmitter.emit('order.created', ...)
74
+ const nodeEmitMatch = matchCode(/(?:eventEmitter|\$emit)\.emit\s*\(\s*['"]([^'"]+)['"]/);
75
+ if (nodeEmitMatch) {
76
+ emittedEvents.add(nodeEmitMatch[1]);
77
+ }
78
+
79
+ // 4. Dispatched Background Jobs
80
+ // Laravel: ProcessPaymentJob::dispatch($order); or ProcessPayment::dispatchSync(...)
81
+ const jobDispatchStaticMatch = matchCode(/\b([A-Z][a-zA-Z0-9_]*(?:Job|Queue|Task|Process)[a-zA-Z0-9_]*)::dispatch/);
82
+ if (jobDispatchStaticMatch) {
83
+ dispatchedJobs.add(jobDispatchStaticMatch[1]);
84
+ }
85
+ // Laravel: dispatch(new ProcessPayment($order));
86
+ const dispatchNewMatch = matchCode(/\bdispatch\s*\(\s*new\s+([A-Za-z0-9_]+)/);
87
+ if (dispatchNewMatch) {
88
+ dispatchedJobs.add(dispatchNewMatch[1]);
89
+ }
90
+ // BullMQ / Queue: queue.add('process-payment', ...)
91
+ const queueAddMatch = matchCode(/(?:queue|queueService)\.add\s*\(\s*['"]([^'"]+)['"]/);
92
+ if (queueAddMatch) {
93
+ dispatchedJobs.add(queueAddMatch[1]);
94
+ }
95
+
96
+ // 5. Model Mutations
97
+ // Laravel / ORM: $order->update([...]);
98
+ const updateMatch = matchCode(/\$([a-zA-Z0-9_]+)->update\s*\(/);
99
+ if (updateMatch) {
100
+ mutations.add(`${updateMatch[1]}.update()`);
101
+ }
102
+ // Laravel / ORM: $order->delete();
103
+ const deleteMatch = matchCode(/\$([a-zA-Z0-9_]+)->delete\s*\(/);
104
+ if (deleteMatch) {
105
+ mutations.add(`${deleteMatch[1]}.delete()`);
106
+ }
107
+ // Direct property assignment: $order->status = 'completed';
108
+ const assignMatch = matchCode(/\$([a-zA-Z0-9_]+)->([a-zA-Z0-9_]+)\s*=(?![=>])\s*([^;]+);/);
109
+ if (assignMatch && !["this", "request"].includes(assignMatch[1])) {
110
+ mutations.add(`${assignMatch[1]}.${assignMatch[2]}`);
111
+ }
112
+ }
113
+
114
+ return {
115
+ analysis: "lexical_heuristic",
116
+ guards: Array.from(guards),
117
+ hasTransaction,
118
+ emittedEvents: Array.from(emittedEvents),
119
+ dispatchedJobs: Array.from(dispatchedJobs),
120
+ mutations: Array.from(mutations),
121
+ };
122
+ }
123
+ }
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Utility to find the end line (1-based index) of a code block.
3
+ * Handles brace matching with string and comment awareness for C-like languages (TS, JS, PHP, Go).
4
+ */
5
+ export function findBraceBlockEnd(lines: string[], startLineIndex: number): number {
6
+ let depth = 0;
7
+ let hasOpened = false;
8
+ let inMultiLineComment = false;
9
+
10
+ for (let i = startLineIndex; i < lines.length; i++) {
11
+ const line = lines[i];
12
+ let inSingleQuote = false;
13
+ let inDoubleQuote = false;
14
+ let inTemplateString = false;
15
+
16
+ for (let j = 0; j < line.length; j++) {
17
+ const char = line[j];
18
+ const prevChar = j > 0 ? line[j - 1] : "";
19
+ const nextChar = j + 1 < line.length ? line[j + 1] : "";
20
+
21
+ // Multi-line comment boundary
22
+ if (inMultiLineComment) {
23
+ if (char === "*" && nextChar === "/") {
24
+ inMultiLineComment = false;
25
+ j++; // skip '/'
26
+ }
27
+ continue;
28
+ }
29
+
30
+ // Check start of multi-line comment /*
31
+ if (!inSingleQuote && !inDoubleQuote && !inTemplateString && char === "/" && nextChar === "*") {
32
+ inMultiLineComment = true;
33
+ j++;
34
+ continue;
35
+ }
36
+
37
+ // Check single-line comment //
38
+ if (!inSingleQuote && !inDoubleQuote && !inTemplateString && char === "/" && nextChar === "/") {
39
+ break; // ignore rest of line
40
+ }
41
+
42
+ // String quote handling (with escape character check)
43
+ if (char === "'" && !inDoubleQuote && !inTemplateString && prevChar !== "\\") {
44
+ inSingleQuote = !inSingleQuote;
45
+ continue;
46
+ }
47
+ if (char === '"' && !inSingleQuote && !inTemplateString && prevChar !== "\\") {
48
+ inDoubleQuote = !inDoubleQuote;
49
+ continue;
50
+ }
51
+ if (char === "`" && !inSingleQuote && !inDoubleQuote && prevChar !== "\\") {
52
+ inTemplateString = !inTemplateString;
53
+ continue;
54
+ }
55
+
56
+ if (inSingleQuote || inDoubleQuote || inTemplateString) {
57
+ continue;
58
+ }
59
+
60
+ // Brace tracking
61
+ if (char === "{") {
62
+ depth++;
63
+ hasOpened = true;
64
+ } else if (char === "}") {
65
+ if (hasOpened) {
66
+ depth--;
67
+ if (depth === 0) {
68
+ return i + 1; // 1-based line number
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ // Safety guard: If we haven't seen an opening brace within 40 lines or hit a declaration-only statement
75
+ if (!hasOpened) {
76
+ const trimmed = line.trim();
77
+ if (trimmed.endsWith(";") && i > startLineIndex) {
78
+ return i + 1;
79
+ }
80
+ if (i - startLineIndex > 40) {
81
+ return startLineIndex + 1;
82
+ }
83
+ }
84
+ }
85
+
86
+ // Fallback: If braces were unclosed or not found, return start line
87
+ return startLineIndex + 1;
88
+ }
89
+
90
+ /**
91
+ * Utility to find the end line (1-based index) of an indentation-based block (Python).
92
+ */
93
+ export function findPythonBlockEnd(lines: string[], startLineIndex: number): number {
94
+ if (startLineIndex >= lines.length) return startLineIndex + 1;
95
+
96
+ const startLine = lines[startLineIndex];
97
+ const baseIndentMatch = startLine.match(/^(\s*)/);
98
+ const baseIndent = baseIndentMatch ? baseIndentMatch[1].length : 0;
99
+
100
+ let lastContentLine = startLineIndex + 1;
101
+ let bodyStarted = false;
102
+
103
+ for (let i = startLineIndex + 1; i < lines.length; i++) {
104
+ const line = lines[i];
105
+ const trimmed = line.trim();
106
+
107
+ // Skip empty lines or pure comment lines
108
+ if (!trimmed || trimmed.startsWith("#")) {
109
+ continue;
110
+ }
111
+
112
+ const currentIndentMatch = line.match(/^(\s*)/);
113
+ const currentIndent = currentIndentMatch ? currentIndentMatch[1].length : 0;
114
+
115
+ if (currentIndent > baseIndent) {
116
+ bodyStarted = true;
117
+ lastContentLine = i + 1;
118
+ } else {
119
+ // Returned to same or lesser indentation -> block ended
120
+ if (bodyStarted) {
121
+ return lastContentLine;
122
+ }
123
+ break;
124
+ }
125
+ }
126
+
127
+ return lastContentLine;
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
+ }
289
+
290
+ export function findClosingParenthesis(maskedSource: string, openingIndex: number): number {
291
+ if (maskedSource[openingIndex] !== "(") return -1;
292
+ let depth = 0;
293
+ for (let i = openingIndex; i < maskedSource.length; i++) {
294
+ if (maskedSource[i] === "(") depth++;
295
+ else if (maskedSource[i] === ")" && --depth === 0) return i;
296
+ }
297
+ return -1;
298
+ }
299
+
300
+ /**
301
+ * Replaces the contents of comments and string/template literals with spaces while
302
+ * preserving exact character offsets, outer quote delimiters, and line breaks.
303
+ */
304
+ export function blankCommentsAndStrings(
305
+ content: string,
306
+ options?: { hashComments?: boolean }
307
+ ): string {
308
+ const hashComments = options?.hashComments ?? false;
309
+ const out = content.split("");
310
+ const len = out.length;
311
+
312
+ let i = 0;
313
+ let inSingle = false;
314
+ let inDouble = false;
315
+ let inTemplate = false;
316
+ let inLineComment = false;
317
+ let inBlockComment = false;
318
+
319
+ while (i < len) {
320
+ const ch = out[i];
321
+ const next = i + 1 < len ? out[i + 1] : "";
322
+
323
+ if (inLineComment) {
324
+ if (ch === "\n") {
325
+ inLineComment = false;
326
+ } else if (ch !== "\r") {
327
+ out[i] = " ";
328
+ }
329
+ i++;
330
+ continue;
331
+ }
332
+
333
+ if (inBlockComment) {
334
+ if (ch === "*" && next === "/") {
335
+ out[i] = " ";
336
+ out[i + 1] = " ";
337
+ inBlockComment = false;
338
+ i += 2;
339
+ continue;
340
+ }
341
+ if (ch !== "\n" && ch !== "\r") {
342
+ out[i] = " ";
343
+ }
344
+ i++;
345
+ continue;
346
+ }
347
+
348
+ if (inSingle) {
349
+ if (ch === "\\" && i + 1 < len) {
350
+ if (out[i] !== "\n" && out[i] !== "\r") out[i] = " ";
351
+ if (out[i + 1] !== "\n" && out[i + 1] !== "\r") out[i + 1] = " ";
352
+ i += 2;
353
+ continue;
354
+ }
355
+ if (ch === "'") {
356
+ inSingle = false;
357
+ } else if (ch !== "\n" && ch !== "\r") {
358
+ out[i] = " ";
359
+ }
360
+ i++;
361
+ continue;
362
+ }
363
+
364
+ if (inDouble) {
365
+ if (ch === "\\" && i + 1 < len) {
366
+ if (out[i] !== "\n" && out[i] !== "\r") out[i] = " ";
367
+ if (out[i + 1] !== "\n" && out[i + 1] !== "\r") out[i + 1] = " ";
368
+ i += 2;
369
+ continue;
370
+ }
371
+ if (ch === '"') {
372
+ inDouble = false;
373
+ } else if (ch !== "\n" && ch !== "\r") {
374
+ out[i] = " ";
375
+ }
376
+ i++;
377
+ continue;
378
+ }
379
+
380
+ if (inTemplate) {
381
+ if (ch === "\\" && i + 1 < len) {
382
+ if (out[i] !== "\n" && out[i] !== "\r") out[i] = " ";
383
+ if (out[i + 1] !== "\n" && out[i + 1] !== "\r") out[i + 1] = " ";
384
+ i += 2;
385
+ continue;
386
+ }
387
+ if (ch === "`") {
388
+ inTemplate = false;
389
+ } else if (ch !== "\n" && ch !== "\r") {
390
+ out[i] = " ";
391
+ }
392
+ i++;
393
+ continue;
394
+ }
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
+
411
+ // Normal code state
412
+ if (ch === "/" && next === "/") {
413
+ out[i] = " ";
414
+ out[i + 1] = " ";
415
+ inLineComment = true;
416
+ i += 2;
417
+ continue;
418
+ }
419
+
420
+ if (ch === "/" && next === "*") {
421
+ out[i] = " ";
422
+ out[i + 1] = " ";
423
+ inBlockComment = true;
424
+ i += 2;
425
+ continue;
426
+ }
427
+
428
+ if (hashComments && ch === "#") {
429
+ out[i] = " ";
430
+ inLineComment = true;
431
+ i++;
432
+ continue;
433
+ }
434
+
435
+ if (ch === "'") {
436
+ inSingle = true;
437
+ i++;
438
+ continue;
439
+ }
440
+
441
+ if (ch === '"') {
442
+ inDouble = true;
443
+ i++;
444
+ continue;
445
+ }
446
+
447
+ if (ch === "`") {
448
+ inTemplate = true;
449
+ i++;
450
+ continue;
451
+ }
452
+
453
+ i++;
454
+ }
455
+
456
+ return out.join("");
457
+ }
458
+
@@ -0,0 +1,71 @@
1
+ import type { ArchetypeKind, ParsedFileAST } from "../../../types/index.ts";
2
+
3
+ export interface CodeExtractor {
4
+ canHandle(filePath: string): boolean;
5
+ extract(filePath: string, content: string): Promise<ParsedFileAST>;
6
+ }
7
+
8
+ export function detectArchetype(filePath: string, archetypesMap: Record<string, string>): ArchetypeKind {
9
+ const normalized = filePath.replace(/\\/g, "/");
10
+
11
+ // Check user-configured archetype glob patterns
12
+ for (const [archetype, pattern] of Object.entries(archetypesMap)) {
13
+ if (matchesSimpleGlob(normalized, pattern)) {
14
+ return archetype as ArchetypeKind;
15
+ }
16
+ }
17
+
18
+ // Built-in convention heuristics
19
+ const lower = normalized.toLowerCase();
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";
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";
27
+ if (lower.includes("service")) return "service";
28
+ if (lower.includes("repository") || lower.includes("repo")) return "repository";
29
+ if (/(?:^|\/)actions?\/|action\.(?:php|ts|js|py|go)$/i.test(lower)) return "action";
30
+ if (lower.includes("job") || lower.includes("queue")) return "job";
31
+ if (lower.includes("event")) return "event";
32
+ if (lower.includes("listener")) return "listener";
33
+ if (lower.includes("middleware")) return "middleware";
34
+ if (lower.includes("request") || lower.includes("serializer") || lower.includes("schema")) return "request";
35
+ if (lower.includes("resource")) return "resource";
36
+ if (lower.includes(".blade.php") || lower.includes("views/") || lower.includes("templates/")) return "view";
37
+ if (lower.includes("route") || lower.includes("router")) return "route";
38
+ if (lower.includes("util") || lower.includes("helper")) return "util";
39
+
40
+ return "unknown";
41
+ }
42
+
43
+ export function matchesSimpleGlob(path: string, pattern: string, allowBasename: boolean = true): boolean {
44
+ const normalizedPath = path.replace(/\\/g, "/").replace(/^\.\//, "");
45
+ const normalizedPattern = pattern.replace(/\\/g, "/").replace(/^\.\//, "");
46
+
47
+ const escaped = normalizedPattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
48
+ const regexStr = escaped
49
+ .replace(/\*\*\//g, "\0GLOB_GLOB_SLASH\0")
50
+ .replace(/\*\*/g, "\0GLOB_GLOB\0")
51
+ .replace(/\*/g, "\0GLOB_STAR\0")
52
+ .replace(/\?/g, "\0GLOB_Q\0")
53
+ .replace(/\0GLOB_GLOB_SLASH\0/g, "(?:.*\\/)?")
54
+ .replace(/\0GLOB_GLOB\0/g, ".*")
55
+ .replace(/\0GLOB_STAR\0/g, "[^/]*")
56
+ .replace(/\0GLOB_Q\0/g, "[^/]");
57
+
58
+ const regex = new RegExp(`^${regexStr}$`, "i");
59
+ if (regex.test(normalizedPath)) {
60
+ return true;
61
+ }
62
+
63
+ // If pattern does not contain directory separators, allow matching against the basename
64
+ if (allowBasename && !normalizedPattern.includes("/")) {
65
+ const base = normalizedPath.split("/").pop() ?? "";
66
+ return regex.test(base);
67
+ }
68
+
69
+ return false;
70
+ }
71
+