@dimassetoid/septum-mcp 0.2.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  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 +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
@@ -1,34 +1,32 @@
1
- import { readOptionalSourceFile } from "../../resources/source-files.ts";
1
+ import { probeSourcePath, readOptionalSourceFile } from "../../resources/source-files.ts";
2
+ import { listSourceFiles, type SourceInventory } from "../../resources/source-inventory.ts";
2
3
  import * as fs from "node:fs";
3
4
  import * as path from "node:path";
4
5
  import { ImportResolver } from "../../resolver/import-resolver.ts";
5
6
  import type { ExecutionChainNode, VerticalSliceRecord } from "../../../types/index.ts";
6
7
  import { BehavioralAnalyzer, type MethodBehavioralSummary } from "../behavioral-analyzer.ts";
7
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";
8
11
  import { SchemaProviderRegistry } from "../schema/schema-provider-registry.ts";
9
12
  import type {
10
13
  SemanticSliceExtractor,
11
14
  VerticalSliceCandidate,
12
15
  } from "./semantic-extractor.interface.ts";
13
16
 
14
- export interface ParsedRoute {
15
- httpMethod: string;
16
- uri: string;
17
- routeName?: string;
18
- controllerClass: string;
19
- actionName: string;
20
- file?: string;
21
- }
17
+ export type { ParsedRoute } from "./laravel-routing.ts";
22
18
 
23
19
  export type LaravelSemanticExtractionResult = VerticalSliceCandidate[] & {
24
20
  slices: VerticalSliceCandidate[];
25
21
  };
26
22
 
23
+ type ControllerDeclarations = { classes: Map<string, Map<string, LaravelAction>>; source: string };
24
+
27
25
  export class LaravelSemanticExtractor implements SemanticSliceExtractor {
28
26
  public readonly id = "laravel";
29
27
  public readonly name = "Laravel MVC Semantic Extractor";
30
28
 
31
- constructor(private projectRoot: string = process.cwd()) {}
29
+ constructor(private projectRoot: string = process.cwd(), private inventory?: SourceInventory) {}
32
30
 
33
31
  public canHandle(projectRoot: string, framework?: string): boolean {
34
32
  if (framework === "laravel") return true;
@@ -40,12 +38,19 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
40
38
  }
41
39
 
42
40
  /**
43
- * Scan route files and extract complete vertical slices.
41
+ * Scan route files and build bounded vertical slices.
44
42
  */
45
- public extractSlices(
43
+ public async extractSlices(
46
44
  projectRootOrDomainId?: string | number,
47
- maybeDomainId?: number
48
- ): LaravelSemanticExtractionResult {
45
+ maybeDomainId?: number,
46
+ signal?: AbortSignal,
47
+ inventory?: SourceInventory
48
+ ): Promise<LaravelSemanticExtractionResult> {
49
+ // The registry reuses one adapter across workspaces. Keep helpers bound to
50
+ // this invocation's root without mutating the shared adapter instance.
51
+ if (typeof projectRootOrDomainId === "string" && (inventory || path.resolve(projectRootOrDomainId) !== path.resolve(this.projectRoot))) {
52
+ return new LaravelSemanticExtractor(projectRootOrDomainId, inventory).extractSlices(maybeDomainId, undefined, signal);
53
+ }
49
54
  let root = this.projectRoot;
50
55
  let domainId: number | undefined;
51
56
 
@@ -56,27 +61,41 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
56
61
  domainId = projectRootOrDomainId;
57
62
  }
58
63
 
59
- const routeFiles = [
64
+ const standardRouteFiles = [
60
65
  path.join(root, "routes/web.php"),
61
66
  path.join(root, "routes/api.php"),
62
- ].filter((f) => fs.existsSync(f));
67
+ ].filter((f) => fs.existsSync(f) && (!this.inventory || this.inventory.files.includes(f)));
63
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>();
64
77
  const parsedRoutes: ParsedRoute[] = [];
65
78
 
66
79
  for (const routeFile of routeFiles) {
80
+ signal?.throwIfAborted();
81
+ if (includedFiles.has(path.resolve(routeFile))) continue;
67
82
  const content = readOptionalSourceFile(routeFile, "utf-8");
68
83
  const relativeRouteFile = path.relative(root, routeFile).replace(/\\/g, "/");
69
- const routesFromFile = this.parseRoutesContent(content);
84
+ const routesFromFile = await this.parseRoutesContentWithIncludes(content, routeFile, root, includedFiles, signal);
70
85
  for (const r of routesFromFile) {
71
- r.file = relativeRouteFile;
86
+ if (!r.file) r.file = relativeRouteFile;
72
87
  }
73
88
  parsedRoutes.push(...routesFromFile);
74
89
  }
75
90
 
76
91
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
77
92
 
93
+ const resolver = new ImportResolver(root);
94
+ const declarations = new Map<string, ControllerDeclarations>();
78
95
  for (const route of parsedRoutes) {
79
- 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();
80
99
 
81
100
  let formRequestInfo: {
82
101
  className: string;
@@ -103,9 +122,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
103
122
  }> = [];
104
123
 
105
124
  let behavioralInfo: MethodBehavioralSummary | null = null;
106
- if (controllerInfo.filePath && fs.existsSync(controllerInfo.filePath)) {
107
- const controllerCode = readOptionalSourceFile(controllerInfo.filePath, "utf-8");
108
- const actionBody = this.extractActionBody(controllerCode, route.actionName);
125
+ if (controllerInfo.action) {
126
+ const controllerCode = controllerInfo.action.source;
127
+ const actionBody = controllerInfo.action.body;
109
128
  behavioralInfo = BehavioralAnalyzer.analyzeMethod(actionBody);
110
129
 
111
130
  // 1. Detect FormRequest in method signature
@@ -140,7 +159,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
140
159
  actionServices = this.detectActionAndServiceInvocations(
141
160
  controllerCode,
142
161
  route.actionName,
143
- actionBody
162
+ actionBody,
163
+ controllerInfo.constructorSource,
164
+ controllerInfo.fileSource
144
165
  );
145
166
  }
146
167
 
@@ -149,7 +170,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
149
170
  stage: "ingress",
150
171
  symbol: `${route.httpMethod.toUpperCase()} ${route.uri.startsWith("/") ? route.uri : `/${route.uri}`}`,
151
172
  file: route.file,
173
+ line: route.line,
152
174
  description: `HTTP Route: ${route.routeName || route.uri}`,
175
+ relationship: { kind: "declares", derivation: "source", reason: "Laravel facade call" },
153
176
  },
154
177
  ];
155
178
 
@@ -176,7 +199,10 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
176
199
  symbol: `${route.controllerClass}::${route.actionName}`,
177
200
  file: controllerInfo.filePath ? path.relative(this.projectRoot, controllerInfo.filePath) : undefined,
178
201
  line: controllerInfo.line,
179
- 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
+ } : {}),
180
206
  guards: behavioralInfo && behavioralInfo.guards.length > 0 ? behavioralInfo.guards : undefined,
181
207
  mutations: behavioralInfo && behavioralInfo.mutations.length > 0 ? behavioralInfo.mutations : undefined,
182
208
  transactions: behavioralInfo?.hasTransaction,
@@ -273,7 +299,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
273
299
  controller_line: controllerInfo.line,
274
300
  architecture_style: "mvc",
275
301
  entry_kind: "http_route",
276
- execution_chain_json: JSON.stringify(chain),
302
+ execution_chain_json: JSON.stringify(chain.map(node => (node.guards || node.mutations || node.emits || node.dispatches || node.transactions) ? { ...node, semantic_analysis: "lexical_heuristic" } : node)),
277
303
  });
278
304
  }
279
305
 
@@ -285,313 +311,115 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
285
311
  return Object.assign(slices, { slices });
286
312
  }
287
313
 
288
- /**
289
- * Parse Laravel Route declarations.
290
- */
291
- public parseRoutesContent(content: string): ParsedRoute[] {
292
- const routes: ParsedRoute[] = [];
293
-
294
- // 1. Process Route::resource
295
- const resourceRegex = /Route::resource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
296
- let resMatch;
297
- while ((resMatch = resourceRegex.exec(content)) !== null) {
298
- const baseUri = resMatch[1].replace(/^\//, "");
299
- const controllerClass = resMatch[2];
300
- const resourceActions = [
301
- { method: "GET", sub: "", action: "index" },
302
- { method: "GET", sub: "/create", action: "create" },
303
- { method: "POST", sub: "", action: "store" },
304
- { method: "GET", sub: "/{id}", action: "show" },
305
- { method: "GET", sub: "/{id}/edit", action: "edit" },
306
- { method: "PUT", sub: "/{id}", action: "update" },
307
- { method: "DELETE", sub: "/{id}", action: "destroy" },
308
- ];
309
-
310
- for (const res of resourceActions) {
311
- routes.push({
312
- httpMethod: res.method,
313
- uri: `/${baseUri}${res.sub}`,
314
- routeName: `${baseUri}.${res.action}`,
315
- controllerClass,
316
- actionName: res.action,
317
- });
318
- }
319
- }
320
-
321
- // 1b. Process Route::apiResource
322
- const apiResourceRegex = /Route::apiResource\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\\A-Za-z0-9_]+)::class\s*\)/gi;
323
- let apiResMatch;
324
- while ((apiResMatch = apiResourceRegex.exec(content)) !== null) {
325
- const baseUri = apiResMatch[1].replace(/^\//, "");
326
- const controllerClass = apiResMatch[2];
327
- const apiResourceActions = [
328
- { method: "GET", sub: "", action: "index" },
329
- { method: "POST", sub: "", action: "store" },
330
- { method: "GET", sub: "/{id}", action: "show" },
331
- { method: "PUT", sub: "/{id}", action: "update" },
332
- { method: "DELETE", sub: "/{id}", action: "destroy" },
333
- ];
334
-
335
- for (const res of apiResourceActions) {
336
- routes.push({
337
- httpMethod: res.method,
338
- uri: `/${baseUri}${res.sub}`,
339
- routeName: `${baseUri}.${res.action}`,
340
- controllerClass,
341
- actionName: res.action,
342
- });
343
- }
344
- }
345
-
346
- // 2. Parse routes with group context tracking (prefix, controller, name prefix)
347
- const lines = content.split(/\r?\n/);
348
- const cleanLines = blankCommentsAndStrings(content, { hashComments: true }).split(/\r?\n/);
349
- interface GroupContext {
350
- prefix: string;
351
- controller: string;
352
- namePrefix: string;
353
- braceDepth: number;
354
- }
355
-
356
- const groupStack: GroupContext[] = [];
357
- let currentBraceDepth = 0;
358
- let statementBuffer = "";
359
- let inStatement = false;
360
-
361
- for (let i = 0; i < lines.length; i++) {
362
- const line = lines[i];
363
- const cleanLine = cleanLines[i] ?? "";
364
- const cleanTrimmed = cleanLine.trim();
365
- const trimmed = line.trim();
366
-
367
- if (!cleanTrimmed) continue;
368
-
369
- // Check group opens: Route::...group(
370
- if (cleanTrimmed.includes("Route::") && cleanTrimmed.includes("group(") && cleanTrimmed.includes("function")) {
371
- const prefixMatch = /prefix\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
372
- const controllerMatch = /controller\s*\(\s*([\\A-Za-z0-9_]+)::class\s*\)/.exec(trimmed);
373
- const nameMatch = /name\s*\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
374
-
375
- const currentCtx = groupStack[groupStack.length - 1];
376
- const newPrefix = [currentCtx?.prefix, prefixMatch ? prefixMatch[1] : ""]
377
- .filter(Boolean)
378
- .join("/");
379
- const newController = controllerMatch ? controllerMatch[1] : (currentCtx?.controller || "");
380
- const newNamePrefix = [currentCtx?.namePrefix, nameMatch ? nameMatch[1] : ""]
381
- .filter(Boolean)
382
- .join("");
383
-
384
- groupStack.push({
385
- prefix: newPrefix,
386
- controller: newController,
387
- namePrefix: newNamePrefix,
388
- braceDepth: currentBraceDepth,
389
- });
390
- }
391
-
392
- // Track brace depth on string/comment-stripped line so '/orders/{id}' never corrupts braceDepth
393
- for (const char of cleanLine) {
394
- if (char === "{") currentBraceDepth++;
395
- if (char === "}") {
396
- currentBraceDepth--;
397
- if (groupStack.length > 0) {
398
- const top = groupStack[groupStack.length - 1];
399
- if (currentBraceDepth <= top.braceDepth) {
400
- groupStack.pop();
401
- }
402
- }
403
- }
404
- }
405
-
406
- // Route statement accumulation across lines
407
- if (!inStatement && cleanTrimmed.startsWith("Route::") && !cleanTrimmed.includes("Route::resource") && !cleanTrimmed.includes("Route::group") && !(cleanTrimmed.includes("group(") && cleanTrimmed.includes("function"))) {
408
- statementBuffer = trimmed;
409
- inStatement = true;
410
- } else if (inStatement) {
411
- statementBuffer += " " + trimmed;
412
- }
413
-
414
- if (inStatement && cleanLine.includes(";")) {
415
- inStatement = false;
416
- const stmt = statementBuffer;
417
- statementBuffer = "";
418
-
419
- const currentCtx = groupStack[groupStack.length - 1];
420
- const parsed = this.parseSingleRouteStatement(stmt, currentCtx);
421
- if (parsed) {
422
- routes.push(parsed);
423
- }
424
- }
425
- }
426
-
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.");
427
321
  return routes;
428
322
  }
429
323
 
430
- private parseSingleRouteStatement(
431
- stmt: string,
432
- ctx?: { prefix: string; controller: string; namePrefix: string }
433
- ): ParsedRoute | null {
434
- const methodMatch = /Route::(get|post|put|patch|delete|any|options)\s*\(\s*['"]([^'"]+)['"]([\s\S]*)/i.exec(stmt);
435
- if (!methodMatch) {
436
- const viewMatch = /Route::view\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/i.exec(stmt);
437
- if (viewMatch) {
438
- const rawUri = viewMatch[1];
439
- const viewTarget = viewMatch[2];
440
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
441
- const fullUri = ctx?.prefix ? `/${ctx.prefix.replace(/^\/|\/$/g, "")}/${rawUri.replace(/^\//, "")}` : rawUri;
442
- return {
443
- httpMethod: "GET",
444
- uri: fullUri.startsWith("/") ? fullUri : `/${fullUri}`,
445
- routeName: (ctx?.namePrefix || "") + (nameMatch ? nameMatch[1] : ""),
446
- controllerClass: "View",
447
- actionName: viewTarget,
448
- };
449
- }
450
- return null;
451
- }
452
-
453
- const httpMethod = methodMatch[1].toUpperCase();
454
- let uri = methodMatch[2];
455
- const rest = methodMatch[3];
456
-
457
- if (ctx?.prefix) {
458
- const cleanPrefix = ctx.prefix.replace(/^\/|\/$/g, "");
459
- const cleanUri = uri.replace(/^\//, "");
460
- uri = cleanUri ? `/${cleanPrefix}/${cleanUri}` : `/${cleanPrefix}`;
461
- }
462
- if (!uri.startsWith("/")) uri = `/${uri}`;
463
-
464
- const nameMatch = /->name\s*\(\s*['"]([^'"]+)['"]\s*\)/i.exec(stmt);
465
- const rawRouteName = nameMatch ? nameMatch[1] : undefined;
466
- const fullRouteName = rawRouteName
467
- ? (ctx?.namePrefix || "") + rawRouteName
468
- : undefined;
469
-
470
- // [Controller::class, 'action']
471
- const arrayMatch = /\[\s*([\\A-Za-z0-9_]+)::class\s*,\s*['"]([A-Za-z0-9_]+)['"]\s*\]/.exec(rest);
472
- if (arrayMatch) {
473
- return {
474
- httpMethod,
475
- uri,
476
- routeName: fullRouteName,
477
- controllerClass: arrayMatch[1],
478
- actionName: arrayMatch[2],
479
- };
480
- }
481
-
482
- // 'Controller@action'
483
- const stringActionMatch = /['"]([\\A-Za-z0-9_]+)@([A-Za-z0-9_]+)['"]/.exec(rest);
484
- if (stringActionMatch) {
485
- return {
486
- httpMethod,
487
- uri,
488
- routeName: fullRouteName,
489
- controllerClass: stringActionMatch[1],
490
- actionName: stringActionMatch[2],
491
- };
492
- }
493
-
494
- // Action inside controller group
495
- if (ctx?.controller) {
496
- const singleActionMatch = /,\s*['"]([A-Za-z0-9_]+)['"]/.exec(rest);
497
- if (singleActionMatch) {
498
- return {
499
- httpMethod,
500
- uri,
501
- routeName: fullRouteName,
502
- controllerClass: ctx.controller,
503
- actionName: singleActionMatch[1],
504
- };
505
- }
506
- }
507
-
508
- // Invokable controller
509
- const invokableMatch = /,\s*([\\A-Za-z0-9_]+)::class/.exec(rest);
510
- if (invokableMatch) {
511
- return {
512
- httpMethod,
513
- uri,
514
- routeName: fullRouteName,
515
- controllerClass: invokableMatch[1],
516
- actionName: "__invoke",
517
- };
518
- }
519
-
520
- // Closure
521
- if (rest.includes("function")) {
522
- return {
523
- httpMethod,
524
- uri,
525
- routeName: fullRouteName,
526
- controllerClass: "Closure",
527
- actionName: "handle",
528
- };
529
- }
530
-
531
- return null;
532
- }
533
-
534
- private resolveController(
535
- controllerClass: string,
536
- actionName: string,
537
- routeFilePath?: string
538
- ): { filePath?: string; line: number } {
539
- let resolvedFilePath: string | undefined;
540
-
541
- // 1. Try ImportResolver via PSR-4 if routeFilePath or full namespace provided
542
- const resolver = new ImportResolver(this.projectRoot);
543
- const sourceRef = routeFilePath
544
- ? path.resolve(this.projectRoot, routeFilePath)
545
- : path.join(this.projectRoot, "routes/web.php");
546
-
547
- if (controllerClass.includes("\\")) {
548
- const res = resolver.resolve(controllerClass, sourceRef);
549
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
550
- resolvedFilePath = path.resolve(this.projectRoot, res.targets[0].files[0]);
551
- }
552
- } else if (routeFilePath && fs.existsSync(sourceRef)) {
553
- const routeContent = readOptionalSourceFile(sourceRef, "utf-8");
554
- const useRegex = new RegExp(`use\\s+([^;]+?\\\\${controllerClass})(?:\\s+as\\s+[A-Za-z0-9_]+)?;`, "i");
555
- const match = useRegex.exec(routeContent);
556
- if (match) {
557
- const fqn = match[1].trim();
558
- const res = resolver.resolve(fqn, sourceRef);
559
- if (res.status === "resolved" && res.targets[0]?.files?.[0]) {
560
- resolvedFilePath = path.resolve(this.projectRoot, res.targets[0].files[0]);
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 });
561
347
  }
562
- }
563
- }
564
-
565
- // 2. Fallback heuristics if not found via PSR-4
566
- if (!resolvedFilePath) {
567
- const simpleName = controllerClass.split(/\\|\//).pop() || controllerClass;
568
- const candidates = [
569
- path.join(this.projectRoot, `app/Http/Controllers/${simpleName}.php`),
570
- path.join(this.projectRoot, `app/Http/Controllers/Api/${simpleName}.php`),
571
- path.join(this.projectRoot, `app/Http/Controllers/Admin/${simpleName}.php`),
572
- ];
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;
573
354
 
574
- for (const c of candidates) {
575
- if (fs.existsSync(c)) {
576
- resolvedFilePath = c;
577
- break;
578
- }
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);
579
364
  }
580
365
  }
581
366
 
582
- if (resolvedFilePath && fs.existsSync(resolvedFilePath)) {
583
- const lines = readOptionalSourceFile(resolvedFilePath, "utf-8").split("\n");
584
- let targetLine = 1;
585
- for (let i = 0; i < lines.length; i++) {
586
- if (new RegExp(`function\\s+${actionName}\\s*\\(`, "i").test(lines[i])) {
587
- targetLine = i + 1;
588
- break;
589
- }
590
- }
591
- return { filePath: resolvedFilePath, line: targetLine };
592
- }
367
+ return routes;
368
+ }
593
369
 
594
- 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 };
595
423
  }
596
424
 
597
425
  private extractActionBody(controllerCode: string, actionName: string): string {
@@ -708,7 +536,9 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
708
536
  private detectActionAndServiceInvocations(
709
537
  controllerCode: string,
710
538
  actionName: string,
711
- actionBody: string
539
+ actionBody: string,
540
+ constructorSource?: string,
541
+ fileSource: string = controllerCode
712
542
  ): Array<{
713
543
  className: string;
714
544
  filePath?: string;
@@ -745,7 +575,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
745
575
  }
746
576
 
747
577
  // 2. Check constructor injection
748
- const ctorMatch = controllerCode.match(/function\s+__construct\s*\(([^)]*)\)/i);
578
+ const ctorMatch = constructorSource?.match(/function\s+__construct\s*\(([^)]*)\)/i);
749
579
  if (ctorMatch && ctorMatch[1]) {
750
580
  const params = ctorMatch[1].split(",");
751
581
  for (const param of params) {
@@ -794,7 +624,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
794
624
 
795
625
  // 4. Also scan 'use' imports in controller for App\Actions\... or App\Services\...
796
626
  const usePattern = /use\s+App\\(Actions|Services)\\(?:[a-zA-Z0-9_\\]+\\)?([A-Z][a-zA-Z0-9_]*);/g;
797
- while ((match = usePattern.exec(controllerCode)) !== null) {
627
+ while ((match = usePattern.exec(fileSource)) !== null) {
798
628
  const folder = match[1];
799
629
  const cls = match[2];
800
630
  if (actionBody.includes(cls) && !detected.has(cls)) {
@@ -886,7 +716,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
886
716
  const jobsDir = path.join(root, "app/Jobs");
887
717
  if (!fs.existsSync(jobsDir)) return [];
888
718
 
889
- const jobFiles = fs.readdirSync(jobsDir).filter((f) => f.endsWith(".php"));
719
+ const jobFiles = listSourceFiles(jobsDir, /\.php$/, this.inventory).filter(file => path.dirname(file) === jobsDir).map(file => path.basename(file));
890
720
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
891
721
 
892
722
  for (const file of jobFiles) {
@@ -948,7 +778,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
948
778
  controller_line: 1,
949
779
  architecture_style: "clean",
950
780
  entry_kind: "queue_job",
951
- execution_chain_json: JSON.stringify(chain),
781
+ execution_chain_json: JSON.stringify(chain.map(node => (node.guards || node.mutations || node.emits || node.dispatches || node.transactions) ? { ...node, semantic_analysis: "lexical_heuristic" } : node)),
952
782
  });
953
783
  }
954
784
 
@@ -962,7 +792,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
962
792
  const commandsDir = path.join(root, "app/Console/Commands");
963
793
  if (!fs.existsSync(commandsDir)) return [];
964
794
 
965
- const files = fs.readdirSync(commandsDir).filter((f) => f.endsWith(".php"));
795
+ const files = listSourceFiles(commandsDir, /\.php$/, this.inventory).filter(file => path.dirname(file) === commandsDir).map(file => path.basename(file));
966
796
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
967
797
 
968
798
  for (const file of files) {
@@ -975,6 +805,10 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
975
805
  const sigMatch = content.match(/protected\s+\$signature\s*=\s*['"]([^'"]+)['"]/);
976
806
  const commandSignature = sigMatch ? sigMatch[1].split(/\s+/)[0] : this.toSnakeCase(className);
977
807
 
808
+ const handleMatch = content.match(/\bfunction\s+handle\s*\(/);
809
+ const handleLine = handleMatch && handleMatch.index !== undefined
810
+ ? content.slice(0, handleMatch.index).split("\n").length
811
+ : 1;
978
812
  const actionBody = this.extractActionBody(content, "handle");
979
813
  const behavior = BehavioralAnalyzer.analyzeMethod(actionBody);
980
814
 
@@ -983,12 +817,14 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
983
817
  stage: "ingress",
984
818
  symbol: `CLI ${commandSignature}`,
985
819
  file: path.relative(this.projectRoot, fullPath),
820
+ line: handleLine,
986
821
  description: `Console Command: ${commandSignature}`,
987
822
  },
988
823
  {
989
824
  stage: "controller",
990
825
  symbol: `${className}::handle`,
991
826
  file: path.relative(this.projectRoot, fullPath),
827
+ line: handleLine,
992
828
  description: "Command Execution Handler",
993
829
  mutations: behavior.mutations.length ? behavior.mutations : undefined,
994
830
  transactions: behavior.hasTransaction,
@@ -1024,10 +860,10 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
1024
860
  controller_class: className,
1025
861
  action_name: "handle",
1026
862
  controller_file: path.relative(this.projectRoot, fullPath),
1027
- controller_line: 1,
863
+ controller_line: handleLine,
1028
864
  architecture_style: "clean",
1029
865
  entry_kind: "scheduled_command",
1030
- execution_chain_json: JSON.stringify(chain),
866
+ execution_chain_json: JSON.stringify(chain.map(node => (node.guards || node.mutations || node.emits || node.dispatches || node.transactions) ? { ...node, semantic_analysis: "lexical_heuristic" } : node)),
1031
867
  });
1032
868
  }
1033
869
 
@@ -1041,7 +877,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
1041
877
  const listenersDir = path.join(root, "app/Listeners");
1042
878
  if (!fs.existsSync(listenersDir)) return [];
1043
879
 
1044
- const files = fs.readdirSync(listenersDir).filter((f) => f.endsWith(".php"));
880
+ const files = listSourceFiles(listenersDir, /\.php$/, this.inventory).filter(file => path.dirname(file) === listenersDir).map(file => path.basename(file));
1045
881
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
1046
882
 
1047
883
  for (const file of files) {
@@ -1106,7 +942,7 @@ export class LaravelSemanticExtractor implements SemanticSliceExtractor {
1106
942
  controller_line: 1,
1107
943
  architecture_style: "clean",
1108
944
  entry_kind: "event_listener",
1109
- execution_chain_json: JSON.stringify(chain),
945
+ execution_chain_json: JSON.stringify(chain.map(node => (node.guards || node.mutations || node.emits || node.dispatches || node.transactions) ? { ...node, semantic_analysis: "lexical_heuristic" } : node)),
1110
946
  });
1111
947
  }
1112
948