Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix: resolve parser bugs and address structural limitations in core-ingestion

Joseph Mikhail715fe0dcb602
diff --git a/core-ingestion/dist/index.d.ts b/core-ingestion/dist/index.d.ts
new file mode 100644
index 00000000..9106e75c
--- /dev/null
+++ b/core-ingestion/dist/index.d.ts
@@ -0,0 +1,57 @@
+import { SupportedLanguages } from './languages.js';
+export interface ParsedEntity {
+ name: string;
+ kind: string;
+ lineStart: number;
+ lineEnd: number;
+ language: string;
+ /** Direct enclosing class/interface/trait, if any (undefined for file-level entities). */
+ container?: string;
+}
+export interface ParsedRelationship {
+ srcName: string;
+ dstName: string;
+ predicate: string;
+}
+export interface FileParseResult {
+ filePath: string;
+ language: SupportedLanguages;
+ entities: ParsedEntity[];
+ relationships: ParsedRelationship[];
+}
+/** Returns true if a grammar is installed for the given file's language. */
+export declare function isGrammarSupported(filePath: string): boolean;
+export declare function parseFile(filePath: string, source: string): FileParseResult | null;
+export interface ResolvedCallEdge {
+ callerFilePath: string;
+ callerName: string;
+ calleeFilePath: string;
+ calleeName: string;
+ calleeQualifiedKey: string;
+ confidence: number;
+}
+/**
+ * Resolves CALLS relationships to their cross-file targets by building a
+ * symbol table and import map over the full batch of parsed files.
+ *
+ * Tiers (in priority order):
+ * 0.9 — import-scoped: callee is in a file the caller explicitly imports
+ * 0.5 — global fallback: callee exists in exactly one other file (unambiguous)
+ *
+ * Same-file calls (tier 0.95) are already handled correctly by buildPatch and
+ * are not emitted here.
+ *
+ * Import resolution handles:
+ * - Stem-based: './payments' → 'payments.ts'
+ * - Path-aliased: '@/lib/payments' → 'payments.ts' (last segment)
+ * - Directory index: './services' → 'services/index.ts'
+ * - Bare aliases: '@components' → 'components.ts' (strip leading non-word chars)
+ * '~lib' → 'lib.ts'
+ * - External bare: 'react' → unresolved (no match in batch)
+ *
+ * Qualified-key resolution:
+ * - Module-level function: calleeQualifiedKey === calleeName
+ * - Unambiguous class method: calleeQualifiedKey === 'ClassName.method'
+ * - Ambiguous (two classes define same method name): edge not emitted
+ */
+export declare function resolveCallEdges(results: FileParseResult[]): ResolvedCallEdge[];
diff --git a/core-ingestion/dist/index.js b/core-ingestion/dist/index.js
new file mode 100644
index 00000000..9ae8264e
--- /dev/null
+++ b/core-ingestion/dist/index.js
@@ -0,0 +1,467 @@
+import * as nodePath from 'node:path';
+// @ts-ignore — tree-sitter has no bundled types
+import Parser from 'tree-sitter';
+// @ts-ignore
+import JavaScript from 'tree-sitter-javascript';
+// @ts-ignore
+import TypeScript from 'tree-sitter-typescript';
+// @ts-ignore
+import Python from 'tree-sitter-python';
+// @ts-ignore
+import Java from 'tree-sitter-java';
+// @ts-ignore
+import C from 'tree-sitter-c';
+// @ts-ignore
+import CPP from 'tree-sitter-cpp';
+// @ts-ignore
+import CSharp from 'tree-sitter-c-sharp';
+// @ts-ignore
+import Go from 'tree-sitter-go';
+// @ts-ignore
+import Rust from 'tree-sitter-rust';
+// @ts-ignore
+import Ruby from 'tree-sitter-ruby';
+// @ts-ignore
+import PHP from 'tree-sitter-php';
+import { SupportedLanguages, languageFromPath } from './languages.js';
+import { LANGUAGE_QUERIES } from './queries.js';
+// ---------------------------------------------------------------------------
+// Language → grammar map
+// ---------------------------------------------------------------------------
+const GRAMMAR_MAP = {
+ [SupportedLanguages.JavaScript]: JavaScript,
+ [SupportedLanguages.TypeScript]: TypeScript.typescript,
+ [SupportedLanguages.Python]: Python,
+ [SupportedLanguages.Java]: Java,
+ [SupportedLanguages.C]: C,
+ [SupportedLanguages.CPlusPlus]: CPP,
+ [SupportedLanguages.CSharp]: CSharp,
+ [SupportedLanguages.Go]: Go,
+ [SupportedLanguages.Rust]: Rust,
+ [SupportedLanguages.Ruby]: Ruby,
+ [SupportedLanguages.PHP]: PHP.php_only,
+};
+// Capture key prefix → NodeKind string
+const DEFINITION_KIND_MAP = {
+ 'definition.class': 'class',
+ 'definition.interface': 'interface',
+ 'definition.function': 'function',
+ 'definition.method': 'method',
+ 'definition.struct': 'class',
+ 'definition.enum': 'class',
+ 'definition.trait': 'trait',
+ 'definition.module': 'module',
+ 'definition.namespace': 'module',
+ 'definition.impl': 'class',
+ 'definition.type': 'class',
+ 'definition.property': 'function',
+ 'definition.const': 'function',
+ 'definition.static': 'function',
+ 'definition.macro': 'function',
+ 'definition.union': 'class',
+ 'definition.typedef': 'class',
+ 'definition.template': 'class',
+ 'definition.record': 'class',
+ 'definition.delegate': 'class',
+ 'definition.annotation': 'class',
+ 'definition.constructor': 'method',
+};
+// Builtins to exclude from CALLS edges
+const BUILTINS = new Set([
+ 'print', 'println', 'len', 'range', 'int', 'str', 'float', 'list', 'dict',
+ 'set', 'tuple', 'type', 'isinstance', 'super', 'property', 'enumerate',
+ 'zip', 'map', 'filter', 'sorted', 'any', 'all', 'min', 'max', 'sum',
+ 'console', 'log', 'warn', 'error', 'debug', 'info',
+ 'module', 'exports', 'undefined', 'null', 'true', 'false',
+ 'if', 'for', 'while', 'return', 'new', 'this', 'self',
+ 'Promise', 'Array', 'Object', 'String', 'Number', 'Boolean', 'JSON',
+ 'Math', 'Date', 'Error', 'Map', 'Set', 'Symbol',
+ 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval',
+ 'process', 'Buffer', 'global', 'window', 'document',
+ 'require', 'fetch', 'parseInt', 'parseFloat', 'isNaN', 'isFinite',
+]);
+/** Returns true if a grammar is installed for the given file's language. */
+export function isGrammarSupported(filePath) {
+ const language = languageFromPath(filePath);
+ if (!language)
+ return false;
+ if (filePath.endsWith('.tsx'))
+ return true; // TSX uses TypeScript.tsx, always available
+ return GRAMMAR_MAP[language] !== undefined;
+}
+// ---------------------------------------------------------------------------
+// Parser instance (reused across calls)
+// ---------------------------------------------------------------------------
+let _parser = null;
+function getParser() {
+ if (!_parser)
+ _parser = new Parser();
+ return _parser;
+}
+// ---------------------------------------------------------------------------
+// Main parse function
+// ---------------------------------------------------------------------------
+export function parseFile(filePath, source) {
+ const language = languageFromPath(filePath);
+ if (!language)
+ return null;
+ // TypeScript TSX uses a separate grammar
+ const isTsx = filePath.endsWith('.tsx');
+ const grammar = isTsx ? TypeScript.tsx : GRAMMAR_MAP[language];
+ if (!grammar)
+ return null;
+ const queries = LANGUAGE_QUERIES[language];
+ if (!queries)
+ return null;
+ try {
+ const parser = getParser();
+ parser.setLanguage(grammar);
+ const tree = parser.parse(source);
+ const query = new Parser.Query(grammar, queries);
+ const matches = query.matches(tree.rootNode);
+ const fileName = nodePath.basename(filePath);
+ const lines = source.split('\n');
+ const entities = [
+ { name: fileName, kind: 'file', lineStart: 1, lineEnd: lines.length, language },
+ ];
+ const relationships = [];
+ // Track class ranges for containment: [name, startLine, endLine]
+ const classRanges = [];
+ // Track seen calls per enclosing scope to avoid duplicate CALLS edges
+ const seenCalls = new Map();
+ // --- First pass: collect definitions ---
+ for (const match of matches) {
+ // Definition captures: name + definition.*
+ const defCapture = match.captures.find((c) => c.name.startsWith('definition.'));
+ const nameCapture = match.captures.find((c) => c.name === 'name');
+ if (defCapture) {
+ const kind = DEFINITION_KIND_MAP[defCapture.name] ?? 'function';
+ const name = nameCapture?.node.text
+ ?? (defCapture.name === 'definition.constructor' ? 'init' : '');
+ if (!name || name.length === 0)
+ continue;
+ const defNode = defCapture.node;
+ const lineStart = defNode.startPosition.row + 1;
+ const lineEnd = defNode.endPosition.row + 1;
+ // Containment: file CONTAINS or class CONTAINS
+ const enclosing = findEnclosing(classRanges, lineStart, name);
+ entities.push({
+ name,
+ kind,
+ lineStart,
+ lineEnd,
+ language,
+ container: enclosing ?? undefined,
+ });
+ if (kind === 'class' || kind === 'interface' || kind === 'trait') {
+ classRanges.push({ name, start: lineStart, end: lineEnd });
+ }
+ if (enclosing) {
+ relationships.push({ srcName: enclosing, dstName: name, predicate: 'CONTAINS' });
+ }
+ else {
+ relationships.push({ srcName: fileName, dstName: name, predicate: 'CONTAINS' });
+ }
+ continue;
+ }
+ // Heritage: EXTENDS
+ const heritageClass = match.captures.find((c) => c.name === 'heritage.class');
+ const heritageExtends = match.captures.find((c) => c.name === 'heritage.extends' || c.name === 'heritage.trait');
+ if (heritageClass && heritageExtends) {
+ relationships.push({
+ srcName: heritageClass.node.text,
+ dstName: heritageExtends.node.text,
+ predicate: 'EXTENDS',
+ });
+ continue;
+ }
+ // Heritage: IMPLEMENTS (separate edge type, use EXTENDS for simplicity)
+ const heritageImpl = match.captures.find((c) => c.name === 'heritage.implements');
+ if (heritageClass && heritageImpl) {
+ relationships.push({
+ srcName: heritageClass.node.text,
+ dstName: heritageImpl.node.text,
+ predicate: 'EXTENDS',
+ });
+ continue;
+ }
+ }
+ // --- Second pass: calls and imports ---
+ for (const match of matches) {
+ // Import captures
+ const importSource = match.captures.find((c) => c.name === 'import.source');
+ if (importSource) {
+ let importPath = importSource.node.text
+ .replace(/^["'`]|["'`]$/g, '') // strip quotes
+ .replace(/\\\\/g, '/'); // normalise backslashes
+ if (importPath.length > 0 && importPath !== '*') {
+ const rawMod = importPath.split('/').filter(s => s !== '*').pop() ?? importPath;
+ const modName = rawMod.replace(/^\.+/, ''); // strip leading dots: '.models' → 'models'
+ if (!modName)
+ continue; // skip bare '.' relative imports
+ entities.push({ name: modName, kind: 'module', lineStart: importSource.node.startPosition.row + 1, lineEnd: importSource.node.startPosition.row + 1, language });
+ relationships.push({ srcName: fileName, dstName: modName, predicate: 'IMPORTS' });
+ }
+ continue;
+ }
+ // Import name captures (e.g. from . import utils — the symbol name, not the module path)
+ const importName = match.captures.find((c) => c.name === 'import.name');
+ if (importName) {
+ const name = importName.node.text;
+ if (name && name !== '*' && name.length > 1) {
+ entities.push({ name, kind: 'module', lineStart: importName.node.startPosition.row + 1, lineEnd: importName.node.startPosition.row + 1, language });
+ relationships.push({ srcName: fileName, dstName: name, predicate: 'IMPORTS' });
+ }
+ continue;
+ }
+ // Call captures
+ const callName = match.captures.find((c) => c.name === 'call.name');
+ if (callName) {
+ const callee = callName.node.text;
+ if (!callee || BUILTINS.has(callee) || callee.length <= 1)
+ continue;
+ // Find enclosing function/method for the call
+ const callLine = callName.node.startPosition.row + 1;
+ const caller = findEnclosingFunction(entities, callLine) ?? fileName;
+ const scope = caller;
+ if (!seenCalls.has(scope))
+ seenCalls.set(scope, new Set());
+ const seen = seenCalls.get(scope);
+ if (!seen.has(callee)) {
+ seen.add(callee);
+ relationships.push({ srcName: caller, dstName: callee, predicate: 'CALLS' });
+ }
+ continue;
+ }
+ }
+ return { filePath, language, entities, relationships };
+ }
+ catch {
+ return null;
+ }
+}
+// ---------------------------------------------------------------------------
+// resolveCallEdges helpers
+// ---------------------------------------------------------------------------
+/** Build the qualified key for an entity (mirrors buildPatch's entityQKey logic). */
+function qualifiedKey(e) {
+ return e.container ? `${e.container}.${e.name}` : e.name;
+}
+/**
+ * Given a file's qualified-key map and a plain callee name, return the single
+ * unambiguous qualified key, or null if the name maps to 0 or >1 entities.
+ * Callers must treat null as "do not emit" to avoid dangling nodeIds.
+ */
+function bestQKey(fileQKeys, filePath, plainName) {
+ const qks = fileQKeys.get(filePath)?.get(plainName) ?? [];
+ return qks.length === 1 ? qks[0] : null;
+}
+/**
+ * Resolves CALLS relationships to their cross-file targets by building a
+ * symbol table and import map over the full batch of parsed files.
+ *
+ * Tiers (in priority order):
+ * 0.9 — import-scoped: callee is in a file the caller explicitly imports
+ * 0.5 — global fallback: callee exists in exactly one other file (unambiguous)
+ *
+ * Same-file calls (tier 0.95) are already handled correctly by buildPatch and
+ * are not emitted here.
+ *
+ * Import resolution handles:
+ * - Stem-based: './payments' → 'payments.ts'
+ * - Path-aliased: '@/lib/payments' → 'payments.ts' (last segment)
+ * - Directory index: './services' → 'services/index.ts'
+ * - Bare aliases: '@components' → 'components.ts' (strip leading non-word chars)
+ * '~lib' → 'lib.ts'
+ * - External bare: 'react' → unresolved (no match in batch)
+ *
+ * Qualified-key resolution:
+ * - Module-level function: calleeQualifiedKey === calleeName
+ * - Unambiguous class method: calleeQualifiedKey === 'ClassName.method'
+ * - Ambiguous (two classes define same method name): edge not emitted
+ */
+export function resolveCallEdges(results) {
+ // fileQKeys: filePath → (plainName → qualifiedKeys[])
+ // Mirrors the entityQKey computation in buildPatch so nodeIds match exactly.
+ const fileQKeys = new Map();
+ for (const r of results) {
+ const qkMap = new Map();
+ for (const e of r.entities) {
+ if (e.kind === 'file' || e.kind === 'module')
+ continue;
+ const qk = qualifiedKey(e);
+ const list = qkMap.get(e.name) ?? [];
+ list.push(qk);
+ qkMap.set(e.name, list);
+ }
+ fileQKeys.set(r.filePath, qkMap);
+ }
+ // fileHasSymbol: filePath → Set<plainName> (fast membership check)
+ const fileHasSymbol = new Map();
+ for (const [fp, qkMap] of fileQKeys) {
+ fileHasSymbol.set(fp, new Set(qkMap.keys()));
+ }
+ // stemToFiles: basename-without-extension → filePath[]
+ // Matches the last path segment of an import to files in the batch.
+ // e.g. './payments' → modName 'payments' → 'payments.ts'
+ // '@/lib/payments' → modName 'payments' → 'payments.ts'
+ const stemToFiles = new Map();
+ for (const r of results) {
+ const stem = nodePath.basename(r.filePath, nodePath.extname(r.filePath));
+ const list = stemToFiles.get(stem) ?? [];
+ list.push(r.filePath);
+ stemToFiles.set(stem, list);
+ }
+ // dirToIndexFiles: directory basename → filePath[] for 'index.*' files
+ // Handles directory imports: './services' → 'services/index.ts'
+ const dirToIndexFiles = new Map();
+ for (const r of results) {
+ const stem = nodePath.basename(r.filePath, nodePath.extname(r.filePath));
+ if (stem === 'index') {
+ const dirName = nodePath.basename(nodePath.dirname(r.filePath));
+ const list = dirToIndexFiles.get(dirName) ?? [];
+ list.push(r.filePath);
+ dirToIndexFiles.set(dirName, list);
+ }
+ }
+ const resolved = [];
+ for (const result of results) {
+ const callerFilePath = result.filePath;
+ const callerSymbols = fileHasSymbol.get(callerFilePath);
+ // Build the set of file paths this caller explicitly imports.
+ // For each IMPORTS edge, try the modName as-is, then with leading
+ // non-word characters stripped (handles bare aliases: '@components' → 'components',
+ // '~lib' → 'lib', '#utils' → 'utils').
+ const importedFilePaths = new Set();
+ for (const rel of result.relationships) {
+ if (rel.predicate !== 'IMPORTS')
+ continue;
+ const candidates = [rel.dstName];
+ const stripped = rel.dstName.replace(/^[^a-zA-Z0-9_]+/, '');
+ if (stripped && stripped !== rel.dstName)
+ candidates.push(stripped);
+ for (const modName of candidates) {
+ for (const fp of stemToFiles.get(modName) ?? []) {
+ if (fp !== callerFilePath)
+ importedFilePaths.add(fp);
+ }
+ for (const fp of dirToIndexFiles.get(modName) ?? []) {
+ if (fp !== callerFilePath)
+ importedFilePaths.add(fp);
+ }
+ }
+ }
+ // Build one-hop transitive import set: files imported by directly-imported files.
+ // Handles re-exports: baz.ts → index.ts (re-exports from bar.ts) → bar.ts
+ const transitiveFilePaths = new Set();
+ for (const fp of importedFilePaths) {
+ const fpResult = results.find(r => r.filePath === fp);
+ if (!fpResult)
+ continue;
+ for (const rel of fpResult.relationships) {
+ if (rel.predicate !== 'IMPORTS')
+ continue;
+ const candidates = [rel.dstName];
+ const stripped = rel.dstName.replace(/^[^a-zA-Z0-9_]+/, '');
+ if (stripped && stripped !== rel.dstName)
+ candidates.push(stripped);
+ for (const modName of candidates) {
+ for (const transitiveFp of stemToFiles.get(modName) ?? []) {
+ if (transitiveFp !== callerFilePath && !importedFilePaths.has(transitiveFp))
+ transitiveFilePaths.add(transitiveFp);
+ }
+ for (const transitiveFp of dirToIndexFiles.get(modName) ?? []) {
+ if (transitiveFp !== callerFilePath && !importedFilePaths.has(transitiveFp))
+ transitiveFilePaths.add(transitiveFp);
+ }
+ }
+ }
+ }
+ for (const rel of result.relationships) {
+ if (rel.predicate !== 'CALLS')
+ continue;
+ const calleeName = rel.dstName;
+ const callerName = rel.srcName;
+ // Tier 1: same-file — already correct in buildPatch, skip here
+ if (callerSymbols.has(calleeName))
+ continue;
+ // Tier 2: import-scoped (confidence 0.9)
+ const importMatches = [];
+ for (const fp of importedFilePaths) {
+ if (fileHasSymbol.get(fp)?.has(calleeName))
+ importMatches.push(fp);
+ }
+ if (importMatches.length === 1) {
+ const fp = importMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null)
+ continue; // ambiguous class methods — do not emit bad nodeId
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.9 });
+ continue;
+ }
+ if (importMatches.length > 1)
+ continue; // ambiguous file — do not emit
+ // Tier 2.5: transitive import-scoped (confidence 0.8) — one re-export hop away
+ const transitiveMatches = [];
+ for (const fp of transitiveFilePaths) {
+ if (fileHasSymbol.get(fp)?.has(calleeName))
+ transitiveMatches.push(fp);
+ }
+ if (transitiveMatches.length === 1) {
+ const fp = transitiveMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null)
+ continue;
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.8 });
+ continue;
+ }
+ if (transitiveMatches.length > 1)
+ continue; // ambiguous — do not emit
+ // Tier 3: global fallback (confidence 0.5) — exactly one other file defines it
+ const globalMatches = [];
+ for (const [fp, symbols] of fileHasSymbol) {
+ if (fp !== callerFilePath && symbols.has(calleeName))
+ globalMatches.push(fp);
+ }
+ if (globalMatches.length === 1) {
+ const fp = globalMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null)
+ continue; // ambiguous class methods — do not emit bad nodeId
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.5 });
+ }
+ // 0 or >1 global matches — leave as dangling edge, do not emit
+ }
+ }
+ return resolved;
+}
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+function findEnclosing(ranges, line, excludeName) {
+ // Find the innermost class/interface that contains this line
+ let best = null;
+ for (const r of ranges) {
+ if (r.name === excludeName)
+ continue;
+ if (line >= r.start && line <= r.end) {
+ if (!best || (r.end - r.start) < (best.end - best.start)) {
+ best = r;
+ }
+ }
+ }
+ return best?.name ?? null;
+}
+function findEnclosingFunction(entities, line) {
+ let best = null;
+ for (const e of entities) {
+ if (e.kind !== 'function' && e.kind !== 'method')
+ continue;
+ if (line >= e.lineStart && line <= e.lineEnd) {
+ if (!best || (e.lineEnd - e.lineStart) < (best.lineEnd - best.lineStart)) {
+ best = e;
+ }
+ }
+ }
+ return best ? (best.container ? `${best.container}.${best.name}` : best.name) : null;
+}
diff --git a/core-ingestion/dist/languages.d.ts b/core-ingestion/dist/languages.d.ts
new file mode 100644
index 00000000..210c5d21
--- /dev/null
+++ b/core-ingestion/dist/languages.d.ts
@@ -0,0 +1,16 @@
+export declare enum SupportedLanguages {
+ JavaScript = "javascript",
+ TypeScript = "typescript",
+ Python = "python",
+ Java = "java",
+ C = "c",
+ CPlusPlus = "cpp",
+ CSharp = "csharp",
+ Go = "go",
+ Ruby = "ruby",
+ Rust = "rust",
+ PHP = "php",
+ Kotlin = "kotlin",
+ Swift = "swift"
+}
+export declare function languageFromPath(filePath: string): SupportedLanguages | null;
diff --git a/core-ingestion/dist/languages.js b/core-ingestion/dist/languages.js
new file mode 100644
index 00000000..12fcf558
--- /dev/null
+++ b/core-ingestion/dist/languages.js
@@ -0,0 +1,44 @@
+export var SupportedLanguages;
+(function (SupportedLanguages) {
+ SupportedLanguages["JavaScript"] = "javascript";
+ SupportedLanguages["TypeScript"] = "typescript";
+ SupportedLanguages["Python"] = "python";
+ SupportedLanguages["Java"] = "java";
+ SupportedLanguages["C"] = "c";
+ SupportedLanguages["CPlusPlus"] = "cpp";
+ SupportedLanguages["CSharp"] = "csharp";
+ SupportedLanguages["Go"] = "go";
+ SupportedLanguages["Ruby"] = "ruby";
+ SupportedLanguages["Rust"] = "rust";
+ SupportedLanguages["PHP"] = "php";
+ SupportedLanguages["Kotlin"] = "kotlin";
+ SupportedLanguages["Swift"] = "swift";
+})(SupportedLanguages || (SupportedLanguages = {}));
+const EXT_MAP = {
+ '.ts': SupportedLanguages.TypeScript,
+ '.tsx': SupportedLanguages.TypeScript,
+ '.js': SupportedLanguages.JavaScript,
+ '.jsx': SupportedLanguages.JavaScript,
+ '.mjs': SupportedLanguages.JavaScript,
+ '.cjs': SupportedLanguages.JavaScript,
+ '.py': SupportedLanguages.Python,
+ '.java': SupportedLanguages.Java,
+ '.c': SupportedLanguages.C,
+ '.h': SupportedLanguages.C,
+ '.cpp': SupportedLanguages.CPlusPlus,
+ '.cc': SupportedLanguages.CPlusPlus,
+ '.cxx': SupportedLanguages.CPlusPlus,
+ '.hpp': SupportedLanguages.CPlusPlus,
+ '.cs': SupportedLanguages.CSharp,
+ '.go': SupportedLanguages.Go,
+ '.rb': SupportedLanguages.Ruby,
+ '.rs': SupportedLanguages.Rust,
+ '.php': SupportedLanguages.PHP,
+ '.kt': SupportedLanguages.Kotlin,
+ '.kts': SupportedLanguages.Kotlin,
+ '.swift': SupportedLanguages.Swift,
+};
+export function languageFromPath(filePath) {
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
+ return EXT_MAP[ext] ?? null;
+}
diff --git a/core-ingestion/dist/patch-builder.d.ts b/core-ingestion/dist/patch-builder.d.ts
new file mode 100644
index 00000000..181f65c5
--- /dev/null
+++ b/core-ingestion/dist/patch-builder.d.ts
@@ -0,0 +1,4 @@
+import type { GraphPatchPayload } from './types.js';
+import type { FileParseResult, ResolvedCallEdge } from './index.js';
+export declare function buildPatch(result: FileParseResult, sourceHash: string, previousSourceHash?: string): GraphPatchPayload;
+export declare function buildPatchWithResolution(result: FileParseResult, sourceHash: string, resolvedEdges: ResolvedCallEdge[], previousSourceHash?: string): GraphPatchPayload;
diff --git a/core-ingestion/dist/patch-builder.js b/core-ingestion/dist/patch-builder.js
new file mode 100644
index 00000000..8c34e648
--- /dev/null
+++ b/core-ingestion/dist/patch-builder.js
@@ -0,0 +1,237 @@
+import * as crypto from 'node:crypto';
+import * as nodePath from 'node:path';
+// ---------------------------------------------------------------------------
+// Deterministic UUID from a string (matches existing CLI convention)
+// ---------------------------------------------------------------------------
+function deterministicId(input) {
+ const hash = crypto.createHash('sha256').update(input).digest('hex');
+ return [
+ hash.slice(0, 8),
+ hash.slice(8, 12),
+ hash.slice(12, 16),
+ hash.slice(16, 20),
+ hash.slice(20, 32),
+ ].join('-');
+}
+function nodeId(filePath, name) {
+ return deterministicId(`${filePath}:${name}`);
+}
+function edgeId(filePath, src, dst, predicate) {
+ return deterministicId(`${filePath}:${src}:${dst}:${predicate}`);
+}
+// ---------------------------------------------------------------------------
+// Source type from file extension
+// ---------------------------------------------------------------------------
+function sourceType(filePath) {
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
+ if (['.json', '.yaml', '.yml', '.toml', '.ini', '.conf', '.env'].includes(ext))
+ return 'config';
+ if (['.md', '.mdx', '.rst', '.txt'].includes(ext))
+ return 'doc';
+ return 'code';
+}
+function extractorName() {
+ return `tree-sitter/1.0`;
+}
+// ---------------------------------------------------------------------------
+// Build a GraphPatchPayload from a FileParseResult
+// ---------------------------------------------------------------------------
+export function buildPatch(result, sourceHash, previousSourceHash) {
+ const { filePath, entities, relationships } = result;
+ const ops = [];
+ // Build a qualified-key map so that same-named entities in different
+ // enclosing classes within the same file get distinct nodeIds.
+ // e.g. ClassA.update vs ClassB.update instead of both being "update".
+ const entityQKey = new Map();
+ for (const e of entities) {
+ entityQKey.set(e, e.container ? `${e.container}.${e.name}` : e.name);
+ }
+ // Reverse lookup: plain name → list of qualified keys (for edge resolution).
+ const nameToQKeys = new Map();
+ for (const [e, qk] of entityQKey) {
+ const list = nameToQKeys.get(e.name) ?? [];
+ list.push(qk);
+ nameToQKeys.set(e.name, list);
+ }
+ // Resolve a relationship endpoint to the best qualified key.
+ // For unambiguous names (appear once), returns the single qualified key.
+ // For ambiguous names (appear multiple times), falls back to the plain name
+ // so that the edge still points to *something* deterministic.
+ function resolveKey(name, container) {
+ const keys = nameToQKeys.get(name);
+ if (!keys || keys.length === 1)
+ return keys?.[0] ?? name;
+ // More than one entity with this name — try to pick by container
+ if (container) {
+ const qualified = `${container}.${name}`;
+ if (keys.includes(qualified))
+ return qualified;
+ }
+ // Ambiguous: return plain name so we don't silently drop the edge
+ return name;
+ }
+ // UpsertNode for each entity
+ for (const e of entities) {
+ const qk = entityQKey.get(e);
+ ops.push({
+ type: 'UpsertNode',
+ id: nodeId(filePath, qk),
+ kind: e.kind,
+ name: e.name,
+ attrs: {
+ line_start: e.lineStart,
+ line_end: e.lineEnd,
+ language: e.language,
+ },
+ });
+ }
+ // UpsertEdge for each relationship
+ for (const r of relationships) {
+ // For CONTAINS edges, srcName is the container of dstName — use that to disambiguate.
+ const srcKey = resolveKey(r.srcName);
+ const dstKey = r.predicate === 'CONTAINS'
+ ? resolveKey(r.dstName, r.srcName)
+ : resolveKey(r.dstName);
+ ops.push({
+ type: 'UpsertEdge',
+ id: edgeId(filePath, srcKey, dstKey, r.predicate),
+ src: nodeId(filePath, srcKey),
+ dst: nodeId(filePath, dstKey),
+ predicate: r.predicate,
+ attrs: {},
+ });
+ }
+ // AssertClaim for each relationship (feeds the confidence/conflict engine)
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ ops.push({
+ type: 'AssertClaim',
+ entityId: nodeId(filePath, srcKey),
+ field: `${r.predicate.toLowerCase()}:${r.dstName}`,
+ value: r.dstName,
+ confidence: null,
+ });
+ }
+ // patchId is deterministic: same file + same content → same id across runs.
+ // This makes repeated ingestion idempotent at the patch level.
+ const patchId = deterministicId(`${filePath}:${sourceHash}`);
+ const previousPatchId = previousSourceHash
+ ? deterministicId(`${filePath}:${previousSourceHash}`)
+ : undefined;
+ return {
+ patchId,
+ actor: 'ix/ingestion',
+ timestamp: new Date().toISOString(),
+ source: {
+ uri: filePath,
+ sourceHash,
+ extractor: extractorName(),
+ sourceType: sourceType(filePath),
+ },
+ baseRev: 0,
+ ops,
+ replaces: previousPatchId ? [previousPatchId] : [],
+ intent: `Parsed ${nodePath.basename(filePath)}`,
+ };
+}
+// ---------------------------------------------------------------------------
+// buildPatchWithResolution — like buildPatch but fixes CALLS edge dst to point
+// to the actual defining file for cross-file calls resolved by resolveCallEdges.
+// ---------------------------------------------------------------------------
+export function buildPatchWithResolution(result, sourceHash, resolvedEdges, previousSourceHash) {
+ // Build lookup: calleeName → { calleeFilePath, calleeQualifiedKey }
+ const callResolution = new Map();
+ for (const edge of resolvedEdges) {
+ if (edge.callerFilePath === result.filePath) {
+ callResolution.set(edge.calleeName, {
+ calleeFilePath: edge.calleeFilePath,
+ calleeQualifiedKey: edge.calleeQualifiedKey,
+ });
+ }
+ }
+ const { filePath, entities, relationships } = result;
+ const ops = [];
+ const entityQKey = new Map();
+ for (const e of entities) {
+ entityQKey.set(e, e.container ? `${e.container}.${e.name}` : e.name);
+ }
+ const nameToQKeys = new Map();
+ for (const [e, qk] of entityQKey) {
+ const list = nameToQKeys.get(e.name) ?? [];
+ list.push(qk);
+ nameToQKeys.set(e.name, list);
+ }
+ function resolveKey(name, container) {
+ const keys = nameToQKeys.get(name);
+ if (!keys || keys.length === 1)
+ return keys?.[0] ?? name;
+ if (container) {
+ const qualified = `${container}.${name}`;
+ if (keys.includes(qualified))
+ return qualified;
+ }
+ return name;
+ }
+ for (const e of entities) {
+ const qk = entityQKey.get(e);
+ ops.push({
+ type: 'UpsertNode',
+ id: nodeId(filePath, qk),
+ kind: e.kind,
+ name: e.name,
+ attrs: { line_start: e.lineStart, line_end: e.lineEnd, language: e.language },
+ });
+ }
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ const dstKey = r.predicate === 'CONTAINS'
+ ? resolveKey(r.dstName, r.srcName)
+ : resolveKey(r.dstName);
+ // For CALLS edges with a cross-file resolution, use the callee file's nodeId
+ let dstNodeId;
+ if (r.predicate === 'CALLS' && callResolution.has(r.dstName)) {
+ const { calleeFilePath, calleeQualifiedKey } = callResolution.get(r.dstName);
+ dstNodeId = nodeId(calleeFilePath, calleeQualifiedKey);
+ }
+ else {
+ dstNodeId = nodeId(filePath, dstKey);
+ }
+ ops.push({
+ type: 'UpsertEdge',
+ id: edgeId(filePath, srcKey, dstKey, r.predicate),
+ src: nodeId(filePath, srcKey),
+ dst: dstNodeId,
+ predicate: r.predicate,
+ attrs: {},
+ });
+ }
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ ops.push({
+ type: 'AssertClaim',
+ entityId: nodeId(filePath, srcKey),
+ field: `${r.predicate.toLowerCase()}:${r.dstName}`,
+ value: r.dstName,
+ confidence: null,
+ });
+ }
+ const patchId = deterministicId(`${filePath}:${sourceHash}`);
+ const previousPatchId = previousSourceHash
+ ? deterministicId(`${filePath}:${previousSourceHash}`)
+ : undefined;
+ return {
+ patchId,
+ actor: 'ix/ingestion',
+ timestamp: new Date().toISOString(),
+ source: {
+ uri: filePath,
+ sourceHash,
+ extractor: extractorName(),
+ sourceType: sourceType(filePath),
+ },
+ baseRev: 0,
+ ops,
+ replaces: previousPatchId ? [previousPatchId] : [],
+ intent: `Parsed ${nodePath.basename(filePath)}`,
+ };
+}
diff --git a/core-ingestion/dist/queries.d.ts b/core-ingestion/dist/queries.d.ts
new file mode 100644
index 00000000..f8aeb533
--- /dev/null
+++ b/core-ingestion/dist/queries.d.ts
@@ -0,0 +1,15 @@
+import { SupportedLanguages } from './languages.js';
+export declare const TYPESCRIPT_QUERIES = "\n(class_declaration\n name: (type_identifier) @name) @definition.class\n\n(interface_declaration\n name: (type_identifier) @name) @definition.interface\n\n(function_declaration\n name: (identifier) @name) @definition.function\n\n(method_definition\n name: (property_identifier) @name) @definition.method\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function)))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression)))) @definition.function\n\n(import_statement\n source: (string) @import.source) @import\n\n; Re-export statements: export { X } from './y'\n(export_statement\n source: (string) @import.source) @import\n\n; Dynamic import with string literal: import('./foo') or await import('./foo')\n(call_expression\n function: (import)\n arguments: (arguments (string) @import.source)) @import\n\n(call_expression\n function: (identifier) @call.name) @call\n\n(call_expression\n function: (member_expression\n property: (property_identifier) @call.name)) @call\n\n; Constructor calls: new Foo()\n(new_expression\n constructor: (identifier) @call.name) @call\n\n; Heritage queries - class extends\n(class_declaration\n name: (type_identifier) @heritage.class\n (class_heritage\n (extends_clause\n value: (identifier) @heritage.extends))) @heritage\n\n; Heritage queries - class implements interface\n(class_declaration\n name: (type_identifier) @heritage.class\n (class_heritage\n (implements_clause\n (type_identifier) @heritage.implements))) @heritage.impl\n";
+export declare const JAVASCRIPT_QUERIES = "\n(class_declaration\n name: (identifier) @name) @definition.class\n\n(function_declaration\n name: (identifier) @name) @definition.function\n\n(method_definition\n name: (property_identifier) @name) @definition.method\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function)))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression)))) @definition.function\n\n(import_statement\n source: (string) @import.source) @import\n\n; Re-export statements: export { X } from './y'\n(export_statement\n source: (string) @import.source) @import\n\n; Dynamic import with string literal: import('./foo') or await import('./foo')\n(call_expression\n function: (import)\n arguments: (arguments (string) @import.source)) @import\n\n(call_expression\n function: (identifier) @call.name) @call\n\n(call_expression\n function: (member_expression\n property: (property_identifier) @call.name)) @call\n\n; Constructor calls: new Foo()\n(new_expression\n constructor: (identifier) @call.name) @call\n\n; Heritage queries - class extends (JavaScript uses different AST than TypeScript)\n; In tree-sitter-javascript, class_heritage directly contains the parent identifier\n(class_declaration\n name: (identifier) @heritage.class\n (class_heritage\n (identifier) @heritage.extends)) @heritage\n";
+export declare const PYTHON_QUERIES = "\n(class_definition\n name: (identifier) @name) @definition.class\n\n(function_definition\n name: (identifier) @name) @definition.function\n\n(import_statement\n name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (relative_import) @import.source) @import\n\n; from . import utils / from .models import User \u2014 also capture the imported symbol names\n(import_from_statement\n module_name: (relative_import)\n name: (dotted_name (identifier) @import.name)) @import.names\n\n(call\n function: (identifier) @call.name) @call\n\n(call\n function: (attribute\n attribute: (identifier) @call.name)) @call\n\n; Heritage queries - Python class inheritance\n(class_definition\n name: (identifier) @heritage.class\n superclasses: (argument_list\n (identifier) @heritage.extends)) @heritage\n";
+export declare const JAVA_QUERIES = "\n; Classes, Interfaces, Enums, Annotations\n(class_declaration name: (identifier) @name) @definition.class\n(interface_declaration name: (identifier) @name) @definition.interface\n(enum_declaration name: (identifier) @name) @definition.enum\n(annotation_type_declaration name: (identifier) @name) @definition.annotation\n\n; Methods & Constructors\n(method_declaration name: (identifier) @name) @definition.method\n(constructor_declaration name: (identifier) @name) @definition.constructor\n\n; Imports - capture any import declaration child as source\n(import_declaration (_) @import.source) @import\n\n; Calls\n(method_invocation name: (identifier) @call.name) @call\n(method_invocation object: (_) name: (identifier) @call.name) @call\n\n; Constructor calls: new Foo()\n(object_creation_expression type: (type_identifier) @call.name) @call\n\n; Heritage - extends class\n(class_declaration name: (identifier) @heritage.class\n (superclass (type_identifier) @heritage.extends)) @heritage\n\n; Heritage - implements interfaces\n(class_declaration name: (identifier) @heritage.class\n (super_interfaces (type_list (type_identifier) @heritage.implements))) @heritage.impl\n";
+export declare const C_QUERIES = "\n; Functions (direct declarator)\n(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n\n; Functions returning pointers (pointer_declarator wraps function_declarator)\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n\n; Functions returning double pointers (nested pointer_declarator)\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function\n\n; Structs, Unions, Enums, Typedefs\n(struct_specifier name: (type_identifier) @name) @definition.struct\n(union_specifier name: (type_identifier) @name) @definition.union\n(enum_specifier name: (type_identifier) @name) @definition.enum\n(type_definition declarator: (type_identifier) @name) @definition.typedef\n\n; Macros\n(preproc_function_def name: (identifier) @name) @definition.macro\n(preproc_def name: (identifier) @name) @definition.macro\n\n; Includes\n(preproc_include path: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n";
+export declare const GO_QUERIES = "\n; Functions & Methods\n(function_declaration name: (identifier) @name) @definition.function\n(method_declaration name: (field_identifier) @name) @definition.method\n\n; Types\n(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition.struct\n(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition.interface\n\n; Imports\n(import_declaration (import_spec path: (interpreted_string_literal) @import.source)) @import\n(import_declaration (import_spec_list (import_spec path: (interpreted_string_literal) @import.source))) @import\n\n; Struct embedding (anonymous fields = inheritance)\n(type_declaration\n (type_spec\n name: (type_identifier) @heritage.class\n type: (struct_type\n (field_declaration_list\n (field_declaration\n type: (type_identifier) @heritage.extends))))) @definition.struct\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (selector_expression field: (field_identifier) @call.name)) @call\n\n; Struct literal construction: User{Name: \"Alice\"}\n(composite_literal type: (type_identifier) @call.name) @call\n";
+export declare const CPP_QUERIES = "\n; Classes, Structs, Namespaces\n(class_specifier name: (type_identifier) @name) @definition.class\n(struct_specifier name: (type_identifier) @name) @definition.struct\n(namespace_definition name: (namespace_identifier) @name) @definition.namespace\n(enum_specifier name: (type_identifier) @name) @definition.enum\n\n; Typedefs and unions (common in C-style headers and mixed C/C++ code)\n(type_definition declarator: (type_identifier) @name) @definition.typedef\n(union_specifier name: (type_identifier) @name) @definition.union\n\n; Macros\n(preproc_function_def name: (identifier) @name) @definition.macro\n(preproc_def name: (identifier) @name) @definition.macro\n\n; Functions & Methods (direct declarator)\n(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))) @definition.method\n\n; Functions/methods returning pointers (pointer_declarator wraps function_declarator)\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method\n\n; Functions/methods returning double pointers (nested pointer_declarator)\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))))) @definition.method\n\n; Functions/methods returning references (reference_declarator wraps function_declarator)\n(function_definition declarator: (reference_declarator (function_declarator declarator: (identifier) @name))) @definition.function\n(function_definition declarator: (reference_declarator (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method\n\n; Destructors (destructor_name is distinct from identifier in tree-sitter-cpp)\n(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (destructor_name) @name))) @definition.method\n\n; Function declarations / prototypes (common in headers)\n(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n\n; Inline class method declarations (inside class body, no body: void Foo();)\n(field_declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.method\n\n; Inline class method definitions (inside class body, with body: void Foo() { ... })\n(field_declaration_list\n (function_definition\n declarator: (function_declarator\n declarator: [(field_identifier) (identifier) (operator_name) (destructor_name)] @name)) @definition.method)\n\n; Templates\n(template_declaration (class_specifier name: (type_identifier) @name)) @definition.template\n(template_declaration (function_definition declarator: (function_declarator declarator: (identifier) @name))) @definition.template\n\n; Includes\n(preproc_include path: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n(call_expression function: (qualified_identifier name: (identifier) @call.name)) @call\n(call_expression function: (template_function name: (identifier) @call.name)) @call\n\n; Constructor calls: new User()\n(new_expression type: (type_identifier) @call.name) @call\n\n; Heritage\n(class_specifier name: (type_identifier) @heritage.class\n (base_class_clause (type_identifier) @heritage.extends)) @heritage\n(class_specifier name: (type_identifier) @heritage.class\n (base_class_clause (access_specifier) (type_identifier) @heritage.extends)) @heritage\n";
+export declare const CSHARP_QUERIES = "\n; Types\n(class_declaration name: (identifier) @name) @definition.class\n(interface_declaration name: (identifier) @name) @definition.interface\n(struct_declaration name: (identifier) @name) @definition.struct\n(enum_declaration name: (identifier) @name) @definition.enum\n(record_declaration name: (identifier) @name) @definition.record\n(delegate_declaration name: (identifier) @name) @definition.delegate\n\n; Namespaces (block form and C# 10+ file-scoped form)\n(namespace_declaration name: (identifier) @name) @definition.namespace\n(namespace_declaration name: (qualified_name) @name) @definition.namespace\n(file_scoped_namespace_declaration name: (identifier) @name) @definition.namespace\n(file_scoped_namespace_declaration name: (qualified_name) @name) @definition.namespace\n\n; Methods & Properties\n(method_declaration name: (identifier) @name) @definition.method\n(local_function_statement name: (identifier) @name) @definition.function\n(constructor_declaration name: (identifier) @name) @definition.constructor\n(property_declaration name: (identifier) @name) @definition.property\n\n; Primary constructors (C# 12): class User(string name, int age) { }\n(class_declaration name: (identifier) @name (parameter_list) @definition.constructor)\n(record_declaration name: (identifier) @name (parameter_list) @definition.constructor)\n\n; Using\n(using_directive (qualified_name) @import.source) @import\n(using_directive (identifier) @import.source) @import\n\n; Calls\n(invocation_expression function: (identifier) @call.name) @call\n(invocation_expression function: (member_access_expression name: (identifier) @call.name)) @call\n\n; Null-conditional method calls: user?.Save()\n; Parses as: invocation_expression \u2192 conditional_access_expression \u2192 member_binding_expression \u2192 identifier\n(invocation_expression\n function: (conditional_access_expression\n (member_binding_expression\n (identifier) @call.name))) @call\n\n; Constructor calls: new Foo() and new Foo { Props }\n(object_creation_expression type: (identifier) @call.name) @call\n\n; Target-typed new (C# 9): User u = new(\"x\", 5)\n(variable_declaration type: (identifier) @call.name (variable_declarator (implicit_object_creation_expression) @call))\n\n; Heritage\n(class_declaration name: (identifier) @heritage.class\n (base_list (identifier) @heritage.extends)) @heritage\n(class_declaration name: (identifier) @heritage.class\n (base_list (generic_name (identifier) @heritage.extends))) @heritage\n";
+export declare const RUST_QUERIES = "\n; Functions & Items\n(function_item name: (identifier) @name) @definition.function\n(struct_item name: (type_identifier) @name) @definition.struct\n(enum_item name: (type_identifier) @name) @definition.enum\n(trait_item name: (type_identifier) @name) @definition.trait\n(impl_item type: (type_identifier) @name !trait) @definition.impl\n(impl_item type: (generic_type type: (type_identifier) @name) !trait) @definition.impl\n(mod_item name: (identifier) @name) @definition.module\n\n; Type aliases, const, static, macros\n(type_item name: (type_identifier) @name) @definition.type\n(const_item name: (identifier) @name) @definition.const\n(static_item name: (identifier) @name) @definition.static\n(macro_definition name: (identifier) @name) @definition.macro\n\n; Use statements\n(use_declaration argument: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n(call_expression function: (scoped_identifier name: (identifier) @call.name)) @call\n(call_expression function: (generic_function function: (identifier) @call.name)) @call\n\n; Struct literal construction: User { name: value }\n(struct_expression name: (type_identifier) @call.name) @call\n\n; Heritage (trait implementation) \u2014 all combinations of concrete/generic trait \u00D7 concrete/generic type\n(impl_item trait: (type_identifier) @heritage.trait type: (type_identifier) @heritage.class) @heritage\n(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (type_identifier) @heritage.class) @heritage\n(impl_item trait: (type_identifier) @heritage.trait type: (generic_type type: (type_identifier) @heritage.class)) @heritage\n(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (generic_type type: (type_identifier) @heritage.class)) @heritage\n";
+export declare const PHP_QUERIES = "\n; \u2500\u2500 Namespace \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(namespace_definition\n name: (namespace_name) @name) @definition.namespace\n\n; \u2500\u2500 Classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class_declaration\n name: (name) @name) @definition.class\n\n; \u2500\u2500 Interfaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(interface_declaration\n name: (name) @name) @definition.interface\n\n; \u2500\u2500 Traits \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(trait_declaration\n name: (name) @name) @definition.trait\n\n; \u2500\u2500 Enums (PHP 8.1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(enum_declaration\n name: (name) @name) @definition.enum\n\n; \u2500\u2500 Top-level functions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(function_definition\n name: (name) @name) @definition.function\n\n; \u2500\u2500 Methods (including constructors) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(method_declaration\n name: (name) @name) @definition.method\n\n; \u2500\u2500 Class properties (including Eloquent $fillable, $casts, etc.) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(property_declaration\n (property_element\n (variable_name\n (name) @name))) @definition.property\n\n; \u2500\u2500 Imports: use statements \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; Simple: use App\\Models\\User;\n(namespace_use_declaration\n (namespace_use_clause\n (qualified_name) @import.source)) @import\n\n; \u2500\u2500 Function/method calls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; Regular function call: foo()\n(function_call_expression\n function: (name) @call.name) @call\n\n; Method call: $obj->method()\n(member_call_expression\n name: (name) @call.name) @call\n\n; Nullsafe method call: $obj?->method()\n(nullsafe_member_call_expression\n name: (name) @call.name) @call\n\n; Static call: Foo::bar() (php_only uses scoped_call_expression)\n(scoped_call_expression\n name: (name) @call.name) @call\n\n; Constructor call: new User()\n(object_creation_expression (name) @call.name) @call\n\n; \u2500\u2500 Heritage: extends \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class_declaration\n name: (name) @heritage.class\n (base_clause\n [(name) (qualified_name)] @heritage.extends)) @heritage\n\n; \u2500\u2500 Heritage: implements \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class_declaration\n name: (name) @heritage.class\n (class_interface_clause\n [(name) (qualified_name)] @heritage.implements)) @heritage.impl\n\n; \u2500\u2500 Heritage: use trait (must capture enclosing class name) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class_declaration\n name: (name) @heritage.class\n body: (declaration_list\n (use_declaration\n [(name) (qualified_name)] @heritage.trait))) @heritage\n";
+export declare const RUBY_QUERIES = "\n; \u2500\u2500 Modules \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(module\n name: (constant) @name) @definition.module\n\n; \u2500\u2500 Classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class\n name: (constant) @name) @definition.class\n\n; \u2500\u2500 Instance methods \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(method\n name: (identifier) @name) @definition.method\n\n; \u2500\u2500 Singleton (class-level) methods \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(singleton_method\n name: (identifier) @name) @definition.method\n\n; \u2500\u2500 Require / require_relative \u2192 IMPORTS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; Capture the string argument so the second pass emits an IMPORTS edge.\n(call\n method: (identifier) @_req\n arguments: (argument_list\n (string (string_content) @import.source))\n (#match? @_req \"^require\")) @import\n\n; \u2500\u2500 All other calls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(call\n method: (identifier) @call.name) @call\n\n; \u2500\u2500 Bare calls without parens (identifiers at statement level are method calls) \u2500\n; NOTE: This may over-capture variable reads as calls (e.g. 'result' at\n; statement level). Ruby's grammar makes bare identifiers ambiguous \u2014 they\n; could be local variables or zero-arity method calls. Post-processing via\n; the BUILTINS set suppresses most false positives.\n(body_statement\n (identifier) @call.name @call)\n\n; \u2500\u2500 Heritage: class < SuperClass \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(class\n name: (constant) @heritage.class\n superclass: (superclass\n (constant) @heritage.extends)) @heritage\n";
+export declare const KOTLIN_QUERIES = "\n; \u2500\u2500 Interfaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; tree-sitter-kotlin (fwcd) has no interface_declaration node type.\n; Interfaces are class_declaration nodes with an anonymous \"interface\" keyword child.\n(class_declaration\n \"interface\"\n (type_identifier) @name) @definition.interface\n\n; \u2500\u2500 Classes (regular, data, sealed, enum) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; All have the anonymous \"class\" keyword child. enum class has both\n; \"enum\" and \"class\" children \u2014 the \"class\" child still matches.\n(class_declaration\n \"class\"\n (type_identifier) @name) @definition.class\n\n; \u2500\u2500 Object declarations (Kotlin singletons) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(object_declaration\n (type_identifier) @name) @definition.class\n\n; \u2500\u2500 Companion objects (named only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(companion_object\n (type_identifier) @name) @definition.class\n\n; \u2500\u2500 Functions (top-level, member, extension) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(function_declaration\n (simple_identifier) @name) @definition.function\n\n; \u2500\u2500 Properties \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(property_declaration\n (variable_declaration\n (simple_identifier) @name)) @definition.property\n\n; \u2500\u2500 Enum entries \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(enum_entry\n (simple_identifier) @name) @definition.enum\n\n; \u2500\u2500 Type aliases \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(type_alias\n (type_identifier) @name) @definition.type\n\n; \u2500\u2500 Imports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(import_header\n (identifier) @import.source) @import\n\n; \u2500\u2500 Function calls (direct) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(call_expression\n (simple_identifier) @call.name) @call\n\n; \u2500\u2500 Method calls (via navigation: obj.method()) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(call_expression\n (navigation_expression\n (navigation_suffix\n (simple_identifier) @call.name))) @call\n\n; \u2500\u2500 Constructor invocations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(constructor_invocation\n (user_type\n (type_identifier) @call.name)) @call\n\n; \u2500\u2500 Infix function calls (e.g., a to b, x until y) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n(infix_expression\n (simple_identifier) @call.name) @call\n\n; \u2500\u2500 Heritage: extends / implements via delegation_specifier \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n; Interface implementation (bare user_type): class Foo : Bar\n(class_declaration\n (type_identifier) @heritage.class\n (delegation_specifier\n (user_type (type_identifier) @heritage.extends))) @heritage\n\n; Class extension (constructor_invocation): class Foo : Bar()\n(class_declaration\n (type_identifier) @heritage.class\n (delegation_specifier\n (constructor_invocation\n (user_type (type_identifier) @heritage.extends)))) @heritage\n";
+export declare const SWIFT_QUERIES = "\n; Classes\n(class_declaration \"class\" name: (type_identifier) @name) @definition.class\n\n; Structs\n(class_declaration \"struct\" name: (type_identifier) @name) @definition.struct\n\n; Enums\n(class_declaration \"enum\" name: (type_identifier) @name) @definition.enum\n\n; Extensions (mapped to class \u2014 no dedicated label in schema)\n(class_declaration \"extension\" name: (user_type (type_identifier) @name)) @definition.class\n\n; Actors\n(class_declaration \"actor\" name: (type_identifier) @name) @definition.class\n\n; Protocols (mapped to interface)\n(protocol_declaration name: (type_identifier) @name) @definition.interface\n\n; Type aliases\n(typealias_declaration name: (type_identifier) @name) @definition.type\n\n; Functions (top-level and methods)\n(function_declaration name: (simple_identifier) @name) @definition.function\n\n; Protocol method declarations\n(protocol_function_declaration name: (simple_identifier) @name) @definition.method\n\n; Initializers \u2014 \"init\" is the canonical name; line offset tracked via definition node\n(init_declaration \"init\" @name) @definition.constructor\n\n; Properties (stored and computed)\n(property_declaration (pattern (simple_identifier) @name)) @definition.property\n\n; Imports\n(import_declaration (identifier (simple_identifier) @import.source)) @import\n\n; Calls - direct function calls\n(call_expression (simple_identifier) @call.name) @call\n\n; Calls - member/navigation calls (obj.method())\n(call_expression (navigation_expression (navigation_suffix (simple_identifier) @call.name))) @call\n\n; Heritage - class/struct/enum inheritance and protocol conformance\n(class_declaration name: (type_identifier) @heritage.class\n (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage\n\n; Heritage - protocol inheritance\n(protocol_declaration name: (type_identifier) @heritage.class\n (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage\n\n; Heritage - extension protocol conformance (e.g. extension Foo: SomeProtocol)\n; Extensions wrap the name in user_type unlike class/struct/enum declarations\n(class_declaration \"extension\" name: (user_type (type_identifier) @heritage.class)\n (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage\n";
+export declare const LANGUAGE_QUERIES: Record<SupportedLanguages, string>;
diff --git a/core-ingestion/dist/queries.js b/core-ingestion/dist/queries.js
new file mode 100644
index 00000000..679b0cb7
--- /dev/null
+++ b/core-ingestion/dist/queries.js
@@ -0,0 +1,703 @@
+import { SupportedLanguages } from './languages.js';
+/*
+ * Tree-sitter queries for extracting code definitions.
+ *
+ * Note: Different grammars (typescript vs tsx vs javascript) may have
+ * slightly different node types. These queries are designed to be
+ * compatible with the standard tree-sitter grammars.
+ */
+// TypeScript queries - works with tree-sitter-typescript
+export const TYPESCRIPT_QUERIES = `
+(class_declaration
+ name: (type_identifier) @name) @definition.class
+
+(interface_declaration
+ name: (type_identifier) @name) @definition.interface
+
+(function_declaration
+ name: (identifier) @name) @definition.function
+
+(method_definition
+ name: (property_identifier) @name) @definition.method
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function)))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression)))) @definition.function
+
+(import_statement
+ source: (string) @import.source) @import
+
+; Re-export statements: export { X } from './y'
+(export_statement
+ source: (string) @import.source) @import
+
+; Dynamic import with string literal: import('./foo') or await import('./foo')
+(call_expression
+ function: (import)
+ arguments: (arguments (string) @import.source)) @import
+
+(call_expression
+ function: (identifier) @call.name) @call
+
+(call_expression
+ function: (member_expression
+ property: (property_identifier) @call.name)) @call
+
+; Constructor calls: new Foo()
+(new_expression
+ constructor: (identifier) @call.name) @call
+
+; Heritage queries - class extends
+(class_declaration
+ name: (type_identifier) @heritage.class
+ (class_heritage
+ (extends_clause
+ value: (identifier) @heritage.extends))) @heritage
+
+; Heritage queries - class implements interface
+(class_declaration
+ name: (type_identifier) @heritage.class
+ (class_heritage
+ (implements_clause
+ (type_identifier) @heritage.implements))) @heritage.impl
+`;
+// JavaScript queries - works with tree-sitter-javascript
+export const JAVASCRIPT_QUERIES = `
+(class_declaration
+ name: (identifier) @name) @definition.class
+
+(function_declaration
+ name: (identifier) @name) @definition.function
+
+(method_definition
+ name: (property_identifier) @name) @definition.method
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function)))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression)))) @definition.function
+
+(import_statement
+ source: (string) @import.source) @import
+
+; Re-export statements: export { X } from './y'
+(export_statement
+ source: (string) @import.source) @import
+
+; Dynamic import with string literal: import('./foo') or await import('./foo')
+(call_expression
+ function: (import)
+ arguments: (arguments (string) @import.source)) @import
+
+(call_expression
+ function: (identifier) @call.name) @call
+
+(call_expression
+ function: (member_expression
+ property: (property_identifier) @call.name)) @call
+
+; Constructor calls: new Foo()
+(new_expression
+ constructor: (identifier) @call.name) @call
+
+; Heritage queries - class extends (JavaScript uses different AST than TypeScript)
+; In tree-sitter-javascript, class_heritage directly contains the parent identifier
+(class_declaration
+ name: (identifier) @heritage.class
+ (class_heritage
+ (identifier) @heritage.extends)) @heritage
+`;
+// Python queries - works with tree-sitter-python
+export const PYTHON_QUERIES = `
+(class_definition
+ name: (identifier) @name) @definition.class
+
+(function_definition
+ name: (identifier) @name) @definition.function
+
+(import_statement
+ name: (dotted_name) @import.source) @import
+
+(import_from_statement
+ module_name: (dotted_name) @import.source) @import
+
+(import_from_statement
+ module_name: (relative_import) @import.source) @import
+
+; from . import utils / from .models import User — also capture the imported symbol names
+(import_from_statement
+ module_name: (relative_import)
+ name: (dotted_name (identifier) @import.name)) @import.names
+
+(call
+ function: (identifier) @call.name) @call
+
+(call
+ function: (attribute
+ attribute: (identifier) @call.name)) @call
+
+; Heritage queries - Python class inheritance
+(class_definition
+ name: (identifier) @heritage.class
+ superclasses: (argument_list
+ (identifier) @heritage.extends)) @heritage
+`;
+// Java queries - works with tree-sitter-java
+export const JAVA_QUERIES = `
+; Classes, Interfaces, Enums, Annotations
+(class_declaration name: (identifier) @name) @definition.class
+(interface_declaration name: (identifier) @name) @definition.interface
+(enum_declaration name: (identifier) @name) @definition.enum
+(annotation_type_declaration name: (identifier) @name) @definition.annotation
+
+; Methods & Constructors
+(method_declaration name: (identifier) @name) @definition.method
+(constructor_declaration name: (identifier) @name) @definition.constructor
+
+; Imports - capture any import declaration child as source
+(import_declaration (_) @import.source) @import
+
+; Calls
+(method_invocation name: (identifier) @call.name) @call
+(method_invocation object: (_) name: (identifier) @call.name) @call
+
+; Constructor calls: new Foo()
+(object_creation_expression type: (type_identifier) @call.name) @call
+
+; Heritage - extends class
+(class_declaration name: (identifier) @heritage.class
+ (superclass (type_identifier) @heritage.extends)) @heritage
+
+; Heritage - implements interfaces
+(class_declaration name: (identifier) @heritage.class
+ (super_interfaces (type_list (type_identifier) @heritage.implements))) @heritage.impl
+`;
+// C queries - works with tree-sitter-c
+export const C_QUERIES = `
+; Functions (direct declarator)
+(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+
+; Functions returning pointers (pointer_declarator wraps function_declarator)
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+
+; Functions returning double pointers (nested pointer_declarator)
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function
+
+; Structs, Unions, Enums, Typedefs
+(struct_specifier name: (type_identifier) @name) @definition.struct
+(union_specifier name: (type_identifier) @name) @definition.union
+(enum_specifier name: (type_identifier) @name) @definition.enum
+(type_definition declarator: (type_identifier) @name) @definition.typedef
+
+; Macros
+(preproc_function_def name: (identifier) @name) @definition.macro
+(preproc_def name: (identifier) @name) @definition.macro
+
+; Includes
+(preproc_include path: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+`;
+// Go queries - works with tree-sitter-go
+export const GO_QUERIES = `
+; Functions & Methods
+(function_declaration name: (identifier) @name) @definition.function
+(method_declaration name: (field_identifier) @name) @definition.method
+
+; Types
+(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition.struct
+(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition.interface
+
+; Imports
+(import_declaration (import_spec path: (interpreted_string_literal) @import.source)) @import
+(import_declaration (import_spec_list (import_spec path: (interpreted_string_literal) @import.source))) @import
+
+; Struct embedding (anonymous fields = inheritance)
+(type_declaration
+ (type_spec
+ name: (type_identifier) @heritage.class
+ type: (struct_type
+ (field_declaration_list
+ (field_declaration
+ type: (type_identifier) @heritage.extends))))) @definition.struct
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (selector_expression field: (field_identifier) @call.name)) @call
+
+; Struct literal construction: User{Name: "Alice"}
+(composite_literal type: (type_identifier) @call.name) @call
+`;
+// C++ queries - works with tree-sitter-cpp
+export const CPP_QUERIES = `
+; Classes, Structs, Namespaces
+(class_specifier name: (type_identifier) @name) @definition.class
+(struct_specifier name: (type_identifier) @name) @definition.struct
+(namespace_definition name: (namespace_identifier) @name) @definition.namespace
+(enum_specifier name: (type_identifier) @name) @definition.enum
+
+; Typedefs and unions (common in C-style headers and mixed C/C++ code)
+(type_definition declarator: (type_identifier) @name) @definition.typedef
+(union_specifier name: (type_identifier) @name) @definition.union
+
+; Macros
+(preproc_function_def name: (identifier) @name) @definition.macro
+(preproc_def name: (identifier) @name) @definition.macro
+
+; Functions & Methods (direct declarator)
+(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))) @definition.method
+
+; Functions/methods returning pointers (pointer_declarator wraps function_declarator)
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method
+
+; Functions/methods returning double pointers (nested pointer_declarator)
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))))) @definition.method
+
+; Functions/methods returning references (reference_declarator wraps function_declarator)
+(function_definition declarator: (reference_declarator (function_declarator declarator: (identifier) @name))) @definition.function
+(function_definition declarator: (reference_declarator (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method
+
+; Destructors (destructor_name is distinct from identifier in tree-sitter-cpp)
+(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (destructor_name) @name))) @definition.method
+
+; Function declarations / prototypes (common in headers)
+(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+
+; Inline class method declarations (inside class body, no body: void Foo();)
+(field_declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.method
+
+; Inline class method definitions (inside class body, with body: void Foo() { ... })
+(field_declaration_list
+ (function_definition
+ declarator: (function_declarator
+ declarator: [(field_identifier) (identifier) (operator_name) (destructor_name)] @name)) @definition.method)
+
+; Templates
+(template_declaration (class_specifier name: (type_identifier) @name)) @definition.template
+(template_declaration (function_definition declarator: (function_declarator declarator: (identifier) @name))) @definition.template
+
+; Includes
+(preproc_include path: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+(call_expression function: (qualified_identifier name: (identifier) @call.name)) @call
+(call_expression function: (template_function name: (identifier) @call.name)) @call
+
+; Constructor calls: new User()
+(new_expression type: (type_identifier) @call.name) @call
+
+; Heritage
+(class_specifier name: (type_identifier) @heritage.class
+ (base_class_clause (type_identifier) @heritage.extends)) @heritage
+(class_specifier name: (type_identifier) @heritage.class
+ (base_class_clause (access_specifier) (type_identifier) @heritage.extends)) @heritage
+`;
+// C# queries - works with tree-sitter-c-sharp
+export const CSHARP_QUERIES = `
+; Types
+(class_declaration name: (identifier) @name) @definition.class
+(interface_declaration name: (identifier) @name) @definition.interface
+(struct_declaration name: (identifier) @name) @definition.struct
+(enum_declaration name: (identifier) @name) @definition.enum
+(record_declaration name: (identifier) @name) @definition.record
+(delegate_declaration name: (identifier) @name) @definition.delegate
+
+; Namespaces (block form and C# 10+ file-scoped form)
+(namespace_declaration name: (identifier) @name) @definition.namespace
+(namespace_declaration name: (qualified_name) @name) @definition.namespace
+(file_scoped_namespace_declaration name: (identifier) @name) @definition.namespace
+(file_scoped_namespace_declaration name: (qualified_name) @name) @definition.namespace
+
+; Methods & Properties
+(method_declaration name: (identifier) @name) @definition.method
+(local_function_statement name: (identifier) @name) @definition.function
+(constructor_declaration name: (identifier) @name) @definition.constructor
+(property_declaration name: (identifier) @name) @definition.property
+
+; Primary constructors (C# 12): class User(string name, int age) { }
+(class_declaration name: (identifier) @name (parameter_list) @definition.constructor)
+(record_declaration name: (identifier) @name (parameter_list) @definition.constructor)
+
+; Using
+(using_directive (qualified_name) @import.source) @import
+(using_directive (identifier) @import.source) @import
+
+; Calls
+(invocation_expression function: (identifier) @call.name) @call
+(invocation_expression function: (member_access_expression name: (identifier) @call.name)) @call
+
+; Null-conditional method calls: user?.Save()
+; Parses as: invocation_expression → conditional_access_expression → member_binding_expression → identifier
+(invocation_expression
+ function: (conditional_access_expression
+ (member_binding_expression
+ (identifier) @call.name))) @call
+
+; Constructor calls: new Foo() and new Foo { Props }
+(object_creation_expression type: (identifier) @call.name) @call
+
+; Target-typed new (C# 9): User u = new("x", 5)
+(variable_declaration type: (identifier) @call.name (variable_declarator (implicit_object_creation_expression) @call))
+
+; Heritage
+(class_declaration name: (identifier) @heritage.class
+ (base_list (identifier) @heritage.extends)) @heritage
+(class_declaration name: (identifier) @heritage.class
+ (base_list (generic_name (identifier) @heritage.extends))) @heritage
+`;
+// Rust queries - works with tree-sitter-rust
+export const RUST_QUERIES = `
+; Functions & Items
+(function_item name: (identifier) @name) @definition.function
+(struct_item name: (type_identifier) @name) @definition.struct
+(enum_item name: (type_identifier) @name) @definition.enum
+(trait_item name: (type_identifier) @name) @definition.trait
+(impl_item type: (type_identifier) @name !trait) @definition.impl
+(impl_item type: (generic_type type: (type_identifier) @name) !trait) @definition.impl
+(mod_item name: (identifier) @name) @definition.module
+
+; Type aliases, const, static, macros
+(type_item name: (type_identifier) @name) @definition.type
+(const_item name: (identifier) @name) @definition.const
+(static_item name: (identifier) @name) @definition.static
+(macro_definition name: (identifier) @name) @definition.macro
+
+; Use statements
+(use_declaration argument: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+(call_expression function: (scoped_identifier name: (identifier) @call.name)) @call
+(call_expression function: (generic_function function: (identifier) @call.name)) @call
+
+; Struct literal construction: User { name: value }
+(struct_expression name: (type_identifier) @call.name) @call
+
+; Heritage (trait implementation) — all combinations of concrete/generic trait × concrete/generic type
+(impl_item trait: (type_identifier) @heritage.trait type: (type_identifier) @heritage.class) @heritage
+(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (type_identifier) @heritage.class) @heritage
+(impl_item trait: (type_identifier) @heritage.trait type: (generic_type type: (type_identifier) @heritage.class)) @heritage
+(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (generic_type type: (type_identifier) @heritage.class)) @heritage
+`;
+// PHP queries - works with tree-sitter-php (php_only grammar)
+export const PHP_QUERIES = `
+; ── Namespace ────────────────────────────────────────────────────────────────
+(namespace_definition
+ name: (namespace_name) @name) @definition.namespace
+
+; ── Classes ──────────────────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @name) @definition.class
+
+; ── Interfaces ───────────────────────────────────────────────────────────────
+(interface_declaration
+ name: (name) @name) @definition.interface
+
+; ── Traits ───────────────────────────────────────────────────────────────────
+(trait_declaration
+ name: (name) @name) @definition.trait
+
+; ── Enums (PHP 8.1) ──────────────────────────────────────────────────────────
+(enum_declaration
+ name: (name) @name) @definition.enum
+
+; ── Top-level functions ───────────────────────────────────────────────────────
+(function_definition
+ name: (name) @name) @definition.function
+
+; ── Methods (including constructors) ─────────────────────────────────────────
+(method_declaration
+ name: (name) @name) @definition.method
+
+; ── Class properties (including Eloquent $fillable, $casts, etc.) ────────────
+(property_declaration
+ (property_element
+ (variable_name
+ (name) @name))) @definition.property
+
+; ── Imports: use statements ──────────────────────────────────────────────────
+; Simple: use App\\Models\\User;
+(namespace_use_declaration
+ (namespace_use_clause
+ (qualified_name) @import.source)) @import
+
+; ── Function/method calls ────────────────────────────────────────────────────
+; Regular function call: foo()
+(function_call_expression
+ function: (name) @call.name) @call
+
+; Method call: $obj->method()
+(member_call_expression
+ name: (name) @call.name) @call
+
+; Nullsafe method call: $obj?->method()
+(nullsafe_member_call_expression
+ name: (name) @call.name) @call
+
+; Static call: Foo::bar() (php_only uses scoped_call_expression)
+(scoped_call_expression
+ name: (name) @call.name) @call
+
+; Constructor call: new User()
+(object_creation_expression (name) @call.name) @call
+
+; ── Heritage: extends ────────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @heritage.class
+ (base_clause
+ [(name) (qualified_name)] @heritage.extends)) @heritage
+
+; ── Heritage: implements ─────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @heritage.class
+ (class_interface_clause
+ [(name) (qualified_name)] @heritage.implements)) @heritage.impl
+
+; ── Heritage: use trait (must capture enclosing class name) ──────────────────
+(class_declaration
+ name: (name) @heritage.class
+ body: (declaration_list
+ (use_declaration
+ [(name) (qualified_name)] @heritage.trait))) @heritage
+`;
+// Ruby queries - works with tree-sitter-ruby
+export const RUBY_QUERIES = `
+; ── Modules ──────────────────────────────────────────────────────────────────
+(module
+ name: (constant) @name) @definition.module
+
+; ── Classes ──────────────────────────────────────────────────────────────────
+(class
+ name: (constant) @name) @definition.class
+
+; ── Instance methods ─────────────────────────────────────────────────────────
+(method
+ name: (identifier) @name) @definition.method
+
+; ── Singleton (class-level) methods ──────────────────────────────────────────
+(singleton_method
+ name: (identifier) @name) @definition.method
+
+; ── Require / require_relative → IMPORTS ─────────────────────────────────────
+; Capture the string argument so the second pass emits an IMPORTS edge.
+(call
+ method: (identifier) @_req
+ arguments: (argument_list
+ (string (string_content) @import.source))
+ (#match? @_req "^require")) @import
+
+; ── All other calls ───────────────────────────────────────────────────────────
+(call
+ method: (identifier) @call.name) @call
+
+; ── Bare calls without parens (identifiers at statement level are method calls) ─
+; NOTE: This may over-capture variable reads as calls (e.g. 'result' at
+; statement level). Ruby's grammar makes bare identifiers ambiguous — they
+; could be local variables or zero-arity method calls. Post-processing via
+; the BUILTINS set suppresses most false positives.
+(body_statement
+ (identifier) @call.name @call)
+
+; ── Heritage: class < SuperClass ─────────────────────────────────────────────
+(class
+ name: (constant) @heritage.class
+ superclass: (superclass
+ (constant) @heritage.extends)) @heritage
+`;
+// Kotlin queries - works with tree-sitter-kotlin (fwcd/tree-sitter-kotlin)
+// Based on official tags.scm; functions use simple_identifier, classes use type_identifier
+export const KOTLIN_QUERIES = `
+; ── Interfaces ─────────────────────────────────────────────────────────────
+; tree-sitter-kotlin (fwcd) has no interface_declaration node type.
+; Interfaces are class_declaration nodes with an anonymous "interface" keyword child.
+(class_declaration
+ "interface"
+ (type_identifier) @name) @definition.interface
+
+; ── Classes (regular, data, sealed, enum) ────────────────────────────────
+; All have the anonymous "class" keyword child. enum class has both
+; "enum" and "class" children — the "class" child still matches.
+(class_declaration
+ "class"
+ (type_identifier) @name) @definition.class
+
+; ── Object declarations (Kotlin singletons) ──────────────────────────────
+(object_declaration
+ (type_identifier) @name) @definition.class
+
+; ── Companion objects (named only) ───────────────────────────────────────
+(companion_object
+ (type_identifier) @name) @definition.class
+
+; ── Functions (top-level, member, extension) ──────────────────────────────
+(function_declaration
+ (simple_identifier) @name) @definition.function
+
+; ── Properties ───────────────────────────────────────────────────────────
+(property_declaration
+ (variable_declaration
+ (simple_identifier) @name)) @definition.property
+
+; ── Enum entries ─────────────────────────────────────────────────────────
+(enum_entry
+ (simple_identifier) @name) @definition.enum
+
+; ── Type aliases ─────────────────────────────────────────────────────────
+(type_alias
+ (type_identifier) @name) @definition.type
+
+; ── Imports ──────────────────────────────────────────────────────────────
+(import_header
+ (identifier) @import.source) @import
+
+; ── Function calls (direct) ──────────────────────────────────────────────
+(call_expression
+ (simple_identifier) @call.name) @call
+
+; ── Method calls (via navigation: obj.method()) ──────────────────────────
+(call_expression
+ (navigation_expression
+ (navigation_suffix
+ (simple_identifier) @call.name))) @call
+
+; ── Constructor invocations ──────────────────────────────────────────────
+(constructor_invocation
+ (user_type
+ (type_identifier) @call.name)) @call
+
+; ── Infix function calls (e.g., a to b, x until y) ──────────────────────
+(infix_expression
+ (simple_identifier) @call.name) @call
+
+; ── Heritage: extends / implements via delegation_specifier ──────────────
+; Interface implementation (bare user_type): class Foo : Bar
+(class_declaration
+ (type_identifier) @heritage.class
+ (delegation_specifier
+ (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Class extension (constructor_invocation): class Foo : Bar()
+(class_declaration
+ (type_identifier) @heritage.class
+ (delegation_specifier
+ (constructor_invocation
+ (user_type (type_identifier) @heritage.extends)))) @heritage
+`;
+// Swift queries - works with tree-sitter-swift
+export const SWIFT_QUERIES = `
+; Classes
+(class_declaration "class" name: (type_identifier) @name) @definition.class
+
+; Structs
+(class_declaration "struct" name: (type_identifier) @name) @definition.struct
+
+; Enums
+(class_declaration "enum" name: (type_identifier) @name) @definition.enum
+
+; Extensions (mapped to class — no dedicated label in schema)
+(class_declaration "extension" name: (user_type (type_identifier) @name)) @definition.class
+
+; Actors
+(class_declaration "actor" name: (type_identifier) @name) @definition.class
+
+; Protocols (mapped to interface)
+(protocol_declaration name: (type_identifier) @name) @definition.interface
+
+; Type aliases
+(typealias_declaration name: (type_identifier) @name) @definition.type
+
+; Functions (top-level and methods)
+(function_declaration name: (simple_identifier) @name) @definition.function
+
+; Protocol method declarations
+(protocol_function_declaration name: (simple_identifier) @name) @definition.method
+
+; Initializers — "init" is the canonical name; line offset tracked via definition node
+(init_declaration "init" @name) @definition.constructor
+
+; Properties (stored and computed)
+(property_declaration (pattern (simple_identifier) @name)) @definition.property
+
+; Imports
+(import_declaration (identifier (simple_identifier) @import.source)) @import
+
+; Calls - direct function calls
+(call_expression (simple_identifier) @call.name) @call
+
+; Calls - member/navigation calls (obj.method())
+(call_expression (navigation_expression (navigation_suffix (simple_identifier) @call.name))) @call
+
+; Heritage - class/struct/enum inheritance and protocol conformance
+(class_declaration name: (type_identifier) @heritage.class
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Heritage - protocol inheritance
+(protocol_declaration name: (type_identifier) @heritage.class
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Heritage - extension protocol conformance (e.g. extension Foo: SomeProtocol)
+; Extensions wrap the name in user_type unlike class/struct/enum declarations
+(class_declaration "extension" name: (user_type (type_identifier) @heritage.class)
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+`;
+export const LANGUAGE_QUERIES = {
+ [SupportedLanguages.TypeScript]: TYPESCRIPT_QUERIES,
+ [SupportedLanguages.JavaScript]: JAVASCRIPT_QUERIES,
+ [SupportedLanguages.Python]: PYTHON_QUERIES,
+ [SupportedLanguages.Java]: JAVA_QUERIES,
+ [SupportedLanguages.C]: C_QUERIES,
+ [SupportedLanguages.Go]: GO_QUERIES,
+ [SupportedLanguages.CPlusPlus]: CPP_QUERIES,
+ [SupportedLanguages.CSharp]: CSHARP_QUERIES,
+ [SupportedLanguages.Ruby]: RUBY_QUERIES,
+ [SupportedLanguages.Rust]: RUST_QUERIES,
+ [SupportedLanguages.PHP]: PHP_QUERIES,
+ [SupportedLanguages.Kotlin]: KOTLIN_QUERIES,
+ [SupportedLanguages.Swift]: SWIFT_QUERIES,
+};
diff --git a/core-ingestion/dist/types.d.ts b/core-ingestion/dist/types.d.ts
new file mode 100644
index 00000000..c0868c43
--- /dev/null
+++ b/core-ingestion/dist/types.d.ts
@@ -0,0 +1,20 @@
+export interface PatchSource {
+ uri: string;
+ sourceHash?: string;
+ extractor: string;
+ sourceType: string;
+}
+export interface PatchOp {
+ type: string;
+ [key: string]: unknown;
+}
+export interface GraphPatchPayload {
+ patchId: string;
+ actor: string;
+ timestamp: string;
+ source: PatchSource;
+ baseRev: number;
+ ops: PatchOp[];
+ replaces: string[];
+ intent?: string;
+}
diff --git a/core-ingestion/dist/types.js b/core-ingestion/dist/types.js
new file mode 100644
index 00000000..cb0ff5c3
--- /dev/null
+++ b/core-ingestion/dist/types.js
@@ -0,0 +1 @@
+export {};
diff --git a/core-ingestion/package.json b/core-ingestion/package.json
new file mode 100644
index 00000000..0befc1f6
--- /dev/null
+++ b/core-ingestion/package.json
@@ -0,0 +1,35 @@
+{
+ "name": "@ix/core-ingestion",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "exports": {
+ ".": "./dist/index.js",
+ "./languages": "./dist/languages.js",
+ "./patch-builder": "./dist/patch-builder.js",
+ "./types": "./dist/types.js"
+ },
+ "scripts": {
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json"
+ },
+ "dependencies": {
+ "tree-sitter": "^0.21.0",
+ "tree-sitter-c": "^0.21.0",
+ "tree-sitter-c-sharp": "^0.21.0",
+ "tree-sitter-cpp": "^0.22.0",
+ "tree-sitter-go": "^0.21.0",
+ "tree-sitter-java": "^0.21.0",
+ "tree-sitter-javascript": "^0.21.0",
+ "tree-sitter-php": "^0.23.12",
+ "tree-sitter-python": "^0.21.0",
+ "tree-sitter-ruby": "^0.23.1",
+ "tree-sitter-rust": "^0.21.0",
+ "tree-sitter-typescript": "^0.21.0"
+ },
+ "devDependencies": {
+ "@types/node": "^20.0.0",
+ "typescript": "^5.4.0"
+ }
+}
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
new file mode 100644
index 00000000..1ad07335
--- /dev/null
+++ b/core-ingestion/src/index.ts
@@ -0,0 +1,551 @@
+import * as nodePath from 'node:path';
+// @ts-ignore — tree-sitter has no bundled types
+import Parser from 'tree-sitter';
+// @ts-ignore
+import JavaScript from 'tree-sitter-javascript';
+// @ts-ignore
+import TypeScript from 'tree-sitter-typescript';
+// @ts-ignore
+import Python from 'tree-sitter-python';
+// @ts-ignore
+import Java from 'tree-sitter-java';
+// @ts-ignore
+import C from 'tree-sitter-c';
+// @ts-ignore
+import CPP from 'tree-sitter-cpp';
+// @ts-ignore
+import CSharp from 'tree-sitter-c-sharp';
+// @ts-ignore
+import Go from 'tree-sitter-go';
+// @ts-ignore
+import Rust from 'tree-sitter-rust';
+// @ts-ignore
+import Ruby from 'tree-sitter-ruby';
+// @ts-ignore
+import PHP from 'tree-sitter-php';
+
+import { SupportedLanguages, languageFromPath } from './languages.js';
+import { LANGUAGE_QUERIES } from './queries.js';
+
+// ---------------------------------------------------------------------------
+// Public types
+// ---------------------------------------------------------------------------
+
+export interface ParsedEntity {
+ name: string;
+ kind: string; // NodeKind string: "class", "function", "method", etc.
+ lineStart: number;
+ lineEnd: number;
+ language: string;
+ /** Direct enclosing class/interface/trait, if any (undefined for file-level entities). */
+ container?: string;
+}
+
+export interface ParsedRelationship {
+ srcName: string;
+ dstName: string;
+ predicate: string; // "CONTAINS" | "CALLS" | "IMPORTS" | "EXTENDS"
+}
+
+export interface FileParseResult {
+ filePath: string;
+ language: SupportedLanguages;
+ entities: ParsedEntity[];
+ relationships: ParsedRelationship[];
+}
+
+// ---------------------------------------------------------------------------
+// Language → grammar map
+// ---------------------------------------------------------------------------
+
+const GRAMMAR_MAP: Partial<Record<SupportedLanguages, any>> = {
+ [SupportedLanguages.JavaScript]: JavaScript,
+ [SupportedLanguages.TypeScript]: TypeScript.typescript,
+ [SupportedLanguages.Python]: Python,
+ [SupportedLanguages.Java]: Java,
+ [SupportedLanguages.C]: C,
+ [SupportedLanguages.CPlusPlus]: CPP,
+ [SupportedLanguages.CSharp]: CSharp,
+ [SupportedLanguages.Go]: Go,
+ [SupportedLanguages.Rust]: Rust,
+ [SupportedLanguages.Ruby]: Ruby,
+ [SupportedLanguages.PHP]: PHP.php_only,
+};
+
+// Capture key prefix → NodeKind string
+const DEFINITION_KIND_MAP: Record<string, string> = {
+ 'definition.class': 'class',
+ 'definition.interface': 'interface',
+ 'definition.function': 'function',
+ 'definition.method': 'method',
+ 'definition.struct': 'class',
+ 'definition.enum': 'class',
+ 'definition.trait': 'trait',
+ 'definition.module': 'module',
+ 'definition.namespace': 'module',
+ 'definition.impl': 'class',
+ 'definition.type': 'class',
+ 'definition.property': 'function',
+ 'definition.const': 'function',
+ 'definition.static': 'function',
+ 'definition.macro': 'function',
+ 'definition.union': 'class',
+ 'definition.typedef': 'class',
+ 'definition.template': 'class',
+ 'definition.record': 'class',
+ 'definition.delegate': 'class',
+ 'definition.annotation':'class',
+ 'definition.constructor':'method',
+};
+
+// Builtins to exclude from CALLS edges
+const BUILTINS = new Set([
+ 'print', 'println', 'len', 'range', 'int', 'str', 'float', 'list', 'dict',
+ 'set', 'tuple', 'type', 'isinstance', 'super', 'property', 'enumerate',
+ 'zip', 'map', 'filter', 'sorted', 'any', 'all', 'min', 'max', 'sum',
+ 'console', 'log', 'warn', 'error', 'debug', 'info',
+ 'module', 'exports', 'undefined', 'null', 'true', 'false',
+ 'if', 'for', 'while', 'return', 'new', 'this', 'self',
+ 'Promise', 'Array', 'Object', 'String', 'Number', 'Boolean', 'JSON',
+ 'Math', 'Date', 'Error', 'Map', 'Set', 'Symbol',
+ 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval',
+ 'process', 'Buffer', 'global', 'window', 'document',
+ 'require', 'fetch', 'parseInt', 'parseFloat', 'isNaN', 'isFinite',
+]);
+
+/** Returns true if a grammar is installed for the given file's language. */
+export function isGrammarSupported(filePath: string): boolean {
+ const language = languageFromPath(filePath);
+ if (!language) return false;
+ if (filePath.endsWith('.tsx')) return true; // TSX uses TypeScript.tsx, always available
+ return GRAMMAR_MAP[language] !== undefined;
+}
+
+// ---------------------------------------------------------------------------
+// Parser instance (reused across calls)
+// ---------------------------------------------------------------------------
+
+let _parser: Parser | null = null;
+
+function getParser(): Parser {
+ if (!_parser) _parser = new Parser();
+ return _parser;
+}
+
+// ---------------------------------------------------------------------------
+// Main parse function
+// ---------------------------------------------------------------------------
+
+export function parseFile(filePath: string, source: string): FileParseResult | null {
+ const language = languageFromPath(filePath);
+ if (!language) return null;
+
+ // TypeScript TSX uses a separate grammar
+ const isTsx = filePath.endsWith('.tsx');
+ const grammar = isTsx ? TypeScript.tsx : GRAMMAR_MAP[language];
+ if (!grammar) return null;
+
+ const queries = LANGUAGE_QUERIES[language];
+ if (!queries) return null;
+
+ try {
+ const parser = getParser();
+ parser.setLanguage(grammar);
+ const tree = parser.parse(source);
+ const query = new Parser.Query(grammar, queries);
+ const matches = query.matches(tree.rootNode);
+
+ const fileName = nodePath.basename(filePath);
+ const lines = source.split('\n');
+
+ const entities: ParsedEntity[] = [
+ { name: fileName, kind: 'file', lineStart: 1, lineEnd: lines.length, language },
+ ];
+ const relationships: ParsedRelationship[] = [];
+
+ // Track class ranges for containment: [name, startLine, endLine]
+ const classRanges: Array<{ name: string; start: number; end: number }> = [];
+ // Track seen calls per enclosing scope to avoid duplicate CALLS edges
+ const seenCalls = new Map<string, Set<string>>();
+
+ // --- First pass: collect definitions ---
+ for (const match of matches) {
+ // Definition captures: name + definition.*
+ const defCapture = match.captures.find((c: any) =>
+ c.name.startsWith('definition.')
+ );
+ const nameCapture = match.captures.find((c: any) => c.name === 'name');
+
+ if (defCapture) {
+ const kind = DEFINITION_KIND_MAP[defCapture.name] ?? 'function';
+ const name = nameCapture?.node.text
+ ?? (defCapture.name === 'definition.constructor' ? 'init' : '');
+ if (!name || name.length === 0) continue;
+
+ const defNode = defCapture.node;
+ const lineStart = defNode.startPosition.row + 1;
+ const lineEnd = defNode.endPosition.row + 1;
+
+ // Containment: file CONTAINS or class CONTAINS
+ const enclosing = findEnclosing(classRanges, lineStart, name);
+
+ entities.push({
+ name,
+ kind,
+ lineStart,
+ lineEnd,
+ language,
+ container: enclosing ?? undefined,
+ });
+
+ if (kind === 'class' || kind === 'interface' || kind === 'trait') {
+ classRanges.push({ name, start: lineStart, end: lineEnd });
+ }
+
+ if (enclosing) {
+ relationships.push({ srcName: enclosing, dstName: name, predicate: 'CONTAINS' });
+ } else {
+ relationships.push({ srcName: fileName, dstName: name, predicate: 'CONTAINS' });
+ }
+ continue;
+ }
+
+ // Heritage: EXTENDS
+ const heritageClass = match.captures.find((c: any) =>
+ c.name === 'heritage.class'
+ );
+ const heritageExtends = match.captures.find((c: any) =>
+ c.name === 'heritage.extends' || c.name === 'heritage.trait'
+ );
+ if (heritageClass && heritageExtends) {
+ relationships.push({
+ srcName: heritageClass.node.text,
+ dstName: heritageExtends.node.text,
+ predicate: 'EXTENDS',
+ });
+ continue;
+ }
+
+ // Heritage: IMPLEMENTS (separate edge type, use EXTENDS for simplicity)
+ const heritageImpl = match.captures.find((c: any) =>
+ c.name === 'heritage.implements'
+ );
+ if (heritageClass && heritageImpl) {
+ relationships.push({
+ srcName: heritageClass.node.text,
+ dstName: heritageImpl.node.text,
+ predicate: 'EXTENDS',
+ });
+ continue;
+ }
+ }
+
+ // --- Second pass: calls and imports ---
+ for (const match of matches) {
+ // Import captures
+ const importSource = match.captures.find((c: any) => c.name === 'import.source');
+ if (importSource) {
+ let importPath = importSource.node.text
+ .replace(/^["'`]|["'`]$/g, '') // strip quotes
+ .replace(/\\\\/g, '/'); // normalise backslashes
+ if (importPath.length > 0 && importPath !== '*') {
+ const rawMod = importPath.split('/').filter(s => s !== '*').pop() ?? importPath;
+ const modName = rawMod.replace(/^\.+/, ''); // strip leading dots: '.models' → 'models'
+ if (!modName) continue; // skip bare '.' relative imports
+ entities.push({ name: modName, kind: 'module', lineStart: importSource.node.startPosition.row + 1, lineEnd: importSource.node.startPosition.row + 1, language });
+ relationships.push({ srcName: fileName, dstName: modName, predicate: 'IMPORTS' });
+ }
+ continue;
+ }
+
+ // Import name captures (e.g. from . import utils — the symbol name, not the module path)
+ const importName = match.captures.find((c: any) => c.name === 'import.name');
+ if (importName) {
+ const name = importName.node.text;
+ if (name && name !== '*' && name.length > 1) {
+ entities.push({ name, kind: 'module', lineStart: importName.node.startPosition.row + 1, lineEnd: importName.node.startPosition.row + 1, language });
+ relationships.push({ srcName: fileName, dstName: name, predicate: 'IMPORTS' });
+ }
+ continue;
+ }
+
+ // Call captures
+ const callName = match.captures.find((c: any) => c.name === 'call.name');
+ if (callName) {
+ const callee = callName.node.text;
+ if (!callee || BUILTINS.has(callee) || callee.length <= 1) continue;
+
+ // Find enclosing function/method for the call
+ const callLine = callName.node.startPosition.row + 1;
+ const caller = findEnclosingFunction(entities, callLine) ?? fileName;
+
+ const scope = caller;
+ if (!seenCalls.has(scope)) seenCalls.set(scope, new Set());
+ const seen = seenCalls.get(scope)!;
+ if (!seen.has(callee)) {
+ seen.add(callee);
+ relationships.push({ srcName: caller, dstName: callee, predicate: 'CALLS' });
+ }
+ continue;
+ }
+ }
+
+ return { filePath, language, entities, relationships };
+ } catch {
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Cross-file CALLS resolution
+// ---------------------------------------------------------------------------
+
+export interface ResolvedCallEdge {
+ callerFilePath: string;
+ callerName: string; // the caller entity (function/method/file)
+ calleeFilePath: string; // the file where the callee is actually defined
+ calleeName: string; // plain name as it appears in the CALLS relationship
+ calleeQualifiedKey: string; // qualified key used for nodeId in the callee file
+ // e.g. 'PaymentService.charge' for a class method,
+ // or plain 'processPayment' for a module-level function
+ confidence: number; // 0.9 import-scoped | 0.5 global
+}
+
+// ---------------------------------------------------------------------------
+// resolveCallEdges helpers
+// ---------------------------------------------------------------------------
+
+/** Build the qualified key for an entity (mirrors buildPatch's entityQKey logic). */
+function qualifiedKey(e: ParsedEntity): string {
+ return e.container ? `${e.container}.${e.name}` : e.name;
+}
+
+/**
+ * Given a file's qualified-key map and a plain callee name, return the single
+ * unambiguous qualified key, or null if the name maps to 0 or >1 entities.
+ * Callers must treat null as "do not emit" to avoid dangling nodeIds.
+ */
+function bestQKey(
+ fileQKeys: Map<string, Map<string, string[]>>,
+ filePath: string,
+ plainName: string,
+): string | null {
+ const qks = fileQKeys.get(filePath)?.get(plainName) ?? [];
+ return qks.length === 1 ? qks[0] : null;
+}
+
+/**
+ * Resolves CALLS relationships to their cross-file targets by building a
+ * symbol table and import map over the full batch of parsed files.
+ *
+ * Tiers (in priority order):
+ * 0.9 — import-scoped: callee is in a file the caller explicitly imports
+ * 0.5 — global fallback: callee exists in exactly one other file (unambiguous)
+ *
+ * Same-file calls (tier 0.95) are already handled correctly by buildPatch and
+ * are not emitted here.
+ *
+ * Import resolution handles:
+ * - Stem-based: './payments' → 'payments.ts'
+ * - Path-aliased: '@/lib/payments' → 'payments.ts' (last segment)
+ * - Directory index: './services' → 'services/index.ts'
+ * - Bare aliases: '@components' → 'components.ts' (strip leading non-word chars)
+ * '~lib' → 'lib.ts'
+ * - External bare: 'react' → unresolved (no match in batch)
+ *
+ * Qualified-key resolution:
+ * - Module-level function: calleeQualifiedKey === calleeName
+ * - Unambiguous class method: calleeQualifiedKey === 'ClassName.method'
+ * - Ambiguous (two classes define same method name): edge not emitted
+ */
+export function resolveCallEdges(results: FileParseResult[]): ResolvedCallEdge[] {
+ // fileQKeys: filePath → (plainName → qualifiedKeys[])
+ // Mirrors the entityQKey computation in buildPatch so nodeIds match exactly.
+ const fileQKeys = new Map<string, Map<string, string[]>>();
+ for (const r of results) {
+ const qkMap = new Map<string, string[]>();
+ for (const e of r.entities) {
+ if (e.kind === 'file' || e.kind === 'module') continue;
+ const qk = qualifiedKey(e);
+ const list = qkMap.get(e.name) ?? [];
+ list.push(qk);
+ qkMap.set(e.name, list);
+ }
+ fileQKeys.set(r.filePath, qkMap);
+ }
+
+ // fileHasSymbol: filePath → Set<plainName> (fast membership check)
+ const fileHasSymbol = new Map<string, Set<string>>();
+ for (const [fp, qkMap] of fileQKeys) {
+ fileHasSymbol.set(fp, new Set(qkMap.keys()));
+ }
+
+ // stemToFiles: basename-without-extension → filePath[]
+ // Matches the last path segment of an import to files in the batch.
+ // e.g. './payments' → modName 'payments' → 'payments.ts'
+ // '@/lib/payments' → modName 'payments' → 'payments.ts'
+ const stemToFiles = new Map<string, string[]>();
+ for (const r of results) {
+ const stem = nodePath.basename(r.filePath, nodePath.extname(r.filePath));
+ const list = stemToFiles.get(stem) ?? [];
+ list.push(r.filePath);
+ stemToFiles.set(stem, list);
+ }
+
+ // dirToIndexFiles: directory basename → filePath[] for 'index.*' files
+ // Handles directory imports: './services' → 'services/index.ts'
+ const dirToIndexFiles = new Map<string, string[]>();
+ for (const r of results) {
+ const stem = nodePath.basename(r.filePath, nodePath.extname(r.filePath));
+ if (stem === 'index') {
+ const dirName = nodePath.basename(nodePath.dirname(r.filePath));
+ const list = dirToIndexFiles.get(dirName) ?? [];
+ list.push(r.filePath);
+ dirToIndexFiles.set(dirName, list);
+ }
+ }
+
+ const resolved: ResolvedCallEdge[] = [];
+
+ for (const result of results) {
+ const callerFilePath = result.filePath;
+ const callerSymbols = fileHasSymbol.get(callerFilePath)!;
+
+ // Build the set of file paths this caller explicitly imports.
+ // For each IMPORTS edge, try the modName as-is, then with leading
+ // non-word characters stripped (handles bare aliases: '@components' → 'components',
+ // '~lib' → 'lib', '#utils' → 'utils').
+ const importedFilePaths = new Set<string>();
+ for (const rel of result.relationships) {
+ if (rel.predicate !== 'IMPORTS') continue;
+ const candidates = [rel.dstName];
+ const stripped = rel.dstName.replace(/^[^a-zA-Z0-9_]+/, '');
+ if (stripped && stripped !== rel.dstName) candidates.push(stripped);
+ for (const modName of candidates) {
+ for (const fp of stemToFiles.get(modName) ?? []) {
+ if (fp !== callerFilePath) importedFilePaths.add(fp);
+ }
+ for (const fp of dirToIndexFiles.get(modName) ?? []) {
+ if (fp !== callerFilePath) importedFilePaths.add(fp);
+ }
+ }
+ }
+
+ // Build one-hop transitive import set: files imported by directly-imported files.
+ // Handles re-exports: baz.ts → index.ts (re-exports from bar.ts) → bar.ts
+ const transitiveFilePaths = new Set<string>();
+ for (const fp of importedFilePaths) {
+ const fpResult = results.find(r => r.filePath === fp);
+ if (!fpResult) continue;
+ for (const rel of fpResult.relationships) {
+ if (rel.predicate !== 'IMPORTS') continue;
+ const candidates = [rel.dstName];
+ const stripped = rel.dstName.replace(/^[^a-zA-Z0-9_]+/, '');
+ if (stripped && stripped !== rel.dstName) candidates.push(stripped);
+ for (const modName of candidates) {
+ for (const transitiveFp of stemToFiles.get(modName) ?? []) {
+ if (transitiveFp !== callerFilePath && !importedFilePaths.has(transitiveFp))
+ transitiveFilePaths.add(transitiveFp);
+ }
+ for (const transitiveFp of dirToIndexFiles.get(modName) ?? []) {
+ if (transitiveFp !== callerFilePath && !importedFilePaths.has(transitiveFp))
+ transitiveFilePaths.add(transitiveFp);
+ }
+ }
+ }
+ }
+
+ for (const rel of result.relationships) {
+ if (rel.predicate !== 'CALLS') continue;
+ const calleeName = rel.dstName;
+ const callerName = rel.srcName;
+
+ // Tier 1: same-file — already correct in buildPatch, skip here
+ if (callerSymbols.has(calleeName)) continue;
+
+ // Tier 2: import-scoped (confidence 0.9)
+ const importMatches: string[] = [];
+ for (const fp of importedFilePaths) {
+ if (fileHasSymbol.get(fp)?.has(calleeName)) importMatches.push(fp);
+ }
+
+ if (importMatches.length === 1) {
+ const fp = importMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null) continue; // ambiguous class methods — do not emit bad nodeId
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.9 });
+ continue;
+ }
+ if (importMatches.length > 1) continue; // ambiguous file — do not emit
+
+ // Tier 2.5: transitive import-scoped (confidence 0.8) — one re-export hop away
+ const transitiveMatches: string[] = [];
+ for (const fp of transitiveFilePaths) {
+ if (fileHasSymbol.get(fp)?.has(calleeName)) transitiveMatches.push(fp);
+ }
+
+ if (transitiveMatches.length === 1) {
+ const fp = transitiveMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null) continue;
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.8 });
+ continue;
+ }
+ if (transitiveMatches.length > 1) continue; // ambiguous — do not emit
+
+ // Tier 3: global fallback (confidence 0.5) — exactly one other file defines it
+ const globalMatches: string[] = [];
+ for (const [fp, symbols] of fileHasSymbol) {
+ if (fp !== callerFilePath && symbols.has(calleeName)) globalMatches.push(fp);
+ }
+
+ if (globalMatches.length === 1) {
+ const fp = globalMatches[0];
+ const calleeQualifiedKey = bestQKey(fileQKeys, fp, calleeName);
+ if (calleeQualifiedKey === null) continue; // ambiguous class methods — do not emit bad nodeId
+ resolved.push({ callerFilePath, callerName, calleeFilePath: fp, calleeName, calleeQualifiedKey, confidence: 0.5 });
+ }
+ // 0 or >1 global matches — leave as dangling edge, do not emit
+ }
+ }
+
+ return resolved;
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function findEnclosing(
+ ranges: Array<{ name: string; start: number; end: number }>,
+ line: number,
+ excludeName: string
+): string | null {
+ // Find the innermost class/interface that contains this line
+ let best: { name: string; start: number; end: number } | null = null;
+ for (const r of ranges) {
+ if (r.name === excludeName) continue;
+ if (line >= r.start && line <= r.end) {
+ if (!best || (r.end - r.start) < (best.end - best.start)) {
+ best = r;
+ }
+ }
+ }
+ return best?.name ?? null;
+}
+
+function findEnclosingFunction(
+ entities: ParsedEntity[],
+ line: number
+): string | null {
+ let best: ParsedEntity | null = null;
+ for (const e of entities) {
+ if (e.kind !== 'function' && e.kind !== 'method') continue;
+ if (line >= e.lineStart && line <= e.lineEnd) {
+ if (!best || (e.lineEnd - e.lineStart) < (best.lineEnd - best.lineStart)) {
+ best = e;
+ }
+ }
+ }
+ return best ? (best.container ? `${best.container}.${best.name}` : best.name) : null;
+}
diff --git a/core-ingestion/src/languages.ts b/core-ingestion/src/languages.ts
new file mode 100644
index 00000000..f8d76c14
--- /dev/null
+++ b/core-ingestion/src/languages.ts
@@ -0,0 +1,45 @@
+export enum SupportedLanguages {
+ JavaScript = 'javascript',
+ TypeScript = 'typescript',
+ Python = 'python',
+ Java = 'java',
+ C = 'c',
+ CPlusPlus = 'cpp',
+ CSharp = 'csharp',
+ Go = 'go',
+ Ruby = 'ruby',
+ Rust = 'rust',
+ PHP = 'php',
+ Kotlin = 'kotlin',
+ Swift = 'swift',
+}
+
+const EXT_MAP: Record<string, SupportedLanguages> = {
+ '.ts': SupportedLanguages.TypeScript,
+ '.tsx': SupportedLanguages.TypeScript,
+ '.js': SupportedLanguages.JavaScript,
+ '.jsx': SupportedLanguages.JavaScript,
+ '.mjs': SupportedLanguages.JavaScript,
+ '.cjs': SupportedLanguages.JavaScript,
+ '.py': SupportedLanguages.Python,
+ '.java': SupportedLanguages.Java,
+ '.c': SupportedLanguages.C,
+ '.h': SupportedLanguages.C,
+ '.cpp': SupportedLanguages.CPlusPlus,
+ '.cc': SupportedLanguages.CPlusPlus,
+ '.cxx': SupportedLanguages.CPlusPlus,
+ '.hpp': SupportedLanguages.CPlusPlus,
+ '.cs': SupportedLanguages.CSharp,
+ '.go': SupportedLanguages.Go,
+ '.rb': SupportedLanguages.Ruby,
+ '.rs': SupportedLanguages.Rust,
+ '.php': SupportedLanguages.PHP,
+ '.kt': SupportedLanguages.Kotlin,
+ '.kts': SupportedLanguages.Kotlin,
+ '.swift':SupportedLanguages.Swift,
+};
+
+export function languageFromPath(filePath: string): SupportedLanguages | null {
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
+ return EXT_MAP[ext] ?? null;
+}
diff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.ts
new file mode 100644
index 00000000..bd3a1d1d
--- /dev/null
+++ b/core-ingestion/src/patch-builder.ts
@@ -0,0 +1,272 @@
+import * as crypto from 'node:crypto';
+import * as nodePath from 'node:path';
+import type { GraphPatchPayload, PatchOp } from './types.js';
+import type { FileParseResult, ParsedEntity, ResolvedCallEdge } from './index.js';
+
+// ---------------------------------------------------------------------------
+// Deterministic UUID from a string (matches existing CLI convention)
+// ---------------------------------------------------------------------------
+
+function deterministicId(input: string): string {
+ const hash = crypto.createHash('sha256').update(input).digest('hex');
+ return [
+ hash.slice(0, 8),
+ hash.slice(8, 12),
+ hash.slice(12, 16),
+ hash.slice(16, 20),
+ hash.slice(20, 32),
+ ].join('-');
+}
+
+function nodeId(filePath: string, name: string): string {
+ return deterministicId(`${filePath}:${name}`);
+}
+
+function edgeId(filePath: string, src: string, dst: string, predicate: string): string {
+ return deterministicId(`${filePath}:${src}:${dst}:${predicate}`);
+}
+
+// ---------------------------------------------------------------------------
+// Source type from file extension
+// ---------------------------------------------------------------------------
+
+function sourceType(filePath: string): string {
+ const ext = filePath.slice(filePath.lastIndexOf('.')).toLowerCase();
+ if (['.json', '.yaml', '.yml', '.toml', '.ini', '.conf', '.env'].includes(ext)) return 'config';
+ if (['.md', '.mdx', '.rst', '.txt'].includes(ext)) return 'doc';
+ return 'code';
+}
+
+function extractorName(): string {
+ return `tree-sitter/1.0`;
+}
+
+// ---------------------------------------------------------------------------
+// Build a GraphPatchPayload from a FileParseResult
+// ---------------------------------------------------------------------------
+
+export function buildPatch(
+ result: FileParseResult,
+ sourceHash: string,
+ previousSourceHash?: string
+): GraphPatchPayload {
+ const { filePath, entities, relationships } = result;
+ const ops: PatchOp[] = [];
+
+ // Build a qualified-key map so that same-named entities in different
+ // enclosing classes within the same file get distinct nodeIds.
+ // e.g. ClassA.update vs ClassB.update instead of both being "update".
+ const entityQKey = new Map<ParsedEntity, string>();
+ for (const e of entities) {
+ entityQKey.set(e, e.container ? `${e.container}.${e.name}` : e.name);
+ }
+
+ // Reverse lookup: plain name → list of qualified keys (for edge resolution).
+ const nameToQKeys = new Map<string, string[]>();
+ for (const [e, qk] of entityQKey) {
+ const list = nameToQKeys.get(e.name) ?? [];
+ list.push(qk);
+ nameToQKeys.set(e.name, list);
+ }
+
+ // Resolve a relationship endpoint to the best qualified key.
+ // For unambiguous names (appear once), returns the single qualified key.
+ // For ambiguous names (appear multiple times), falls back to the plain name
+ // so that the edge still points to *something* deterministic.
+ function resolveKey(name: string, container?: string): string {
+ const keys = nameToQKeys.get(name);
+ if (!keys || keys.length === 1) return keys?.[0] ?? name;
+ // More than one entity with this name — try to pick by container
+ if (container) {
+ const qualified = `${container}.${name}`;
+ if (keys.includes(qualified)) return qualified;
+ }
+ // Ambiguous: return plain name so we don't silently drop the edge
+ return name;
+ }
+
+ // UpsertNode for each entity
+ for (const e of entities) {
+ const qk = entityQKey.get(e)!;
+ ops.push({
+ type: 'UpsertNode',
+ id: nodeId(filePath, qk),
+ kind: e.kind,
+ name: e.name,
+ attrs: {
+ line_start: e.lineStart,
+ line_end: e.lineEnd,
+ language: e.language,
+ },
+ });
+ }
+
+ // UpsertEdge for each relationship
+ for (const r of relationships) {
+ // For CONTAINS edges, srcName is the container of dstName — use that to disambiguate.
+ const srcKey = resolveKey(r.srcName);
+ const dstKey = r.predicate === 'CONTAINS'
+ ? resolveKey(r.dstName, r.srcName)
+ : resolveKey(r.dstName);
+
+ ops.push({
+ type: 'UpsertEdge',
+ id: edgeId(filePath, srcKey, dstKey, r.predicate),
+ src: nodeId(filePath, srcKey),
+ dst: nodeId(filePath, dstKey),
+ predicate: r.predicate,
+ attrs: {},
+ });
+ }
+
+ // AssertClaim for each relationship (feeds the confidence/conflict engine)
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ ops.push({
+ type: 'AssertClaim',
+ entityId: nodeId(filePath, srcKey),
+ field: `${r.predicate.toLowerCase()}:${r.dstName}`,
+ value: r.dstName,
+ confidence: null,
+ });
+ }
+
+ // patchId is deterministic: same file + same content → same id across runs.
+ // This makes repeated ingestion idempotent at the patch level.
+ const patchId = deterministicId(`${filePath}:${sourceHash}`);
+ const previousPatchId = previousSourceHash
+ ? deterministicId(`${filePath}:${previousSourceHash}`)
+ : undefined;
+
+ return {
+ patchId,
+ actor: 'ix/ingestion',
+ timestamp: new Date().toISOString(),
+ source: {
+ uri: filePath,
+ sourceHash,
+ extractor: extractorName(),
+ sourceType: sourceType(filePath),
+ },
+ baseRev: 0,
+ ops,
+ replaces: previousPatchId ? [previousPatchId] : [],
+ intent: `Parsed ${nodePath.basename(filePath)}`,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// buildPatchWithResolution — like buildPatch but fixes CALLS edge dst to point
+// to the actual defining file for cross-file calls resolved by resolveCallEdges.
+// ---------------------------------------------------------------------------
+
+export function buildPatchWithResolution(
+ result: FileParseResult,
+ sourceHash: string,
+ resolvedEdges: ResolvedCallEdge[],
+ previousSourceHash?: string,
+): GraphPatchPayload {
+ // Build lookup: calleeName → { calleeFilePath, calleeQualifiedKey }
+ const callResolution = new Map<string, { calleeFilePath: string; calleeQualifiedKey: string }>();
+ for (const edge of resolvedEdges) {
+ if (edge.callerFilePath === result.filePath) {
+ callResolution.set(edge.calleeName, {
+ calleeFilePath: edge.calleeFilePath,
+ calleeQualifiedKey: edge.calleeQualifiedKey,
+ });
+ }
+ }
+
+ const { filePath, entities, relationships } = result;
+ const ops: PatchOp[] = [];
+
+ const entityQKey = new Map<ParsedEntity, string>();
+ for (const e of entities) {
+ entityQKey.set(e, e.container ? `${e.container}.${e.name}` : e.name);
+ }
+
+ const nameToQKeys = new Map<string, string[]>();
+ for (const [e, qk] of entityQKey) {
+ const list = nameToQKeys.get(e.name) ?? [];
+ list.push(qk);
+ nameToQKeys.set(e.name, list);
+ }
+
+ function resolveKey(name: string, container?: string): string {
+ const keys = nameToQKeys.get(name);
+ if (!keys || keys.length === 1) return keys?.[0] ?? name;
+ if (container) {
+ const qualified = `${container}.${name}`;
+ if (keys.includes(qualified)) return qualified;
+ }
+ return name;
+ }
+
+ for (const e of entities) {
+ const qk = entityQKey.get(e)!;
+ ops.push({
+ type: 'UpsertNode',
+ id: nodeId(filePath, qk),
+ kind: e.kind,
+ name: e.name,
+ attrs: { line_start: e.lineStart, line_end: e.lineEnd, language: e.language },
+ });
+ }
+
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ const dstKey = r.predicate === 'CONTAINS'
+ ? resolveKey(r.dstName, r.srcName)
+ : resolveKey(r.dstName);
+
+ // For CALLS edges with a cross-file resolution, use the callee file's nodeId
+ let dstNodeId: string;
+ if (r.predicate === 'CALLS' && callResolution.has(r.dstName)) {
+ const { calleeFilePath, calleeQualifiedKey } = callResolution.get(r.dstName)!;
+ dstNodeId = nodeId(calleeFilePath, calleeQualifiedKey);
+ } else {
+ dstNodeId = nodeId(filePath, dstKey);
+ }
+
+ ops.push({
+ type: 'UpsertEdge',
+ id: edgeId(filePath, srcKey, dstKey, r.predicate),
+ src: nodeId(filePath, srcKey),
+ dst: dstNodeId,
+ predicate: r.predicate,
+ attrs: {},
+ });
+ }
+
+ for (const r of relationships) {
+ const srcKey = resolveKey(r.srcName);
+ ops.push({
+ type: 'AssertClaim',
+ entityId: nodeId(filePath, srcKey),
+ field: `${r.predicate.toLowerCase()}:${r.dstName}`,
+ value: r.dstName,
+ confidence: null,
+ });
+ }
+
+ const patchId = deterministicId(`${filePath}:${sourceHash}`);
+ const previousPatchId = previousSourceHash
+ ? deterministicId(`${filePath}:${previousSourceHash}`)
+ : undefined;
+
+ return {
+ patchId,
+ actor: 'ix/ingestion',
+ timestamp: new Date().toISOString(),
+ source: {
+ uri: filePath,
+ sourceHash,
+ extractor: extractorName(),
+ sourceType: sourceType(filePath),
+ },
+ baseRev: 0,
+ ops,
+ replaces: previousPatchId ? [previousPatchId] : [],
+ intent: `Parsed ${nodePath.basename(filePath)}`,
+ };
+}
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
new file mode 100644
index 00000000..6c9edd97
--- /dev/null
+++ b/core-ingestion/src/queries.ts
@@ -0,0 +1,719 @@
+import { SupportedLanguages } from './languages.js';
+
+/*
+ * Tree-sitter queries for extracting code definitions.
+ *
+ * Note: Different grammars (typescript vs tsx vs javascript) may have
+ * slightly different node types. These queries are designed to be
+ * compatible with the standard tree-sitter grammars.
+ */
+
+// TypeScript queries - works with tree-sitter-typescript
+export const TYPESCRIPT_QUERIES = `
+(class_declaration
+ name: (type_identifier) @name) @definition.class
+
+(interface_declaration
+ name: (type_identifier) @name) @definition.interface
+
+(function_declaration
+ name: (identifier) @name) @definition.function
+
+(method_definition
+ name: (property_identifier) @name) @definition.method
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function)))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression)))) @definition.function
+
+(import_statement
+ source: (string) @import.source) @import
+
+; Re-export statements: export { X } from './y'
+(export_statement
+ source: (string) @import.source) @import
+
+; Dynamic import with string literal: import('./foo') or await import('./foo')
+(call_expression
+ function: (import)
+ arguments: (arguments (string) @import.source)) @import
+
+(call_expression
+ function: (identifier) @call.name) @call
+
+(call_expression
+ function: (member_expression
+ property: (property_identifier) @call.name)) @call
+
+; Constructor calls: new Foo()
+(new_expression
+ constructor: (identifier) @call.name) @call
+
+; Heritage queries - class extends
+(class_declaration
+ name: (type_identifier) @heritage.class
+ (class_heritage
+ (extends_clause
+ value: (identifier) @heritage.extends))) @heritage
+
+; Heritage queries - class implements interface
+(class_declaration
+ name: (type_identifier) @heritage.class
+ (class_heritage
+ (implements_clause
+ (type_identifier) @heritage.implements))) @heritage.impl
+`;
+
+// JavaScript queries - works with tree-sitter-javascript
+export const JAVASCRIPT_QUERIES = `
+(class_declaration
+ name: (identifier) @name) @definition.class
+
+(function_declaration
+ name: (identifier) @name) @definition.function
+
+(method_definition
+ name: (property_identifier) @name) @definition.method
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+(lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function)))) @definition.function
+
+(export_statement
+ declaration: (lexical_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression)))) @definition.function
+
+(import_statement
+ source: (string) @import.source) @import
+
+; Re-export statements: export { X } from './y'
+(export_statement
+ source: (string) @import.source) @import
+
+; Dynamic import with string literal: import('./foo') or await import('./foo')
+(call_expression
+ function: (import)
+ arguments: (arguments (string) @import.source)) @import
+
+(call_expression
+ function: (identifier) @call.name) @call
+
+(call_expression
+ function: (member_expression
+ property: (property_identifier) @call.name)) @call
+
+; Constructor calls: new Foo()
+(new_expression
+ constructor: (identifier) @call.name) @call
+
+; Heritage queries - class extends (JavaScript uses different AST than TypeScript)
+; In tree-sitter-javascript, class_heritage directly contains the parent identifier
+(class_declaration
+ name: (identifier) @heritage.class
+ (class_heritage
+ (identifier) @heritage.extends)) @heritage
+`;
+
+// Python queries - works with tree-sitter-python
+export const PYTHON_QUERIES = `
+(class_definition
+ name: (identifier) @name) @definition.class
+
+(function_definition
+ name: (identifier) @name) @definition.function
+
+(import_statement
+ name: (dotted_name) @import.source) @import
+
+(import_from_statement
+ module_name: (dotted_name) @import.source) @import
+
+(import_from_statement
+ module_name: (relative_import) @import.source) @import
+
+; from . import utils / from .models import User — also capture the imported symbol names
+(import_from_statement
+ module_name: (relative_import)
+ name: (dotted_name (identifier) @import.name)) @import.names
+
+(call
+ function: (identifier) @call.name) @call
+
+(call
+ function: (attribute
+ attribute: (identifier) @call.name)) @call
+
+; Heritage queries - Python class inheritance
+(class_definition
+ name: (identifier) @heritage.class
+ superclasses: (argument_list
+ (identifier) @heritage.extends)) @heritage
+`;
+
+// Java queries - works with tree-sitter-java
+export const JAVA_QUERIES = `
+; Classes, Interfaces, Enums, Annotations
+(class_declaration name: (identifier) @name) @definition.class
+(interface_declaration name: (identifier) @name) @definition.interface
+(enum_declaration name: (identifier) @name) @definition.enum
+(annotation_type_declaration name: (identifier) @name) @definition.annotation
+
+; Methods & Constructors
+(method_declaration name: (identifier) @name) @definition.method
+(constructor_declaration name: (identifier) @name) @definition.constructor
+
+; Imports - capture any import declaration child as source
+(import_declaration (_) @import.source) @import
+
+; Calls
+(method_invocation name: (identifier) @call.name) @call
+(method_invocation object: (_) name: (identifier) @call.name) @call
+
+; Constructor calls: new Foo()
+(object_creation_expression type: (type_identifier) @call.name) @call
+
+; Heritage - extends class
+(class_declaration name: (identifier) @heritage.class
+ (superclass (type_identifier) @heritage.extends)) @heritage
+
+; Heritage - implements interfaces
+(class_declaration name: (identifier) @heritage.class
+ (super_interfaces (type_list (type_identifier) @heritage.implements))) @heritage.impl
+`;
+
+// C queries - works with tree-sitter-c
+export const C_QUERIES = `
+; Functions (direct declarator)
+(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+
+; Functions returning pointers (pointer_declarator wraps function_declarator)
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+
+; Functions returning double pointers (nested pointer_declarator)
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function
+
+; Structs, Unions, Enums, Typedefs
+(struct_specifier name: (type_identifier) @name) @definition.struct
+(union_specifier name: (type_identifier) @name) @definition.union
+(enum_specifier name: (type_identifier) @name) @definition.enum
+(type_definition declarator: (type_identifier) @name) @definition.typedef
+
+; Macros
+(preproc_function_def name: (identifier) @name) @definition.macro
+(preproc_def name: (identifier) @name) @definition.macro
+
+; Includes
+(preproc_include path: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+`;
+
+// Go queries - works with tree-sitter-go
+export const GO_QUERIES = `
+; Functions & Methods
+(function_declaration name: (identifier) @name) @definition.function
+(method_declaration name: (field_identifier) @name) @definition.method
+
+; Types
+(type_declaration (type_spec name: (type_identifier) @name type: (struct_type))) @definition.struct
+(type_declaration (type_spec name: (type_identifier) @name type: (interface_type))) @definition.interface
+
+; Imports
+(import_declaration (import_spec path: (interpreted_string_literal) @import.source)) @import
+(import_declaration (import_spec_list (import_spec path: (interpreted_string_literal) @import.source))) @import
+
+; Struct embedding (anonymous fields = inheritance)
+(type_declaration
+ (type_spec
+ name: (type_identifier) @heritage.class
+ type: (struct_type
+ (field_declaration_list
+ (field_declaration
+ type: (type_identifier) @heritage.extends))))) @definition.struct
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (selector_expression field: (field_identifier) @call.name)) @call
+
+; Struct literal construction: User{Name: "Alice"}
+(composite_literal type: (type_identifier) @call.name) @call
+`;
+
+// C++ queries - works with tree-sitter-cpp
+export const CPP_QUERIES = `
+; Classes, Structs, Namespaces
+(class_specifier name: (type_identifier) @name) @definition.class
+(struct_specifier name: (type_identifier) @name) @definition.struct
+(namespace_definition name: (namespace_identifier) @name) @definition.namespace
+(enum_specifier name: (type_identifier) @name) @definition.enum
+
+; Typedefs and unions (common in C-style headers and mixed C/C++ code)
+(type_definition declarator: (type_identifier) @name) @definition.typedef
+(union_specifier name: (type_identifier) @name) @definition.union
+
+; Macros
+(preproc_function_def name: (identifier) @name) @definition.macro
+(preproc_def name: (identifier) @name) @definition.macro
+
+; Functions & Methods (direct declarator)
+(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))) @definition.method
+
+; Functions/methods returning pointers (pointer_declarator wraps function_declarator)
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method
+
+; Functions/methods returning double pointers (nested pointer_declarator)
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function
+(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @name))))) @definition.method
+
+; Functions/methods returning references (reference_declarator wraps function_declarator)
+(function_definition declarator: (reference_declarator (function_declarator declarator: (identifier) @name))) @definition.function
+(function_definition declarator: (reference_declarator (function_declarator declarator: (qualified_identifier name: (identifier) @name)))) @definition.method
+
+; Destructors (destructor_name is distinct from identifier in tree-sitter-cpp)
+(function_definition declarator: (function_declarator declarator: (qualified_identifier name: (destructor_name) @name))) @definition.method
+
+; Function declarations / prototypes (common in headers)
+(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function
+(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function
+
+; Inline class method declarations (inside class body, no body: void Foo();)
+(field_declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.method
+
+; Inline class method definitions (inside class body, with body: void Foo() { ... })
+(field_declaration_list
+ (function_definition
+ declarator: (function_declarator
+ declarator: [(field_identifier) (identifier) (operator_name) (destructor_name)] @name)) @definition.method)
+
+; Templates
+(template_declaration (class_specifier name: (type_identifier) @name)) @definition.template
+(template_declaration (function_definition declarator: (function_declarator declarator: (identifier) @name))) @definition.template
+
+; Includes
+(preproc_include path: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+(call_expression function: (qualified_identifier name: (identifier) @call.name)) @call
+(call_expression function: (template_function name: (identifier) @call.name)) @call
+
+; Constructor calls: new User()
+(new_expression type: (type_identifier) @call.name) @call
+
+; Heritage
+(class_specifier name: (type_identifier) @heritage.class
+ (base_class_clause (type_identifier) @heritage.extends)) @heritage
+(class_specifier name: (type_identifier) @heritage.class
+ (base_class_clause (access_specifier) (type_identifier) @heritage.extends)) @heritage
+`;
+
+// C# queries - works with tree-sitter-c-sharp
+export const CSHARP_QUERIES = `
+; Types
+(class_declaration name: (identifier) @name) @definition.class
+(interface_declaration name: (identifier) @name) @definition.interface
+(struct_declaration name: (identifier) @name) @definition.struct
+(enum_declaration name: (identifier) @name) @definition.enum
+(record_declaration name: (identifier) @name) @definition.record
+(delegate_declaration name: (identifier) @name) @definition.delegate
+
+; Namespaces (block form and C# 10+ file-scoped form)
+(namespace_declaration name: (identifier) @name) @definition.namespace
+(namespace_declaration name: (qualified_name) @name) @definition.namespace
+(file_scoped_namespace_declaration name: (identifier) @name) @definition.namespace
+(file_scoped_namespace_declaration name: (qualified_name) @name) @definition.namespace
+
+; Methods & Properties
+(method_declaration name: (identifier) @name) @definition.method
+(local_function_statement name: (identifier) @name) @definition.function
+(constructor_declaration name: (identifier) @name) @definition.constructor
+(property_declaration name: (identifier) @name) @definition.property
+
+; Primary constructors (C# 12): class User(string name, int age) { }
+(class_declaration name: (identifier) @name (parameter_list) @definition.constructor)
+(record_declaration name: (identifier) @name (parameter_list) @definition.constructor)
+
+; Using
+(using_directive (qualified_name) @import.source) @import
+(using_directive (identifier) @import.source) @import
+
+; Calls
+(invocation_expression function: (identifier) @call.name) @call
+(invocation_expression function: (member_access_expression name: (identifier) @call.name)) @call
+
+; Null-conditional method calls: user?.Save()
+; Parses as: invocation_expression → conditional_access_expression → member_binding_expression → identifier
+(invocation_expression
+ function: (conditional_access_expression
+ (member_binding_expression
+ (identifier) @call.name))) @call
+
+; Constructor calls: new Foo() and new Foo { Props }
+(object_creation_expression type: (identifier) @call.name) @call
+
+; Target-typed new (C# 9): User u = new("x", 5)
+(variable_declaration type: (identifier) @call.name (variable_declarator (implicit_object_creation_expression) @call))
+
+; Heritage
+(class_declaration name: (identifier) @heritage.class
+ (base_list (identifier) @heritage.extends)) @heritage
+(class_declaration name: (identifier) @heritage.class
+ (base_list (generic_name (identifier) @heritage.extends))) @heritage
+`;
+
+// Rust queries - works with tree-sitter-rust
+export const RUST_QUERIES = `
+; Functions & Items
+(function_item name: (identifier) @name) @definition.function
+(struct_item name: (type_identifier) @name) @definition.struct
+(enum_item name: (type_identifier) @name) @definition.enum
+(trait_item name: (type_identifier) @name) @definition.trait
+(impl_item type: (type_identifier) @name !trait) @definition.impl
+(impl_item type: (generic_type type: (type_identifier) @name) !trait) @definition.impl
+(mod_item name: (identifier) @name) @definition.module
+
+; Type aliases, const, static, macros
+(type_item name: (type_identifier) @name) @definition.type
+(const_item name: (identifier) @name) @definition.const
+(static_item name: (identifier) @name) @definition.static
+(macro_definition name: (identifier) @name) @definition.macro
+
+; Use statements
+(use_declaration argument: (_) @import.source) @import
+
+; Calls
+(call_expression function: (identifier) @call.name) @call
+(call_expression function: (field_expression field: (field_identifier) @call.name)) @call
+(call_expression function: (scoped_identifier name: (identifier) @call.name)) @call
+(call_expression function: (generic_function function: (identifier) @call.name)) @call
+
+; Struct literal construction: User { name: value }
+(struct_expression name: (type_identifier) @call.name) @call
+
+; Heritage (trait implementation) — all combinations of concrete/generic trait × concrete/generic type
+(impl_item trait: (type_identifier) @heritage.trait type: (type_identifier) @heritage.class) @heritage
+(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (type_identifier) @heritage.class) @heritage
+(impl_item trait: (type_identifier) @heritage.trait type: (generic_type type: (type_identifier) @heritage.class)) @heritage
+(impl_item trait: (generic_type type: (type_identifier) @heritage.trait) type: (generic_type type: (type_identifier) @heritage.class)) @heritage
+`;
+
+// PHP queries - works with tree-sitter-php (php_only grammar)
+export const PHP_QUERIES = `
+; ── Namespace ────────────────────────────────────────────────────────────────
+(namespace_definition
+ name: (namespace_name) @name) @definition.namespace
+
+; ── Classes ──────────────────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @name) @definition.class
+
+; ── Interfaces ───────────────────────────────────────────────────────────────
+(interface_declaration
+ name: (name) @name) @definition.interface
+
+; ── Traits ───────────────────────────────────────────────────────────────────
+(trait_declaration
+ name: (name) @name) @definition.trait
+
+; ── Enums (PHP 8.1) ──────────────────────────────────────────────────────────
+(enum_declaration
+ name: (name) @name) @definition.enum
+
+; ── Top-level functions ───────────────────────────────────────────────────────
+(function_definition
+ name: (name) @name) @definition.function
+
+; ── Methods (including constructors) ─────────────────────────────────────────
+(method_declaration
+ name: (name) @name) @definition.method
+
+; ── Class properties (including Eloquent $fillable, $casts, etc.) ────────────
+(property_declaration
+ (property_element
+ (variable_name
+ (name) @name))) @definition.property
+
+; ── Imports: use statements ──────────────────────────────────────────────────
+; Simple: use App\\Models\\User;
+(namespace_use_declaration
+ (namespace_use_clause
+ (qualified_name) @import.source)) @import
+
+; ── Function/method calls ────────────────────────────────────────────────────
+; Regular function call: foo()
+(function_call_expression
+ function: (name) @call.name) @call
+
+; Method call: $obj->method()
+(member_call_expression
+ name: (name) @call.name) @call
+
+; Nullsafe method call: $obj?->method()
+(nullsafe_member_call_expression
+ name: (name) @call.name) @call
+
+; Static call: Foo::bar() (php_only uses scoped_call_expression)
+(scoped_call_expression
+ name: (name) @call.name) @call
+
+; Constructor call: new User()
+(object_creation_expression (name) @call.name) @call
+
+; ── Heritage: extends ────────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @heritage.class
+ (base_clause
+ [(name) (qualified_name)] @heritage.extends)) @heritage
+
+; ── Heritage: implements ─────────────────────────────────────────────────────
+(class_declaration
+ name: (name) @heritage.class
+ (class_interface_clause
+ [(name) (qualified_name)] @heritage.implements)) @heritage.impl
+
+; ── Heritage: use trait (must capture enclosing class name) ──────────────────
+(class_declaration
+ name: (name) @heritage.class
+ body: (declaration_list
+ (use_declaration
+ [(name) (qualified_name)] @heritage.trait))) @heritage
+`;
+
+// Ruby queries - works with tree-sitter-ruby
+export const RUBY_QUERIES = `
+; ── Modules ──────────────────────────────────────────────────────────────────
+(module
+ name: (constant) @name) @definition.module
+
+; ── Classes ──────────────────────────────────────────────────────────────────
+(class
+ name: (constant) @name) @definition.class
+
+; ── Instance methods ─────────────────────────────────────────────────────────
+(method
+ name: (identifier) @name) @definition.method
+
+; ── Singleton (class-level) methods ──────────────────────────────────────────
+(singleton_method
+ name: (identifier) @name) @definition.method
+
+; ── Require / require_relative → IMPORTS ─────────────────────────────────────
+; Capture the string argument so the second pass emits an IMPORTS edge.
+(call
+ method: (identifier) @_req
+ arguments: (argument_list
+ (string (string_content) @import.source))
+ (#match? @_req "^require")) @import
+
+; ── All other calls ───────────────────────────────────────────────────────────
+(call
+ method: (identifier) @call.name) @call
+
+; ── Bare calls without parens (identifiers at statement level are method calls) ─
+; NOTE: This may over-capture variable reads as calls (e.g. 'result' at
+; statement level). Ruby's grammar makes bare identifiers ambiguous — they
+; could be local variables or zero-arity method calls. Post-processing via
+; the BUILTINS set suppresses most false positives.
+(body_statement
+ (identifier) @call.name @call)
+
+; ── Heritage: class < SuperClass ─────────────────────────────────────────────
+(class
+ name: (constant) @heritage.class
+ superclass: (superclass
+ (constant) @heritage.extends)) @heritage
+`;
+
+// Kotlin queries - works with tree-sitter-kotlin (fwcd/tree-sitter-kotlin)
+// Based on official tags.scm; functions use simple_identifier, classes use type_identifier
+export const KOTLIN_QUERIES = `
+; ── Interfaces ─────────────────────────────────────────────────────────────
+; tree-sitter-kotlin (fwcd) has no interface_declaration node type.
+; Interfaces are class_declaration nodes with an anonymous "interface" keyword child.
+(class_declaration
+ "interface"
+ (type_identifier) @name) @definition.interface
+
+; ── Classes (regular, data, sealed, enum) ────────────────────────────────
+; All have the anonymous "class" keyword child. enum class has both
+; "enum" and "class" children — the "class" child still matches.
+(class_declaration
+ "class"
+ (type_identifier) @name) @definition.class
+
+; ── Object declarations (Kotlin singletons) ──────────────────────────────
+(object_declaration
+ (type_identifier) @name) @definition.class
+
+; ── Companion objects (named only) ───────────────────────────────────────
+(companion_object
+ (type_identifier) @name) @definition.class
+
+; ── Functions (top-level, member, extension) ──────────────────────────────
+(function_declaration
+ (simple_identifier) @name) @definition.function
+
+; ── Properties ───────────────────────────────────────────────────────────
+(property_declaration
+ (variable_declaration
+ (simple_identifier) @name)) @definition.property
+
+; ── Enum entries ─────────────────────────────────────────────────────────
+(enum_entry
+ (simple_identifier) @name) @definition.enum
+
+; ── Type aliases ─────────────────────────────────────────────────────────
+(type_alias
+ (type_identifier) @name) @definition.type
+
+; ── Imports ──────────────────────────────────────────────────────────────
+(import_header
+ (identifier) @import.source) @import
+
+; ── Function calls (direct) ──────────────────────────────────────────────
+(call_expression
+ (simple_identifier) @call.name) @call
+
+; ── Method calls (via navigation: obj.method()) ──────────────────────────
+(call_expression
+ (navigation_expression
+ (navigation_suffix
+ (simple_identifier) @call.name))) @call
+
+; ── Constructor invocations ──────────────────────────────────────────────
+(constructor_invocation
+ (user_type
+ (type_identifier) @call.name)) @call
+
+; ── Infix function calls (e.g., a to b, x until y) ──────────────────────
+(infix_expression
+ (simple_identifier) @call.name) @call
+
+; ── Heritage: extends / implements via delegation_specifier ──────────────
+; Interface implementation (bare user_type): class Foo : Bar
+(class_declaration
+ (type_identifier) @heritage.class
+ (delegation_specifier
+ (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Class extension (constructor_invocation): class Foo : Bar()
+(class_declaration
+ (type_identifier) @heritage.class
+ (delegation_specifier
+ (constructor_invocation
+ (user_type (type_identifier) @heritage.extends)))) @heritage
+`;
+
+// Swift queries - works with tree-sitter-swift
+export const SWIFT_QUERIES = `
+; Classes
+(class_declaration "class" name: (type_identifier) @name) @definition.class
+
+; Structs
+(class_declaration "struct" name: (type_identifier) @name) @definition.struct
+
+; Enums
+(class_declaration "enum" name: (type_identifier) @name) @definition.enum
+
+; Extensions (mapped to class — no dedicated label in schema)
+(class_declaration "extension" name: (user_type (type_identifier) @name)) @definition.class
+
+; Actors
+(class_declaration "actor" name: (type_identifier) @name) @definition.class
+
+; Protocols (mapped to interface)
+(protocol_declaration name: (type_identifier) @name) @definition.interface
+
+; Type aliases
+(typealias_declaration name: (type_identifier) @name) @definition.type
+
+; Functions (top-level and methods)
+(function_declaration name: (simple_identifier) @name) @definition.function
+
+; Protocol method declarations
+(protocol_function_declaration name: (simple_identifier) @name) @definition.method
+
+; Initializers — "init" is the canonical name; line offset tracked via definition node
+(init_declaration "init" @name) @definition.constructor
+
+; Properties (stored and computed)
+(property_declaration (pattern (simple_identifier) @name)) @definition.property
+
+; Imports
+(import_declaration (identifier (simple_identifier) @import.source)) @import
+
+; Calls - direct function calls
+(call_expression (simple_identifier) @call.name) @call
+
+; Calls - member/navigation calls (obj.method())
+(call_expression (navigation_expression (navigation_suffix (simple_identifier) @call.name))) @call
+
+; Heritage - class/struct/enum inheritance and protocol conformance
+(class_declaration name: (type_identifier) @heritage.class
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Heritage - protocol inheritance
+(protocol_declaration name: (type_identifier) @heritage.class
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+
+; Heritage - extension protocol conformance (e.g. extension Foo: SomeProtocol)
+; Extensions wrap the name in user_type unlike class/struct/enum declarations
+(class_declaration "extension" name: (user_type (type_identifier) @heritage.class)
+ (inheritance_specifier inherits_from: (user_type (type_identifier) @heritage.extends))) @heritage
+`;
+
+export const LANGUAGE_QUERIES: Record<SupportedLanguages, string> = {
+ [SupportedLanguages.TypeScript]: TYPESCRIPT_QUERIES,
+ [SupportedLanguages.JavaScript]: JAVASCRIPT_QUERIES,
+ [SupportedLanguages.Python]: PYTHON_QUERIES,
+ [SupportedLanguages.Java]: JAVA_QUERIES,
+ [SupportedLanguages.C]: C_QUERIES,
+ [SupportedLanguages.Go]: GO_QUERIES,
+ [SupportedLanguages.CPlusPlus]: CPP_QUERIES,
+ [SupportedLanguages.CSharp]: CSHARP_QUERIES,
+ [SupportedLanguages.Ruby]: RUBY_QUERIES,
+ [SupportedLanguages.Rust]: RUST_QUERIES,
+ [SupportedLanguages.PHP]: PHP_QUERIES,
+ [SupportedLanguages.Kotlin]: KOTLIN_QUERIES,
+ [SupportedLanguages.Swift]: SWIFT_QUERIES,
+};
+
diff --git a/core-ingestion/src/types.ts b/core-ingestion/src/types.ts
new file mode 100644
index 00000000..01bacd7b
--- /dev/null
+++ b/core-ingestion/src/types.ts
@@ -0,0 +1,22 @@
+export interface PatchSource {
+ uri: string;
+ sourceHash?: string;
+ extractor: string;
+ sourceType: string;
+}
+
+export interface PatchOp {
+ type: string;
+ [key: string]: unknown;
+}
+
+export interface GraphPatchPayload {
+ patchId: string;
+ actor: string;
+ timestamp: string;
+ source: PatchSource;
+ baseRev: number;
+ ops: PatchOp[];
+ replaces: string[];
+ intent?: string;
+}
diff --git a/core-ingestion/tsconfig.json b/core-ingestion/tsconfig.json
new file mode 100644
index 00000000..77af2577
--- /dev/null
+++ b/core-ingestion/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "outDir": "dist",
+ "rootDir": "src",
+ "strict": true,
+ "esModuleInterop": true,
+ "declaration": true,
+ "skipLibCheck": true,
+ "types": ["node"]
+ },
+ "include": ["src"]
+}
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 1912a83c..5d4a4171 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -8,6 +8,7 @@ import type { GraphPatchPayload } from '../../client/types.js';
import { getEndpoint, resolveWorkspaceRoot } from '../config.js';
import { resolveGitHubToken } from '../github/auth.js';
import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';
+import { loadIngestionModules } from './ingestion-loader.js';
import {
deterministicId,
transformIssue,
@@ -16,10 +17,6 @@ import {
transformPRComment,
transformCommit,
} from '../github/transform.js';
-import { parseFile } from '../../parser/index.js';
-import { buildPatch } from '../../parser/patch-builder.js';
-import { languageFromPath } from '../../parser/languages.js';
-
// ---------------------------------------------------------------------------
// File discovery
// ---------------------------------------------------------------------------
@@ -31,7 +28,11 @@ const IGNORE_DIRS = new Set([
const MAX_FILE_BYTES = 1024 * 1024; // 1 MB
-function* walkFiles(dir: string, recursive: boolean): Generator<string> {
+function* walkFiles(
+ dir: string,
+ recursive: boolean,
+ supportsFile: (fileName: string) => boolean
+): Generator<string> {
let entries: fs.Dirent[];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
catch { return; }
@@ -40,9 +41,9 @@ function* walkFiles(dir: string, recursive: boolean): Generator<string> {
if (IGNORE_DIRS.has(entry.name)) continue;
const full = nodePath.join(dir, entry.name);
if (entry.isDirectory()) {
- if (recursive) yield* walkFiles(full, true);
+ if (recursive) yield* walkFiles(full, true, supportsFile);
} else if (entry.isFile()) {
- if (languageFromPath(entry.name) !== null) yield full;
+ if (supportsFile(entry.name)) yield full;
}
}
}
@@ -93,6 +94,7 @@ async function ingestFiles(
path: string,
opts: { recursive?: boolean; force?: boolean; format: string; root?: string }
): Promise<void> {
+ const [{ parseFile, resolveCallEdges, isGrammarSupported }, { buildPatchWithResolution }] = await loadIngestionModules();
const resolvedPath = nodePath.isAbsolute(path)
? path
: nodePath.resolve(resolveWorkspaceRoot(opts.root), path);
@@ -113,19 +115,24 @@ async function ingestFiles(
let parseErrors = 0;
let tooLarge = 0;
let latestRev = 0;
+ let entitiesParsed = 0;
try {
// Collect files
const stat = fs.statSync(resolvedPath);
const filePaths: string[] = stat.isFile()
? [resolvedPath]
- : Array.from(walkFiles(resolvedPath, opts.recursive ?? false));
+ : Array.from(walkFiles(resolvedPath, opts.recursive ?? false, isGrammarSupported));
filesDiscovered = filePaths.length;
// Load existing source hashes for change detection (unless --force)
const knownHashes = opts.force ? new Map<string, string>() : await loadExistingHashes(client, filePaths);
+ // Phase 1: parse all files
+ type ParsedFile = { filePath: string; parsed: any; hash: string; previousHash: string | undefined };
+ const parsedFiles: ParsedFile[] = [];
+
for (const filePath of filePaths) {
try {
const fileSize = fs.statSync(filePath).size;
@@ -144,12 +151,25 @@ async function ingestFiles(
const parsed = parseFile(filePath, source);
if (!parsed) {
- // Unsupported file type — skip silently
filesSkipped++;
continue;
}
- const patch = buildPatch(parsed, hash);
+ entitiesParsed += parsed.entities.length;
+ const previousHash = knownHashes.get(filePath);
+ parsedFiles.push({ filePath, parsed, hash, previousHash: previousHash !== hash ? previousHash : undefined });
+ } catch {
+ parseErrors++;
+ }
+ }
+
+ // Phase 2: cross-file CALLS resolution over the full batch
+ const resolvedEdges = resolveCallEdges(parsedFiles.map(f => f.parsed));
+
+ // Phase 3: build and commit patches
+ for (const { parsed, hash, previousHash } of parsedFiles) {
+ try {
+ const patch = buildPatchWithResolution(parsed, hash, resolvedEdges, previousHash);
const result = await client.commitPatch(patch);
if (result.rev > latestRev) latestRev = result.rev;
patchesApplied++;
@@ -171,7 +191,7 @@ async function ingestFiles(
filesProcessed: filesDiscovered,
patchesApplied,
filesSkipped,
- entitiesCreated: 0,
+ entitiesParsed,
latestRev,
skipReasons: { unchanged: filesSkipped, emptyFile: 0, parseError: parseErrors, tooLarge },
elapsedSeconds: parseFloat(elapsed),
diff --git a/ix-cli/src/cli/commands/ingestion-loader.ts b/ix-cli/src/cli/commands/ingestion-loader.ts
new file mode 100644
index 00000000..14088c5a
--- /dev/null
+++ b/ix-cli/src/cli/commands/ingestion-loader.ts
@@ -0,0 +1,50 @@
+import { dirname, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+type IngestionModule = {
+ parseFile: (filePath: string, source: string) => any;
+ resolveCallEdges: (results: any[]) => any[];
+ isGrammarSupported: (filePath: string) => boolean;
+};
+
+type PatchBuilderModule = {
+ buildPatch: (parsed: any, hash: string, previousSourceHash?: string) => any;
+ buildPatchWithResolution: (parsed: any, hash: string, resolvedEdges: any[], previousSourceHash?: string) => any;
+};
+
+type LanguagesModule = {
+ languageFromPath: (filePath: string) => string | null;
+};
+
+const importModule = new Function(
+ "specifier",
+ "return import(specifier);"
+) as (specifier: string) => Promise<any>;
+
+const currentDir = dirname(fileURLToPath(import.meta.url));
+
+function resolveIngestionModule(relativePath: string): string {
+ return pathToFileURL(resolve(currentDir, relativePath)).href;
+}
+
+export async function loadIngestionModules(): Promise<[
+ IngestionModule,
+ PatchBuilderModule,
+ LanguagesModule,
+]> {
+ return Promise.all([
+ importModule(resolveIngestionModule("../../../../core-ingestion/dist/index.js")),
+ importModule(resolveIngestionModule("../../../../core-ingestion/dist/patch-builder.js")),
+ importModule(resolveIngestionModule("../../../../core-ingestion/dist/languages.js")),
+ ]);
+}
+
+export async function loadWatchIngestionModules(): Promise<[
+ IngestionModule,
+ PatchBuilderModule,
+]> {
+ return Promise.all([
+ importModule(resolveIngestionModule("../../../../core-ingestion/dist/index.js")),
+ importModule(resolveIngestionModule("../../../../core-ingestion/dist/patch-builder.js")),
+ ]);
+}
diff --git a/ix-cli/test/parser.stress.mjs b/ix-cli/test/parser.stress.mjs
new file mode 100644
index 00000000..451970e4
--- /dev/null
+++ b/ix-cli/test/parser.stress.mjs
@@ -0,0 +1,1465 @@
+/**
+ * parser.stress.mjs — Comprehensive stress test for core-ingestion parser.
+ *
+ * Run from ix-cli/ directory:
+ * node test/parser.stress.mjs
+ *
+ * Tests correctness, robustness, idempotency, silent-skip behaviour,
+ * and graph plausibility across all supported languages.
+ *
+ * Exit code 0 = all pass, 1 = at least one failure.
+ */
+
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+// ---------------------------------------------------------------------------
+// Load compiled modules
+// ---------------------------------------------------------------------------
+
+const distBase = pathToFileURL(resolve(process.cwd(), '../core-ingestion/dist')).href;
+
+const { parseFile, resolveCallEdges } = await import(`${distBase}/index.js`);
+const { buildPatch, buildPatchWithResolution } = await import(`${distBase}/patch-builder.js`);
+const { languageFromPath } = await import(`${distBase}/languages.js`);
+
+// ---------------------------------------------------------------------------
+// Test harness
+// ---------------------------------------------------------------------------
+
+let passed = 0;
+let failed = 0;
+const failures = [];
+
+function assert(condition, name, detail = '') {
+ if (condition) {
+ passed++;
+ console.log(` ✓ ${name}`);
+ } else {
+ failed++;
+ failures.push({ name, detail });
+ console.log(` ✗ ${name}${detail ? ': ' + detail : ''}`);
+ }
+}
+
+function section(title) {
+ console.log(`\n── ${title} ──`);
+}
+
+// ---------------------------------------------------------------------------
+// § 1 Language detection completeness
+// ---------------------------------------------------------------------------
+section('1. Language detection');
+
+const extExpectations = [
+ ['.ts', 'typescript'], ['.tsx', 'typescript'],
+ ['.js', 'javascript'], ['.jsx', 'javascript'], ['.mjs', 'javascript'], ['.cjs', 'javascript'],
+ ['.py', 'python'],
+ ['.java', 'java'],
+ ['.c', 'c'], ['.h', 'c'],
+ ['.cpp', 'cpp'], ['.cc', 'cpp'], ['.cxx', 'cpp'], ['.hpp', 'cpp'],
+ ['.cs', 'csharp'],
+ ['.go', 'go'],
+ ['.rb', 'ruby'],
+ ['.rs', 'rust'],
+ ['.php', 'php'],
+ ['.kt', 'kotlin'], ['.kts', 'kotlin'],
+ ['.swift', 'swift'],
+];
+
+for (const [ext, expected] of extExpectations) {
+ const result = languageFromPath(`file${ext}`);
+ assert(result === expected, `languageFromPath(${ext}) === ${expected}`, `got ${result}`);
+}
+
+assert(languageFromPath('file.txt') === null, 'languageFromPath(.txt) === null');
+assert(languageFromPath('Makefile') === null, 'languageFromPath(no-ext) === null');
+
+// ---------------------------------------------------------------------------
+// § 2 Core entity + relationship extraction (TypeScript)
+// ---------------------------------------------------------------------------
+section('2. TypeScript — entity and relationship extraction');
+
+const TS_FIXTURE = `
+import { Foo } from './foo';
+import type { Bar } from './bar';
+
+export class Animal {
+ name: string;
+ constructor(name: string) { this.name = name; }
+ speak(): string { return 'sound'; }
+}
+
+export class Dog extends Animal {
+ fetch(): void { this.speak(); }
+}
+
+export function createDog(name: string): Dog {
+ return new Dog(name);
+}
+
+export const greet = (x: string) => x.toUpperCase();
+`;
+
+const tsResult = parseFile('animal.ts', TS_FIXTURE);
+assert(tsResult !== null, 'TypeScript fixture parses without error');
+if (tsResult) {
+ const names = tsResult.entities.map(e => e.name);
+ assert(names.includes('animal.ts'), 'file entity emitted');
+ assert(names.includes('Animal'), 'class Animal detected');
+ assert(names.includes('Dog'), 'class Dog detected');
+ assert(names.includes('speak'), 'method speak detected');
+ assert(names.includes('fetch'), 'method fetch detected');
+ assert(names.includes('createDog'), 'function createDog detected');
+ assert(names.includes('greet'), 'arrow-function greet detected');
+
+ const preds = tsResult.relationships.map(r => r.predicate);
+ assert(preds.includes('CONTAINS'), 'CONTAINS relationships emitted');
+ assert(preds.includes('EXTENDS'), 'EXTENDS relationship (Dog→Animal) emitted');
+ assert(preds.includes('IMPORTS'), 'IMPORTS relationship emitted');
+
+ const extendsRel = tsResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(extendsRel?.srcName === 'Dog' && extendsRel?.dstName === 'Animal',
+ 'EXTENDS is Dog→Animal', JSON.stringify(extendsRel));
+
+ // File should CONTAIN Animal; Animal should CONTAIN speak
+ const fileContainsAnimal = tsResult.relationships.some(
+ r => r.srcName === 'animal.ts' && r.dstName === 'Animal' && r.predicate === 'CONTAINS'
+ );
+ assert(fileContainsAnimal, 'animal.ts CONTAINS Animal');
+
+ const classContainsMethod = tsResult.relationships.some(
+ r => r.srcName === 'Animal' && r.dstName === 'speak' && r.predicate === 'CONTAINS'
+ );
+ assert(classContainsMethod, 'Animal CONTAINS speak');
+
+ const importFoo = tsResult.relationships.some(
+ r => r.srcName === 'animal.ts' && r.dstName === 'foo' && r.predicate === 'IMPORTS'
+ );
+ assert(importFoo, 'animal.ts IMPORTS foo');
+}
+
+// ---------------------------------------------------------------------------
+// § 3 Python extraction
+// ---------------------------------------------------------------------------
+section('3. Python — entity and relationship extraction');
+
+const PY_FIXTURE = `
+import os
+import sys
+from collections import defaultdict
+
+class Stack:
+ def __init__(self):
+ self.items = []
+
+ def push(self, item):
+ self.items.append(item)
+
+ def pop(self):
+ return self.items.pop()
+
+class SpecialStack(Stack):
+ def peek(self):
+ return self.items[-1]
+
+def helper(x):
+ return x * 2
+`;
+
+const pyResult = parseFile('stack.py', PY_FIXTURE);
+assert(pyResult !== null, 'Python fixture parses');
+if (pyResult) {
+ const names = pyResult.entities.map(e => e.name);
+ assert(names.includes('Stack'), 'class Stack detected');
+ assert(names.includes('SpecialStack'), 'class SpecialStack detected');
+ assert(names.includes('push'), 'method push detected');
+ assert(names.includes('helper'), 'function helper detected');
+
+ const ext = pyResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(ext?.srcName === 'SpecialStack' && ext?.dstName === 'Stack',
+ 'EXTENDS SpecialStack→Stack', JSON.stringify(ext));
+
+ const hasImports = pyResult.relationships.some(r => r.predicate === 'IMPORTS');
+ assert(hasImports, 'IMPORTS edges present for Python');
+}
+
+// ---------------------------------------------------------------------------
+// § 4 JavaScript extraction
+// ---------------------------------------------------------------------------
+section('4. JavaScript — extraction');
+
+const JS_FIXTURE = `
+const express = require('express');
+
+class Router {
+ get(path, handler) { handler(); }
+}
+
+class ApiRouter extends Router {
+ setup() {
+ this.get('/health', () => {});
+ }
+}
+
+function startServer(port) {
+ const app = express();
+ return app;
+}
+`;
+
+const jsResult = parseFile('server.js', JS_FIXTURE);
+assert(jsResult !== null, 'JavaScript fixture parses');
+if (jsResult) {
+ const names = jsResult.entities.map(e => e.name);
+ assert(names.includes('Router'), 'class Router detected');
+ assert(names.includes('ApiRouter'), 'class ApiRouter detected');
+ assert(names.includes('startServer'), 'function startServer detected');
+ const ext = jsResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(ext?.srcName === 'ApiRouter', 'EXTENDS ApiRouter→Router', JSON.stringify(ext));
+}
+
+// ---------------------------------------------------------------------------
+// § 5 Go extraction
+// ---------------------------------------------------------------------------
+section('5. Go — extraction');
+
+const GO_FIXTURE = `
+package main
+
+import (
+ "fmt"
+ "os"
+)
+
+type Server struct {
+ port int
+}
+
+type Logger interface {
+ Log(msg string)
+}
+
+func NewServer(port int) *Server {
+ return &Server{port: port}
+}
+
+func (s *Server) Start() {
+ fmt.Println("starting")
+}
+`;
+
+const goResult = parseFile('server.go', GO_FIXTURE);
+assert(goResult !== null, 'Go fixture parses');
+if (goResult) {
+ const names = goResult.entities.map(e => e.name);
+ assert(names.includes('Server'), 'struct Server detected');
+ assert(names.includes('Logger'), 'interface Logger detected');
+ assert(names.includes('NewServer'), 'function NewServer detected');
+ assert(names.includes('Start'), 'method Start detected');
+ assert(goResult.relationships.some(r => r.predicate === 'IMPORTS'), 'IMPORTS edges in Go');
+}
+
+// ---------------------------------------------------------------------------
+// § 6 Rust extraction
+// ---------------------------------------------------------------------------
+section('6. Rust — extraction');
+
+const RUST_FIXTURE = `
+use std::collections::HashMap;
+
+pub struct Config {
+ pub name: String,
+}
+
+pub trait Runnable {
+ fn run(&self);
+}
+
+pub struct App {
+ config: Config,
+}
+
+impl Runnable for App {
+ fn run(&self) {
+ println!("running");
+ }
+}
+
+pub fn create_app(name: &str) -> App {
+ App { config: Config { name: name.to_string() } }
+}
+`;
+
+const rustResult = parseFile('app.rs', RUST_FIXTURE);
+assert(rustResult !== null, 'Rust fixture parses');
+if (rustResult) {
+ const names = rustResult.entities.map(e => e.name);
+ assert(names.includes('Config'), 'struct Config detected');
+ assert(names.includes('Runnable'), 'trait Runnable detected');
+ assert(names.includes('App'), 'struct App detected');
+ assert(names.includes('create_app'), 'fn create_app detected');
+
+ const traitImpl = rustResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(traitImpl !== undefined, 'EXTENDS edge for impl Runnable for App exists');
+}
+
+// ---------------------------------------------------------------------------
+// § 7 Java extraction
+// ---------------------------------------------------------------------------
+section('7. Java — extraction');
+
+const JAVA_FIXTURE = `
+import java.util.List;
+import java.util.ArrayList;
+
+public class UserService {
+ private List<String> users = new ArrayList<>();
+
+ public void addUser(String name) {
+ users.add(name);
+ }
+
+ public List<String> getUsers() {
+ return users;
+ }
+}
+
+public class AdminService extends UserService {
+ public void deleteUser(String name) {
+ getUsers().remove(name);
+ }
+}
+`;
+
+const javaResult = parseFile('UserService.java', JAVA_FIXTURE);
+assert(javaResult !== null, 'Java fixture parses');
+if (javaResult) {
+ const names = javaResult.entities.map(e => e.name);
+ assert(names.includes('UserService'), 'class UserService detected');
+ assert(names.includes('AdminService'), 'class AdminService detected');
+ assert(names.includes('addUser'), 'method addUser detected');
+ const ext = javaResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(ext?.srcName === 'AdminService', 'EXTENDS AdminService→UserService');
+}
+
+// ---------------------------------------------------------------------------
+// § 8 C extraction
+// ---------------------------------------------------------------------------
+section('8. C — extraction');
+
+const C_FIXTURE = `
+#include <stdio.h>
+#include <stdlib.h>
+
+typedef struct {
+ int x;
+ int y;
+} Point;
+
+Point* create_point(int x, int y) {
+ Point* p = malloc(sizeof(Point));
+ p->x = x;
+ p->y = y;
+ return p;
+}
+
+void print_point(Point* p) {
+ printf("(%d, %d)\\n", p->x, p->y);
+}
+`;
+
+const cResult = parseFile('point.c', C_FIXTURE);
+assert(cResult !== null, 'C fixture parses');
+if (cResult) {
+ const names = cResult.entities.map(e => e.name);
+ assert(names.includes('create_point'), 'function create_point detected');
+ assert(names.includes('print_point'), 'function print_point detected');
+ assert(cResult.relationships.some(r => r.predicate === 'IMPORTS'), 'IMPORTS edges for C includes');
+}
+
+// ---------------------------------------------------------------------------
+// § 9 C++ extraction
+// ---------------------------------------------------------------------------
+section('9. C++ — extraction');
+
+const CPP_FIXTURE = `
+#include <string>
+#include <vector>
+
+class Shape {
+public:
+ virtual double area() const = 0;
+ virtual ~Shape() {}
+};
+
+class Circle : public Shape {
+private:
+ double radius_;
+public:
+ explicit Circle(double r) : radius_(r) {}
+ double area() const override { return 3.14 * radius_ * radius_; }
+};
+
+template<typename T>
+class Container {
+ std::vector<T> items_;
+public:
+ void add(T item) { items_.push_back(item); }
+};
+`;
+
+const cppResult = parseFile('shapes.cpp', CPP_FIXTURE);
+assert(cppResult !== null, 'C++ fixture parses');
+if (cppResult) {
+ const names = cppResult.entities.map(e => e.name);
+ assert(names.includes('Shape'), 'class Shape detected');
+ assert(names.includes('Circle'), 'class Circle detected');
+ assert(names.includes('Container'), 'template Container detected');
+ const ext = cppResult.relationships.find(r => r.predicate === 'EXTENDS');
+ assert(ext?.srcName === 'Circle' && ext?.dstName === 'Shape',
+ 'EXTENDS Circle→Shape', JSON.stringify(ext));
+}
+
+// ---------------------------------------------------------------------------
+// § 10 C# extraction
+// ---------------------------------------------------------------------------
+section('10. C# — extraction');
+
+const CS_FIXTURE = `
+using System;
+using System.Collections.Generic;
+
+namespace MyApp {
+ public class Repository<T> {
+ private List<T> items = new List<T>();
+
+ public void Add(T item) {
+ items.Add(item);
+ }
+
+ public List<T> GetAll() {
+ return items;
+ }
+ }
+
+ public class UserRepository : Repository<string> {
+ public string Find(string name) {
+ return GetAll().Find(x => x == name);
+ }
+ }
+}
+`;
+
+const csResult = parseFile('Repository.cs', CS_FIXTURE);
+assert(csResult !== null, 'C# fixture parses');
+if (csResult) {
+ const names = csResult.entities.map(e => e.name);
+ assert(names.includes('Repository'), 'class Repository detected');
+ assert(names.includes('UserRepository'), 'class UserRepository detected');
+ assert(names.includes('Add'), 'method Add detected');
+ assert(csResult.relationships.some(r => r.predicate === 'IMPORTS'), 'using directives as IMPORTS');
+}
+
+// ---------------------------------------------------------------------------
+// § 11 PHP extraction
+// ---------------------------------------------------------------------------
+section('11. PHP — extraction');
+
+const PHP_FIXTURE = `<?php
+namespace App\\Models;
+
+use App\\Contracts\\Storable;
+
+abstract class Model implements Storable {
+ protected $table;
+
+ public function find(int $id): static {
+ return new static();
+ }
+}
+
+class User extends Model {
+ protected $fillable = ['name', 'email'];
+
+ public function greet(): string {
+ return 'hello';
+ }
+}
+`;
+
+const phpResult = parseFile('User.php', PHP_FIXTURE);
+assert(phpResult !== null, 'PHP fixture parses');
+if (phpResult) {
+ const names = phpResult.entities.map(e => e.name);
+ assert(names.includes('Model'), 'class Model detected');
+ assert(names.includes('User'), 'class User detected');
+ assert(names.includes('greet'), 'method greet detected');
+ const userExtendsModel = phpResult.relationships.find(
+ r => r.predicate === 'EXTENDS' && r.srcName === 'User' && r.dstName === 'Model'
+ );
+ assert(userExtendsModel !== undefined, 'EXTENDS User→Model exists');
+ const modelImplementsStoable = phpResult.relationships.find(
+ r => r.predicate === 'EXTENDS' && r.srcName === 'Model' && r.dstName === 'Storable'
+ );
+ assert(modelImplementsStoable !== undefined, 'EXTENDS Model→Storable (implements) exists');
+}
+
+// ---------------------------------------------------------------------------
+// § 12 Ruby extraction
+// ---------------------------------------------------------------------------
+section('12. Ruby — extraction');
+
+const RUBY_FIXTURE = `
+require 'json'
+require_relative './base'
+
+module Auth
+ class Session
+ include Serializable
+
+ def initialize(token)
+ @token = token
+ end
+
+ def valid?
+ end
+ end
+end
+`;
+
+const rubyResult = parseFile('session.rb', RUBY_FIXTURE);
+assert(rubyResult !== null, 'Ruby fixture parses');
+if (rubyResult) {
+ const names = rubyResult.entities.map(e => e.name);
+ assert(names.includes('Auth'), 'module Auth detected');
+ assert(names.includes('Session'), 'class Session detected');
+ assert(names.includes('valid?'), 'method valid? detected');
+ assert(rubyResult.relationships.some(r => r.predicate === 'IMPORTS'), 'require → IMPORTS');
+}
+
+// ---------------------------------------------------------------------------
+// § 13 TSX extraction
+// ---------------------------------------------------------------------------
+section('13. TSX — React component extraction');
+
+const TSX_FIXTURE = `
+import React, { useState } from 'react';
+
+interface Props {
+ title: string;
+}
+
+const Header: React.FC<Props> = ({ title }) => {
+ const [count, setCount] = useState(0);
+ return <h1>{title}</h1>;
+};
+
+export default Header;
+`;
+
+const tsxResult = parseFile('Header.tsx', TSX_FIXTURE);
+assert(tsxResult !== null, 'TSX fixture parses');
+if (tsxResult) {
+ const names = tsxResult.entities.map(e => e.name);
+ assert(names.includes('Header'), 'Header component detected');
+ assert(names.includes('Props'), 'Props interface detected');
+}
+
+// ---------------------------------------------------------------------------
+// § 14 CRITICAL: Duplicate entity names within the same file → nodeId collision
+// ---------------------------------------------------------------------------
+section('14. CRITICAL: Duplicate entity names → nodeId collision in patch');
+
+const DUPLICATE_NAMES_FIXTURE = `
+class ClassA {
+ update() { return 1; }
+ process() { return 2; }
+}
+
+class ClassB {
+ update() { return 3; } // same name as ClassA.update
+ process() { return 4; } // same name as ClassA.process
+}
+`;
+
+const dupResult = parseFile('dup.ts', DUPLICATE_NAMES_FIXTURE);
+assert(dupResult !== null, 'Duplicate names fixture parses');
+if (dupResult) {
+ const methodEntities = dupResult.entities.filter(e => e.name === 'update');
+ assert(methodEntities.length === 2,
+ 'Two "update" entities extracted (one per class)', `got ${methodEntities.length}`);
+
+ const patch = buildPatch(dupResult, 'abc123');
+ const upsertNodes = patch.ops.filter(op => op.type === 'UpsertNode');
+ const updateNodes = upsertNodes.filter(op => op.name === 'update');
+ assert(updateNodes.length === 2,
+ 'Two UpsertNode ops for "update"', `got ${updateNodes.length}`);
+
+ // Check for ID collision — both should have the SAME id (the bug)
+ const ids = updateNodes.map(op => op.id);
+ const collision = ids[0] === ids[1];
+ // This is the BUG: same nodeId means the second upsert silently overwrites the first
+ assert(!collision,
+ 'No nodeId collision between ClassA.update and ClassB.update (EXPECT FAIL → BUG)',
+ `Both get id=${ids[0]} — the second UpsertNode silently overwrites the first`);
+}
+
+// ---------------------------------------------------------------------------
+// § 15 Kotlin/Swift: discovered but silently skipped (no grammar installed)
+// ---------------------------------------------------------------------------
+section('15. Kotlin/Swift: parse returns null (no grammar installed)');
+
+const KOTLIN_FIXTURE = `
+data class User(val name: String, val age: Int)
+
+fun greet(user: User): String = "Hello, \${user.name}"
+`;
+
+const kotlinResult = parseFile('user.kt', KOTLIN_FIXTURE);
+// We EXPECT null — Kotlin grammar is not installed. This confirms the silent skip.
+assert(kotlinResult === null,
+ 'Kotlin parses to null (grammar not installed — files are discovered but silently skipped)');
+
+const SWIFT_FIXTURE = `
+struct User {
+ var name: String
+ var age: Int
+
+ init(name: String, age: Int) {
+ self.name = name
+ self.age = age
+ }
+}
+
+func greet(user: User) -> String {
+ return "Hello, \\(user.name)"
+}
+`;
+
+const swiftResult = parseFile('user.swift', SWIFT_FIXTURE);
+assert(swiftResult === null,
+ 'Swift parses to null (grammar not installed — files are discovered but silently skipped)');
+
+// Consequence: walk during ix ingest discovers .kt/.swift files (languageFromPath → non-null)
+// but parseFile returns null, so they are counted as "skipped" without a clear reason in output.
+assert(languageFromPath('user.kt') !== null,
+ 'Kotlin files ARE discovered by walkFiles (languageFromPath non-null) — counts inflate');
+assert(languageFromPath('user.swift') !== null,
+ 'Swift files ARE discovered by walkFiles (languageFromPath non-null) — counts inflate');
+
+// ---------------------------------------------------------------------------
+// § 16 Swift init_declaration: no @name capture → silent miss
+// ---------------------------------------------------------------------------
+section('16. Swift init_declaration missing @name capture');
+
+// Swift grammar IS available? Actually it's not installed. But we can verify the query issue
+// by checking that init_declaration entries would have no name extracted.
+// The query: (init_declaration) @definition.constructor
+// has NO @name capture. In parseFile, the first pass requires BOTH defCapture AND nameCapture.
+// So all Swift initializers would be silently dropped even if the grammar were installed.
+// We document this as a known issue.
+console.log(' ℹ Swift init_declaration query has no @name capture → initializers would be');
+console.log(' silently skipped even if swift grammar were installed. See queries.ts:661');
+
+// ---------------------------------------------------------------------------
+// § 17 patchId non-determinism and replaces always empty
+// ---------------------------------------------------------------------------
+section('17. patch-builder: patchId non-determinism + replaces always empty');
+
+const SIMPLE_FIXTURE = `export function hello() { return 42; }`;
+const r1 = parseFile('hello.ts', SIMPLE_FIXTURE);
+const r2 = parseFile('hello.ts', SIMPLE_FIXTURE);
+
+if (r1 && r2) {
+ const patch1 = buildPatch(r1, 'deadbeef');
+ const patch2 = buildPatch(r2, 'deadbeef');
+
+ // patchId uses Date.now() so it is wall-clock-dependent.
+ // Two calls within the same millisecond produce the same id (accidentally stable);
+ // calls across milliseconds produce different ids (unstable across separate ingest runs).
+ // We document this as a known design limitation rather than a hard assertion.
+ console.log(` ℹ patchId1=${patch1.patchId}`);
+ console.log(` ℹ patchId2=${patch2.patchId}`);
+ console.log(' ℹ patchId uses Date.now() — non-deterministic across separate ingest runs');
+
+ assert(patch1.replaces.length === 0 && patch2.replaces.length === 0,
+ 'replaces is always [] (previousPatchId never passed from ingest.ts)');
+
+ // Verify that node IDs ARE deterministic (the graph nodes are stable)
+ const node1 = patch1.ops.find(op => op.type === 'UpsertNode' && op.name === 'hello');
+ const node2 = patch2.ops.find(op => op.type === 'UpsertNode' && op.name === 'hello');
+ assert(node1?.id === node2?.id,
+ 'UpsertNode IDs are deterministic across runs (safe)', `${node1?.id}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 18 Idempotency: same entities/edges produced on second parse
+// ---------------------------------------------------------------------------
+section('18. Idempotency: re-parsing produces identical entities and edges');
+
+const IDEM_FIXTURE = `
+class Counter {
+ count: number = 0;
+ increment() { this.count++; }
+ decrement() { this.count--; }
+}
+`;
+
+const idem1 = parseFile('counter.ts', IDEM_FIXTURE);
+const idem2 = parseFile('counter.ts', IDEM_FIXTURE);
+
+if (idem1 && idem2) {
+ assert(idem1.entities.length === idem2.entities.length,
+ 'Entity count identical on re-parse');
+ assert(idem1.relationships.length === idem2.relationships.length,
+ 'Relationship count identical on re-parse');
+
+ const sortNames = arr => arr.map(e => e.name).sort().join(',');
+ assert(sortNames(idem1.entities) === sortNames(idem2.entities),
+ 'Entity names identical on re-parse');
+}
+
+// ---------------------------------------------------------------------------
+// § 19 Malformed / partial files: no crash
+// ---------------------------------------------------------------------------
+section('19. Robustness: malformed and partial files do not crash');
+
+const MALFORMED_CASES = [
+ ['empty.ts', ''],
+ ['only-ws.ts', ' \n\t\n '],
+ ['truncated.ts', 'class Foo { method(x: string) {'],
+ ['syntax-err.ts', 'function @invalid@@() { ??? }'],
+ ['unicode.ts', '// 你好世界\nconst x = "emoji: 🎉";'],
+ ['huge-string.ts', `const x = "${'a'.repeat(100_000)}";`],
+ ['null-bytes.ts', 'function f() {}\x00\x00\x00'],
+ ['only-comments.ts', '// just a comment\n/* and another */'],
+];
+
+for (const [name, src] of MALFORMED_CASES) {
+ let threw = false;
+ try {
+ parseFile(name, src);
+ } catch {
+ threw = true;
+ }
+ assert(!threw, `no exception on ${name}`);
+ // empty file and pure whitespace return null (no entities), which is fine
+}
+
+// ---------------------------------------------------------------------------
+// § 20 File size and empty file gating (the caller-side check in ingest.ts)
+// ---------------------------------------------------------------------------
+section('20. Parser return value for edge-case files');
+
+assert(parseFile('empty.ts', '') !== null || true,
+ 'empty .ts returns null gracefully (tree-sitter parses empty source)');
+// Actually tree-sitter can parse empty source — let's verify
+const emptyResult = parseFile('really-empty.ts', '');
+if (emptyResult !== null) {
+ // If it parses, it should have exactly the file entity
+ assert(emptyResult.entities.length === 1 && emptyResult.entities[0].kind === 'file',
+ 'Empty file produces only file entity', `got ${emptyResult.entities.length} entities`);
+} else {
+ console.log(' ℹ empty source returns null — consistent with error path');
+}
+
+// ---------------------------------------------------------------------------
+// § 21 Graph plausibility: node/edge counts make sense
+// ---------------------------------------------------------------------------
+section('21. Graph plausibility: counts are sane for moderate fixture');
+
+const PLAUSIBILITY_FIXTURE = `
+import { EventEmitter } from 'events';
+
+export class Queue extends EventEmitter {
+ private items: any[] = [];
+
+ enqueue(item: any): void {
+ this.items.push(item);
+ this.emit('enqueue', item);
+ }
+
+ dequeue(): any {
+ const item = this.items.shift();
+ this.emit('dequeue', item);
+ return item;
+ }
+
+ get size(): number { return this.items.length; }
+}
+
+export class PriorityQueue extends Queue {
+ enqueue(item: any): void {
+ this.items.sort();
+ super.enqueue(item);
+ }
+}
+
+export function createQueue(): Queue { return new Queue(); }
+`;
+
+const pqResult = parseFile('queue.ts', PLAUSIBILITY_FIXTURE);
+if (pqResult) {
+ const numEntities = pqResult.entities.length;
+ const numRels = pqResult.relationships.length;
+ const predicates = pqResult.relationships.reduce((acc, r) => {
+ acc[r.predicate] = (acc[r.predicate] ?? 0) + 1;
+ return acc;
+ }, {});
+
+ console.log(` entities: ${numEntities}, relationships: ${numRels}`);
+ console.log(` predicates: ${JSON.stringify(predicates)}`);
+
+ assert(numEntities >= 6, `at least 6 entities (file + 2 classes + 3+ methods), got ${numEntities}`);
+ assert(numRels >= 5, `at least 5 relationships, got ${numRels}`);
+ assert(predicates.CONTAINS >= 2, `CONTAINS edges >= 2, got ${predicates.CONTAINS}`);
+ assert(predicates.EXTENDS >= 1, `EXTENDS edge (PriorityQueue→Queue), got ${predicates.EXTENDS}`);
+ assert(predicates.IMPORTS >= 1, `IMPORTS edge, got ${predicates.IMPORTS}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 22 Cross-file CALLS are file-scoped (dangling-edge design limitation)
+// ---------------------------------------------------------------------------
+section('22. Cross-file CALLS edges are file-scoped (design limitation)');
+
+const CALLER_FIXTURE = `
+import { processPayment } from './payments';
+
+export function checkout(cart: any) {
+ processPayment(cart.total);
+}
+`;
+
+const callerResult = parseFile('checkout.ts', CALLER_FIXTURE);
+if (callerResult) {
+ const callsPayment = callerResult.relationships.find(
+ r => r.predicate === 'CALLS' && r.dstName === 'processPayment'
+ );
+ if (callsPayment) {
+ // The dst nodeId will be deterministicId('checkout.ts:processPayment') — NOT the real entity
+ // from payments.ts. This is a dangling edge.
+ const patch = buildPatch(callerResult, 'abc');
+ const callEdge = patch.ops.find(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS');
+ console.log(` ℹ CALLS edge: dst=${callEdge?.dst} (file-scoped, likely dangling)`);
+ console.log(` ℹ The destination is deterministicId("checkout.ts:processPayment"),`);
+ console.log(` NOT the real processPayment node from payments.ts`);
+ assert(true, 'Cross-file CALLS edge confirmed present (design limitation documented)');
+ } else {
+ assert(false, 'Expected CALLS processPayment edge to be generated');
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 23 CALLS deduplication within scope
+// ---------------------------------------------------------------------------
+section('23. CALLS deduplication: same callee in same scope produces one edge');
+
+const DEDUP_FIXTURE = `
+function processOrder(order: any) {
+ validate(order);
+ validate(order); // duplicate call — should produce only ONE edge
+ save(order);
+}
+`;
+
+const dedupResult = parseFile('order.ts', DEDUP_FIXTURE);
+if (dedupResult) {
+ const validateCalls = dedupResult.relationships.filter(
+ r => r.predicate === 'CALLS' && r.dstName === 'validate'
+ );
+ assert(validateCalls.length === 1,
+ 'Duplicate calls deduplicated to one CALLS edge', `got ${validateCalls.length}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 24 Java import over-capture check
+// ---------------------------------------------------------------------------
+section('24. Java import: checking for over-capture with child wildcard');
+
+const JAVA_IMPORT_FIXTURE = `
+import java.util.List;
+import java.util.Map;
+import java.util.*;
+
+public class Test {}
+`;
+
+const javaImportResult = parseFile('Test.java', JAVA_IMPORT_FIXTURE);
+if (javaImportResult) {
+ const imports = javaImportResult.relationships.filter(r => r.predicate === 'IMPORTS');
+ console.log(` Import edges: ${imports.length} (raw text: ${imports.map(r => r.dstName).join(', ')})`);
+ // The Java query uses (_) @import.source which may match multiple children
+ // including scoped_identifier children, potentially producing duplicates
+ assert(imports.length >= 3, `At least 3 import edges for 3 import stmts, got ${imports.length}`);
+ // Check for obvious over-capture: "java" being extracted as an import name (just the first token)
+ const trivialImports = imports.filter(r => r.dstName.length <= 4);
+ if (trivialImports.length > 0) {
+ console.log(` ⚠ Over-capture: got trivial import names: ${trivialImports.map(r => r.dstName).join(', ')}`);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 25 buildPatch ops completeness
+// ---------------------------------------------------------------------------
+section('25. buildPatch: ops contain UpsertNode, UpsertEdge, AssertClaim');
+
+const patchFixture = `
+class Service {
+ doWork(): void {}
+}
+`;
+const pfResult = parseFile('service.ts', patchFixture);
+if (pfResult) {
+ const patch = buildPatch(pfResult, 'hashval');
+ const opTypes = new Set(patch.ops.map(op => op.type));
+
+ assert(opTypes.has('UpsertNode'), 'Patch contains UpsertNode ops');
+ assert(opTypes.has('UpsertEdge'), 'Patch contains UpsertEdge ops');
+ assert(opTypes.has('AssertClaim'), 'Patch contains AssertClaim ops');
+
+ // Every UpsertNode should have required fields
+ const badNodes = patch.ops
+ .filter(op => op.type === 'UpsertNode')
+ .filter(op => !op.id || !op.kind || !op.name);
+ assert(badNodes.length === 0, `All UpsertNode ops have id/kind/name, bad: ${badNodes.length}`);
+
+ // Every UpsertEdge should have src/dst/predicate
+ const badEdges = patch.ops
+ .filter(op => op.type === 'UpsertEdge')
+ .filter(op => !op.id || !op.src || !op.dst || !op.predicate);
+ assert(badEdges.length === 0, `All UpsertEdge ops have id/src/dst/predicate, bad: ${badEdges.length}`);
+
+ // Source metadata should be present
+ assert(patch.source.uri === 'service.ts', 'patch.source.uri correct');
+ assert(patch.source.extractor === 'tree-sitter/1.0', 'patch.source.extractor correct');
+ assert(patch.source.sourceHash === 'hashval', 'patch.source.sourceHash correct');
+}
+
+// ---------------------------------------------------------------------------
+// § 26 entitiesCreated hardcoded 0 in JSON output (ingest.ts bug)
+// ---------------------------------------------------------------------------
+section('26. JSON output: entitiesCreated is hardcoded 0 (ingest.ts:176)');
+console.log(' ℹ ingest.ts line 176: entitiesCreated: 0 — this field is always 0 in JSON output.');
+console.log(' The parser does not return a count of backend-created entities (that requires');
+console.log(' a server round-trip). This is a misleading metric, not a crash bug.');
+
+// ---------------------------------------------------------------------------
+// § 27 Cross-file CALLS resolution
+// ---------------------------------------------------------------------------
+section('27. Cross-file CALLS resolution via resolveCallEdges()');
+
+const PAYMENTS_FIXTURE = `
+export function processPayment(amount: number): boolean {
+ return amount > 0;
+}
+
+export function refund(amount: number): void {}
+`;
+
+const CHECKOUT_FIXTURE = `
+import { processPayment } from './payments';
+
+export function checkout(cart: any) {
+ processPayment(cart.total);
+}
+`;
+
+const paymentsResult = parseFile('payments.ts', PAYMENTS_FIXTURE);
+const checkoutResult = parseFile('checkout.ts', CHECKOUT_FIXTURE);
+
+assert(paymentsResult !== null, '§27 payments.ts parses');
+assert(checkoutResult !== null, '§27 checkout.ts parses');
+
+if (paymentsResult && checkoutResult) {
+ const resolved = resolveCallEdges([paymentsResult, checkoutResult]);
+
+ const edge = resolved.find(e => e.calleeName === 'processPayment');
+
+ assert(edge !== undefined, '§27 resolveCallEdges finds processPayment edge');
+
+ if (edge) {
+ assert(
+ edge.calleeFilePath.includes('payments'),
+ '§27 calleeFilePath points to payments file',
+ `got ${edge.calleeFilePath}`
+ );
+ assert(
+ edge.calleeName === 'processPayment',
+ '§27 calleeName is processPayment',
+ `got ${edge.calleeName}`
+ );
+ assert(
+ edge.confidence >= 0.9,
+ `§27 confidence >= 0.9 (import-scoped, not global fallback), got ${edge.confidence}`
+ );
+
+ // Build patch with resolution and verify CALLS edge dst
+ const checkoutPatch = buildPatchWithResolution(checkoutResult, 'abc123', resolved);
+ const callsEdge = checkoutPatch.ops.find(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS' && op.dst !== undefined);
+
+ assert(callsEdge !== undefined, '§27 CALLS UpsertEdge present in patch');
+
+ if (callsEdge) {
+ // Build the expected dst: nodeId("payments.ts", "processPayment")
+ // nodeId uses deterministicId(`${filePath}:${name}`) which is SHA256-derived
+ // We verify by building the payments patch and finding the processPayment node id
+ const paymentsPatch = buildPatch(paymentsResult, 'xyz456');
+ const processPaymentNode = paymentsPatch.ops.find(
+ op => op.type === 'UpsertNode' && op.name === 'processPayment'
+ );
+
+ assert(processPaymentNode !== undefined, '§27 processPayment UpsertNode found in payments patch');
+
+ if (processPaymentNode) {
+ assert(
+ callsEdge.dst === processPaymentNode.id,
+ `§27 CALLS edge dst === nodeId("payments.ts","processPayment")`,
+ `dst=${callsEdge.dst} expected=${processPaymentNode.id}`
+ );
+
+ // Also verify it does NOT equal the file-scoped (dangling) id
+ const danglingPatch = buildPatch(checkoutResult, 'abc123');
+ const danglingEdge = danglingPatch.ops.find(
+ op => op.type === 'UpsertEdge' && op.predicate === 'CALLS'
+ );
+ if (danglingEdge) {
+ assert(
+ callsEdge.dst !== danglingEdge.dst,
+ '§27 resolved dst differs from dangling (file-scoped) dst'
+ );
+ }
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 28 Class-method qualified key resolution
+// ---------------------------------------------------------------------------
+section('28. Cross-file CALLS resolution: class method uses qualified key (ClassName.method)');
+
+const PAYMENT_SERVICE_FIXTURE = `
+export class PaymentService {
+ charge(amount: number): boolean { return amount > 0; }
+ refund(amount: number): void {}
+}
+`;
+
+const ORDER_FIXTURE = `
+import { PaymentService } from './payment-service';
+
+export function placeOrder(cart: any) {
+ const svc = new PaymentService();
+ svc.charge(cart.total);
+}
+`;
+
+const psResult = parseFile('payment-service.ts', PAYMENT_SERVICE_FIXTURE);
+const orderResult = parseFile('order.ts', ORDER_FIXTURE);
+
+assert(psResult !== null, '§28 payment-service.ts parses');
+assert(orderResult !== null, '§28 order.ts parses');
+
+if (psResult && orderResult) {
+ const resolvedCM = resolveCallEdges([psResult, orderResult]);
+ const chargeEdge = resolvedCM.find(e => e.calleeName === 'charge');
+
+ assert(chargeEdge !== undefined, '§28 resolveCallEdges finds charge edge');
+
+ if (chargeEdge) {
+ assert(
+ chargeEdge.calleeQualifiedKey === 'PaymentService.charge',
+ `§28 calleeQualifiedKey is PaymentService.charge`,
+ `got ${chargeEdge.calleeQualifiedKey}`
+ );
+ assert(chargeEdge.confidence >= 0.9, `§28 confidence >= 0.9, got ${chargeEdge.confidence}`);
+
+ // Verify dst in patch points to the qualified nodeId
+ const psPatch = buildPatch(psResult, 'ps-hash');
+ const chargeNode = psPatch.ops.find(op => op.type === 'UpsertNode' && op.name === 'charge');
+ assert(chargeNode !== undefined, '§28 charge UpsertNode found in payment-service patch');
+
+ if (chargeNode) {
+ const orderPatch = buildPatchWithResolution(orderResult, 'order-hash', resolvedCM);
+ const callsCharge = orderPatch.ops.find(
+ op => op.type === 'UpsertEdge' && op.predicate === 'CALLS' && op.dst === chargeNode.id
+ );
+ assert(
+ callsCharge !== undefined,
+ `§28 CALLS edge dst === nodeId("payment-service.ts", "PaymentService.charge")`
+ );
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 29 Directory import resolution (index.ts)
+// ---------------------------------------------------------------------------
+section('29. Cross-file CALLS resolution: directory import resolves to index.ts');
+
+const UTILS_INDEX_FIXTURE = `
+export function formatCurrency(amount: number): string {
+ return '$' + amount.toFixed(2);
+}
+`;
+
+const INVOICE_FIXTURE = `
+import { formatCurrency } from './utils';
+
+export function generateInvoice(total: number): string {
+ return formatCurrency(total);
+}
+`;
+
+// Simulate utils/index.ts by using a path where basename is 'index' and parent dir is 'utils'
+const utilsIndexResult = parseFile('utils/index.ts', UTILS_INDEX_FIXTURE);
+const invoiceResult = parseFile('invoice.ts', INVOICE_FIXTURE);
+
+assert(utilsIndexResult !== null, '§29 utils/index.ts parses');
+assert(invoiceResult !== null, '§29 invoice.ts parses');
+
+if (utilsIndexResult && invoiceResult) {
+ const resolvedDir = resolveCallEdges([utilsIndexResult, invoiceResult]);
+ const fmtEdge = resolvedDir.find(e => e.calleeName === 'formatCurrency');
+
+ assert(fmtEdge !== undefined, '§29 resolveCallEdges finds formatCurrency via directory import');
+
+ if (fmtEdge) {
+ assert(
+ fmtEdge.calleeFilePath.includes('utils'),
+ `§29 calleeFilePath resolves into utils directory`,
+ `got ${fmtEdge.calleeFilePath}`
+ );
+ assert(fmtEdge.confidence >= 0.9, `§29 confidence >= 0.9, got ${fmtEdge.confidence}`);
+
+ const utilsPatch = buildPatch(utilsIndexResult, 'utils-hash');
+ const fmtNode = utilsPatch.ops.find(op => op.type === 'UpsertNode' && op.name === 'formatCurrency');
+ assert(fmtNode !== undefined, '§29 formatCurrency UpsertNode found in utils/index patch');
+
+ if (fmtNode) {
+ const invPatch = buildPatchWithResolution(invoiceResult, 'inv-hash', resolvedDir);
+ const callsFmt = invPatch.ops.find(
+ op => op.type === 'UpsertEdge' && op.predicate === 'CALLS' && op.dst === fmtNode.id
+ );
+ assert(
+ callsFmt !== undefined,
+ `§29 CALLS edge dst === nodeId("utils/index.ts", "formatCurrency")`
+ );
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 30 Bare path-alias import resolution (@components, ~lib, #utils)
+// ---------------------------------------------------------------------------
+section('30. Import resolution: bare aliases strip leading non-word chars');
+
+const AUTH_MODULE_FIXTURE = `
+export function verifyToken(token: string): boolean {
+ return token.length > 0;
+}
+`;
+
+// Simulates: import { verifyToken } from '@auth'
+// parseFile stores modName = '@auth' (no slash to split on)
+// resolveCallEdges should strip '@' → 'auth' → match 'auth.ts'
+const BARE_ALIAS_CALLER_FIXTURE = `
+import { verifyToken } from '@auth';
+
+export function protect(req: any) {
+ verifyToken(req.headers.token);
+}
+`;
+
+const authResult = parseFile('auth.ts', AUTH_MODULE_FIXTURE);
+const protectResult = parseFile('middleware.ts', BARE_ALIAS_CALLER_FIXTURE);
+
+assert(authResult !== null, '§30 auth.ts parses');
+assert(protectResult !== null, '§30 middleware.ts parses');
+
+if (authResult && protectResult) {
+ const resolvedAlias = resolveCallEdges([authResult, protectResult]);
+ const vtEdge = resolvedAlias.find(e => e.calleeName === 'verifyToken');
+
+ assert(vtEdge !== undefined, '§30 resolveCallEdges finds verifyToken via @auth alias');
+ if (vtEdge) {
+ assert(vtEdge.calleeFilePath === 'auth.ts', `§30 calleeFilePath = auth.ts, got ${vtEdge.calleeFilePath}`);
+ assert(vtEdge.confidence >= 0.9, `§30 confidence >= 0.9, got ${vtEdge.confidence}`);
+ assert(vtEdge.calleeQualifiedKey === 'verifyToken', `§30 calleeQualifiedKey = verifyToken, got ${vtEdge.calleeQualifiedKey}`);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 31 Ambiguous class methods: edge suppressed rather than emitting bad nodeId
+// ---------------------------------------------------------------------------
+section('31. Ambiguous class method resolution: edge not emitted (prevents bad nodeId)');
+
+const AMBIGUOUS_SERVICE_FIXTURE = `
+export class ServiceA {
+ process(data: any): void {}
+}
+
+export class ServiceB {
+ process(data: any): void {}
+}
+`;
+
+const AMBIGUOUS_CALLER_FIXTURE = `
+import { ServiceA } from './ambiguous-service';
+
+export function run(data: any) {
+ const svc = new ServiceA();
+ svc.process(data);
+}
+`;
+
+const ambSvcResult = parseFile('ambiguous-service.ts', AMBIGUOUS_SERVICE_FIXTURE);
+const ambCallerResult = parseFile('runner.ts', AMBIGUOUS_CALLER_FIXTURE);
+
+assert(ambSvcResult !== null, '§31 ambiguous-service.ts parses');
+assert(ambCallerResult !== null, '§31 runner.ts parses');
+
+if (ambSvcResult && ambCallerResult) {
+ const resolvedAmb = resolveCallEdges([ambSvcResult, ambCallerResult]);
+ const processEdge = resolvedAmb.find(e => e.calleeName === 'process');
+
+ assert(processEdge === undefined,
+ '§31 ambiguous class method "process" produces no resolved edge (prevents dangling nodeId)');
+
+ // Verify that a non-ambiguous call in the same file still resolves
+ const newEdge = resolvedAmb.find(e => e.calleeName === 'ServiceA');
+ // ServiceA constructor call: only one entity named ServiceA → resolves
+ if (newEdge) {
+ assert(newEdge.calleeQualifiedKey === 'ServiceA',
+ '§31 unambiguous ServiceA constructor call resolves correctly');
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 32 require() calls filtered by BUILTINS
+// ---------------------------------------------------------------------------
+section('32. require() calls are filtered by BUILTINS');
+const r32 = parseFile('server.js', `
+ const express = require('express');
+ const fs = require('fs');
+ function start() { require('path'); }
+`);
+if (r32) {
+ const requireCalls = r32.relationships.filter(
+ r => r.predicate === 'CALLS' && r.dstName === 'require'
+ );
+ assert(requireCalls.length === 0,
+ '§32 require() calls not emitted as CALLS edges', `got ${requireCalls.length}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 33 Imported module name does not block cross-file CALLS resolution
+// ---------------------------------------------------------------------------
+section('33. Imported module name does not block cross-file CALLS resolution');
+const r33caller = parseFile('checkout.ts', `
+ import format from './format';
+ export function run(x) { format(x); }
+`);
+const r33callee = parseFile('format.ts', `
+ export function format(x) { return String(x); }
+`);
+if (r33caller && r33callee) {
+ const edges33 = resolveCallEdges([r33caller, r33callee]);
+ const edge33 = edges33.find(e => e.calleeName === 'format');
+ assert(edge33 !== undefined,
+ '§33 format() resolves to format.ts despite module entity of same name in caller');
+ if (edge33) {
+ assert(edge33.calleeFilePath === 'format.ts',
+ `§33 calleeFilePath = format.ts, got ${edge33.calleeFilePath}`);
+ assert(edge33.confidence >= 0.9, `§33 confidence >= 0.9, got ${edge33.confidence}`);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 34 Two classes with same method name produce two distinct CALLS edges
+// ---------------------------------------------------------------------------
+section('34. Two classes with same method name produce two distinct CALLS edges');
+const r34 = parseFile('multi.ts', `
+ class ClassA {
+ update() { helper(); }
+ }
+ class ClassB {
+ update() { helper(); }
+ }
+`);
+if (r34) {
+ const helperCalls = r34.relationships.filter(
+ r => r.predicate === 'CALLS' && r.dstName === 'helper'
+ );
+ assert(helperCalls.length === 2,
+ '§34 Both ClassA.update and ClassB.update emit a CALLS edge to helper',
+ `got ${helperCalls.length}`);
+
+ const srcNames = helperCalls.map(r => r.srcName).sort();
+ assert(srcNames.includes('ClassA.update'),
+ '§34 one CALLS edge has srcName ClassA.update', `srcNames: ${srcNames}`);
+ assert(srcNames.includes('ClassB.update'),
+ '§34 one CALLS edge has srcName ClassB.update', `srcNames: ${srcNames}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 35 Python relative imports strip leading dots from entity/IMPORTS names
+// ---------------------------------------------------------------------------
+section('35. Python relative imports strip leading dots from entity/IMPORTS names');
+const r35 = parseFile('auth.py', `
+from . import utils
+from .models import User
+from ..core import Config
+`);
+if (r35) {
+ const moduleEntities = r35.entities.filter(e => e.kind === 'module').map(e => e.name);
+ const dotEntities = moduleEntities.filter(n => n.startsWith('.'));
+ assert(dotEntities.length === 0,
+ '§35 no module entity names start with a dot', `got: ${dotEntities}`);
+
+ const importNames = r35.relationships
+ .filter(r => r.predicate === 'IMPORTS')
+ .map(r => r.dstName);
+ const dotImports = importNames.filter(n => n.startsWith('.'));
+ assert(dotImports.length === 0,
+ '§35 no IMPORTS dstName starts with a dot', `got: ${dotImports}`);
+
+ // 'from . import utils' should produce no entity at all (bare dot → empty after strip)
+ const bareImport = r35.relationships.find(
+ r => r.predicate === 'IMPORTS' && r.dstName === ''
+ );
+ assert(bareImport === undefined, '§35 bare "from . import X" does not create empty IMPORTS edge');
+}
+
+// ---------------------------------------------------------------------------
+// § 36 Swift init_declaration — 'init' name synthesised when no @name capture
+// ---------------------------------------------------------------------------
+section('36. Swift init_declaration produces entity with name "init"');
+const r36 = parseFile('app.swift', `
+ class DataStore {
+ init(url: String) { }
+ func load() { fetch(); }
+ }
+`);
+// Swift grammar not installed — parseFile returns null; skip gracefully
+if (r36 !== null) {
+ const initEntity = r36.entities.find(e => e.name === 'init');
+ assert(initEntity !== undefined, '§36 init entity emitted for Swift initializer');
+ if (initEntity) {
+ assert(initEntity.kind === 'method', `§36 init kind is method, got ${initEntity.kind}`);
+ assert(initEntity.container === 'DataStore', `§36 init is contained by DataStore, got ${initEntity.container}`);
+ }
+} else {
+ console.log(' ℹ §36 skipped — Swift grammar not installed');
+}
+
+// ---------------------------------------------------------------------------
+// § 37 isGrammarSupported filters Kotlin and Swift
+// ---------------------------------------------------------------------------
+section('37. isGrammarSupported returns false for Kotlin/Swift, true for TS/Python');
+const { isGrammarSupported } = await import(`${distBase}/index.js`);
+assert(isGrammarSupported('foo.kt') === false, '§37 isGrammarSupported(foo.kt) === false');
+assert(isGrammarSupported('foo.swift') === false, '§37 isGrammarSupported(foo.swift) === false');
+assert(isGrammarSupported('foo.ts') === true, '§37 isGrammarSupported(foo.ts) === true');
+assert(isGrammarSupported('foo.tsx') === true, '§37 isGrammarSupported(foo.tsx) === true');
+assert(isGrammarSupported('foo.py') === true, '§37 isGrammarSupported(foo.py) === true');
+assert(isGrammarSupported('foo.txt') === false, '§37 isGrammarSupported(foo.txt) === false');
+
+// ---------------------------------------------------------------------------
+// § 38 Python relative imports — imported symbol names recorded as IMPORTS
+// ---------------------------------------------------------------------------
+section('38. Python "from . import utils" records IMPORTS edge to utils');
+const r38 = parseFile('services/auth.py', `
+from . import utils
+from .models import User
+from ..core import Config
+`);
+if (r38) {
+ const importDstNames = r38.relationships
+ .filter(r => r.predicate === 'IMPORTS')
+ .map(r => r.dstName);
+
+ assert(importDstNames.includes('utils'),
+ '§38 IMPORTS edge to "utils" from "from . import utils"',
+ `got: ${importDstNames}`);
+
+ assert(importDstNames.includes('User'),
+ '§38 IMPORTS edge to "User" from "from .models import User"',
+ `got: ${importDstNames}`);
+
+ assert(importDstNames.includes('Config'),
+ '§38 IMPORTS edge to "Config" from "from ..core import Config"',
+ `got: ${importDstNames}`);
+
+ // 'models' and 'core' still captured from the module path (after dot-stripping)
+ assert(importDstNames.includes('models'),
+ '§38 IMPORTS edge to "models" (module path) still emitted',
+ `got: ${importDstNames}`);
+
+ const dotImports = importDstNames.filter(n => n.startsWith('.'));
+ assert(dotImports.length === 0, '§38 no dot-prefixed IMPORTS dstName', `got: ${dotImports}`);
+}
+
+// ---------------------------------------------------------------------------
+// § 39 Transitive re-export resolution (three-file chain)
+// ---------------------------------------------------------------------------
+section('39. Transitive re-export: baz.ts calls foo() defined in bar.ts, re-exported via index.ts');
+const r39bar = parseFile('bar.ts', `
+ export function foo(x: number): number { return x * 2; }
+`);
+const r39index = parseFile('index.ts', `
+ export { foo } from './bar';
+`);
+const r39baz = parseFile('baz.ts', `
+ import { foo } from './index';
+ export function run(n: number) { return foo(n); }
+`);
+if (r39bar && r39index && r39baz) {
+ const edges39 = resolveCallEdges([r39bar, r39index, r39baz]);
+ const fooEdge = edges39.find(e => e.calleeName === 'foo' && e.callerFilePath === 'baz.ts');
+ assert(fooEdge !== undefined,
+ '§39 foo() in baz.ts resolves through re-export in index.ts to bar.ts');
+ if (fooEdge) {
+ assert(fooEdge.calleeFilePath === 'bar.ts',
+ `§39 calleeFilePath = bar.ts, got ${fooEdge.calleeFilePath}`);
+ assert(fooEdge.confidence >= 0.8, `§39 confidence >= 0.8, got ${fooEdge.confidence}`);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// § 40 Dynamic import with string literal produces IMPORTS edge
+// ---------------------------------------------------------------------------
+section('40. Dynamic import("./utils") produces IMPORTS edge');
+const r40 = parseFile('loader.ts', `
+ async function loadUtils() {
+ const mod = await import('./utils');
+ return mod.parse();
+ }
+`);
+if (r40) {
+ const importDsts = r40.relationships
+ .filter(r => r.predicate === 'IMPORTS')
+ .map(r => r.dstName);
+ assert(importDsts.includes('utils'),
+ '§40 IMPORTS edge to "utils" from dynamic import("./utils")',
+ `got: ${importDsts}`);
+}
+
+// ---------------------------------------------------------------------------
+// Summary
+// ---------------------------------------------------------------------------
+console.log('\n════════════════════════════════════════════');
+console.log(` Total: ${passed + failed} checks`);
+console.log(` ✓ Passed: ${passed}`);
+console.log(` ✗ Failed: ${failed}`);
+if (failures.length > 0) {
+ console.log('\n Failures:');
+ for (const f of failures) {
+ console.log(` - ${f.name}`);
+ if (f.detail) console.log(` ${f.detail}`);
+ }
+}
+console.log('════════════════════════════════════════════\n');
+
+process.exit(failed > 0 ? 1 : 0);