@dimassetoid/septum-mcp 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +46 -28
  2. package/package.json +4 -4
  3. package/src/cli/commands/check.ts +27 -16
  4. package/src/cli/commands/hook.ts +38 -101
  5. package/src/cli/commands/init.ts +26 -9
  6. package/src/cli/commands/sync.ts +4 -6
  7. package/src/cli/hook-payload.ts +43 -0
  8. package/src/cli/index.ts +9 -52
  9. package/src/cli/scaffold/harness-config.ts +48 -8
  10. package/src/cli/templates/hooks.ts +49 -14
  11. package/src/cli/templates/rules.ts +34 -49
  12. package/src/cli/templates/skill.ts +39 -35
  13. package/src/core/boundary/evaluator.ts +67 -83
  14. package/src/core/boundary/staged-auditor.ts +102 -40
  15. package/src/core/config/domain-ownership.ts +45 -0
  16. package/src/core/config/loader.ts +81 -29
  17. package/src/core/config/schema.ts +0 -10
  18. package/src/core/database/repositories/dependency.repository.ts +169 -148
  19. package/src/core/database/repositories/domain.repository.ts +46 -3
  20. package/src/core/database/repositories/symbol.repository.ts +226 -87
  21. package/src/core/database/repository.ts +73 -18
  22. package/src/core/database/schema.ts +2 -33
  23. package/src/core/discovery/navigation.ts +105 -0
  24. package/src/core/discovery/topology-detector.ts +60 -2
  25. package/src/core/ingestion/pipeline.ts +96 -129
  26. package/src/core/parser/behavioral-analyzer.ts +26 -22
  27. package/src/core/parser/boundary-tracker.ts +15 -0
  28. package/src/core/parser/extractors/base.ts +7 -3
  29. package/src/core/parser/extractors/csharp.ts +7 -3
  30. package/src/core/parser/extractors/django-semantic.ts +4 -36
  31. package/src/core/parser/extractors/elysia-semantic.ts +3 -24
  32. package/src/core/parser/extractors/express-semantic.ts +3 -18
  33. package/src/core/parser/extractors/fastapi-semantic.ts +19 -53
  34. package/src/core/parser/extractors/fastify-semantic.ts +3 -18
  35. package/src/core/parser/extractors/flask-semantic.ts +22 -55
  36. package/src/core/parser/extractors/go-semantic.ts +92 -33
  37. package/src/core/parser/extractors/hono-semantic.ts +3 -24
  38. package/src/core/parser/extractors/java.ts +5 -3
  39. package/src/core/parser/extractors/laravel-semantic.ts +44 -16
  40. package/src/core/parser/extractors/mcp-cli-semantic.ts +6 -7
  41. package/src/core/parser/extractors/nestjs-semantic.ts +3 -19
  42. package/src/core/parser/extractors/php.ts +16 -0
  43. package/src/core/parser/extractors/python.ts +9 -4
  44. package/src/core/parser/extractors/registry.ts +26 -5
  45. package/src/core/parser/extractors/ruby.ts +8 -5
  46. package/src/core/parser/extractors/rust.ts +31 -13
  47. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  48. package/src/core/parser/extractors/symfony-semantic.ts +4 -37
  49. package/src/core/parser/extractors/typescript.ts +14 -1
  50. package/src/core/parser/implementation-fingerprint.ts +97 -0
  51. package/src/core/parser/language-capabilities.ts +23 -7
  52. package/src/core/parser/schema/providers/laravel-migration-provider.ts +73 -50
  53. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  54. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  55. package/src/core/parser/semantic-revision.ts +3 -0
  56. package/src/core/parser/static-string.ts +51 -0
  57. package/src/core/resolver/call-graph-tracer.ts +337 -28
  58. package/src/core/resolver/import-resolver.ts +107 -179
  59. package/src/core/resolver/interpretation-inputs.ts +7 -0
  60. package/src/core/resolver/languages/go.ts +103 -0
  61. package/src/core/resolver/languages/managed.ts +200 -0
  62. package/src/core/resolver/languages/python.ts +115 -0
  63. package/src/core/resolver/languages/ruby.ts +40 -0
  64. package/src/core/resolver/languages/rust.ts +127 -0
  65. package/src/core/resolver/languages/shared.ts +71 -0
  66. package/src/core/resolver/module-resolver.ts +8 -4
  67. package/src/core/resolver/slice-catalog.ts +79 -0
  68. package/src/core/resolver/slice-format.ts +9 -0
  69. package/src/core/resolver/symbol-impact.ts +381 -0
  70. package/src/core/resolver/vertical-slice-tracer.ts +93 -115
  71. package/src/core/resources/ignore.ts +22 -1
  72. package/src/core/resources/source-files.ts +143 -20
  73. package/src/core/resources/source-inventory.ts +55 -0
  74. package/src/core/retrieval/context-page.ts +109 -0
  75. package/src/core/retrieval/context.ts +320 -0
  76. package/src/core/retrieval/resolution-warnings.ts +21 -0
  77. package/src/core/retrieval/symbol-evidence.ts +97 -0
  78. package/src/core/retrieval/typescript-references.ts +262 -0
  79. package/src/core/telemetry/telemetry.ts +54 -9
  80. package/src/index.ts +0 -3
  81. package/src/mcp/schemas.ts +61 -420
  82. package/src/mcp/server.ts +116 -290
  83. package/src/mcp/tools/boundary.ts +2 -2
  84. package/src/mcp/tools/check-boundary.ts +55 -60
  85. package/src/mcp/tools/get-domain-catalog.ts +32 -219
  86. package/src/mcp/tools/get-symbol-impact.ts +45 -5
  87. package/src/mcp/tools/get-symbol.ts +227 -3
  88. package/src/mcp/tools/locate-symbol.ts +54 -14
  89. package/src/mcp/tools/{domain.ts → map.ts} +4 -18
  90. package/src/mcp/tools/register-domain.ts +41 -3
  91. package/src/mcp/tools/symbol.ts +23 -21
  92. package/src/mcp/tools/trace-vertical-slice.ts +36 -10
  93. package/src/mcp/workspace-manager.ts +15 -4
  94. package/src/mcp/workspace-watcher.ts +8 -8
  95. package/src/types/index.ts +35 -53
  96. package/src/cli/commands/topology.ts +0 -161
  97. package/src/core/database/repositories/environment.repository.ts +0 -207
  98. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  99. package/src/core/session/session-manager.ts +0 -107
  100. package/src/core/topology/environment-detector.ts +0 -973
  101. package/src/core/topology/types.ts +0 -83
  102. package/src/mcp/tools/feature.ts +0 -67
  103. package/src/mcp/tools/get-environment-topology.ts +0 -138
  104. package/src/mcp/tools/get-feature-context.ts +0 -224
  105. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  106. package/src/mcp/tools/register-feature.ts +0 -110
@@ -23,6 +23,7 @@ export interface DiscoveredRoute {
23
23
 
24
24
  export class CallGraphTracer {
25
25
  private importEvidence?: ReturnType<SeptumRepository["getImportRelationships"]>;
26
+ private evidenceByFile = new Map<string, ReturnType<SeptumRepository["getImportRelationships"]>>();
26
27
  private fileMapByNormPath: Map<string, FileRecord> = new Map();
27
28
  private fileMapById: Map<number, FileRecord> = new Map();
28
29
  private symbolsByFileId: Map<number, SymbolRecord[]> = new Map();
@@ -33,10 +34,33 @@ export class CallGraphTracer {
33
34
 
34
35
  constructor(private repo: SeptumRepository, private projectRoot: string = process.cwd()) {}
35
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
+
36
58
  /**
37
59
  * Initializes internal fast lookup maps from SQLite repository data.
38
60
  */
39
61
  public initMaps(): void {
62
+ this.fileMapByNormPath.clear(); this.fileMapById.clear();
63
+ this.symbolsByFileId.clear(); this.dependenciesByFileId.clear(); this.evidenceByFile.clear();
40
64
  const allSymbolsWithFiles = this.repo.getAllSymbolsWithFiles();
41
65
  const allDeps = this.repo.getAllDependenciesWithDomains();
42
66
  this.importEvidence = this.repo.getMeta?.("workspace_root") ? this.repo.getImportRelationships(this.projectRoot) : undefined;
@@ -160,7 +184,7 @@ export class CallGraphTracer {
160
184
  /**
161
185
  * Build execution chains for all discovered entrypoints and controller actions.
162
186
  */
163
- public traceAllSlices(maxDepth: number = 5): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
187
+ public traceAllSlices(maxDepth: number = 5, options: { includeInferredControllers?: boolean; excludeEntrypointFiles?: ReadonlySet<string> } = {}): Array<Omit<VerticalSliceRecord, "id" | "created_at">> {
164
188
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
165
189
  this.initMaps();
166
190
  const slices: Array<Omit<VerticalSliceRecord, "id" | "created_at">> = [];
@@ -168,6 +192,7 @@ export class CallGraphTracer {
168
192
 
169
193
  // 1. Trace from declarative routes
170
194
  for (const route of declarativeRoutes) {
195
+ if (options.excludeEntrypointFiles?.has(route.file)) continue;
171
196
  const chain = this.traceChainFromRoute(route, effectiveMaxDepth);
172
197
  if (chain.length > 0) {
173
198
  const sliceRecord = this.buildSliceRecordFromChain(
@@ -180,6 +205,8 @@ export class CallGraphTracer {
180
205
  }
181
206
  }
182
207
 
208
+ if (options.includeInferredControllers === false) return slices;
209
+
183
210
  // 2. Trace controllers if routes were not explicitly bound or found
184
211
  for (const [normPath, file] of this.fileMapByNormPath.entries()) {
185
212
  const isController =
@@ -190,7 +217,7 @@ export class CallGraphTracer {
190
217
 
191
218
  if (!isController) continue;
192
219
 
193
- const symbols = this.symbolsByFileId.get(file.id) || [];
220
+ const symbols = this.fileSymbols(file.id);
194
221
  const methods = symbols.filter((s) => s.kind === "method" || s.kind === "function");
195
222
 
196
223
  for (const m of methods) {
@@ -278,7 +305,7 @@ export class CallGraphTracer {
278
305
  }
279
306
 
280
307
  if (controllerFile) {
281
- const syms = this.symbolsByFileId.get(controllerFile.id) || [];
308
+ const syms = this.fileSymbols(controllerFile.id);
282
309
  const methodSym = syms.find(
283
310
  (s) => s.name.toLowerCase() === actionMethod.toLowerCase()
284
311
  );
@@ -315,7 +342,7 @@ export class CallGraphTracer {
315
342
  ): ExecutionChainNode[] {
316
343
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
317
344
  const chain: ExecutionChainNode[] = [];
318
- const syms = this.symbolsByFileId.get(controllerFile.id) || [];
345
+ const syms = this.fileSymbols(controllerFile.id);
319
346
  const ctrlName =
320
347
  syms.find((s) => s.kind === "class")?.name ||
321
348
  controllerFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") ||
@@ -363,10 +390,7 @@ export class CallGraphTracer {
363
390
  maxDepth: number = 5
364
391
  ): ExecutionChainNode[] {
365
392
  const effectiveMaxDepth = Math.min(Math.max(Math.trunc(maxDepth || 5), 1), 8);
366
- if (this.fileMapByNormPath.size === 0) {
367
- this.initMaps();
368
- }
369
- const startFile = this.fileMapByNormPath.get(this.normalizeFilePath(controllerFilePath));
393
+ const startFile = this.fileForPath(controllerFilePath);
370
394
  if (!startFile) {
371
395
  return existingChain.slice(0, CallGraphTracer.MAX_CHAIN_NODES);
372
396
  }
@@ -376,6 +400,243 @@ export class CallGraphTracer {
376
400
  return chain;
377
401
  }
378
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
+
379
640
  /**
380
641
  * Traverse outbound dependencies using BFS with cycle detection, max hop limit, and node ceiling.
381
642
  */
@@ -395,9 +656,10 @@ export class CallGraphTracer {
395
656
  const current = queue.shift()!;
396
657
  if (current.depth > effectiveMaxDepth) break;
397
658
 
398
- const deps = this.dependenciesByFileId.get(current.file.id) || [];
659
+ const deps = this.fileDependencies(current.file.id);
399
660
 
400
661
  for (const dep of deps) {
662
+ if (/^\s*(?:import|export)\s+type\b/.test(dep.statement)) continue;
401
663
  if (chain.length >= CallGraphTracer.MAX_CHAIN_NODES) break;
402
664
  const resolvedFiles = this.repo.getMeta?.("workspace_root") ? this.resolveImportTargets(current.file.path, dep.target)
403
665
  : dep.is_external ? [] : [this.resolveImportToFile(current.file.path, dep.target)].filter((file): file is FileRecord => !!file);
@@ -407,15 +669,14 @@ export class CallGraphTracer {
407
669
  visitedFiles.add(resolvedFile.path);
408
670
 
409
671
  const stage = this.detectStage(resolvedFile.path, resolvedFile.archetype);
410
- const fileSymbols = this.symbolsByFileId.get(resolvedFile.id) || [];
411
- const mainSymbol =
412
- fileSymbols.find((s) => s.kind === "class" || s.kind === "interface") ||
413
- fileSymbols.find((s) => s.kind === "function") ||
414
- fileSymbols[0];
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
+ }
415
678
 
416
- const symbolDisplay = mainSymbol
417
- ? mainSymbol.name
418
- : resolvedFile.path.split("/").pop()?.replace(/\.[^.]+$/, "") || "Module";
679
+ const symbolDisplay = mainSymbol.name;
419
680
 
420
681
  // Prevent adding duplicate stages if already present, or add as refinement
421
682
  const existingStageNode = chain.find(
@@ -427,7 +688,7 @@ export class CallGraphTracer {
427
688
  stage,
428
689
  symbol: symbolDisplay,
429
690
  file: resolvedFile.path,
430
- line: mainSymbol?.line_start || 1,
691
+ line: mainSymbol.line_start || 1,
431
692
  description: `${stage.toUpperCase()} (dependency, not a proven call): ${symbolDisplay}`,
432
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" },
433
694
  });
@@ -463,6 +724,35 @@ export class CallGraphTracer {
463
724
  }
464
725
  }
465
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
+
466
756
  /**
467
757
  * Detect generic pipeline stage from file path and archetype.
468
758
  */
@@ -511,12 +801,31 @@ export class CallGraphTracer {
511
801
  * Resolve an import target path (relative or alias) to a FileRecord in the catalog.
512
802
  */
513
803
  public resolveImportTargets(sourceFilePath: string, importTarget: string): FileRecord[] {
514
- const evidence = this.importEvidence?.find(edge => edge.source.file === sourceFilePath && edge.resolution.source.target === importTarget);
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);
515
808
  if (evidence && (evidence.freshness !== "current" || evidence.index_coverage !== "complete")) return [];
516
809
  const result = evidence?.resolution ?? new ImportResolver(this.projectRoot, this.repo.getAllDomains?.().map(domain => domain.root_path) ?? []).resolve(importTarget,sourceFilePath);
517
- if (result.status !== "resolved" || result.coverage === "conditional") return [];
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
+ }
518
827
  return result.targets.flatMap(target => target.files).flatMap(file => {
519
- const indexed = this.fileMapByNormPath.get(this.normalizeFilePath(file));
828
+ const indexed = this.fileForPath(file);
520
829
  return indexed ? [indexed] : [];
521
830
  });
522
831
  }
@@ -542,7 +851,7 @@ export class CallGraphTracer {
542
851
  ];
543
852
 
544
853
  for (const cand of candidates) {
545
- const found = this.fileMapByNormPath.get(this.normalizeFilePath(cand));
854
+ const found = this.fileForPath(cand);
546
855
  if (found) return found;
547
856
  }
548
857
  }
@@ -560,7 +869,7 @@ export class CallGraphTracer {
560
869
  ];
561
870
 
562
871
  for (const cand of aliasCandidates) {
563
- const found = this.fileMapByNormPath.get(this.normalizeFilePath(cand));
872
+ const found = this.fileForPath(cand);
564
873
  if (found) return found;
565
874
  }
566
875
 
@@ -590,12 +899,12 @@ export class CallGraphTracer {
590
899
  if (relativeToFile) {
591
900
  const file = this.fileMapByNormPath.get(this.normalizeFilePath(relativeToFile));
592
901
  if (file) {
593
- const deps = this.dependenciesByFileId.get(file.id) || [];
902
+ const deps = this.fileDependencies(file.id);
594
903
  for (const dep of deps) {
595
904
  if (dep.target.includes(cleanSymbol) || dep.statement.includes(cleanSymbol)) {
596
905
  const targetFile = this.resolveImportToFile(relativeToFile, dep.target);
597
906
  if (targetFile) {
598
- const syms = this.symbolsByFileId.get(targetFile.id) || [];
907
+ const syms = this.fileSymbols(targetFile.id);
599
908
  const s = syms.find((sym) => sym.name === cleanSymbol);
600
909
  return {
601
910
  file: targetFile.path,
@@ -637,12 +946,12 @@ export class CallGraphTracer {
637
946
  if (contextFile) {
638
947
  const srcFile = this.fileMapByNormPath.get(this.normalizeFilePath(contextFile));
639
948
  if (srcFile) {
640
- const deps = this.dependenciesByFileId.get(srcFile.id) || [];
949
+ const deps = this.fileDependencies(srcFile.id);
641
950
  for (const d of deps) {
642
951
  if (d.statement.toLowerCase().includes(cleanIdent) || d.target.toLowerCase().includes(cleanIdent)) {
643
952
  const resolved = this.resolveImportToFile(contextFile, d.target);
644
953
  if (resolved) {
645
- const syms = this.symbolsByFileId.get(resolved.id) || [];
954
+ const syms = this.fileSymbols(resolved.id);
646
955
  const sym = syms.find(
647
956
  (s) => s.name.toLowerCase() === ident.toLowerCase() || s.name.toLowerCase().includes(cleanIdent)
648
957
  );
@@ -662,7 +971,7 @@ export class CallGraphTracer {
662
971
  // 2. Try match file path
663
972
  for (const [norm, file] of this.fileMapByNormPath.entries()) {
664
973
  if (norm.toLowerCase().includes(cleanIdent) && norm.toLowerCase().includes("controller")) {
665
- const syms = this.symbolsByFileId.get(file.id) || [];
974
+ const syms = this.fileSymbols(file.id);
666
975
  return { file, symbol: syms.find((s) => s.kind === "class") };
667
976
  }
668
977
  }