@dimassetoid/septum-mcp 0.3.0 → 0.5.1

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 (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +255 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -1,4 +1,4 @@
1
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
1
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
2
2
  import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
@@ -6,25 +6,22 @@ import { ImportResolver } from "../../resolver/import-resolver.ts";
6
6
  import type { ExecutionChainNode, VerticalSliceRecord } from "../../../types/index.ts";
7
7
  import { BehavioralAnalyzer, type MethodBehavioralSummary } from "../behavioral-analyzer.ts";
8
8
  import { blankCommentsAndStrings } from "../boundary-tracker.ts";
9
+ import { parseWithTreeSitter } from "../wasm-loader.ts";
10
+ import { readLaravelActions, readLaravelRoutes, type LaravelAction, type ParsedRoute } from "./laravel-routing.ts";
9
11
  import { SchemaProviderRegistry } from "../schema/schema-provider-registry.ts";
10
12
  import type {
11
13
  SemanticSliceExtractor,
12
14
  VerticalSliceCandidate,
13
15
  } from "./semantic-extractor.interface.ts";
14
16
 
15
- export interface ParsedRoute {
16
- httpMethod: string;
17
- uri: string;
18
- routeName?: string;
19
- controllerClass: string;
20
- actionName: string;
21
- file?: string;
22
- }
17
+ export type { ParsedRoute } from "./laravel-routing.ts";
23
18
 
24
19
  export type LaravelSemanticExtractionResult = VerticalSliceCandidate[] & {
25
20
  slices: VerticalSliceCandidate[];
26
21
  };
27
22
 
23
+ type ControllerDeclarations = { classes: Map<string, Map<string, LaravelAction>>; source: string };
24
+
28
25
  export class LaravelSemanticExtractor implements SemanticSliceExtractor {
29
26
  public readonly id = "laravel";
30
27
  public readonly name = "Laravel MVC Semantic Extractor";
@@ -41,14 +38,14 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
41
38
  }
42
39
 
43
40
  /**
44
- * Scan route files and extract complete vertical slices.
41
+ * Scan route files and build bounded vertical slices.
45
42
  */
46
- public extractSlices(
43
+ public async extractSlices(
47
44
  projectRootOrDomainId?: string | number,
48
45
  maybeDomainId?: number,
49
46
  signal?: AbortSignal,
50
47
  inventory?: SourceInventory
51
- ): LaravelSemanticExtractionResult {
48
+ ): Promise<LaravelSemanticExtractionResult> {
52
49
  // The registry reuses one adapter across workspaces. Keep helpers bound to
53
50
  // this invocation's root without mutating the shared adapter instance.
54
51
  if (typeof projectRootOrDomainId === "string" && (inventory || path.resolve(projectRootOrDomainId) !== path.resolve(this.projectRoot))) {
@@ -64,28 +61,41 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
64
61
  domainId = projectRootOrDomainId;
65
62
  }
66
63
 
67
- const routeFiles = [
64
+ const standardRouteFiles = [
68
65
  path.join(root, "routes/web.php"),
69
66
  path.join(root, "routes/api.php"),
70
67
  ].filter((f) => fs.existsSync(f) && (!this.inventory || this.inventory.files.includes(f)));
71
68
 
69
+ const discoveredRouteFiles = listSourceFiles(
70
+ root,
71
+ /(?:^|\/)(?:routes\/[^/]+\.php|[^/]+-routes\.php)$/i,
72
+ this.inventory
73
+ ).filter((f) => !/(?:^|\/)routes\/(?:console|channels)\.php$/i.test(f));
74
+
75
+ const routeFiles = [...new Set([...standardRouteFiles, ...discoveredRouteFiles])];
76
+ const includedFiles = new Set<string>();
72
77
  const parsedRoutes: ParsedRoute[] = [];
73
78
 
74
79
  for (const routeFile of routeFiles) {
75
80
  signal?.throwIfAborted();
81
+ if (includedFiles.has(path.resolve(routeFile))) continue;
76
82
  const content = readOptionalSourceFile(routeFile, "utf-8");
77
83
  const relativeRouteFile = path.relative(root, routeFile).replace(/\\/g, "/");
78
- const routesFromFile = this.parseRoutesContent(content);
84
+ const routesFromFile = await this.parseRoutesContentWithIncludes(content, routeFile, root, includedFiles, signal);
79
85
  for (const r of routesFromFile) {
80
- r.file = relativeRouteFile;
86
+ if (!r.file) r.file = relativeRouteFile;
81
87
  }
82
88
  parsedRoutes.push(...routesFromFile);
83
89
  }
84
90
 
85
91
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
86
92
 
93
+ const resolver = new ImportResolver(root);
94
+ const declarations = new Map<string, ControllerDeclarations>();
87
95
  for (const route of parsedRoutes) {
88
- const controllerInfo = this.resolveController(route.controllerClass, route.actionName, route.file);
96
+ signal?.throwIfAborted();
97
+ const controllerInfo = await this.resolveController(route, resolver, declarations);
98
+ signal?.throwIfAborted();
89
99
 
90
100
  let formRequestInfo: {
91
101
  className: string;
@@ -112,9 +122,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
112
122
  }> = [];
113
123
 
114
124
  let behavioralInfo: MethodBehavioralSummary | null = null;
115
- if (controllerInfo.filePath && fs.existsSync(controllerInfo.filePath)) {
116
- const controllerCode = readOptionalSourceFile(controllerInfo.filePath, "utf-8");
117
- const actionBody = this.extractActionBody(controllerCode, route.actionName);
125
+ if (controllerInfo.action) {
126
+ const controllerCode = controllerInfo.action.source;
127
+ const actionBody = controllerInfo.action.body;
118
128
  behavioralInfo = BehavioralAnalyzer.analyzeMethod(actionBody);
119
129
 
120
130
  // 1. Detect FormRequest in method signature
@@ -149,7 +159,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
149
159
  actionServices = this.detectActionAndServiceInvocations(
150
160
  controllerCode,
151
161
  route.actionName,
152
- actionBody
162
+ actionBody,
163
+ controllerInfo.constructorSource,
164
+ controllerInfo.fileSource
153
165
  );
154
166
  }
155
167
 
@@ -158,7 +170,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
158
170
  stage: "ingress",
159
171
  symbol: `${route.httpMethod.toUpperCase()} ${route.uri.startsWith("/") ? route.uri : `/${route.uri}`}`,
160
172
  file: route.file,
173
+ line: route.line,
161
174
  description: `HTTP Route: ${route.routeName || route.uri}`,
175
+ relationship: { kind: "declares", derivation: "source", reason: "Laravel facade call" },
162
176
  },
163
177
  ];
164
178
 
@@ -185,7 +199,10 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
185
199
  symbol: `${route.controllerClass}::${route.actionName}`,
186
200
  file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : undefined,
187
201
  line: controllerInfo.line,
188
- description: `Controller Action`,
202
+ description: controllerInfo.action || route.handlerLine ? "Controller Action" : "Declared Route Target",
203
+ ...(controllerInfo.action || route.handlerLine ? {
204
+ relationship: { kind: "route_binding", derivation: "source", reason: "Laravel route target" } as const,
205
+ } : {}),
189
206
  guards: behavioralInfo && behavioralInfo.guards.length > 0 ? behavioralInfo.guards : undefined,
190
207
  mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
191
208
  transactions: behavioralInfo?.hasTransaction,
@@ -294,326 +311,115 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
294
311
  return Object.assign(slices, { slices });
295
312
  }
296
313
 
297
- /**
298
- * Parse Laravel Route declarations.
299
- */
300
- public parseRoutesContent(content: string): ParsedRoute[] {
301
- const routes: ParsedRoute[] = [];
302
- const executable = blankCommentsAndStrings(content, { hashComments: true });
303
-
304
- // 1. Process Route::resource
305
- const resourceRegex = /Route::resource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
306
- let resMatch;
307
- while ((resMatch = resourceRegex.exec(content)) !== null) {
308
- if (executable.slice(resMatch.index, resMatch.index + "Route::resource".length).toLowerCase() !== "route::resource") continue;
309
- const baseUri = resMatch[1].replace(/^\//, "");
310
- const controllerClass = resMatch[2];
311
- const resourceActions = [
312
- { method: "GET", sub: "", action: "index" },
313
- { method: "GET", sub: "/create", action: "create" },
314
- { method: "POST", sub: "", action: "store" },
315
- { method: "GET", sub: "/{id}", action: "show" },
316
- { method: "GET", sub: "/{id}/edit", action: "edit" },
317
- { method: "PUT", sub: "/{id}", action: "update" },
318
- { method: "DELETE", sub: "/{id}", action: "destroy" },
319
- ];
320
-
321
- for (const res of resourceActions) {
322
- routes.push({
323
- httpMethod: res.method,
324
- uri: `/${baseUri}${res.sub}`,
325
- routeName: `${baseUri}.${res.action}`,
326
- controllerClass,
327
- actionName: res.action,
328
- });
329
- }
330
- }
331
-
332
- // 1b. Process Route::apiResource
333
- const apiResourceRegex = /Route::apiResource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
334
- let apiResMatch;
335
- while ((apiResMatch = apiResourceRegex.exec(content)) !== null) {
336
- if (executable.slice(apiResMatch.index, apiResMatch.index + "Route::apiResource".length).toLowerCase() !== "route::apiresource") continue;
337
- const baseUri = apiResMatch[1].replace(/^\//, "");
338
- const controllerClass = apiResMatch[2];
339
- const apiResourceActions = [
340
- { method: "GET", sub: "", action: "index" },
341
- { method: "POST", sub: "", action: "store" },
342
- { method: "GET", sub: "/{id}", action: "show" },
343
- { method: "PUT", sub: "/{id}", action: "update" },
344
- { method: "DELETE", sub: "/{id}", action: "destroy" },
345
- ];
346
-
347
- for (const res of apiResourceActions) {
348
- routes.push({
349
- httpMethod: res.method,
350
- uri: `/${baseUri}${res.sub}`,
351
- routeName: `${baseUri}.${res.action}`,
352
- controllerClass,
353
- actionName: res.action,
354
- });
355
- }
356
- }
357
-
358
- // 2. Parse routes with group context tracking (prefix, controller, name prefix)
359
- const lines = content.split(/\r?\n/);
360
- const cleanLines = blankCommentsAndStrings(content, { hashComments: true }).split(/\r?\n/);
361
- interface GroupContext {
362
- prefix: string;
363
- controller: string;
364
- namePrefix: string;
365
- braceDepth: number;
366
- }
367
-
368
- const groupStack: GroupContext[] = [];
369
- let currentBraceDepth = 0;
370
- let statementBuffer = "";
371
- let inStatement = false;
372
-
373
- for (let i = 0; i < lines.length; i++) {
374
- const line = lines[i];
375
- const cleanLine = cleanLines[i] ?? "";
376
- const cleanTrimmed = cleanLine.trim();
377
- const trimmed = line.trim();
378
-
379
- if (!cleanTrimmed) continue;
380
-
381
- // Check group opens: Route::...group(
382
- if (cleanTrimmed.includes("Route::") && cleanTrimmed.includes("group(") && cleanTrimmed.includes("function")) {
383
- const prefixMatch = /prefix\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
384
- const controllerMatch = /controller\s*\(\s*([\\A-Za-z0-9_]+)::class\s*\)/.exec(trimmed);
385
- const nameMatch = /name\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
386
-
387
- const currentCtx = groupStack[groupStack.length - 1];
388
- const newPrefix = [currentCtx?.prefix, prefixMatch ? prefixMatch[1] : ""]
389
- .filter(Boolean)
390
- .join("/");
391
- const newController = controllerMatch ? controllerMatch[1] : (currentCtx?.controller || "");
392
- const newNamePrefix = [currentCtx?.namePrefix, nameMatch ? nameMatch[1] : ""]
393
- .filter(Boolean)
394
- .join("");
395
-
396
- groupStack.push({
397
- prefix: newPrefix,
398
- controller: newController,
399
- namePrefix: newNamePrefix,
400
- braceDepth: currentBraceDepth,
401
- });
402
- }
403
-
404
- // Track brace depth on string/comment-stripped line so '/orders/{id}' never corrupts braceDepth
405
- for (const char of cleanLine) {
406
- if (char === "{") currentBraceDepth++;
407
- if (char === "}") {
408
- currentBraceDepth--;
409
- if (groupStack.length > 0) {
410
- const top = groupStack[groupStack.length - 1];
411
- if (currentBraceDepth <= top.braceDepth) {
412
- groupStack.pop();
413
- }
414
- }
415
- }
416
- }
417
-
418
- // Route statement accumulation across lines
419
- if (!inStatement && cleanTrimmed.startsWith("Route::") && !cleanTrimmed.includes("Route::resource") && !cleanTrimmed.includes("Route::group") && !(cleanTrimmed.includes("group(") && cleanTrimmed.includes("function"))) {
420
- statementBuffer = trimmed;
421
- inStatement = true;
422
- } else if (inStatement) {
423
- statementBuffer += " " + trimmed;
424
- }
425
-
426
- if (inStatement && cleanLine.includes(";")) {
427
- inStatement = false;
428
- const stmt = statementBuffer;
429
- statementBuffer = "";
430
-
431
- const currentCtx = groupStack[groupStack.length - 1];
432
- const parsed = this.parseSingleRouteStatement(stmt, currentCtx);
433
- if (parsed) {
434
- routes.push(parsed);
435
- }
436
- }
437
- }
438
-
314
+ public async parseRoutesContent(content: string, signal?: AbortSignal): Promise<ParsedRoute[]> {
315
+ if (!content.trim()) return [];
316
+ // Direct parser callers also supply PHP snippets without the opening tag.
317
+ const source = /^\s*<\?php\b/i.test(content) ? content : "<?php " + content;
318
+ const routes = await parseWithTreeSitter("php", source, root => readLaravelRoutes(root, signal));
319
+ signal?.throwIfAborted();
320
+ if (!routes) throw new Error("Laravel route AST extraction failed.");
439
321
  return routes;
440
322
  }
441
323
 
442
- private parseSingleRouteStatement(
443
- stmt: string,
444
- ctx?: { prefix: string; controller: string; namePrefix: string }
445
- ): ParsedRoute | null {
446
- const methodMatch = /Route::(get|post|put|patch|delete|any|options)\s*\(\s*['"]([^'"]+)['"]([\s\S]*)/i.exec(stmt);
447
- if (!methodMatch) {
448
- const viewMatch = /Route::view\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/i.exec(stmt);
449
- if (viewMatch) {
450
- const rawUri = viewMatch[1];
451
- const viewTarget = viewMatch[2];
452
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
453
- const fullUri = ctx?.prefix ? `/${ctx.prefix.replace(/^\/|\/$/g, "")}/${rawUri.replace(/^\//, "")}` : rawUri;
454
- return {
455
- httpMethod: "GET",
456
- uri: fullUri.startsWith("/") ? fullUri : `/${fullUri}`,
457
- routeName: (ctx?.namePrefix || "") + (nameMatch ? nameMatch[1] : ""),
458
- controllerClass: "View",
459
- actionName: viewTarget,
460
- };
461
- }
462
- return null;
463
- }
464
-
465
- const httpMethod = methodMatch[1].toUpperCase();
466
- let uri = methodMatch[2];
467
- const rest = methodMatch[3];
468
-
469
- if (ctx?.prefix) {
470
- const cleanPrefix = ctx.prefix.replace(/^\/|\/$/g, "");
471
- const cleanUri = uri.replace(/^\//, "");
472
- uri = cleanUri ? `/${cleanPrefix}/${cleanUri}` : `/${cleanPrefix}`;
473
- }
474
- if (!uri.startsWith("/")) uri = `/${uri}`;
475
-
476
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
477
- const rawRouteName = nameMatch ? nameMatch[1] : undefined;
478
- const fullRouteName = rawRouteName
479
- ? (ctx?.namePrefix || "") + rawRouteName
480
- : undefined;
481
-
482
- // [Controller::class, 'action']
483
- const arrayMatch = /\[\s*([\\A-Za-z0-9_]+)::class\s*,\s*['"]([A-Za-z0-9_]+)['"]\s*\]/.exec(rest);
484
- if (arrayMatch) {
485
- return {
486
- httpMethod,
487
- uri,
488
- routeName: fullRouteName,
489
- controllerClass: arrayMatch[1],
490
- actionName: arrayMatch[2],
491
- };
492
- }
493
-
494
- // 'Controller@action'
495
- const stringActionMatch = /['"]([\\A-Za-z0-9_]+)@([A-Za-z0-9_]+)['"]/.exec(rest);
496
- if (stringActionMatch) {
497
- return {
498
- httpMethod,
499
- uri,
500
- routeName: fullRouteName,
501
- controllerClass: stringActionMatch[1],
502
- actionName: stringActionMatch[2],
503
- };
504
- }
505
-
506
- // Action inside controller group
507
- if (ctx?.controller) {
508
- const singleActionMatch = /,\s*['"]([A-Za-z0-9_]+)['"]/.exec(rest);
509
- if (singleActionMatch) {
510
- return {
511
- httpMethod,
512
- uri,
513
- routeName: fullRouteName,
514
- controllerClass: ctx.controller,
515
- actionName: singleActionMatch[1],
516
- };
517
- }
518
- }
519
-
520
- // Invokable controller
521
- const invokableMatch = /,\s*([\\A-Za-z0-9_]+)::class/.exec(rest);
522
- if (invokableMatch) {
523
- return {
524
- httpMethod,
525
- uri,
526
- routeName: fullRouteName,
527
- controllerClass: invokableMatch[1],
528
- actionName: "__invoke",
529
- };
530
- }
531
-
532
- // Closure
533
- if (rest.includes("function")) {
534
- return {
535
- httpMethod,
536
- uri,
537
- routeName: fullRouteName,
538
- controllerClass: "Closure",
539
- actionName: "handle",
540
- };
541
- }
542
-
543
- return null;
544
- }
545
-
546
- private resolveController(
547
- controllerClass: string,
548
- actionName: string,
549
- routeFilePath?: string
550
- ): { filePath?: string; line: number } {
551
- let resolvedFilePath: string | undefined;
552
-
553
- // 1. Try ImportResolver via PSR-4 if routeFilePath or full namespace provided
554
- const resolver = new ImportResolver(this.projectRoot);
555
- const sourceRef = routeFilePath
556
- ? path.resolve(this.projectRoot, routeFilePath)
557
- : path.join(this.projectRoot, "routes/web.php");
558
-
559
- if (controllerClass.includes("\\")) {
560
- const res = resolver.resolve(controllerClass, sourceRef);
561
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
562
- resolvedFilePath = path.resolve(this.projectRoot, res.targets[0].files[0]);
563
- }
564
- if (!resolvedFilePath) return { line: 0 };
565
- } else if (routeFilePath && fs.existsSync(sourceRef)) {
566
- const routeContent = readOptionalSourceFile(sourceRef, "utf-8");
567
- const executable = blankCommentsAndStrings(routeContent, { hashComments: true });
568
- const bindings = [...executable.matchAll(/\buse\s+([\\A-Za-z0-9_]+)(?:\s+as\s+([A-Za-z0-9_]+))?\s*;/gi)]
569
- .filter(match => (match[2] || match[1]!.split("\\").pop())?.toLowerCase() === controllerClass.toLowerCase());
570
- if (bindings.length > 1) return { line: 0 };
571
- if (bindings.length === 1) {
572
- const fqn = bindings[0]![1]!;
573
- const res = resolver.resolve(fqn, sourceRef);
574
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
575
- resolvedFilePath = path.resolve(this.projectRoot, res.targets[0].files[0]);
576
- }
577
- // Existing source-only fixtures may omit composer.json. A conventional
578
- // App namespace maps to its exact conventional path, never the alias.
579
- if (!resolvedFilePath && !fs.existsSync(path.join(this.projectRoot, "composer.json")) && fqn.startsWith("App\\Http\\Controllers\\")) {
580
- const conventional = path.join(this.projectRoot, "app", fqn.slice(4).replace(/\\/g, "/") + ".php");
581
- if (fs.existsSync(conventional)) resolvedFilePath = conventional;
324
+ private async parseRoutesContentWithIncludes(
325
+ content: string,
326
+ routeFile: string,
327
+ projectRoot: string,
328
+ includedFiles: Set<string>,
329
+ signal?: AbortSignal,
330
+ visited = new Set<string>()
331
+ ): Promise<ParsedRoute[]> {
332
+ if (!content.trim()) return [];
333
+ const absRoute = path.resolve(routeFile);
334
+ if (visited.has(absRoute)) return [];
335
+ visited.add(absRoute);
336
+
337
+ const relRoute = path.relative(projectRoot, absRoute).replace(/\\/g, "/");
338
+ const pendingIncludes: Array<{ targetFile: string; prefix: string; name: string }> = [];
339
+ const source = /^\s*<\?php\b/i.test(content) ? content : "<?php " + content;
340
+ const routes = await parseWithTreeSitter("php", source, (root) =>
341
+ readLaravelRoutes(root, signal, (spec, group) => {
342
+ const cleaned = spec.replace(/^['"]|['"]$/g, "").trim();
343
+ if (!cleaned) return undefined;
344
+ const target = path.resolve(path.dirname(absRoute), cleaned);
345
+ if (probeSourcePath(target) === "file") {
346
+ pendingIncludes.push({ targetFile: target, prefix: group.prefix, name: group.name });
582
347
  }
583
- if (!resolvedFilePath) return { line: 0 };
584
- }
585
- }
586
-
587
- // 2. Fallback heuristics if not found via PSR-4
588
- if (!resolvedFilePath) {
589
- const simpleName = controllerClass.split(/\\|\//).pop() || controllerClass;
590
- const candidates = [
591
- path.join(this.projectRoot, `app/Http/Controllers/${simpleName}.php`),
592
- path.join(this.projectRoot, `app/Http/Controllers/Api/${simpleName}.php`),
593
- path.join(this.projectRoot, `app/Http/Controllers/Admin/${simpleName}.php`),
594
- ];
348
+ return undefined;
349
+ })
350
+ );
351
+ signal?.throwIfAborted();
352
+ if (!routes) throw new Error("Laravel route AST extraction failed.");
353
+ for (const r of routes) r.file = relRoute;
595
354
 
596
- for (const c of candidates) {
597
- if (fs.existsSync(c)) {
598
- resolvedFilePath = c;
599
- break;
600
- }
355
+ for (const inc of pendingIncludes) {
356
+ includedFiles.add(path.resolve(inc.targetFile));
357
+ const incContent = readOptionalSourceFile(inc.targetFile, "utf-8");
358
+ const incRoutes = await this.parseRoutesContentWithIncludes(incContent, inc.targetFile, projectRoot, includedFiles, signal, visited);
359
+ for (const r of incRoutes) {
360
+ const joinedUri = "/" + [inc.prefix, r.uri].map((v) => v.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
361
+ r.uri = joinedUri;
362
+ if (inc.name && r.routeName) r.routeName = inc.name + r.routeName;
363
+ routes.push(r);
601
364
  }
602
365
  }
603
366
 
604
- if (resolvedFilePath && fs.existsSync(resolvedFilePath)) {
605
- const lines = blankCommentsAndStrings(readOptionalSourceFile(resolvedFilePath, "utf-8"), { hashComments: true }).split("\n");
606
- let targetLine = 1;
607
- for (let i = 0; i < lines.length; i++) {
608
- if (new RegExp(`function\\s+${actionName}\\s*\\(`, "i").test(lines[i])) {
609
- targetLine = i + 1;
610
- break;
611
- }
612
- }
613
- return { filePath: resolvedFilePath, line: targetLine };
614
- }
367
+ return routes;
368
+ }
615
369
 
616
- return { line: 0 };
370
+ private async resolveController(
371
+ route: ParsedRoute,
372
+ resolver: ImportResolver,
373
+ declarations: Map<string, ControllerDeclarations>,
374
+ ): Promise<{ filePath?: string; line: number; action?: LaravelAction; constructorSource?: string; fileSource?: string }> {
375
+ if (route.handlerLine && route.file) {
376
+ return { filePath: path.join(this.projectRoot, route.file), line: route.handlerLine };
377
+ }
378
+ if (["Closure", "View"].includes(route.controllerClass) || route.controllerTarget === "") return { line: 0 };
379
+
380
+ const target = route.controllerTarget;
381
+ const shortName = (target ?? route.controllerClass).split("\\").at(-1)!;
382
+ let candidates: string[] = [];
383
+ if (target) {
384
+ const source = route.file ?? "routes/web.php";
385
+ const resolution = resolver.resolve(target, source);
386
+ if (resolution.status === "resolved") {
387
+ candidates = resolution.targets.flatMap(item => item.files).map(file => path.resolve(this.projectRoot, file));
388
+ } else if (resolution.reason === "php_namespace_not_mapped" && target.startsWith("App\\Http\\Controllers\\") &&
389
+ probeSourcePath(path.join(this.projectRoot, "composer.json")) === "missing") {
390
+ candidates = [path.join(this.projectRoot, "app", target.slice(4).replace(/\\/g, "/") + ".php")];
391
+ }
392
+ } else {
393
+ candidates = ["", "Api", "Admin"].map(directory =>
394
+ path.join(this.projectRoot, "app/Http/Controllers", directory, shortName + ".php"));
395
+ }
396
+ if (candidates.every((c) => probeSourcePath(c) !== "file") && this.inventory) {
397
+ const namespaceTail = (target ?? route.controllerClass).replace(/^\\/, "").replace(/\\/g, "/");
398
+ const tailMatches = this.inventory.files.filter(
399
+ (f) => f.endsWith(`/${namespaceTail}.php`) || f.endsWith(`/${shortName}.php`)
400
+ );
401
+ if (tailMatches.length > 0) candidates.push(...tailMatches);
402
+ }
403
+ const matches = [...new Set(candidates)].filter(file => probeSourcePath(file) === "file");
404
+ if (matches.length !== 1) return { line: 0 };
405
+ const filePath = matches[0]!;
406
+ let declaration = declarations.get(filePath);
407
+ if (!declaration) {
408
+ const source = readOptionalSourceFile(filePath, "utf-8");
409
+ const classes = await parseWithTreeSitter("php", source, readLaravelActions);
410
+ if (!classes) throw new Error("Laravel controller AST extraction failed for " + path.relative(this.projectRoot, filePath));
411
+ declaration = { classes, source };
412
+ declarations.set(filePath, declaration);
413
+ }
414
+ const { classes, source: fileSource } = declaration;
415
+ const targetKey = target?.toLowerCase();
416
+ const names = [...classes.keys()].filter(name => name.split("\\").at(-1) === shortName.toLowerCase());
417
+ const selected = targetKey
418
+ ? classes.get(targetKey)
419
+ : names.length === 1 ? classes.get(names[0]!) : undefined;
420
+ const action = selected?.get(route.actionName.toLowerCase());
421
+ if (!action) return { line: 0 };
422
+ return { filePath, line: action.line, action, constructorSource: selected?.get("__construct")?.source, fileSource };
617
423
  }
618
424
 
619
425
  private extractActionBody(controllerCode: string, actionName: string): string {
@@ -730,7 +536,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
730
536
  private detectActionAndServiceInvocations(
731
537
  controllerCode: string,
732
538
  actionName: string,
733
- actionBody: string
539
+ actionBody: string,
540
+ constructorSource?: string,
541
+ fileSource: string = controllerCode
734
542
  ): Array<{
735
543
  className: string;
736
544
  filePath?: string;
@@ -767,7 +575,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
767
575
  }
768
576
 
769
577
  // 2. Check constructor injection
770
- const ctorMatch = controllerCode.match(/function\s+__construct\s*\(([^)]*)\)/i);
578
+ const ctorMatch = constructorSource?.match(/function\s+__construct\s*\(([^)]*)\)/i);
771
579
  if (ctorMatch && ctorMatch[1]) {
772
580
  const params = ctorMatch[1].split(",");
773
581
  for (const param of params) {
@@ -816,7 +624,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
816
624
 
817
625
  // 4. Also scan 'use' imports in controller for App\Actions\... or App\Services\...
818
626
  const usePattern = /use\s+App\\(Actions|Services)\\(?:[a-zA-Z0-9_\\]+\\)?([A-Z][a-zA-Z0-9_]*);/g;
819
- while ((match = usePattern.exec(controllerCode)) !== null) {
627
+ while ((match = usePattern.exec(fileSource)) !== null) {
820
628
  const folder = match[1];
821
629
  const cls = match[2];
822
630
  if (actionBody.includes(cls) && !detected.has(cls)) {
@@ -0,0 +1,64 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
4
+
5
+ export function warnIfUnexpectedParserError(context: string, err: unknown): void {
6
+ const errno = (err as NodeJS.ErrnoException | undefined)?.code;
7
+ if (errno === "ENOENT" || errno === "ENOTDIR") return;
8
+ const msg = err instanceof Error ? err.message : String(err);
9
+ console.warn(`[Septum Extractor] ${context}: ${msg}`);
10
+ }
11
+
12
+ export function readPackageJson(projectRoot: string): Record<string, any> | null {
13
+ const manifestPath = path.join(projectRoot, "package.json");
14
+ if (probeSourcePath(manifestPath) !== "file") return null;
15
+ try {
16
+ return JSON.parse(readOptionalSourceFile(manifestPath, "utf-8"));
17
+ } catch (err: unknown) {
18
+ warnIfUnexpectedParserError(`Failed to parse ${manifestPath}`, err);
19
+ return null;
20
+ }
21
+ }
22
+
23
+ export function hasPackageJsonDependency(projectRoot: string, depNames: string[]): boolean {
24
+ const pkg = readPackageJson(projectRoot);
25
+ if (!pkg) return false;
26
+ return depNames.some(
27
+ (name) => Boolean(pkg.dependencies?.[name] || pkg.devDependencies?.[name])
28
+ );
29
+ }
30
+
31
+ export function hasComposerDependency(projectRoot: string, depNames: string[]): boolean {
32
+ const composerJson = path.join(projectRoot, "composer.json");
33
+ if (probeSourcePath(composerJson) !== "file") return false;
34
+ try {
35
+ const composer = JSON.parse(readOptionalSourceFile(composerJson, "utf-8"));
36
+ const reqs = { ...(composer.require ?? {}), ...(composer["require-dev"] ?? {}) };
37
+ return depNames.some((name) => Boolean(reqs[name]));
38
+ } catch (err: unknown) {
39
+ warnIfUnexpectedParserError(`Failed to parse ${composerJson}`, err);
40
+ return false;
41
+ }
42
+ }
43
+
44
+ export function anyFileContains(
45
+ rootDir: string,
46
+ relativePaths: string[],
47
+ needles: string[],
48
+ caseInsensitive = false
49
+ ): boolean {
50
+ for (const rel of relativePaths) {
51
+ const fullPath = path.join(rootDir, rel);
52
+ if (probeSourcePath(fullPath) !== "file") continue;
53
+ try {
54
+ const raw = readOptionalSourceFile(fullPath, "utf-8");
55
+ const content = caseInsensitive ? raw.toLowerCase() : raw;
56
+ if (needles.some((needle) => content.includes(needle))) {
57
+ return true;
58
+ }
59
+ } catch (err: unknown) {
60
+ warnIfUnexpectedParserError(`Failed to read ${fullPath}`, err);
61
+ }
62
+ }
63
+ return false;
64
+ }