Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(ingest): infer Scala, TypeScript and Go receiver types (#854)
Tanner Kocherb0bd0644882a
diff --git a/core-ingestion/src/__tests__/__snapshots__/parseFile.test.ts.snap b/core-ingestion/src/__tests__/__snapshots__/parseFile.test.ts.snapindex 1a8ee633..6e021cf6 100644--- a/core-ingestion/src/__tests__/__snapshots__/parseFile.test.ts.snap+++ b/core-ingestion/src/__tests__/__snapshots__/parseFile.test.ts.snap@@ -143,6 +143,27 @@ exports[`parseFile snapshots > snapshots Identifiers.scala 1`] = `"importAliases": undefined,"importBindings": undefined,"language": "scala",+ "receiverFactories": [+ [+ "WorkspaceId",+ "WorkspaceId",+ ],+ [+ "NodeId",+ "NodeId",+ ],+ ],+ "receiverHeritage": [+ [+ "WorkspaceId",+ "AnyVal",+ ],+ [+ "NodeId",+ "AnyVal",+ ],+ ],+ "receiverPackage": "ix.sample.model","relationships": [{"dstName": "WorkspaceId",@@ -418,6 +439,31 @@ exports[`parseFile snapshots > snapshots Node.scala 1`] = `"importAliases": undefined,"importBindings": undefined,"language": "scala",+ "receiverFactories": [+ [+ "Node",+ "Node",+ ],+ ],+ "receiverHeritage": [+ [+ "Module",+ "NodeKind",+ ],+ [+ "File",+ "NodeKind",+ ],+ [+ "Class",+ "NodeKind",+ ],+ [+ "Function",+ "NodeKind",+ ],+ ],+ "receiverPackage": "ix.sample.model","relationships": [{"dstName": "NodeKind",diff --git a/core-ingestion/src/__tests__/queries.go.test.ts b/core-ingestion/src/__tests__/queries.go.test.tsindex 5e4be577..e4b93e6b 100644--- a/core-ingestion/src/__tests__/queries.go.test.ts+++ b/core-ingestion/src/__tests__/queries.go.test.ts@@ -325,6 +325,7 @@ func (s *Scheme) start(opts *Options) {expect(rels).toContainEqual({srcName: 'handle',dstName: 'Options.Run',+ receiverType: 'Options',predicate: 'CALLS',});@@ -333,6 +334,7 @@ func (s *Scheme) start(opts *Options) {expect(rels).toContainEqual({srcName: 'Scheme.start',dstName: 'Scheme.Register',+ receiverType: 'Scheme',predicate: 'CALLS',});@@ -340,6 +342,7 @@ func (s *Scheme) start(opts *Options) {expect(rels).toContainEqual({srcName: 'Scheme.start',dstName: 'Options.Run',+ receiverType: 'Options',predicate: 'CALLS',});});diff --git a/core-ingestion/src/__tests__/receiver-inference.test.ts b/core-ingestion/src/__tests__/receiver-inference.test.tsnew file mode 100644index 00000000..3528dba3--- /dev/null+++ b/core-ingestion/src/__tests__/receiver-inference.test.ts@@ -0,0 +1,610 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from 'vitest';+import { buildGlobalResolutionIndex, parseFile, resolveEdges, summarizeParseResult } from '../index.js';+import { buildPatch, buildPatchWithResolution } from '../patch-builder.js';+import labelledCases from '../../test-fixtures/receiver-inference/cases.json';++const parse = (ext: string, source: string, name = 'use') => {+ const result = parseFile(`/repo/${name}.${ext}`, source.replaceAll(';', ';\n').replaceAll('} ', '}\n'))!;+ expect(result).not.toBeNull();+ expect(result.hasParseErrors).toBeUndefined();+ return result;+};+const methods = (ext: string, body: string) => ext === 'scala'+ ? `class Target { def run() = () }; class Other { def run() = () }; ${body}`+ : ext === 'ts'+ ? `class Target { run() {} } class Other { run() {} } ${body}`+ : `package p\ntype Target struct{}; type Other struct{}; func (t Target) Run() {}; func (o Other) Run() {}; ${body}`;++const typedEdgeOps = (ops: Array<{ type: string; attrs?: unknown }>) =>+ ops.filter(op => op.type === 'UpsertEdge' && (op.attrs as { tier?: string } | undefined)?.tier === 'type');++describe('typed local receivers', () => {+ it('Go resolves a receiver method declared in another package file', () => {+ const files = [+ parse('go', 'package p\ntype Target struct{}\n', 'types'),+ parse('go', 'package p\nfunc (t Target) Run() {}\n', 'methods'),+ parse('go', 'package p\nfunc use(t Target) { t.Run() }\n'),+ ];+ const edges = resolveEdges(files);+ expect(edges).toContainEqual(expect.objectContaining({+ srcFilePath: files[2].filePath, dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run', tier: 'type',+ }));+ const summaries = new Map(files.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([files[2]], undefined, index)).toEqual(edges.filter(e => e.srcFilePath === files[2].filePath));+ expect(buildPatchWithResolution(files[2], 'hash', 'workspace', edges).ops).toContainEqual(+ expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS', attrs: { confidence: 0.95, tier: 'type' } }),+ );+ });++ it.each(['dep := Target{}', 'dep := &Target{}', 'var dep Target', 'dep := NewTarget()'])('Go finds split-file methods for %s', (binding) => {+ const files = [+ parse('go', 'package p\ntype Target struct{}\nfunc NewTarget() Target { return Target{} }\n', 'types'),+ parse('go', 'package p\nfunc (t Target) Run() {}\n', 'methods'),+ parse('go', `package p\nfunc use() { ${binding}; dep.Run() }\n`),+ ];+ expect(resolveEdges(files)).toContainEqual(expect.objectContaining({ dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run', tier: 'type' }));+ });++ it('counts type-tier resolutions separately from qualifier ones', () => {+ const stats = { importLookups: 0, transitiveLookups: 0, globalFallbacks: 0, globalCandidateTotal: 0, resolvedImport: 0,+ resolvedTransitive: 0, resolvedGlobal: 0, resolvedQualifier: 0, resolvedType: 0, skippedSameFile: 0, skippedAmbiguous: 0 };+ resolveEdges([parse('ts', methods('ts', 'function use(dep: Target) { dep.run(); }'))], stats);+ expect(stats).toMatchObject({ resolvedType: 1, resolvedQualifier: 0 });+ });++ it('Go does not borrow methods from the external test package in the same directory', () => {+ const files = [+ parse('go', 'package p\ntype Target struct{}\n', 'types'),+ parse('go', 'package p_test\ntype Target struct{}\nfunc (t Target) Run() {}\n', 'methods_test'),+ parse('go', 'package p\nfunc use(t Target) { t.Run() }\n'),+ ];+ expect(resolveEdges(files).filter(e => e.tier === 'type')).toEqual([]);+ });++ it('Go rejects multiple method definitions across package files', () => {+ const files = [+ parse('go', 'package p\ntype Target struct{}\n', 'types'),+ parse('go', 'package p\nfunc (t Target) Run() {}\n', 'methods'),+ parse('go', 'package p\nfunc (t Target) Run() {}\n', 'duplicate'),+ parse('go', 'package p\nfunc use(t Target) { t.Run() }\n'),+ ];+ expect(resolveEdges(files).filter(e => e.tier === 'type')).toEqual([]);+ });++ it('Go resolves imported receiver types and factories with methods in another file', () => {+ const files = [+ parse('go', 'package model\ntype Target struct{}\nfunc NewTarget() Target { return Target{} }\n', 'model/types'),+ parse('go', 'package model\nfunc (t Target) Run() {}\n', 'model/methods'),+ parse('go', 'package app\nimport model "example/model"\nfunc typed(t model.Target) { t.Run() }; func factory() { dep := model.NewTarget(); dep.Run() }\n'),+ ];+ const calls = resolveEdges(files).filter(e => e.tier === 'type');+ expect(calls).toEqual([+ expect.objectContaining({ srcName: 'typed', dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run' }),+ expect.objectContaining({ srcName: 'factory', dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run' }),+ ]);+ const summaries = new Map(files.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([files[2]], undefined, index).filter(e => e.tier === 'type')).toEqual(calls);+ });++ it('Go does not use a package factory return for a shadowing local function', () => {+ const result = parse('go', methods('go', 'func NewTarget() Target { return Target{} }; func use() { NewTarget := func() Other { return Other{} }; dep := NewTarget(); dep.Run() }'));+ const edges = resolveEdges([result]);+ expect(edges.filter(e => e.tier === 'type')).toEqual([]);+ expect(buildPatchWithResolution(result, 'hash', 'workspace', edges).ops.filter(op => op.type === 'UpsertEdge' && op.attrs?.tier === 'type')).toEqual([]);+ });++ it('Go rejects a shadowing factory parameter but keeps the package factory in a sibling scope', () => {+ const result = parse('go', methods('go', 'func NewTarget() Target { return Target{} }; func shadowed(NewTarget func() Other) { dep := NewTarget(); dep.Run() }; func known() { dep := NewTarget(); dep.Run() }'));+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([+ expect.objectContaining({ srcName: 'known', dstQualifiedKey: 'Target.Run' }),+ ]);+ });++ it('TypeScript var in a nested block overwrites a function parameter binding', () => {+ const result = parse('ts', methods('ts', 'function use(dep: Target) { if (true) { var dep = { run() {} }; } dep.run(); }'));+ const edges = resolveEdges([result]);+ expect(edges.filter(e => e.tier === 'type')).toEqual([]);+ expect(buildPatchWithResolution(result, 'hash', 'workspace', edges).ops.filter(op => op.type === 'UpsertEdge' && op.attrs?.tier === 'type')).toEqual([]);+ });++ it('TypeScript leaves a block at its end, even when the next node starts there', () => {+ // `}{` and `}function`: the next node starts at the block's end index.+ const result = parse('ts', methods('ts', 'function use() { {let dep = new Other();}{let dep = new Target();dep.run();}{dep.run();} }; function shadowed(dep: Target) { {}function dep() {} dep.run(); }'));+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([+ expect.objectContaining({ srcName: 'use', dstQualifiedKey: 'Target.run' }),+ ]);+ });++ it('TypeScript infers function-scoped var after a block without confusing let shadows', () => {+ const result = parse('ts', methods('ts', 'function fromVar() { if (true) { var dep = new Target(); } dep.run(); }; function fromLet(dep: Target) { if (true) { let dep = { run() {} }; } dep.run(); }'));+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([+ expect.objectContaining({ srcName: 'fromVar', dstQualifiedKey: 'Target.run' }),+ expect.objectContaining({ srcName: 'fromLet', dstQualifiedKey: 'Target.run' }),+ ]);+ });++ it.each([+ 'class Holder { static { var dep = new Target(); } }; function use() { dep.run(); }',+ 'namespace Holder { var dep = new Target(); }; function use() { dep.run(); }',+ ])('TypeScript var does not escape a static block or namespace', (source) => {+ const result = parse('ts', methods('ts', source));+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([]);+ });++ it.each(labelledCases)('matches the labelled $language $name sample', (fixture) => {+ const result = parse(fixture.language, fixture.source);+ const edges = resolveEdges([result]).filter(e => e.tier === 'type');+ expect(edges.map(e => e.dstQualifiedKey)).toEqual(fixture.expected);+ });+ it.each([+ ['scala', 'class T { def run() = () }; class U { def run() = () }; object Use { def use() = { val x: T = new T(); x.run() } }'],+ ['ts', 'class T { run() {} } class U { run() {} } function use() { const x: T = new T(); x.run(); }'],+ ['go', 'package p\ntype T struct{}; type U struct{}; func (t T) Run() {}; func (u U) Run() {}; func use() { x := T{}; x.Run() }'],+ ])('resolves a %s local despite competing method names', (extension, source) => {+ const result = parseFile(`/repo/use.${extension}`, source.replaceAll(';', ';\n').replaceAll('} ', '}\n'))!;+ expect(result).not.toBeNull();+ expect(result.relationships).toContainEqual(expect.objectContaining({+ predicate: 'CALLS', dstName: extension === 'go' ? 'T.Run' : 'T.run', receiverType: 'T',+ }));+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({+ predicate: 'CALLS', dstQualifiedKey: extension === 'go' ? 'T.Run' : 'T.run', tier: 'type', confidence: 0.95,+ }));+ });++ it.each([+ ['scala', 'constructor parameter', 'class Use(dep: Target) { def use() = dep.run() }'],+ ['scala', 'qualified field', 'class Use(val dep: Target) { def use() = this.dep.run() }'],+ ['scala', 'field', 'class Use { val dep: Target = new Target(); def use() = dep.run() }'],+ ['scala', 'typed val', 'object Use { def use() = { val dep: Target = new Target(); dep.run() } }'],+ ['scala', 'typed var', 'object Use { def use() = { var dep: Target = new Target(); dep.run() } }'],+ ['scala', 'new', 'object Use { def use() = { val dep = new Target(); dep.run() } }'],+ ['scala', 'typed parameter', 'object Use { def use(dep: Target) = dep.run() }'],+ ['ts', 'typed parameter', 'function use(dep: Target) { dep.run(); }'],+ ['ts', 'annotated const', 'function use() { const dep: Target = new Target(); dep.run(); }'],+ ['ts', 'annotated let', 'function use() { let dep: Target = new Target(); dep.run(); }'],+ ['ts', 'new', 'function use() { let dep = new Target(); dep.run(); }'],+ ['ts', 'field', 'class Use { dep: Target; use() { this.dep.run(); } }'],+ ['ts', 'abstract field', 'abstract class Use { dep: Target; use() { this.dep.run(); } }'],+ ['ts', 'initialized field', 'class Use { dep = new Target(); use() { this.dep.run(); } }'],+ ['ts', 'parameter property', 'class Use { constructor(private dep: Target) {} use() { this.dep.run(); } }'],+ ['ts', 'readonly parameter property', 'class Use { constructor(readonly dep: Target) {} use() { this.dep.run(); } }'],+ ['go', 'literal', 'func use() { dep := Target{}; dep.Run() }'],+ ['go', 'pointer literal', 'func use() { dep := &Target{}; dep.Run() }'],+ ['go', 'var', 'func use() { var dep Target; dep.Run() }'],+ ['go', 'pointer var', 'func use() { var dep *Target; dep.Run() }'],+ ['go', 'factory', 'func NewTarget() *Target { return &Target{} }; func use() { dep := NewTarget(); dep.Run() }'],+ ])('%s infers %s', (ext, _rule, body) => {+ const result = parse(ext, methods(ext, body));+ const key = ext === 'go' ? 'Target.Run' : 'Target.run';+ const edges = resolveEdges([result]);+ expect(edges).toContainEqual(expect.objectContaining({ dstQualifiedKey: key, tier: 'type', confidence: 0.95 }));+ const patch = buildPatchWithResolution(result, 'hash', 'workspace', edges);+ expect(patch.ops).toContainEqual(expect.objectContaining({ type: 'UpsertEdge', predicate: 'CALLS', attrs: { tier: 'type', confidence: 0.95 } }));+ });++ it.each(['Target()', 'Target.apply()'])('Scala infers companion %s from its declared return', (factory) => {+ const result = parse('scala', methods('scala', `object Target { def apply(): Target = new Target() }; object Use { def use() = { val dep = ${factory}; dep.run() } }`));+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' }));+ });++ it('Scala infers a case-class constructor', () => {+ const result = parse('scala', 'case class Target() { def run() = () }; object Use { def use() = { val dep = Target(); dep.run() } }');+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' }));+ });++ it.each(['Target()', 'Target.apply()'])('Scala infers companion %s returning a constructor directly', (factory) => {+ const result = parse('scala', methods('scala', `object Target { def apply() = new Target() }; object Use { def use() = { val dep = ${factory}; dep.run() } }`));+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' }));+ });++ it.each([+ ['scala', 'object Use { def use(dep: Target) = { { val dep = unknown(); dep.run() } } }'],+ ['scala', 'class Use(dep: Target) { def use(dep: Any) = dep.run() }'],+ ['ts', 'function use(dep: Target) { { const dep = unknown(); dep.run(); } }'],+ ['ts', 'function use(dep: Target) { function nested(dep) { dep.run(); } }'],+ ['ts', 'function use(dep: Target) { const nested = dep => dep.run(); }'],+ ['ts', 'function use<Target>(dep: Target) { dep.run(); }'],+ ['ts', 'function use() { type Target = any; const dep: Target = unknown(); dep.run(); }'],+ ['ts', 'function use(dep: Missing.Target) { dep.run(); }'],+ ['ts', 'function use(dep: Target) { { dep.run(); const dep = unknown(); } }'],+ ['ts', 'function use(dep: Target) { try {} catch (dep) { dep.run(); } }'],+ ['ts', 'class Use { signature(dep: Target): void; use() { this.dep.run(); } }'],+ ['go', 'func use(dep *Target) { { dep := unknown(); dep.Run() } }'],+ ['go', 'func use(dep *Target) { f := func(dep interface{}) { dep.Run() }; _ = f }'],+ ['go', 'func use(dep *Target) { for _, dep := range unknown() { dep.Run() } }'],+ ['ts', 'function use(dep: Target) { for (const dep of unknown()) { dep.run(); } }'],+ ['ts', 'function use(dep: Target) { for (dep of unknown()) {} dep.run(); }'],+ ['scala', 'object Use { def use(dep: Target) = unknown().foreach { dep => dep.run() } }'],+ ['scala', 'object Use { def use(dep: Target) = unknown() match { case dep: Any => dep.run() } }'],+ ['scala', 'object Use { def use(dep: Target) = for (dep <- unknown()) yield dep.run() }'],+ ['go', 'func use(dep Target) { switch dep := unknown().(type) { default: dep.Run() } }'],+ ['go', 'func use(dep Target) { if dep := unknown(); dep != nil { dep.Run() } }'],+ ])('%s unknown shadows do not borrow the outer receiver', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ expect(result.relationships.filter(r => r.receiverType === 'Target')).toEqual([]);+ expect(resolveEdges([result]).filter(e => e.predicate === 'CALLS')).toEqual([]);+ expect(typedEdgeOps(buildPatch(result, 'hash', 'workspace').ops)).toEqual([]);+ });++ it.each([+ ['scala', 'class Use { def use[Target](dep: Target) = dep.run() }'],+ ['scala', 'class Use[Target](dep: Target) { def use() = dep.run() }'],+ ['scala', 'trait Use[+Target <: AnyRef] { def use(dep: Target) = dep.run() }'],+ ['scala', 'object Use { def use[F[_], @specialized Target: Ordering](dep: Target) = dep.run() }'],+ ['scala', 'class Use { type Target = Other; def use(dep: Target) = dep.run() }'],+ ['ts', 'function use<K, Target>(dep: Target) { dep.run(); }'],+ ['go', 'func use[K comparable, Target any](dep Target) { dep.Run() }'],+ ['go', 'type Box[K, Target any] struct{}; func (b *Box[K, Target]) use(dep Target) { dep.Run() }'],+ ['go', 'func use() { type Target struct{}; var dep Target; dep.Run() }'],+ ])('%s type parameters and local types shadow the same-named class', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ expect(result.relationships.filter(r => r.receiverType === 'Target')).toEqual([]);+ expect(resolveEdges([result]).filter(e => e.predicate === 'CALLS')).toEqual([]);+ expect(typedEdgeOps(buildPatch(result, 'hash', 'workspace').ops)).toEqual([]);+ });++ it.each([+ ['scala', 'object Target { def apply(): Other = new Other() }; object Use { def use() = { val dep = Target(); dep.run() } }'],+ ['ts', 'function use() { let dep = new Target(); dep = unknown(); dep.run(); }'],+ ['go', 'func NewTarget() (*Target, error) { return nil, nil }; func use() { dep, err := NewTarget(); dep.Run(); _ = err }'],+ ])('%s does not assume a factory name or stale assignment is its type', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ const edges = resolveEdges([result]).filter(e => e.predicate === 'CALLS');+ if (ext === 'scala') expect(edges).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Other.run', tier: 'type' }));+ else expect(edges.filter(e => e.tier === 'type')).toEqual([]);+ expect(edges.some(e => e.dstQualifiedKey === (ext === 'go' ? 'Target.Run' : 'Target.run'))).toBe(false);+ });++ it.each([+ ['ts', 'function use() { let dep = new Target(); [dep] = [new Other()]; dep.run(); }'],+ ['ts', 'function use() { let dep = new Target(); ({ dep } = unknown()); dep.run(); }'],+ ['ts', 'function use() { let dep = new Target(); ({ a: dep } = unknown()); dep.run(); }'],+ ['ts', 'function use() { let dep = new Target(); [, ...[dep]] = unknown(); dep.run(); }'],+ ['ts', 'function use(c: Other) { let dep = new Target(); dep ||= c; dep.run(); }'],+ ['ts', 'function use(c: Other) { let dep = new Target(); dep ??= c; dep.run(); }'],+ ['ts', 'function use() { let dep = new Target(); dep += unknown(); dep.run(); }'],+ ['scala', 'object Use { def use() = { var dep = new Target(); dep += 1; dep.run() } }'],+ ['go', 'func use() { dep := Target{}; dep, ok := unknown(); dep.Run(); _ = ok }'],+ ])('%s destructuring and compound assignments make a binding unknown', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ const key = ext === 'go' ? 'Target.Run' : 'Target.run';+ expect(resolveEdges([result]).filter(e => e.tier === 'type' && e.dstQualifiedKey === key)).toEqual([]);+ expect(typedEdgeOps(buildPatch(result, 'hash', 'workspace').ops)).toEqual([]);+ });++ it.each([+ ['ts', 'function use() { let dep = new Target(); [other] = [unknown()]; dep.run(); }'],+ ['ts', 'function use() { let dep = new Target(); dep.x ||= unknown(); dep.run(); }'],+ ['scala', 'object Use { def use() = { var dep = new Target(); if (dep <= 1) dep.run() } }'],+ ])('%s assignments to other targets keep the binding typed', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' }));+ });++ it.each([+ ['ts', 'class Use { dep: Target = new Target(); use() { return { dep: 1, go() { this.dep.run(); } }; } }'],+ ['ts', 'class Use { dep: Target = new Target(); use() { const f = function (this: any) { this.dep.run(); }; } }'],+ ['ts', 'class Use { dep: Target = new Target(); use() { function f(this: any) { this.dep.run(); } } }'],+ ['ts', 'class Use { dep: Target = new Target(); use() { const g = function* (this: any) { this.dep.run(); }; } }'],+ ['ts', 'class Use { dep: Target = new Target(); f = function (this: any) { this.dep.run(); }; }'],+ ['ts', 'class Use { dep: Target = new Target(); use() { return { go() { const a = () => this.dep.run(); } }; } }'],+ ['scala', 'class Use(val dep: Target) { def use() = new Runnable { def run() = this.dep.run() } }'],+ ])('%s `this` rebound by a nested function or object does not reach the class field', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([]);+ expect(typedEdgeOps(buildPatch(result, 'hash', 'workspace').ops)).toEqual([]);+ });++ it.each([+ ['ts', 'class Use { dep: Target = new Target(); use() { const a = () => this.dep.run(); } }'],+ ['scala', 'class Use { def use() = new Runnable { val dep = new Target(); def run() = this.dep.run() } }'],+ ])('%s `this` in an arrow function or its own anonymous class keeps the field type', (ext, body) => {+ const result = parse(ext, methods(ext, body));+ expect(resolveEdges([result])).toContainEqual(expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' }));+ });++ it('Scala leaves conflicting inherited members unresolved', () => {+ const result = parse('scala', 'trait A { def run() = () }; trait B { def run() = () }; class Target extends A with B {}; object Use { def use(dep: Target) = dep.run() }');+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([]);+ });++ it.each([+ ['ts', 'function first(dep: Target) {} function use() { dep.run(); } class Target { run() {} }'],+ ['scala', 'class First(dep: Target) {}; object Use { def use() = dep.run() }; class Target { def run() = () }'],+ ['go', 'package p\nfunc first(dep Target) {}; func use() { dep.Run() }; type Target struct{}; func (t Target) Run() {}'],+ ])('%s parameters do not leak to sibling scopes at the root offset', (ext, source) => {+ const result = parse(ext, source);+ expect(resolveEdges([result]).filter(e => e.tier === 'type')).toEqual([]);+ });++ it.each([+ ['scala', 'class Target { def run(x: Int) = (); def run(x: String) = () }; object Use { def use(dep: Target) = dep.run(1) }'],+ ['go', 'package p\ntype Target struct{}; func (t Target) Run() {}; func (t Target) Run() {}; func use(dep Target) { dep.Run() }'],+ ])('%s ambiguous member definitions do not guess a type-tier signature', (ext, source) => {+ const result = parse(ext, source);+ expect(resolveEdges([result]).filter(e => e.predicate === 'CALLS')).toEqual([]);+ // The call falls back to its bare member name, as it resolved before inference.+ const ops = buildPatch(result, 'hash', 'workspace').ops;+ expect(typedEdgeOps(ops)).toEqual([]);+ expect(ops.filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS')).toHaveLength(1);+ });++ it('TypeScript overload signatures share their one implementation node', () => {+ const result = parse('ts', 'class Target { run(x: number): void; run(x: string): void; run(x: any) {} } function use(dep: Target) { dep.run(1); }');+ expect(result.entities.filter(e => e.name === 'run')).toHaveLength(1);+ expect(resolveEdges([result])).toEqual([expect.objectContaining({ dstQualifiedKey: 'Target.run', tier: 'type' })]);+ });++ it('TypeScript bare names never resolve through a same-named field or parameter property', () => {+ const result = parse('ts', "import { logger } from './logger'; class AuditLog { info() {} } class Client { send() {} } class Other { send() {} } const client = new Other(); class Svc { private logger: AuditLog = new AuditLog(); constructor(private client: Client) {} run() { logger.info('x'); client.send(); this.logger.info('y'); } }");+ expect(resolveEdges([result]).filter(e => e.tier === 'type').map(e => e.dstQualifiedKey)).toEqual(['Other.send', 'AuditLog.info']);+ });++ it('Go closure parameters stay inside the closure', () => {+ const result = parse('go', methods('go', 'func use() { dep := Target{}; f := func(dep Other) { dep.Run() }; _ = f; dep.Run() }'));+ expect(resolveEdges([result]).filter(e => e.tier === 'type').map(e => e.dstQualifiedKey)).toEqual(['Other.Run', 'Target.Run']);+ });++ it.each(['extends Base', 'extends Empty with Base'])('Scala resolves inherited members: %s', (heritage) => {+ const base = parse('scala', 'trait Base { def run() = () }; trait Empty {}', 'base');+ const child = parse('scala', `class Child ${heritage} {}`, 'child');+ const caller = parse('scala', 'object Use { def use(dep: Child) = dep.run() }');+ const fresh = resolveEdges([base, child, caller]);+ expect(fresh).toContainEqual(expect.objectContaining({ dstFilePath: base.filePath, dstQualifiedKey: 'Base.run', tier: 'type' }));+ const summaries = new Map([base, child, caller].map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([caller], undefined, index)).toEqual(fresh.filter(e => e.srcFilePath === caller.filePath));+ });++ it('TypeScript does not type a receiver through an import a namespace class shadows', () => {+ const dep = parse('ts', 'export class Dep { run() {} }', 'dep');+ const use = parse('ts', "import { Dep } from './dep'; namespace N { class Dep { run() {} } export function f(d: Dep) { d.run(); } }");+ expect(resolveEdges([dep, use]).filter(e => e.tier === 'type')).toEqual([]);+ });++ it('TypeScript does not type a global or library receiver as a same-named repo class', () => {+ const geo = parse('ts', 'export class Map { set() {} }', 'geo/map');+ const use = parse('ts', 'function use() { const m = new Map<string, number>(); m.set("a", 1); }');+ expect(resolveEdges([geo, use]).filter(e => e.tier === 'type')).toEqual([]);+ const imported = parse('ts', "import { Map } from './geo/map'; function use() { const m = new Map(); m.set(); }");+ expect(resolveEdges([geo, imported]).filter(e => e.tier === 'type')).toEqual([+ expect.objectContaining({ dstFilePath: geo.filePath, dstQualifiedKey: 'Map.set' }),+ ]);+ });++ it.each([+ ['', []],+ ['import mylib._\n', ['Option.get']],+ ['import mylib.Option\n', ['Option.get']],+ ])('Scala types a receiver only from a type in scope (%j)', (imports, expected) => {+ const lib = parse('scala', 'package mylib\nclass Option { def get() = () }', 'option');+ const use = parse('scala', `package app\n${imports}object Use { def use(o: Option) = o.get() }`);+ expect(resolveEdges([lib, use]).filter(e => e.tier === 'type').map(e => e.dstQualifiedKey)).toEqual(expected);+ });++ it('Scala types a receiver from its own package without an import', () => {+ const target = parse('scala', 'package app\nclass Target { def run() = () }', 'target');+ const other = parse('scala', 'package other\nclass Target { def run() = () }', 'other');+ const use = parse('scala', 'package app\nobject Use { def use(dep: Target) = dep.run() }');+ expect(resolveEdges([target, other, use]).filter(e => e.tier === 'type')).toEqual([+ expect.objectContaining({ dstFilePath: target.filePath, dstQualifiedKey: 'Target.run' }),+ ]);+ });++ it.each([+ ['package a\n', []],+ ['package a.b\n', ['Dep.run']],+ ['package a\npackage b\n', ['Dep.run']],+ ['package a\nimport a.b.Dep\n', ['Dep.run']],+ ])('Scala chained package clauses declare the joined package (%j)', (header, expected) => {+ const dep = parse('scala', 'package a\npackage b\nclass Dep { def run() = () }', 'dep');+ const use = parse('scala', `${header}object Use { def use(d: Dep) = d.run() }`);+ expect(summarizeParseResult(dep).receiverPackage).toBe('a.b');+ expect(resolveEdges([dep, use]).filter(e => e.tier === 'type').map(e => e.dstQualifiedKey)).toEqual(expected);+ });++ it('Scala imports disambiguate same-named types by declared package', () => {+ const caller = parse('scala', 'import model.Target\nobject Use { def use(dep: Target) = dep.run() }');+ const target = parse('scala', 'package model\nclass Target { def run() = () }', 'target');+ const other = parse('scala', 'package other\nclass Target { def run() = () }', 'other');+ const files = [caller, target, other];+ const fresh = resolveEdges(files).filter(e => e.tier === 'type');+ expect(fresh).toEqual([expect.objectContaining({ dstFilePath: target.filePath, dstQualifiedKey: 'Target.run' })]);+ const summaries = new Map(files.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([caller], undefined, index).filter(e => e.tier === 'type')).toEqual(fresh);+ });++ it.each([+ ['renamed', 'import other.{Target => T}\n', 'T', 'other'],+ ['Scala 3 renamed', 'import other.Target as T\n', 'T', 'other'],+ ['renamed beside a wildcard', 'import other.{Target => T, _}\n', 'T', 'other'],+ ['renamed away from a wildcard', 'import other.{Target => Renamed, _}\n', 'Target', undefined],+ ['hidden from a wildcard', 'import other.{Target => _, _}\n', 'Target', undefined],+ ['wildcard in braces', 'import other.{_}\n', 'Target', 'other'],+ ])('Scala %s import binds the receiver type it names', (_name, imports, local, expected) => {+ const target = parse('scala', 'package other\nclass Target { def run() = () }', 'other/Target');+ const sameName = parse('scala', `package app\nclass ${local === 'T' ? 'T' : 'Unrelated'} { def run() = () }`, 'app/Local');+ const use = parse('scala', `package app\n${imports}object Use { def use(dep: ${local}) = dep.run() }`, 'app/Use');+ const files = [target, sameName, use];+ const fresh = resolveEdges(files).filter(e => e.tier === 'type');+ expect(fresh).toEqual(expected ? [expect.objectContaining({ dstFilePath: target.filePath, dstQualifiedKey: 'Target.run' })] : []);+ const summaries = new Map(files.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([use], undefined, index).filter(e => e.tier === 'type')).toEqual(fresh);+ });++ it('Scala renamed import also names a factory return type', () => {+ const target = parse('scala', 'package other\nclass Target { def run() = () }', 'other/Target');+ const sameName = parse('scala', 'package app\nclass T { def run() = () }', 'app/T');+ const mk = parse('scala', 'package app\nimport other.{Target => T}\nobject Mk { def apply(): T = new T() }', 'app/Mk');+ const use = parse('scala', 'package app\nobject Use { def use() = { val x = Mk(); x.run() } }', 'app/Use');+ expect(resolveEdges([target, sameName, mk, use]).filter(e => e.tier === 'type' && e.srcFilePath === use.filePath)).toEqual([+ expect.objectContaining({ dstFilePath: target.filePath, dstQualifiedKey: 'Target.run' }),+ ]);+ });++ it.each([+ ['ts', "import { Target as Alias } from './target'; function use(dep: Alias) { dep.run(); }", 'export class Target { run() {} }'],+ ['scala', 'import model.Target\nobject Use { def use(dep: Target) = dep.run() }', 'package model\nclass Target { def run() = () }'],+ ['go', 'package p\nfunc use() { dep := NewTarget(); dep.Run() }', 'package p\ntype Target struct{}; func (t Target) Run() {}; func NewTarget() *Target { return &Target{} }'],+ ])('%s resolves across files and stored summaries', (ext, source, targetSource) => {+ const caller = parse(ext, source);+ const target = parse(ext, targetSource, 'target');+ const competing = parse(ext, ext === 'ts' ? 'export class Other { run() {} }' : ext === 'scala' ? 'class Other { def run() = () }' : 'package p\ntype Other struct{}; func (o Other) Run() {}', 'other');+ const files = [caller, target, competing];+ const fresh = resolveEdges(files).filter(e => e.srcFilePath === caller.filePath);+ expect(fresh).toContainEqual(expect.objectContaining({ dstFilePath: target.filePath, dstQualifiedKey: ext === 'go' ? 'Target.Run' : 'Target.run', tier: 'type' }));+ const summaries = new Map(files.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ expect(resolveEdges([caller], undefined, index)).toEqual(fresh);+ });+});++describe('receiver inference is additive', () => {+ const callsFrom = (edges: ReturnType<typeof resolveEdges>, srcName: string) =>+ edges.filter(e => e.predicate === 'CALLS' && e.srcName === srcName);++ it('Go keeps calls through an unaliased package import and types its factory', () => {+ const svc = parse('go', 'package svc\ntype Store struct{}\nfunc NewStore() *Store { return &Store{} }\nfunc (s *Store) Save() {}\nfunc Helper() {}\n', 'pkg/svc/store');+ const app = parse('go', 'package main\nimport "example.com/m/pkg/svc"\nfunc main() { svc.Helper(); s := svc.NewStore(); s.Save() }\n', 'cmd/app/main');+ const calls = callsFrom(resolveEdges([svc, app]), 'main');+ expect(calls).toContainEqual(expect.objectContaining({ dstFilePath: svc.filePath, dstQualifiedKey: 'Helper', tier: 'import' }));+ expect(calls).toContainEqual(expect.objectContaining({ dstFilePath: svc.filePath, dstQualifiedKey: 'NewStore', tier: 'import' }));+ expect(calls).toContainEqual(expect.objectContaining({ dstFilePath: svc.filePath, dstQualifiedKey: 'Store.Save', tier: 'type' }));+ });++ it('TypeScript namespace-import calls resolve by their bare name, as before', () => {+ const util = parse('ts', 'export function helper() {}', 'util');+ const lib = parse('ts', 'export function boot() {}', 'lib');+ const main = parse('ts', "import * as U from './util'; import * as lib from './lib'; function main() { U.helper(); lib.boot(); }", 'main');+ expect(main.relationships.filter(r => r.predicate === 'CALLS').map(r => r.dstName)).toEqual(['helper', 'boot']);+ const calls = callsFrom(resolveEdges([util, lib, main]), 'main');+ expect(calls).toContainEqual(expect.objectContaining({ dstFilePath: util.filePath, dstQualifiedKey: 'helper', tier: 'import' }));+ expect(calls).toContainEqual(expect.objectContaining({ dstFilePath: lib.filePath, dstQualifiedKey: 'boot', tier: 'import' }));+ });++ it('a receiver whose type is not inferred falls back to its bare member name', () => {+ const client = parse('ts', 'export class IxClient { stats() {} } export function createClient(): IxClient { return new IxClient(); }', 'client');+ const cmd = parse('ts', "import { IxClient, createClient } from './client'; function run() { const client = createClient(); client.stats(); } function check(c: Pick<IxClient, 'stats'>) { c.stats(); }", 'cmd');+ const edges = resolveEdges([client, cmd]);+ for (const caller of ['run', 'check']) {+ expect(callsFrom(edges, caller)).toContainEqual(expect.objectContaining({ dstFilePath: client.filePath, dstQualifiedKey: 'IxClient.stats', tier: 'import' }));+ }+ // The fallback edge is written under the relationship's own name.+ const ops = buildPatchWithResolution(cmd, 'hash', 'workspace', edges).ops;+ // run -> createClient, run -> stats, check -> stats.+ expect(ops.filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS').map(op => op.attrs))+ .toEqual([{ confidence: 0.9, tier: 'binding' }, { confidence: 0.9, tier: 'import' }, { confidence: 0.9, tier: 'import' }]);+ });++ it('Scala falls back to the bare member when a factory return is unknown', () => {+ const repo = parse('scala', 'class Repo { def find() = () }; object Factory { def makeRepo() = new Repo() }', 'repo');+ const use = parse('scala', 'object Use { def use() = { val r = makeRepo(); r.find() } }');+ expect(callsFrom(resolveEdges([repo, use]), 'Use.use')).toContainEqual(expect.objectContaining({ dstFilePath: repo.filePath, dstQualifiedKey: 'Repo.find' }));+ });++ it('Scala chained calls keep bare callee names, never receiver source text', () => {+ const result = parseFile('/repo/use.scala', 'object Use {\n def use(xs: Seq[Int]) = {\n xs.map { x =>\n x + 1\n }.filter(_ > 2).foreach(println)\n Option(1).getOrElse(0)\n }\n}\n')!;+ const names = result.relationships.filter(r => r.predicate === 'CALLS').map(r => r.dstName);+ expect(names).toEqual(expect.arrayContaining(['filter', 'foreach', 'getOrElse']));+ expect(names.filter(n => /[^\w.$]/.test(n))).toEqual([]);+ });++ it('an unresolved typed call is recorded under its bare member name, as before', () => {+ const result = parse('ts', 'function main() { const seen = new Registry(); seen.lookup(1); }', 'main');+ expect(result.relationships).toContainEqual(expect.objectContaining({ dstName: 'Registry.lookup', receiverType: 'Registry' }));+ const main = buildPatch(result, 'hash', 'workspace').ops.find(op => op.type === 'UpsertNode' && op.name === 'main');+ expect((main as { attrs?: Record<string, unknown> } | undefined)?.attrs?.unresolved_calls).toEqual(['Registry', 'lookup']);+ });++ it('builtin member calls on an uninferred receiver stay filtered', () => {+ const result = parse('ts', "function main() { console.log('x'); }", 'main');+ expect(result.relationships.filter(r => r.predicate === 'CALLS')).toEqual([]);+ const file = buildPatch(result, 'hash', 'workspace').ops.find(op => op.type === 'UpsertNode' && op.name === 'main');+ expect((file as { attrs?: Record<string, unknown> } | undefined)?.attrs?.unresolved_calls).toBeUndefined();+ });+});++describe('summaries stored before receiver inference', () => {+ it('Go incremental resolution keeps the edge it had, without receiver facts', () => {+ const files = [+ parse('go', 'package p\ntype Target struct{}\n', 'types'),+ parse('go', 'package p\nfunc (t Target) Run() {}\n', 'methods'),+ parse('go', 'package p\nfunc use(t Target) { t.Run() }\n'),+ ];+ const stale = new Map(files.map(r => {+ const { receiverFactories: _f, receiverHeritage: _h, receiverPackage: _p, ...summary } = summarizeParseResult(r);+ return [r.filePath, summary];+ }));+ const index = buildGlobalResolutionIndex([...stale.keys()], undefined, undefined, stale);+ const edges = resolveEdges([files[2]], undefined, index).filter(e => e.predicate === 'CALLS');+ expect(edges).toContainEqual(expect.objectContaining({ dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run', tier: 'qualifier' }));+ const fresh = resolveEdges(files).filter(e => e.predicate === 'CALLS' && e.srcFilePath === files[2].filePath);+ expect(fresh).toContainEqual(expect.objectContaining({ dstFilePath: files[1].filePath, dstQualifiedKey: 'Target.Run', tier: 'type' }));+ // Both land on the same graph edge; only its tier differs until the file is re-parsed.+ const ids = (e: typeof edges) => buildPatchWithResolution(files[2], 'h', 'ws', e).ops.filter(op => op.type === 'UpsertEdge').map(op => op.id);+ expect(ids(edges)).toEqual(ids(fresh));+ });+});++describe('receiver summary signature', () => {+ const sig = (ext: string, source: string) => summarizeParseResult(parse(ext, source, 'child')).sig;++ it('changes when only a Scala subclass file re-imports its superclass', () => {+ expect(sig('scala', 'import p1.Parent\nclass Child extends Parent {}'))+ .not.toBe(sig('scala', 'import p2.Parent\nclass Child extends Parent {}'));+ });++ it.each([+ ['scala', 'import other.Target\nobject Mk { def apply(): Target = new Target() }', 'import third.Target\nobject Mk { def apply(): Target = new Target() }'],+ ['go', 'package app\nimport m "example.com/x/other"\nfunc NewThing() m.Target { return m.Target{} }', 'package app\nimport m "example.com/x/third"\nfunc NewThing() m.Target { return m.Target{} }'],+ ])('changes when only a %s factory file re-imports its return type', (ext, before, after) => {+ expect(sig(ext, before)).not.toBe(sig(ext, after));+ });++ it('stays the same for a file without receiver facts when its imports change', () => {+ expect(sig('ts', "import { a } from './a'; export function f() {}"))+ .toBe(sig('ts', "import { a } from './b'; export function f() {}"));+ });+});++describe('receiver inference only adds to a patch', () => {+ const withoutInference = (r: ReturnType<typeof parse>) => ({+ ...r,+ relationships: r.relationships.filter(rel => !rel.receiverOnly)+ .map(({ receiverType: _t, receiverFactory: _f, ...rel }) => rel),+ });+ it.each([+ ['ts', "import { Target as T } from './t'; function use(dep: Target, o: T) { dep.run(); o.run(); this.x(); console.log(dep); }"],+ ['scala', 'object Use { def use(dep: Target) = { dep.run(); List(1).map(x => x).filter(_ > 0) } }'],+ ['go', 'import "example.com/m/yaml"\nfunc use(dep Target, n yaml.Node) { dep.Run(); n.Decode(); yaml.Helper(); d := NewTarget(); d.Run() }; func NewTarget() *Target { return &Target{} }'],+ ])('%s keeps every claim and edge id of the uninferred patch', (ext, body) => {+ const typed = parse(ext, methods(ext, body));+ const plain = withoutInference(typed);+ const typedOps = buildPatchWithResolution(typed, 'h', 'ws', resolveEdges([typed])).ops;+ const plainOps = buildPatchWithResolution(plain, 'h', 'ws', resolveEdges([plain])).ops;+ const claims = (ops: typeof typedOps) => ops.filter(op => op.type === 'AssertClaim');+ expect(claims(typedOps)).toEqual(claims(plainOps));+ const edges = (ops: typeof typedOps) => new Map(ops.filter(op => op.type === 'UpsertEdge').map(op => [op.id, op]));+ const typedEdges = edges(typedOps);+ for (const [id, op] of edges(plainOps)) {+ expect(typedEdges.get(id)).toMatchObject({ src: op.src, dst: op.dst, predicate: op.predicate });+ }+ // Nodes are the same, except that a call resolved by type leaves unresolved_calls.+ const nodes = (ops: typeof typedOps) => ops.filter(op => op.type !== 'UpsertEdge' && op.type !== 'AssertClaim');+ const strip = (op: (typeof typedOps)[number]) => {+ const { unresolved_calls: _c, unresolved_call_count: _n, ...attrs } = (op.attrs ?? {}) as Record<string, unknown>;+ return { ...op, attrs };+ };+ expect(nodes(typedOps).map(strip)).toEqual(nodes(plainOps).map(strip));+ nodes(typedOps).forEach((op, i) => {+ const unresolved = (o: typeof op) => ((o.attrs as { unresolved_calls?: string[] } | undefined)?.unresolved_calls ?? []);+ expect(unresolved(nodes(plainOps)[i])).toEqual(expect.arrayContaining(unresolved(op)));+ });+ });+});diff --git a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts b/core-ingestion/src/__tests__/resolveEdges.scope.test.tsindex 56d6976e..c4007d07 100644--- a/core-ingestion/src/__tests__/resolveEdges.scope.test.ts+++ b/core-ingestion/src/__tests__/resolveEdges.scope.test.ts@@ -10,7 +10,7 @@import { describe, expect, it } from 'vitest';-import { parseFile, type FileParseResult, type ResolvedEdge } from '../index.js';+import { parseFile, resolveEdges as resolveEdgesWithTier, type FileParseResult, type ResolvedEdge } from '../index.js';import { resolveEdges } from './helpers/untiered.js';import { buildPatch, buildPatchWithResolution } from '../patch-builder.js';@@ -116,9 +116,18 @@ describe('call resolution respects lexical scope (JS/TS)', () => {);const sample = parse('src/sample.ts', SAMPLE_COMMAND_SOURCE);- expect(callsTo(resolveEdges([caller, sample]), 'src/sample.ts')).toEqual([+ const edges = resolveEdges([caller, sample]);+ // The call's own edge as before, plus the typed receiver's exact member.+ expect(callsTo(edges, 'src/sample.ts')).toEqual([expect.objectContaining({ dstName: 'describe', dstQualifiedKey: 'CheckRunner.describe', confidence: 0.9 }),+ expect.objectContaining({ dstName: 'CheckRunner.describe', dstQualifiedKey: 'CheckRunner.describe', confidence: 0.95 }),]);+ // One graph edge: the call's own id, upgraded to the type tier.+ const tiered = resolveEdgesWithTier([caller, sample]);+ const calls = buildPatchWithResolution(caller, 'h', 'ws', tiered).ops.filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS');+ const untyped = buildPatchWithResolution(caller, 'h', 'ws', tiered.filter(e => e.dstName === 'describe')).ops+ .filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS');+ expect(calls).toEqual(untyped.map(op => ({ ...op, attrs: { confidence: 0.95, tier: 'type' } })));});it('resolves a bare call to the module-scope definition when a same-named member also exists', () => {diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.tsindex e7a0fde3..cb03f6f1 100644--- a/core-ingestion/src/index.ts+++ b/core-ingestion/src/index.ts@@ -153,6 +153,7 @@ import { SupportedLanguages, languageFromPath } from './languages.js';import { LANGUAGE_QUERIES } from './queries.js';import { classifyFileRole } from './role-classifier.js';import type { RoleClassification } from './role-classifier.js';+import { callReceiver, collectReceiverFacts } from './receiver-types.js';import { summarySignature, type FileSummary } from './symbol-index.js';export type { FileSummary } from './symbol-index.js';@@ -234,6 +235,18 @@ export interface ParsedRelationship {* it becomes an edge only when it resolves to exactly one tracked file.*/importVia?: 'helper';+ /**+ * Lexically inferred receiver. An exact member resolves at tier `type`;+ * otherwise the relationship resolves by its name, as without inference.+ */+ receiverType?: string;+ receiverFactory?: string;+ /**+ * Set on a typed relationship that only exists for its receiver (the call+ * also has its own, unchanged relationship). Without an exact member it+ * resolves to nothing: no edge, no claim, no unresolved-call entry.+ */+ receiverOnly?: true;}/**@@ -284,6 +297,9 @@ export interface FileParseResult {* file parsed cleanly.*/hasParseErrors?: true;+ receiverFactories?: Array<[string, string]>;+ receiverHeritage?: Array<[string, string]>;+ receiverPackage?: string;fileRole: RoleClassification;}@@ -2645,6 +2661,9 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptiolanguage === SupportedLanguages.Rust || language === SupportedLanguages.PHP;const jsTsCallBareOnly = new Map<string, boolean>();const jsTsCallRelationship = new Map<string, ParsedRelationship>();+ // Every CALLS relationship by `${scope}\0${callKey}`, so a typed relationship+ // can join the call relationship of the same name.+ const callRelationships = new Map<string, ParsedRelationship>();// JS/TS: helper-literal module paths already emitted (see importVia).const jsTsHelperImports = new Set<string>();if (isJsTs) {@@ -2998,6 +3017,9 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio}}+ const receiverFacts = [SupportedLanguages.Scala, SupportedLanguages.TypeScript, SupportedLanguages.Go].includes(language)+ ? collectReceiverFacts(tree.rootNode, language, checkBudget) : undefined;+// --- Second pass: calls and imports ---for (const match of pass2Matches) {checkBudget();@@ -3184,7 +3206,14 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio// R package-qualified calls (pkg::func) carry a distinct @_namespace// capture so the dstName can keep the :: separator (vs a plain dotted name).const namespaceCapture = match.captures.find((c: any) => c.name === '_namespace');- if (builtinsForLanguage(language).has(callee) && !qualifierCapture && !namespaceCapture) continue;+ // A member call whose receiver has a lexically inferred type or factory+ // also gets a typed relationship (below). The call's own relationship is+ // unchanged, so inference only ever adds edges.+ const typedReceiver = receiverFacts && match.captures.some((c: any) => c.name === 'call')+ ? callReceiver(callName.node, receiverFacts) : undefined;+ // A builtin-named call is still dropped; only its typed relationship stays.+ const builtinCall = builtinsForLanguage(language).has(callee) && !qualifierCapture && !namespaceCapture;+ if (builtinCall && !typedReceiver) continue;// For Python: skip calls that are decorator applications.// When a method is decorated (e.g. @util.deprecated(...)), the call sits at the@@ -3340,13 +3369,13 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptioreturn `${qualifier}.${callee}`;})();- if (!qualifierCapture && !namespaceCapture && effectiveCallee === callee) {+ if (!builtinCall && !qualifierCapture && !namespaceCapture && effectiveCallee === callee) {recordJsTsImportUse('CALLS', caller, effectiveCallee, callName.node, callee);}const callKey = phpCallKind ? `${phpCallKind}:${effectiveCallee}` : effectiveCallee;const bareKey = `${scope}\x00${callKey}`;- if (tracksBareCalls) {+ if (!builtinCall && tracksBareCalls) {let isBare: boolean;if (isJsTs) {// `foo()` / `new Foo()`: the JS/TS queries capture the callee as an@@ -3374,7 +3403,9 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio}jsTsCallBareOnly.set(bareKey, (jsTsCallBareOnly.get(bareKey) ?? true) && isBare);}- if (!seen.has(callKey)) {+ if (builtinCall) {+ // Only the typed relationship below.+ } else if (!seen.has(callKey)) {seen.add(callKey);const rel: ParsedRelationship = {srcName: caller,@@ -3383,7 +3414,29 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio...(phpCallKind ? { phpCallKind } : {}),};relationships.push(rel);+ callRelationships.set(bareKey, rel);if (tracksBareCalls) jsTsCallRelationship.set(bareKey, rel);+ } else {+ // The call also names what an earlier typed relationship named: it is+ // a call in its own right, so it keeps its name-based fallback.+ delete callRelationships.get(bareKey)?.receiverOnly;+ }+ if (typedReceiver) {+ // `Type.member`, or `receiver.member` for a factory-typed receiver.+ const typedName = `${typedReceiver.type ?? typedReceiver.receiver}.${callee}`;+ const typedKey = `${scope}\x00${typedName}`;+ const receiver = typedReceiver.type ? { receiverType: typedReceiver.type } : { receiverFactory: typedReceiver.factory! };+ const named = callRelationships.get(typedKey);+ if (named) {+ // Same name as the call's own relationship: try the type first, then+ // fall back to that name as before.+ if (!named.receiverType && !named.receiverFactory) Object.assign(named, receiver);+ } else if (!seen.has(typedName)) {+ seen.add(typedName);+ const rel: ParsedRelationship = { srcName: caller, dstName: typedName, predicate: 'CALLS', ...receiver, receiverOnly: true };+ relationships.push(rel);+ callRelationships.set(typedKey, rel);+ }}continue;}@@ -3501,6 +3554,9 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio...(phpNamespaces.blocks > 0 ? { phpNamespaceBlocks: phpNamespaces.blocks } : {}),// Absent unless true, for the same reason....(tree.rootNode.hasError ? { hasParseErrors: true as const } : {}),+ ...(receiverFacts?.factories.length ? { receiverFactories: receiverFacts.factories } : {}),+ ...(receiverFacts?.heritage.length ? { receiverHeritage: receiverFacts.heritage } : {}),+ ...(receiverFacts?.package ? { receiverPackage: receiverFacts.package } : {}),fileRole: classifyFileRole(filePath, source),};} catch (e) {@@ -3540,12 +3596,13 @@ export interface ResolvedEdge {}/**+ * `type`: a lexical receiver type resolved an exact member (confidence 0.95).* `binding`: an explicit import binding names the target. `import`: the* target is in a file this one imports (or the import itself). `transitive`:* one re-export hop away. `qualifier`: a dotted name's qualifier picked the* file. `global`: the only definition of the name anywhere.*/-export type ResolutionTier = 'binding' | 'import' | 'transitive' | 'qualifier' | 'global';+export type ResolutionTier = 'type' | 'binding' | 'import' | 'transitive' | 'qualifier' | 'global';// ---------------------------------------------------------------------------// resolveCallEdges helpers@@ -3619,6 +3676,8 @@ export function summarizeParseResult(r: FileParseResult): FileSummary {});} else if (rel.predicate === 'CALLS' || rel.predicate === 'REFERENCES' || rel.predicate === 'EXTENDS') {refs.add(rel.dstName);+ if (rel.receiverType) refs.add(rel.receiverType);+ if (rel.receiverFactory) refs.add(rel.receiverFactory);}}const summary = {@@ -3629,6 +3688,10 @@ export function summarizeParseResult(r: FileParseResult): FileSummary {...(exportPublicNames ? { exportPublicNames } : {}),imports,...(phpTypes ? { phpTypes } : {}),+ ...(r.receiverFactories ? { receiverFactories: r.receiverFactories } : {}),+ ...(r.receiverHeritage ? { receiverHeritage: r.receiverHeritage } : {}),+ ...(r.receiverPackage ? { receiverPackage: r.receiverPackage } : {}),+ ...(r.importAliases ? { importAliases: r.importAliases } : {}),refs: [...refs].sort(),};return { ...summary, sig: summarySignature(summary) };@@ -4106,6 +4169,8 @@ export function resolveEdges(importLookups: number; transitiveLookups: number; globalFallbacks: number;globalCandidateTotal: number; resolvedImport: number; resolvedTransitive: number;resolvedGlobal: number; resolvedQualifier: number; skippedSameFile: number; skippedAmbiguous: number;+ /** Exact members of an inferred receiver type (optional for older callers). */+ resolvedType?: number;},globalIndex?: GlobalResolutionIndex,opts?: {@@ -4889,6 +4954,171 @@ export function resolveEdges(return narrowed;}+ // Receiver types resolve exact members, in the defining file's import context+ // as well (factory returns and inheritance).+ // A Go qualifier names an aliased import, or an unaliased one by its last path element.+ function goImportForQualifier(summary: FileSummary | undefined, qualifier: string): string | undefined {+ const aliased = summary?.importAliases?.[qualifier];+ if (aliased) return aliased;+ const named = [...new Set((summary?.imports ?? []).map(imp => imp.dstName)+ .filter(dst => dst.split('/').pop() === qualifier))];+ return named.length === 1 ? named[0] : undefined;+ }+ /**+ * The names a Scala file's imports bring into scope. Imports are summarized+ * as written per selector: `a.b.X`, `a.b` (from `a.b._`), and from braces or+ * Scala 3 `a.b.X => Y` / `a.b.X as Y` (renamed), `a.b.X => _` (hidden),+ * `a.b._` / `a.b.*` (wildcard).+ */+ function scalaImportScope(summary: FileSummary | undefined): {+ named: Map<string, string[]>; wildcards: Set<string>; excluded: Set<string>;+ } {+ const named = new Map<string, string[]>();+ const wildcards = new Set<string>();+ const excluded = new Set<string>();+ const bind = (local: string, fq: string) => named.set(local, [...(named.get(local) ?? []), fq]);+ for (const { dstName } of summary?.imports ?? []) {+ const renamed = /^(\S+?)\s*=>\s*(\S+)$/.exec(dstName) ?? /^(\S+)\s+as\s+(\S+)$/.exec(dstName);+ if (renamed) {+ // The original name is not imported, not even by a wildcard beside it.+ excluded.add(renamed[1]);+ if (renamed[2] !== '_') bind(renamed[2], renamed[1]);+ continue;+ }+ if (dstName.endsWith('._') || dstName.endsWith('.*')) {+ wildcards.add(dstName.slice(0, -2));+ continue;+ }+ // `a.b.X`, or the package of a top-level wildcard (`import a.b._`).+ wildcards.add(dstName);+ if (dstName.includes('.')) bind(dstName.slice(dstName.lastIndexOf('.') + 1), dstName);+ }+ return { named, wildcards, excluded };+ }+ function findReceiverProviders(context: string, rawType: string): Array<{ fp: string; type: string }> {+ const summary = summaries.get(context);+ const language = summary?.language ?? languageFromPath(context);+ const parts = rawType.split('.');+ let type = parts.pop()!;+ if (language === SupportedLanguages.Scala) {+ const candidates = (symbolToFiles.get(type) ?? []).filter(fp => summaries.get(fp)?.language === language);+ if (parts.length) return candidates.filter(fp => summaries.get(fp)?.receiverPackage === parts.join('.')).map(fp => ({ fp, type }));+ const scope = scalaImportScope(summary);+ // An explicit import binds the name, renamed (`{Target => T}`) or not, to+ // that type only: never a same-named type of this package.+ const named = scope.named.get(type);+ if (named) {+ return named.flatMap(fq => {+ const dot = fq.lastIndexOf('.');+ const original = fq.slice(dot + 1);+ return (symbolToFiles.get(original) ?? [])+ .filter(fp => summaries.get(fp)?.language === language && dot > 0 && summaries.get(fp)?.receiverPackage === fq.slice(0, dot))+ .map(fp => ({ fp, type: original }));+ });+ }+ if (fileHasSymbol.get(context)?.has(type)) return [{ fp: context, type }];+ // Otherwise only a type in scope: this package's, or a wildcard-imported+ // package's (`import p._` is summarized as `p`) unless the import renamed+ // or hid it (`{Target => T, _}`, `{Target => _, _}`). Never a same-named+ // type elsewhere, which is how `Option` would land on an unrelated class.+ return candidates.filter(fp => {+ const pkg = summaries.get(fp)?.receiverPackage;+ if (pkg === summary?.receiverPackage) return true;+ return pkg !== undefined && scope.wildcards.has(pkg) && !scope.excluded.has(`${pkg}.${type}`);+ }).map(fp => ({ fp, type }));+ }+ const binding = importBindingsByLocal.get(context)?.get(type);+ // A same-named declaration in the importing file can only be a nested+ // shadow (a `namespace` class); without scope facts, guess neither.+ if (binding && parts.length === 0 && fileHasSymbol.get(context)?.has(type)) return [];+ if (binding && parts.length === 0) {+ const files = resolveImportTargets(context, language!, binding.pkg, binding.pkg, 'types');+ type = binding.imported === 'default'+ ? (files.length === 1 ? filePublicNames.get(files[0])?.get('default') ?? type : type)+ : binding.imported;+ return files.filter(fp => fileHasSymbol.get(fp)?.has(type)).map(fp => ({ fp, type }));+ }+ if (parts.length && language === SupportedLanguages.Go) {+ const prefix = parts.join('.');+ const alias = goImportForQualifier(summary, prefix);+ if (!alias) return [];+ return resolveImportQualifierTargets(context, language, alias)+ .filter(fp => fileHasSymbol.get(fp)?.has(type)).map(fp => ({ fp, type }));+ }+ // A namespace-qualified TS type must not degrade to an unrelated bare type.+ if (parts.length && language === SupportedLanguages.TypeScript) return [];+ if (!parts.length && fileHasSymbol.get(context)?.has(type)) return [{ fp: context, type }];+ // TypeScript: a type neither defined here nor imported is a global or+ // library type (`Map`, `Response`), never a same-named class elsewhere.+ if (language !== SupportedLanguages.Go) return [];+ const compatible = (fp: string): boolean => importLanguageCompatible(language, fileLanguage.get(fp) ?? languageFromPath(fp));+ return (symbolToFiles.get(type) ?? []).filter(compatible)+ .filter(fp => goPackageKey(fp) === goPackageKey(context)).map(fp => ({ fp, type }));+ }++ const receiverProviderCache = new Map<string, Array<{ fp: string; type: string }>>();+ function receiverProviders(context: string, type: string): Array<{ fp: string; type: string }> {+ const key = `${context}\0${type}`;+ if (!receiverProviderCache.has(key)) receiverProviderCache.set(key, findReceiverProviders(context, type));+ return receiverProviderCache.get(key)!;+ }+ const goReceiverFiles = new Map<string, string[]>();+ const goPackageKey = (fp: string): string => `${nodePath.dirname(fp)}\0${summaries.get(fp)?.receiverPackage ?? ''}`;+ for (const [fp, summary] of summaries) if (summary.language === SupportedLanguages.Go) {+ const key = goPackageKey(fp);+ const files = goReceiverFiles.get(key) ?? [];+ files.push(fp);+ goReceiverFiles.set(key, files);+ }++ function receiverMembers(context: string, type: string, member: string, seen = new Set<string>()): Array<{ fp: string; key: string }> {+ const providers = receiverProviders(context, type);+ if (providers.length !== 1) return [];+ const { fp, type: name } = providers[0];+ const marker = `${fp}\0${name}`;+ if (seen.has(marker)) return [];+ const nextSeen = new Set(seen).add(marker);+ const key = `${name}.${member}`;+ if (summaries.get(fp)?.language === SupportedLanguages.Go) {+ const targets = (qualifiedToFiles.get(key) ?? [])+ .filter(candidate => summaries.get(candidate)?.language === SupportedLanguages.Go && goPackageKey(candidate) === goPackageKey(fp))+ .flatMap(candidate => (fileQKeys.get(candidate)?.get(member) ?? [])+ .filter(q => q === key).map(() => ({ fp: candidate, key })));+ return targets.length === 1 ? targets : [];+ }+ const exact = (fileQKeys.get(fp)?.get(member) ?? []).filter(q => q === key);+ // Multiple definitions include overloads. Do not guess a signature.+ if (exact.length) return exact.length === 1 ? [{ fp, key }] : [];+ const inherited = (summaries.get(fp)?.receiverHeritage ?? []).filter(([child]) => child === name)+ .flatMap(([, parent]) => receiverMembers(fp, parent, member, nextSeen));+ const unique = new Map(inherited.map(target => [`${target.fp}\0${target.key}`, target]));+ return [...unique.values()];+ }++ function factoryReceiver(context: string, factory: string): { context: string; type: string } | undefined {+ const summary = summaries.get(context);+ const language = summary?.language;+ let name = factory;+ let pool = [context];+ if (language === SupportedLanguages.Go) {+ const dot = factory.lastIndexOf('.');+ if (dot >= 0) {+ name = factory.slice(dot + 1);+ const alias = goImportForQualifier(summary, factory.slice(0, dot));+ pool = alias ? resolveImportQualifierTargets(context, language, alias) : [];+ } else pool = goReceiverFiles.get(goPackageKey(context)) ?? [];+ } else {+ const owner = factory.replace(/\.apply$/, '');+ const providers = receiverProviders(context, owner);+ if (providers.length !== 1) return;+ pool = [providers[0].fp];+ name = factory.endsWith('.apply') ? `${providers[0].type}.apply` : providers[0].type;+ }+ const matches = pool.flatMap(fp => (summaries.get(fp)?.receiverFactories ?? [])+ .filter(([fn]) => fn === name).map(([, type]) => ({ context: fp, type })));+ return matches.length === 1 && matches[0].type ? matches[0] : undefined;+ }+// ── Main resolution loop ───────────────────────────────────────────@@ -5130,6 +5360,21 @@ export function resolveEdges(continue;}+ // A typed receiver resolves to its exact member. Otherwise a receiver-only+ // relationship stops here, and any other resolves by its own name below.+ if (rel.predicate === 'CALLS' && (rel.receiverType || rel.receiverFactory)) {+ const receiver = rel.receiverType ? { context: srcFilePath, type: rel.receiverType }+ : factoryReceiver(srcFilePath, rel.receiverFactory!);+ const member = rel.dstName.slice(rel.dstName.lastIndexOf('.') + 1);+ const targets = receiver ? receiverMembers(receiver.context, receiver.type, member) : [];+ if (targets.length === 1) {+ resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: targets[0].fp, dstName: rel.dstName,+ dstQualifiedKey: targets[0].key, predicate: 'CALLS', confidence: 0.95, tier: 'type' });+ stats.resolvedType = (stats.resolvedType ?? 0) + 1;+ continue;+ }+ if (rel.receiverOnly) continue;+ }const origDstName = rel.dstName;// Z: resolve a renamed-import call by the provider's public symbol, but keep the// ORIGINAL local name on the emitted edge (buildPatchWithResolution maps the edgediff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.tsindex 5985209a..702e7600 100644--- a/core-ingestion/src/patch-builder.ts+++ b/core-ingestion/src/patch-builder.ts@@ -3,6 +3,7 @@import * as crypto from 'node:crypto';import * as nodePath from 'node:path';import type { GraphPatchPayload, PatchOp } from './types.js';+import { resolveEdges } from './index.js';import type { FileParseResult, ParsedEntity, ResolutionTier, ResolvedEdge } from './index.js';// ---------------------------------------------------------------------------@@ -157,11 +158,11 @@ export function patchActor(): string {}export function extractorName(): string {- return `tree-sitter/1.29`;+ return `tree-sitter/1.30`;}/** Previous extractor versions — their patches are superseded when re-ingesting. */-export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.28', 'tree-sitter/1.27', 'tree-sitter/1.26', 'tree-sitter/1.25', 'tree-sitter/1.24', 'tree-sitter/1.23', 'tree-sitter/1.22', 'tree-sitter/1.21', 'tree-sitter/1.20', 'tree-sitter/1.19', 'tree-sitter/1.18', 'tree-sitter/1.17', 'tree-sitter/1.16', 'tree-sitter/1.15', 'tree-sitter/1.14', 'tree-sitter/1.13', 'tree-sitter/1.12', 'tree-sitter/1.11', 'tree-sitter/1.10', 'tree-sitter/1.9', 'tree-sitter/1.8', 'tree-sitter/1.7', 'tree-sitter/1.6', 'tree-sitter/1.5', 'tree-sitter/1.4', 'tree-sitter/1.3', 'tree-sitter/1.2', 'tree-sitter/1.1'];+export const PREVIOUS_EXTRACTORS = ['tree-sitter/1.29', 'tree-sitter/1.28', 'tree-sitter/1.27', 'tree-sitter/1.26', 'tree-sitter/1.25', 'tree-sitter/1.24', 'tree-sitter/1.23', 'tree-sitter/1.22', 'tree-sitter/1.21', 'tree-sitter/1.20', 'tree-sitter/1.19', 'tree-sitter/1.18', 'tree-sitter/1.17', 'tree-sitter/1.16', 'tree-sitter/1.15', 'tree-sitter/1.14', 'tree-sitter/1.13', 'tree-sitter/1.12', 'tree-sitter/1.11', 'tree-sitter/1.10', 'tree-sitter/1.9', 'tree-sitter/1.8', 'tree-sitter/1.7', 'tree-sitter/1.6', 'tree-sitter/1.5', 'tree-sitter/1.4', 'tree-sitter/1.3', 'tree-sitter/1.2', 'tree-sitter/1.1'];/** Patch ids that may own the active graph entities for a stored source hash. */export function sourcePatchIdCandidates(@@ -255,6 +256,11 @@ export function buildPatch(multiRepo?: MultiRepoContext,): GraphPatchPayload {const { entities, chunks } = result;+ // A typed receiver call is resolved even within one file: its exact member+ // decides whether a receiver-only relationship becomes an edge at all.+ if (result.relationships.some(r => r.receiverType || r.receiverFactory)) {+ return buildPatchWithResolution(result, sourceHash, workspaceId, resolveEdges([result]), previousSourceHash, multiRepo);+ }// A helper-literal import is inferred and only means something once resolved// to a tracked file; without resolution it would be a dangling edge.const relationships = result.relationships.filter(r => r.importVia !== 'helper');@@ -599,8 +605,15 @@ export function buildPatchWithResolution(const { entities, chunks } = result;// A helper-literal import (see ParsedRelationship.importVia) is inferred from a// string, so it is emitted only when resolveEdges tied it to exactly one file.- const relationships = result.relationships.filter(r =>- r.importVia !== 'helper' || edgeResolution.has(`${r.srcName}:${r.predicate}:${r.dstName}`));+ const resolvedHere = (r: (typeof result.relationships)[number]): boolean =>+ edgeResolution.has(`${r.srcName}:${r.predicate}:${r.dstName}`);+ const relationships = [+ ...result.relationships.filter(r => !r.receiverOnly && (r.importVia !== 'helper' || resolvedHere(r))),+ // A receiver-only typed call (see ParsedRelationship.receiverOnly) exists only+ // once resolved. Last, so an edge the call's own relationship already wrote+ // keeps its id and only takes the type tier.+ ...result.relationships.filter(r => r.receiverOnly && resolvedHere(r)),+ ];// filePath = workspace-relative PROVENANCE (source_uri / file_uri / patch id);// idPath = member-relative IDENTITY (node / edge / chunk ids) so a member's ids are// byte-identical solo vs. co-ingested. Edge matching still keys on the full@@ -732,7 +745,7 @@ export function buildPatchWithResolution(}const seenExternalNodes2 = new Set<string>();- const emittedEdgeIdentities = new Set<string>();+ const emittedEdgeIdentities = new Map<string, PatchOp>();/** CALLS dropped for want of a destination node; recorded on their caller. */const unresolvedCalls = unresolvedCallRecorder(seenNodeIds2, fileNodeId2);const relationshipShapeCounts = new Map<string, number>();@@ -837,9 +850,7 @@ export function buildPatchWithResolution(for (const r of relationships) {const srcKey = resolveKey(r.srcName);- const dstKey = r.predicate === 'CONTAINS'- ? resolveKey(r.dstName, r.srcName)- : resolveKey(r.dstName);+ const dstKey = relationshipDstKey(r);const baseResolutionKey = `${r.srcName}:${r.predicate}:${r.dstName}`;const dst = resolveDst(r, dstKey);@@ -868,14 +879,20 @@ export function buildPatchWithResolution(// keys on id, both commit. An edge is identified by (src, dst, predicate) —// two of those with empty attrs are indistinguishable in the graph.const edgeIdentity = `${nodeId(idPath, srcKey)}\x00${dstNodeId}\x00${r.predicate}`;- if (emittedEdgeIdentities.has(edgeIdentity)) continue;- emittedEdgeIdentities.add(edgeIdentity);+ const emitted = emittedEdgeIdentities.get(edgeIdentity);+ if (emitted) {+ // A typed relationship confirming an edge the call already wrote.+ if (r.receiverOnly && resolution) {+ emitted.attrs = { confidence: resolution.confidence, ...(resolution.tier ? { tier: resolution.tier } : {}) };+ }+ continue;+ }// Only a colliding tuple is salted, so every other edge keeps the id it// had before this change.const idDstKey = collidingIdTuples.has(edgeIdTuple(srcKey, edgeDstKey, r.predicate))? `${edgeDstKey}\x00${dstNodeId}`: edgeDstKey;- ops.push({+ const edgeOp: PatchOp = {type: 'UpsertEdge',id: edgeId(idPath, srcKey, idDstKey, r.predicate),src: nodeId(idPath, srcKey),@@ -884,7 +901,9 @@ export function buildPatchWithResolution(attrs: resolution? { confidence: resolution.confidence, ...(resolution.tier ? { tier: resolution.tier } : {}) }: {},- });+ };+ emittedEdgeIdentities.set(edgeIdentity, edgeOp);+ ops.push(edgeOp);}unresolvedCalls.applyTo(ops);@@ -893,6 +912,8 @@ export function buildPatchWithResolution(// not part of a claim, so nothing downstream can tell them apart.const emittedClaims = new Set<string>();for (const r of relationships) {+ // A receiver-only typed call claims nothing the call's own relationship does not.+ if (r.receiverOnly) continue;const srcKey = resolveKey(r.srcName);const entityId = nodeId(idPath, srcKey);const field = `${r.predicate.toLowerCase()}:${r.dstName}`;diff --git a/core-ingestion/src/receiver-types.ts b/core-ingestion/src/receiver-types.tsnew file mode 100644index 00000000..1e28ccaf--- /dev/null+++ b/core-ingestion/src/receiver-types.ts@@ -0,0 +1,347 @@+// Copyright 2026 Ix Infrastructure Inc.++/** Conservative lexical inference. Unknown bindings deliberately stop lookup. */+export interface ReceiverType {+ type?: string;+ factory?: string;+}++export interface ReceiverFacts {+ factories: Array<[string, string]>;+ heritage: Array<[string, string]>;+ package?: string;+ /** Names some binding in the file gives a type or factory; no other name can resolve to one. */+ typedNames: ReadonlySet<string>;+ lookup(node: any): ReceiverType | undefined;+}++interface ReceiverBinding extends ReceiverType {+ available?: number;+ factoryNode?: any;+}++const classes = new Set(['class_definition', 'trait_definition', 'object_definition', 'class_declaration', 'abstract_class_declaration', 'class']);+const functions = new Set(['function_definition', 'function_declaration', 'method_declaration', 'method_definition', 'arrow_function', 'function_expression', 'func_literal', 'lambda_expression', 'method_signature', 'abstract_method_signature', 'function_signature']);+// Also the statements that own a binding of their own: Go `if x := …;`,+// `switch x := v.(type)`, Scala `case x: T =>` and `for (x <- xs)`.+// TypeScript functions that bind their own `this` (arrow functions do not).+const thisFunctions = new Set(['function_declaration', 'function_expression', 'generator_function', 'generator_function_declaration']);+const blocks = new Set(['block', 'statement_block', 'template_body', 'class_body', 'for_statement', 'for_in_statement', 'catch_clause',+ 'if_statement', 'expression_switch_statement', 'type_switch_statement', 'case_clause', 'for_expression']);++const bindingTypes = ['variable_declarator', 'public_field_definition', 'var_spec', 'val_definition', 'var_definition', 'val_declaration', 'var_declaration'];+const parameterTypes = ['required_parameter', 'optional_parameter', 'parameter', 'class_parameter', 'parameter_declaration'];+const mutationTypes = ['assignment_expression', 'augmented_assignment_expression', 'assignment_statement', 'assignment', 'update_expression'];+// Node types whose `name` field is read, and every non-scope type visited.+const named = new Set(['type_alias_declaration', ...classes, ...functions, ...bindingTypes, ...parameterTypes]);+const visited = new Set([...named, ...mutationTypes, 'short_var_declaration', 'range_clause', 'for_in_statement', 'case_clause', 'enumerator',+ 'type_switch_statement', 'catch_clause', 'infix_expression', 'type_definition', 'type_spec', 'type_alias']);+const isScope = (type: string): boolean =>+ classes.has(type) || functions.has(type) || blocks.has(type) || type === 'class_static_block' || type === 'internal_module';+// Every node type the walk stops at: the scopes and the visited types.+const walkedTypes = [...new Set([...classes, ...functions, ...blocks, 'class_static_block', 'internal_module', ...visited])];++function typeName(node: any): string | undefined {+ if (!node) return;+ if (node.type === 'type_annotation' || node.type === 'pointer_type') return typeName(node.firstNamedChild);+ if (node.type === 'generic_type') return typeName(node.childForFieldName('name') ?? node.firstNamedChild);+ // Unions, tuples, structural types and type parameters are not a concrete receiver.+ if (/^(?:type_identifier|identifier|qualified_type|nested_type_identifier|stable_type_identifier)$/.test(node.type)) {+ const text = node.text.replace(/\s/g, '');+ if (/^[\w$]+(?:\.[\w$]+)*$/.test(text)) return text;+ }+}++// The type names a class or function declares for its own body. Scala lists+// them as bare identifiers (under `parameters` on a function), a Go entry can+// declare several names, and a Go method receiver `Box[K, T]` redeclares them.+function declaredTypeParameters(node: any): string[] {+ const names: string[] = [];+ for (const list of node.namedChildren) {+ if (list.type !== 'type_parameters' && list.type !== 'type_parameter_list') continue;+ for (const p of list.namedChildren) {+ if (p.type === 'identifier' || p.type === 'type_identifier') names.push(p.text);+ else if (p.type !== 'annotation' && p.type !== 'type_parameters') {+ const declared = p.childrenForFieldName('name');+ if (declared.length) names.push(...declared.map((n: any) => n.text));+ else if (p.firstNamedChild) names.push(p.firstNamedChild.text);+ }+ }+ }+ let receiver = node.type === 'method_declaration' ? node.childForFieldName('receiver')?.firstNamedChild?.childForFieldName('type') : null;+ if (receiver?.type === 'pointer_type') receiver = receiver.firstNamedChild;+ for (const arg of receiver?.type === 'generic_type' ? receiver.childForFieldName('type_arguments')?.namedChildren ?? [] : []) {+ if (/^\w+$/.test(arg.text)) names.push(arg.text);+ }+ return names;+}++export function collectReceiverFacts(root: any, language: string, checkBudget: () => void): ReceiverFacts {+ const scopes = new Map<number, Map<string, ReceiverBinding>>();+ const typeParameters = new Map<number, Set<string>>();+ const factories: Array<[string, string]> = [];+ const heritage: Array<[string, string]> = [];+ // Scope ancestors of the node being visited, innermost last. Tracking them+ // during the walk avoids a parent-chain walk per node.+ const frames: Array<{ node: any; type: string; end: number }> = [];+ const scopeOf = (classOnly = false): any => {+ for (let i = frames.length - 1; i >= 0; i--) {+ const type = frames[i].type;+ if (classes.has(type) || (!classOnly && (functions.has(type) || blocks.has(type)))) return frames[i].node;+ }+ return root;+ };+ const functionScope = (): any => {+ // Static blocks and TypeScript namespaces also own their var declarations.+ for (let i = frames.length - 1; i >= 0; i--) {+ const type = frames[i].type;+ if (functions.has(type) || type === 'class_static_block' || type === 'internal_module') return frames[i].node;+ }+ return root;+ };+ const bind = (scope: any, name: string, info: ReceiverBinding): void => {+ if (!scopes.has(scope.id)) scopes.set(scope.id, new Map());+ scopes.get(scope.id)!.set(name, info);+ };+ const valueType = (value: any): ReceiverBinding => {+ if (!value) return {};+ if (value.type === 'new_expression') return { type: typeName(value.childForFieldName('constructor')) };+ if (value.type === 'instance_expression') return { type: typeName(value.firstNamedChild) };+ if (value.type === 'unary_expression' && value.text.startsWith('&')) return valueType(value.childForFieldName('operand'));+ if (value.type === 'composite_literal') return { type: typeName(value.childForFieldName('type')) };+ if (value.type === 'call_expression') {+ const fn = value.childForFieldName('function')?.text;+ if (fn && /^[\w$]+(?:\.[\w$]+)*$/.test(fn) && (language === 'scala' || /(?:^|\.)New\w+$/.test(fn))) {+ return { factory: fn, factoryNode: value.childForFieldName('function') };+ }+ }+ return {};+ };+ const mutations: any[] = [];+ // Every name a pattern binds. Scala pattern names start lowercase (an+ // uppercase one, or a dotted path, refers to an existing value).+ const bindPattern = (scope: any, pattern: any): void => {+ const pending = pattern ? [pattern] : [];+ while (pending.length) {+ const p = pending.pop()!;+ if (p.type === 'identifier' || p.type === 'shorthand_property_identifier_pattern') {+ if (language !== 'scala' || (/^[a-z_]/.test(p.text) && p.parent?.type !== 'stable_identifier')) bind(scope, p.text, {});+ } else pending.push(...p.namedChildren);+ }+ };+ const visit = (node: any, type: string): void => {+ const name = named.has(type) ? node.childForFieldName('name') : null;+ // A local type declaration shadows a same-named class (a package-level Go+ // `type_spec` is the class itself).+ const localType = ['type_definition', 'type_spec', 'type_alias'].includes(type) && scopeOf() !== root ? node.childForFieldName('name') : null;+ if ((type === 'type_alias_declaration' && name) || localType) {+ const scope = scopeOf();+ const names = typeParameters.get(scope.id) ?? new Set<string>();+ names.add((name ?? localType).text);+ typeParameters.set(scope.id, names);+ }+ if (classes.has(type) || functions.has(type)) {+ const generics = declaredTypeParameters(node);+ if (generics.length) typeParameters.set(node.id, new Set(generics));+ const singleParameter = node.childForFieldName('parameter');+ if (singleParameter?.type === 'identifier') bind(node, singleParameter.text, {});+ }+ if (language === 'scala' && classes.has(type)) {+ const extend = node.childForFieldName('extend');+ for (const parent of extend?.namedChildren ?? []) {+ const parentType = typeName(parent);+ if (name && parentType) heritage.push([name.text, parentType]);+ }+ if (type === 'class_definition' && /^(?:(?:final|sealed|private|protected|abstract)\s+)*case\s+class\b/.test(node.text)) factories.push([name.text, name.text]);+ }+ if (language === 'go' && type === 'function_declaration') {+ const result = typeName(node.childForFieldName('result'));+ if (name && result) factories.push([name.text, result]);+ }+ if (language === 'scala' && type === 'function_definition' && name?.text === 'apply') {+ const owner = scopeOf(true);+ const body = node.childForFieldName('body');+ const result = typeName(node.childForFieldName('return_type')) ?? valueType(body).type;+ const ownerName = owner.childForFieldName('name')?.text;+ // Keep unknown/overloaded apply definitions as blockers, including case-class companions.+ if (ownerName && owner.type === 'object_definition') {+ factories.push([`${ownerName}.apply`, result ?? '']);+ factories.push([ownerName, result ?? '']);+ }+ }+ let binding: any;+ let owner = scopeOf();+ if (language === 'typescript' && type === 'variable_declarator' && node.parent?.type === 'variable_declaration') {+ owner = functionScope();+ }+ if (['function_definition', 'function_declaration'].includes(type) && name && owner !== root && !classes.has(owner.type) && !['template_body', 'class_body'].includes(owner.type)) {+ bind(owner, name.text, {});+ }+ const declares = bindingTypes.includes(type) || parameterTypes.includes(type);+ const annotation = declares ? node.childForFieldName('type') : null;+ const value = declares ? node.childForFieldName('value') : null;+ if (['variable_declarator', 'public_field_definition', 'var_spec'].includes(type)) binding = name;+ if (['val_definition', 'var_definition', 'val_declaration', 'var_declaration'].includes(type) && language === 'scala') binding = node.childForFieldName('pattern');+ if (parameterTypes.includes(type)) {+ binding = name ?? node.childForFieldName('pattern');+ // Parameter-list nodes are not scopes; owner is their enclosing function/class.+ owner = scopeOf(type === 'class_parameter');+ if (language === 'typescript' && node.children.some((n: any) => n.type === 'accessibility_modifier' || n.type === 'readonly')) {+ if (binding?.type === 'identifier') bind(scopeOf(true), binding.text, { type: typeName(annotation) });+ }+ }+ if (type === 'short_var_declaration') {+ const left = node.childForFieldName('left')?.namedChildren ?? [];+ const right = node.childForFieldName('right')?.namedChildren ?? [];+ for (let i = 0; i < left.length; i++) if (left[i].type === 'identifier') bind(owner, left[i].text, { ...(left.length === right.length ? valueType(right[i]) : {}), available: node.endIndex });+ }+ if (type === 'range_clause') for (const id of node.childForFieldName('left')?.namedChildren ?? []) {+ if (id.type === 'identifier') bind(owner, id.text, {});+ }+ // Binders whose type is not inferred still shadow an outer receiver.+ if (type === 'for_in_statement') {+ const declared = node.children.some((c: any) => ['const', 'let', 'var'].includes(c.type));+ // `for (x of xs)` without a declaration assigns an existing binding.+ if (!declared) mutations.push(node);+ else bindPattern(node.children.some((c: any) => c.type === 'var') ? functionScope() : node, node.childForFieldName('left'));+ }+ if (type === 'lambda_expression') bindPattern(node, node.childForFieldName('parameters'));+ if (type === 'case_clause') bindPattern(node, node.childForFieldName('pattern'));+ if (type === 'enumerator') {+ const forExpression = scopeOf();+ if (forExpression.type === 'for_expression') bindPattern(forExpression, node.firstNamedChild);+ }+ if (type === 'type_switch_statement') bindPattern(node, node.childForFieldName('alias'));+ if (type === 'catch_clause') {+ const parameter = node.childForFieldName('parameter');+ if (parameter?.type === 'identifier') bind(node, parameter.text, {});+ }+ if (binding) {+ const info = typeName(annotation) ? { type: typeName(annotation) } : valueType(value);+ const local = ['variable_declarator', 'val_definition', 'var_definition', 'var_spec'].includes(type) &&+ !['template_body', 'class_body'].includes(owner.type);+ if (local) Object.assign(info, { available: node.endIndex });+ if (binding.type === 'identifier' || binding.type === 'property_identifier') bind(owner, binding.text, info);+ else {+ // A destructured binding shadows outer values even when its type is unknown.+ const pending = [binding];+ while (pending.length) {+ const p = pending.pop()!;+ if (p.type === 'identifier' || p.type === 'shorthand_property_identifier_pattern') bind(owner, p.text, {});+ pending.push(...p.namedChildren);+ }+ }+ // Go permits several names with a single annotation.+ if (language === 'go') for (const child of node.childrenForFieldName('name')) bind(owner, child.text, info);+ }+ if (mutationTypes.includes(type)) mutations.push(node);+ // Scala `x += y` on a var is `x = x + y` (comparisons are not assignments).+ if (type === 'infix_expression' && /^[^=]*[^=<>!]=$/.test(node.childForFieldName('operator')?.text ?? '')) mutations.push(node);+ };+ // Only scopes and the node types in `visited` carry facts. tree-sitter finds+ // them natively, in document order, so no other node is ever materialized.+ // A node after a scope in that order is inside it unless it starts at or+ // past the scope's end; only a zero-width node at the end is ambiguous.+ const within = (frame: { node: any; end: number }, node: any): boolean => {+ if (node.startIndex !== frame.end) return node.startIndex < frame.end;+ if (node.endIndex !== frame.end) return false;+ for (let p = node.parent; p; p = p.parent) if (p.id === frame.node.id) return true;+ return false;+ };+ for (const node of root.descendantsOfType(walkedTypes)) {+ // Types are matched by name, and `class` is also a keyword.+ if (!node.isNamed) continue;+ checkBudget();+ while (frames.length && !within(frames[frames.length - 1], node)) frames.pop();+ const type: string = node.type;+ visit(node, type);+ if (isScope(type)) frames.push({ node, type, end: node.endIndex });+ }+ const lookupName = (node: any, name: string, field = false): ReceiverType | undefined => {+ for (let p = node; p; p = p.parent) {+ // A non-arrow function or an object-literal method gives `this` a+ // value of its own, not the enclosing class instance.+ if (field && (thisFunctions.has(p.type) || (p.type === 'method_definition' && p.parent?.type !== 'class_body'))) return;+ if (field && !classes.has(p.type) && !['template_body', 'class_body'].includes(p.type)) continue;+ // A bare TypeScript name never refers to a field or parameter property.+ if (!field && language === 'typescript' && (classes.has(p.type) || p.type === 'class_body')) continue;+ const bindings = scopes.get(p.id);+ if (bindings?.has(name)) {+ const info = bindings.get(name)!;+ if (info.available !== undefined && info.available > node.startIndex) return {};+ if (info.type) for (let scope = node; scope; scope = scope.parent) {+ if (typeParameters.get(scope.id)?.has(info.type)) return {};+ }+ return info;+ }+ // A Scala anonymous class (`new T { … }`) is its own `this`.+ if (field && (classes.has(p.type) || (p.type === 'template_body' && !classes.has(p.parent?.type)))) return;+ }+ };+ // Package/companion return facts apply only when the call still names that+ // factory. A local variable, parameter or function can shadow its spelling.+ for (const bindings of scopes.values()) for (const info of bindings.values()) {+ if (info.factory && info.factoryNode && lookupName(info.factoryNode, info.factory.split('.')[0]) !== undefined) delete info.factory;+ }+ // Without dataflow, a reassigned binding is unknown throughout its scope.+ for (const node of mutations) {+ // Every name the target assigns: `x`, Go `x, y`, and destructuring+ // `[x] = …` / `({ a: x, y } = …)`. A member or index target (`o.x = …`)+ // assigns no binding.+ const pending = [node.childForFieldName('left') ?? node.childForFieldName('argument')];+ while (pending.length) {+ const id = pending.pop();+ if (!id || ['member_expression', 'subscript_expression', 'field_expression', 'selector_expression', 'index_expression'].includes(id.type)) continue;+ if (id.type === 'identifier' || id.type === 'shorthand_property_identifier_pattern') {+ const info = lookupName(node, id.text);+ if (info) { delete info.type; delete info.factory; }+ } else if (id.type === 'pair_pattern') pending.push(id.childForFieldName('value'));+ else pending.push(...id.namedChildren);+ }+ }+ const typedNames = new Set<string>();+ for (const bindings of scopes.values()) for (const [name, info] of bindings) if (info.type || info.factory) typedNames.add(name);+ return {+ factories, heritage, typedNames,+ // Chained Scala clauses (`package a` then `package b`) declare package `a.b`.+ package: language === 'scala'+ ? root.namedChildren.filter((node: any) => node.type === 'package_clause')+ .map((node: any) => node.childForFieldName('name')?.text).filter(Boolean).join('.') || undefined+ : language === 'go' ? root.namedChildren.find((node: any) => node.type === 'package_clause')?.firstNamedChild?.text : undefined,+ // A name no binding gives a type or factory skips the scope walk: it+ // cannot resolve to one, whatever binds it.+ lookup(node: any): ReceiverType | undefined {+ if (node.type === 'identifier') {+ const name = node.text;+ return typedNames.has(name) ? lookupName(node, name) : {};+ }+ if (node.type === 'member_expression' && node.childForFieldName('object')?.type === 'this') {+ const name = node.childForFieldName('property')?.text;+ return (typedNames.has(name) ? lookupName(node, name, true) : undefined) ?? {};+ }+ if (node.type === 'field_expression' && node.childForFieldName('value')?.text === 'this') {+ const name = node.childForFieldName('field')?.text;+ return (typedNames.has(name) ? lookupName(node, name, true) : undefined) ?? {};+ }+ },+ };+}++/**+ * The inferred receiver of a member call, given the call's member-name node:+ * `dep.run()` (TS), `dep.run()` (Scala), `dep.Run()` (Go). Only a receiver with+ * an inferred type or factory counts; `receiver` is its source text.+ */+export function callReceiver(nameNode: any, facts: ReceiverFacts): (ReceiverType & { receiver: string }) | undefined {+ if (facts.typedNames.size === 0) return;+ const member = nameNode.parent;+ const field = member?.type === 'member_expression' ? 'object'+ : member?.type === 'field_expression' ? 'value'+ : member?.type === 'selector_expression' ? 'operand' : undefined;+ const call = member?.parent;+ if (!field || call?.type !== 'call_expression' || call.childForFieldName('function')?.id !== member.id) return;+ const receiver = member.childForFieldName(field);+ if (!receiver || receiver.id === nameNode.id) return;+ const info = facts.lookup(receiver);+ return info?.type || info?.factory ? { type: info.type, factory: info.factory, receiver: receiver.text } : undefined;+}diff --git a/core-ingestion/src/symbol-index.ts b/core-ingestion/src/symbol-index.tsindex 80988335..392ea223 100644--- a/core-ingestion/src/symbol-index.ts+++ b/core-ingestion/src/symbol-index.ts@@ -28,6 +28,11 @@ export interface FileSummary {imports: Array<{ dstName: string; importRaw?: string; importVia?: string }>;/** `[fqcn, typeName]` for unambiguous PHP types. */phpTypes?: Array<[string, string]>;+ /** Receiver inference facts needed across incremental batches. */+ receiverFactories?: Array<[string, string]>;+ receiverHeritage?: Array<[string, string]>;+ receiverPackage?: string;+ importAliases?: Record<string, string>;/** Sorted unique names this file calls, references or extends (for IN-11). */refs: string[];/** Hash of what other files can resolve to here: qualified keys, exports, PHP types. */@@ -35,11 +40,33 @@ export interface FileSummary {}/** The part of a summary other files depend on, hashed. */-export function summarySignature(s: Pick<FileSummary, 'qkeys' | 'exportPublicNames' | 'phpTypes'>): string {- const canonical = JSON.stringify([+export function summarySignature(s: Pick<FileSummary, 'qkeys' | 'exportPublicNames' | 'phpTypes' | 'receiverFactories' | 'receiverHeritage' | 'receiverPackage'> & Partial<Pick<FileSummary, 'imports' | 'importAliases'>>): string {+ const parts: unknown[] = [[...s.qkeys].map(([n, q]) => `${n}\0${q}`).sort(),[...(s.exportPublicNames ?? [])].map(([p, l]) => `${p}\0${l}`).sort(),[...(s.phpTypes ?? [])].map(([f, t]) => `${f}\0${t}`).sort(),- ]);+ ];+ // Receiver facts only when present, so other files keep their signature.+ if (s.receiverFactories?.length || s.receiverHeritage?.length || s.receiverPackage) {+ parts.push(+ // A factory's return type resolves through this file's imports (and Go aliases).+ [...(s.receiverFactories ?? [])].map(([f, t]) => `${f}\0${t}\0${heritageImportsKey(s.imports, s.importAliases)}`).sort(),+ // A superclass resolves through this file's imports.+ [...(s.receiverHeritage ?? [])].map(([f, t]) => `${f}\0${t}\0${heritageImportsKey(s.imports)}`).sort(),+ s.receiverPackage ?? '',+ );+ }+ const canonical = JSON.stringify(parts);return crypto.createHash('sha256').update(canonical).digest('hex').slice(0, 32);}++/**+ * The imports a Scala superclass or a factory's return type resolves through,+ * as one key. Any import can pick the type (wildcards included), so all of+ * them count, and so do Go import aliases when given.+ */+export function heritageImportsKey(imports: Array<{ dstName: string }> | undefined, aliases?: Record<string, string>): string {+ const key = [...new Set((imports ?? []).map(i => i.dstName))].sort().join('\0');+ const named = Object.entries(aliases ?? {}).map(([a, m]) => `${a}=${m}`).sort().join('\0');+ return named ? `${key}\0\0${named}` : key;+}diff --git a/core-ingestion/test-fixtures/receiver-inference/cases.json b/core-ingestion/test-fixtures/receiver-inference/cases.jsonnew file mode 100644index 00000000..ee344115--- /dev/null+++ b/core-ingestion/test-fixtures/receiver-inference/cases.json@@ -0,0 +1,212 @@+[+ {+ "language": "scala",+ "name": "constructor parameter",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n class Use(dep: Target) { def use() = dep.run() }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "scala",+ "name": "field",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n class Use { val dep: Target = new Target();\n def use() = dep.run() }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "scala",+ "name": "typed val",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n object Use { def use() = { val dep: Target = new Target();\n dep.run() }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "scala",+ "name": "typed var",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n object Use { def use() = { var dep: Target = new Target();\n dep.run() }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "scala",+ "name": "new",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n object Use { def use() = { val dep = new Target();\n dep.run() }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "scala",+ "name": "typed parameter",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n object Use { def use(dep: Target) = dep.run() }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "typed parameter",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { dep.run();\n }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "annotated const",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use() { const dep: Target = new Target();\n dep.run();\n }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "annotated let",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use() { let dep: Target = new Target();\n dep.run();\n }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "new",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use() { let dep = new Target();\n dep.run();\n }",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "field",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nclass Use { dep: Target;\n use() { this.dep.run();\n }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "initialized field",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nclass Use { dep = new Target();\n use() { this.dep.run();\n }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "ts",+ "name": "parameter property",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nclass Use { constructor(private dep: Target) {}\nuse() { this.dep.run();\n }\n}",+ "expected": [+ "Target.run"+ ]+ },+ {+ "language": "go",+ "name": "literal",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use() { dep := Target{};\n dep.Run() }",+ "expected": [+ "Target.Run"+ ]+ },+ {+ "language": "go",+ "name": "pointer literal",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use() { dep := &Target{};\n dep.Run() }",+ "expected": [+ "Target.Run"+ ]+ },+ {+ "language": "go",+ "name": "var",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use() { var dep Target;\n dep.Run() }",+ "expected": [+ "Target.Run"+ ]+ },+ {+ "language": "go",+ "name": "pointer var",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use() { var dep *Target;\n dep.Run() }",+ "expected": [+ "Target.Run"+ ]+ },+ {+ "language": "go",+ "name": "factory",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func NewTarget() *Target { return &Target{}\n};\n func use() { dep := NewTarget();\n dep.Run() }",+ "expected": [+ "Target.Run"+ ]+ },+ {+ "language": "scala",+ "name": "shadow 18",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n object Use { def use(dep: Target) = { { val dep = unknown();\n dep.run() }\n}\n}",+ "expected": []+ },+ {+ "language": "scala",+ "name": "shadow 19",+ "source": "class Target { def run() = () };\n class Other { def run() = () };\n class Use(dep: Target) { def use(dep: Any) = dep.run() }",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 20",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { { const dep = unknown();\n dep.run();\n }\n}",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 21",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { function nested(dep) { dep.run();\n }\n}",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 22",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { const nested = dep => dep.run();\n }",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 23",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use<Target>(dep: Target) { dep.run();\n }",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 24",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { { dep.run();\n const dep = unknown();\n }\n}",+ "expected": []+ },+ {+ "language": "ts",+ "name": "shadow 25",+ "source": "class Target { run() {}\n}\nclass Other { run() {}\n}\nfunction use(dep: Target) { try {}\ncatch (dep) { dep.run();\n }\n}",+ "expected": []+ },+ {+ "language": "go",+ "name": "shadow 26",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use(dep *Target) { { dep := unknown();\n dep.Run() }\n}",+ "expected": []+ },+ {+ "language": "go",+ "name": "shadow 27",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use(dep *Target) { f := func(dep interface{}) { dep.Run() };\n _ = f }",+ "expected": []+ },+ {+ "language": "go",+ "name": "shadow 28",+ "source": "package p\ntype Target struct{};\n type Other struct{};\n func (t Target) Run() {};\n func (o Other) Run() {};\n func use(dep *Target) { for _, dep := range unknown() { dep.Run() }\n}",+ "expected": []+ }+]diff --git a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts b/ix-cli/src/cli/__tests__/helpers/fake-backend.tsindex 11aa3e63..d41c54a1 100644--- a/ix-cli/src/cli/__tests__/helpers/fake-backend.ts+++ b/ix-cli/src/cli/__tests__/helpers/fake-backend.ts@@ -21,6 +21,12 @@ function planMismatchBody(ids: string[]): Record<string, unknown> {};}+/** One live edge as a `graphSignature` line. */+function edgeLine(id: string, e: { src: unknown; dst: unknown; predicate: unknown; attrs?: unknown }): string {+ const attrs = (e.attrs ?? {}) as { tier?: unknown; confidence?: unknown };+ return `${id} ${String(e.src)} ${String(e.dst)} ${String(e.predicate)} tier=${String(attrs.tier)} confidence=${String(attrs.confidence)}`;+}+/** A backend that answers the endpoints an ingest touches, and records them. */export class FakeBackend {readonly requests: Array<{ path: string; patches: number; code?: number }> = [];@@ -210,7 +216,7 @@ export class FakeBackend {releaseVersion: string | null | undefined = undefined;private readonly nodes = new Map<string, { kind: unknown; name: unknown; attrs?: unknown; uri?: string; hash?: string; extractor?: string; live: boolean }>();private readonly edges = new Map<string, {- src: unknown; dst: unknown; predicate: unknown; workspaceId: string; uri: string; live: boolean;+ src: unknown; dst: unknown; predicate: unknown; attrs?: unknown; workspaceId: string; uri: string; live: boolean;}>();/** Every committed patch by id, with the rev it last landed at. */private readonly stored = new Map<string, {@@ -226,17 +232,24 @@ export class FakeBackend {/*** The live graph as a sorted, comparable list: nodes as `id kind name`,- * edges as `id src dst predicate`. Two backends hold the same graph exactly- * when their signatures are equal.+ * edges as `id src dst predicate tier=<tier> confidence=<confidence>`. The+ * resolution attrs are part of the line because an edge can be upgraded in+ * place (same id, new tier). Two backends hold the same graph exactly when+ * their signatures are equal.*/graphSignature(): { nodes: string[]; edges: string[] } {const nodes = [...this.nodes].filter(([, n]) => n.live).map(([id, n]) => `${id} ${String(n.kind)} ${String(n.name)}`).sort();- const edges = [...this.edges].filter(([, e]) => e.live)- .map(([id, e]) => `${id} ${String(e.src)} ${String(e.dst)} ${String(e.predicate)}`).sort();+ const edges = [...this.edges].filter(([, e]) => e.live).map(([id, e]) => edgeLine(id, e)).sort();return { nodes, edges };}+ /** Live edges whose `tier` attr is `tier`, as `graphSignature` lines. */+ edgesOfTier(tier: string): string[] {+ return [...this.edges].filter(([, e]) => e.live && (e.attrs as { tier?: unknown } | undefined)?.tier === tier)+ .map(([id, e]) => edgeLine(id, e)).sort();+ }+/** Names of the live nodes, to make a signature diff readable. */nodeName(id: string): string {const n = this.nodes.get(id);@@ -289,7 +302,7 @@ export class FakeBackend {this.nodes.set(id, { kind: op.kind, name: op.name, attrs: op.attrs, uri, hash: patch.source?.sourceHash, extractor: patch.source?.extractor, live: true });}else if (op.type === "UpsertEdge") {- this.edges.set(id, { src: op.src, dst: op.dst, predicate: op.predicate, workspaceId, uri, live: true });+ this.edges.set(id, { src: op.src, dst: op.dst, predicate: op.predicate, attrs: op.attrs, workspaceId, uri, live: true });}}if (patch.patchId === undefined) return;diff --git a/ix-cli/src/cli/__tests__/ingest-dependents.test.ts b/ix-cli/src/cli/__tests__/ingest-dependents.test.tsindex 47b0c92a..a6ac32ed 100644--- a/ix-cli/src/cli/__tests__/ingest-dependents.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-dependents.test.ts@@ -53,9 +53,9 @@ async function liveVsFresh(steps: Step[], predicate: string): Promise<{ live: st};const edges = (backend: FakeBackend): string[] =>backend.graphSignature().edges- .filter((line) => line.endsWith(` ${predicate}`))- .map((line) => {- const [, src, dst] = line.split(" ");+ .map((line) => line.split(" "))+ .filter(([, , , pred]) => pred === predicate)+ .map(([, src, dst]) => {// The target's id too: `x.foo` and `y.foo` share a name.return `${backend.nodeName(src!)} -> ${backend.nodeName(dst!)} ${dst}`;})diff --git a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts b/ix-cli/src/cli/__tests__/ingest-equivalence.test.tsindex 2ae31c56..a36f7506 100644--- a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts@@ -30,7 +30,8 @@ vi.mock("node:os", async (importOriginal) => {* sweeps the edges of the files it carries, `/v1/patch` does not, a patch id* seen before is not written again, and `/v1/source-hashes` reports the head* patch. Graphs are compared by `graphSignature()`: live nodes as- * `id kind name`, live edges as `id src dst predicate`.+ * `id kind name`, live edges as `id src dst predicate` plus their `tier` and+ * `confidence` attrs.** Each class of defect has a fixed scenario. A class that fails on `main` is* marked `it.fails` with the card that fixes it; that card deletes the marker,@@ -90,13 +91,17 @@ class World {/** Make the working tree match `repo`, and stage it so discovery sees it. */write(repo: Repo): void {const want = new Map([...repo].map(([p, fns]) => [p, render(p, fns)]));+ this.writeSources(want);+ }++ writeSources(want: Map<string, string>): void {for (const p of this.onDisk.keys()) if (!want.has(p)) rmSync(join(this.repo, p));for (const [p, text] of want) {if (this.onDisk.get(p) === text) continue;mkdirSync(dirname(join(this.repo, p)), { recursive: true });writeFileSync(join(this.repo, p), text, "utf8");}- this.onDisk = want;+ this.onDisk = new Map(want);execFileSync("git", ["add", "-A"], { cwd: this.repo, stdio: "ignore" });}@@ -139,8 +144,8 @@ class World {/** The lines two signatures disagree on, with edge endpoints named. */function signatureDiff(world: World, live: Signature, want: Signature): string {const named = (line: string) => {- const [id, src, dst, predicate] = line.split(" ");- return `${predicate} ${world.backend.nodeName(src!)} -> ${world.backend.nodeName(dst!)} (${id!.slice(0, 8)})`;+ const [id, src, dst, predicate, ...attrs] = line.split(" ");+ return `${predicate} ${world.backend.nodeName(src!)} -> ${world.backend.nodeName(dst!)} (${id!.slice(0, 8)}) ${attrs.join(" ")}`;};const out: string[] = [];for (const key of ["nodes", "edges"] as const) {@@ -223,6 +228,62 @@ describe("incremental ix map equals a fresh map (fake backend)", () => {await runSequence("head", []);});+ it("changing an intermediate Scala superclass re-resolves subclass callers", async () => {+ const world = new World("head");+ try {+ await world.start();+ const sources = new Map([+ ["a.scala", "trait A { def run() = () }\n"],+ ["b.scala", "trait B { def run() = () }\n"],+ ["mid.scala", "class Mid extends A {}\n"],+ ["child.scala", "class Child extends Mid {}\n"],+ ["use.scala", "object Use { def use(x: Child) = x.run() }\n"],+ ]);+ world.writeSources(sources);+ await world.map();+ const before = world.backend.graphSignature();+ sources.set("mid.scala", "class Mid extends B {}\n");+ world.writeSources(sources);+ await world.map();+ const live = world.backend.graphSignature();+ const fresh = await world.freshSignature();+ expect(fresh.edges).not.toEqual(before.edges);+ expect(signatureDiff(world, live, fresh)).toBe("");+ } finally {+ await world.stop();+ }+ });++ it("a superclass edit re-tiers a subclass caller's edge in place", async () => {+ // `x.run()` binds to A.run by name and by type, so the edge keeps its id;+ // only its tier and confidence depend on Child's parents in another file.+ const world = new World("head");+ try {+ await world.start();+ const sources = new Map([+ ["a.scala", "trait A { def run() = () }\n"],+ ["child.scala", "class Child extends A {}\n"],+ ["use.scala", "object Use { def use(x: Child) = x.run() }\n"],+ ]);+ world.writeSources(sources);+ await world.map();+ const [typed, ...more] = world.backend.edgesOfTier("type");+ expect(more, "one typed edge before the edit").toEqual([]);+ sources.set("child.scala", "class Child {}\n");+ world.writeSources(sources);+ await world.map();+ const live = world.backend.graphSignature();+ const fresh = await world.freshSignature();+ const id = typed!.split(" ")[0]!;+ const now = fresh.edges.find((line) => line.startsWith(`${id} `));+ expect(now, "the same edge, no longer typed").toBeDefined();+ expect(now).not.toEqual(typed);+ expect(signatureDiff(world, live, fresh)).toBe("");+ } finally {+ await world.stop();+ }+ });+it("a re-map with nothing changed commits nothing", async () => {// A revert to the first state is a second map of an unchanged tree.await runSequence("head", [{ kind: "revert", a: 0, b: 0 }], {diff --git a/ix-cli/src/cli/__tests__/ingest-receiver-extractor-bump.test.ts b/ix-cli/src/cli/__tests__/ingest-receiver-extractor-bump.test.tsnew file mode 100644index 00000000..25e6f9da--- /dev/null+++ b/ix-cli/src/cli/__tests__/ingest-receiver-extractor-bump.test.ts@@ -0,0 +1,165 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { execFileSync } from "node:child_process";++import { ingestFiles } from "../commands/ingest.js";+import { loadIngestionModules } from "../commands/ingestion-loader.js";+import { FakeBackend } from "./helpers/fake-backend.js";++/**+ * tree-sitter/1.30 adds receiver-type facts: `tier: type` CALLS edges and the+ * receiver fields of stored summaries. A graph built by 1.29 has neither, and+ * an unchanged file keeps its patch and summary until the extractor changes.+ * This checks that the extractor change alone brings such a graph to what a+ * fresh map writes, typed edges included (see `ingest-extractor-bump.test.ts`).+ *+ * The 1.29 graph is made by the current parser with its receiver facts+ * stripped from every parse result and summary, under the 1.29 extractor name+ * and patch ids.+ */++const OLD_EXTRACTOR = "tree-sitter/1.29";++const legacy = vi.hoisted(() => ({ on: false }));++vi.mock("../commands/ingestion-loader.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../commands/ingestion-loader.js")>();+ /** A parse result as 1.29 produced it: no receiver-only calls, no receiver fields. */+ const strip = (parsed: any): any => {+ if (!parsed || !Array.isArray(parsed.relationships)) return parsed;+ parsed.relationships = parsed.relationships.filter((r: any) => !r.receiverOnly);+ for (const r of parsed.relationships) { delete r.receiverType; delete r.receiverFactory; }+ delete parsed.receiverPackage; delete parsed.receiverFactories; delete parsed.receiverHeritage;+ return parsed;+ };+ return {+ ...actual,+ loadIngestionModules: async () => {+ const [ingestion, patchBuilder, languages] = await actual.loadIngestionModules();+ if (!legacy.on) return [ingestion, patchBuilder, languages];+ const asOldIngestion = {+ ...ingestion,+ parseFile: (...args: any[]) => strip((ingestion.parseFile as any)(...args)),+ summarizeParseResult: (parsed: any) => strip((ingestion.summarizeParseResult as any)(strip(parsed))),+ resolveEdges: (results: any[], ...rest: any[]) => (ingestion.resolveEdges as any)(results.map(strip), ...rest),+ };+ const asOldExtractor = {+ ...patchBuilder,+ extractorName: () => OLD_EXTRACTOR,+ buildPatchWithResolution: (parsed: any, hash: string, workspaceId: string, ...rest: any[]) => {+ const patch = (patchBuilder.buildPatchWithResolution as any)(strip(parsed), hash, workspaceId, ...rest);+ patch.patchId = patchBuilder.sourcePatchIdCandidates(parsed.filePath, hash, workspaceId)[+ (patchBuilder as unknown as { PREVIOUS_EXTRACTORS: string[] }).PREVIOUS_EXTRACTORS.indexOf(OLD_EXTRACTOR) + 1+ ];+ return patch;+ },+ };+ return [asOldIngestion, asOldExtractor, languages];+ },+ };+});++vi.mock("node:os", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:os")>();+ return { ...actual, cpus: () => actual.cpus().slice(0, 3) };+});++const ENV_KEYS = [+ "HOME", "USERPROFILE", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_HOME", "IX_DEBUG",+ "IX_COMMIT_FAILURE_LIMIT", "IX_COMMIT_HTTP_MAX_FILES", "IX_COMMIT_CONCURRENCY",+ "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS", "IX_MAP_DEADLINE_MS",+] as const;++/** Typed receivers whose member name alone is ambiguous, in each language. */+const SOURCES: Record<string, string> = {+ "ts/dep.ts": "export class Dep { run() {} }\nexport class Other { run() {} }\n",+ "ts/use.ts": "import { Dep } from './dep';\nexport function use(d: Dep) { d.run(); }\n",+ "go/types.go": "package p\n\ntype Target struct{}\n",+ "go/methods.go": "package p\n\nfunc (t Target) Run() {}\n\ntype Other struct{}\n\nfunc (o Other) Run() {}\n",+ "go/use.go": "package p\n\nfunc use(t Target) { t.Run() }\n",+ "scala/model.scala": "package model\nclass Target { def run() = () }\nclass Other { def run() = () }\n",+ "scala/use.scala": "import model.Target\nobject Use { def use(d: Target) = d.run() }\n",+};++describe("the tree-sitter/1.30 extractor bump", () => {+ vi.setConfig({ testTimeout: 120_000 });++ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-receiver-bump-")));+ const repoDir = join(root, "repo");+ const saved: Record<string, string | undefined> = {};++ beforeAll(() => {+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ mkdirSync(repoDir);+ execFileSync("git", ["init", "-q"], { cwd: repoDir, stdio: "ignore" });+ for (const [p, text] of Object.entries(SOURCES)) {+ mkdirSync(dirname(join(repoDir, p)), { recursive: true });+ writeFileSync(join(repoDir, p), text, "utf8");+ }+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ });+ afterAll(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+ });++ async function map(home: string, endpoint: string): Promise<string> {+ mkdirSync(home, { recursive: true });+ process.env.HOME = home;+ process.env.USERPROFILE = home;+ process.env.IX_ENDPOINT = endpoint;+ process.env.IX_LOCK_DIR = join(home, "locks");+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ await ingestFiles(repoDir, { recursive: true, format: "json", printSummary: false, suppressOutput: true, mapMode: true });+ return stderr.mock.calls.map(([chunk]) => String(chunk)).join("");+ } finally {+ stderr.mockRestore();+ }+ }++ it("re-ingests a 1.29 graph once and gains the fresh map's typed edges", async () => {+ const current = (await loadIngestionModules())[1].extractorName();+ const backend = new FakeBackend({ semantics: "head" });+ const fresh = new FakeBackend({ semantics: "head" });+ const home = join(root, "home");+ try {+ const endpoint = await backend.start();+ await map(join(root, "fresh-home"), await fresh.start());+ // One typed edge per language.+ expect(fresh.edgesOfTier("type"), "the fresh map").toHaveLength(3);++ legacy.on = true;+ await map(home, endpoint);+ legacy.on = false;+ expect(backend.edgesOfTier("type"), "the 1.29 graph").toEqual([]);+ expect(backend.graphSignature().edges).not.toEqual(fresh.graphSignature().edges);++ backend.resetRequests();+ const log = await map(home, endpoint);+ expect(log).toContain(`[extractor changed] ${OLD_EXTRACTOR} -> ${current}`);+ expect(backend.acceptedPatches(), "every file re-ingested").toBe(Object.keys(SOURCES).length);+ expect(backend.graphSignature()).toEqual(fresh.graphSignature());+ expect(backend.edgesOfTier("type")).toEqual(fresh.edgesOfTier("type"));++ // Once: the next map has nothing to do.+ backend.resetRequests();+ expect(await map(home, endpoint)).not.toContain("[extractor changed]");+ expect(backend.acceptedPatches()).toBe(0);+ } finally {+ legacy.on = false;+ await backend.stop();+ await fresh.stop();+ }+ });+});diff --git a/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.ts b/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.tsnew file mode 100644index 00000000..29b70a34--- /dev/null+++ b/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.ts@@ -0,0 +1,133 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { execFileSync } from "node:child_process";++import { ingestFiles } from "../commands/ingest.js";+import { FakeBackend } from "./helpers/fake-backend.js";++/**+ * A factory's return type (a Scala companion `apply`, a Go `NewX`) resolves in+ * the file that defines the factory: through its imports, its package and the+ * types visible there. A caller elsewhere types its receiver by that return+ * type. When only the defining file's imports change, or a type it can see+ * appears, the caller's typed edge must follow on the next incremental map, as+ * a fresh map would write it.+ *+ * Self-contained (no fast-check), so it runs where `ingest-equivalence` cannot.+ */++vi.mock("node:os", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:os")>();+ return { ...actual, cpus: () => actual.cpus().slice(0, 3) };+});++const ENV_KEYS = [+ "HOME", "USERPROFILE", "IX_ENDPOINT", "IX_LOCK_DIR", "IX_HOME", "IX_DEBUG",+ "IX_COMMIT_FAILURE_LIMIT", "IX_COMMIT_HTTP_MAX_FILES", "IX_COMMIT_CONCURRENCY",+ "IX_STITCH_COOLDOWN_MS", "IX_STITCH_WAIT_MS", "IX_MAP_DEADLINE_MS",+] as const;++type Sources = Record<string, string>;++const SCALA_BASE: Sources = {+ "other/Target.scala": "package other\nclass Target { def run() = () }\n",+ "third/Target.scala": "package third\nclass Target { def run() = () }\n",+ "app/Mk.scala": "package app\nimport other.Target\nobject Mk { def apply(): Target = new Target() }\n",+ "app/Use.scala": "package app\nobject Use { def use() = { val x = Mk(); x.run() } }\n",+};++const GO_BASE: Sources = {+ "go.mod": "module example.com/x\n\ngo 1.22\n",+ "other/target.go": "package other\n\ntype Target struct{}\n\nfunc (t Target) Run() {}\n",+ "third/target.go": "package third\n\ntype Target struct{}\n\nfunc (t Target) Run() {}\n",+ "app/mk.go": "package app\n\nimport m \"example.com/x/other\"\n\nfunc NewThing() m.Target { return m.Target{} }\n",+ "app/use.go": "package app\n\nfunc use() {\n\tx := NewThing()\n\tx.Run()\n}\n",+};++const SCENARIOS: Array<[string, Sources, Sources]> = [+ ["a Scala factory file changes only its import", SCALA_BASE,+ { "app/Mk.scala": "package app\nimport third.Target\nobject Mk { def apply(): Target = new Target() }\n" }],+ ["a Go factory file changes only its import path", GO_BASE,+ { "app/mk.go": "package app\n\nimport m \"example.com/x/third\"\n\nfunc NewThing() m.Target { return m.Target{} }\n" }],+ ["a type the Scala factory file can see appears in another file",+ {+ ...SCALA_BASE,+ "third/Target.scala": "package third\nclass Unrelated\n",+ "app/Mk.scala": "package app\nimport other._\nimport third._\nobject Mk { def apply(): Target = new Target() }\n",+ },+ { "third/Target.scala": "package third\nclass Target { def stop() = () }\n" }],+];++describe("incremental map follows factory return types (fake backend)", () => {+ vi.setConfig({ testTimeout: 120_000 });++ const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ix-receiver-incremental-")));+ const saved: Record<string, string | undefined> = {};+ let run = 0;++ beforeAll(() => {+ for (const k of ENV_KEYS) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+ });+ afterAll(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ rmSync(root, { recursive: true, force: true });+ });++ function write(repoDir: string, sources: Sources): void {+ for (const [p, text] of Object.entries(sources)) {+ mkdirSync(dirname(join(repoDir, p)), { recursive: true });+ writeFileSync(join(repoDir, p), text, "utf8");+ }+ execFileSync("git", ["add", "-A"], { cwd: repoDir, stdio: "ignore" });+ }++ async function map(repoDir: string, home: string, endpoint: string): Promise<void> {+ mkdirSync(home, { recursive: true });+ process.env.HOME = home;+ process.env.USERPROFILE = home;+ process.env.IX_ENDPOINT = endpoint;+ process.env.IX_LOCK_DIR = join(home, "locks");+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ try {+ await ingestFiles(repoDir, { recursive: true, format: "json", printSummary: false, suppressOutput: true, mapMode: true });+ } finally {+ stderr.mockRestore();+ }+ }++ it.each(SCENARIOS)("%s", async (_name, base, edit) => {+ const dir = join(root, `run-${run++}`);+ const repoDir = join(dir, "repo");+ mkdirSync(repoDir, { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repoDir, stdio: "ignore" });+ const live = new FakeBackend({ semantics: "head" });+ const fresh = new FakeBackend({ semantics: "head" });+ try {+ const endpoint = await live.start();+ write(repoDir, base);+ await map(repoDir, join(dir, "home"), endpoint);+ const before = live.edgesOfTier("type");+ expect(before, "the caller's typed edge before the edit").toHaveLength(1);++ write(repoDir, edit);+ await map(repoDir, join(dir, "home"), endpoint);+ await map(repoDir, join(dir, "fresh-home"), await fresh.start());+ expect(fresh.edgesOfTier("type"), "the edit moves or drops the typed edge").not.toEqual(before);+ expect(live.edgesOfTier("type")).toEqual(fresh.edgesOfTier("type"));+ expect(live.graphSignature()).toEqual(fresh.graphSignature());+ } finally {+ await live.stop();+ await fresh.stop();+ }+ });+});diff --git a/ix-cli/src/cli/__tests__/ingest-symbols.test.ts b/ix-cli/src/cli/__tests__/ingest-symbols.test.tsindex 01a0f6ab..9cd7eb00 100644--- a/ix-cli/src/cli/__tests__/ingest-symbols.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-symbols.test.ts@@ -187,6 +187,43 @@ describe("dependents (IN-11)", () => {const summary = (filePath: string, fields: Record<string, unknown>) => ({ filePath, ...fields });const entry = (s: ReturnType<typeof summary>): SymbolEntry => ({ hash: "h", summary: s });+ it("propagates changed superclass bindings to transitive subclass callers", () => {+ const before = summary("mid.scala", { receiverHeritage: [["Mid", "A"]] });+ const after = summary("mid.scala", { receiverHeritage: [["Mid", "B"]] });+ const table = new Map([+ ["mid.scala", entry(after)],+ ["child.scala", entry(summary("child.scala", { receiverHeritage: [["Child", "Mid"]], refs: ["Mid"] }))],+ ["leaf.scala", entry(summary("leaf.scala", { receiverHeritage: [["Leaf", "Child"]], refs: ["Child"] }))],+ ["use.scala", entry(summary("use.scala", { refs: ["Leaf.run"] }))],+ ["unrelated.scala", entry(summary("unrelated.scala", { refs: ["Other.run"] }))],+ ]);+ expect(findDependents(table, changedNames(before, after), [], new Set(["mid.scala"])))+ .toEqual(["child.scala", "leaf.scala", "use.scala"]);+ });++ it("propagates inheritance through excluded files and terminates on cycles", () => {+ const table = new Map([+ ["a.scala", entry(summary("a.scala", { receiverHeritage: [["A", "B"]], refs: ["B"] }))],+ ["b.scala", entry(summary("b.scala", { receiverHeritage: [["B", "A"]], refs: ["A"] }))],+ ["use.scala", entry(summary("use.scala", { refs: ["B.run"] }))],+ ]);+ const names = new Set(["A"]);+ expect(findDependents(table, names, [], new Set(["a.scala", "b.scala"]))).toEqual(["use.scala"]);+ expect(names).toEqual(new Set(["A"]));+ });++ it.each(["receiverFactories", "receiverHeritage"])("invalidates dependents when %s changes", (field) => {+ const before = summary("target", { sig: "before", [field]: [["Target", "Base"]] });+ const after = summary("target", { sig: "after", [field]: [["Target", "Other"]] });+ expect(changedNames(before, after)).toEqual(new Set(["Target"]));+ });++ it("invalidates a subclass when only its file's imports pick a different superclass", () => {+ const before = summary("child.scala", { sig: "before", receiverHeritage: [["Child", "Parent"]], imports: [{ dstName: "p1.Parent" }] });+ const after = summary("child.scala", { sig: "after", receiverHeritage: [["Child", "Parent"]], imports: [{ dstName: "p2.Parent" }] });+ expect(changedNames(before, after)).toEqual(new Set(["Child"]));+ });+it("changes no names when the signature is the same, and the symmetric difference otherwise", () => {const before = summary("m.ts", { sig: "s1", qkeys: [["add", "add"], ["sub", "sub"]] });expect(changedNames(before, summary("m.ts", { sig: "s1", qkeys: [["add", "add"], ["sub", "sub"]] }))).toEqual(new Set());@@ -232,11 +269,21 @@ describe("dependents (IN-11)", () => {expect(findDependents(table, new Set(), ["web/a.ts"], new Set())).toEqual(["uses-a.ts", "uses-pkg-a.py"]);});- it("hashes a patch's edges and their targets, in any order, and nothing else", () => {+ it("hashes a patch's edges and their targets, in any order, and no other op", () => {const a = { type: "UpsertEdge", id: "e1", dst: "n1" };const b = { type: "UpsertEdge", id: "e2", dst: "n2" };const node = { type: "UpsertNode", id: "n9" };expect(resolutionHash([a, b, node])).toBe(resolutionHash([b, a]));expect(resolutionHash([a, b])).not.toBe(resolutionHash([a, { ...b, dst: "n3" }]));});++ it("hashes an edge's tier and confidence, so a re-tiered edge with the same id and target counts", () => {+ const typed = { type: "UpsertEdge", id: "e1", dst: "n1", attrs: { confidence: 0.95, tier: "type" } };+ const global = { ...typed, attrs: { confidence: 0.5, tier: "global" } };+ expect(resolutionHash([typed])).not.toBe(resolutionHash([global]));+ expect(resolutionHash([typed])).toBe(resolutionHash([{ ...typed, attrs: { tier: "type", confidence: 0.95, other: 1 } }]));+ // An edge with no resolution attrs hashes as it always has.+ expect(resolutionHash([{ type: "UpsertEdge", id: "e1", dst: "n1", attrs: {} }]))+ .toBe(resolutionHash([{ type: "UpsertEdge", id: "e1", dst: "n1" }]));+ });});diff --git a/ix-cli/src/cli/__tests__/stitch-call-entry.test.ts b/ix-cli/src/cli/__tests__/stitch-call-entry.test.tsnew file mode 100644index 00000000..d755d8ca--- /dev/null+++ b/ix-cli/src/cli/__tests__/stitch-call-entry.test.ts@@ -0,0 +1,25 @@+// Copyright 2026 Ix Infrastructure Inc.++import { describe, expect, it } from "vitest";++import { stitchCallEntry } from "../commands/ingest.js";++describe("stitchCallEntry", () => {+ it("offers a call's own relationship to the cross-repo stitch", () => {+ expect(stitchCallEntry({ predicate: "CALLS", srcName: "use", dstName: "run" }, "src/use.ts"))+ .toEqual({ symbol: "run", caller: "use", callerFilePath: "src/use.ts" });+ });++ it("never offers a receiver-only typed call", () => {+ const rels = [+ { predicate: "CALLS", srcName: "use", dstName: "run" },+ { predicate: "CALLS", srcName: "use", dstName: "Dep.run", receiverType: "Dep", receiverOnly: true },+ ];+ expect(rels.map((r) => stitchCallEntry(r, "src/use.ts")?.symbol).filter(Boolean)).toEqual(["run"]);+ });++ it("skips non-calls and builtin member names", () => {+ expect(stitchCallEntry({ predicate: "IMPORTS", srcName: "use.ts", dstName: "dep" }, "src/use.ts")).toBeUndefined();+ expect(stitchCallEntry({ predicate: "CALLS", srcName: "use", dstName: "forEach" }, "src/use.ts")).toBeUndefined();+ });+});diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex c4fe12dc..41356d81 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -2103,6 +2103,24 @@ export function describeCommitOutcome(};}+// Builtin instance-method names that are never a real cross-repo call target.+const STITCH_COMMODITY = new Set(['map', 'forEach', 'reduce', 'reduceRight', 'flatMap', 'flat', 'push', 'pop', 'shift', 'unshift', 'splice', 'slice', 'concat', 'get', 'set', 'has', 'keys', 'values', 'entries', 'then', 'catch', 'finally', 'resolve', 'race', 'allSettled', 'bind', 'call', 'apply', 'stringify', 'toString', 'valueOf', 'hasOwnProperty']);++/**+ * The cross-repo stitch entry a parsed relationship contributes, if any. A+ * receiver-only typed call (ParsedRelationship.receiverOnly) names a target+ * inferred from a local receiver's type; it is written only when it resolves+ * in this workspace, so it is never a cross-repo call candidate.+ */+export function stitchCallEntry(+ rel: { predicate?: unknown; dstName?: unknown; srcName?: unknown; receiverOnly?: unknown },+ filePath: string,+): { symbol: string; caller: string; callerFilePath: string } | undefined {+ if (rel.predicate !== 'CALLS' || rel.receiverOnly || typeof rel.dstName !== 'string' || typeof rel.srcName !== 'string') return undefined;+ if (STITCH_COMMODITY.has(rel.dstName)) return undefined;+ return { symbol: rel.dstName, caller: rel.srcName, callerFilePath: filePath };+}+/*** Did the run finish with the graph fully matching what it set out to ingest?*@@ -2291,8 +2309,6 @@ export async function ingestFiles(// {filePath, local entity name, public name} -> add an export entry by public name.const stitchExportAliases: Array<{ filePath: string; local: string; pub: string }> = [];const stitchExportAliasSeen = new Set<string>();- // Builtin instance-method names that are never a real cross-repo call target.- const STITCH_COMMODITY = new Set(['map', 'forEach', 'reduce', 'reduceRight', 'flatMap', 'flat', 'push', 'pop', 'shift', 'unshift', 'splice', 'slice', 'concat', 'get', 'set', 'has', 'keys', 'values', 'entries', 'then', 'catch', 'finally', 'resolve', 'race', 'allSettled', 'bind', 'call', 'apply', 'stringify', 'toString', 'valueOf', 'hasOwnProperty']);const specToPkg = (spec: string | undefined): string | null => {if (!spec || spec.startsWith('.') || spec.startsWith('/')) return null;if (spec.startsWith('@')) { const parts = spec.split('/'); return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null; }@@ -2323,9 +2339,8 @@ export async function ingestFiles(stitchExportAliases.push({ filePath: p.filePath, local: x.local, pub: x.public });}for (const rel of (p.relationships ?? [])) {- if (rel.predicate === 'CALLS' && typeof rel.dstName === 'string' && typeof rel.srcName === 'string' && !STITCH_COMMODITY.has(rel.dstName)) {- stitchCalls.push({ symbol: rel.dstName, caller: rel.srcName, callerFilePath: p.filePath });- }+ const call = stitchCallEntry(rel, p.filePath);+ if (call) stitchCalls.push(call);if (rel.predicate !== 'IMPORTS') continue;const pkg = specToPkg(typeof rel.importRaw === 'string' ? rel.importRaw : rel.dstName);if (!pkg || !stitchProdDeps.has(pkg)) continue;@@ -2679,7 +2694,7 @@ export async function ingestFiles(const resolveStats = {importLookups: 0, transitiveLookups: 0, globalFallbacks: 0,globalCandidateTotal: 0, resolvedImport: 0, resolvedTransitive: 0,- resolvedGlobal: 0, resolvedQualifier: 0, skippedSameFile: 0, skippedAmbiguous: 0,+ resolvedGlobal: 0, resolvedQualifier: 0, resolvedType: 0, skippedSameFile: 0, skippedAmbiguous: 0,};// Per-language parse timing: language → { ms, files }const langParseMs = new Map<string, { ms: number; files: number }>();@@ -5391,6 +5406,7 @@ export async function ingestFiles(console.log(chalk.dim(` resolved transitive:${resolveStats.resolvedTransitive}`));console.log(chalk.dim(` resolved global: ${resolveStats.resolvedGlobal}`));console.log(chalk.dim(` resolved qualifier: ${resolveStats.resolvedQualifier}`));+ console.log(chalk.dim(` resolved type: ${resolveStats.resolvedType}`));console.log(chalk.dim(` skipped same-file: ${resolveStats.skippedSameFile}`));console.log(chalk.dim(` skipped ambiguous: ${resolveStats.skippedAmbiguous}`));}diff --git a/ix-cli/src/cli/ingest-symbols.ts b/ix-cli/src/cli/ingest-symbols.tsindex fb623dbe..e2f03869 100644--- a/ix-cli/src/cli/ingest-symbols.ts+++ b/ix-cli/src/cli/ingest-symbols.ts@@ -50,8 +50,8 @@ export interface SymbolEntry {summary: StoredSummary;/*** What the file's patch resolved its edges to, recorded when the patch is- * built from these bytes: a hash of its edge ids and their targets- * (`resolutionHash`). A re-resolution's re-send records it only once it lands. An unchanged file is+ * built from these bytes: a hash of its edge ids, their targets and their+ * tier/confidence (`resolutionHash`). A re-resolution's re-send records it only once it lands. An unchanged file is* re-sent when names it uses change elsewhere, and only if this differs.*/res?: string;@@ -65,14 +65,20 @@ export interface SymbolEntry {}/**- * A hash of a patch's edges and where they point. Same bytes resolved against- * the same names gives the same value, so it changes exactly when something- * the file refers to moved, appeared or went away.+ * A hash of a patch's edges, where they point and how they were resolved.+ * Same bytes resolved against the same names gives the same value, so it+ * changes exactly when something the file refers to moved, appeared or went+ * away -- or when an edge keeps its id and target but its `tier`/`confidence`+ * changes (a receiver's type learned or lost through another file).*/-export function resolutionHash(ops: ReadonlyArray<{ type?: unknown; id?: unknown; dst?: unknown }>): string {+export function resolutionHash(ops: ReadonlyArray<{ type?: unknown; id?: unknown; dst?: unknown; attrs?: unknown }>): string {const pairs = ops.filter(op => op.type === "UpsertEdge")- .map(op => `${String(op.id)}>${String(op.dst)}`)+ .map(op => {+ const { tier, confidence } = (op.attrs ?? {}) as { tier?: unknown; confidence?: unknown };+ const how = tier === undefined && confidence === undefined ? "" : ` ${String(tier)}/${String(confidence)}`;+ return `${String(op.id)}>${String(op.dst)}${how}`;+ }).sort();return createHash("sha256").update(pairs.join("\n")).digest("hex");}@@ -304,6 +310,10 @@ type SummaryFields = {qkeys?: Array<[string, string]>;exportPublicNames?: Array<[string, string]>;phpTypes?: Array<[string, string]>;+ receiverFactories?: Array<[string, string]>;+ receiverHeritage?: Array<[string, string]>;+ receiverPackage?: string;+ importAliases?: Record<string, string>;refs?: string[];imports?: Array<{ dstName?: string; importRaw?: string }>;sig?: string;@@ -330,9 +340,15 @@ function bindings(summary: StoredSummary | undefined): Map<string, string[]> {const out = new Map<string, string[]>();if (!summary) return out;const s = summary as SummaryFields;- for (const [name, qkey] of s.qkeys ?? []) out.set(`q\0${name}\0${qkey}`, [name, qkey]);+ for (const [name, qkey] of s.qkeys ?? []) out.set(`q\0${s.receiverPackage ?? ''}\0${name}\0${qkey}`, [name, qkey]);for (const [publicName, local] of s.exportPublicNames ?? []) out.set(`e\0${publicName}\0${local}`, [publicName]);for (const [fqcn, typeName] of s.phpTypes ?? []) out.set(`p\0${fqcn}\0${typeName}`, [fqcn, typeName]);+ // A superclass and a factory's return type resolve through this file's+ // imports (and Go import aliases), so they are part of the key.+ const heritageImports = [...new Set((s.imports ?? []).map(i => i.dstName ?? ""))].sort().join("\0");+ const aliases = Object.entries(s.importAliases ?? {}).map(([a, m]) => `${a}=${m}`).sort().join("\0");+ for (const [name, type] of s.receiverFactories ?? []) out.set(`f\0${name}\0${type}\0${heritageImports}\0\0${aliases}`, [name]);+ for (const [name, base] of s.receiverHeritage ?? []) out.set(`h\0${name}\0${base}\0${heritageImports}`, [name]);return out;}@@ -400,16 +416,45 @@ export function findDependents(if (stem.length > 0 && stem !== ".") stems.add(stem);}if (names.size === 0 && stems.size === 0) return [];+ // A changed superclass changes the members visible through every subclass,+ // even when those subclass files were not edited (or were already sent).+ // Likewise a changed type changes what every factory returning it gives a+ // caller's receiver (a Scala `apply`, a Go `NewX`), so the factory counts too.+ const inheritors = new Map<string, Set<string>>();+ const dependsOn = (type: string, name: string) => {+ for (const key of new Set([type, type.split(".").pop()!])) {+ const children = inheritors.get(key) ?? new Set<string>();+ children.add(name);+ inheritors.set(key, children);+ }+ };+ for (const entry of table.values()) {+ const s = entry.summary as SummaryFields;+ for (const [child, parent] of s.receiverHeritage ?? []) {+ dependsOn(parent, child);+ if (s.receiverPackage) dependsOn(parent, `${s.receiverPackage}.${child}`);+ }+ for (const [factory, type] of s.receiverFactories ?? []) if (type) dependsOn(type, factory);+ }+ const affectedNames = new Set(names);+ const pending = [...affectedNames];+ for (let i = 0; i < pending.length; i++) {+ for (const child of inheritors.get(pending[i]) ?? []) {+ if (affectedNames.has(child)) continue;+ affectedNames.add(child);+ pending.push(child);+ }+ }const out: string[] = [];for (const [rel, entry] of table) {if (exclude.has(rel)) continue;const s = entry.summary as SummaryFields;- const byName = names.size > 0 && (s.refs ?? []).some(ref => {- if (names.has(ref)) return true;+ const byName = affectedNames.size > 0 && (s.refs ?? []).some(ref => {+ if (affectedNames.has(ref)) return true;// Most refs are plain names; splitting each costs more than the rest of the scan.if (!REF_SEPARATOR.test(ref)) return false;const parts = ref.split(/::|->|\.|#|\\/).filter(Boolean);- return parts.length > 1 && (names.has(parts[0]) || names.has(parts[parts.length - 1]));+ return parts.length > 1 && (affectedNames.has(parts[0]) || affectedNames.has(parts[parts.length - 1]));});// By path segment, not substring: an added `a.ts` must not match every// import with an "a" in it.