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): Java call edges via typed receivers and dispatch callers (#878)
Ian Hocka7caca30c826
diff --git a/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts b/core-ingestion/src/__tests__/patchBuilder.endpoints.test.tsindex 8bba2771..0ed87bbf 100644--- a/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts+++ b/core-ingestion/src/__tests__/patchBuilder.endpoints.test.ts@@ -66,7 +66,7 @@ describe('every edge has a node at both ends', () => {const crossFile = edges.filter((e) => e.attrs.confidence !== undefined);expect(crossFile.length).toBeGreaterThan(10);for (const e of crossFile) {- expect(['binding', 'import', 'transitive', 'qualifier', 'global']).toContain(e.attrs.tier);+ expect(['type', 'binding', 'import', 'transitive', 'qualifier', 'global']).toContain(e.attrs.tier);}});diff --git a/core-ingestion/src/__tests__/receiver-inference.java.test.ts b/core-ingestion/src/__tests__/receiver-inference.java.test.tsnew file mode 100644index 00000000..122a2179--- /dev/null+++ b/core-ingestion/src/__tests__/receiver-inference.java.test.ts@@ -0,0 +1,259 @@+// Copyright 2026 Ix Infrastructure Inc.++import * as fs from 'node:fs';+import * as path from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import { buildGlobalResolutionIndex, parseFile, resolveEdges, summarizeParseResult, type FileParseResult } from '../index.js';+import { buildPatchWithResolution } from '../patch-builder.js';++const FIXTURE = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../test-fixtures/java-receivers');++const parse = (filePath: string, source: string): FileParseResult => {+ const result = parseFile(filePath, source)!;+ expect(result).not.toBeNull();+ expect(result.hasParseErrors).toBeUndefined();+ return result;+};++function fixture(): FileParseResult[] {+ const walk = (dir: string): string[] => fs.readdirSync(dir, { withFileTypes: true })+ .flatMap(e => e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)]);+ return walk(FIXTURE).filter(f => f.endsWith('.java')).sort()+ .map(f => parse(`/repo/${path.relative(FIXTURE, f).split(path.sep).join('/')}`, fs.readFileSync(f, 'utf8')));+}++/** Every CALLS edge the patches write, as `file::name` of both ends. */+function callEdges(results: FileParseResult[], edges = resolveEdges(results)): Array<{ src: string; dst: string; tier?: string }> {+ const patches = results.map(r => buildPatchWithResolution(r, 'hash', 'workspace', edges));+ const names = new Map<string, string>();+ results.forEach((r, i) => {+ for (const op of patches[i].ops as any[]) if (op.type === 'UpsertNode') names.set(op.id, `${r.filePath.replace('/repo/', '')}::${op.name}`);+ });+ return patches.flatMap(p => (p.ops as any[]).filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS')+ .map(op => ({ src: names.get(op.src) ?? op.src, dst: names.get(op.dst) ?? op.dst, tier: op.attrs?.tier })));+}++const typedEdges = (edges: ReturnType<typeof resolveEdges>, srcName?: string) =>+ edges.filter(e => e.tier === 'type' && (srcName === undefined || e.srcName === srcName));++// Provider and caller in different packages; `Other` declares a same-named member.+const provider = (extra = '') => [+ parse('/repo/p/Target.java', `package p;\npublic class Target {\n public void run() {}\n public Target self() { return this; }\n${extra}}\n`),+ parse('/repo/p/Other.java', 'package p;\npublic class Other {\n public void run() {}\n}\n'),+];+const caller = (body: string, members = '') => parse('/repo/q/Use.java',+ `package q;\nimport p.Target;\nimport p.Other;\nimport java.util.List;\npublic class Use {\n${members} void use(Target param, List<Target> list) {\n ${body}\n }\n}\n`);++describe('Java typed receivers (fixture)', () => {+ const results = fixture();+ const edges = resolveEdges(results);++ it('resolves a member call through a typed local, parameter, field and this.field to the declared class', () => {+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstName: 'URL.getMethodParameter',+ dstFilePath: '/repo/com/acme/common/URL.java', dstQualifiedKey: 'URL.getMethodParameter', tier: 'type', confidence: 0.95,+ }));+ });++ it('resolves a call through an interface-typed field to the interface method', () => {+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstFilePath: '/repo/com/acme/common/Node.java', dstQualifiedKey: 'Node.isAvailable', tier: 'type',+ }));+ });++ it('resolves a method only a superclass declares, two levels up', () => {+ // `var service = new ServiceUrl(..)`: ServiceUrl -> URL -> AbstractURL.+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstName: 'ServiceUrl.getProtocol',+ dstFilePath: '/repo/com/acme/common/AbstractURL.java', dstQualifiedKey: 'AbstractURL.getProtocol', tier: 'type',+ }));+ });++ it('resolves super.m() to the superclass, never the overriding method itself', () => {+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'ServiceUrl.getMethodParameter', dstFilePath: '/repo/com/acme/common/URL.java', dstQualifiedKey: 'URL.getMethodParameter', tier: 'type',+ }));+ expect(callEdges(results, edges)).not.toContainEqual(expect.objectContaining({+ src: 'com/acme/rpc/ServiceUrl.java::getMethodParameter', dst: 'com/acme/rpc/ServiceUrl.java::getMethodParameter',+ }));+ });++ it('resolves this.m() and a bare m() through the enclosing class and its supertypes', () => {+ expect(typedEdges(edges, 'ServiceUrl.describe').map(e => e.dstQualifiedKey).sort()).toEqual(['AbstractURL.getProtocol', 'URL.getHost']);+ expect(edges).toContainEqual(expect.objectContaining({ srcName: 'URL.isAvailable', dstQualifiedKey: 'URL.getMethodParameter', tier: 'type' }));+ });++ it('resolves static Type.m() calls on an imported and a same-package class', () => {+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstName: 'URL.valueOf', dstQualifiedKey: 'URL.valueOf', tier: 'type',+ }));+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstName: 'RpcUtils.methodName',+ dstFilePath: '/repo/com/acme/rpc/RpcUtils.java', dstQualifiedKey: 'RpcUtils.methodName', tier: 'type',+ }));+ });++ it('resolves a chained call through the declared return type of the first call', () => {+ // `invoker.getUrl()` is Invoker.getUrl, declared to return URL.+ expect(edges).toContainEqual(expect.objectContaining({+ srcName: 'TimeoutFilter.invoke', dstName: 'Invoker.getUrl().getMethodParameter',+ dstFilePath: '/repo/com/acme/common/URL.java', dstQualifiedKey: 'URL.getMethodParameter', tier: 'type',+ }));+ });++ it('writes one edge per caller to a method with several overloads', () => {+ const toUrl = callEdges(results, edges).filter(e => e.src === 'com/acme/rpc/TimeoutFilter.java::invoke' && e.dst === 'com/acme/common/URL.java::getMethodParameter');+ expect(toUrl).toEqual([{ src: 'com/acme/rpc/TimeoutFilter.java::invoke', dst: 'com/acme/common/URL.java::getMethodParameter', tier: 'type' }]);+ });++ it('no longer lets the same-file method claim calls typed as another class', () => {+ const calls = callEdges(results, edges);+ expect(calls).not.toContainEqual(expect.objectContaining({+ src: 'com/acme/rpc/TimeoutFilter.java::invoke', dst: 'com/acme/rpc/TimeoutFilter.java::getMethodParameter',+ }));+ });++ it('keeps every CALLS edge the name-based resolution wrote before, except the corrected same-file ones', () => {+ // What resolution wrote for this fixture before Java receivers were inferred.+ const before: Array<[string, string]> = [+ ['com/acme/common/URL.java::isAvailable', 'com/acme/common/URL.java::getMethodParameter'],+ ['com/acme/common/URL.java::valueOf', 'com/acme/common/URL.java::URL'],+ ['com/acme/rpc/ServiceUrl.java::describe', 'com/acme/common/AbstractURL.java::getProtocol'],+ ['com/acme/rpc/ServiceUrl.java::describe', 'com/acme/common/URL.java::getHost'],+ ['com/acme/rpc/TimeoutFilter.java::invoke', 'com/acme/common/AbstractURL.java::getProtocol'],+ ['com/acme/rpc/TimeoutFilter.java::invoke', 'com/acme/common/URL.java::valueOf'],+ ['com/acme/rpc/TimeoutFilter.java::invoke', 'com/acme/rpc/Invoker.java::getUrl'],+ ['com/acme/rpc/TimeoutFilter.java::invoke', 'com/acme/rpc/RpcUtils.java::methodName'],+ ['com/acme/rpc/TimeoutFilter.java::invoke', 'com/acme/rpc/ServiceUrl.java::ServiceUrl'],+ ];+ const now = new Set(callEdges(results, edges).map(e => `${e.src} -> ${e.dst}`));+ for (const [src, dst] of before) expect(now).toContain(`${src} -> ${dst}`);+ });++ it('resolves a batch against summaries exactly as the full run does', () => {+ const summaries = new Map(results.map(r => [r.filePath, summarizeParseResult(r)]));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ const filter = results.find(r => r.filePath.endsWith('TimeoutFilter.java'))!;+ expect(resolveEdges([filter], undefined, index)).toEqual(edges.filter(e => e.srcFilePath === filter.filePath));+ });++ it('gives no typed edge, and no error, against summaries written without Java receiver facts', () => {+ const summaries = new Map(results.map(r => {+ const { receiverFactories: _f, receiverHeritage: _h, receiverPackage: _p, ...old } = summarizeParseResult(r);+ return [r.filePath, old];+ }));+ const index = buildGlobalResolutionIndex([...summaries.keys()], undefined, undefined, summaries);+ const filter = results.find(r => r.filePath.endsWith('TimeoutFilter.java'))!;+ const batch = resolveEdges([filter], undefined, index);+ expect(typedEdges(batch)).toEqual([]);+ // The name-based edges are the ones resolution writes without receiver types.+ const untyped = { ...filter, relationships: filter.relationships.filter(r => !r.receiverOnly), receiverTypedCalls: undefined };+ expect(batch).toEqual(resolveEdges([untyped], undefined, index));+ });+});++describe('Java typed receivers', () => {+ it.each([+ ['a local', 'Target t = new Target(); t.run();'],+ ['a var local', 'var t = new Target(); t.run();'],+ ['a parameter', 'param.run();'],+ ['an enhanced-for variable', 'for (Target t : list) { t.run(); }'],+ ['a catch parameter', 'try { } catch (Target e) { e.run(); }'],+ ['a try resource', 'try (Target t = new Target()) { t.run(); }'],+ ['a cast', '((Target) list.get(0)).run();'],+ ['a typed lambda parameter', 'list.forEach((Target t) -> t.run());'],+ ['a field', 'field.run();', ' private Target field;\n'],+ ['this.field', 'this.field.run();', ' private Target field;\n'],+ ['a reassigned local (its declared type stays)', 'Target t = null; t = param; t.run();'],+ ])('resolves a call through %s', (_label, body, members = '') => {+ const files = [...provider(), caller(body, members)];+ expect(typedEdges(resolveEdges(files), 'Use.use')).toEqual([expect.objectContaining({+ dstFilePath: '/repo/p/Target.java', dstQualifiedKey: 'Target.run', tier: 'type',+ })]);+ });++ it.each([+ ['a lambda parameter', 'list.forEach(field -> field.run());'],+ ['a var local of unknown type', 'var field = list.get(0); field.run();'],+ ['a pattern variable', 'Object o = param; if (o instanceof Other field) { field.run(); }'],+ ])('gives no typed edge when %s shadows a typed field', (_label, body) => {+ const files = [...provider(), caller(body, ' private Target field;\n')];+ expect(typedEdges(resolveEdges(files), 'Use.use')).toEqual([]);+ });++ it('gives no typed edge for a receiver whose type is not in the repository', () => {+ const files = [...provider(), caller('StringBuilder b = new StringBuilder(); b.run();')];+ const edges = resolveEdges(files);+ expect(typedEdges(edges)).toEqual([]);+ const use = files[2];+ expect(edges).toEqual(resolveEdges([...provider(), { ...use, relationships: use.relationships.filter(r => !r.receiverOnly), receiverTypedCalls: undefined }]));+ });++ it('gives no typed edge through a generic container element', () => {+ const files = [...provider(), caller('list.get(0).run(); for (var t : list) { t.run(); }')];+ expect(typedEdges(resolveEdges(files))).toEqual([]);+ });++ it('gives no typed edge for a receiver typed by a type parameter', () => {+ const files = [...provider(), parse('/repo/q/Box.java',+ 'package q;\nimport p.Target;\npublic class Box<T extends Target> {\n private T item;\n <U extends Target> void use(U u) {\n item.run();\n u.run();\n }\n}\n')];+ expect(typedEdges(resolveEdges(files))).toEqual([]);+ });++ it('gives no typed edge when two classes in scope share the simple name', () => {+ const files = [+ parse('/repo/a/Dup.java', 'package a;\npublic class Dup {\n public void run() {}\n}\n'),+ parse('/repo/b/Dup.java', 'package b;\npublic class Dup {\n public void run() {}\n}\n'),+ parse('/repo/q/Use.java', 'package q;\nimport a.*;\nimport b.*;\npublic class Use {\n void use(Dup d) {\n d.run();\n Dup.run();\n }\n}\n'),+ ];+ const edges = resolveEdges(files);+ expect(typedEdges(edges)).toEqual([]);+ const use = files[2];+ expect(edges).toEqual(resolveEdges([files[0], files[1], { ...use, relationships: use.relationships.filter(r => !r.receiverOnly), receiverTypedCalls: undefined }]));+ });++ it('prefers a single-type import over a same-named class in the package', () => {+ const files = [+ ...provider(),+ parse('/repo/q/Target.java', 'package q;\npublic class Target {\n public void run() {}\n}\n'),+ caller('param.run();'),+ ];+ expect(typedEdges(resolveEdges(files), 'Use.use')).toEqual([expect.objectContaining({ dstFilePath: '/repo/p/Target.java' })]);+ });++ it('does not treat a lowercase or bound name as a static type receiver', () => {+ const files = [...provider(), caller('Object Target = null; Target.run();')];+ expect(typedEdges(resolveEdges(files), 'Use.use')).toEqual([]);+ });++ it('gives no typed edge for this.m() inside an anonymous class', () => {+ const files = [...provider(), parse('/repo/p/Use.java',+ 'package p;\npublic class Use extends Target {\n void use() {\n new Object() {\n void inner() { this.run(); run(); }\n };\n }\n}\n')];+ expect(typedEdges(resolveEdges(files))).toEqual([]);+ });++ it('stops a chain at a step whose result is not a class type', () => {+ const files = [...provider(' public int count() { return 0; }\n'), caller('param.self().run(); param.count().run();')];+ const edges = typedEdges(resolveEdges(files), 'Use.use');+ // `count()` itself resolves; nothing is chained through its int result.+ expect(edges.map(e => e.dstName).sort()).toEqual(['Target.count', 'Target.self', 'Target.self().run']);+ });++ it('keeps the same-file claim when the typed receiver does not resolve', () => {+ const use = parse('/repo/q/Use.java',+ 'package q;\npublic class Use {\n void run() {}\n void use(Missing m) {\n m.run();\n }\n}\n');+ expect(callEdges([use])).toContainEqual(expect.objectContaining({ src: 'q/Use.java::use', dst: 'q/Use.java::run' }));+ });++ it('records heritage, package and class-returning method results as summary facts', () => {+ const result = fixture().find(r => r.filePath.endsWith('/URL.java'))!;+ expect(result.receiverPackage).toBe('com.acme.common');+ expect(result.receiverHeritage).toEqual([['URL', 'AbstractURL'], ['URL', 'Node']]);+ // The int overload blocks chaining through getMethodParameter.+ expect(result.receiverFactories).toEqual([+ ['URL.valueOf', 'URL'], ['URL.getMethodParameter', 'String'], ['URL.getMethodParameter', ''], ['URL.getHost', 'String'],+ ]);+ expect(summarizeParseResult(result)).toMatchObject({ receiverPackage: 'com.acme.common' });+ });+});diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.tsindex cb03f6f1..9118f355 100644--- a/core-ingestion/src/index.ts+++ b/core-ingestion/src/index.ts@@ -241,6 +241,11 @@ export interface ParsedRelationship {*/receiverType?: string;receiverFactory?: string;+ /**+ * Java: methods called in turn on `receiverType` before this call+ * (`a.getB().m()`); each one's declared return type is the next receiver.+ */+ receiverChain?: 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@@ -300,6 +305,12 @@ export interface FileParseResult {receiverFactories?: Array<[string, string]>;receiverHeritage?: Array<[string, string]>;receiverPackage?: string;+ /**+ * Java: `${srcName}\0${dstName}` of each CALLS relationship whose every call+ * site also has a typed receiver relationship. When those all resolve to+ * another file, a same-named method in this file is not the target.+ */+ receiverTypedCalls?: string[];fileRole: RoleClassification;}@@ -2664,6 +2675,8 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio// 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>();+ // Java: per `${scope}\0${callKey}`, whether every call site has a typed receiver.+ const javaTypedSites = new Map<string, boolean>();// JS/TS: helper-literal module paths already emitted (see importVia).const jsTsHelperImports = new Set<string>();if (isJsTs) {@@ -3017,7 +3030,7 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio}}- const receiverFacts = [SupportedLanguages.Scala, SupportedLanguages.TypeScript, SupportedLanguages.Go].includes(language)+ const receiverFacts = [SupportedLanguages.Scala, SupportedLanguages.TypeScript, SupportedLanguages.Go, SupportedLanguages.Java].includes(language)? collectReceiverFacts(tree.rootNode, language, checkBudget) : undefined;// --- Second pass: calls and imports ---@@ -3209,8 +3222,8 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio// 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;+ const callCapture = receiverFacts ? match.captures.find((c: any) => c.name === 'call') : undefined;+ const typedReceiver = callCapture ? callReceiver(callName.node, receiverFacts!, callCapture.node) : 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;@@ -3403,6 +3416,9 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio}jsTsCallBareOnly.set(bareKey, (jsTsCallBareOnly.get(bareKey) ?? true) && isBare);}+ if (language === SupportedLanguages.Java && !builtinCall) {+ javaTypedSites.set(bareKey, (javaTypedSites.get(bareKey) ?? true) && typedReceiver?.type !== undefined);+ }if (builtinCall) {// Only the typed relationship below.} else if (!seen.has(callKey)) {@@ -3422,10 +3438,14 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptiodelete callRelationships.get(bareKey)?.receiverOnly;}if (typedReceiver) {- // `Type.member`, or `receiver.member` for a factory-typed receiver.- const typedName = `${typedReceiver.type ?? typedReceiver.receiver}.${callee}`;+ // `Type.member`, `receiver.member` for a factory-typed receiver, or+ // Java `Type.getB().member` for a chain.+ const chain = typedReceiver.chain?.length ? `${typedReceiver.chain.map(m => `${m}()`).join('.')}.` : '';+ const typedName = `${typedReceiver.type ?? typedReceiver.receiver}.${chain}${callee}`;const typedKey = `${scope}\x00${typedName}`;- const receiver = typedReceiver.type ? { receiverType: typedReceiver.type } : { receiverFactory: typedReceiver.factory! };+ const receiver = typedReceiver.type+ ? { receiverType: typedReceiver.type, ...(chain ? { receiverChain: typedReceiver.chain } : {}) }+ : { receiverFactory: typedReceiver.factory! };const named = callRelationships.get(typedKey);if (named) {// Same name as the call's own relationship: try the type first, then@@ -3469,6 +3489,8 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptiofor (const [bareKey, rel] of jsTsCallRelationship) {if (jsTsCallBareOnly.get(bareKey) === true) rel.bareCall = true;}+ const receiverTypedCalls = [...javaTypedSites].filter(([key, all]) => all && callRelationships.has(key))+ .map(([key]) => `${callRelationships.get(key)!.srcName}\0${callRelationships.get(key)!.dstName}`);// A single relationship can represent multiple same-name uses in one scope.// Mark it local-only only when every captured use is shadowed; if any use still@@ -3557,6 +3579,7 @@ export function parseFile(filePath: string, source: string, opts: ParseFileOptio...(receiverFacts?.factories.length ? { receiverFactories: receiverFacts.factories } : {}),...(receiverFacts?.heritage.length ? { receiverHeritage: receiverFacts.heritage } : {}),...(receiverFacts?.package ? { receiverPackage: receiverFacts.package } : {}),+ ...(receiverTypedCalls.length ? { receiverTypedCalls } : {}),fileRole: classifyFileRole(filePath, source),};} catch (e) {@@ -5027,6 +5050,7 @@ export function resolveEdges(return pkg !== undefined && scope.wildcards.has(pkg) && !scope.excluded.has(`${pkg}.${type}`);}).map(fp => ({ fp, type }));}+ if (language === SupportedLanguages.Java) return javaReceiverProviders(context, summary, parts, 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.@@ -5056,6 +5080,45 @@ export function resolveEdges(.filter(fp => goPackageKey(fp) === goPackageKey(context)).map(fp => ({ fp, type }));}+ /**+ * A Java type name in scope, in the order Java looks: this file, a+ * single-type import, this package, an on-demand import (`import p.*`,+ * summarized as `p`). The first that has it decides; several files there+ * mean no type. A qualified `p.T` names its package (or `Outer.T` a nested+ * type of a type in scope). Summaries without Java facts have no package,+ * so they provide nothing.+ */+ function javaReceiverProviders(context: string, summary: FileSummary | undefined, parts: string[], type: string): Array<{ fp: string; type: string }> {+ const inPackage = (pkg: string, name: string): string[] => (symbolToFiles.get(name) ?? [])+ .filter(fp => summaries.get(fp)?.language === SupportedLanguages.Java && summaries.get(fp)?.receiverPackage === pkg);+ const named = (fq: string): string[] => {+ const dot = fq.lastIndexOf('.');+ if (dot <= 0) return [];+ const prefix = fq.slice(0, dot);+ const name = fq.slice(dot + 1);+ const direct = inPackage(prefix, name);+ if (direct.length) return direct;+ // `p.Outer.T`: a nested type is declared in its outer type's file.+ const outer = prefix.lastIndexOf('.');+ return outer > 0 ? inPackage(prefix.slice(0, outer), name).filter(fp => fileHasSymbol.get(fp)?.has(prefix.slice(outer + 1))) : [];+ };+ const as = (fps: string[]) => [...new Set(fps)].map(fp => ({ fp, type }));+ if (parts.length) {+ const packaged = named(`${parts.join('.')}.${type}`);+ if (packaged.length || parts.length > 1) return as(packaged);+ const outer = receiverProviders(context, parts[0]);+ return outer.length === 1 && fileHasSymbol.get(outer[0].fp)?.has(type) ? [{ fp: outer[0].fp, type }] : [];+ }+ if (fileHasSymbol.get(context)?.has(type)) return [{ fp: context, type }];+ const imports = (summary?.imports ?? []).map(i => i.dstName);+ // A single-type import shadows the package, even of a type not in the repo.+ const single = imports.filter(fq => fq.endsWith(`.${type}`));+ if (single.length) return as(single.flatMap(named));+ const samePackage = summary?.receiverPackage ? inPackage(summary.receiverPackage, type) : [];+ if (samePackage.length) return as(samePackage);+ return as(imports.flatMap(pkg => inPackage(pkg, 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}`;@@ -5087,14 +5150,55 @@ export function resolveEdges(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 java = summaries.get(fp)?.language === SupportedLanguages.Java;+ // Multiple definitions include overloads. Do not guess a signature. Java+ // overloads in one class are one node (one key), so they are one target.+ if (exact.length) return exact.length === 1 || java ? [{ fp, key }] : [];+ const parents = (summaries.get(fp)?.receiverHeritage ?? []).filter(([child]) => child === name);+ if (java) {+ // The nearest declaration: the superclass chain (listed first), then+ // each interface in declaration order.+ for (const [, parent] of parents) {+ const found = receiverMembers(fp, parent, member, nextSeen);+ if (found.length) return found;+ }+ return [];+ }+ const inherited = parents.flatMap(([, parent]) => receiverMembers(fp, parent, member, nextSeen));const unique = new Map(inherited.map(target => [`${target.fp}\0${target.key}`, target]));return [...unique.values()];}+ /**+ * Java `a.getB().m()`: the receiver after each call in `chain`, from the+ * declared return type of the one method that call resolves to. Stops at the+ * first step that does not resolve or does not return a class type.+ */+ function javaChainReceiver(context: string, type: string, chain: string[]): { context: string; type: string } | undefined {+ let at = { context, type };+ for (const method of chain) {+ const targets = receiverMembers(at.context, at.type, method);+ if (targets.length !== 1) return;+ const { fp, key } = targets[0];+ const returns = new Set((summaries.get(fp)?.receiverFactories ?? []).filter(([fn]) => fn === key).map(([, t]) => t));+ const [returned] = returns;+ // Overloads with different results (or a primitive one) are not guessed.+ if (returns.size !== 1 || !returned) return;+ at = { context: fp, type: returned };+ }+ return at;+ }++ /** The one member a typed CALLS relationship names, if it names exactly one. */+ function typedCallTarget(srcFilePath: string, rel: ParsedRelationship): { fp: string; key: string } | undefined {+ const receiver = rel.receiverType+ ? rel.receiverChain ? javaChainReceiver(srcFilePath, rel.receiverType, rel.receiverChain) : { 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) : [];+ return targets.length === 1 ? targets[0] : undefined;+ }+function factoryReceiver(context: string, factory: string): { context: string; type: string } | undefined {const summary = summaries.get(context);const language = summary?.language;@@ -5219,6 +5323,22 @@ export function resolveEdges(const importedOrder = new Map([...importedFilePaths].map((fp, i) => [fp, i]));const transitiveOrder = new Map([...transitiveFilePaths].map((fp, i) => [fp, i]));+ const typedCalls = result.receiverTypedCalls?.length ? new Set(result.receiverTypedCalls) : undefined;+ let typedByCall: Map<string, ParsedRelationship[]> | undefined;+ // The typed relationships of a call's sites: same caller, same member name.+ const typedSites = (srcName: string, member: string): ParsedRelationship[] => {+ if (!typedByCall) {+ typedByCall = new Map();+ for (const r of result.relationships) {+ if (r.predicate !== 'CALLS' || !r.receiverType) continue;+ const key = `${r.srcName}\0${r.dstName.slice(r.dstName.lastIndexOf('.') + 1)}`;+ const list = typedByCall.get(key);+ if (list) list.push(r); else typedByCall.set(key, [r]);+ }+ }+ return typedByCall.get(`${srcName}\0${member}`) ?? [];+ };+for (const rel of result.relationships) {if (rel.predicate !== 'CALLS' && rel.predicate !== 'EXTENDS' && rel.predicate !== 'REFERENCES' && rel.predicate !== 'IMPORTS') continue;@@ -5363,13 +5483,10 @@ export function resolveEdges(// 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' });+ const target = typedCallTarget(srcFilePath, rel);+ if (target) {+ resolved.push({ srcFilePath, srcName: rel.srcName, dstFilePath: target.fp, dstName: rel.dstName,+ dstQualifiedKey: target.key, predicate: 'CALLS', confidence: 0.95, tier: 'type' });stats.resolvedType = (stats.resolvedType ?? 0) + 1;continue;}@@ -5399,6 +5516,19 @@ export function resolveEdges(// call-site name before any import binding rewrite so a local shadow wins.// Without an import binding, preserve the existing file-wide preference.const hasSameFileDefinition = fileHasSymbol.get(srcFilePath)?.has(origDstName) === true;+ // Java: when every site of this call has a typed receiver and each one+ // resolved to a member in another file, a same-named method here is+ // some other class's. The call goes to a typed target (which its typed+ // relationship writes anyway), never to this file.+ if (hasSameFileDefinition && rel.predicate === 'CALLS' && typedCalls?.has(`${rel.srcName}\0${rel.dstName}`)) {+ const sites = typedSites(rel.srcName, rel.dstName).map(site => typedCallTarget(srcFilePath, site));+ if (sites.length && sites.every(t => t && t.fp !== srcFilePath)) {+ resolved.push({ srcFilePath, srcName, dstFilePath: sites[0]!.fp, dstName: origDstName,+ dstQualifiedKey: sites[0]!.key, predicate: 'CALLS', confidence: 0.95, tier: 'type' });+ stats.resolvedType = (stats.resolvedType ?? 0) + 1;+ continue;+ }+ }if (hasSameFileDefinition &&(!binding || (rel.importBinding !== true && sameScopeDefines(result, srcName, origDstName)))diff --git a/core-ingestion/src/receiver-types.ts b/core-ingestion/src/receiver-types.tsindex 1e28ccaf..aa2de379 100644--- a/core-ingestion/src/receiver-types.ts+++ b/core-ingestion/src/receiver-types.ts@@ -4,6 +4,11 @@export interface ReceiverType {type?: string;factory?: string;+ /**+ * Java: methods called in turn on `type` (`a.getB().m()` is `A` then+ * `getB`). Each step's declared return type is the next receiver.+ */+ chain?: string[];}export interface ReceiverFacts {@@ -13,6 +18,8 @@ export interface ReceiverFacts {/** 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;+ /** Java: the receiver of the call whose name node is given, implicit `this` included. */+ receiverOfCall?(nameNode: any, callNode?: any): (ReceiverType & { receiver: string }) | undefined;}interface ReceiverBinding extends ReceiverType {@@ -20,38 +27,55 @@ interface ReceiverBinding extends ReceiverType {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']);+const classTypes = new Set(['class_definition', 'trait_definition', 'object_definition', 'class_declaration', 'abstract_class_declaration', 'class']);+const functionTypes = 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',+const blockTypes = 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 named = new Set(['type_alias_declaration', ...classTypes, ...functionTypes, ...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])];+const walkedTypes = [...new Set([...classTypes, ...functionTypes, ...blockTypes, 'class_static_block', 'internal_module', ...visited])];++// Java: every type declaration is a class scope, constructors are functions,+// and the statements that declare a variable for their own body are blocks.+const javaClasses = new Set([...classTypes, 'interface_declaration', 'enum_declaration', 'record_declaration', 'annotation_type_declaration']);+const javaFunctions = new Set([...functionTypes, 'constructor_declaration', 'compact_constructor_declaration']);+const javaBlocks = new Set([...blockTypes, 'enhanced_for_statement', 'try_with_resources_statement', 'switch_block']);+// A Java variable keeps its declared type when reassigned, so assignments are not walked.+// Java declarations whose `type` field types their variable_declarator children.+const javaDeclarations = ['local_variable_declaration', 'field_declaration', 'constant_declaration'];+const javaWalkedTypes = [...new Set([...walkedTypes.filter(t => !mutationTypes.includes(t)), ...javaClasses, ...javaFunctions, ...javaBlocks,+ ...javaDeclarations, 'formal_parameter', 'catch_formal_parameter', 'resource', 'instanceof_expression', 'type_pattern', 'record_pattern_component'])];+/** Longest Java call chain followed to a receiver (`a.b().c().d()`). */+const JAVA_MAX_CHAIN = 4;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)) {+ if (/^(?:type_identifier|identifier|qualified_type|nested_type_identifier|stable_type_identifier|scoped_type_identifier)$/.test(node.type)) {const text = node.text.replace(/\s/g, '');if (/^[\w$]+(?:\.[\w$]+)*$/.test(text)) return text;}}+// Java's `<T extends U, @A V>`, read through the field rather than every child.+function javaTypeParameters(node: any): string[] {+ const list = node.childForFieldName('type_parameters');+ return list ? list.namedChildren.map((p: any) => p.namedChildren.find((c: any) => c.type === 'type_identifier')?.text).filter(Boolean) : [];+}+// 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.@@ -77,13 +101,32 @@ function declaredTypeParameters(node: any): string[] {}export function collectReceiverFacts(root: any, language: string, checkBudget: () => void): ReceiverFacts {+ const java = language === 'java';+ const classes = java ? javaClasses : classTypes;+ const functions = java ? javaFunctions : functionTypes;+ const blocks = java ? javaBlocks : blockTypes;+ const isScope = (type: string): boolean =>+ classes.has(type) || functions.has(type) || blocks.has(type) || type === 'class_static_block' || type === 'internal_module';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]> = [];+ // Java: each type declaration and anonymous class body in document order+ // (`name` absent for an anonymous one), and the declared return types of+ // each `Class.method` key (overloads share the key).+ const javaTypes: Array<{ start: number; end: number; name?: string; superclass?: string }> = [];+ const namedBodies = new Set<number>();+ const anonymousBodies = new Set<number>();+ const javaReturns = new Map<string, Set<string>>();+ // Java: each variable_declarator's declared type (from its declaration), and+ // every scope in document order with its enclosing scope's index (-1: the+ // file), so a lookup walks scopes by position instead of `.parent`, which+ // these bindings rebuild from the root on every call.+ const declaratorTypes = new Map<number, any>();+ const javaScopes: Array<{ start: number; end: number; id: number; type: string; parent: number }> = [];// 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 frames: Array<{ node: any; type: string; end: number; scope?: number }> = [];const scopeOf = (classOnly = false): any => {for (let i = frames.length - 1; i >= 0; i--) {const type = frames[i].type;@@ -99,6 +142,15 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (}return root;};+ // Java: the named type a member being visited belongs to; none inside an+ // anonymous class body.+ const javaOwner = (): any => {+ for (let i = frames.length - 1; i >= 0; i--) {+ if (anonymousBodies.has(frames[i].node.id)) return;+ if (classes.has(frames[i].type)) return frames[i].node;+ }+ };+ const javaTypeParameter = (name: string): boolean => frames.some(f => typeParameters.get(f.node.id)?.has(name));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);@@ -109,6 +161,7 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (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 (java && (value.type === 'object_creation_expression' || value.type === 'cast_expression')) 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))) {@@ -129,6 +182,79 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (} else pending.push(...p.namedChildren);}};+ // `var` (a local, a lambda or resource parameter) declares no type of its own.+ const javaDeclaredType = (declaration: any): any => {+ const type = declaration?.childForFieldName('type');+ return type && type.text !== 'var' ? type : null;+ };+ const javaTypeList = (node: any): Array<string | undefined> =>+ node?.namedChildren.find((c: any) => c.type === 'type_list')?.namedChildren.map(typeName) ?? [];+ const visitJava = (node: any, type: string): void => {+ if (javaDeclarations.includes(type)) {+ const declared = javaDeclaredType(node);+ for (const declarator of node.childrenForFieldName('declarator')) declaratorTypes.set(declarator.id, declared);+ return;+ }+ const name = ['class_body', 'type_pattern', 'record_pattern_component'].includes(type) ? null : node.childForFieldName('name');+ if (classes.has(type)) {+ const body = node.childForFieldName('body');+ if (body) namedBodies.add(body.id);+ if (!name) return;+ // Superclass first: a member it declares is the one a subclass inherits.+ const superclass = typeName(node.childForFieldName('superclass')?.firstNamedChild);+ const parents = [superclass, ...javaTypeList(node.childForFieldName('interfaces')),+ ...javaTypeList(node.namedChildren.find((c: any) => c.type === 'extends_interfaces'))];+ for (const parent of parents) if (parent) heritage.push([name.text, parent]);+ javaTypes.push({ start: node.startIndex, end: node.endIndex, name: name.text, superclass });+ return;+ }+ if (type === 'class_body' && !namedBodies.has(node.id)) {+ // `new T() { … }` or an enum constant's body: `this` is not the enclosing class.+ anonymousBodies.add(node.id);+ javaTypes.push({ start: node.startIndex, end: node.endIndex });+ return;+ }+ if (type === 'method_declaration' && name) {+ const owner = javaOwner()?.childForFieldName('name')?.text;+ const result = node.childForFieldName('type');+ if (!owner || !result || result.type === 'void_type') return;+ const own = typeParameters.get(node.id);+ const returned = typeName(result);+ const key = `${owner}.${name.text}`;+ const returns = javaReturns.get(key) ?? new Set<string>();+ // A primitive, array or type-parameter result is not a receiver (''), but+ // still blocks an overload's class type.+ returns.add(returned && !own?.has(returned) && !javaTypeParameter(returned) ? returned : '');+ javaReturns.set(key, returns);+ return;+ }+ if (type === 'formal_parameter' && name) {+ // Method, constructor, record-component and typed lambda parameters.+ bind(scopeOf(), name.text, { type: typeName(javaDeclaredType(node)) });+ return;+ }+ if (type === 'catch_formal_parameter' && name) {+ // `catch (A | B e)` has no single type.+ const caught = node.namedChildren.find((c: any) => c.type === 'catch_type')?.namedChildren ?? [];+ bind(scopeOf(), name.text, { type: caught.length === 1 ? typeName(caught[0]) : undefined });+ return;+ }+ if (type === 'enhanced_for_statement' && name) {+ bind(node, name.text, { type: typeName(javaDeclaredType(node)) });+ return;+ }+ if (type === 'resource' && name) {+ const declared = typeName(javaDeclaredType(node));+ bind(scopeOf(), name.text, declared ? { type: declared } : valueType(node.childForFieldName('value')));+ return;+ }+ // Pattern variables (`x instanceof T t`, `case T t ->`, record patterns)+ // only shadow: their scope follows control flow.+ if (type === 'instanceof_expression' && name) bind(scopeOf(), name.text, {});+ if (type === 'type_pattern' || type === 'record_pattern_component') {+ for (const child of node.namedChildren) if (child.type === 'identifier') bind(scopeOf(), child.text, {});+ }+ };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@@ -141,9 +267,9 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (typeParameters.set(scope.id, names);}if (classes.has(type) || functions.has(type)) {- const generics = declaredTypeParameters(node);+ const generics = java ? javaTypeParameters(node) : declaredTypeParameters(node);if (generics.length) typeParameters.set(node.id, new Set(generics));- const singleParameter = node.childForFieldName('parameter');+ const singleParameter = java ? null : node.childForFieldName('parameter');if (singleParameter?.type === 'identifier') bind(node, singleParameter.text, {});}if (language === 'scala' && classes.has(type)) {@@ -169,6 +295,7 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (factories.push([ownerName, result ?? '']);}}+ if (java) visitJava(node, type);let binding: any;let owner = scopeOf();if (language === 'typescript' && type === 'variable_declarator' && node.parent?.type === 'variable_declaration') {@@ -178,7 +305,9 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (bind(owner, name.text, {});}const declares = bindingTypes.includes(type) || parameterTypes.includes(type);- const annotation = declares ? node.childForFieldName('type') : null;+ const annotation = !declares ? null+ : java && type === 'variable_declarator' ? declaratorTypes.get(node.id) ?? null+ : node.childForFieldName('type');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');@@ -218,8 +347,9 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (}if (binding) {const info = typeName(annotation) ? { type: typeName(annotation) } : valueType(value);+ // A Java field can also belong to an interface, enum or record.const local = ['variable_declarator', 'val_definition', 'var_definition', 'var_spec'].includes(type) &&- !['template_body', 'class_body'].includes(owner.type);+ !['template_body', 'class_body'].includes(owner.type) && !(java && classes.has(owner.type));if (local) Object.assign(info, { available: node.endIndex });if (binding.type === 'identifier' || binding.type === 'property_identifier') bind(owner, binding.text, info);else {@@ -248,15 +378,50 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (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)) {+ for (const node of root.descendantsOfType(java ? javaWalkedTypes : 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 });+ if (isScope(type)) {+ const frame: (typeof frames)[number] = { node, type, end: node.endIndex };+ if (java) {+ const parent = frames.length ? frames[frames.length - 1].scope! : -1;+ frame.scope = javaScopes.push({ start: node.startIndex, end: node.endIndex, id: node.id, type, parent }) - 1;+ }+ frames.push(frame);+ }}+ // `lookupName` for Java, by position: the scopes around `pos`, innermost first.+ const javaLookupName = (pos: number, name: string, field = false): ReceiverType | undefined => {+ let lo = 0;+ let hi = javaScopes.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (javaScopes[mid].start <= pos) lo = mid + 1; else hi = mid;+ }+ // Scopes nest, so the innermost one around `pos` is the last to start+ // before it or one of that scope's ancestors.+ let at = lo - 1;+ while (at >= 0 && javaScopes[at].end <= pos) at = javaScopes[at].parent;+ for (let i = at; ; i = javaScopes[i].parent) {+ const scope = i >= 0 ? javaScopes[i] : { id: root.id, type: root.type };+ const skip = field && !classes.has(scope.type) && scope.type !== 'class_body';+ const info = skip ? undefined : scopes.get(scope.id)?.get(name);+ if (info) {+ if (info.available !== undefined && info.available > pos) return {};+ if (info.type) for (let j = at; j >= 0; j = javaScopes[j].parent) {+ if (typeParameters.get(javaScopes[j].id)?.has(info.type)) return {};+ }+ return info;+ }+ // `this` stops at the innermost class, named or anonymous.+ if (field && !skip && (classes.has(scope.type) || anonymousBodies.has(scope.id))) return;+ if (i < 0) return;+ }+ };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@@ -274,8 +439,8 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (}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;+ // A Scala or Java anonymous class (`new T { … }`) is its own `this`.+ if (field && (classes.has(p.type) || (p.type === 'template_body' && !classes.has(p.parent?.type)) || anonymousBodies.has(p.id))) return;}};// Package/companion return facts apply only when the call still names that@@ -301,6 +466,10 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (}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);+ // Java method results, only for methods that can return a class: a getter+ // returning `int` is never a chained receiver, so it costs no summary space.+ for (const [method, returns] of javaReturns) if ([...returns].some(Boolean)) for (const type of returns) factories.push([method, type]);+ if (java) return javaFacts(root, { factories, heritage, typedNames, scopes, javaTypes, lookupName: javaLookupName });return {factories, heritage, typedNames,// Chained Scala clauses (`package a` then `package b`) declare package `a.b`.@@ -327,12 +496,114 @@ export function collectReceiverFacts(root: any, language: string, checkBudget: (};}+/** The innermost Java type declaration or anonymous class body around `pos`. */+function javaTypeAt(types: Array<{ start: number; end: number; name?: string; superclass?: string }>, pos: number) {+ // Document order: the last range starting at or before `pos` that still+ // contains it is the innermost one.+ let lo = 0;+ let hi = types.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (types[mid].start <= pos) lo = mid + 1; else hi = mid;+ }+ for (let i = lo - 1; i >= 0; i--) if (types[i].end > pos) return types[i];+ return undefined;+}++function javaFacts(root: any, facts: {+ factories: Array<[string, string]>;+ heritage: Array<[string, string]>;+ typedNames: Set<string>;+ scopes: Map<number, Map<string, ReceiverBinding>>;+ javaTypes: Array<{ start: number; end: number; name?: string; superclass?: string }>;+ lookupName(pos: number, name: string, field?: boolean): ReceiverType | undefined;+}): ReceiverFacts {+ const { scopes, javaTypes, lookupName } = facts;+ // Every name a declaration binds, typed or not: any of them can shadow a type name.+ const boundNames = new Set<string>();+ for (const bindings of scopes.values()) for (const name of bindings.keys()) boundNames.add(name);+ const pkg = root.namedChildren.find((node: any) => node.type === 'package_declaration')?.firstNamedChild;+ const calls = new Map<number, (ReceiverType & { receiver: string }) | undefined>();+ // `this` (implicit for a bare `m()`) is the innermost named class; inside an+ // anonymous class body it is that unnamed class, so unknown.+ const enclosing = (node: any) => {+ const at = javaTypeAt(javaTypes, node.startIndex);+ return at?.name ? at : undefined;+ };+ const lookup = (node: any, depth = 0): ReceiverType => {+ switch (node?.type) {+ case 'identifier': {+ const name = node.text;+ const bound = boundNames.has(name) ? lookupName(node.startIndex, name) : undefined;+ if (bound) return bound;+ // Not a variable in scope: an uppercase name is a type (`URL.valueOf()`),+ // which resolution only accepts when exactly one class in scope has it.+ return /^[A-Z]/.test(name) ? { type: name } : {};+ }+ case 'field_access': {+ const object = node.childForFieldName('object');+ const field = node.childForFieldName('field');+ if (object?.type === 'this' && field?.type === 'identifier') {+ return (boundNames.has(field.text) ? lookupName(node.startIndex, field.text, true) : undefined) ?? {};+ }+ // `Outer.this`+ if (field?.type === 'this' && object?.type === 'identifier') return { type: object.text };+ return {};+ }+ case 'this': return { type: enclosing(node)?.name };+ case 'super': return { type: enclosing(node)?.superclass };+ case 'object_creation_expression':+ case 'cast_expression':+ return { type: typeName(node.childForFieldName('type')) };+ case 'parenthesized_expression': return lookup(node.firstNamedChild, depth);+ case 'method_invocation': {+ // `a.getB().m()`: the receiver is what `getB` returns, known only once resolved.+ const name = node.childForFieldName('name')?.text;+ const object = node.childForFieldName('object');+ if (!name || depth >= JAVA_MAX_CHAIN - 1 || qualifiedSuper(node, object)) return {};+ const base = object ? lookup(object, depth + 1) : { type: enclosing(node)?.name };+ return base.type ? { type: base.type, chain: [...(base.chain ?? []), name] } : {};+ }+ default: return {};+ }+ };+ return {+ factories: facts.factories, heritage: facts.heritage, typedNames: facts.typedNames,+ package: pkg?.text.replace(/\s/g, '') || undefined,+ lookup: (node: any) => lookup(node),+ // Each call matches both Java call patterns, so its receiver is kept by call.+ receiverOfCall(nameNode: any, callNode?: any) {+ const call = callNode ?? nameNode.parent;+ if (call?.type !== 'method_invocation') return;+ if (calls.has(call.id)) return calls.get(call.id);+ const object = call.childForFieldName('object');+ const info = qualifiedSuper(call, object) ? {} : object ? lookup(object) : { type: enclosing(call)?.name };+ const receiver = info.type ? { type: info.type, ...(info.chain ? { chain: info.chain } : {}), receiver: object?.text ?? 'this' } : undefined;+ calls.set(call.id, receiver);+ return receiver;+ },+ };+}++/**+ * `X.super.m()`: an interface's default method or an outer class's+ * superclass, not `X`. Its `super` is an extra named child; counting children+ * avoids materializing them (a comment there also counts, which only costs+ * the typed edge).+ */+function qualifiedSuper(call: any, object = call.childForFieldName('object')): boolean {+ if (!object || object.type === 'super') return false;+ const plain = call.childForFieldName('type_arguments') ? 4 : 3;+ return call.namedChildCount > plain;+}+/*** 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 {+export function callReceiver(nameNode: any, facts: ReceiverFacts, callNode?: any): (ReceiverType & { receiver: string }) | undefined {+ if (facts.receiverOfCall) return facts.receiverOfCall(nameNode, callNode);if (facts.typedNames.size === 0) return;const member = nameNode.parent;const field = member?.type === 'member_expression' ? 'object'diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/common/AbstractURL.java b/core-ingestion/test-fixtures/java-receivers/com/acme/common/AbstractURL.javanew file mode 100644index 00000000..d1bf5b09--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/common/AbstractURL.java@@ -0,0 +1,7 @@+package com.acme.common;++public abstract class AbstractURL {+ public String getProtocol() {+ return "acme";+ }+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/common/Node.java b/core-ingestion/test-fixtures/java-receivers/com/acme/common/Node.javanew file mode 100644index 00000000..2a28cc5c--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/common/Node.java@@ -0,0 +1,5 @@+package com.acme.common;++public interface Node {+ boolean isAvailable();+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/common/Parameters.java b/core-ingestion/test-fixtures/java-receivers/com/acme/common/Parameters.javanew file mode 100644index 00000000..09b420e5--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/common/Parameters.java@@ -0,0 +1,7 @@+package com.acme.common;++public class Parameters {+ public String getMethodParameter(String method, String key) {+ return key;+ }+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/common/URL.java b/core-ingestion/test-fixtures/java-receivers/com/acme/common/URL.javanew file mode 100644index 00000000..a98ecb1f--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/common/URL.java@@ -0,0 +1,34 @@+package com.acme.common;++public class URL extends AbstractURL implements Node {+ private final String host;++ public URL(String host) {+ this.host = host;+ }++ public static URL valueOf(String text) {+ return new URL(text);+ }++ public String getMethodParameter(String method, String key) {+ return key;+ }++ public String getMethodParameter(String method, String key, String defaultValue) {+ return defaultValue;+ }++ public int getMethodParameter(String method, String key, int defaultValue) {+ return defaultValue;+ }++ public String getHost() {+ return host;+ }++ @Override+ public boolean isAvailable() {+ return getMethodParameter("ping", "enabled") != null;+ }+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/Invoker.java b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/Invoker.javanew file mode 100644index 00000000..d6b28f90--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/Invoker.java@@ -0,0 +1,7 @@+package com.acme.rpc;++import com.acme.common.URL;++public interface Invoker {+ URL getUrl();+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/RpcUtils.java b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/RpcUtils.javanew file mode 100644index 00000000..8bae71f5--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/RpcUtils.java@@ -0,0 +1,7 @@+package com.acme.rpc;++public final class RpcUtils {+ public static String methodName(Invoker invoker) {+ return "invoke";+ }+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/ServiceUrl.java b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/ServiceUrl.javanew file mode 100644index 00000000..0c94c44d--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/ServiceUrl.java@@ -0,0 +1,18 @@+package com.acme.rpc;++import com.acme.common.URL;++public class ServiceUrl extends URL {+ public ServiceUrl(String host) {+ super(host);+ }++ @Override+ public String getMethodParameter(String method, String key) {+ return super.getMethodParameter(method, key);+ }++ public String describe() {+ return this.getHost() + getProtocol();+ }+}diff --git a/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/TimeoutFilter.java b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/TimeoutFilter.javanew file mode 100644index 00000000..1f1d797d--- /dev/null+++ b/core-ingestion/test-fixtures/java-receivers/com/acme/rpc/TimeoutFilter.java@@ -0,0 +1,27 @@+package com.acme.rpc;++import com.acme.common.URL;+import com.acme.common.*;++public class TimeoutFilter {+ private URL url;+ private Node node;++ // Same name as URL's method: the same-file tier used to claim the calls below.+ public String getMethodParameter(String method, String key) {+ return key;+ }++ public void invoke(Invoker invoker, URL param) {+ String method = RpcUtils.methodName(invoker);+ URL local = URL.valueOf("acme://host");+ local.getMethodParameter(method, "timeout");+ param.getMethodParameter(method, "retries", 3);+ url.getMethodParameter(method, "weight", "1");+ this.url.getMethodParameter(method, "weight");+ invoker.getUrl().getMethodParameter(method, "x");+ node.isAvailable();+ var service = new ServiceUrl("h");+ service.getProtocol();+ }+}diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 6b6a36c9..cf776b28 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -367,6 +367,22 @@ use, skipping comments and the name's own declaration. A row whose file ismissing, outside the workspace, or has no findable use simply has no `site=`.`--format json` carries the same object as `site: {path, line, snippet, also}`.+`ix callers` on a Java method also lists the callers that reach it through a+supertype. For a target `C.m`, it walks `C`'s superclasses and interfaces (up+to five levels) and adds the callers of each one's own `m`: a call typed+against the interface or superclass can run `C.m`. Such a row ends with+`via=<Supertype>.<m>`, the member the call names; json adds `via` to the row.+Direct rows come first and carry no `via`; a caller that is both is listed+once, as a direct row. `shown`/`total` count every row, and `--all` adds the+same rows per candidate. A call typed directly against the interface is a+plain caller of the interface method, with no `via`.++```+callers target=getUrl shown=2 total=2 resolved=2+ref name=invoke kind=method path=src/rpc/Filter.java lines=10-24+ref name=select kind=method path=src/cluster/Cluster.java lines=30-41 via=Invoker.getUrl+```+`ix around <path>[:<line>]` — the dependents of the code at a location, sizedfor an agent's context (`--budget`, default 300 tokens):diff --git a/ix-cli/src/cli/__tests__/callers-dispatch.test.ts b/ix-cli/src/cli/__tests__/callers-dispatch.test.tsnew file mode 100644index 00000000..966b9c9c--- /dev/null+++ b/ix-cli/src/cli/__tests__/callers-dispatch.test.ts@@ -0,0 +1,239 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";++import { registerCallersCommand } from "../commands/callers.js";++/**+ * `ix callers` on a Java method also lists the callers of the same-named+ * method on each supertype (interface or superclass): a call typed against+ * the supertype may run this implementation. Those rows carry `via` (json) /+ * `via=` (llm); everything else about the output stays as it was.+ */++type Node = { id: string; kind: string; name: string; attrs: Record<string, unknown> };++const { graph, target, rgMatches } = vi.hoisted(() => ({+ graph: { value: new Map<string, unknown[]>(), calls: [] as string[] },+ target: { value: {} as Record<string, unknown> },+ rgMatches: { value: [] as Array<[string, number, string]> },+}));++vi.mock("../../client/factory.js", () => ({+ createClient: () => ({+ expand: async (id: string, opts: { direction: string; predicates: string[] }) => {+ const key = `${id} ${opts.direction} ${opts.predicates.join(",")}`;+ graph.calls.push(key);+ return { nodes: graph.value.get(key) ?? [], edges: [] };+ },+ }),+}));+vi.mock("../resolve.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("../resolve.js")>(),+ resolveTargetSetOrReport: async (_client: unknown, _symbol: string, opts: { all?: boolean }) =>+ opts.all ? { entities: [{ ...target.value, n: 1 }], all: { total: 1 } } : { entities: [target.value] },+ printResolved: () => {},+}));+vi.mock("../graph-health.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("../graph-health.js")>(),+ checkGraphHealth: async () => ({ status: "healthy" }),+}));+vi.mock("../config.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("../config.js")>(),+ resolveWorkspaceRoot: () => "/ws",+}));+vi.mock("node:child_process", async (importOriginal) => ({+ ...await importOriginal<typeof import("node:child_process")>(),+ execFile: (_file: string, _args: string[], _opts: unknown, cb: (err: unknown, out: { stdout: string; stderr: string }) => void) => {+ const stdout = rgMatches.value.map(([path, line, text]) => JSON.stringify({+ type: "match", data: { path: { text: path }, line_number: line, lines: { text: `${text}\n` } },+ })).join("\n");+ cb(null, { stdout, stderr: "" });+ },+}));++const node = (id: string, kind: string, name: string, path: string, line: number): Node =>+ ({ id, kind, name, attrs: { path, line_start: line, line_end: line + 2 } });++const IMPL = { id: "impl-getUrl", kind: "method", name: "getUrl", path: "src/rpc/TimeoutInvoker.java", resolutionMode: "exact" };+const OWNER = node("cls-TimeoutInvoker", "class", "TimeoutInvoker", "src/rpc/TimeoutInvoker.java", 3);+const ABSTRACT = node("cls-AbstractInvoker", "class", "AbstractInvoker", "src/rpc/AbstractInvoker.java", 3);+const IFACE = node("ifc-Invoker", "interface", "Invoker", "src/rpc/Invoker.java", 3);+const NODE = node("ifc-Node", "interface", "Node", "src/common/Node.java", 3);+const FILTER = node("m-Filter.invoke", "method", "invoke", "src/rpc/Filter.java", 10);+const WRAP = node("m-Base.wrap", "method", "wrap", "src/rpc/Base.java", 20);+const SELECT = node("m-Cluster.select", "method", "select", "src/cluster/Cluster.java", 30);++function javaGraph(): Map<string, unknown[]> {+ return new Map<string, unknown[]>([+ // Direct callers of the implementation.+ [`${IMPL.id} in CALLS,REFERENCES`, [FILTER]],+ [`${IMPL.id} in CONTAINS`, [OWNER]],+ // TimeoutInvoker extends AbstractInvoker implements Invoker; AbstractInvoker implements Invoker; Invoker extends Node.+ [`${OWNER.id} out EXTENDS`, [IFACE, ABSTRACT]],+ [`${ABSTRACT.id} out EXTENDS`, [IFACE]],+ [`${IFACE.id} out EXTENDS`, [NODE]],+ [`${ABSTRACT.id} out CONTAINS`, [node("m-AbstractInvoker.getUrl", "method", "getUrl", "src/rpc/AbstractInvoker.java", 5)]],+ [`${IFACE.id} out CONTAINS`, [node("m-Invoker.getUrl", "method", "getUrl", "src/rpc/Invoker.java", 4), node("m-Invoker.invoke", "method", "invoke", "src/rpc/Invoker.java", 5)]],+ [`${NODE.id} out CONTAINS`, [node("m-Node.isAvailable", "method", "isAvailable", "src/common/Node.java", 4)]],+ // FILTER also calls through the superclass: it stays a direct row.+ ["m-AbstractInvoker.getUrl in CALLS", [WRAP, FILTER]],+ ["m-Invoker.getUrl in CALLS", [SELECT, WRAP]],+ ]);+}++async function run(args: string[]): Promise<{ out: string[]; exitCode: number | undefined }> {+ const program = new Command().name("ix").exitOverride();+ registerCallersCommand(program);+ const out: string[] = [];+ vi.spyOn(console, "log").mockImplementation((...parts) => { out.push(parts.join(" ")); });+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);+ process.exitCode = undefined;+ await program.parseAsync(["callers", "getUrl", ...args], { from: "user" });+ const exitCode = process.exitCode;+ process.exitCode = undefined;+ return { out, exitCode: exitCode === 0 ? undefined : exitCode as number | undefined };+}++const json = (out: string[]) => JSON.parse(out.join("\n"));++describe("ix callers dispatch rows (Java)", () => {+ beforeEach(() => {+ graph.value = javaGraph();+ graph.calls = [];+ target.value = IMPL;+ rgMatches.value = [];+ });+ afterEach(() => vi.restoreAllMocks());++ it("lists callers through a superclass and an interface after the direct ones, flagged with via", async () => {+ const { out, exitCode } = await run(["--format", "json"]);+ const body = json(out);+ expect(body.results.map((r: any) => [r.name, r.via])).toEqual([+ ["invoke", undefined],+ ["wrap", "AbstractInvoker.getUrl"],+ ["select", "Invoker.getUrl"],+ ]);+ expect(Object.keys(body.results[0])).not.toContain("via");+ expect(body.results[1]).toMatchObject({ name: "wrap", path: "src/rpc/Base.java", lineStart: 20, via: "AbstractInvoker.getUrl" });+ expect(body.summary).toMatchObject({ shown: 3, total: 3, resolved: 3 });+ expect(body.resultSource).toBe("graph");+ expect(exitCode).toBeUndefined();+ });++ it("prints via= on dispatch ref lines only (llm)", async () => {+ const { out } = await run(["--format", "llm"]);+ expect(out[0]).toBe("callers target=getUrl shown=3 total=3 resolved=3");+ const refs = out.filter((l) => l.startsWith("ref "));+ expect(refs).toHaveLength(3);+ expect(refs[0]).not.toContain("via=");+ expect(refs[1]).toMatch(/^ref name=wrap .* via=AbstractInvoker\.getUrl$/);+ expect(refs[2]).toMatch(/^ref name=select .* via=Invoker\.getUrl$/);+ });++ it("shows a dim (via X) suffix in text", async () => {+ const { out } = await run([]);+ expect(out.find((l) => l.includes("wrap"))).toContain("(via AbstractInvoker.getUrl)");+ expect(out.find((l) => l.includes("invoke"))).not.toContain("(via");+ });++ it("answers from dispatch rows when the implementation has no direct caller, without the text fallback", async () => {+ graph.value.delete(`${IMPL.id} in CALLS,REFERENCES`);+ rgMatches.value = [["src/x.java", 1, "x.getUrl();"]];+ const body = json((await run(["--format", "json"])).out);+ expect(body.resultSource).toBe("graph");+ expect(body.results.map((r: any) => [r.name, r.via])).toEqual([+ ["wrap", "AbstractInvoker.getUrl"], ["invoke", "AbstractInvoker.getUrl"], ["select", "Invoker.getUrl"],+ ]);+ });++ it("walks a bounded, cycle-safe supertype graph", async () => {+ graph.value.set(`${NODE.id} out EXTENDS`, [OWNER, IFACE]);+ await run(["--format", "json"]);+ // One EXTENDS expand per type, each type once.+ expect(graph.calls.filter((c) => c.endsWith("out EXTENDS")).sort()).toEqual([+ `${ABSTRACT.id} out EXTENDS`, `${IFACE.id} out EXTENDS`, `${NODE.id} out EXTENDS`, `${OWNER.id} out EXTENDS`,+ ].sort());+ });++ it("applies under --all too, per candidate", async () => {+ const body = json((await run(["--all", "--format", "json"])).out);+ expect(body.results.map((r: any) => [r.name, r.candidate, r.via])).toEqual([+ ["invoke", 1, undefined],+ ["wrap", 1, "AbstractInvoker.getUrl"],+ ["select", 1, "Invoker.getUrl"],+ ]);+ });++ it("costs two requests for a Java class with no supertype, and none for another language", async () => {+ graph.value.delete(`${OWNER.id} out EXTENDS`);+ await run(["--format", "json"]);+ expect(graph.calls).toEqual([`${IMPL.id} in CALLS,REFERENCES`, `${IMPL.id} in CONTAINS`, `${OWNER.id} out EXTENDS`]);+ graph.calls = [];+ target.value = { ...IMPL, path: "src/rpc/timeout.ts" };+ await run(["--format", "json"]);+ expect(graph.calls).toEqual([`${IMPL.id} in CALLS,REFERENCES`]);+ });+});++/**+ * The output contract plugins read: unchanged by dispatch rows wherever there+ * are none. These expectations held before dispatch rows existed.+ */+describe("ix callers output contract", () => {+ beforeEach(() => {+ graph.calls = [];+ rgMatches.value = [];+ target.value = { id: "fn-foo", kind: "function", name: "getUrl", path: "src/a.ts", resolutionMode: "exact" };+ });+ afterEach(() => vi.restoreAllMocks());++ it("direct callers: json keys, llm line shapes and exit code", async () => {+ graph.value = new Map([["fn-foo in CALLS,REFERENCES", [node("m-a", "function", "main", "src/main.ts", 4)]]]);+ const j = await run(["--format", "json"]);+ const body = json(j.out);+ expect(Object.keys(body)).toEqual(["results", "resultSource", "resolvedTarget", "summary"]);+ expect(Object.keys(body.results[0])).toEqual(["name", "kind", "id", "path", "lineStart", "lineEnd"]);+ expect(Object.keys(body.summary)).toEqual(["shown", "total", "resolved", "unresolved", "truncated", "offset"]);+ expect(j.exitCode).toBeUndefined();+ const l = await run(["--format", "llm"]);+ expect(l.out).toEqual([+ "callers target=getUrl shown=1 total=1 resolved=1",+ "ref name=main kind=function path=src/main.ts lines=4-6",+ ]);+ expect(l.exitCode).toBeUndefined();+ });++ it("an unresolved caller row: json keys, llm line shape and exit code", async () => {+ graph.value = new Map([["fn-foo in CALLS,REFERENCES", [{ id: "0123abcd-0000-0000-0000-000000000000", kind: "function", name: "0123abcd-0000-0000-0000-000000000000", attrs: {} }]]]);+ const j = await run(["--format", "json"]);+ const body = json(j.out);+ expect(Object.keys(body)).toEqual(["results", "resultSource", "resolvedTarget", "diagnostics", "summary"]);+ expect(Object.keys(body.results[0])).toEqual(["kind", "resolved", "rawId", "diagnostic"]);+ expect(body.diagnostics.map((d: any) => d.code)).toEqual(["dangling_reference_filtered"]);+ expect(Object.keys(body.summary)).toEqual(["shown", "total", "resolved", "unresolved", "truncated", "offset"]);+ expect(j.exitCode).toBeUndefined();+ const l = await run(["--format", "llm"]);+ expect(l.out).toEqual(["callers target=getUrl shown=1 total=1 resolved=0 unresolved=1", "ref kind=function id=0123abcd resolved=false"]);+ });++ it("no graph callers: the text fallback keeps its keys, lines and exit code", async () => {+ graph.value = new Map();+ rgMatches.value = [["src/b.ts", 3, "getUrl();"]];+ const j = await run(["--format", "json"]);+ const body = json(j.out);+ expect(Object.keys(body)).toEqual(["results", "resultSource", "resolvedTarget", "summary", "diagnostics"]);+ expect(body.resultSource).toBe("text");+ expect(Object.keys(body.results[0])).toEqual(["id", "kind", "name", "resolved", "path", "line", "attrs"]);+ expect(Object.keys(body.summary)).toEqual(["candidatesFound", "candidatesReturned"]);+ expect(body.diagnostics.map((d: any) => d.code)).toEqual(["text_fallback_used"]);+ expect(j.exitCode).toBeUndefined();+ const l = await run(["--format", "llm"]);+ expect(l.out).toEqual([+ "callers target=getUrl source=text shown=1 total=1",+ 'diagnostic code=text_fallback_used message="No graph-backed CALLS/REFERENCES edges; showing text matches."',+ "ref path=src/b.ts line=3 snippet=getUrl();",+ ]);+ });+});diff --git a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts b/ix-cli/src/cli/__tests__/ingest-equivalence.test.tsindex a36f7506..9320ba88 100644--- a/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-equivalence.test.ts@@ -254,6 +254,32 @@ describe("incremental ix map equals a fresh map (fake backend)", () => {}});+ it("changing an intermediate Java superclass re-resolves subclass callers", async () => {+ const world = new World("head");+ try {+ await world.start();+ const sources = new Map([+ ["src/p/A.java", "package p;\npublic class A {\n public void run() {}\n}\n"],+ ["src/p/B.java", "package p;\npublic class B {\n public void run() {}\n}\n"],+ ["src/p/Mid.java", "package p;\npublic class Mid extends A {\n}\n"],+ ["src/p/Child.java", "package p;\npublic class Child extends Mid {\n}\n"],+ ["src/q/Use.java", "package q;\nimport p.Child;\npublic class Use {\n void use(Child x) {\n x.run();\n }\n}\n"],+ ]);+ world.writeSources(sources);+ await world.map();+ const before = world.backend.graphSignature();+ sources.set("src/p/Mid.java", "package p;\npublic class Mid extends B {\n}\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.diff --git a/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.ts b/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.tsindex 29b70a34..98145012 100644--- a/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-receiver-incremental.test.ts@@ -62,6 +62,43 @@ const SCENARIOS: Array<[string, Sources, Sources]> = [{ "third/Target.scala": "package third\nclass Target { def stop() = () }\n" }],];+// Java: `get()` is declared by both URL and URI; only the caller's receiver+// type picks one. Every scenario edits a provider, never the caller.+const JAVA_TYPES: Sources = {+ "src/common/URL.java": "package common;\npublic class URL {\n public String get() { return \"url\"; }\n}\n",+ "src/common/URI.java": "package common;\npublic class URI {\n public String get() { return \"uri\"; }\n}\n",+};+const JAVA_INVOKER = (result: string, parent = "") =>+ `package rpc;\nimport common.URL;\nimport common.URI;\npublic interface Invoker${parent} {\n${result ? ` ${result} getUrl();\n` : ""}}\n`;++const JAVA_SCENARIOS: Array<[string, Sources, Sources]> = [+ ["a Java method's declared return type changes", {+ ...JAVA_TYPES,+ "src/rpc/Invoker.java": JAVA_INVOKER("URL"),+ "src/rpc/Use.java": "package rpc;\npublic class Use {\n void use(Invoker invoker) {\n invoker.getUrl().get();\n }\n}\n",+ }, { "src/rpc/Invoker.java": JAVA_INVOKER("URI") }],+ ["an inherited Java method's declared return type changes", {+ ...JAVA_TYPES,+ "src/rpc/Base.java": JAVA_INVOKER("URL").replace("Invoker", "Base"),+ "src/rpc/Invoker.java": JAVA_INVOKER("", " extends Base"),+ "src/rpc/Use.java": "package rpc;\npublic class Use {\n void use(Invoker invoker) {\n invoker.getUrl().get();\n }\n}\n",+ }, { "src/rpc/Base.java": JAVA_INVOKER("URI").replace("Invoker", "Base") }],+ ["a Java class changes its superclass", {+ ...JAVA_TYPES,+ "src/rpc/Sub.java": "package rpc;\nimport common.*;\npublic class Sub extends URL {\n}\n",+ "src/rpc/Use.java": "package rpc;\npublic class Use {\n void use(Sub sub) {\n sub.get();\n }\n}\n",+ }, { "src/rpc/Sub.java": "package rpc;\nimport common.*;\npublic class Sub extends URI {\n}\n" }],+ ["a Java field changes its declared type", {+ ...JAVA_TYPES,+ "src/rpc/Holder.java": "package rpc;\nimport common.*;\npublic class Holder {\n private URL target;\n public String ping() {\n return target.get();\n }\n}\n",+ "src/rpc/Use.java": "package rpc;\npublic class Use {\n void use(Holder holder) {\n holder.ping();\n }\n}\n",+ }, { "src/rpc/Holder.java": "package rpc;\nimport common.*;\npublic class Holder {\n private URI target;\n public String ping() {\n return target.get();\n }\n}\n" }],+ ["a same-package Java class appears and shadows an on-demand import", {+ ...JAVA_TYPES,+ "src/rpc/Use.java": "package rpc;\nimport common.*;\npublic class Use {\n void use(URL url) {\n url.get();\n }\n}\n",+ }, { "src/rpc/URL.java": "package rpc;\npublic class URL {\n public String get() { return \"rpc\"; }\n}\n" }],+];+describe("incremental map follows factory return types (fake backend)", () => {vi.setConfig({ testTimeout: 120_000 });@@ -130,4 +167,30 @@ describe("incremental map follows factory return types (fake backend)", () => {await fresh.stop();}});++ it.each(JAVA_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.length, "typed edges before the edit").toBeGreaterThan(0);++ 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 a 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 9cd7eb00..cd179aa4 100644--- a/ix-cli/src/cli/__tests__/ingest-symbols.test.ts+++ b/ix-cli/src/cli/__tests__/ingest-symbols.test.ts@@ -218,6 +218,29 @@ describe("dependents (IN-11)", () => {expect(changedNames(before, after)).toEqual(new Set(["Target"]));});+ it("invalidates a Java chained caller when a method's declared result changes, inherited or not", () => {+ // `i.getUrl().get()` where Invoker inherits getUrl from Base: the caller+ // names `getUrl`, never `Base.getUrl`.+ const before = summary("Base.java", { language: "java", sig: "before", receiverFactories: [["Base.getUrl", "URL"]] });+ const after = summary("Base.java", { language: "java", sig: "after", receiverFactories: [["Base.getUrl", "URI"]] });+ expect(changedNames(before, after)).toEqual(new Set(["Base.getUrl", "getUrl"]));+ const table = new Map([+ ["Base.java", entry(after)],+ ["Use.java", entry(summary("Use.java", { language: "java", refs: ["Invoker", "Invoker.getUrl", "Invoker.getUrl().get", "get", "getUrl"] }))],+ ["Other.java", entry(summary("Other.java", { language: "java", refs: ["Other.run"] }))],+ ]);+ expect(findDependents(table, changedNames(before, after), [], new Set(["Base.java"]))).toEqual(["Use.java"]);+ // A changed class reaches callers chained through a method returning it.+ const holder = new Map([+ ["Invoker.java", entry(summary("Invoker.java", { language: "java", receiverFactories: [["Invoker.getUrl", "URL"]] }))],+ ["Use.java", entry(summary("Use.java", { language: "java", refs: ["getUrl", "get"] }))],+ ]);+ expect(findDependents(holder, new Set(["URL"]), [], new Set())).toEqual(["Use.java"]);+ // Scala factories keep naming the factory only.+ const scala = summary("Mk.scala", { language: "scala", sig: "a", receiverFactories: [["Mk.apply", "T"]] });+ expect(changedNames(scala, { ...scala, sig: "b", receiverFactories: [["Mk.apply", "U"]] })).toEqual(new Set(["Mk.apply"]));+ });+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" }] });diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.tsindex 5c7fef91..c4e63f1c 100644--- a/ix-cli/src/cli/commands/callers.ts+++ b/ix-cli/src/cli/commands/callers.ts@@ -30,6 +30,79 @@ export const ALL_CONCURRENCY = 4;/** Rows per page of the text fallback. --limit does not apply to it. */export const TEXT_FALLBACK_PAGE = 10;+/** Supertype levels walked for a Java method's dispatch callers. */+export const DISPATCH_DEPTH = 5;+/** Supertypes looked at, at most, for one target: each costs one small expand. */+export const DISPATCH_MAX_TYPES = 16;++const TYPE_KINDS = new Set(["class", "interface", "enum", "record", "trait", "object", "annotation"]);+const byName = (a: any, b: any): number =>+ String(a.name ?? "").localeCompare(String(b.name ?? "")) || String(a.id ?? "").localeCompare(String(b.id ?? ""));++/**+ * Callers that reach a Java method through a supertype. For a target `C.m`,+ * the callers of `S.m` for each supertype `S` of `C` (EXTENDS edges, which+ * include `implements`) that declares `m`: a call typed against `S` targets+ * `S.m` statically and may run `C.m`. Each row carries `dispatchVia: "S.m"`+ * (printed as `via`). Nothing for another language, or for a class with no+ * supertype in the graph (two requests then).+ */+export async function dispatchCallers(+ client: Pick<IxClient, "expand">,+ target: { id: string; name: string; path?: string },+): Promise<{ rows: any[]; capped: boolean }> {+ const none = { rows: [], capped: false };+ if (!/\.java$/i.test(target.path ?? "")) return none;+ const owners = (await client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] })).nodes+ .filter((n: any) => TYPE_KINDS.has(String(n.kind ?? "").toLowerCase()));+ if (owners.length !== 1) return none;+ const seen = new Set<string>([owners[0].id]);+ const members: Array<{ id: string; via: string }> = [];+ let frontier: any[] = owners;+ for (let depth = 0; depth < DISPATCH_DEPTH && frontier.length > 0 && seen.size <= DISPATCH_MAX_TYPES; depth++) {+ const parents = await mapLimit(frontier, ALL_CONCURRENCY, (n) => client.expand(n.id, { direction: "out", predicates: ["EXTENDS"] }));+ const next: any[] = [];+ for (const n of parents.flatMap((r) => r.nodes).sort(byName)) {+ if (!n?.id || seen.has(n.id) || seen.size > DISPATCH_MAX_TYPES) continue;+ seen.add(n.id);+ next.push(n);+ }+ const contained = await mapLimit(next, ALL_CONCURRENCY, (n) => client.expand(n.id, { direction: "out", predicates: ["CONTAINS"] }));+ next.forEach((type, i) => {+ for (const m of contained[i].nodes) {+ if (m?.id && m.id !== target.id && m.name === target.name && /^(method|function)$/i.test(String(m.kind ?? ""))) {+ members.push({ id: m.id, via: `${type.name}.${target.name}` });+ }+ }+ });+ frontier = next;+ }+ const calls = await mapLimit(members, ALL_CONCURRENCY, (m) => client.expand(m.id, { direction: "in", predicates: ["CALLS"] }));+ return {+ rows: calls.flatMap((r, i) => r.nodes.map((n: any) => ({ ...n, dispatchVia: members[i].via }))),+ capped: calls.some((r) => expandCapped(r)),+ };+}++/**+ * Direct rows as the graph gave them, then dispatch rows for callers not+ * already listed (a direct row wins; the first supertype wins among the rest).+ */+async function withDispatch(+ client: IxClient, target: { id: string; name: string; path?: string }, direct: any[],+): Promise<{ rows: any[]; capped: boolean }> {+ const dispatch = await dispatchCallers(client, target);+ if (dispatch.rows.length === 0) return { rows: direct, capped: false };+ const listed = new Set(direct.map((n) => n.id).filter(Boolean));+ const extra: any[] = [];+ for (const n of dispatch.rows) {+ if (n.id && listed.has(n.id)) continue;+ if (n.id) listed.add(n.id);+ extra.push(n);+ }+ return { rows: [...direct, ...extra], capped: dispatch.capped };+}+/*** rg's argv for the text fallback. -F and -e: the name is a literal pattern,* never a regex or a flag (a symbol named `--pre=x` would otherwise run an rg@@ -85,10 +158,14 @@ async function edgesOfAll(direction: relation === "callers" ? "in" : "out",predicates: ["CALLS", "REFERENCES"],}));- const rows = expanded.flatMap((result, i) => result.nodes.map((n: any) => ({ ...n, candidate: candidates[i].n })));+ // Callers of a Java method also include its dispatch callers, per candidate.+ const merged = relation === "callers"+ ? await mapLimit(set.entities, ALL_CONCURRENCY, (e, i) => withDispatch(client, e, expanded[i].nodes))+ : expanded.map((r) => ({ rows: r.nodes, capped: false }));+ const rows = merged.flatMap((result, i) => result.rows.map((n: any) => ({ ...n, candidate: candidates[i].n })));const health = await healthDiagnostics(healthCheck);bannerOverRows(health, format, rows.length);- const slice = sliceEdgeResults(rows, limit, offset, expanded.some((r) => expandCapped(r)));+ const slice = sliceEdgeResults(rows, limit, offset, expanded.some((r) => expandCapped(r)) || merged.some((m) => m.capped));if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);// Call sites are looked up against the candidate the row belongs to.const sites = await mapLimit(set.entities, ALL_CONCURRENCY, (e) => edgeTargetFor(client, e, relation));@@ -185,10 +262,12 @@ async function callersOne(client: IxClient, symbol: string, opts: EdgeOpts, cmd:if (opts.format === "text") printResolved(target);const healthCheck = checkGraphHealth(client, activeReadScope());// Use expand by entity ID to avoid aggregating results across all same-named entities- const result = await client.expand(target.id, {+ const direct = await client.expand(target.id, {direction: "in",predicates: ["CALLS", "REFERENCES"],});+ const merged = await withDispatch(client, target, direct.nodes);+ const result = { ...direct, nodes: merged.rows };const health = await healthDiagnostics(healthCheck);bannerOverRows(health, opts.format, result.nodes.length);// `ix ingest --force` does not bring a hollowed graph's edges back; the@@ -314,7 +393,7 @@ async function callersOne(client: IxClient, symbol: string, opts: EdgeOpts, cmd:// Both graph and text empty (also the health-gated path: --offset does not apply).formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);} else {- const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(direct) || merged.capped);if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);const site = await edgeTargetFor(client, target, "callers");formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callers", site) }, "callers", target.name, opts.format, target, "graph", health.diagnostics);diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.tsindex f7fb664d..c55e5019 100644--- a/ix-cli/src/cli/format.ts+++ b/ix-cli/src/cli/format.ts@@ -225,11 +225,18 @@ function isRawIdName(value: string): boolean {}function edgeRowPriority(node: any): number {+ // A dispatch row (`ix callers` through a supertype) follows every direct one.+ const dispatch = typeof node.dispatchVia === "string" ? 3 : 0;const name = node.name || node.attrs?.name || "";const resolved = !!name && !isRawIdName(name);- if (!resolved) return 2;+ if (!resolved) return dispatch + 2;const path = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? node.attrs?.path;- return path ? 0 : 1;+ return dispatch + (path ? 0 : 1);+}++/** The supertype member a dispatch row's call targets (`via`), absent on a direct row. */+function dispatchVia(node: any): string | undefined {+ return typeof node.dispatchVia === "string" ? node.dispatchVia : undefined;}/**@@ -922,6 +929,7 @@ export function renderEdgeResultsLlm(id: n.id ?? undefined,site: n.site as EdgeSite | undefined,candidate: typeof n.candidate === "number" ? n.candidate as number : undefined,+ via: dispatchVia(n),...rowLocation(n),};});@@ -966,6 +974,8 @@ export function renderEdgeResultsLlm(// Which `--all` candidate the row belongs to. Outside projectRow: a row// that lost it under `--fields` could not be attributed at all.const tag: Array<[string, LlmValue]> = ref.candidate !== undefined ? [["candidate", ref.candidate]] : [];+ // A dispatch row: the call targets this supertype member.+ if (ref.via !== undefined) tag.push(["via", ref.via]);// An unresolved row has no name to go by, so its id is all there is.lines.push(ref.resolved? llmLine("ref", [...projectRow([@@ -1007,6 +1017,7 @@ export function formatEdgeResults(...rowLocation(n),...(n.site ? { site: n.site } : {}),...(typeof n.candidate === "number" ? { candidate: n.candidate } : {}),+ ...(dispatchVia(n) ? { via: dispatchVia(n) } : {}),};if (!resolved) {ref.resolved = false;@@ -1096,7 +1107,8 @@ export function formatEdgeResults(console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`+ (where ? ` ${chalk.dim(where)}` : "")- + (typeof n.candidate === "number" ? ` ${chalk.dim(`[${n.candidate}]`)}` : ""),+ + (typeof n.candidate === "number" ? ` ${chalk.dim(`[${n.candidate}]`)}` : "")+ + (dispatchVia(n) ? ` ${chalk.dim(`(via ${dispatchVia(n)})`)}` : ""),);const site = n.site as EdgeSite | undefined;if (site) console.log(` ${chalk.dim(`at ${siteLabel(site)}`)} ${site.snippet}`);diff --git a/ix-cli/src/cli/ingest-symbols.ts b/ix-cli/src/cli/ingest-symbols.tsindex e2f03869..0dc7d93e 100644--- a/ix-cli/src/cli/ingest-symbols.ts+++ b/ix-cli/src/cli/ingest-symbols.ts@@ -307,6 +307,7 @@ function onDiskGen(target: string): string | undefined {// and refers to, so the run can find those files without reading the rest.type SummaryFields = {+ language?: string;qkeys?: Array<[string, string]>;exportPublicNames?: Array<[string, string]>;phpTypes?: Array<[string, string]>;@@ -347,11 +348,19 @@ function bindings(summary: StoredSummary | undefined): Map<string, string[]> {// 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]);+ // A Java method result (`URL.getUrl`) types a chained call, which names the+ // method only (`x.getUrl().m()`): the method name counts too.+ for (const [name, type] of s.receiverFactories ?? []) out.set(`f\0${name}\0${type}\0${heritageImports}\0\0${aliases}`, javaMember(s, name));for (const [name, base] of s.receiverHeritage ?? []) out.set(`h\0${name}\0${base}\0${heritageImports}`, [name]);return out;}+/** `[Class.method, method]` for a Java method result, else `[name]`. */+function javaMember(s: SummaryFields, name: string): string[] {+ const dot = name.lastIndexOf(".");+ return s.language === "java" && dot > 0 ? [name, name.slice(dot + 1)] : [name];+}+/*** Names whose binding differs before and after: defined in one but not the* other, or now pointing at something else. None when the signature is the same.@@ -419,7 +428,8 @@ export function findDependents(// 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.+ // caller's receiver (a Scala `apply`, a Go `NewX`, a Java method result), 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()!])) {@@ -434,7 +444,7 @@ export function findDependents(dependsOn(parent, child);if (s.receiverPackage) dependsOn(parent, `${s.receiverPackage}.${child}`);}- for (const [factory, type] of s.receiverFactories ?? []) if (type) dependsOn(type, factory);+ for (const [factory, type] of s.receiverFactories ?? []) if (type) for (const name of javaMember(s, factory)) dependsOn(type, name);}const affectedNames = new Set(names);const pending = [...affectedNames];diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex 302ae394..dcfc16cb 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -191,7 +191,9 @@ Show methods/functions called by the given symbol (cross-file).### `ix callers <symbols...>`Show methods/functions that call the given symbols (cross-file). Several-symbols answer in one call, grouped per symbol.+symbols answer in one call, grouped per symbol. For a Java method, callers+through a superclass or interface follow the direct ones, tagged+`via=<Supertype>.<method>` (json: `via`).| Flag | Value | Default | Effect ||---|---|---|---|diff --git a/skills/ix/references/output-formats.md b/skills/ix/references/output-formats.mdindex 20f76f0e..f0230e1c 100644--- a/skills/ix/references/output-formats.md+++ b/skills/ix/references/output-formats.md@@ -21,6 +21,9 @@ Each row carries the location you would otherwise grep or re-read for:- `callers`, `callees`, `imports`, `imported-by` rows: `site=path:line` is thecall or import itself, with `snippet=` (the line) and `also=` (more sites inthe same scope); `path=`/`lines=` are where the other entity is defined.+ On a Java method, `callers` also lists callers through a superclass or+ interface after the direct ones, each ending `via=<Supertype>.<method>`+ (json: `via`).- `read`: every source line is `<line number><TAB><source>`, after a`content lines=<n> numbered=true` record — cite and edit by those numbers.- `text`: `match path=... line=... snippet=...`.