gitnexus 1.3.11 → 1.4.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 (91) hide show
  1. package/README.md +22 -2
  2. package/dist/cli/ai-context.d.ts +2 -1
  3. package/dist/cli/ai-context.js +15 -6
  4. package/dist/cli/analyze.d.ts +2 -0
  5. package/dist/cli/analyze.js +12 -2
  6. package/dist/cli/index.js +2 -0
  7. package/dist/cli/skill-gen.d.ts +26 -0
  8. package/dist/cli/skill-gen.js +549 -0
  9. package/dist/core/graph/types.d.ts +5 -2
  10. package/dist/core/ingestion/call-processor.d.ts +5 -5
  11. package/dist/core/ingestion/call-processor.js +173 -260
  12. package/dist/core/ingestion/constants.d.ts +16 -0
  13. package/dist/core/ingestion/constants.js +16 -0
  14. package/dist/core/ingestion/entry-point-scoring.d.ts +2 -1
  15. package/dist/core/ingestion/entry-point-scoring.js +81 -22
  16. package/dist/core/ingestion/export-detection.d.ts +18 -0
  17. package/dist/core/ingestion/export-detection.js +230 -0
  18. package/dist/core/ingestion/framework-detection.d.ts +5 -1
  19. package/dist/core/ingestion/framework-detection.js +39 -8
  20. package/dist/core/ingestion/heritage-processor.d.ts +13 -4
  21. package/dist/core/ingestion/heritage-processor.js +92 -28
  22. package/dist/core/ingestion/import-processor.d.ts +17 -19
  23. package/dist/core/ingestion/import-processor.js +170 -695
  24. package/dist/core/ingestion/language-config.d.ts +46 -0
  25. package/dist/core/ingestion/language-config.js +167 -0
  26. package/dist/core/ingestion/mro-processor.d.ts +45 -0
  27. package/dist/core/ingestion/mro-processor.js +369 -0
  28. package/dist/core/ingestion/named-binding-extraction.d.ts +61 -0
  29. package/dist/core/ingestion/named-binding-extraction.js +363 -0
  30. package/dist/core/ingestion/parsing-processor.d.ts +1 -10
  31. package/dist/core/ingestion/parsing-processor.js +41 -177
  32. package/dist/core/ingestion/pipeline.js +26 -24
  33. package/dist/core/ingestion/process-processor.js +2 -1
  34. package/dist/core/ingestion/resolvers/csharp.d.ts +22 -0
  35. package/dist/core/ingestion/resolvers/csharp.js +109 -0
  36. package/dist/core/ingestion/resolvers/go.d.ts +19 -0
  37. package/dist/core/ingestion/resolvers/go.js +42 -0
  38. package/dist/core/ingestion/resolvers/index.d.ts +16 -0
  39. package/dist/core/ingestion/resolvers/index.js +11 -0
  40. package/dist/core/ingestion/resolvers/jvm.d.ts +23 -0
  41. package/dist/core/ingestion/resolvers/jvm.js +87 -0
  42. package/dist/core/ingestion/resolvers/php.d.ts +15 -0
  43. package/dist/core/ingestion/resolvers/php.js +35 -0
  44. package/dist/core/ingestion/resolvers/rust.d.ts +15 -0
  45. package/dist/core/ingestion/resolvers/rust.js +73 -0
  46. package/dist/core/ingestion/resolvers/standard.d.ts +28 -0
  47. package/dist/core/ingestion/resolvers/standard.js +145 -0
  48. package/dist/core/ingestion/resolvers/utils.d.ts +33 -0
  49. package/dist/core/ingestion/resolvers/utils.js +120 -0
  50. package/dist/core/ingestion/symbol-resolver.d.ts +32 -0
  51. package/dist/core/ingestion/symbol-resolver.js +83 -0
  52. package/dist/core/ingestion/symbol-table.d.ts +12 -1
  53. package/dist/core/ingestion/symbol-table.js +19 -12
  54. package/dist/core/ingestion/tree-sitter-queries.d.ts +11 -11
  55. package/dist/core/ingestion/tree-sitter-queries.js +114 -9
  56. package/dist/core/ingestion/type-env.d.ts +27 -0
  57. package/dist/core/ingestion/type-env.js +86 -0
  58. package/dist/core/ingestion/type-extractors/c-cpp.d.ts +2 -0
  59. package/dist/core/ingestion/type-extractors/c-cpp.js +60 -0
  60. package/dist/core/ingestion/type-extractors/csharp.d.ts +2 -0
  61. package/dist/core/ingestion/type-extractors/csharp.js +89 -0
  62. package/dist/core/ingestion/type-extractors/go.d.ts +2 -0
  63. package/dist/core/ingestion/type-extractors/go.js +105 -0
  64. package/dist/core/ingestion/type-extractors/index.d.ts +21 -0
  65. package/dist/core/ingestion/type-extractors/index.js +29 -0
  66. package/dist/core/ingestion/type-extractors/jvm.d.ts +3 -0
  67. package/dist/core/ingestion/type-extractors/jvm.js +121 -0
  68. package/dist/core/ingestion/type-extractors/php.d.ts +2 -0
  69. package/dist/core/ingestion/type-extractors/php.js +31 -0
  70. package/dist/core/ingestion/type-extractors/python.d.ts +2 -0
  71. package/dist/core/ingestion/type-extractors/python.js +41 -0
  72. package/dist/core/ingestion/type-extractors/rust.d.ts +2 -0
  73. package/dist/core/ingestion/type-extractors/rust.js +39 -0
  74. package/dist/core/ingestion/type-extractors/shared.d.ts +17 -0
  75. package/dist/core/ingestion/type-extractors/shared.js +97 -0
  76. package/dist/core/ingestion/type-extractors/swift.d.ts +2 -0
  77. package/dist/core/ingestion/type-extractors/swift.js +43 -0
  78. package/dist/core/ingestion/type-extractors/types.d.ts +14 -0
  79. package/dist/core/ingestion/type-extractors/types.js +1 -0
  80. package/dist/core/ingestion/type-extractors/typescript.d.ts +2 -0
  81. package/dist/core/ingestion/type-extractors/typescript.js +46 -0
  82. package/dist/core/ingestion/utils.d.ts +67 -0
  83. package/dist/core/ingestion/utils.js +691 -4
  84. package/dist/core/ingestion/workers/parse-worker.d.ts +20 -3
  85. package/dist/core/ingestion/workers/parse-worker.js +84 -345
  86. package/dist/core/kuzu/csv-generator.js +19 -3
  87. package/dist/core/kuzu/kuzu-adapter.js +3 -0
  88. package/dist/core/kuzu/schema.d.ts +3 -3
  89. package/dist/core/kuzu/schema.js +16 -1
  90. package/dist/mcp/tools.js +12 -3
  91. package/package.json +1 -1
@@ -0,0 +1,46 @@
1
+ /** TypeScript path alias config parsed from tsconfig.json */
2
+ export interface TsconfigPaths {
3
+ /** Map of alias prefix -> target prefix (e.g., "@/" -> "src/") */
4
+ aliases: Map<string, string>;
5
+ /** Base URL for path resolution (relative to repo root) */
6
+ baseUrl: string;
7
+ }
8
+ /** Go module config parsed from go.mod */
9
+ export interface GoModuleConfig {
10
+ /** Module path (e.g., "github.com/user/repo") */
11
+ modulePath: string;
12
+ }
13
+ /** PHP Composer PSR-4 autoload config */
14
+ export interface ComposerConfig {
15
+ /** Map of namespace prefix -> directory (e.g., "App\\" -> "app/") */
16
+ psr4: Map<string, string>;
17
+ }
18
+ /** C# project config parsed from .csproj files */
19
+ export interface CSharpProjectConfig {
20
+ /** Root namespace from <RootNamespace> or assembly name (default: project directory name) */
21
+ rootNamespace: string;
22
+ /** Directory containing the .csproj file */
23
+ projectDir: string;
24
+ }
25
+ /** Swift Package Manager module config */
26
+ export interface SwiftPackageConfig {
27
+ /** Map of target name -> source directory path (e.g., "SiuperModel" -> "Package/Sources/SiuperModel") */
28
+ targets: Map<string, string>;
29
+ }
30
+ /**
31
+ * Parse tsconfig.json to extract path aliases.
32
+ * Tries tsconfig.json, tsconfig.app.json, tsconfig.base.json in order.
33
+ */
34
+ export declare function loadTsconfigPaths(repoRoot: string): Promise<TsconfigPaths | null>;
35
+ /**
36
+ * Parse go.mod to extract module path.
37
+ */
38
+ export declare function loadGoModulePath(repoRoot: string): Promise<GoModuleConfig | null>;
39
+ /** Parse composer.json to extract PSR-4 autoload mappings (including autoload-dev). */
40
+ export declare function loadComposerConfig(repoRoot: string): Promise<ComposerConfig | null>;
41
+ /**
42
+ * Parse .csproj files to extract RootNamespace.
43
+ * Scans the repo root for .csproj files and returns configs for each.
44
+ */
45
+ export declare function loadCSharpProjectConfig(repoRoot: string): Promise<CSharpProjectConfig[]>;
46
+ export declare function loadSwiftPackageConfig(repoRoot: string): Promise<SwiftPackageConfig | null>;
@@ -0,0 +1,167 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ const isDev = process.env.NODE_ENV === 'development';
4
+ // ============================================================================
5
+ // LANGUAGE-SPECIFIC CONFIG LOADERS
6
+ // ============================================================================
7
+ /**
8
+ * Parse tsconfig.json to extract path aliases.
9
+ * Tries tsconfig.json, tsconfig.app.json, tsconfig.base.json in order.
10
+ */
11
+ export async function loadTsconfigPaths(repoRoot) {
12
+ const candidates = ['tsconfig.json', 'tsconfig.app.json', 'tsconfig.base.json'];
13
+ for (const filename of candidates) {
14
+ try {
15
+ const tsconfigPath = path.join(repoRoot, filename);
16
+ const raw = await fs.readFile(tsconfigPath, 'utf-8');
17
+ // Strip JSON comments (// and /* */ style) for robustness
18
+ const stripped = raw.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
19
+ const tsconfig = JSON.parse(stripped);
20
+ const compilerOptions = tsconfig.compilerOptions;
21
+ if (!compilerOptions?.paths)
22
+ continue;
23
+ const baseUrl = compilerOptions.baseUrl || '.';
24
+ const aliases = new Map();
25
+ for (const [pattern, targets] of Object.entries(compilerOptions.paths)) {
26
+ if (!Array.isArray(targets) || targets.length === 0)
27
+ continue;
28
+ const target = targets[0];
29
+ // Convert glob patterns: "@/*" -> "@/", "src/*" -> "src/"
30
+ const aliasPrefix = pattern.endsWith('/*') ? pattern.slice(0, -1) : pattern;
31
+ const targetPrefix = target.endsWith('/*') ? target.slice(0, -1) : target;
32
+ aliases.set(aliasPrefix, targetPrefix);
33
+ }
34
+ if (aliases.size > 0) {
35
+ if (isDev) {
36
+ console.log(`📦 Loaded ${aliases.size} path aliases from ${filename}`);
37
+ }
38
+ return { aliases, baseUrl };
39
+ }
40
+ }
41
+ catch {
42
+ // File doesn't exist or isn't valid JSON - try next
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Parse go.mod to extract module path.
49
+ */
50
+ export async function loadGoModulePath(repoRoot) {
51
+ try {
52
+ const goModPath = path.join(repoRoot, 'go.mod');
53
+ const content = await fs.readFile(goModPath, 'utf-8');
54
+ const match = content.match(/^module\s+(\S+)/m);
55
+ if (match) {
56
+ if (isDev) {
57
+ console.log(`📦 Loaded Go module path: ${match[1]}`);
58
+ }
59
+ return { modulePath: match[1] };
60
+ }
61
+ }
62
+ catch {
63
+ // No go.mod
64
+ }
65
+ return null;
66
+ }
67
+ /** Parse composer.json to extract PSR-4 autoload mappings (including autoload-dev). */
68
+ export async function loadComposerConfig(repoRoot) {
69
+ try {
70
+ const composerPath = path.join(repoRoot, 'composer.json');
71
+ const raw = await fs.readFile(composerPath, 'utf-8');
72
+ const composer = JSON.parse(raw);
73
+ const psr4Raw = composer.autoload?.['psr-4'] ?? {};
74
+ const psr4Dev = composer['autoload-dev']?.['psr-4'] ?? {};
75
+ const merged = { ...psr4Raw, ...psr4Dev };
76
+ const psr4 = new Map();
77
+ for (const [ns, dir] of Object.entries(merged)) {
78
+ const nsNorm = ns.replace(/\\+$/, '');
79
+ const dirNorm = dir.replace(/\\/g, '/').replace(/\/+$/, '');
80
+ psr4.set(nsNorm, dirNorm);
81
+ }
82
+ if (isDev) {
83
+ console.log(`📦 Loaded ${psr4.size} PSR-4 mappings from composer.json`);
84
+ }
85
+ return { psr4 };
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ /**
92
+ * Parse .csproj files to extract RootNamespace.
93
+ * Scans the repo root for .csproj files and returns configs for each.
94
+ */
95
+ export async function loadCSharpProjectConfig(repoRoot) {
96
+ const configs = [];
97
+ // BFS scan for .csproj files up to 5 levels deep, cap at 100 dirs to avoid runaway scanning
98
+ const scanQueue = [{ dir: repoRoot, depth: 0 }];
99
+ const maxDepth = 5;
100
+ const maxDirs = 100;
101
+ let dirsScanned = 0;
102
+ while (scanQueue.length > 0 && dirsScanned < maxDirs) {
103
+ const { dir, depth } = scanQueue.shift();
104
+ dirsScanned++;
105
+ try {
106
+ const entries = await fs.readdir(dir, { withFileTypes: true });
107
+ for (const entry of entries) {
108
+ if (entry.isDirectory() && depth < maxDepth) {
109
+ // Skip common non-project directories
110
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'bin' || entry.name === 'obj')
111
+ continue;
112
+ scanQueue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
113
+ }
114
+ if (entry.isFile() && entry.name.endsWith('.csproj')) {
115
+ try {
116
+ const csprojPath = path.join(dir, entry.name);
117
+ const content = await fs.readFile(csprojPath, 'utf-8');
118
+ const nsMatch = content.match(/<RootNamespace>\s*([^<]+)\s*<\/RootNamespace>/);
119
+ const rootNamespace = nsMatch
120
+ ? nsMatch[1].trim()
121
+ : entry.name.replace(/\.csproj$/, '');
122
+ const projectDir = path.relative(repoRoot, dir).replace(/\\/g, '/');
123
+ configs.push({ rootNamespace, projectDir });
124
+ if (isDev) {
125
+ console.log(`📦 Loaded C# project: ${entry.name} (namespace: ${rootNamespace}, dir: ${projectDir})`);
126
+ }
127
+ }
128
+ catch {
129
+ // Can't read .csproj
130
+ }
131
+ }
132
+ }
133
+ }
134
+ catch {
135
+ // Can't read directory
136
+ }
137
+ }
138
+ return configs;
139
+ }
140
+ export async function loadSwiftPackageConfig(repoRoot) {
141
+ // Swift imports are module-name based (e.g., `import SiuperModel`)
142
+ // SPM convention: Sources/<TargetName>/ or Package/Sources/<TargetName>/
143
+ // We scan for these directories to build a target map
144
+ const targets = new Map();
145
+ const sourceDirs = ['Sources', 'Package/Sources', 'src'];
146
+ for (const sourceDir of sourceDirs) {
147
+ try {
148
+ const fullPath = path.join(repoRoot, sourceDir);
149
+ const entries = await fs.readdir(fullPath, { withFileTypes: true });
150
+ for (const entry of entries) {
151
+ if (entry.isDirectory()) {
152
+ targets.set(entry.name, sourceDir + '/' + entry.name);
153
+ }
154
+ }
155
+ }
156
+ catch {
157
+ // Directory doesn't exist
158
+ }
159
+ }
160
+ if (targets.size > 0) {
161
+ if (isDev) {
162
+ console.log(`📦 Loaded ${targets.size} Swift package targets`);
163
+ }
164
+ return { targets };
165
+ }
166
+ return null;
167
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * MRO (Method Resolution Order) Processor
3
+ *
4
+ * Walks the inheritance DAG (EXTENDS/IMPLEMENTS edges), collects methods from
5
+ * each ancestor via HAS_METHOD edges, detects method-name collisions across
6
+ * parents, and applies language-specific resolution rules to emit OVERRIDES edges.
7
+ *
8
+ * Language-specific rules:
9
+ * - C++: leftmost base class in declaration order wins
10
+ * - C#/Java: class method wins over interface default; multiple interface
11
+ * methods with same name are ambiguous (null resolution)
12
+ * - Python: C3 linearization determines MRO; first in linearized order wins
13
+ * - Rust: no auto-resolution — requires qualified syntax, resolvedTo = null
14
+ * - Default: single inheritance — first definition wins
15
+ *
16
+ * OVERRIDES edge direction: Class → Method (not Method → Method).
17
+ * The source is the child class that inherits conflicting methods,
18
+ * the target is the winning ancestor method node.
19
+ * Cypher: MATCH (c:Class)-[r:CodeRelation {type: 'OVERRIDES'}]->(m:Method)
20
+ */
21
+ import { KnowledgeGraph } from '../graph/types.js';
22
+ import { SupportedLanguages } from '../../config/supported-languages.js';
23
+ export interface MROEntry {
24
+ classId: string;
25
+ className: string;
26
+ language: SupportedLanguages;
27
+ mro: string[];
28
+ ambiguities: MethodAmbiguity[];
29
+ }
30
+ export interface MethodAmbiguity {
31
+ methodName: string;
32
+ definedIn: Array<{
33
+ classId: string;
34
+ className: string;
35
+ methodId: string;
36
+ }>;
37
+ resolvedTo: string | null;
38
+ reason: string;
39
+ }
40
+ export interface MROResult {
41
+ entries: MROEntry[];
42
+ overrideEdges: number;
43
+ ambiguityCount: number;
44
+ }
45
+ export declare function computeMRO(graph: KnowledgeGraph): MROResult;
@@ -0,0 +1,369 @@
1
+ /**
2
+ * MRO (Method Resolution Order) Processor
3
+ *
4
+ * Walks the inheritance DAG (EXTENDS/IMPLEMENTS edges), collects methods from
5
+ * each ancestor via HAS_METHOD edges, detects method-name collisions across
6
+ * parents, and applies language-specific resolution rules to emit OVERRIDES edges.
7
+ *
8
+ * Language-specific rules:
9
+ * - C++: leftmost base class in declaration order wins
10
+ * - C#/Java: class method wins over interface default; multiple interface
11
+ * methods with same name are ambiguous (null resolution)
12
+ * - Python: C3 linearization determines MRO; first in linearized order wins
13
+ * - Rust: no auto-resolution — requires qualified syntax, resolvedTo = null
14
+ * - Default: single inheritance — first definition wins
15
+ *
16
+ * OVERRIDES edge direction: Class → Method (not Method → Method).
17
+ * The source is the child class that inherits conflicting methods,
18
+ * the target is the winning ancestor method node.
19
+ * Cypher: MATCH (c:Class)-[r:CodeRelation {type: 'OVERRIDES'}]->(m:Method)
20
+ */
21
+ import { generateId } from '../../lib/utils.js';
22
+ import { SupportedLanguages } from '../../config/supported-languages.js';
23
+ // ---------------------------------------------------------------------------
24
+ // Internal helpers
25
+ // ---------------------------------------------------------------------------
26
+ /** Collect EXTENDS, IMPLEMENTS, and HAS_METHOD adjacency from the graph. */
27
+ function buildAdjacency(graph) {
28
+ // parentMap: childId → parentIds[] (in insertion / declaration order)
29
+ const parentMap = new Map();
30
+ // methodMap: classId → methodIds[]
31
+ const methodMap = new Map();
32
+ // Track which edge type each parent link came from
33
+ const parentEdgeType = new Map();
34
+ graph.forEachRelationship((rel) => {
35
+ if (rel.type === 'EXTENDS' || rel.type === 'IMPLEMENTS') {
36
+ let parents = parentMap.get(rel.sourceId);
37
+ if (!parents) {
38
+ parents = [];
39
+ parentMap.set(rel.sourceId, parents);
40
+ }
41
+ parents.push(rel.targetId);
42
+ let edgeTypes = parentEdgeType.get(rel.sourceId);
43
+ if (!edgeTypes) {
44
+ edgeTypes = new Map();
45
+ parentEdgeType.set(rel.sourceId, edgeTypes);
46
+ }
47
+ edgeTypes.set(rel.targetId, rel.type);
48
+ }
49
+ if (rel.type === 'HAS_METHOD') {
50
+ let methods = methodMap.get(rel.sourceId);
51
+ if (!methods) {
52
+ methods = [];
53
+ methodMap.set(rel.sourceId, methods);
54
+ }
55
+ methods.push(rel.targetId);
56
+ }
57
+ });
58
+ return { parentMap, methodMap, parentEdgeType };
59
+ }
60
+ /**
61
+ * Gather all ancestor IDs in BFS / topological order.
62
+ * Returns the linearized list of ancestor IDs (excluding the class itself).
63
+ */
64
+ function gatherAncestors(classId, parentMap) {
65
+ const visited = new Set();
66
+ const order = [];
67
+ const queue = [...(parentMap.get(classId) ?? [])];
68
+ while (queue.length > 0) {
69
+ const id = queue.shift();
70
+ if (visited.has(id))
71
+ continue;
72
+ visited.add(id);
73
+ order.push(id);
74
+ const grandparents = parentMap.get(id);
75
+ if (grandparents) {
76
+ for (const gp of grandparents) {
77
+ if (!visited.has(gp))
78
+ queue.push(gp);
79
+ }
80
+ }
81
+ }
82
+ return order;
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // C3 linearization (Python MRO)
86
+ // ---------------------------------------------------------------------------
87
+ /**
88
+ * Compute C3 linearization for a class given a parentMap.
89
+ * Returns an array of ancestor IDs in C3 order (excluding the class itself),
90
+ * or null if linearization fails (inconsistent or cyclic hierarchy).
91
+ */
92
+ function c3Linearize(classId, parentMap, cache, inProgress) {
93
+ if (cache.has(classId))
94
+ return cache.get(classId);
95
+ // Cycle detection: if we're already computing this class, the hierarchy is cyclic
96
+ const visiting = inProgress ?? new Set();
97
+ if (visiting.has(classId)) {
98
+ cache.set(classId, null);
99
+ return null;
100
+ }
101
+ visiting.add(classId);
102
+ const directParents = parentMap.get(classId);
103
+ if (!directParents || directParents.length === 0) {
104
+ visiting.delete(classId);
105
+ cache.set(classId, []);
106
+ return [];
107
+ }
108
+ // Compute linearization for each parent first
109
+ const parentLinearizations = [];
110
+ for (const pid of directParents) {
111
+ const pLin = c3Linearize(pid, parentMap, cache, visiting);
112
+ if (pLin === null) {
113
+ visiting.delete(classId);
114
+ cache.set(classId, null);
115
+ return null;
116
+ }
117
+ parentLinearizations.push([pid, ...pLin]);
118
+ }
119
+ // Add the direct parents list as the final sequence
120
+ const sequences = [...parentLinearizations, [...directParents]];
121
+ const result = [];
122
+ while (sequences.some(s => s.length > 0)) {
123
+ // Find a good head: one that doesn't appear in the tail of any other sequence
124
+ let head = null;
125
+ for (const seq of sequences) {
126
+ if (seq.length === 0)
127
+ continue;
128
+ const candidate = seq[0];
129
+ const inTail = sequences.some(other => other.length > 1 && other.indexOf(candidate, 1) !== -1);
130
+ if (!inTail) {
131
+ head = candidate;
132
+ break;
133
+ }
134
+ }
135
+ if (head === null) {
136
+ // Inconsistent hierarchy
137
+ visiting.delete(classId);
138
+ cache.set(classId, null);
139
+ return null;
140
+ }
141
+ result.push(head);
142
+ // Remove the chosen head from all sequences
143
+ for (const seq of sequences) {
144
+ if (seq.length > 0 && seq[0] === head) {
145
+ seq.shift();
146
+ }
147
+ }
148
+ }
149
+ visiting.delete(classId);
150
+ cache.set(classId, result);
151
+ return result;
152
+ }
153
+ /** Resolve by MRO order — first ancestor in linearized order wins. */
154
+ function resolveByMroOrder(methodName, defs, mroOrder, reasonPrefix) {
155
+ for (const ancestorId of mroOrder) {
156
+ const match = defs.find(d => d.classId === ancestorId);
157
+ if (match) {
158
+ return {
159
+ resolvedTo: match.methodId,
160
+ reason: `${reasonPrefix}: ${match.className}::${methodName}`,
161
+ };
162
+ }
163
+ }
164
+ return { resolvedTo: defs[0].methodId, reason: `${reasonPrefix} fallback: first definition` };
165
+ }
166
+ function resolveCsharpJava(methodName, defs, parentEdgeTypes) {
167
+ const classDefs = [];
168
+ const interfaceDefs = [];
169
+ for (const def of defs) {
170
+ const edgeType = parentEdgeTypes?.get(def.classId);
171
+ if (edgeType === 'IMPLEMENTS') {
172
+ interfaceDefs.push(def);
173
+ }
174
+ else {
175
+ classDefs.push(def);
176
+ }
177
+ }
178
+ if (classDefs.length > 0) {
179
+ return {
180
+ resolvedTo: classDefs[0].methodId,
181
+ reason: `class method wins: ${classDefs[0].className}::${methodName}`,
182
+ };
183
+ }
184
+ if (interfaceDefs.length > 1) {
185
+ return {
186
+ resolvedTo: null,
187
+ reason: `ambiguous: ${methodName} defined in multiple interfaces: ${interfaceDefs.map(d => d.className).join(', ')}`,
188
+ };
189
+ }
190
+ if (interfaceDefs.length === 1) {
191
+ return {
192
+ resolvedTo: interfaceDefs[0].methodId,
193
+ reason: `single interface default: ${interfaceDefs[0].className}::${methodName}`,
194
+ };
195
+ }
196
+ return { resolvedTo: null, reason: 'no resolution found' };
197
+ }
198
+ // ---------------------------------------------------------------------------
199
+ // Main entry point
200
+ // ---------------------------------------------------------------------------
201
+ export function computeMRO(graph) {
202
+ const { parentMap, methodMap, parentEdgeType } = buildAdjacency(graph);
203
+ const c3Cache = new Map();
204
+ const entries = [];
205
+ let overrideEdges = 0;
206
+ let ambiguityCount = 0;
207
+ // Process every class that has at least one parent
208
+ for (const [classId, directParents] of parentMap) {
209
+ if (directParents.length === 0)
210
+ continue;
211
+ const classNode = graph.getNode(classId);
212
+ if (!classNode)
213
+ continue;
214
+ const language = classNode.properties.language;
215
+ if (!language)
216
+ continue;
217
+ const className = classNode.properties.name;
218
+ // Compute linearized MRO depending on language
219
+ let mroOrder;
220
+ if (language === SupportedLanguages.Python) {
221
+ const c3Result = c3Linearize(classId, parentMap, c3Cache);
222
+ mroOrder = c3Result ?? gatherAncestors(classId, parentMap);
223
+ }
224
+ else {
225
+ mroOrder = gatherAncestors(classId, parentMap);
226
+ }
227
+ // Get the parent names for the MRO entry
228
+ const mroNames = mroOrder
229
+ .map(id => graph.getNode(id)?.properties.name)
230
+ .filter((n) => n !== undefined);
231
+ // Collect methods from all ancestors, grouped by method name
232
+ const methodsByName = new Map();
233
+ for (const ancestorId of mroOrder) {
234
+ const ancestorNode = graph.getNode(ancestorId);
235
+ if (!ancestorNode)
236
+ continue;
237
+ const methods = methodMap.get(ancestorId) ?? [];
238
+ for (const methodId of methods) {
239
+ const methodNode = graph.getNode(methodId);
240
+ if (!methodNode)
241
+ continue;
242
+ // Properties don't participate in method resolution order
243
+ if (methodNode.label === 'Property')
244
+ continue;
245
+ const methodName = methodNode.properties.name;
246
+ let defs = methodsByName.get(methodName);
247
+ if (!defs) {
248
+ defs = [];
249
+ methodsByName.set(methodName, defs);
250
+ }
251
+ // Avoid duplicates (same method seen via multiple paths)
252
+ if (!defs.some(d => d.methodId === methodId)) {
253
+ defs.push({
254
+ classId: ancestorId,
255
+ className: ancestorNode.properties.name,
256
+ methodId,
257
+ });
258
+ }
259
+ }
260
+ }
261
+ // Detect collisions: methods defined in 2+ different ancestors
262
+ const ambiguities = [];
263
+ // Compute transitive edge types once per class (only needed for C#/Java)
264
+ const needsEdgeTypes = language === SupportedLanguages.CSharp || language === SupportedLanguages.Java || language === SupportedLanguages.Kotlin;
265
+ const classEdgeTypes = needsEdgeTypes
266
+ ? buildTransitiveEdgeTypes(classId, parentMap, parentEdgeType)
267
+ : undefined;
268
+ for (const [methodName, defs] of methodsByName) {
269
+ if (defs.length < 2)
270
+ continue;
271
+ // Own method shadows inherited — no ambiguity
272
+ const ownMethods = methodMap.get(classId) ?? [];
273
+ const ownDefinesIt = ownMethods.some(mid => {
274
+ const mn = graph.getNode(mid);
275
+ return mn?.properties.name === methodName;
276
+ });
277
+ if (ownDefinesIt)
278
+ continue;
279
+ let resolution;
280
+ switch (language) {
281
+ case SupportedLanguages.CPlusPlus:
282
+ resolution = resolveByMroOrder(methodName, defs, mroOrder, 'C++ leftmost base');
283
+ break;
284
+ case SupportedLanguages.CSharp:
285
+ case SupportedLanguages.Java:
286
+ case SupportedLanguages.Kotlin:
287
+ resolution = resolveCsharpJava(methodName, defs, classEdgeTypes);
288
+ break;
289
+ case SupportedLanguages.Python:
290
+ resolution = resolveByMroOrder(methodName, defs, mroOrder, 'Python C3 MRO');
291
+ break;
292
+ case SupportedLanguages.Rust:
293
+ resolution = {
294
+ resolvedTo: null,
295
+ reason: `Rust requires qualified syntax: <Type as Trait>::${methodName}()`,
296
+ };
297
+ break;
298
+ default:
299
+ resolution = resolveByMroOrder(methodName, defs, mroOrder, 'first definition');
300
+ break;
301
+ }
302
+ const ambiguity = {
303
+ methodName,
304
+ definedIn: defs,
305
+ resolvedTo: resolution.resolvedTo,
306
+ reason: resolution.reason,
307
+ };
308
+ ambiguities.push(ambiguity);
309
+ if (resolution.resolvedTo === null) {
310
+ ambiguityCount++;
311
+ }
312
+ // Emit OVERRIDES edge if resolution found
313
+ if (resolution.resolvedTo !== null) {
314
+ graph.addRelationship({
315
+ id: generateId('OVERRIDES', `${classId}->${resolution.resolvedTo}`),
316
+ sourceId: classId,
317
+ targetId: resolution.resolvedTo,
318
+ type: 'OVERRIDES',
319
+ confidence: 1.0,
320
+ reason: resolution.reason,
321
+ });
322
+ overrideEdges++;
323
+ }
324
+ }
325
+ entries.push({
326
+ classId,
327
+ className,
328
+ language,
329
+ mro: mroNames,
330
+ ambiguities,
331
+ });
332
+ }
333
+ return { entries, overrideEdges, ambiguityCount };
334
+ }
335
+ /**
336
+ * Build transitive edge types for a class using BFS from the class to all ancestors.
337
+ *
338
+ * Known limitation: BFS first-reach heuristic can misclassify an interface as
339
+ * EXTENDS if it's reachable via a class chain before being seen via IMPLEMENTS.
340
+ * E.g. if BaseClass also implements IFoo, IFoo may be classified as EXTENDS.
341
+ * This affects C#/Java/Kotlin conflict resolution in rare diamond hierarchies.
342
+ */
343
+ function buildTransitiveEdgeTypes(classId, parentMap, parentEdgeType) {
344
+ const result = new Map();
345
+ const directEdges = parentEdgeType.get(classId);
346
+ if (!directEdges)
347
+ return result;
348
+ // BFS: propagate edge type from direct parents
349
+ const queue = [];
350
+ const directParents = parentMap.get(classId) ?? [];
351
+ for (const pid of directParents) {
352
+ const et = directEdges.get(pid) ?? 'EXTENDS';
353
+ if (!result.has(pid)) {
354
+ result.set(pid, et);
355
+ queue.push({ id: pid, edgeType: et });
356
+ }
357
+ }
358
+ while (queue.length > 0) {
359
+ const { id, edgeType } = queue.shift();
360
+ const grandparents = parentMap.get(id) ?? [];
361
+ for (const gp of grandparents) {
362
+ if (!result.has(gp)) {
363
+ result.set(gp, edgeType);
364
+ queue.push({ id: gp, edgeType });
365
+ }
366
+ }
367
+ }
368
+ return result;
369
+ }
@@ -0,0 +1,61 @@
1
+ import { SupportedLanguages } from '../../config/supported-languages.js';
2
+ import type { SymbolTable, SymbolDefinition } from './symbol-table.js';
3
+ import type { NamedImportMap } from './import-processor.js';
4
+ /**
5
+ * Walk a named-binding re-export chain through NamedImportMap.
6
+ *
7
+ * When file A imports { User } from B, and B re-exports { User } from C,
8
+ * the NamedImportMap for A points to B, but B has no User definition.
9
+ * This function follows the chain: A→B→C until a definition is found.
10
+ *
11
+ * Returns the definitions found at the end of the chain, or null if the
12
+ * chain breaks (missing binding, circular reference, or depth exceeded).
13
+ * Max depth 5 to prevent infinite loops.
14
+ *
15
+ * @param allDefs Pre-computed `symbolTable.lookupFuzzy(name)` result — must be the
16
+ * complete unfiltered result. Passing a file-filtered subset will cause
17
+ * silent misses at depth=0 for non-aliased bindings.
18
+ */
19
+ export declare function walkBindingChain(name: string, currentFilePath: string, symbolTable: SymbolTable, namedImportMap: NamedImportMap, allDefs: SymbolDefinition[]): SymbolDefinition[] | null;
20
+ /**
21
+ * Extract named bindings from an import AST node.
22
+ * Returns undefined if the import is not a named import (e.g., import * or default).
23
+ *
24
+ * TS: import { User, Repo as R } from './models'
25
+ * → [{local:'User', exported:'User'}, {local:'R', exported:'Repo'}]
26
+ *
27
+ * Python: from models import User, Repo as R
28
+ * → [{local:'User', exported:'User'}, {local:'R', exported:'Repo'}]
29
+ */
30
+ export declare function extractNamedBindings(importNode: any, language: SupportedLanguages): {
31
+ local: string;
32
+ exported: string;
33
+ }[] | undefined;
34
+ export declare function extractTsNamedBindings(importNode: any): {
35
+ local: string;
36
+ exported: string;
37
+ }[] | undefined;
38
+ export declare function extractPythonNamedBindings(importNode: any): {
39
+ local: string;
40
+ exported: string;
41
+ }[] | undefined;
42
+ export declare function extractKotlinNamedBindings(importNode: any): {
43
+ local: string;
44
+ exported: string;
45
+ }[] | undefined;
46
+ export declare function extractRustNamedBindings(importNode: any): {
47
+ local: string;
48
+ exported: string;
49
+ }[] | undefined;
50
+ export declare function extractPhpNamedBindings(importNode: any): {
51
+ local: string;
52
+ exported: string;
53
+ }[] | undefined;
54
+ export declare function extractCsharpNamedBindings(importNode: any): {
55
+ local: string;
56
+ exported: string;
57
+ }[] | undefined;
58
+ export declare function extractJavaNamedBindings(importNode: any): {
59
+ local: string;
60
+ exported: string;
61
+ }[] | undefined;