GitNexus/gitnexus/test/integration/cross-file-binding.test.ts
Gergő Magyar ab077b4c29
feat(ingestion): TypeScript registry-primary scope resolution (Ring 3) (#1050)
* feat(ingestion): TypeScript registry-primary scope resolution (Ring 3)

- Add TypeScript ScopeResolver stack (query/captures/interpret, import decomposition, hooks, arity, merge, receiver binding) and register in SCOPE_RESOLVERS.

- Harden shared compound receiver and receiver-bound CALLS pass for map for-of tuple bindings, dotted typeRef shapes, and callable-alias fallbacks.

- Flip TypeScript into MIGRATED_LANGUAGES; refresh AGENTS.md and type-resolution-system.md.

- Shared finalize-algorithm updates for cross-file scope parity.

- Tests: TS scope-resolution unit suite; legacy call-processor suite forces REGISTRY_PRIMARY_TYPESCRIPT=0; registry-primary flag test opts out TS in override scenario.

Made-with: Cursor

* fix(ingestion): SCC-ordered cross-file return-type propagation + multi-hop re-export resolution

Fix CI failures on PR #1050 (TypeScript registry-primary migration) by
making `propagateImportedReturnTypes` deterministic via reverse-
topological SCC ordering and updating the multi-hop re-export contract
to match `followReexportChain` behavior.

Why: the legacy pass mirrored an intermediate ref instead of the
terminal type when an importer was processed before its source module
had its own typeBindings chain-followed (4-file alias chain regression
in `ts-simple` fixture: `models.User -> service.user -> app.user`
collapsed to `getUser` instead of `User`). Reverse-topological walk of
`indexes.sccs` (leaves first) lets every importer see the source's
already-followed terminal type in a single pass.

Changes:
- `imported-return-types.ts`: rewrite to walk SCCs leaves-first, chain-
  follow the source module's typeBindings BEFORE mirroring, and chain-
  follow the importer's typeBindings AFTER mirroring. Cyclic SCCs
  reach a partial fixpoint (no convergence guarantee, ts-circular only
  asserts no-throw).
- `finalize-algorithm.ts`: docstring update on `FinalizeFile.localDefs`
  to reflect that `followReexportChain` resolves multi-hop re-exports
  through barrels even when intermediates do not surface the name -
  surfacing is now a static optimization, not a correctness requirement.
- `contract/scope-resolver.ts` Invariant I3: explicitly document the
  SCC ordering requirement.
- `pipeline/run.ts`: split PROF timer into `finalize` and `propagate`
  so the pass's cost is observable independently.
- `ARCHITECTURE.md` Performance notes: describe SCC-ordered propagation.
- `imported-return-types.ts`: expand chain-depth comment (2x effective
  depth from pre/post follow), add multi-ref break rationale, add
  `ts-simple` motivating-fixture pointer.

Tests:
- `finalize-algorithm.test.ts`: add 4 cases (3-hop chain, cyclic
  re-export visited-set guard, wildcard re-export fall-through,
  multi-source first-match-wins); fix misleading shared nodeId in the
  thick variant; rename and update the multi-hop test for the new
  contract (transitiveVia assertion on the thin variant).
- `imported-return-types.test.ts` (NEW): unit tests for the SCC pass
  pinning topological collapse, local-annotation guard, missing-source
  skip, and cyclic-SCC no-throw.
- `cross-file-binding.test.ts` + `ts-deep-alias-chain` fixture (NEW):
  5-file integration regression guard for SCC-ordered propagation
  through 4 module boundaries.

Validation: 865 scope-resolution + cross-file tests pass on Windows;
typecheck clean across both packages; only pre-existing Swift overload
failures remain (verified on PR base commit, environmental).

Made-with: Cursor

* fix(ingestion): address PR #1050 review findings — side-effect imports, resolve-cache perf, adapter signature

Three independent fixes surfaced by the production-readiness review of
the TypeScript registry-primary scope-resolution migration (RFC #909
Ring 3). All three pass under both REGISTRY_PRIMARY_TYPESCRIPT=0 and =1.

1. Side-effect imports were silently dropped (correctness regression).
   The legacy DAG emitted IMPORTS edges for `import './polyfill'` because
   its tree-sitter query matches `(import_statement source: (string))`
   regardless of clause. The new registry-primary path returned `[]`
   from `splitImportStatement()` for clause-less imports, so no
   ParsedImport / ImportEdge was ever produced — silent file-level edge
   loss. Add a generic 'side-effect' variant to `ParsedImport` and
   `ImportEdge['kind']` in `gitnexus-shared`; finalize resolves the
   target file and pre-finalizes the edge (no `targetDefId`, no
   `BindingRef`) so the SCC fixpoint loop skips it. The TypeScript
   provider now emits + interprets the new kind end-to-end. The
   variant is intentionally generic so other languages (Rust
   `use foo as _`, Python module-init) can adopt it.

2. Per-import re-derivation in `resolveImportTarget` (perf regression).
   The TS adapter built `new Set(allFilePaths)` on every call and let
   `resolveTsImportTarget` re-derive `allFileList` /
   `normalizedFileList` and discard the `resolveCache`. For a workspace
   with N files and M imports that's O(N × M) work per pass. Wrap the
   adapter in a closure that memoizes all five derived values keyed on
   the orchestrator's `ReadonlySet` identity; reset only when the set
   reference changes (start of new pass). New cost: O(N + M).

3. Misleading fake `ParsedImport` in the adapter (architecture).
   The adapter constructed `{ kind: 'named', localName: '_',
   importedName: '_', targetRaw }` to call `resolveTsImportTarget`,
   even though only `targetRaw` and the structural-typed context are
   read. Extract `resolveTsTarget(targetRaw, ctx)` so the adapter has
   an honest signature; `resolveTsImportTarget` still works for other
   callers. Also extract `narrowTsContext` for the type narrowing.

Tests: - New 4-file fixture `typescript-side-effect-imports` with two
    side-effect imports + one named import.
  - New "TypeScript side-effect imports" describe in
    `test/integration/resolvers/typescript.test.ts` (parity-gated by
    `ci-scope-parity.yml` — runs under both flag states).
  - Updated 2 unit tests to expect 1 side-effect ParsedImport and 4
    `@import.statement` matches (was 0 / 3).
  - 785 / 785 TS scope-resolution tests pass under both
    REGISTRY_PRIMARY_TYPESCRIPT=0 and =1.
Made-with: Cursor

* fix(scope): address Codex adversarial review findings on PR #1050

Four findings from the Codex adversarial review broke registry-primary
TypeScript resolution for common patterns. All four now have unit and
integration regression coverage that pass under both
`REGISTRY_PRIMARY_TYPESCRIPT=0` (legacy DAG) and the default
registry-primary path.

[high] tsconfig path aliases dropped:
Threaded `tsconfigPaths` through ScopeResolver via a new opaque
`resolutionConfig` parameter and a `loadResolutionConfig(repoPath)`
hook. The orchestrator (`scopeResolutionPhase` + `runScopeResolution`)
loads it once per workspace pass and forwards into every
`resolveImportTarget` call. TypeScript resolver now resolves
`@/services/user` style imports through the standard resolver's alias
branch.

[high] TSX parsed with the wrong grammar:
`emitTsScopeCaptures` now picks the parser/query by `filePath`
(`.tsx` -> TSX grammar) and validates cached trees against the
expected grammar via the new exported `tsCachedTreeMatchesGrammar`
helper. Stale TS-grammar trees for `.tsx` files no longer leak through
the scope query.

[medium] Literal dynamic imports never linked:
Added `kind: 'dynamic-resolved'` to `ParsedImport` and `ImportEdge`.
The decomposer emits a synthetic `@import.literal` capture for
string-literal dynamic imports; the interpreter maps that to
`dynamic-resolved`; finalize pre-finalizes it as a file-level terminal
(same shape as `side-effect`). `import('./feature')` now produces a
real IMPORTS edge under the registry-primary path. Legacy DAG keeps
its existing behavior — the new integration assertion is gated behind
the flag.

[medium] Namespace re-exports invisible from barrels:
The decomposer now emits TWO captures for `export * as ns from './m'`
— the existing `reexport-namespace` import draft AND a synthetic
`@declaration.namespace` capture (via `buildNamespaceDeclarationMatch`).
The latter creates a Namespace `SymbolDefinition` in the barrel's
`localDefs`, so downstream `import { ns } from './barrel'` resolves
through `findExportByName`.

Regression fixtures under `gitnexus/test/fixtures/lang-resolution/`:
- typescript-tsconfig-aliases (`@/` alias)
- typescript-tsx-jsx (Button.tsx + App.tsx with JSX)
- typescript-dynamic-import (`await import('./feature')`)
- typescript-reexport-namespace (`export * as Models from './base'`)

Validation:
- gitnexus-shared builds clean
- gitnexus typecheck clean
- 385/385 TS scope-resolution tests pass under both
  `REGISTRY_PRIMARY_TYPESCRIPT=0` and default

Made-with: Cursor

* perf(scope): O(1) defById lookup + bounded re-export depth (PR #1050 round 3)

Addresses the round-3 PR #1050 reviews (Claude adversarial + xkonjin):
both flagged the existing O(N²) `findDefById` linear scan in
`materializeBindings` and the unbounded recursion in
`followReexportChain` as production-readiness blockers for TypeScript
monorepos. Both fixes land alongside their regression tests under
both `REGISTRY_PRIMARY_TYPESCRIPT=0` and the default registry-primary
path.

[high] materializeBindings O(N_files × N_defs × N_edges) → O(N_defs + N_edges):
Build a `nodeId → SymbolDefinition` index map once at the top of
`materializeBindings` (one O(N_defs) pass), then replace the per-edge
`findDefById(files, edge.targetDefId)` linear scan with an O(1)
`defById.get(edge.targetDefId)` lookup. Also drop the now-unused
`findDefById` helper. At realistic TypeScript monorepo scale (~5k
files × ~50 defs/file × ~100k linked import edges) this is the
difference between ~25 s and a few ms inside finalize. Regression
test in `finalize-algorithm.test.ts` builds 200 leaf files +
1 consumer importing one symbol from each, asserts every binding
materializes correctly.

[medium] followReexportChain unbounded recursion:
The existing `visited` set caps depth at `O(N_files)` but allows
recursion proportional to barrel-chain depth, mismatching the
explicit "Iterative DFS to avoid stack overflow" policy in
`tarjanSccs`. Added a `MAX_REEXPORT_DEPTH = 100` constant and a
`depth` parameter to `followReexportChain` (defaults to 0); each
recursive call passes `depth + 1` and the function returns `null`
when the cap is exceeded. 100 is comfortably above any realistic
hand-authored barrel chain (typical depth 1-5; auto-generated
barrels rarely exceed 20) while staying well below JS engine call
stack limits. Regression test wires a 200-link reexport chain and
verifies the crawl terminates cleanly with `linkStatus: 'unresolved'`
(no terminal def reachable within the budget).

[low] synthesizeInstanceofNarrowings bare-identifier-only limitation:
xkonjin's review #4 noted that the LHS narrowing only handles bare
identifiers (`if (x instanceof Foo)`), not member expressions
(`if (user.address instanceof Address)`). Added a JSDoc note
explaining the constraint and pointing readers at field-type
resolution as the workaround for member-chain receivers.

Validation:
- gitnexus-shared builds clean
- gitnexus typecheck clean
- 413/413 tests pass under both flag states for finalize-algorithm +
  TS unit + TS integration suites
- 972/972 tests pass across full scope-resolution + Python +
  C# integration smoke (no cross-language regression)

Made-with: Cursor

* refactor(finalize): replace recursive followReexportChain with SCC-condensed iterative closure

The legacy `followReexportChain` walked re-export drafts via mutual
recursion guarded by a per-call visited set + a `MAX_REEXPORT_DEPTH`
ceiling. Recursion is fragile (call-stack ceiling, no bound on depth
that's actually meaningful), so this replaces it with a structurally
better algorithm: a precomputed per-file re-export closure built by
running Tarjan SCC over the re-export sub-graph and propagating names
in reverse-topological order with a bounded intra-SCC fixpoint.

Algorithm (`buildReexportClosures` in finalize-algorithm.ts):

  1. Sub-graph: build the directed graph of `reexport` + `wildcard`
     drafts only (regular/namespace/dynamic imports do not contribute).
  2. SCC condensation: run the same iterative `tarjanSccs` already
     used for the file-level import graph; output is in reverse-topo
     order so out-of-SCC neighbors are always already-finalized.
  3. Per-SCC propagation:
       - Acyclic singleton: one pass populates from neighbors' closures.
       - Cyclic SCC: bounded fixpoint capped at |SCC|+1 iterations.
         With first-wins precedence the closure map is monotone, so
         each name needs at most |SCC| hops to traverse the cycle.

Precedence (preserved from the recursive crawl):
  - Named re-exports take precedence over wildcards.
  - Within each kind, declaration order wins.

Lookup at finalize time becomes O(1) (`lookupReexportedName`), down
from O(chain_depth × drafts) per consult and recursive at that.

Properties vs the legacy implementation:
  - Stack-safe by construction; no `MAX_REEXPORT_DEPTH` guard needed.
  - 1000-hop barrel chains now resolve in full (legacy capped at 100
    and surfaced anything deeper as `unresolved`).
  - Cycles handled structurally via SCC, not via per-call visited set.
  - Same observable semantics: every existing test passes unchanged.

Tests:
  - Replace the obsolete `MAX_REEXPORT_DEPTH (200-hop chain stops
    cleanly without stack overflow)` test (which asserted the OLD
    bug — that deep chains failed to resolve) with a positive
    1000-hop test that asserts full resolution + accurate
    `transitiveVia`. Proves both the recursion is gone AND the
    closure correctly inherits the leaf def across all hops.
  - Update commentary on adjacent re-export tests to reference the
    closure mechanism.
  - Update `FinalizeFile.localDefs` JSDoc + import-decomposer.ts
    inline doc to point at `buildReexportClosures` instead of the
    removed function name.

Validation: - gitnexus-shared builds cleanly.
  - gitnexus typechecks cleanly.
  - 28/28 finalize-algorithm.test.ts tests pass (incl. new 1000-hop).
  - 801/801 TypeScript scope-resolution tests pass under default
    (registry-primary) AND `REGISTRY_PRIMARY_TYPESCRIPT=0` (legacy DAG).
  - 404/404 Python + C# integration tests pass — no regression in
    cross-language consumers of the shared `finalize`.
Made-with: Cursor

* fix(scope): remove non-null assertions from scope resolution

Made-with: Cursor

* fix(scope): address TypeScript review follow-ups

Made-with: Cursor

* fix(scope): address TypeScript import review follow-ups

Add regression coverage for non-binding import edges and circular TypeScript bindings so PR #1050 review concerns stay visible without changing runtime semantics.

Made-with: Cursor
2026-04-26 08:23:08 +01:00

895 lines
34 KiB
TypeScript

/**
* Phase 14: Cross-file type binding propagation
*
* When file A exports `const user = getUser()` (resolved to type User), and
* file B imports `user`, Phase 14 seeds `user → User` into file B's type
* environment, enabling `user.save()` in file B to produce a CALLS edge to
* User#save.
*/
import { describe, it, expect, beforeAll } from 'vitest';
import path from 'path';
import {
getRelationships,
getNodesByLabel,
runPipelineFromRepo,
type PipelineResult,
} from './resolvers/helpers.js';
const CROSS_FILE_FIXTURES = path.resolve(__dirname, '..', 'fixtures', 'cross-file-binding');
// ---------------------------------------------------------------------------
// Simple cross-file: models → service → app
// models.ts exports getUser(): User
// service.ts exports const user = getUser() (user → User via call-result)
// app.ts imports user from service → seeds user → User → resolves user.save()
// ---------------------------------------------------------------------------
describe('Cross-File Binding Propagation: TypeScript simple cross-file', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'ts-simple'), () => {});
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('detects getUser function and main function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getUser');
expect(getNodesByLabel(result, 'Function')).toContain('main');
});
it('resolves user.save() in main() to User#save via cross-file binding', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
it('resolves user.getName() in main() to User#getName via cross-file binding', () => {
const calls = getRelationships(result, 'CALLS');
const getNameCall = calls.find(
(c) => c.target === 'getName' && c.source === 'main' && c.targetFilePath.includes('models'),
);
expect(getNameCall).toBeDefined();
});
it('emits HAS_METHOD edges linking save and getName to User', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const saveEdge = hasMethod.find((e) => e.source === 'User' && e.target === 'save');
const getNameEdge = hasMethod.find((e) => e.source === 'User' && e.target === 'getName');
expect(saveEdge).toBeDefined();
expect(getNameEdge).toBeDefined();
});
it('emits IMPORTS edges across all three files', () => {
const imports = getRelationships(result, 'IMPORTS');
// service.ts → models.ts and app.ts → service.ts
expect(imports.length).toBeGreaterThanOrEqual(2);
const paths = imports.map((e) => `${e.sourceFilePath}${e.targetFilePath}`);
expect(paths.some((p) => p.includes('service') && p.includes('models'))).toBe(true);
expect(paths.some((p) => p.includes('app') && p.includes('service'))).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Deep alias chain: 5 files, type collapses across 4 module boundaries.
// Regression guard for SCC-ordered propagation (PR #1050) — without
// reverse-topological ordering, app.ts may be processed before
// service/util/bridge had their own typeBindings chain-followed,
// leaving `bridge` unresolvable. With SCC ordering the type collapses
// to `User` in a single pass.
//
// models.ts: class User; getUser(): User
// service.ts: const user = getUser() // user → User
// util.ts: const alias = user // alias → User
// bridge.ts: const bridge = alias // bridge → User
// app.ts: bridge.save(); bridge.getName() // resolve to User#save / #getName
// ---------------------------------------------------------------------------
describe('Cross-File Binding Propagation: TypeScript deep alias chain (5 files, SCC-ordered collapse)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'ts-deep-alias-chain'),
() => {},
);
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('resolves bridge.save() in main() to User#save through 4-hop alias chain', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
it('resolves bridge.getName() in main() to User#getName through 4-hop alias chain', () => {
const calls = getRelationships(result, 'CALLS');
const getNameCall = calls.find(
(c) => c.target === 'getName' && c.source === 'main' && c.targetFilePath.includes('models'),
);
expect(getNameCall).toBeDefined();
});
it('emits IMPORTS edges along the full chain (4 boundaries)', () => {
const imports = getRelationships(result, 'IMPORTS');
const paths = imports.map((e) => `${e.sourceFilePath}${e.targetFilePath}`);
expect(paths.some((p) => p.includes('service') && p.includes('models'))).toBe(true);
expect(paths.some((p) => p.includes('util') && p.includes('service'))).toBe(true);
expect(paths.some((p) => p.includes('bridge') && p.includes('util'))).toBe(true);
expect(paths.some((p) => p.includes('app') && p.includes('bridge'))).toBe(true);
});
});
// ---------------------------------------------------------------------------
// Re-export chain: core → index (barrel) → app
// core.ts exports getConfig(): Config
// index.ts re-exports getConfig from core (no new bindings)
// app.ts imports getConfig from index, creates local const config = getConfig()
// → config.validate() resolves to Config#validate via local call-result binding
// ---------------------------------------------------------------------------
describe('Cross-File Binding Propagation: TypeScript re-export chain', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'ts-reexport'), () => {});
}, 60000);
it('detects Config class with validate method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Config');
expect(getNodesByLabel(result, 'Method')).toContain('validate');
});
it('detects getConfig function and init function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getConfig');
expect(getNodesByLabel(result, 'Function')).toContain('init');
});
it('resolves config.validate() in init() to Config#validate', () => {
const calls = getRelationships(result, 'CALLS');
const validateCall = calls.find(
(c) => c.target === 'validate' && c.source === 'init' && c.targetFilePath.includes('core'),
);
expect(validateCall).toBeDefined();
});
it('emits HAS_METHOD edge from Config to validate', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const edge = hasMethod.find((e) => e.source === 'Config' && e.target === 'validate');
expect(edge).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// E3: Cross-file return type propagation
// api.ts exports getConfig(): Config
// consumer.ts imports getConfig, calls const c = getConfig(); c.validate()
// → c is typed Config via importedReturnTypes (E3), enabling Config#validate edge
// ---------------------------------------------------------------------------
describe('Cross-File Binding Propagation: TypeScript E3 return type propagation', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'ts-return-type'), () => {});
}, 60000);
it('detects Config class with validate method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Config');
expect(getNodesByLabel(result, 'Method')).toContain('validate');
});
it('detects getConfig function and run function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getConfig');
expect(getNodesByLabel(result, 'Function')).toContain('run');
});
it('resolves c.validate() in run() to Config#validate via cross-file return type propagation', () => {
const calls = getRelationships(result, 'CALLS');
const validateCall = calls.find(
(c) => c.target === 'validate' && c.source === 'run' && c.targetFilePath.includes('api'),
);
expect(validateCall).toBeDefined();
});
it('emits HAS_METHOD edge from Config to validate', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const edge = hasMethod.find((e) => e.source === 'Config' && e.target === 'validate');
expect(edge).toBeDefined();
});
it('emits IMPORTS edge from consumer to api', () => {
const imports = getRelationships(result, 'IMPORTS');
const edge = imports.find(
(e) => e.sourceFilePath.includes('consumer') && e.targetFilePath.includes('api'),
);
expect(edge).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Circular imports: a.ts ↔ b.ts
// a.ts imports getB from b.ts; b.ts imports A from a.ts
// Regression guard: the pipeline completes and still resolves the
// imported factory plus the inferred receiver binding for b.doB().
// ---------------------------------------------------------------------------
describe('Cross-File Binding Propagation: TypeScript circular imports', () => {
let result: PipelineResult;
let pipelineError: unknown;
beforeAll(async () => {
try {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'ts-circular'), () => {});
} catch (err) {
pipelineError = err;
}
}, 60000);
it('pipeline completes without throwing on circular imports', () => {
expect(pipelineError).toBeUndefined();
});
it('detects both class A and class B', () => {
expect(getNodesByLabel(result, 'Class')).toContain('A');
expect(getNodesByLabel(result, 'Class')).toContain('B');
});
it('detects doA and doB methods', () => {
expect(getNodesByLabel(result, 'Method')).toContain('doA');
expect(getNodesByLabel(result, 'Method')).toContain('doB');
});
it('detects processA and getB functions', () => {
expect(getNodesByLabel(result, 'Function')).toContain('processA');
expect(getNodesByLabel(result, 'Function')).toContain('getB');
});
it('emits IMPORTS edges reflecting the circular dependency', () => {
const imports = getRelationships(result, 'IMPORTS');
const paths = imports.map((e) => `${e.sourceFilePath}${e.targetFilePath}`);
// a.ts imports from b.ts
expect(paths.some((p) => p.includes('a.ts') && p.includes('b.ts'))).toBe(true);
// b.ts imports from a.ts
expect(paths.some((p) => p.includes('b.ts') && p.includes('a.ts'))).toBe(true);
});
it('resolves processA through imported getB and inferred B.doB binding', () => {
const calls = getRelationships(result, 'CALLS');
const getBCall = calls.find((c) => c.source === 'processA' && c.target === 'getB');
expect(getBCall).toBeDefined();
expect(getBCall!.targetFilePath).toBe('src/b.ts');
const doBCall = calls.find((c) => c.source === 'processA' && c.target === 'doB');
expect(doBCall).toBeDefined();
expect(doBCall!.targetLabel).toBe('Method');
expect(doBCall!.targetFilePath).toBe('src/b.ts');
});
});
// ---------------------------------------------------------------------------
// SM-15 / Phase 9: Cross-file call-result variable binding — multi-language
//
// Each suite below loads a multi-file fixture where:
// - File A defines a factory function getUser() / get_user() → User
// - File B imports that function, calls `u = getUser()`, then calls u.save()
//
// The acceptance criteria: u.save() / u.save() / u.get_name() must resolve
// to the correct User method via cross-file call-result variable binding.
// These tests cover both the SymbolTable path (languages with explicit return
// type annotations) and validate that the Phase 9 BindingAccumulator wiring
// does not break existing behavior.
// ---------------------------------------------------------------------------
describe('Phase 9 — Cross-File Call-Result Binding: Java', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'java-cross-file'), () => {});
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('detects getUser factory and run method', () => {
expect(getNodesByLabel(result, 'Method')).toContain('getUser');
expect(getNodesByLabel(result, 'Method')).toContain('run');
});
it('resolves user.save() in run() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'run' && c.targetFilePath.includes('User'),
);
expect(saveCall).toBeDefined();
});
it('resolves user.getName() in run() to User#getName via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const getNameCall = calls.find(
(c) => c.target === 'getName' && c.source === 'run' && c.targetFilePath.includes('User'),
);
expect(getNameCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: Python', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'py-cross-file'), () => {});
}, 60000);
it('detects User class with save and get_name methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
// Python tree-sitter captures all function_definitions as Function, including methods
expect(getNodesByLabel(result, 'Function')).toContain('save');
expect(getNodesByLabel(result, 'Function')).toContain('get_name');
});
it('detects get_user function and run function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('get_user');
expect(getNodesByLabel(result, 'Function')).toContain('run');
});
it('resolves u.save() in run() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'run' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
it('resolves u.get_name() in run() to User#get_name via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const getNameCall = calls.find(
(c) => c.target === 'get_name' && c.source === 'run' && c.targetFilePath.includes('models'),
);
expect(getNameCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: Go', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'go-cross-file'), () => {});
}, 60000);
it('detects User struct with Save and GetName methods', () => {
expect(getNodesByLabel(result, 'Struct')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('Save');
expect(getNodesByLabel(result, 'Method')).toContain('GetName');
});
it('detects GetUser function and main function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('GetUser');
expect(getNodesByLabel(result, 'Function')).toContain('main');
});
it('resolves user.Save() in main() to User#Save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'Save' && c.source === 'main' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: Kotlin', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'kotlin-cross-file'),
() => {},
);
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('detects getUser function and run method', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getUser');
expect(getNodesByLabel(result, 'Method')).toContain('run');
});
it('resolves u.save() in run() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'run' && c.targetFilePath.includes('User'),
);
expect(saveCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: Rust', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'rs-cross-file'), () => {});
}, 60000);
it('detects User struct with save and get_name methods', () => {
expect(getNodesByLabel(result, 'Struct')).toContain('User');
// Rust tree-sitter captures impl fns as Function nodes
expect(getNodesByLabel(result, 'Function')).toContain('save');
expect(getNodesByLabel(result, 'Function')).toContain('get_name');
});
it('detects get_user function and process function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('get_user');
expect(getNodesByLabel(result, 'Function')).toContain('process');
});
it('resolves u.save() in process() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
});
// ── R5: Missing language coverage (PR #763 review finding #5) ────────────
describe('Phase 9 — Cross-File Call-Result Binding: JavaScript', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'js-cross-file'), () => {});
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('detects getUser factory and run function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getUser');
expect(getNodesByLabel(result, 'Function')).toContain('run');
});
it('resolves u.save() in run() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'run' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: C++', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'cpp-cross-file'), () => {});
}, 60000);
it('detects User class with save and get_name methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('get_name');
});
it('detects get_user factory function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('get_user');
});
it('resolves user.save() in process() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath.includes('user'),
);
expect(saveCall).toBeDefined();
});
});
describe('Cross-File Call Resolution: pure C transitive #include', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'c-cross-file'), () => {});
}, 60000);
it('detects dictFind and dictFetchValue functions', () => {
expect(getNodesByLabel(result, 'Function')).toContain('dictFind');
expect(getNodesByLabel(result, 'Function')).toContain('dictFetchValue');
});
it('detects lookupKey and dbGet in db.c', () => {
expect(getNodesByLabel(result, 'Function')).toContain('lookupKey');
expect(getNodesByLabel(result, 'Function')).toContain('dbGet');
});
it('resolves dictFind() call in db.c to dict via transitive header chain', () => {
const calls = getRelationships(result, 'CALLS');
const crossFileCall = calls.find(
(c) =>
c.target === 'dictFind' && c.source === 'lookupKey' && c.targetFilePath.includes('dict'),
);
expect(crossFileCall).toBeDefined();
});
it('resolves dictFetchValue() call in db.c to dict via transitive header chain', () => {
const calls = getRelationships(result, 'CALLS');
const crossFileCall = calls.find(
(c) =>
c.target === 'dictFetchValue' && c.source === 'dbGet' && c.targetFilePath.includes('dict'),
);
expect(crossFileCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: C#', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'csharp-cross-file'),
() => {},
);
}, 60000);
it('detects User class with Save and GetName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('Save');
expect(getNodesByLabel(result, 'Method')).toContain('GetName');
});
it('detects GetUser factory and Run method', () => {
expect(getNodesByLabel(result, 'Method')).toContain('GetUser');
expect(getNodesByLabel(result, 'Method')).toContain('Run');
});
it('resolves u.Save() in Run() to User#Save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'Save' && c.source === 'Run' && c.targetFilePath.includes('User'),
);
expect(saveCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: PHP', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'php-cross-file'), () => {});
}, 60000);
it('detects User class with save and getName methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('getName');
});
it('detects getUser factory function', () => {
expect(getNodesByLabel(result, 'Function')).toContain('getUser');
});
it('resolves $u->save() in run() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'run' && c.targetFilePath.includes('User'),
);
expect(saveCall).toBeDefined();
});
});
describe('Phase 9 — Cross-File Call-Result Binding: Ruby', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(path.join(CROSS_FILE_FIXTURES, 'rb-cross-file'), () => {});
}, 60000);
it('detects User class with save and get_name methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
expect(getNodesByLabel(result, 'Method')).toContain('get_name');
});
it('detects get_user factory method', () => {
expect(getNodesByLabel(result, 'Method')).toContain('get_user');
});
it('resolves user.save in process() to User#save via cross-file return type', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath.includes('models'),
);
expect(saveCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Note: shadowed import tier gating is tested at the unit level
// (call-processor.test.ts "Phase 9 tier gating" tests) because the scenario
// requires invalid TypeScript (same name imported and locally defined).
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Regression: consumer file processed before provider in sequential path
// a-consumer.ts (alphabetically first) imports getUser from b-provider.ts.
// Without the two-pass flush fix, the accumulator wouldn't have b-provider's
// bindings when a-consumer's verifyConstructorBindings runs.
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Consumer-before-provider regression tests (sequential ordering fix)
//
// Each language fixture has a consumer file that sorts alphabetically before
// the provider file. In the sequential path, the consumer is processed first.
// The two-pass flush ensures the accumulator has provider bindings before
// verifyConstructorBindings runs for the consumer.
// ---------------------------------------------------------------------------
describe('Consumer-Before-Provider: TypeScript', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'ts-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method from provider', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves x.save() to User#save despite consumer sorted before provider', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath.includes('b-provider'),
);
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: JavaScript', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'js-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves u.save() in main() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath.includes('b-provider'),
);
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Python', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'py-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save function', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
// Python tree-sitter captures all function_definitions as Function, including methods
expect(getNodesByLabel(result, 'Function')).toContain('save');
});
it('resolves u.save() in main() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath.includes('b_provider'),
);
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Java', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'java-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves user.save() in run() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'run');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Go', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'go-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User struct and Save method', () => {
expect(getNodesByLabel(result, 'Struct')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('Save');
});
it('resolves user.Save() in main() to User#Save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'Save' && c.source === 'main');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: C++', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'cpp-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves user.save() in process() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'process');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: C#', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'csharp-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and Save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('Save');
});
it('resolves u.Save() in Run() to User#Save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'Save' && c.source === 'Run');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Kotlin', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'kotlin-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves u.save() in run() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'run');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: PHP', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'php-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves $u->save() in run() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'run');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Ruby', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'rb-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User class and save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('save');
});
it('resolves user.save in process() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'process');
expect(saveCall).toBeDefined();
});
});
describe('Consumer-Before-Provider: Rust', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(CROSS_FILE_FIXTURES, 'rs-consumer-before-provider'),
() => {},
);
}, 60000);
it('detects User struct and save function', () => {
expect(getNodesByLabel(result, 'Struct')).toContain('User');
// Rust tree-sitter captures impl fns as Function nodes
expect(getNodesByLabel(result, 'Function')).toContain('save');
});
it('resolves u.save() in process() to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'process');
expect(saveCall).toBeDefined();
});
});