septum 0.1.4 → 0.1.6

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 (70) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +105 -105
  3. package/bin/septum.ts +4 -4
  4. package/package.json +63 -63
  5. package/src/cli/commands/check.ts +161 -161
  6. package/src/cli/commands/hook.ts +216 -188
  7. package/src/cli/commands/ingest.ts +29 -29
  8. package/src/cli/commands/init.ts +213 -211
  9. package/src/cli/commands/locate.ts +61 -61
  10. package/src/cli/commands/query.ts +104 -64
  11. package/src/cli/commands/serve.ts +5 -5
  12. package/src/cli/commands/slice.ts +50 -48
  13. package/src/cli/commands/sync.ts +31 -31
  14. package/src/cli/index.ts +220 -210
  15. package/src/cli/templates/hooks.ts +75 -75
  16. package/src/cli/templates/rules.ts +50 -38
  17. package/src/cli/templates/skill.ts +65 -69
  18. package/src/core/boundary/evaluator.ts +429 -210
  19. package/src/core/config/loader.ts +117 -97
  20. package/src/core/config/schema.ts +39 -39
  21. package/src/core/database/client.ts +44 -44
  22. package/src/core/database/repositories/dependency.repository.ts +552 -349
  23. package/src/core/database/repositories/domain.repository.ts +275 -198
  24. package/src/core/database/repositories/file.repository.ts +117 -106
  25. package/src/core/database/repositories/meta.repository.ts +33 -33
  26. package/src/core/database/repositories/symbol.repository.ts +482 -443
  27. package/src/core/database/repository.ts +281 -260
  28. package/src/core/database/schema.ts +154 -153
  29. package/src/core/discovery/topology-detector.ts +486 -486
  30. package/src/core/ingestion/hasher.ts +5 -5
  31. package/src/core/ingestion/pipeline.ts +606 -535
  32. package/src/core/parser/boundary-tracker.ts +433 -288
  33. package/src/core/parser/extractors/base.ts +62 -62
  34. package/src/core/parser/extractors/blade.ts +158 -158
  35. package/src/core/parser/extractors/frontend.ts +147 -194
  36. package/src/core/parser/extractors/go.ts +408 -180
  37. package/src/core/parser/extractors/laravel-semantic.ts +1045 -901
  38. package/src/core/parser/extractors/mcp-cli-semantic.ts +328 -199
  39. package/src/core/parser/extractors/nestjs-semantic.ts +134 -119
  40. package/src/core/parser/extractors/php.ts +415 -153
  41. package/src/core/parser/extractors/python.ts +460 -228
  42. package/src/core/parser/extractors/registry.ts +70 -70
  43. package/src/core/parser/extractors/semantic-extractor.interface.ts +21 -21
  44. package/src/core/parser/extractors/typescript.ts +668 -181
  45. package/src/core/parser/tree-sitter.ts +41 -41
  46. package/src/core/parser/wasm-loader.ts +271 -0
  47. package/src/core/resolver/call-graph-tracer.ts +698 -668
  48. package/src/core/resolver/module-resolver.ts +479 -342
  49. package/src/core/resolver/path-resolver.ts +147 -147
  50. package/src/core/resolver/symbol-locator.ts +543 -543
  51. package/src/core/resolver/vertical-slice-tracer.ts +323 -285
  52. package/src/core/session/session-manager.ts +56 -56
  53. package/src/core/telemetry/telemetry.ts +86 -86
  54. package/src/core/topology/environment-detector.ts +109 -6
  55. package/src/index.ts +21 -21
  56. package/src/mcp/schemas.ts +695 -286
  57. package/src/mcp/server.ts +927 -716
  58. package/src/mcp/tools/check-boundary.ts +307 -152
  59. package/src/mcp/tools/get-domain-catalog.ts +155 -121
  60. package/src/mcp/tools/get-environment-topology.ts +3 -6
  61. package/src/mcp/tools/get-feature-context.ts +227 -116
  62. package/src/mcp/tools/get-symbol-hotspots.ts +54 -59
  63. package/src/mcp/tools/get-symbol-impact.ts +28 -26
  64. package/src/mcp/tools/get-symbol.ts +65 -63
  65. package/src/mcp/tools/locate-symbol.ts +169 -190
  66. package/src/mcp/tools/register-domain.ts +59 -64
  67. package/src/mcp/tools/register-feature.ts +91 -0
  68. package/src/mcp/tools/trace-vertical-slice.ts +74 -48
  69. package/src/types/index.ts +366 -315
  70. package/src/version.ts +3 -3
@@ -1,901 +1,1045 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import type { ExecutionChainNode, VerticalSliceRecord } from "../../../types/index.ts";
4
- import { BehavioralAnalyzer } from "../behavioral-analyzer.ts";
5
- import { SchemaProviderRegistry } from "../schema/schema-provider-registry.ts";
6
- import type {
7
- SemanticSliceExtractor,
8
- VerticalSliceCandidate,
9
- } from "./semantic-extractor.interface.ts";
10
-
11
- export interface ParsedRoute {
12
- httpMethod: string;
13
- uri: string;
14
- routeName?: string;
15
- controllerClass: string;
16
- actionName: string;
17
- file?: string;
18
- }
19
-
20
- export type LaravelSemanticExtractionResult = VerticalSliceCandidate[] & {
21
- slices: VerticalSliceCandidate[];
22
- };
23
-
24
- export class LaravelSemanticExtractor implements SemanticSliceExtractor {
25
- public readonly id = "laravel";
26
- public readonly name = "Laravel MVC Semantic Extractor";
27
-
28
- constructor(private projectRoot: string = process.cwd()) {}
29
-
30
- public canHandle(projectRoot: string, framework?: string): boolean {
31
- if (framework === "laravel") return true;
32
- return (
33
- fs.existsSync(path.join(projectRoot, "artisan")) ||
34
- fs.existsSync(path.join(projectRoot, "routes/web.php")) ||
35
- fs.existsSync(path.join(projectRoot, "routes/api.php"))
36
- );
37
- }
38
-
39
- /**
40
- * Scan route files and extract complete vertical slices.
41
- */
42
- public extractSlices(
43
- projectRootOrDomainId?: string | number,
44
- maybeDomainId?: number
45
- ): LaravelSemanticExtractionResult {
46
- let root = this.projectRoot;
47
- let domainId: number | undefined;
48
-
49
- if (typeof projectRootOrDomainId === "string") {
50
- root = projectRootOrDomainId;
51
- domainId = maybeDomainId;
52
- } else if (typeof projectRootOrDomainId === "number") {
53
- domainId = projectRootOrDomainId;
54
- }
55
-
56
- const routeFiles = [
57
- path.join(root, "routes/web.php"),
58
- path.join(root, "routes/api.php"),
59
- ].filter((f) => fs.existsSync(f));
60
-
61
- const parsedRoutes: ParsedRoute[] = [];
62
-
63
- for (const routeFile of routeFiles) {
64
- const content = fs.readFileSync(routeFile, "utf-8");
65
- parsedRoutes.push(...this.parseRoutesContent(content));
66
- }
67
-
68
- const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
69
-
70
- for (const route of parsedRoutes) {
71
- const controllerInfo = this.resolveController(route.controllerClass, route.actionName);
72
-
73
- let formRequestInfo: {
74
- className: string;
75
- filePath?: string;
76
- rules: Record<string, string>;
77
- } | null = null;
78
-
79
- let modelInfo: {
80
- className: string;
81
- filePath?: string;
82
- fillable: string[];
83
- casts: Record<string, string>;
84
- } | null = null;
85
-
86
- let frontendInfo: {
87
- target: string;
88
- props: string[];
89
- } | null = null;
90
-
91
- let behavioralInfo: import("../behavioral-analyzer.ts").MethodBehavioralSummary | null = null;
92
- if (controllerInfo.filePath && fs.existsSync(controllerInfo.filePath)) {
93
- const controllerCode = fs.readFileSync(controllerInfo.filePath, "utf-8");
94
- const actionBody = this.extractActionBody(controllerCode, route.actionName);
95
- behavioralInfo = BehavioralAnalyzer.analyzeMethod(actionBody);
96
-
97
- // 1. Detect FormRequest in method signature
98
- const requestClassName = this.detectFormRequestClass(controllerCode, route.actionName);
99
- if (requestClassName) {
100
- const reqFile = this.findClassFile("Requests", requestClassName);
101
- const rules = reqFile && fs.existsSync(reqFile) ? this.extractValidationRules(fs.readFileSync(reqFile, "utf-8")) : {};
102
- formRequestInfo = {
103
- className: requestClassName,
104
- filePath: reqFile ? path.relative(this.projectRoot, reqFile) : undefined,
105
- rules,
106
- };
107
- }
108
-
109
- // 2. Detect Model referenced in parameters or action body
110
- const modelClassName = this.detectModelClass(controllerCode, route.actionName, actionBody);
111
- if (modelClassName) {
112
- const modFile = this.findClassFile("Models", modelClassName);
113
- const modMetadata = modFile && fs.existsSync(modFile) ? this.extractModelMetadata(fs.readFileSync(modFile, "utf-8")) : { fillable: [], casts: {} };
114
- modelInfo = {
115
- className: modelClassName,
116
- filePath: modFile ? path.relative(this.projectRoot, modFile) : undefined,
117
- fillable: modMetadata.fillable,
118
- casts: modMetadata.casts,
119
- };
120
- }
121
-
122
- // 3. Detect Inertia Render / View Target
123
- frontendInfo = this.detectFrontendTarget(actionBody);
124
- }
125
-
126
- const chain: ExecutionChainNode[] = [
127
- {
128
- stage: "ingress",
129
- symbol: `${route.httpMethod.toUpperCase()} ${route.uri.startsWith("/") ? route.uri : `/${route.uri}`}`,
130
- file: route.file,
131
- description: `HTTP Route: ${route.routeName || route.uri}`,
132
- },
133
- ];
134
-
135
- if (behavioralInfo && behavioralInfo.guards.length > 0) {
136
- chain.push({
137
- stage: "guard",
138
- symbol: behavioralInfo.guards.join(", "),
139
- description: "Authorization / Security Guard",
140
- guards: behavioralInfo.guards,
141
- });
142
- }
143
-
144
- if (formRequestInfo) {
145
- chain.push({
146
- stage: "validation",
147
- symbol: formRequestInfo.className,
148
- file: formRequestInfo.filePath,
149
- description: "Form Request Validation",
150
- });
151
- }
152
-
153
- chain.push({
154
- stage: "controller",
155
- symbol: `${route.controllerClass}::${route.actionName}`,
156
- file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : undefined,
157
- line: controllerInfo.line,
158
- description: `Controller Action`,
159
- guards: behavioralInfo && behavioralInfo.guards.length > 0 ? behavioralInfo.guards : undefined,
160
- mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
161
- transactions: behavioralInfo?.hasTransaction,
162
- });
163
-
164
- if (behavioralInfo && behavioralInfo.hasTransaction) {
165
- chain.push({
166
- stage: "transaction",
167
- symbol: "DB::transaction",
168
- description: "Database Transaction Scope",
169
- transactions: true,
170
- });
171
- }
172
-
173
- if (modelInfo) {
174
- const schema = SchemaProviderRegistry.resolveSchema(
175
- root,
176
- modelInfo.className,
177
- modelInfo.filePath
178
- );
179
-
180
- const columnsSummary =
181
- schema && schema.fields.length > 0
182
- ? schema.fields.map((f) => `${f.name}:${f.type}${f.nullable ? "?" : ""}`).join(", ")
183
- : undefined;
184
-
185
- chain.push({
186
- stage: "entity",
187
- symbol: modelInfo.className,
188
- file: modelInfo.filePath,
189
- description: schema?.tableName ? `Eloquent Model (${schema.tableName})` : "Eloquent Model",
190
- table: schema?.tableName,
191
- schema_file: schema?.schemaSourceFile,
192
- columns_summary: columnsSummary,
193
- mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
194
- });
195
- }
196
-
197
- if (behavioralInfo && behavioralInfo.dispatchedJobs.length > 0) {
198
- for (const job of behavioralInfo.dispatchedJobs) {
199
- const jobFile = this.findClassFile("Jobs", job);
200
- chain.push({
201
- stage: "job",
202
- symbol: job,
203
- file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
204
- description: "Background Queue Job Dispatched",
205
- dispatches: [job],
206
- });
207
- }
208
- }
209
-
210
- if (behavioralInfo && behavioralInfo.emittedEvents.length > 0) {
211
- for (const evt of behavioralInfo.emittedEvents) {
212
- const evtFile = this.findClassFile("Events", evt);
213
- chain.push({
214
- stage: "event",
215
- symbol: evt,
216
- file: evtFile ? path.relative(this.projectRoot, evtFile) : undefined,
217
- description: "Domain Event Emitted",
218
- emits: [evt],
219
- });
220
- }
221
- }
222
-
223
- if (frontendInfo) {
224
- chain.push({
225
- stage: "egress",
226
- symbol: frontendInfo.target,
227
- description: "Inertia / Frontend Target",
228
- });
229
- }
230
-
231
- slices.push({
232
- domain_id: domainId ?? null,
233
- feature_key: route.routeName || null,
234
- http_method: route.httpMethod.toUpperCase(),
235
- route_uri: route.uri.startsWith("/") ? route.uri : `/${route.uri}`,
236
- route_name: route.routeName || null,
237
- controller_class: route.controllerClass,
238
- action_name: route.actionName,
239
- controller_file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : null,
240
- controller_line: controllerInfo.line,
241
- architecture_style: "mvc",
242
- entry_kind: "http_route",
243
- execution_chain_json: JSON.stringify(chain),
244
- });
245
- }
246
-
247
- // Also discover Omni-Trigger slices (Jobs, Console Commands, Event Listeners)
248
- slices.push(...this.extractJobSlices(root, domainId));
249
- slices.push(...this.extractCommandSlices(root, domainId));
250
- slices.push(...this.extractListenerSlices(root, domainId));
251
-
252
- return Object.assign(slices, { slices });
253
- }
254
-
255
- /**
256
- * Parse Laravel Route declarations.
257
- */
258
- public parseRoutesContent(content: string): ParsedRoute[] {
259
- const routes: ParsedRoute[] = [];
260
-
261
- // 1. Process Route::resource
262
- const resourceRegex = /Route::resource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
263
- let resMatch;
264
- while ((resMatch = resourceRegex.exec(content)) !== null) {
265
- const baseUri = resMatch[1].replace(/^\//, "");
266
- const controllerClass = resMatch[2];
267
- const resourceActions = [
268
- { method: "GET", sub: "", action: "index" },
269
- { method: "GET", sub: "/create", action: "create" },
270
- { method: "POST", sub: "", action: "store" },
271
- { method: "GET", sub: "/{id}", action: "show" },
272
- { method: "GET", sub: "/{id}/edit", action: "edit" },
273
- { method: "PUT", sub: "/{id}", action: "update" },
274
- { method: "DELETE", sub: "/{id}", action: "destroy" },
275
- ];
276
-
277
- for (const res of resourceActions) {
278
- routes.push({
279
- httpMethod: res.method,
280
- uri: `/${baseUri}${res.sub}`,
281
- routeName: `${baseUri}.${res.action}`,
282
- controllerClass,
283
- actionName: res.action,
284
- });
285
- }
286
- }
287
-
288
- // 2. Parse routes with group context tracking (prefix, controller, name prefix)
289
- const lines = content.split(/\r?\n/);
290
- interface GroupContext {
291
- prefix: string;
292
- controller: string;
293
- namePrefix: string;
294
- braceDepth: number;
295
- }
296
-
297
- const groupStack: GroupContext[] = [];
298
- let currentBraceDepth = 0;
299
- let statementBuffer = "";
300
- let inStatement = false;
301
-
302
- for (let i = 0; i < lines.length; i++) {
303
- const line = lines[i];
304
- const trimmed = line.trim();
305
-
306
- // Check group opens: Route::...group(
307
- if (trimmed.includes("Route::") && trimmed.includes("group(") && trimmed.includes("function")) {
308
- const prefixMatch = /prefix\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
309
- const controllerMatch = /controller\s*\(\s*([\\A-Za-z0-9_]+)::class\s*\)/.exec(trimmed);
310
- const nameMatch = /name\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
311
-
312
- const currentCtx = groupStack[groupStack.length - 1];
313
- const newPrefix = [currentCtx?.prefix, prefixMatch ? prefixMatch[1] : ""]
314
- .filter(Boolean)
315
- .join("/");
316
- const newController = controllerMatch ? controllerMatch[1] : (currentCtx?.controller || "");
317
- const newNamePrefix = [currentCtx?.namePrefix, nameMatch ? nameMatch[1] : ""]
318
- .filter(Boolean)
319
- .join("");
320
-
321
- groupStack.push({
322
- prefix: newPrefix,
323
- controller: newController,
324
- namePrefix: newNamePrefix,
325
- braceDepth: currentBraceDepth,
326
- });
327
- }
328
-
329
- // Track brace depth
330
- for (const char of line) {
331
- if (char === "{") currentBraceDepth++;
332
- if (char === "}") {
333
- currentBraceDepth--;
334
- if (groupStack.length > 0) {
335
- const top = groupStack[groupStack.length - 1];
336
- if (currentBraceDepth <= top.braceDepth) {
337
- groupStack.pop();
338
- }
339
- }
340
- }
341
- }
342
-
343
- // Route statement accumulation across lines
344
- if (!inStatement && trimmed.startsWith("Route::") && !trimmed.includes("Route::resource") && !trimmed.includes("Route::group")) {
345
- statementBuffer = trimmed;
346
- inStatement = true;
347
- } else if (inStatement) {
348
- statementBuffer += " " + trimmed;
349
- }
350
-
351
- if (inStatement && statementBuffer.includes(";")) {
352
- inStatement = false;
353
- const stmt = statementBuffer;
354
- statementBuffer = "";
355
-
356
- const currentCtx = groupStack[groupStack.length - 1];
357
- const parsed = this.parseSingleRouteStatement(stmt, currentCtx);
358
- if (parsed) {
359
- routes.push(parsed);
360
- }
361
- }
362
- }
363
-
364
- return routes;
365
- }
366
-
367
- private parseSingleRouteStatement(
368
- stmt: string,
369
- ctx?: { prefix: string; controller: string; namePrefix: string }
370
- ): ParsedRoute | null {
371
- const methodMatch = /Route::(get|post|put|patch|delete|any|options)\s*\(\s*['"]([^'"]+)['"]([\s\S]*)/i.exec(stmt);
372
- if (!methodMatch) {
373
- const viewMatch = /Route::view\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/i.exec(stmt);
374
- if (viewMatch) {
375
- const rawUri = viewMatch[1];
376
- const viewTarget = viewMatch[2];
377
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
378
- const fullUri = ctx?.prefix ? `/${ctx.prefix.replace(/^\/|\/$/g, "")}/${rawUri.replace(/^\//, "")}` : rawUri;
379
- return {
380
- httpMethod: "GET",
381
- uri: fullUri.startsWith("/") ? fullUri : `/${fullUri}`,
382
- routeName: (ctx?.namePrefix || "") + (nameMatch ? nameMatch[1] : ""),
383
- controllerClass: "View",
384
- actionName: viewTarget,
385
- };
386
- }
387
- return null;
388
- }
389
-
390
- const httpMethod = methodMatch[1].toUpperCase();
391
- let uri = methodMatch[2];
392
- const rest = methodMatch[3];
393
-
394
- if (ctx?.prefix) {
395
- const cleanPrefix = ctx.prefix.replace(/^\/|\/$/g, "");
396
- const cleanUri = uri.replace(/^\//, "");
397
- uri = cleanUri ? `/${cleanPrefix}/${cleanUri}` : `/${cleanPrefix}`;
398
- }
399
- if (!uri.startsWith("/")) uri = `/${uri}`;
400
-
401
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
402
- const rawRouteName = nameMatch ? nameMatch[1] : undefined;
403
- const fullRouteName = rawRouteName
404
- ? (ctx?.namePrefix || "") + rawRouteName
405
- : undefined;
406
-
407
- // [Controller::class, 'action']
408
- const arrayMatch = /\[\s*([\\A-Za-z0-9_]+)::class\s*,\s*['"]([A-Za-z0-9_]+)['"]\s*\]/.exec(rest);
409
- if (arrayMatch) {
410
- return {
411
- httpMethod,
412
- uri,
413
- routeName: fullRouteName,
414
- controllerClass: arrayMatch[1],
415
- actionName: arrayMatch[2],
416
- };
417
- }
418
-
419
- // 'Controller@action'
420
- const stringActionMatch = /['"]([\\A-Za-z0-9_]+)@([A-Za-z0-9_]+)['"]/.exec(rest);
421
- if (stringActionMatch) {
422
- return {
423
- httpMethod,
424
- uri,
425
- routeName: fullRouteName,
426
- controllerClass: stringActionMatch[1],
427
- actionName: stringActionMatch[2],
428
- };
429
- }
430
-
431
- // Action inside controller group
432
- if (ctx?.controller) {
433
- const singleActionMatch = /,\s*['"]([A-Za-z0-9_]+)['"]/.exec(rest);
434
- if (singleActionMatch) {
435
- return {
436
- httpMethod,
437
- uri,
438
- routeName: fullRouteName,
439
- controllerClass: ctx.controller,
440
- actionName: singleActionMatch[1],
441
- };
442
- }
443
- }
444
-
445
- // Invokable controller
446
- const invokableMatch = /,\s*([\\A-Za-z0-9_]+)::class/.exec(rest);
447
- if (invokableMatch) {
448
- return {
449
- httpMethod,
450
- uri,
451
- routeName: fullRouteName,
452
- controllerClass: invokableMatch[1],
453
- actionName: "__invoke",
454
- };
455
- }
456
-
457
- // Closure
458
- if (rest.includes("function")) {
459
- return {
460
- httpMethod,
461
- uri,
462
- routeName: fullRouteName,
463
- controllerClass: "Closure",
464
- actionName: "handle",
465
- };
466
- }
467
-
468
- return null;
469
- }
470
-
471
- private resolveController(controllerClass: string, actionName: string): { filePath?: string; line: number } {
472
- const simpleName = controllerClass.split(/\\|\//).pop() || controllerClass;
473
- const candidates = [
474
- path.join(this.projectRoot, `app/Http/Controllers/${simpleName}.php`),
475
- path.join(this.projectRoot, `app/Http/Controllers/Api/${simpleName}.php`),
476
- path.join(this.projectRoot, `app/Http/Controllers/Admin/${simpleName}.php`),
477
- ];
478
-
479
- for (const c of candidates) {
480
- if (fs.existsSync(c)) {
481
- const lines = fs.readFileSync(c, "utf-8").split("\n");
482
- let targetLine = 1;
483
- for (let i = 0; i < lines.length; i++) {
484
- if (new RegExp(`function\\s+${actionName}\\s*\\(`, "i").test(lines[i])) {
485
- targetLine = i + 1;
486
- break;
487
- }
488
- }
489
- return { filePath: c, line: targetLine };
490
- }
491
- }
492
-
493
- return { line: 0 };
494
- }
495
-
496
- private extractActionBody(controllerCode: string, actionName: string): string {
497
- const fnRegex = new RegExp(`public\\s+function\\s+${actionName}\\s*\\([^{]*\\)\\s*\\{`, "i");
498
- const match = fnRegex.exec(controllerCode);
499
- if (!match) return "";
500
-
501
- const startIndex = match.index + match[0].length;
502
- let braceDepth = 1;
503
- let endIndex = startIndex;
504
-
505
- while (braceDepth > 0 && endIndex < controllerCode.length) {
506
- const char = controllerCode[endIndex];
507
- if (char === "{") braceDepth++;
508
- else if (char === "}") braceDepth--;
509
- endIndex++;
510
- }
511
-
512
- return controllerCode.substring(startIndex, endIndex - 1);
513
- }
514
-
515
- private detectFormRequestClass(controllerCode: string, actionName: string): string | null {
516
- const paramRegex = new RegExp(`public\\s+function\\s+${actionName}\\s*\\(([^)]*)\\)`, "i");
517
- const match = paramRegex.exec(controllerCode);
518
- if (!match) return null;
519
-
520
- const params = match[1];
521
- // Find class names ending with Request
522
- const reqMatch = params.match(/([A-Za-z0-9_]+Request)\s+\$/);
523
- if (reqMatch && reqMatch[1] !== "Request") {
524
- return reqMatch[1];
525
- }
526
- return null;
527
- }
528
-
529
- private detectModelClass(controllerCode: string, actionName: string, actionBody: string): string | null {
530
- // 1. Method signature type-hints: (Order $order)
531
- const paramRegex = new RegExp(`public\\s+function\\s+${actionName}\\s*\\(([^)]*)\\)`, "i");
532
- const match = paramRegex.exec(controllerCode);
533
- if (match) {
534
- const parts = match[1].split(",");
535
- for (const p of parts) {
536
- const pMatch = p.trim().match(/^([A-Z][A-Za-z0-9_]+)\s+\$/);
537
- if (pMatch && !pMatch[1].endsWith("Request") && pMatch[1] !== "Request") {
538
- return pMatch[1];
539
- }
540
- }
541
- }
542
-
543
- // 2. Action body static calls: Order::find(), Order::create(), Order::query()
544
- const staticModelMatch = actionBody.match(/([A-Z][A-Za-z0-9_]+)::(?:find|findOrFail|create|where|query)\s*\(/);
545
- if (staticModelMatch && !["Inertia", "Route", "DB", "Auth", "Log", "Response"].includes(staticModelMatch[1])) {
546
- return staticModelMatch[1];
547
- }
548
-
549
- return null;
550
- }
551
-
552
- private detectFrontendTarget(actionBody: string): { target: string; props: string[] } | null {
553
- // 1. Inertia::render('Orders/Show', ['order' => $order])
554
- const inertiaMatch = actionBody.match(/Inertia::render\s*\(\s*['"]([^'"]+)['"](?:\s*,\s*\[([^\]]*)\])?\s*\)/);
555
- if (inertiaMatch) {
556
- const pageComponent = inertiaMatch[1]; // e.g. "Orders/Show"
557
- const rawProps = inertiaMatch[2] || "";
558
-
559
- // Extract prop keys: 'order' => ...
560
- const propMatches = rawProps.matchAll(/['"]([A-Za-z0-9_]+)['"]\s*=>/g);
561
- const props: string[] = [];
562
- for (const pm of propMatches) {
563
- props.push(pm[1]);
564
- }
565
-
566
- // Check for Vue, TSX, JSX files in resources/js/Pages
567
- const possibleExtensions = [".vue", ".tsx", ".jsx", ".svelte"];
568
- let frontendPath = `resources/js/Pages/${pageComponent}`;
569
- for (const ext of possibleExtensions) {
570
- const fullCandidate = path.join(this.projectRoot, `resources/js/Pages/${pageComponent}${ext}`);
571
- if (fs.existsSync(fullCandidate)) {
572
- frontendPath = `resources/js/Pages/${pageComponent}${ext}`;
573
- break;
574
- }
575
- }
576
- if (!frontendPath.includes(".")) {
577
- frontendPath += ".vue"; // Default inertia convention
578
- }
579
-
580
- return {
581
- target: frontendPath,
582
- props,
583
- };
584
- }
585
-
586
- // 2. view('orders.show', compact('order'))
587
- const viewMatch = actionBody.match(/view\s*\(\s*['"]([^'"]+)['"]/);
588
- if (viewMatch) {
589
- const viewPath = viewMatch[1].replace(/\./g, "/");
590
- return {
591
- target: `resources/views/${viewPath}.blade.php`,
592
- props: [],
593
- };
594
- }
595
-
596
- return null;
597
- }
598
-
599
- private findClassFile(
600
- subDir: "Requests" | "Models" | "Jobs" | "Events" | "Listeners" | "Console/Commands",
601
- className: string
602
- ): string | null {
603
- const directPath = path.join(this.projectRoot, `app/${subDir}/${className}.php`);
604
- if (fs.existsSync(directPath)) return directPath;
605
-
606
- // Direct app/ fallback for older Laravel
607
- const flatPath = path.join(this.projectRoot, `app/${className}.php`);
608
- if (fs.existsSync(flatPath)) return flatPath;
609
-
610
- return null;
611
- }
612
-
613
- private extractValidationRules(requestCode: string): Record<string, string> {
614
- const rules: Record<string, string> = {};
615
- const rulesMatch = requestCode.match(/function\s+rules\s*\(\s*\)[^{]*\{([^}]*)\}/i);
616
- if (!rulesMatch) return rules;
617
-
618
- const body = rulesMatch[1];
619
- // Match 'status' => 'in:pending,paid' or 'status' => ['required', 'string']
620
- const rulePairRegex = /['"]([A-Za-z0-9_]+)['"]\s*=>\s*(?:['"]([^'"]+)['"]|\[([^\]]+)\])/g;
621
- let rm;
622
- while ((rm = rulePairRegex.exec(body)) !== null) {
623
- const field = rm[1];
624
- const singleRule = rm[2];
625
- const arrayRules = rm[3];
626
- if (singleRule) {
627
- rules[field] = singleRule;
628
- } else if (arrayRules) {
629
- rules[field] = arrayRules.replace(/['"\s]/g, "").replace(/,/g, "|");
630
- }
631
- }
632
-
633
- return rules;
634
- }
635
-
636
- private extractModelMetadata(modelCode: string): { fillable: string[]; casts: Record<string, string> } {
637
- const fillable: string[] = [];
638
- const casts: Record<string, string> = {};
639
-
640
- // Match protected $fillable = [...]
641
- const fillableMatch = modelCode.match(/\$fillable\s*=\s*\[([^\]]*)\]/);
642
- if (fillableMatch) {
643
- const items = fillableMatch[1].matchAll(/['"]([A-Za-z0-9_]+)['"]/g);
644
- for (const it of items) {
645
- fillable.push(it[1]);
646
- }
647
- }
648
-
649
- // Match protected $casts = [...]
650
- const castsMatch = modelCode.match(/\$casts\s*=\s*\[([^\]]*)\]/);
651
- if (castsMatch) {
652
- const castItems = castsMatch[1].matchAll(/['"]([A-Za-z0-9_]+)['"]\s*=>\s*(?:['"]([^'"]+)['"]|([A-Za-z0-9_]+)::class)/g);
653
- for (const ci of castItems) {
654
- casts[ci[1]] = ci[2] || ci[3];
655
- }
656
- }
657
-
658
- return { fillable, casts };
659
- }
660
-
661
- private extractJobSlices(
662
- root: string,
663
- domainId?: number
664
- ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
665
- const jobsDir = path.join(root, "app/Jobs");
666
- if (!fs.existsSync(jobsDir)) return [];
667
-
668
- const jobFiles = fs.readdirSync(jobsDir).filter((f) => f.endsWith(".php"));
669
- const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
670
-
671
- for (const file of jobFiles) {
672
- const fullPath = path.join(jobsDir, file);
673
- const content = fs.readFileSync(fullPath, "utf-8");
674
- const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
675
- if (!classMatch) continue;
676
-
677
- const className = classMatch[1];
678
- const actionBody = this.extractActionBody(content, "handle");
679
- const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
680
-
681
- const chain: ExecutionChainNode[] = [
682
- {
683
- stage: "ingress",
684
- symbol: `JOB ${className}`,
685
- file: path.relative(this.projectRoot, fullPath),
686
- description: `Queue Worker Trigger: ${className}`,
687
- },
688
- {
689
- stage: "controller",
690
- symbol: `${className}::handle`,
691
- file: path.relative(this.projectRoot, fullPath),
692
- description: "Queue Job Handler",
693
- mutations: behavior.mutations.length ? behavior.mutations : undefined,
694
- transactions: behavior.hasTransaction,
695
- },
696
- ];
697
-
698
- if (behavior.hasTransaction) {
699
- chain.push({
700
- stage: "transaction",
701
- symbol: "DB::transaction",
702
- description: "Database Transaction Scope",
703
- transactions: true,
704
- });
705
- }
706
-
707
- for (const evt of behavior.emittedEvents) {
708
- const evtFile = this.findClassFile("Events", evt);
709
- chain.push({
710
- stage: "event",
711
- symbol: evt,
712
- file: evtFile ? path.relative(this.projectRoot, evtFile) : undefined,
713
- description: "Domain Event Emitted",
714
- emits: [evt],
715
- });
716
- }
717
-
718
- slices.push({
719
- domain_id: domainId ?? null,
720
- feature_key: `job:${className}`,
721
- http_method: "JOB",
722
- route_uri: `job:${className}`,
723
- route_name: `queue.${this.toSnakeCase(className)}`,
724
- controller_class: className,
725
- action_name: "handle",
726
- controller_file: path.relative(this.projectRoot, fullPath),
727
- controller_line: 1,
728
- architecture_style: "clean",
729
- entry_kind: "queue_job",
730
- execution_chain_json: JSON.stringify(chain),
731
- });
732
- }
733
-
734
- return slices;
735
- }
736
-
737
- private extractCommandSlices(
738
- root: string,
739
- domainId?: number
740
- ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
741
- const commandsDir = path.join(root, "app/Console/Commands");
742
- if (!fs.existsSync(commandsDir)) return [];
743
-
744
- const files = fs.readdirSync(commandsDir).filter((f) => f.endsWith(".php"));
745
- const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
746
-
747
- for (const file of files) {
748
- const fullPath = path.join(commandsDir, file);
749
- const content = fs.readFileSync(fullPath, "utf-8");
750
- const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
751
- if (!classMatch) continue;
752
-
753
- const className = classMatch[1];
754
- const sigMatch = content.match(/protected\s+\$signature\s*=\s*['"]([^'"]+)['"]/);
755
- const commandSignature = sigMatch ? sigMatch[1].split(/\s+/)[0] : this.toSnakeCase(className);
756
-
757
- const actionBody = this.extractActionBody(content, "handle");
758
- const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
759
-
760
- const chain: ExecutionChainNode[] = [
761
- {
762
- stage: "ingress",
763
- symbol: `CLI ${commandSignature}`,
764
- file: path.relative(this.projectRoot, fullPath),
765
- description: `Console Command: ${commandSignature}`,
766
- },
767
- {
768
- stage: "controller",
769
- symbol: `${className}::handle`,
770
- file: path.relative(this.projectRoot, fullPath),
771
- description: "Command Execution Handler",
772
- mutations: behavior.mutations.length ? behavior.mutations : undefined,
773
- transactions: behavior.hasTransaction,
774
- },
775
- ];
776
-
777
- if (behavior.hasTransaction) {
778
- chain.push({
779
- stage: "transaction",
780
- symbol: "DB::transaction",
781
- description: "Database Transaction Scope",
782
- transactions: true,
783
- });
784
- }
785
-
786
- for (const job of behavior.dispatchedJobs) {
787
- const jobFile = this.findClassFile("Jobs", job);
788
- chain.push({
789
- stage: "job",
790
- symbol: job,
791
- file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
792
- description: "Dispatched Background Worker",
793
- dispatches: [job],
794
- });
795
- }
796
-
797
- slices.push({
798
- domain_id: domainId ?? null,
799
- feature_key: `command:${commandSignature}`,
800
- http_method: "CLI",
801
- route_uri: `command:${commandSignature}`,
802
- route_name: `cli.${commandSignature}`,
803
- controller_class: className,
804
- action_name: "handle",
805
- controller_file: path.relative(this.projectRoot, fullPath),
806
- controller_line: 1,
807
- architecture_style: "clean",
808
- entry_kind: "scheduled_command",
809
- execution_chain_json: JSON.stringify(chain),
810
- });
811
- }
812
-
813
- return slices;
814
- }
815
-
816
- private extractListenerSlices(
817
- root: string,
818
- domainId?: number
819
- ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
820
- const listenersDir = path.join(root, "app/Listeners");
821
- if (!fs.existsSync(listenersDir)) return [];
822
-
823
- const files = fs.readdirSync(listenersDir).filter((f) => f.endsWith(".php"));
824
- const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
825
-
826
- for (const file of files) {
827
- const fullPath = path.join(listenersDir, file);
828
- const content = fs.readFileSync(fullPath, "utf-8");
829
- const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
830
- if (!classMatch) continue;
831
-
832
- const className = classMatch[1];
833
- const actionBody = this.extractActionBody(content, "handle");
834
- const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
835
-
836
- const eventParamMatch = content.match(/public\s+function\s+handle\s*\(\s*([A-Za-z0-9_]+)\s+\$event\s*\)/i);
837
- const listenedEvent = eventParamMatch ? eventParamMatch[1] : undefined;
838
-
839
- const chain: ExecutionChainNode[] = [
840
- {
841
- stage: "ingress",
842
- symbol: `EVENT ${listenedEvent || className}`,
843
- file: path.relative(this.projectRoot, fullPath),
844
- description: `Event Listener Trigger${listenedEvent ? ` for [${listenedEvent}]` : ""}`,
845
- },
846
- {
847
- stage: "controller",
848
- symbol: `${className}::handle`,
849
- file: path.relative(this.projectRoot, fullPath),
850
- description: "Event Listener Handler",
851
- mutations: behavior.mutations.length ? behavior.mutations : undefined,
852
- transactions: behavior.hasTransaction,
853
- },
854
- ];
855
-
856
- if (behavior.hasTransaction) {
857
- chain.push({
858
- stage: "transaction",
859
- symbol: "DB::transaction",
860
- description: "Database Transaction Scope",
861
- transactions: true,
862
- });
863
- }
864
-
865
- for (const job of behavior.dispatchedJobs) {
866
- const jobFile = this.findClassFile("Jobs", job);
867
- chain.push({
868
- stage: "job",
869
- symbol: job,
870
- file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
871
- description: "Dispatched Background Worker",
872
- dispatches: [job],
873
- });
874
- }
875
-
876
- slices.push({
877
- domain_id: domainId ?? null,
878
- feature_key: `listener:${className}`,
879
- http_method: "EVENT",
880
- route_uri: `event:${className}`,
881
- route_name: `event.${this.toSnakeCase(className)}`,
882
- controller_class: className,
883
- action_name: "handle",
884
- controller_file: path.relative(this.projectRoot, fullPath),
885
- controller_line: 1,
886
- architecture_style: "clean",
887
- entry_kind: "event_listener",
888
- execution_chain_json: JSON.stringify(chain),
889
- });
890
- }
891
-
892
- return slices;
893
- }
894
-
895
- private toSnakeCase(str: string): string {
896
- return str
897
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
898
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
899
- .toLowerCase();
900
- }
901
- }
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExecutionChainNode, VerticalSliceRecord } from "../../../types/index.ts";
4
+ import { BehavioralAnalyzer } from "../behavioral-analyzer.ts";
5
+ import { blankCommentsAndStrings } from "../boundary-tracker.ts";
6
+ import { SchemaProviderRegistry } from "../schema/schema-provider-registry.ts";
7
+ import type {
8
+ SemanticSliceExtractor,
9
+ VerticalSliceCandidate,
10
+ } from "./semantic-extractor.interface.ts";
11
+
12
+ export interface ParsedRoute {
13
+ httpMethod: string;
14
+ uri: string;
15
+ routeName?: string;
16
+ controllerClass: string;
17
+ actionName: string;
18
+ file?: string;
19
+ }
20
+
21
+ export type LaravelSemanticExtractionResult = VerticalSliceCandidate[] & {
22
+ slices: VerticalSliceCandidate[];
23
+ };
24
+
25
+ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
26
+ public readonly id = "laravel";
27
+ public readonly name = "Laravel MVC Semantic Extractor";
28
+
29
+ constructor(private projectRoot: string = process.cwd()) {}
30
+
31
+ public canHandle(projectRoot: string, framework?: string): boolean {
32
+ if (framework === "laravel") return true;
33
+ return (
34
+ fs.existsSync(path.join(projectRoot, "artisan")) ||
35
+ fs.existsSync(path.join(projectRoot, "routes/web.php")) ||
36
+ fs.existsSync(path.join(projectRoot, "routes/api.php"))
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Scan route files and extract complete vertical slices.
42
+ */
43
+ public extractSlices(
44
+ projectRootOrDomainId?: string | number,
45
+ maybeDomainId?: number
46
+ ): LaravelSemanticExtractionResult {
47
+ let root = this.projectRoot;
48
+ let domainId: number | undefined;
49
+
50
+ if (typeof projectRootOrDomainId === "string") {
51
+ root = projectRootOrDomainId;
52
+ domainId = maybeDomainId;
53
+ } else if (typeof projectRootOrDomainId === "number") {
54
+ domainId = projectRootOrDomainId;
55
+ }
56
+
57
+ const routeFiles = [
58
+ path.join(root, "routes/web.php"),
59
+ path.join(root, "routes/api.php"),
60
+ ].filter((f) => fs.existsSync(f));
61
+
62
+ const parsedRoutes: ParsedRoute[] = [];
63
+
64
+ for (const routeFile of routeFiles) {
65
+ const content = fs.readFileSync(routeFile, "utf-8");
66
+ parsedRoutes.push(...this.parseRoutesContent(content));
67
+ }
68
+
69
+ const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
70
+
71
+ for (const route of parsedRoutes) {
72
+ const controllerInfo = this.resolveController(route.controllerClass, route.actionName);
73
+
74
+ let formRequestInfo: {
75
+ className: string;
76
+ filePath?: string;
77
+ rules: Record<string, string>;
78
+ } | null = null;
79
+
80
+ let modelInfo: {
81
+ className: string;
82
+ filePath?: string;
83
+ fillable: string[];
84
+ casts: Record<string, string>;
85
+ } | null = null;
86
+
87
+ let frontendInfo: {
88
+ target: string;
89
+ props: string[];
90
+ } | null = null;
91
+
92
+ let actionServices: Array<{
93
+ className: string;
94
+ filePath?: string;
95
+ isService: boolean;
96
+ }> = [];
97
+
98
+ let behavioralInfo: import("../behavioral-analyzer.ts").MethodBehavioralSummary | null = null;
99
+ if (controllerInfo.filePath && fs.existsSync(controllerInfo.filePath)) {
100
+ const controllerCode = fs.readFileSync(controllerInfo.filePath, "utf-8");
101
+ const actionBody = this.extractActionBody(controllerCode, route.actionName);
102
+ behavioralInfo = BehavioralAnalyzer.analyzeMethod(actionBody);
103
+
104
+ // 1. Detect FormRequest in method signature
105
+ const requestClassName = this.detectFormRequestClass(controllerCode, route.actionName);
106
+ if (requestClassName) {
107
+ const reqFile = this.findClassFile("Requests", requestClassName);
108
+ const rules = reqFile && fs.existsSync(reqFile) ? this.extractValidationRules(fs.readFileSync(reqFile, "utf-8")) : {};
109
+ formRequestInfo = {
110
+ className: requestClassName,
111
+ filePath: reqFile ? path.relative(this.projectRoot, reqFile) : undefined,
112
+ rules,
113
+ };
114
+ }
115
+
116
+ // 2. Detect Model referenced in parameters or action body
117
+ const modelClassName = this.detectModelClass(controllerCode, route.actionName, actionBody);
118
+ if (modelClassName) {
119
+ const modFile = this.findClassFile("Models", modelClassName);
120
+ const modMetadata = modFile && fs.existsSync(modFile) ? this.extractModelMetadata(fs.readFileSync(modFile, "utf-8")) : { fillable: [], casts: {} };
121
+ modelInfo = {
122
+ className: modelClassName,
123
+ filePath: modFile ? path.relative(this.projectRoot, modFile) : undefined,
124
+ fillable: modMetadata.fillable,
125
+ casts: modMetadata.casts,
126
+ };
127
+ }
128
+
129
+ // 3. Detect Inertia Render / View Target
130
+ frontendInfo = this.detectFrontendTarget(actionBody);
131
+
132
+ // 4. Detect Action & Service invocations
133
+ actionServices = this.detectActionAndServiceInvocations(
134
+ controllerCode,
135
+ route.actionName,
136
+ actionBody
137
+ );
138
+ }
139
+
140
+ const chain: ExecutionChainNode[] = [
141
+ {
142
+ stage: "ingress",
143
+ symbol: `${route.httpMethod.toUpperCase()} ${route.uri.startsWith("/") ? route.uri : `/${route.uri}`}`,
144
+ file: route.file,
145
+ description: `HTTP Route: ${route.routeName || route.uri}`,
146
+ },
147
+ ];
148
+
149
+ if (behavioralInfo && behavioralInfo.guards.length > 0) {
150
+ chain.push({
151
+ stage: "guard",
152
+ symbol: behavioralInfo.guards.join(", "),
153
+ description: "Authorization / Security Guard",
154
+ guards: behavioralInfo.guards,
155
+ });
156
+ }
157
+
158
+ if (formRequestInfo) {
159
+ chain.push({
160
+ stage: "validation",
161
+ symbol: formRequestInfo.className,
162
+ file: formRequestInfo.filePath,
163
+ description: "Form Request Validation",
164
+ });
165
+ }
166
+
167
+ chain.push({
168
+ stage: "controller",
169
+ symbol: `${route.controllerClass}::${route.actionName}`,
170
+ file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : undefined,
171
+ line: controllerInfo.line,
172
+ description: `Controller Action`,
173
+ guards: behavioralInfo && behavioralInfo.guards.length > 0 ? behavioralInfo.guards : undefined,
174
+ mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
175
+ transactions: behavioralInfo?.hasTransaction,
176
+ });
177
+
178
+ if (actionServices && actionServices.length > 0) {
179
+ for (const asItem of actionServices) {
180
+ chain.push({
181
+ stage: asItem.isService ? "service" : "action",
182
+ symbol: asItem.className,
183
+ file: asItem.filePath,
184
+ description: asItem.isService ? "Domain Service Invocation" : "Action Invocation",
185
+ });
186
+ }
187
+ }
188
+
189
+ if (behavioralInfo && behavioralInfo.hasTransaction) {
190
+ chain.push({
191
+ stage: "transaction",
192
+ symbol: "DB::transaction",
193
+ description: "Database Transaction Scope",
194
+ transactions: true,
195
+ });
196
+ }
197
+
198
+ if (modelInfo) {
199
+ const schema = SchemaProviderRegistry.resolveSchema(
200
+ root,
201
+ modelInfo.className,
202
+ modelInfo.filePath
203
+ );
204
+
205
+ const columnsSummary =
206
+ schema && schema.fields.length > 0
207
+ ? schema.fields.map((f) => `${f.name}:${f.type}${f.nullable ? "?" : ""}`).join(", ")
208
+ : undefined;
209
+
210
+ chain.push({
211
+ stage: "entity",
212
+ symbol: modelInfo.className,
213
+ file: modelInfo.filePath,
214
+ description: schema?.tableName ? `Eloquent Model (${schema.tableName})` : "Eloquent Model",
215
+ table: schema?.tableName,
216
+ schema_file: schema?.schemaSourceFile,
217
+ columns_summary: columnsSummary,
218
+ mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
219
+ });
220
+ }
221
+
222
+ if (behavioralInfo && behavioralInfo.dispatchedJobs.length > 0) {
223
+ for (const job of behavioralInfo.dispatchedJobs) {
224
+ const jobFile = this.findClassFile("Jobs", job);
225
+ chain.push({
226
+ stage: "job",
227
+ symbol: job,
228
+ file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
229
+ description: "Background Queue Job Dispatched",
230
+ dispatches: [job],
231
+ });
232
+ }
233
+ }
234
+
235
+ if (behavioralInfo && behavioralInfo.emittedEvents.length > 0) {
236
+ for (const evt of behavioralInfo.emittedEvents) {
237
+ const evtFile = this.findClassFile("Events", evt);
238
+ chain.push({
239
+ stage: "event",
240
+ symbol: evt,
241
+ file: evtFile ? path.relative(this.projectRoot, evtFile) : undefined,
242
+ description: "Domain Event Emitted",
243
+ emits: [evt],
244
+ });
245
+ }
246
+ }
247
+
248
+ if (frontendInfo) {
249
+ chain.push({
250
+ stage: "egress",
251
+ symbol: frontendInfo.target,
252
+ description: "Inertia / Frontend Target",
253
+ payload_props: frontendInfo.props.length > 0 ? frontendInfo.props : undefined,
254
+ });
255
+ }
256
+
257
+ slices.push({
258
+ domain_id: domainId ?? null,
259
+ feature_key: route.routeName || null,
260
+ http_method: route.httpMethod.toUpperCase(),
261
+ route_uri: route.uri.startsWith("/") ? route.uri : `/${route.uri}`,
262
+ route_name: route.routeName || null,
263
+ controller_class: route.controllerClass,
264
+ action_name: route.actionName,
265
+ controller_file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : null,
266
+ controller_line: controllerInfo.line,
267
+ architecture_style: "mvc",
268
+ entry_kind: "http_route",
269
+ execution_chain_json: JSON.stringify(chain),
270
+ });
271
+ }
272
+
273
+ // Also discover Omni-Trigger slices (Jobs, Console Commands, Event Listeners)
274
+ slices.push(...this.extractJobSlices(root, domainId));
275
+ slices.push(...this.extractCommandSlices(root, domainId));
276
+ slices.push(...this.extractListenerSlices(root, domainId));
277
+
278
+ return Object.assign(slices, { slices });
279
+ }
280
+
281
+ /**
282
+ * Parse Laravel Route declarations.
283
+ */
284
+ public parseRoutesContent(content: string): ParsedRoute[] {
285
+ const routes: ParsedRoute[] = [];
286
+
287
+ // 1. Process Route::resource
288
+ const resourceRegex = /Route::resource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
289
+ let resMatch;
290
+ while ((resMatch = resourceRegex.exec(content)) !== null) {
291
+ const baseUri = resMatch[1].replace(/^\//, "");
292
+ const controllerClass = resMatch[2];
293
+ const resourceActions = [
294
+ { method: "GET", sub: "", action: "index" },
295
+ { method: "GET", sub: "/create", action: "create" },
296
+ { method: "POST", sub: "", action: "store" },
297
+ { method: "GET", sub: "/{id}", action: "show" },
298
+ { method: "GET", sub: "/{id}/edit", action: "edit" },
299
+ { method: "PUT", sub: "/{id}", action: "update" },
300
+ { method: "DELETE", sub: "/{id}", action: "destroy" },
301
+ ];
302
+
303
+ for (const res of resourceActions) {
304
+ routes.push({
305
+ httpMethod: res.method,
306
+ uri: `/${baseUri}${res.sub}`,
307
+ routeName: `${baseUri}.${res.action}`,
308
+ controllerClass,
309
+ actionName: res.action,
310
+ });
311
+ }
312
+ }
313
+
314
+ // 2. Parse routes with group context tracking (prefix, controller, name prefix)
315
+ const lines = content.split(/\r?\n/);
316
+ const cleanLines = blankCommentsAndStrings(content, { hashComments: true }).split(/\r?\n/);
317
+ interface GroupContext {
318
+ prefix: string;
319
+ controller: string;
320
+ namePrefix: string;
321
+ braceDepth: number;
322
+ }
323
+
324
+ const groupStack: GroupContext[] = [];
325
+ let currentBraceDepth = 0;
326
+ let statementBuffer = "";
327
+ let inStatement = false;
328
+
329
+ for (let i = 0; i < lines.length; i++) {
330
+ const line = lines[i];
331
+ const cleanLine = cleanLines[i] ?? "";
332
+ const cleanTrimmed = cleanLine.trim();
333
+ const trimmed = line.trim();
334
+
335
+ if (!cleanTrimmed) continue;
336
+
337
+ // Check group opens: Route::...group(
338
+ if (cleanTrimmed.includes("Route::") && cleanTrimmed.includes("group(") && cleanTrimmed.includes("function")) {
339
+ const prefixMatch = /prefix\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
340
+ const controllerMatch = /controller\s*\(\s*([\\A-Za-z0-9_]+)::class\s*\)/.exec(trimmed);
341
+ const nameMatch = /name\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
342
+
343
+ const currentCtx = groupStack[groupStack.length - 1];
344
+ const newPrefix = [currentCtx?.prefix, prefixMatch ? prefixMatch[1] : ""]
345
+ .filter(Boolean)
346
+ .join("/");
347
+ const newController = controllerMatch ? controllerMatch[1] : (currentCtx?.controller || "");
348
+ const newNamePrefix = [currentCtx?.namePrefix, nameMatch ? nameMatch[1] : ""]
349
+ .filter(Boolean)
350
+ .join("");
351
+
352
+ groupStack.push({
353
+ prefix: newPrefix,
354
+ controller: newController,
355
+ namePrefix: newNamePrefix,
356
+ braceDepth: currentBraceDepth,
357
+ });
358
+ }
359
+
360
+ // Track brace depth on string/comment-stripped line so '/orders/{id}' never corrupts braceDepth
361
+ for (const char of cleanLine) {
362
+ if (char === "{") currentBraceDepth++;
363
+ if (char === "}") {
364
+ currentBraceDepth--;
365
+ if (groupStack.length > 0) {
366
+ const top = groupStack[groupStack.length - 1];
367
+ if (currentBraceDepth <= top.braceDepth) {
368
+ groupStack.pop();
369
+ }
370
+ }
371
+ }
372
+ }
373
+
374
+ // Route statement accumulation across lines
375
+ if (!inStatement && cleanTrimmed.startsWith("Route::") && !cleanTrimmed.includes("Route::resource") && !cleanTrimmed.includes("Route::group") && !(cleanTrimmed.includes("group(") && cleanTrimmed.includes("function"))) {
376
+ statementBuffer = trimmed;
377
+ inStatement = true;
378
+ } else if (inStatement) {
379
+ statementBuffer += " " + trimmed;
380
+ }
381
+
382
+ if (inStatement && cleanLine.includes(";")) {
383
+ inStatement = false;
384
+ const stmt = statementBuffer;
385
+ statementBuffer = "";
386
+
387
+ const currentCtx = groupStack[groupStack.length - 1];
388
+ const parsed = this.parseSingleRouteStatement(stmt, currentCtx);
389
+ if (parsed) {
390
+ routes.push(parsed);
391
+ }
392
+ }
393
+ }
394
+
395
+ return routes;
396
+ }
397
+
398
+ private parseSingleRouteStatement(
399
+ stmt: string,
400
+ ctx?: { prefix: string; controller: string; namePrefix: string }
401
+ ): ParsedRoute | null {
402
+ const methodMatch = /Route::(get|post|put|patch|delete|any|options)\s*\(\s*['"]([^'"]+)['"]([\s\S]*)/i.exec(stmt);
403
+ if (!methodMatch) {
404
+ const viewMatch = /Route::view\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/i.exec(stmt);
405
+ if (viewMatch) {
406
+ const rawUri = viewMatch[1];
407
+ const viewTarget = viewMatch[2];
408
+ const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
409
+ const fullUri = ctx?.prefix ? `/${ctx.prefix.replace(/^\/|\/$/g, "")}/${rawUri.replace(/^\//, "")}` : rawUri;
410
+ return {
411
+ httpMethod: "GET",
412
+ uri: fullUri.startsWith("/") ? fullUri : `/${fullUri}`,
413
+ routeName: (ctx?.namePrefix || "") + (nameMatch ? nameMatch[1] : ""),
414
+ controllerClass: "View",
415
+ actionName: viewTarget,
416
+ };
417
+ }
418
+ return null;
419
+ }
420
+
421
+ const httpMethod = methodMatch[1].toUpperCase();
422
+ let uri = methodMatch[2];
423
+ const rest = methodMatch[3];
424
+
425
+ if (ctx?.prefix) {
426
+ const cleanPrefix = ctx.prefix.replace(/^\/|\/$/g, "");
427
+ const cleanUri = uri.replace(/^\//, "");
428
+ uri = cleanUri ? `/${cleanPrefix}/${cleanUri}` : `/${cleanPrefix}`;
429
+ }
430
+ if (!uri.startsWith("/")) uri = `/${uri}`;
431
+
432
+ const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
433
+ const rawRouteName = nameMatch ? nameMatch[1] : undefined;
434
+ const fullRouteName = rawRouteName
435
+ ? (ctx?.namePrefix || "") + rawRouteName
436
+ : undefined;
437
+
438
+ // [Controller::class, 'action']
439
+ const arrayMatch = /\[\s*([\\A-Za-z0-9_]+)::class\s*,\s*['"]([A-Za-z0-9_]+)['"]\s*\]/.exec(rest);
440
+ if (arrayMatch) {
441
+ return {
442
+ httpMethod,
443
+ uri,
444
+ routeName: fullRouteName,
445
+ controllerClass: arrayMatch[1],
446
+ actionName: arrayMatch[2],
447
+ };
448
+ }
449
+
450
+ // 'Controller@action'
451
+ const stringActionMatch = /['"]([\\A-Za-z0-9_]+)@([A-Za-z0-9_]+)['"]/.exec(rest);
452
+ if (stringActionMatch) {
453
+ return {
454
+ httpMethod,
455
+ uri,
456
+ routeName: fullRouteName,
457
+ controllerClass: stringActionMatch[1],
458
+ actionName: stringActionMatch[2],
459
+ };
460
+ }
461
+
462
+ // Action inside controller group
463
+ if (ctx?.controller) {
464
+ const singleActionMatch = /,\s*['"]([A-Za-z0-9_]+)['"]/.exec(rest);
465
+ if (singleActionMatch) {
466
+ return {
467
+ httpMethod,
468
+ uri,
469
+ routeName: fullRouteName,
470
+ controllerClass: ctx.controller,
471
+ actionName: singleActionMatch[1],
472
+ };
473
+ }
474
+ }
475
+
476
+ // Invokable controller
477
+ const invokableMatch = /,\s*([\\A-Za-z0-9_]+)::class/.exec(rest);
478
+ if (invokableMatch) {
479
+ return {
480
+ httpMethod,
481
+ uri,
482
+ routeName: fullRouteName,
483
+ controllerClass: invokableMatch[1],
484
+ actionName: "__invoke",
485
+ };
486
+ }
487
+
488
+ // Closure
489
+ if (rest.includes("function")) {
490
+ return {
491
+ httpMethod,
492
+ uri,
493
+ routeName: fullRouteName,
494
+ controllerClass: "Closure",
495
+ actionName: "handle",
496
+ };
497
+ }
498
+
499
+ return null;
500
+ }
501
+
502
+ private resolveController(controllerClass: string, actionName: string): { filePath?: string; line: number } {
503
+ const simpleName = controllerClass.split(/\\|\//).pop() || controllerClass;
504
+ const candidates = [
505
+ path.join(this.projectRoot, `app/Http/Controllers/${simpleName}.php`),
506
+ path.join(this.projectRoot, `app/Http/Controllers/Api/${simpleName}.php`),
507
+ path.join(this.projectRoot, `app/Http/Controllers/Admin/${simpleName}.php`),
508
+ ];
509
+
510
+ for (const c of candidates) {
511
+ if (fs.existsSync(c)) {
512
+ const lines = fs.readFileSync(c, "utf-8").split("\n");
513
+ let targetLine = 1;
514
+ for (let i = 0; i < lines.length; i++) {
515
+ if (new RegExp(`function\\s+${actionName}\\s*\\(`, "i").test(lines[i])) {
516
+ targetLine = i + 1;
517
+ break;
518
+ }
519
+ }
520
+ return { filePath: c, line: targetLine };
521
+ }
522
+ }
523
+
524
+ return { line: 0 };
525
+ }
526
+
527
+ private extractActionBody(controllerCode: string, actionName: string): string {
528
+ const cleanCode = blankCommentsAndStrings(controllerCode, { hashComments: true });
529
+ const fnRegex = new RegExp(`(?:public\\s+)?function\\s+${actionName}\\s*\\([^{]*\\)\\s*\\{`, "i");
530
+ const match = fnRegex.exec(cleanCode);
531
+ if (!match) return "";
532
+
533
+ const startIndex = match.index + match[0].length;
534
+ let braceDepth = 1;
535
+ let endIndex = startIndex;
536
+
537
+ while (braceDepth > 0 && endIndex < cleanCode.length) {
538
+ const char = cleanCode[endIndex];
539
+ if (char === "{") braceDepth++;
540
+ else if (char === "}") braceDepth--;
541
+ endIndex++;
542
+ }
543
+
544
+ return controllerCode.substring(startIndex, endIndex - 1);
545
+ }
546
+
547
+ private detectFormRequestClass(controllerCode: string, actionName: string): string | null {
548
+ const paramRegex = new RegExp(`public\\s+function\\s+${actionName}\\s*\\(([^)]*)\\)`, "i");
549
+ const match = paramRegex.exec(controllerCode);
550
+ if (!match) return null;
551
+
552
+ const params = match[1];
553
+ // Find class names ending with Request
554
+ const reqMatch = params.match(/([A-Za-z0-9_]+Request)\s+\$/);
555
+ if (reqMatch && reqMatch[1] !== "Request") {
556
+ return reqMatch[1];
557
+ }
558
+ return null;
559
+ }
560
+
561
+ private detectModelClass(controllerCode: string, actionName: string, actionBody: string): string | null {
562
+ // 1. Method signature type-hints: (Order $order)
563
+ const paramRegex = new RegExp(`public\\s+function\\s+${actionName}\\s*\\(([^)]*)\\)`, "i");
564
+ const match = paramRegex.exec(controllerCode);
565
+ if (match) {
566
+ const parts = match[1].split(",");
567
+ for (const p of parts) {
568
+ const pMatch = p.trim().match(/^([A-Z][A-Za-z0-9_]+)\s+\$/);
569
+ if (
570
+ pMatch &&
571
+ !pMatch[1].endsWith("Request") &&
572
+ pMatch[1] !== "Request" &&
573
+ !/(Action|Service|UseCase)$/i.test(pMatch[1])
574
+ ) {
575
+ return pMatch[1];
576
+ }
577
+ }
578
+ }
579
+
580
+ // 2. Action body static calls: Order::find(), Order::create(), Order::query()
581
+ const staticModelMatch = actionBody.match(/([A-Z][A-Za-z0-9_]+)::(?:find|findOrFail|create|where|query)\s*\(/);
582
+ if (staticModelMatch && !["Inertia", "Route", "DB", "Auth", "Log", "Response"].includes(staticModelMatch[1])) {
583
+ return staticModelMatch[1];
584
+ }
585
+
586
+ return null;
587
+ }
588
+
589
+ private detectFrontendTarget(actionBody: string): { target: string; props: string[] } | null {
590
+ // 1. Inertia::render('Orders/Show', ['order' => $order])
591
+ const inertiaMatch = actionBody.match(/Inertia::render\s*\(\s*['"]([^'"]+)['"](?:\s*,\s*\[([\s\S]*?)\])?\s*\)/);
592
+ if (inertiaMatch) {
593
+ const pageComponent = inertiaMatch[1]; // e.g. "Orders/Show"
594
+ const rawProps = inertiaMatch[2] || "";
595
+
596
+ // Extract prop keys: 'order' => ... or "order" => ... or order => ...
597
+ const propMatches = rawProps.matchAll(/['"]?([A-Za-z0-9_]+)['"]?\s*=>/g);
598
+ const props: string[] = [];
599
+ for (const pm of propMatches) {
600
+ if (!props.includes(pm[1])) {
601
+ props.push(pm[1]);
602
+ }
603
+ }
604
+
605
+ // Check for Vue, TSX, JSX files in resources/js/Pages
606
+ const possibleExtensions = [".vue", ".tsx", ".jsx", ".svelte"];
607
+ let frontendPath = `resources/js/Pages/${pageComponent}`;
608
+ for (const ext of possibleExtensions) {
609
+ const fullCandidate = path.join(this.projectRoot, `resources/js/Pages/${pageComponent}${ext}`);
610
+ if (fs.existsSync(fullCandidate)) {
611
+ frontendPath = `resources/js/Pages/${pageComponent}${ext}`;
612
+ break;
613
+ }
614
+ }
615
+ if (!frontendPath.includes(".")) {
616
+ frontendPath += ".vue"; // Default inertia convention
617
+ }
618
+
619
+ return {
620
+ target: frontendPath,
621
+ props,
622
+ };
623
+ }
624
+
625
+ // 2. view('orders.show', compact('order'))
626
+ const viewMatch = actionBody.match(/view\s*\(\s*['"]([^'"]+)['"]/);
627
+ if (viewMatch) {
628
+ const viewPath = viewMatch[1].replace(/\./g, "/");
629
+ return {
630
+ target: `resources/views/${viewPath}.blade.php`,
631
+ props: [],
632
+ };
633
+ }
634
+
635
+ return null;
636
+ }
637
+
638
+ private detectActionAndServiceInvocations(
639
+ controllerCode: string,
640
+ actionName: string,
641
+ actionBody: string
642
+ ): Array<{
643
+ className: string;
644
+ filePath?: string;
645
+ isService: boolean;
646
+ }> {
647
+ const detected = new Map<string, { className: string; filePath?: string; isService: boolean }>();
648
+
649
+ // 1. Check method parameters of actionName
650
+ const methodRegex = new RegExp(
651
+ `(?:public|protected|private)?\\s*function\\s+${actionName}\\s*\\(([^)]*)\\)`,
652
+ "i"
653
+ );
654
+ const methodMatch = controllerCode.match(methodRegex);
655
+ if (methodMatch && methodMatch[1]) {
656
+ const params = methodMatch[1].split(",");
657
+ for (const param of params) {
658
+ const cleanParam = param.trim().replace(/^(?:public|protected|private)?\s*(?:readonly)?\s*/i, "").trim();
659
+ const parts = cleanParam.split(/\s+/);
660
+ if (parts.length >= 2) {
661
+ const typehint = parts[0].replace(/^\\/, "").trim();
662
+ if (/(Action|Service|UseCase)$/i.test(typehint)) {
663
+ const shortName = typehint.split("\\").pop() || typehint;
664
+ const isService = /Service$/i.test(shortName);
665
+ const folder = isService ? "Services" : "Actions";
666
+ const file = this.findClassFile(folder, shortName);
667
+ detected.set(shortName, {
668
+ className: shortName,
669
+ filePath: file ? path.relative(this.projectRoot, file) : undefined,
670
+ isService,
671
+ });
672
+ }
673
+ }
674
+ }
675
+ }
676
+
677
+ // 2. Check constructor injection
678
+ const ctorMatch = controllerCode.match(/function\s+__construct\s*\(([^)]*)\)/i);
679
+ if (ctorMatch && ctorMatch[1]) {
680
+ const params = ctorMatch[1].split(",");
681
+ for (const param of params) {
682
+ const cleanParam = param.trim().replace(/^(?:public|protected|private)?\s*(?:readonly)?\s*/i, "").trim();
683
+ const parts = cleanParam.split(/\s+/);
684
+ if (parts.length >= 2) {
685
+ const typehint = parts[0].replace(/^\\/, "").trim();
686
+ if (/(Action|Service|UseCase)$/i.test(typehint)) {
687
+ const shortName = typehint.split("\\").pop() || typehint;
688
+ const isService = /Service$/i.test(shortName);
689
+ const propName = shortName.charAt(0).toLowerCase() + shortName.slice(1);
690
+ if (
691
+ actionBody.includes(shortName) ||
692
+ actionBody.includes(`$this->${propName}`) ||
693
+ actionBody.toLowerCase().includes(propName.toLowerCase())
694
+ ) {
695
+ const folder = isService ? "Services" : "Actions";
696
+ const file = this.findClassFile(folder, shortName);
697
+ detected.set(shortName, {
698
+ className: shortName,
699
+ filePath: file ? path.relative(this.projectRoot, file) : undefined,
700
+ isService,
701
+ });
702
+ }
703
+ }
704
+ }
705
+ }
706
+ }
707
+
708
+ // 3. Check static calls or class instantiations inside actionBody
709
+ const actionServicePattern = /\b([A-Z][a-zA-Z0-9_]*(?:Action|Service|UseCase))\b(?:::|::class|\s*\(|\s*;)/g;
710
+ let match: RegExpExecArray | null;
711
+ while ((match = actionServicePattern.exec(actionBody)) !== null) {
712
+ const cls = match[1];
713
+ if (!detected.has(cls)) {
714
+ const isService = /Service$/i.test(cls);
715
+ const folder = isService ? "Services" : "Actions";
716
+ const file = this.findClassFile(folder, cls);
717
+ detected.set(cls, {
718
+ className: cls,
719
+ filePath: file ? path.relative(this.projectRoot, file) : undefined,
720
+ isService,
721
+ });
722
+ }
723
+ }
724
+
725
+ // 4. Also scan 'use' imports in controller for App\Actions\... or App\Services\...
726
+ const usePattern = /use\s+App\\(Actions|Services)\\(?:[a-zA-Z0-9_\\]+\\)?([A-Z][a-zA-Z0-9_]*);/g;
727
+ while ((match = usePattern.exec(controllerCode)) !== null) {
728
+ const folder = match[1];
729
+ const cls = match[2];
730
+ if (actionBody.includes(cls) && !detected.has(cls)) {
731
+ const isService = folder === "Services" || /Service$/i.test(cls);
732
+ const file = this.findClassFile(folder, cls);
733
+ detected.set(cls, {
734
+ className: cls,
735
+ filePath: file ? path.relative(this.projectRoot, file) : undefined,
736
+ isService,
737
+ });
738
+ }
739
+ }
740
+
741
+ return Array.from(detected.values());
742
+ }
743
+
744
+ private findClassFile(
745
+ subDir: "Requests" | "Models" | "Jobs" | "Events" | "Listeners" | "Console/Commands" | "Actions" | "Services" | string,
746
+ className: string
747
+ ): string | null {
748
+ const directPath = path.join(this.projectRoot, `app/${subDir}/${className}.php`);
749
+ if (fs.existsSync(directPath)) return directPath;
750
+
751
+ // Direct app/ fallback for older Laravel
752
+ const flatPath = path.join(this.projectRoot, `app/${className}.php`);
753
+ if (fs.existsSync(flatPath)) return flatPath;
754
+
755
+ return null;
756
+ }
757
+
758
+ private extractValidationRules(requestCode: string): Record<string, string> {
759
+ const rules: Record<string, string> = {};
760
+ const body = this.extractActionBody(requestCode, "rules");
761
+ if (!body) return rules;
762
+
763
+ // Match 'status' => 'in:pending,paid' or 'status' => ['required', 'string']
764
+ const rulePairRegex = /['"]([A-Za-z0-9_]+)['"]\s*=>\s*(?:['"]([^'"]+)['"]|\[([^\]]+)\])/g;
765
+ let rm;
766
+ while ((rm = rulePairRegex.exec(body)) !== null) {
767
+ const field = rm[1];
768
+ const singleRule = rm[2];
769
+ const arrayRules = rm[3];
770
+ if (singleRule) {
771
+ rules[field] = singleRule;
772
+ } else if (arrayRules) {
773
+ rules[field] = arrayRules.replace(/['"\s]/g, "").replace(/,/g, "|");
774
+ }
775
+ }
776
+
777
+ return rules;
778
+ }
779
+
780
+ private extractModelMetadata(modelCode: string): { fillable: string[]; casts: Record<string, string> } {
781
+ const fillable: string[] = [];
782
+ const casts: Record<string, string> = {};
783
+
784
+ // Match protected $fillable = [...]
785
+ const fillableMatch = modelCode.match(/\$fillable\s*=\s*\[([^\]]*)\]/);
786
+ if (fillableMatch) {
787
+ const items = fillableMatch[1].matchAll(/['"]([A-Za-z0-9_]+)['"]/g);
788
+ for (const it of items) {
789
+ fillable.push(it[1]);
790
+ }
791
+ }
792
+
793
+ // Match protected $casts = [...]
794
+ const castsMatch = modelCode.match(/\$casts\s*=\s*\[([^\]]*)\]/);
795
+ if (castsMatch) {
796
+ const castItems = castsMatch[1].matchAll(/['"]([A-Za-z0-9_]+)['"]\s*=>\s*(?:['"]([^'"]+)['"]|([A-Za-z0-9_]+)::class)/g);
797
+ for (const ci of castItems) {
798
+ casts[ci[1]] = ci[2] || ci[3];
799
+ }
800
+ }
801
+
802
+ return { fillable, casts };
803
+ }
804
+
805
+ private extractJobSlices(
806
+ root: string,
807
+ domainId?: number
808
+ ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
809
+ const jobsDir = path.join(root, "app/Jobs");
810
+ if (!fs.existsSync(jobsDir)) return [];
811
+
812
+ const jobFiles = fs.readdirSync(jobsDir).filter((f) => f.endsWith(".php"));
813
+ const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
814
+
815
+ for (const file of jobFiles) {
816
+ const fullPath = path.join(jobsDir, file);
817
+ const content = fs.readFileSync(fullPath, "utf-8");
818
+ const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
819
+ if (!classMatch) continue;
820
+
821
+ const className = classMatch[1];
822
+ const actionBody = this.extractActionBody(content, "handle");
823
+ const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
824
+
825
+ const chain: ExecutionChainNode[] = [
826
+ {
827
+ stage: "ingress",
828
+ symbol: `JOB ${className}`,
829
+ file: path.relative(this.projectRoot, fullPath),
830
+ description: `Queue Worker Trigger: ${className}`,
831
+ },
832
+ {
833
+ stage: "controller",
834
+ symbol: `${className}::handle`,
835
+ file: path.relative(this.projectRoot, fullPath),
836
+ description: "Queue Job Handler",
837
+ mutations: behavior.mutations.length ? behavior.mutations : undefined,
838
+ transactions: behavior.hasTransaction,
839
+ },
840
+ ];
841
+
842
+ if (behavior.hasTransaction) {
843
+ chain.push({
844
+ stage: "transaction",
845
+ symbol: "DB::transaction",
846
+ description: "Database Transaction Scope",
847
+ transactions: true,
848
+ });
849
+ }
850
+
851
+ for (const evt of behavior.emittedEvents) {
852
+ const evtFile = this.findClassFile("Events", evt);
853
+ chain.push({
854
+ stage: "event",
855
+ symbol: evt,
856
+ file: evtFile ? path.relative(this.projectRoot, evtFile) : undefined,
857
+ description: "Domain Event Emitted",
858
+ emits: [evt],
859
+ });
860
+ }
861
+
862
+ slices.push({
863
+ domain_id: domainId ?? null,
864
+ feature_key: `job:${className}`,
865
+ http_method: "JOB",
866
+ route_uri: `job:${className}`,
867
+ route_name: `queue.${this.toSnakeCase(className)}`,
868
+ controller_class: className,
869
+ action_name: "handle",
870
+ controller_file: path.relative(this.projectRoot, fullPath),
871
+ controller_line: 1,
872
+ architecture_style: "clean",
873
+ entry_kind: "queue_job",
874
+ execution_chain_json: JSON.stringify(chain),
875
+ });
876
+ }
877
+
878
+ return slices;
879
+ }
880
+
881
+ private extractCommandSlices(
882
+ root: string,
883
+ domainId?: number
884
+ ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
885
+ const commandsDir = path.join(root, "app/Console/Commands");
886
+ if (!fs.existsSync(commandsDir)) return [];
887
+
888
+ const files = fs.readdirSync(commandsDir).filter((f) => f.endsWith(".php"));
889
+ const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
890
+
891
+ for (const file of files) {
892
+ const fullPath = path.join(commandsDir, file);
893
+ const content = fs.readFileSync(fullPath, "utf-8");
894
+ const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
895
+ if (!classMatch) continue;
896
+
897
+ const className = classMatch[1];
898
+ const sigMatch = content.match(/protected\s+\$signature\s*=\s*['"]([^'"]+)['"]/);
899
+ const commandSignature = sigMatch ? sigMatch[1].split(/\s+/)[0] : this.toSnakeCase(className);
900
+
901
+ const actionBody = this.extractActionBody(content, "handle");
902
+ const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
903
+
904
+ const chain: ExecutionChainNode[] = [
905
+ {
906
+ stage: "ingress",
907
+ symbol: `CLI ${commandSignature}`,
908
+ file: path.relative(this.projectRoot, fullPath),
909
+ description: `Console Command: ${commandSignature}`,
910
+ },
911
+ {
912
+ stage: "controller",
913
+ symbol: `${className}::handle`,
914
+ file: path.relative(this.projectRoot, fullPath),
915
+ description: "Command Execution Handler",
916
+ mutations: behavior.mutations.length ? behavior.mutations : undefined,
917
+ transactions: behavior.hasTransaction,
918
+ },
919
+ ];
920
+
921
+ if (behavior.hasTransaction) {
922
+ chain.push({
923
+ stage: "transaction",
924
+ symbol: "DB::transaction",
925
+ description: "Database Transaction Scope",
926
+ transactions: true,
927
+ });
928
+ }
929
+
930
+ for (const job of behavior.dispatchedJobs) {
931
+ const jobFile = this.findClassFile("Jobs", job);
932
+ chain.push({
933
+ stage: "job",
934
+ symbol: job,
935
+ file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
936
+ description: "Dispatched Background Worker",
937
+ dispatches: [job],
938
+ });
939
+ }
940
+
941
+ slices.push({
942
+ domain_id: domainId ?? null,
943
+ feature_key: `command:${commandSignature}`,
944
+ http_method: "CLI",
945
+ route_uri: `command:${commandSignature}`,
946
+ route_name: `cli.${commandSignature}`,
947
+ controller_class: className,
948
+ action_name: "handle",
949
+ controller_file: path.relative(this.projectRoot, fullPath),
950
+ controller_line: 1,
951
+ architecture_style: "clean",
952
+ entry_kind: "scheduled_command",
953
+ execution_chain_json: JSON.stringify(chain),
954
+ });
955
+ }
956
+
957
+ return slices;
958
+ }
959
+
960
+ private extractListenerSlices(
961
+ root: string,
962
+ domainId?: number
963
+ ): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
964
+ const listenersDir = path.join(root, "app/Listeners");
965
+ if (!fs.existsSync(listenersDir)) return [];
966
+
967
+ const files = fs.readdirSync(listenersDir).filter((f) => f.endsWith(".php"));
968
+ const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
969
+
970
+ for (const file of files) {
971
+ const fullPath = path.join(listenersDir, file);
972
+ const content = fs.readFileSync(fullPath, "utf-8");
973
+ const classMatch = content.match(/class\s+([A-Za-z0-9_]+)/);
974
+ if (!classMatch) continue;
975
+
976
+ const className = classMatch[1];
977
+ const actionBody = this.extractActionBody(content, "handle");
978
+ const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
979
+
980
+ const eventParamMatch = content.match(/public\s+function\s+handle\s*\(\s*([A-Za-z0-9_]+)\s+\$event\s*\)/i);
981
+ const listenedEvent = eventParamMatch ? eventParamMatch[1] : undefined;
982
+
983
+ const chain: ExecutionChainNode[] = [
984
+ {
985
+ stage: "ingress",
986
+ symbol: `EVENT ${listenedEvent || className}`,
987
+ file: path.relative(this.projectRoot, fullPath),
988
+ description: `Event Listener Trigger${listenedEvent ? ` for [${listenedEvent}]` : ""}`,
989
+ },
990
+ {
991
+ stage: "controller",
992
+ symbol: `${className}::handle`,
993
+ file: path.relative(this.projectRoot, fullPath),
994
+ description: "Event Listener Handler",
995
+ mutations: behavior.mutations.length ? behavior.mutations : undefined,
996
+ transactions: behavior.hasTransaction,
997
+ },
998
+ ];
999
+
1000
+ if (behavior.hasTransaction) {
1001
+ chain.push({
1002
+ stage: "transaction",
1003
+ symbol: "DB::transaction",
1004
+ description: "Database Transaction Scope",
1005
+ transactions: true,
1006
+ });
1007
+ }
1008
+
1009
+ for (const job of behavior.dispatchedJobs) {
1010
+ const jobFile = this.findClassFile("Jobs", job);
1011
+ chain.push({
1012
+ stage: "job",
1013
+ symbol: job,
1014
+ file: jobFile ? path.relative(this.projectRoot, jobFile) : undefined,
1015
+ description: "Dispatched Background Worker",
1016
+ dispatches: [job],
1017
+ });
1018
+ }
1019
+
1020
+ slices.push({
1021
+ domain_id: domainId ?? null,
1022
+ feature_key: `listener:${className}`,
1023
+ http_method: "EVENT",
1024
+ route_uri: `event:${className}`,
1025
+ route_name: `event.${this.toSnakeCase(className)}`,
1026
+ controller_class: className,
1027
+ action_name: "handle",
1028
+ controller_file: path.relative(this.projectRoot, fullPath),
1029
+ controller_line: 1,
1030
+ architecture_style: "clean",
1031
+ entry_kind: "event_listener",
1032
+ execution_chain_json: JSON.stringify(chain),
1033
+ });
1034
+ }
1035
+
1036
+ return slices;
1037
+ }
1038
+
1039
+ private toSnakeCase(str: string): string {
1040
+ return str
1041
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
1042
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
1043
+ .toLowerCase();
1044
+ }
1045
+ }