@dimassetoid/septum-mcp 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +142 -2
- package/bin/septum.ts +4 -0
- package/package.json +70 -4
- package/scripts/postinstall.ts +25 -0
- package/src/cli/commands/check.ts +133 -0
- package/src/cli/commands/hook.ts +205 -0
- package/src/cli/commands/init.ts +570 -0
- package/src/cli/commands/serve.ts +5 -0
- package/src/cli/commands/sync.ts +39 -0
- package/src/cli/hook-payload.ts +43 -0
- package/src/cli/index.ts +124 -0
- package/src/cli/scaffold/harness-config.ts +661 -0
- package/src/cli/templates/hooks.ts +110 -0
- package/src/cli/templates/rules.ts +35 -0
- package/src/cli/templates/skill.ts +55 -0
- package/src/cli/ui/prompts.ts +122 -0
- package/src/core/boundary/evaluator.ts +426 -0
- package/src/core/boundary/staged-auditor.ts +120 -0
- package/src/core/config/domain-ownership.ts +45 -0
- package/src/core/config/loader.ts +174 -0
- package/src/core/config/schema.ts +59 -0
- package/src/core/database/client.ts +60 -0
- package/src/core/database/repositories/dependency.repository.ts +733 -0
- package/src/core/database/repositories/domain.repository.ts +373 -0
- package/src/core/database/repositories/file.repository.ts +117 -0
- package/src/core/database/repositories/meta.repository.ts +33 -0
- package/src/core/database/repositories/symbol.repository.ts +647 -0
- package/src/core/database/repository.ts +358 -0
- package/src/core/database/schema.ts +123 -0
- package/src/core/discovery/navigation.ts +105 -0
- package/src/core/discovery/topology-detector.ts +863 -0
- package/src/core/ingestion/hasher.ts +5 -0
- package/src/core/ingestion/pipeline.ts +590 -0
- package/src/core/parser/behavioral-analyzer.ts +123 -0
- package/src/core/parser/boundary-tracker.ts +458 -0
- package/src/core/parser/extractors/base.ts +71 -0
- package/src/core/parser/extractors/blade.ts +159 -0
- package/src/core/parser/extractors/csharp.ts +248 -0
- package/src/core/parser/extractors/django-semantic.ts +655 -0
- package/src/core/parser/extractors/elysia-semantic.ts +517 -0
- package/src/core/parser/extractors/express-semantic.ts +429 -0
- package/src/core/parser/extractors/fastapi-semantic.ts +702 -0
- package/src/core/parser/extractors/fastify-semantic.ts +759 -0
- package/src/core/parser/extractors/flask-semantic.ts +482 -0
- package/src/core/parser/extractors/frontend.ts +149 -0
- package/src/core/parser/extractors/go-semantic.ts +670 -0
- package/src/core/parser/extractors/go.ts +491 -0
- package/src/core/parser/extractors/hono-semantic.ts +546 -0
- package/src/core/parser/extractors/java.ts +227 -0
- package/src/core/parser/extractors/laravel-semantic.ts +1150 -0
- package/src/core/parser/extractors/mcp-cli-semantic.ts +367 -0
- package/src/core/parser/extractors/nestjs-semantic.ts +527 -0
- package/src/core/parser/extractors/php.ts +585 -0
- package/src/core/parser/extractors/python.ts +503 -0
- package/src/core/parser/extractors/registry.ts +99 -0
- package/src/core/parser/extractors/ruby.ts +237 -0
- package/src/core/parser/extractors/rust.ts +304 -0
- package/src/core/parser/extractors/semantic-extractor.interface.ts +24 -0
- package/src/core/parser/extractors/symfony-semantic.ts +321 -0
- package/src/core/parser/extractors/typescript.ts +839 -0
- package/src/core/parser/implementation-fingerprint.ts +97 -0
- package/src/core/parser/language-capabilities.ts +87 -0
- package/src/core/parser/schema/providers/laravel-migration-provider.ts +239 -0
- package/src/core/parser/schema/schema-provider-registry.ts +41 -0
- package/src/core/parser/schema/schema-provider.interface.ts +34 -0
- package/src/core/parser/semantic-revision.ts +3 -0
- package/src/core/parser/static-string.ts +51 -0
- package/src/core/parser/tree-sitter.ts +63 -0
- package/src/core/parser/wasm-assets.ts +25 -0
- package/src/core/parser/wasm-loader.ts +274 -0
- package/src/core/resolver/call-graph-tracer.ts +1033 -0
- package/src/core/resolver/import-resolver.ts +365 -0
- package/src/core/resolver/interpretation-inputs.ts +7 -0
- package/src/core/resolver/languages/go.ts +103 -0
- package/src/core/resolver/languages/managed.ts +200 -0
- package/src/core/resolver/languages/python.ts +115 -0
- package/src/core/resolver/languages/ruby.ts +40 -0
- package/src/core/resolver/languages/rust.ts +127 -0
- package/src/core/resolver/languages/shared.ts +71 -0
- package/src/core/resolver/module-resolver.ts +486 -0
- package/src/core/resolver/path-resolver.ts +200 -0
- package/src/core/resolver/slice-catalog.ts +79 -0
- package/src/core/resolver/slice-format.ts +9 -0
- package/src/core/resolver/symbol-impact.ts +381 -0
- package/src/core/resolver/symbol-locator.ts +276 -0
- package/src/core/resolver/symbol-reference.ts +53 -0
- package/src/core/resolver/vertical-slice-tracer.ts +344 -0
- package/src/core/resources/ignore.ts +144 -0
- package/src/core/resources/limits.ts +14 -0
- package/src/core/resources/source-files.ts +185 -0
- package/src/core/resources/source-inventory.ts +55 -0
- package/src/core/resources/work-queue.ts +74 -0
- package/src/core/retrieval/context-page.ts +109 -0
- package/src/core/retrieval/context.ts +320 -0
- package/src/core/retrieval/resolution-warnings.ts +21 -0
- package/src/core/retrieval/symbol-evidence.ts +97 -0
- package/src/core/retrieval/typescript-references.ts +262 -0
- package/src/core/telemetry/telemetry.ts +142 -0
- package/src/index.ts +18 -0
- package/src/mcp/schemas.ts +746 -0
- package/src/mcp/server.ts +600 -0
- package/src/mcp/tools/boundary.ts +17 -0
- package/src/mcp/tools/check-boundary.ts +382 -0
- package/src/mcp/tools/get-domain-catalog.ts +39 -0
- package/src/mcp/tools/get-symbol-impact.ts +104 -0
- package/src/mcp/tools/get-symbol.ts +399 -0
- package/src/mcp/tools/locate-symbol.ts +236 -0
- package/src/mcp/tools/map.ts +26 -0
- package/src/mcp/tools/register-domain.ts +113 -0
- package/src/mcp/tools/slice.ts +16 -0
- package/src/mcp/tools/symbol.ts +95 -0
- package/src/mcp/tools/trace-vertical-slice.ts +106 -0
- package/src/mcp/workspace-manager.ts +170 -0
- package/src/mcp/workspace-watcher.ts +202 -0
- package/src/types/index.ts +438 -0
- package/src/types/wasm.d.ts +4 -0
- package/src/utils/version-check.ts +209 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,1033 @@
|
|
|
1
|
+
import { ImportResolver } from "./import-resolver.ts";
|
|
2
|
+
import { readOptionalSourceFile } from "../resources/source-files.ts";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, normalize, relative, resolve } from "node:path";
|
|
5
|
+
import type {
|
|
6
|
+
ExecutionChainNode,
|
|
7
|
+
FileRecord,
|
|
8
|
+
SymbolRecord,
|
|
9
|
+
VerticalSliceRecord,
|
|
10
|
+
} from "../../types/index.ts";
|
|
11
|
+
import type { SeptumRepository } from "../database/repository.ts";
|
|
12
|
+
|
|
13
|
+
export interface DiscoveredRoute {
|
|
14
|
+
method: string;
|
|
15
|
+
uri: string;
|
|
16
|
+
file: string;
|
|
17
|
+
line: number;
|
|
18
|
+
middlewareSymbols: string[];
|
|
19
|
+
handlerSymbol?: string;
|
|
20
|
+
handlerClass?: string;
|
|
21
|
+
handlerMethod?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class CallGraphTracer {
|
|
25
|
+
private importEvidence?: ReturnType<SeptumRepository["getImportRelationships"]>;
|
|
26
|
+
private evidenceByFile = new Map<string, ReturnType<SeptumRepository["getImportRelationships"]>>();
|
|
27
|
+
private fileMapByNormPath: Map<string, FileRecord> = new Map();
|
|
28
|
+
private fileMapById: Map<number, FileRecord> = new Map();
|
|
29
|
+
private symbolsByFileId: Map<number, SymbolRecord[]> = new Map();
|
|
30
|
+
private dependenciesByFileId: Map<
|
|
31
|
+
number,
|
|
32
|
+
Array<{ target: string; statement: string; line_number: number; is_external: boolean }>
|
|
33
|
+
> = new Map();
|
|
34
|
+
|
|
35
|
+
constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd()) {}
|
|
36
|
+
|
|
37
|
+
private fileForPath(path: string): FileRecord | undefined {
|
|
38
|
+
const key = this.normalizeFilePath(path);
|
|
39
|
+
const cached = this.fileMapByNormPath.get(key);
|
|
40
|
+
if (cached) return cached;
|
|
41
|
+
const file = this.repo.getFileByPath(path.replace(/\\/g, "/").replace(/^\.\//, ""));
|
|
42
|
+
if (!file) return undefined;
|
|
43
|
+
this.fileMapByNormPath.set(key, file);
|
|
44
|
+
this.fileMapById.set(file.id, file);
|
|
45
|
+
return file;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private fileSymbols(fileId: number): SymbolRecord[] {
|
|
49
|
+
if (!this.symbolsByFileId.has(fileId)) this.symbolsByFileId.set(fileId, this.repo.getSymbolsByFileId(fileId));
|
|
50
|
+
return this.symbolsByFileId.get(fileId)!;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private fileDependencies(fileId: number) {
|
|
54
|
+
if (!this.dependenciesByFileId.has(fileId)) this.dependenciesByFileId.set(fileId, this.repo.getDependenciesByFileId(fileId));
|
|
55
|
+
return this.dependenciesByFileId.get(fileId)!;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Initializes internal fast lookup maps from SQLite repository data.
|
|
60
|
+
*/
|
|
61
|
+
public initMaps(): void {
|
|
62
|
+
this.fileMapByNormPath.clear(); this.fileMapById.clear();
|
|
63
|
+
this.symbolsByFileId.clear(); this.dependenciesByFileId.clear(); this.evidenceByFile.clear();
|
|
64
|
+
const allSymbolsWithFiles = this.repo.getAllSymbolsWithFiles();
|
|
65
|
+
const allDeps = this.repo.getAllDependenciesWithDomains();
|
|
66
|
+
this.importEvidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.projectRoot) : undefined;
|
|
67
|
+
|
|
68
|
+
// Map files
|
|
69
|
+
const allFiles = this.repo.getAllFiles();
|
|
70
|
+
for (const f of allFiles) {
|
|
71
|
+
const norm = this.normalizeFilePath(f.path);
|
|
72
|
+
this.fileMapByNormPath.set(norm, f);
|
|
73
|
+
this.fileMapById.set(f.id, f);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Map symbols
|
|
77
|
+
for (const s of allSymbolsWithFiles) {
|
|
78
|
+
const existing = this.symbolsByFileId.get(s.file_id) || [];
|
|
79
|
+
existing.push(s);
|
|
80
|
+
this.symbolsByFileId.set(s.file_id, existing);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Map dependencies
|
|
84
|
+
for (const d of allDeps) {
|
|
85
|
+
const file = this.fileMapByNormPath.get(this.normalizeFilePath(d.source_file));
|
|
86
|
+
if (file) {
|
|
87
|
+
const existing = this.dependenciesByFileId.get(file.id) || [];
|
|
88
|
+
existing.push({
|
|
89
|
+
target: d.target,
|
|
90
|
+
statement: d.statement,
|
|
91
|
+
line_number: d.line_number,
|
|
92
|
+
is_external: d.is_external,
|
|
93
|
+
});
|
|
94
|
+
this.dependenciesByFileId.set(file.id, existing);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Discover declarative HTTP routes from known route/router files in the repository.
|
|
101
|
+
*/
|
|
102
|
+
public discoverDeclarativeRoutes(): DiscoveredRoute[] {
|
|
103
|
+
const discovered: DiscoveredRoute[] = [];
|
|
104
|
+
|
|
105
|
+
for (const [normPath, file] of this.fileMapByNormPath.entries()) {
|
|
106
|
+
const isRouteFile =
|
|
107
|
+
file.archetype === "route" ||
|
|
108
|
+
/routes?|router|endpoints?/i.test(normPath) ||
|
|
109
|
+
/\.(routes?|router)\.[tj]sx?$/i.test(normPath);
|
|
110
|
+
|
|
111
|
+
if (!isRouteFile) continue;
|
|
112
|
+
|
|
113
|
+
const fullPath = resolve(this.projectRoot, file.path);
|
|
114
|
+
if (!existsSync(fullPath)) continue;
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const content = readOptionalSourceFile(fullPath, "utf-8");
|
|
118
|
+
const lines = content.split("\n");
|
|
119
|
+
|
|
120
|
+
for (let i = 0; i < lines.length; i++) {
|
|
121
|
+
const line = lines[i];
|
|
122
|
+
// Pattern: router.post('/api/orders', validateMiddleware, controller.action)
|
|
123
|
+
// or app.get('/orders', handler)
|
|
124
|
+
const match = line.match(
|
|
125
|
+
/(?:router|app|server|api)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(.+)\)/i
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
if (match) {
|
|
129
|
+
const method = match[1].toUpperCase();
|
|
130
|
+
const uri = match[2];
|
|
131
|
+
const rawArgs = match[3];
|
|
132
|
+
|
|
133
|
+
const argTokens = rawArgs
|
|
134
|
+
.split(",")
|
|
135
|
+
.map((t) => t.trim())
|
|
136
|
+
.filter((t) => t.length > 0 && !t.startsWith("//"));
|
|
137
|
+
|
|
138
|
+
const middlewareSymbols: string[] = [];
|
|
139
|
+
let handlerSymbol: string | undefined;
|
|
140
|
+
let handlerClass: string | undefined;
|
|
141
|
+
let handlerMethod: string | undefined;
|
|
142
|
+
|
|
143
|
+
if (argTokens.length === 1) {
|
|
144
|
+
handlerSymbol = argTokens[0];
|
|
145
|
+
} else if (argTokens.length > 1) {
|
|
146
|
+
handlerSymbol = argTokens[argTokens.length - 1];
|
|
147
|
+
middlewareSymbols.push(...argTokens.slice(0, argTokens.length - 1));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (handlerSymbol) {
|
|
151
|
+
// Extract Class.method or classInstance.method
|
|
152
|
+
const parts = handlerSymbol.split(".");
|
|
153
|
+
if (parts.length === 2) {
|
|
154
|
+
handlerClass = parts[0];
|
|
155
|
+
handlerMethod = parts[1];
|
|
156
|
+
} else if (handlerSymbol.includes("::")) {
|
|
157
|
+
const colParts = handlerSymbol.split("::");
|
|
158
|
+
handlerClass = colParts[0];
|
|
159
|
+
handlerMethod = colParts[1];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
discovered.push({
|
|
164
|
+
method,
|
|
165
|
+
uri,
|
|
166
|
+
file: file.path,
|
|
167
|
+
line: i + 1,
|
|
168
|
+
middlewareSymbols,
|
|
169
|
+
handlerSymbol,
|
|
170
|
+
handlerClass,
|
|
171
|
+
handlerMethod,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
} catch (err: unknown) {
|
|
176
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
177
|
+
console.error(`[Septum CallGraph Warning] Route discovery failed for ${file.path}: ${msg}`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return discovered;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Build execution chains for all discovered entrypoints and controller actions.
|
|
186
|
+
*/
|
|
187
|
+
public traceAllSlices(maxDepth: number = 5, options: { includeInferredControllers?: boolean; excludeEntrypointFiles?: ReadonlySet<string> } = {}): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
|
|
188
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
189
|
+
this.initMaps();
|
|
190
|
+
const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
|
|
191
|
+
const declarativeRoutes = this.discoverDeclarativeRoutes();
|
|
192
|
+
|
|
193
|
+
// 1. Trace from declarative routes
|
|
194
|
+
for (const route of declarativeRoutes) {
|
|
195
|
+
if (options.excludeEntrypointFiles?.has(route.file)) continue;
|
|
196
|
+
const chain = this.traceChainFromRoute(route, effectiveMaxDepth);
|
|
197
|
+
if (chain.length > 0) {
|
|
198
|
+
const sliceRecord = this.buildSliceRecordFromChain(
|
|
199
|
+
route.method,
|
|
200
|
+
route.uri,
|
|
201
|
+
chain,
|
|
202
|
+
"clean"
|
|
203
|
+
);
|
|
204
|
+
slices.push(sliceRecord);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (options.includeInferredControllers === false) return slices;
|
|
209
|
+
|
|
210
|
+
// 2. Trace controllers if routes were not explicitly bound or found
|
|
211
|
+
for (const [normPath, file] of this.fileMapByNormPath.entries()) {
|
|
212
|
+
const isController =
|
|
213
|
+
file.archetype === "controller" ||
|
|
214
|
+
/controller/i.test(normPath) ||
|
|
215
|
+
normPath.endsWith("Controller.ts") ||
|
|
216
|
+
normPath.endsWith("Controller.js");
|
|
217
|
+
|
|
218
|
+
if (!isController) continue;
|
|
219
|
+
|
|
220
|
+
const symbols = this.fileSymbols(file.id);
|
|
221
|
+
const methods = symbols.filter((s) => s.kind === "method" || s.kind === "function");
|
|
222
|
+
|
|
223
|
+
for (const m of methods) {
|
|
224
|
+
// Skip constructors or private helpers
|
|
225
|
+
if (m.name === "constructor" || m.name.startsWith("_")) continue;
|
|
226
|
+
|
|
227
|
+
// Check if this method was already covered by declarative routes
|
|
228
|
+
const alreadyCovered = slices.some(
|
|
229
|
+
(s) =>
|
|
230
|
+
s.controller_file === file.path &&
|
|
231
|
+
s.action_name.toLowerCase() === m.name.toLowerCase()
|
|
232
|
+
);
|
|
233
|
+
if (alreadyCovered) continue;
|
|
234
|
+
|
|
235
|
+
const chain = this.traceChainFromController(file, m, effectiveMaxDepth);
|
|
236
|
+
if (chain.length > 0) {
|
|
237
|
+
const defaultMethod = /create|store|save|add/i.test(m.name)
|
|
238
|
+
? "POST"
|
|
239
|
+
: /update|edit|patch/i.test(m.name)
|
|
240
|
+
? "PUT"
|
|
241
|
+
: /delete|remove|destroy/i.test(m.name)
|
|
242
|
+
? "DELETE"
|
|
243
|
+
: "GET";
|
|
244
|
+
|
|
245
|
+
const inferredUri = this.inferRouteUri(file.path, m.name);
|
|
246
|
+
const sliceRecord = this.buildSliceRecordFromChain(
|
|
247
|
+
defaultMethod,
|
|
248
|
+
inferredUri,
|
|
249
|
+
chain,
|
|
250
|
+
"clean"
|
|
251
|
+
);
|
|
252
|
+
slices.push(sliceRecord);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return slices;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Trace execution chain starting from a declarative route.
|
|
262
|
+
*/
|
|
263
|
+
public traceChainFromRoute(route: DiscoveredRoute, maxDepth: number = 5): ExecutionChainNode[] {
|
|
264
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
265
|
+
const chain: ExecutionChainNode[] = [];
|
|
266
|
+
|
|
267
|
+
// Stage 1: Ingress
|
|
268
|
+
chain.push({
|
|
269
|
+
stage: "ingress",
|
|
270
|
+
symbol: `${route.method} ${route.uri}`,
|
|
271
|
+
file: route.file,
|
|
272
|
+
line: route.line,
|
|
273
|
+
description: `HTTP Route Ingress: ${route.method} ${route.uri}`,
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
// Stage 2: Validation / Middleware
|
|
277
|
+
for (const mw of route.middlewareSymbols) {
|
|
278
|
+
const mwLoc = this.locateSymbol(mw, route.file);
|
|
279
|
+
chain.push({
|
|
280
|
+
stage: "validation",
|
|
281
|
+
symbol: mw,
|
|
282
|
+
file: mwLoc?.file,
|
|
283
|
+
line: mwLoc?.line,
|
|
284
|
+
description: `Request Validation / Middleware: ${mw}`,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Stage 3: Controller / Handler
|
|
289
|
+
let controllerFile: FileRecord | undefined;
|
|
290
|
+
let actionMethod = route.handlerMethod || route.handlerSymbol || "handle";
|
|
291
|
+
|
|
292
|
+
if (route.handlerClass) {
|
|
293
|
+
const found = this.findFileBySymbolOrName(route.handlerClass, route.file);
|
|
294
|
+
if (found) {
|
|
295
|
+
controllerFile = found.file;
|
|
296
|
+
if (!route.handlerMethod && found.symbol) {
|
|
297
|
+
actionMethod = found.symbol.name;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
} else if (route.handlerSymbol) {
|
|
301
|
+
const found = this.findFileBySymbolOrName(route.handlerSymbol, route.file);
|
|
302
|
+
if (found) {
|
|
303
|
+
controllerFile = found.file;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (controllerFile) {
|
|
308
|
+
const syms = this.fileSymbols(controllerFile.id);
|
|
309
|
+
const methodSym = syms.find(
|
|
310
|
+
(s) => s.name.toLowerCase() === actionMethod.toLowerCase()
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
const ctrlName =
|
|
314
|
+
syms.find((s) => s.kind === "class")?.name ||
|
|
315
|
+
controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
|
|
316
|
+
"Controller";
|
|
317
|
+
|
|
318
|
+
chain.push({
|
|
319
|
+
stage: "controller",
|
|
320
|
+
symbol: `${ctrlName}::${actionMethod}`,
|
|
321
|
+
file: controllerFile.path,
|
|
322
|
+
line: methodSym?.line_start || 1,
|
|
323
|
+
description: `Controller Action: ${ctrlName}::${actionMethod}`,
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
// Forward reachability BFS from controller
|
|
327
|
+
this.traverseOutboundDependencies(controllerFile, chain, effectiveMaxDepth);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
return chain;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
public static readonly MAX_CHAIN_NODES = 25;
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Trace execution chain starting from a controller method.
|
|
337
|
+
*/
|
|
338
|
+
public traceChainFromController(
|
|
339
|
+
controllerFile: FileRecord,
|
|
340
|
+
method: SymbolRecord,
|
|
341
|
+
maxDepth: number = 5
|
|
342
|
+
): ExecutionChainNode[] {
|
|
343
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
344
|
+
const chain: ExecutionChainNode[] = [];
|
|
345
|
+
const syms = this.fileSymbols(controllerFile.id);
|
|
346
|
+
const ctrlName =
|
|
347
|
+
syms.find((s) => s.kind === "class")?.name ||
|
|
348
|
+
controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
|
|
349
|
+
"Controller";
|
|
350
|
+
|
|
351
|
+
// Stage 1: Ingress (inferred)
|
|
352
|
+
const inferredUri = this.inferRouteUri(controllerFile.path, method.name);
|
|
353
|
+
const defaultMethod = /create|store|save|add/i.test(method.name)
|
|
354
|
+
? "POST"
|
|
355
|
+
: /update|edit|patch/i.test(method.name)
|
|
356
|
+
? "PUT"
|
|
357
|
+
: /delete|remove|destroy/i.test(method.name)
|
|
358
|
+
? "DELETE"
|
|
359
|
+
: "GET";
|
|
360
|
+
|
|
361
|
+
chain.push({
|
|
362
|
+
stage: "ingress",
|
|
363
|
+
symbol: `${defaultMethod} ${inferredUri}`,
|
|
364
|
+
file: controllerFile.path,
|
|
365
|
+
line: method.line_start,
|
|
366
|
+
description: `Inferred Ingress: ${defaultMethod} ${inferredUri}`,
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
// Stage 3: Controller
|
|
370
|
+
chain.push({
|
|
371
|
+
stage: "controller",
|
|
372
|
+
symbol: `${ctrlName}::${method.name}`,
|
|
373
|
+
file: controllerFile.path,
|
|
374
|
+
line: method.line_start,
|
|
375
|
+
description: `Controller Action: ${ctrlName}::${method.name}`,
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// Forward reachability BFS
|
|
379
|
+
this.traverseOutboundDependencies(controllerFile, chain, effectiveMaxDepth);
|
|
380
|
+
|
|
381
|
+
return chain;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Expand an existing slice execution chain starting from controllerFilePath up to maxDepth.
|
|
386
|
+
*/
|
|
387
|
+
public expandChainFromFile(
|
|
388
|
+
controllerFilePath: string,
|
|
389
|
+
existingChain: ExecutionChainNode[],
|
|
390
|
+
maxDepth: number = 5
|
|
391
|
+
): ExecutionChainNode[] {
|
|
392
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
393
|
+
const startFile = this.fileForPath(controllerFilePath);
|
|
394
|
+
if (!startFile) {
|
|
395
|
+
return existingChain.slice(0, CallGraphTracer.MAX_CHAIN_NODES);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const chain = [...existingChain];
|
|
399
|
+
this.traverseOutboundDependencies(startFile, chain, effectiveMaxDepth);
|
|
400
|
+
return chain;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* AST-scoped Call Tracing: Only expands dependencies referenced inside the specific target method body & signature.
|
|
405
|
+
* Completely filters out unused file-level imports to prevent context bloat and cognitive noise.
|
|
406
|
+
*/
|
|
407
|
+
public expandChainFromMethod(
|
|
408
|
+
controllerFilePath: string,
|
|
409
|
+
actionName: string,
|
|
410
|
+
existingChain: ExecutionChainNode[],
|
|
411
|
+
maxDepth: number = 5
|
|
412
|
+
): ExecutionChainNode[] {
|
|
413
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
414
|
+
const startFile = this.fileForPath(controllerFilePath);
|
|
415
|
+
if (!startFile) {
|
|
416
|
+
return existingChain.slice(0, CallGraphTracer.MAX_CHAIN_NODES);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const symbols = this.fileSymbols(startFile.id);
|
|
420
|
+
const methodSymbol = symbols.find(
|
|
421
|
+
(s) => (s.kind === "method" || s.kind === "function") && (s.name.endsWith(`::${actionName}`) || s.name.endsWith(`@${actionName}`) || s.name === actionName)
|
|
422
|
+
);
|
|
423
|
+
|
|
424
|
+
if (!methodSymbol) {
|
|
425
|
+
return this.expandChainFromFile(controllerFilePath, existingChain, maxDepth);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const fullPath = resolve(this.projectRoot, startFile.path);
|
|
429
|
+
if (!existsSync(fullPath)) {
|
|
430
|
+
return existingChain.slice(0, CallGraphTracer.MAX_CHAIN_NODES);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
let methodBody = "";
|
|
434
|
+
try {
|
|
435
|
+
const fileContent = readOptionalSourceFile(fullPath, "utf-8");
|
|
436
|
+
const lines = fileContent.split(/\r?\n/);
|
|
437
|
+
const start = Math.max(0, methodSymbol.line_start - 1);
|
|
438
|
+
const end = Math.min(lines.length, methodSymbol.line_end);
|
|
439
|
+
methodBody = this.scopeWithInjectedTypes(fileContent, lines.slice(start, end).join("\n"));
|
|
440
|
+
} catch {
|
|
441
|
+
return this.expandChainFromFile(controllerFilePath, existingChain, maxDepth);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const chain = [...existingChain];
|
|
445
|
+
this.traverseMethodScopedDependencies(startFile, methodBody, methodSymbol, chain, effectiveMaxDepth);
|
|
446
|
+
return chain;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private extractScopeForCollaborator(
|
|
450
|
+
collaboratorFile: FileRecord,
|
|
451
|
+
callerScopeText: string
|
|
452
|
+
): string {
|
|
453
|
+
const symbols = this.fileSymbols(collaboratorFile.id);
|
|
454
|
+
const methods = symbols.filter((s) => s.kind === "method" || s.kind === "function");
|
|
455
|
+
if (methods.length === 0) return "";
|
|
456
|
+
|
|
457
|
+
// Find methods whose short name is referenced in callerScopeText
|
|
458
|
+
let matchedMethods = methods.filter((m) => {
|
|
459
|
+
const shortName = m.name.split("::").pop() || "";
|
|
460
|
+
return shortName.length > 2 && callerScopeText.includes(shortName);
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
// If no direct method name match, check for standard action execution methods: execute / handle
|
|
464
|
+
if (matchedMethods.length === 0) {
|
|
465
|
+
if (callerScopeText.includes("execute") || callerScopeText.includes("handle")) {
|
|
466
|
+
matchedMethods = methods.filter((m) => {
|
|
467
|
+
const shortName = m.name.split("::").pop() || "";
|
|
468
|
+
return shortName === "execute" || shortName === "handle";
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
if (matchedMethods.length === 0) return "";
|
|
474
|
+
|
|
475
|
+
const fullPath = resolve(this.projectRoot, collaboratorFile.path);
|
|
476
|
+
if (!existsSync(fullPath)) return "";
|
|
477
|
+
|
|
478
|
+
try {
|
|
479
|
+
const fileContent = readOptionalSourceFile(fullPath, "utf-8");
|
|
480
|
+
const lines = fileContent.split(/\r?\n/);
|
|
481
|
+
let scope = "";
|
|
482
|
+
for (const m of matchedMethods) {
|
|
483
|
+
const start = Math.max(0, m.line_start - 1);
|
|
484
|
+
const end = Math.min(lines.length, m.line_end);
|
|
485
|
+
scope += (m.signature || "") + "\n" + lines.slice(start, end).join("\n") + "\n";
|
|
486
|
+
}
|
|
487
|
+
return this.scopeWithInjectedTypes(fileContent, scope);
|
|
488
|
+
} catch {
|
|
489
|
+
return "";
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Static hints for explicitly typed properties used by this scope. */
|
|
494
|
+
private scopeWithInjectedTypes(source: string, scope: string): string {
|
|
495
|
+
const types = new Set<string>();
|
|
496
|
+
for (const match of scope.matchAll(/(?:\bthis\.([A-Za-z_]\w*)|\$this->([A-Za-z_]\w*))/g)) {
|
|
497
|
+
const property = match[1] ?? match[2]!;
|
|
498
|
+
const tsType = new RegExp(`\\b${property}\\s*[?!]?\\s*:\\s*([A-Za-z_]\\w*)\\b`, "g");
|
|
499
|
+
const phpType = new RegExp(`\\b(?:public|protected|private)\\s+(?:readonly\\s+)?([\\\\A-Za-z_]\\w*(?:\\\\\\w+)*)\\s+\\$${property}\\b`, "g");
|
|
500
|
+
for (const declaration of source.matchAll(tsType)) types.add(declaration[1]!);
|
|
501
|
+
for (const declaration of source.matchAll(phpType)) types.add(declaration[1]!.split("\\").pop()!);
|
|
502
|
+
}
|
|
503
|
+
return scope + "\n" + [...types].join("\n");
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
private isExecutableSymbol(s: SymbolRecord): boolean {
|
|
507
|
+
if (
|
|
508
|
+
s.kind === "class" ||
|
|
509
|
+
s.kind === "function" ||
|
|
510
|
+
s.kind === "method" ||
|
|
511
|
+
s.kind === "struct" ||
|
|
512
|
+
s.kind === "trait" ||
|
|
513
|
+
s.kind === "component" ||
|
|
514
|
+
s.kind === "view"
|
|
515
|
+
) {
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
if (
|
|
519
|
+
s.kind === "interface" ||
|
|
520
|
+
s.kind === "type" ||
|
|
521
|
+
s.kind === "property" ||
|
|
522
|
+
s.kind === "constant" ||
|
|
523
|
+
s.kind === "enum"
|
|
524
|
+
) {
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
if (s.kind === "variable") {
|
|
528
|
+
if (/^[A-Z0-9_]{3,}$/.test(s.name)) return false;
|
|
529
|
+
if (/(?:Schema|Config|Options|Settings|Params)$/i.test(s.name)) return false;
|
|
530
|
+
return true;
|
|
531
|
+
}
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private resolveExecutableSymbol(
|
|
536
|
+
fileSymbols: SymbolRecord[],
|
|
537
|
+
importedNames: string[]
|
|
538
|
+
): SymbolRecord | undefined {
|
|
539
|
+
if (importedNames.length > 0) {
|
|
540
|
+
const matched = fileSymbols.find((s) => importedNames.includes(s.name) && this.isExecutableSymbol(s));
|
|
541
|
+
if (matched) return matched;
|
|
542
|
+
|
|
543
|
+
// If imported symbols match in this file but none are executable (e.g. types/constants),
|
|
544
|
+
// then this import was solely for non-executable definitions.
|
|
545
|
+
const nonExecutableMatched = fileSymbols.some((s) => importedNames.includes(s.name));
|
|
546
|
+
if (nonExecutableMatched) {
|
|
547
|
+
return undefined;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const executable = fileSymbols.filter((s) => this.isExecutableSymbol(s));
|
|
552
|
+
return (
|
|
553
|
+
executable.find((s) => s.kind === "class" || s.kind === "struct") ||
|
|
554
|
+
executable.find((s) => s.kind === "function" || s.kind === "method") ||
|
|
555
|
+
executable[0]
|
|
556
|
+
);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
public traverseMethodScopedDependencies(
|
|
560
|
+
startFile: FileRecord,
|
|
561
|
+
methodBody: string,
|
|
562
|
+
methodSymbol: SymbolRecord,
|
|
563
|
+
chain: ExecutionChainNode[],
|
|
564
|
+
maxDepth: number = 5
|
|
565
|
+
): void {
|
|
566
|
+
const visitedFiles = new Set<string>();
|
|
567
|
+
visitedFiles.add(startFile.path);
|
|
568
|
+
|
|
569
|
+
const deps = this.fileDependencies(startFile.id);
|
|
570
|
+
const scopeText = (methodSymbol.signature || "") + "\n" + methodBody;
|
|
571
|
+
|
|
572
|
+
for (const dep of deps) {
|
|
573
|
+
if (/^\s*(?:import|export)\s+type\b/.test(dep.statement)) continue;
|
|
574
|
+
if (chain.length >= CallGraphTracer.MAX_CHAIN_NODES) break;
|
|
575
|
+
const importedNames = this.extractImportedSymbolNames(dep.statement);
|
|
576
|
+
const baseTarget = dep.target.split(/[\/\\]/).pop()?.replace(/\.[^.]+$/, "") || "";
|
|
577
|
+
|
|
578
|
+
// Only include if imported symbol or target name is referenced in the method scope (signature + body)
|
|
579
|
+
const isReferenced =
|
|
580
|
+
(importedNames.length > 0 &&
|
|
581
|
+
importedNames.some((name) => {
|
|
582
|
+
const camel = name.charAt(0).toLowerCase() + name.slice(1);
|
|
583
|
+
return scopeText.includes(name) || scopeText.includes(camel);
|
|
584
|
+
})) ||
|
|
585
|
+
(baseTarget.length > 0 &&
|
|
586
|
+
(scopeText.includes(baseTarget) ||
|
|
587
|
+
scopeText.includes(baseTarget.charAt(0).toLowerCase() + baseTarget.slice(1))));
|
|
588
|
+
|
|
589
|
+
if (!isReferenced) {
|
|
590
|
+
// Drop uncalled static import to eliminate cognitive noise and payload bloat
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const resolvedFiles = this.repo.getMeta?.("workspace_root")
|
|
595
|
+
? this.resolveImportTargets(startFile.path, dep.target)
|
|
596
|
+
: dep.is_external
|
|
597
|
+
? []
|
|
598
|
+
: [this.resolveImportToFile(startFile.path, dep.target)].filter((file): file is FileRecord => !!file);
|
|
599
|
+
|
|
600
|
+
for (const resolvedFile of resolvedFiles) {
|
|
601
|
+
if (!resolvedFile || visitedFiles.has(resolvedFile.path)) continue;
|
|
602
|
+
visitedFiles.add(resolvedFile.path);
|
|
603
|
+
|
|
604
|
+
const stage = this.detectStage(resolvedFile.path, resolvedFile.archetype);
|
|
605
|
+
const fileSymbols = this.fileSymbols(resolvedFile.id);
|
|
606
|
+
const mainSymbol = this.resolveExecutableSymbol(fileSymbols, importedNames);
|
|
607
|
+
if (!mainSymbol) {
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const symbolDisplay = mainSymbol.name;
|
|
612
|
+
|
|
613
|
+
const shortSymbolDisplay = symbolDisplay.split(/[\\:]/).pop();
|
|
614
|
+
const existingNode = chain.find(
|
|
615
|
+
(c) =>
|
|
616
|
+
(c.file && c.file === resolvedFile.path) ||
|
|
617
|
+
(c.stage === stage &&
|
|
618
|
+
(c.symbol === symbolDisplay || c.symbol.split(/[\\:]/).pop() === shortSymbolDisplay))
|
|
619
|
+
);
|
|
620
|
+
|
|
621
|
+
if (!existingNode) {
|
|
622
|
+
chain.push({
|
|
623
|
+
stage,
|
|
624
|
+
symbol: symbolDisplay,
|
|
625
|
+
file: resolvedFile.path,
|
|
626
|
+
line: mainSymbol.line_start || 1,
|
|
627
|
+
description: `${stage.toUpperCase()} (referenced import): ${symbolDisplay}`,
|
|
628
|
+
relationship: {
|
|
629
|
+
kind: "imports",
|
|
630
|
+
derivation: "source",
|
|
631
|
+
source: { file: startFile.path, line: dep.line_number, statement: dep.statement },
|
|
632
|
+
reason: "import referenced in method scope; not proof of a call",
|
|
633
|
+
},
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Traverse outbound dependencies using BFS with cycle detection, max hop limit, and node ceiling.
|
|
642
|
+
*/
|
|
643
|
+
public traverseOutboundDependencies(
|
|
644
|
+
startFile: FileRecord,
|
|
645
|
+
chain: ExecutionChainNode[],
|
|
646
|
+
maxDepth: number = 5
|
|
647
|
+
): void {
|
|
648
|
+
const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
|
|
649
|
+
const visitedFiles = new Set<string>();
|
|
650
|
+
visitedFiles.add(startFile.path);
|
|
651
|
+
const queue: Array<{ file: FileRecord; depth: number }> = [
|
|
652
|
+
{ file: startFile, depth: 1 },
|
|
653
|
+
];
|
|
654
|
+
|
|
655
|
+
while (queue.length > 0 && chain.length < CallGraphTracer.MAX_CHAIN_NODES) {
|
|
656
|
+
const current = queue.shift()!;
|
|
657
|
+
if (current.depth > effectiveMaxDepth) break;
|
|
658
|
+
|
|
659
|
+
const deps = this.fileDependencies(current.file.id);
|
|
660
|
+
|
|
661
|
+
for (const dep of deps) {
|
|
662
|
+
if (/^\s*(?:import|export)\s+type\b/.test(dep.statement)) continue;
|
|
663
|
+
if (chain.length >= CallGraphTracer.MAX_CHAIN_NODES) break;
|
|
664
|
+
const resolvedFiles = this.repo.getMeta?.("workspace_root") ? this.resolveImportTargets(current.file.path, dep.target)
|
|
665
|
+
: dep.is_external ? [] : [this.resolveImportToFile(current.file.path, dep.target)].filter((file): file is FileRecord => !!file);
|
|
666
|
+
for (const resolvedFile of resolvedFiles) {
|
|
667
|
+
if (!resolvedFile || visitedFiles.has(resolvedFile.path)) continue;
|
|
668
|
+
|
|
669
|
+
visitedFiles.add(resolvedFile.path);
|
|
670
|
+
|
|
671
|
+
const stage = this.detectStage(resolvedFile.path, resolvedFile.archetype);
|
|
672
|
+
const fileSymbols = this.fileSymbols(resolvedFile.id);
|
|
673
|
+
const importedNames = this.extractImportedSymbolNames(dep.statement);
|
|
674
|
+
const mainSymbol = this.resolveExecutableSymbol(fileSymbols, importedNames);
|
|
675
|
+
if (!mainSymbol) {
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
const symbolDisplay = mainSymbol.name;
|
|
680
|
+
|
|
681
|
+
// Prevent adding duplicate stages if already present, or add as refinement
|
|
682
|
+
const existingStageNode = chain.find(
|
|
683
|
+
(c) => c.stage === stage && c.file === resolvedFile.path
|
|
684
|
+
);
|
|
685
|
+
|
|
686
|
+
if (!existingStageNode) {
|
|
687
|
+
chain.push({
|
|
688
|
+
stage,
|
|
689
|
+
symbol: symbolDisplay,
|
|
690
|
+
file: resolvedFile.path,
|
|
691
|
+
line: mainSymbol.line_start || 1,
|
|
692
|
+
description: `${stage.toUpperCase()} (dependency, not a proven call): ${symbolDisplay}`,
|
|
693
|
+
relationship: { kind: "imports", derivation: "source", source: { file: current.file.path, line: dep.line_number, statement: dep.statement }, reason: "static import; stage classification is inferred" },
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
queue.push({ file: resolvedFile, depth: current.depth + 1 });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// Sort stages according to standard pipeline order
|
|
703
|
+
const stageOrder: Record<string, number> = {
|
|
704
|
+
ingress: 1,
|
|
705
|
+
validation: 2,
|
|
706
|
+
controller: 3,
|
|
707
|
+
orchestrator: 3,
|
|
708
|
+
use_case: 4,
|
|
709
|
+
service: 4,
|
|
710
|
+
domain: 5,
|
|
711
|
+
entity: 5,
|
|
712
|
+
egress: 6,
|
|
713
|
+
repository: 6,
|
|
714
|
+
};
|
|
715
|
+
|
|
716
|
+
chain.sort((a, b) => {
|
|
717
|
+
const orderA = stageOrder[a.stage] || 99;
|
|
718
|
+
const orderB = stageOrder[b.stage] || 99;
|
|
719
|
+
return orderA - orderB;
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
if (chain.length > CallGraphTracer.MAX_CHAIN_NODES) {
|
|
723
|
+
chain.length = CallGraphTracer.MAX_CHAIN_NODES;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
private extractImportedSymbolNames(statement: string): string[] {
|
|
728
|
+
if (!statement) return [];
|
|
729
|
+
const names = new Set<string>();
|
|
730
|
+
const braceMatch = statement.match(/\{([^}]+)\}/);
|
|
731
|
+
if (braceMatch) {
|
|
732
|
+
for (const spec of braceMatch[1].split(",")) {
|
|
733
|
+
const cleaned = spec.trim().replace(/^type\s+/, "");
|
|
734
|
+
const parts = cleaned.split(/\s+as\s+/);
|
|
735
|
+
for (const p of parts) {
|
|
736
|
+
const id = p.trim();
|
|
737
|
+
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(id)) names.add(id);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
const defaultMatch = statement.match(/^\s*import\s+(?:type\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/);
|
|
742
|
+
if (defaultMatch) names.add(defaultMatch[1]);
|
|
743
|
+
const pyMatch = statement.match(/\bfrom\s+[^\s]+\s+import\s+([^;(\n]+)/);
|
|
744
|
+
if (pyMatch) {
|
|
745
|
+
for (const spec of pyMatch[1].split(",")) {
|
|
746
|
+
const parts = spec.trim().split(/\s+as\s+/);
|
|
747
|
+
const id = (parts[0] || "").trim();
|
|
748
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) names.add(id);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const phpMatch = statement.match(/^\s*use\s+(?:function\s+|const\s+)?[A-Za-z0-9_\\]+\\([A-Za-z0-9_]+)/);
|
|
752
|
+
if (phpMatch) names.add(phpMatch[1]);
|
|
753
|
+
return Array.from(names);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Detect generic pipeline stage from file path and archetype.
|
|
758
|
+
*/
|
|
759
|
+
public detectStage(filePath: string, archetype: string): string {
|
|
760
|
+
const norm = filePath.toLowerCase();
|
|
761
|
+
|
|
762
|
+
if (
|
|
763
|
+
archetype === "validation" ||
|
|
764
|
+
archetype === "dto" ||
|
|
765
|
+
/validation|middleware|dto|request|schema/i.test(norm)
|
|
766
|
+
) {
|
|
767
|
+
return "validation";
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
if (archetype === "controller" || /controller|handler/i.test(norm)) {
|
|
771
|
+
return "controller";
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (
|
|
775
|
+
archetype === "service" ||
|
|
776
|
+
archetype === "use_case" ||
|
|
777
|
+
/use-?cases?|interactor|application|workflow/i.test(norm)
|
|
778
|
+
) {
|
|
779
|
+
return "use_case";
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
if (
|
|
783
|
+
archetype === "model" ||
|
|
784
|
+
archetype === "entity" ||
|
|
785
|
+
/domain|entities|entity|aggregate/i.test(norm)
|
|
786
|
+
) {
|
|
787
|
+
return "entity";
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
if (
|
|
791
|
+
archetype === "repository" ||
|
|
792
|
+
/repositories|repository|database|persistence|egress|adapter/i.test(norm)
|
|
793
|
+
) {
|
|
794
|
+
return "repository";
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
return "service";
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Resolve an import target path (relative or alias) to a FileRecord in the catalog.
|
|
802
|
+
*/
|
|
803
|
+
public resolveImportTargets(sourceFilePath: string, importTarget: string): FileRecord[] {
|
|
804
|
+
if (!this.importEvidence && !this.evidenceByFile.has(sourceFilePath)) {
|
|
805
|
+
this.evidenceByFile.set(sourceFilePath, this.repo.getImportRelationships(this.projectRoot, sourceFilePath));
|
|
806
|
+
}
|
|
807
|
+
const evidence = (this.importEvidence ?? this.evidenceByFile.get(sourceFilePath))?.find(edge => edge.source.file === sourceFilePath && edge.resolution.source.target === importTarget);
|
|
808
|
+
if (evidence && (evidence.freshness !== "current" || evidence.index_coverage !== "complete")) return [];
|
|
809
|
+
const result = evidence?.resolution ?? new ImportResolver(this.projectRoot, this.repo.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(importTarget,sourceFilePath);
|
|
810
|
+
if (result.status !== "resolved" || result.coverage === "conditional") {
|
|
811
|
+
// Fallback: check symbols in repository (e.g. PHP namespace classes, Go packages, Python modules)
|
|
812
|
+
const matching = this.repo.findSymbolsByName(importTarget);
|
|
813
|
+
if (matching.length === 1) {
|
|
814
|
+
const file = this.fileForPath(matching[0].file_path);
|
|
815
|
+
if (file) return [file];
|
|
816
|
+
}
|
|
817
|
+
const shortName = importTarget.split(/[\/\\]/).pop();
|
|
818
|
+
if (shortName && shortName !== importTarget) {
|
|
819
|
+
const shortMatches = this.repo.findSymbolsByName(shortName);
|
|
820
|
+
if (shortMatches.length === 1) {
|
|
821
|
+
const file = this.fileForPath(shortMatches[0].file_path);
|
|
822
|
+
if (file) return [file];
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
return [];
|
|
826
|
+
}
|
|
827
|
+
return result.targets.flatMap(target => target.files).flatMap(file => {
|
|
828
|
+
const indexed = this.fileForPath(file);
|
|
829
|
+
return indexed ? [indexed] : [];
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
public resolveImportToFile(sourceFilePath: string, importTarget: string): FileRecord | undefined {
|
|
834
|
+
if (this.repo.getMeta?.("workspace_root")) {
|
|
835
|
+
const targets = this.resolveImportTargets(sourceFilePath,importTarget);
|
|
836
|
+
return targets.length === 1 ? targets[0] : undefined;
|
|
837
|
+
}
|
|
838
|
+
// 1. Relative import (./ or ../)
|
|
839
|
+
if (importTarget.startsWith(".")) {
|
|
840
|
+
const sourceDir = dirname(sourceFilePath);
|
|
841
|
+
const combined = normalize(join(sourceDir, importTarget)).replace(/\\/g, "/");
|
|
842
|
+
|
|
843
|
+
const candidates = [
|
|
844
|
+
combined,
|
|
845
|
+
`${combined}.ts`,
|
|
846
|
+
`${combined}.tsx`,
|
|
847
|
+
`${combined}.js`,
|
|
848
|
+
`${combined}.jsx`,
|
|
849
|
+
`${combined}/index.ts`,
|
|
850
|
+
`${combined}/index.js`,
|
|
851
|
+
];
|
|
852
|
+
|
|
853
|
+
for (const cand of candidates) {
|
|
854
|
+
const found = this.fileForPath(cand);
|
|
855
|
+
if (found) return found;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// 2. Alias import (@/... or src/...)
|
|
860
|
+
const cleanAlias = importTarget.replace(/^@\//, "src/");
|
|
861
|
+
const aliasCandidates = [
|
|
862
|
+
cleanAlias,
|
|
863
|
+
`${cleanAlias}.ts`,
|
|
864
|
+
`${cleanAlias}.tsx`,
|
|
865
|
+
`${cleanAlias}.js`,
|
|
866
|
+
`${cleanAlias}.jsx`,
|
|
867
|
+
`${cleanAlias}/index.ts`,
|
|
868
|
+
`${cleanAlias}/index.js`,
|
|
869
|
+
];
|
|
870
|
+
|
|
871
|
+
for (const cand of aliasCandidates) {
|
|
872
|
+
const found = this.fileForPath(cand);
|
|
873
|
+
if (found) return found;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// 3. Basename search fallback
|
|
877
|
+
const baseTarget = importTarget.split("/").pop()?.replace(/\.[^.]+$/, "");
|
|
878
|
+
if (baseTarget && baseTarget.length > 3) {
|
|
879
|
+
for (const [norm, file] of this.fileMapByNormPath.entries()) {
|
|
880
|
+
if (norm.includes(`/${baseTarget.toLowerCase()}.`) || norm.endsWith(`/${baseTarget.toLowerCase()}`)) {
|
|
881
|
+
return file;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
return undefined;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Locate a symbol in the codebase or relative to a file.
|
|
891
|
+
*/
|
|
892
|
+
private locateSymbol(
|
|
893
|
+
symbolName: string,
|
|
894
|
+
relativeToFile?: string
|
|
895
|
+
): { file: string; line: number } | null {
|
|
896
|
+
const cleanSymbol = symbolName.replace(/[()]/g, "").trim();
|
|
897
|
+
|
|
898
|
+
// Check imports of relativeToFile first
|
|
899
|
+
if (relativeToFile) {
|
|
900
|
+
const file = this.fileMapByNormPath.get(this.normalizeFilePath(relativeToFile));
|
|
901
|
+
if (file) {
|
|
902
|
+
const deps = this.fileDependencies(file.id);
|
|
903
|
+
for (const dep of deps) {
|
|
904
|
+
if (dep.target.includes(cleanSymbol) || dep.statement.includes(cleanSymbol)) {
|
|
905
|
+
const targetFile = this.resolveImportToFile(relativeToFile, dep.target);
|
|
906
|
+
if (targetFile) {
|
|
907
|
+
const syms = this.fileSymbols(targetFile.id);
|
|
908
|
+
const s = syms.find((sym) => sym.name === cleanSymbol);
|
|
909
|
+
return {
|
|
910
|
+
file: targetFile.path,
|
|
911
|
+
line: s?.line_start || 1,
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// Global symbol search
|
|
920
|
+
for (const [fileId, syms] of this.symbolsByFileId.entries()) {
|
|
921
|
+
const match = syms.find((s) => s.name === cleanSymbol);
|
|
922
|
+
if (match) {
|
|
923
|
+
const file = this.fileMapById.get(fileId);
|
|
924
|
+
if (file) {
|
|
925
|
+
return { file: file.path, line: match.line_start };
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Find FileRecord and Symbol by identifier or class name.
|
|
935
|
+
*/
|
|
936
|
+
private findFileBySymbolOrName(
|
|
937
|
+
ident: string,
|
|
938
|
+
contextFile?: string,
|
|
939
|
+
visited = new Set<string>()
|
|
940
|
+
): { file: FileRecord; symbol?: SymbolRecord } | null {
|
|
941
|
+
if (contextFile && visited.has(contextFile)) return null;
|
|
942
|
+
if (contextFile) visited.add(contextFile);
|
|
943
|
+
const cleanIdent = ident.replace(/controller$/i, "").toLowerCase();
|
|
944
|
+
|
|
945
|
+
// 1. Try imports of contextFile
|
|
946
|
+
if (contextFile) {
|
|
947
|
+
const srcFile = this.fileMapByNormPath.get(this.normalizeFilePath(contextFile));
|
|
948
|
+
if (srcFile) {
|
|
949
|
+
const deps = this.fileDependencies(srcFile.id);
|
|
950
|
+
for (const d of deps) {
|
|
951
|
+
if (d.statement.toLowerCase().includes(cleanIdent) || d.target.toLowerCase().includes(cleanIdent)) {
|
|
952
|
+
const resolved = this.resolveImportToFile(contextFile, d.target);
|
|
953
|
+
if (resolved) {
|
|
954
|
+
const syms = this.fileSymbols(resolved.id);
|
|
955
|
+
const sym = syms.find(
|
|
956
|
+
(s) => s.name.toLowerCase() === ident.toLowerCase() || s.name.toLowerCase().includes(cleanIdent)
|
|
957
|
+
);
|
|
958
|
+
if (sym) {
|
|
959
|
+
return { file: resolved, symbol: sym };
|
|
960
|
+
}
|
|
961
|
+
if (visited.size < 5) {
|
|
962
|
+
const reExported = this.findFileBySymbolOrName(ident, resolved.path, visited);
|
|
963
|
+
if (reExported?.symbol) return reExported;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// 2. Try match file path
|
|
972
|
+
for (const [norm, file] of this.fileMapByNormPath.entries()) {
|
|
973
|
+
if (norm.toLowerCase().includes(cleanIdent) && norm.toLowerCase().includes("controller")) {
|
|
974
|
+
const syms = this.fileSymbols(file.id);
|
|
975
|
+
return { file, symbol: syms.find((s) => s.kind === "class") };
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
return null;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* Build a VerticalSliceRecord structure from an execution chain.
|
|
984
|
+
*/
|
|
985
|
+
private buildSliceRecordFromChain(
|
|
986
|
+
httpMethod: string,
|
|
987
|
+
routeUri: string,
|
|
988
|
+
chain: ExecutionChainNode[],
|
|
989
|
+
architectureStyle: string = "clean"
|
|
990
|
+
): Omit<VerticalSliceRecord, "id" | "created_at"> {
|
|
991
|
+
const controllerNode = chain.find((c) => c.stage === "controller" || c.stage === "orchestrator");
|
|
992
|
+
|
|
993
|
+
const ctrlParts = controllerNode?.symbol.split("::") || [];
|
|
994
|
+
const controllerClass = ctrlParts[0] || "Controller";
|
|
995
|
+
const actionName = ctrlParts[1] || "handle";
|
|
996
|
+
|
|
997
|
+
return {
|
|
998
|
+
domain_id: null,
|
|
999
|
+
feature_key: null,
|
|
1000
|
+
http_method: httpMethod,
|
|
1001
|
+
route_uri: routeUri,
|
|
1002
|
+
route_name: `${httpMethod.toLowerCase()}.${routeUri.replace(/[^a-zA-Z0-9]/g, "_").replace(/^_+|_+$/g, "")}`,
|
|
1003
|
+
controller_class: controllerClass,
|
|
1004
|
+
action_name: actionName,
|
|
1005
|
+
controller_file: controllerNode?.file || null,
|
|
1006
|
+
controller_line: controllerNode?.line || 0,
|
|
1007
|
+
architecture_style: architectureStyle,
|
|
1008
|
+
entry_kind: "http_route",
|
|
1009
|
+
execution_chain_json: JSON.stringify(chain),
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
private inferRouteUri(filePath: string, methodName: string): string {
|
|
1014
|
+
const base = filePath
|
|
1015
|
+
.split("/")
|
|
1016
|
+
.pop()
|
|
1017
|
+
?.replace(/controller\.[^.]+$/i, "")
|
|
1018
|
+
.replace(/\.[^.]+$/, "")
|
|
1019
|
+
.toLowerCase();
|
|
1020
|
+
|
|
1021
|
+
const resource = base ? `/${base}s` : "/resource";
|
|
1022
|
+
if (/store|create/i.test(methodName)) return resource;
|
|
1023
|
+
if (/show|get|find/i.test(methodName)) return `${resource}/:id`;
|
|
1024
|
+
if (/update|edit|patch/i.test(methodName)) return `${resource}/:id`;
|
|
1025
|
+
if (/delete|destroy|remove/i.test(methodName)) return `${resource}/:id`;
|
|
1026
|
+
|
|
1027
|
+
return `${resource}/${methodName}`;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
private normalizeFilePath(p: string): string {
|
|
1031
|
+
return p.replace(/\\/g, "/").replace(/^\.\/?/, "").toLowerCase();
|
|
1032
|
+
}
|
|
1033
|
+
}
|