GitNexus/gitnexus/test/integration/resolvers/ruby-scope.test.ts
Gergő Magyar 083aedbc41
refactor(ingestion): delete legacy call-resolution DAG + heritage processor (RING4-1, #942) (#2023)
* refactor(ingestion): delete legacy call-resolution DAG + heritage processor (#942)

RING4-1: all 16 production languages (incl. Vue #940) are registry-primary, so
the legacy resolution legs only ran under the now-removed CI parity gate. Calls
and inheritance now resolve exclusively through scope-resolution
(Registry.lookup, preEmitInheritanceEdges, emitHeritageEdges, buildMro →
MethodDispatchIndex).

Removed:
- Call-resolution DAG: call-processor.ts legacy body (processCalls,
  processCallsFromExtracted, resolveCallTarget + all resolver/dispatch/chain
  helpers), model/resolve.ts MRO-via-HeritageMap, model/heritage-map.ts,
  type-env DAG types; inferImplicitReceiver/selectDispatch LanguageProvider
  hooks + Ruby impls; DispatchDecision/ImplicitReceiverOverride/ReceiverEnriched.
- Legacy heritage path: heritage-processor.ts, heritage-types.ts,
  heritage-extractors/, @heritage.* tree-sitter queries, heritageExtractor/
  heritageDefaultEdge/interfaceNamePattern wiring, worker + parse-impl heritage
  passes (parse-worker/parsing-processor lockstep), cross-file-impl DAG pass.
- Scope-parity infrastructure entirely (no legacy↔registry parity left to run):
  scripts/run-parity.ts, scripts/ci-list-migrated-languages.ts,
  ci-scope-parity.yml, test:parity, and the scope-parity ci.yml gate. Resolver
  integration tests still run via the normal tests job.

Kept (shared infra, NOT call-DAG-only): type-env.ts buildTypeEnv (field
extraction / structure phase / embeddings), model/resolve.ts c3Linearize +
gatherAncestors (mro-processor mroPhase), route/fetch/exported-type-map helpers
in call-processor.ts, preEmitInheritanceEdges (legacy-edge dedup simplified).

Acceptance: grep for resolveCallTarget/inferImplicitReceiver/selectDispatch/
buildHeritageMap/HeritageMap/processHeritage/heritageExtractor/@heritage. is zero
across src + test. tsc clean (both packages); resolver integration suite green
(bit-compatible EXTENDS/IMPLEMENTS/CALLS); scope-capture fingerprints unchanged
(python re-baselined: removed redundant ignored captures). ARCHITECTURE.md
updated to scope-resolution-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(review): apply autofix feedback (#942)

ce-code-review autofix pass on the RING4-1 deletion:
- parse-cache.ts: bump SCHEMA_BUMP 2→3 — ParseWorkerResult lost its `heritage`
  field, so stale on-disk caches must invalidate (prevents a rollback replaying
  a heritage-less cache into legacy code) [api-contract P2].
- parse-impl.ts: drop 3 now-unused type imports (ExtractedCall,
  ExtractedAssignment, FileConstructorBindings) left by the deferred-block
  removal — would fail the eslint CI gate [correctness+maintainability P1].
- AGENTS.md / CLAUDE.md / scope-resolver.ts contract doc: fix stale pointers to
  the deleted "§ Call-Resolution DAG" section + removed hooks; preserve the
  language-neutrality rule [project-standards P1].
- registry-primary-flag.ts / cross-file.ts / parse-impl.ts: refresh stale
  comments referencing deleted symbols (legacy DAG, runCrossFileBindingPropagation).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(ingestion): remove the vestigial isRegistryPrimary flag (#942)

With the legacy call-resolution DAG deleted, the per-language
`REGISTRY_PRIMARY_<LANG>` / `isRegistryPrimary` / `MIGRATED_LANGUAGES` flag had
only one meaningful state — every production language resolves via
scope-resolution — and an explicit `=0` override could only *disable*
resolution with no fallback (a footgun the review flagged). Removing it.

- Delete `registry-primary-flag.ts` and the now-dead `shadow-harness.ts`
  (legacy↔registry shadow-parity tool) + its test.
- Collapse the three flag gates to their behavior-preserving outcome
  (`SCOPE_RESOLVERS == MIGRATED_LANGUAGES`, so this is a no-op):
  - scope-resolution phase now runs for every registered `SCOPE_RESOLVERS`
    entry (was `∩ MIGRATED_LANGUAGES`).
  - import-processor `addImportGraphEdge` + parse-impl `shouldAccumulate`:
    the legacy emit/accumulate paths were already inert for migrated
    languages (scope-resolution owns IMPORTS via the imports-to-edges bridge);
    drop the flag term.
- Collapse flag-branching tests to the scope-resolution path and delete the
  csharp legacy-`=0`-leg describe blocks; remove the ruby/rust-scope env-forcing
  hooks (no-ops now).
- Refresh docs/comments (ARCHITECTURE.md "one registration", scope-resolver
  cookbook, phase deps) — adding a language is now a single `SCOPE_RESOLVERS`
  registration.

Verified: tsc clean (both packages); resolver integration tests green
(747 assertions across cobol/csharp/ruby/rust/typescript/go, IMPORTS edges
intact); grep for the flag symbols is zero across src + test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style(format): prettier formatting on #942 changes

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): drop legacy heritage-capture tests + re-baseline scope-capture fingerprints (#942)

Two CI failures from the #942 cleanup, surfaced by the tri-review + CI:

- tree-sitter-languages.test.ts: two tests asserted `@heritage.*` captures
  (Rust trait-impl, Dart extends/implements/with) that this PR removed. The
  acceptance grep used `@heritage\.` (with `@`); these reference the runtime
  capture name `heritage.trait` (no `@`), so they slipped the earlier sweep.
  Inheritance is now covered by the resolver integration suite. (fixed macos-latest)

- Re-baselined the scope-capture bench fingerprints for csharp/rust/ruby/java/
  javascript/kotlin (baselines.json) + python (python-scope/baseline-fingerprint.txt).
  The earlier test-cleanup reworded comments inside the lang-resolution fixture
  files (Shapes.cs, child.rs, derived.rb, IA.java/Plain.java, Service.js, F.kt,
  app.py) to scrub deleted-symbol references for the acceptance grep; those are
  the bench corpus, so capture node positions shifted. Capture LOGIC is
  unchanged — verified `--check` passes for all 14 langs + python. (fixed benchmarks)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs/chore: scrub remaining REGISTRY_PRIMARY + deleted-symbol references (#942)

Tri-review P3 follow-ups (verified):
- TESTING.md: rewrite the "Scope-resolution parity" section — the legacy
  dual-leg (REGISTRY_PRIMARY_<LANG>=0/1) and `npm run test:parity` no longer
  exist; resolver tests run once on the sole scope-resolution path in the
  normal tests job.
- scripts/bench-scope-resolution.ts: drop the inert `REGISTRY_PRIMARY_PYTHON=1`
  env set + usage hint (the flag is gone).
- ruby/scope-resolver.ts, php/captures.ts: re-point doc-comments off the
  deleted heritage-map.ts / heritage-processor.ts to the current behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): prettier format + regenerate scope-capture goldens (#942)

Two more CI failures, same root cause as the bench re-baseline (the
test-cleanup reworded comments in lang-resolution bench/golden-corpus fixtures):

- quality/format: prettier on tree-sitter-languages.test.ts (blank line left by
  the deleted heritage-capture tests) + TESTING.md (the rewritten section).
- tests/ubuntu/coverage: `csharp-captures-golden` (and python/ruby/rust) drifted
  because the edited fixtures feed the per-language capture-golden snapshots too
  (not just the bench). Regenerated via UPDATE_GOLDEN=1. Verified safe: only the
  edited-fixture entries changed; csharp `captureGroups` unchanged (38) — digest
  shifted from comment-position only; capture LOGIC untouched. 1168 scope-
  resolution tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(resolvers): drop createResolverParityIt wrapper, use vitest it directly

The parity-aware `it` wrapper became a no-op when #942 removed the legacy
call-resolution DAG (it just returned vitest's `it`). Remove it entirely so
the resolver tests call vitest's `it` directly instead of shadowing it with a
local `const it` (or `pit`/`rustParityIt`):

- helpers.ts: delete createResolverParityIt + its now-unused vitestIt import
  and VitestIt type.
- 16 files: drop `const it = createResolverParityIt('x')` and import `it`
  from vitest instead.
- ruby.test.ts (pit) + rust.test.ts (rustParityIt): rename calls to `it`.
- Scrub every comment that described the removed wrapper / dual-mode parity
  skip / legacy_skip gate (vue-scope, js/ts/dart/php/python headers, rust x2,
  cpp, swift x4, rust-coverage). Genuine test rationale is kept; only the
  vestigial two-leg framing is dropped. Accurate "legacy DAG (removed in
  #942)" historical notes are retained.

No fixtures touched (no bench/golden re-baseline). tsc clean; rust+ruby
resolver suites green (323 tests, incl. #1992 worker-path parity after a
local dist build).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 11:07:37 +01:00

469 lines
13 KiB
TypeScript

/**
* Ruby scope-resolution integration tests (U8).
*
* These tests exercise the scope-based resolution path. They validate
* class methods, module mixins,
* singleton methods, require_relative imports, constructor inference,
* block scope, class inheritance, and super resolution.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import path from 'path';
import fs from 'node:fs';
import os from 'node:os';
import {
getRelationships,
getNodesByLabel,
runPipelineFromRepo,
type PipelineResult,
} from './helpers.js';
function writeFixtureRepo(root: string, files: Record<string, string>): void {
for (const [rel, content] of Object.entries(files)) {
const abs = path.join(root, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, content, 'utf8');
}
}
// ---------------------------------------------------------------------------
// 1. Basic class method resolution
// ---------------------------------------------------------------------------
describe('Ruby scope: basic class method resolution', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-basic-'));
writeFixtureRepo(tmpDir, {
'models/user.rb': `
class User
def save
true
end
def greet
"hello"
end
end
`,
'app.rb': `
require_relative 'models/user'
def main
u = User.new
u.save
u.greet
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects User class', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
});
it('detects save and greet as Method nodes', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('save');
expect(methods).toContain('greet');
});
it('emits HAS_METHOD edges from User to save and greet', () => {
const edges = getRelationships(result, 'HAS_METHOD');
const userSave = edges.find((e) => e.source === 'User' && e.target === 'save');
const userGreet = edges.find((e) => e.source === 'User' && e.target === 'greet');
expect(userSave).toBeDefined();
expect(userGreet).toBeDefined();
});
it('resolves main → u.save() as CALLS edge', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(
(c) => c.target === 'save' && c.source === 'main' && c.targetFilePath?.includes('user.rb'),
);
expect(saveCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 2. Module mixin with include
// ---------------------------------------------------------------------------
describe('Ruby scope: module mixin with include', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-mixin-'));
writeFixtureRepo(tmpDir, {
'serializable.rb': `
module Serializable
def serialize
to_json
end
end
`,
'user.rb': `
require_relative 'serializable'
class User
include Serializable
def save
serialize
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects User as Class and Serializable as Trait', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Trait')).toContain('Serializable');
});
it('emits IMPLEMENTS edge from User to Serializable', () => {
const impls = getRelationships(result, 'IMPLEMENTS');
const edge = impls.find((e) => e.source === 'User' && e.target === 'Serializable');
expect(edge).toBeDefined();
});
it('resolves save → serialize as CALLS edge', () => {
const calls = getRelationships(result, 'CALLS');
const serializeCall = calls.find((c) => c.target === 'serialize' && c.source === 'save');
expect(serializeCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 3. Singleton method (def self.foo)
// ---------------------------------------------------------------------------
describe('Ruby scope: singleton method (def self.foo)', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-singleton-'));
writeFixtureRepo(tmpDir, {
'config.rb': `
class Config
def self.load
new
end
def validate
true
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects Config class', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Config');
});
it('detects load (singleton) and validate (instance) as Method nodes', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('load');
expect(methods).toContain('validate');
});
it('emits HAS_METHOD edges from Config to both methods', () => {
const edges = getRelationships(result, 'HAS_METHOD');
const configLoad = edges.find((e) => e.source === 'Config' && e.target === 'load');
const configValidate = edges.find((e) => e.source === 'Config' && e.target === 'validate');
expect(configLoad).toBeDefined();
expect(configValidate).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 4. Require/require_relative import resolution
// ---------------------------------------------------------------------------
describe('Ruby scope: require_relative import resolution', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-imports-'));
writeFixtureRepo(tmpDir, {
'lib/utils.rb': `
class Utils
def format(text)
text.strip
end
end
`,
'app.rb': `
require_relative 'lib/utils'
def run
u = Utils.new
u.format("hello")
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('emits IMPORTS edge from app.rb to lib/utils.rb', () => {
const imports = getRelationships(result, 'IMPORTS');
const imp = imports.find(
(e) => e.sourceFilePath?.includes('app.rb') && e.targetFilePath?.includes('utils.rb'),
);
expect(imp).toBeDefined();
});
it('resolves run → u.format() as CALLS edge to utils.rb', () => {
const calls = getRelationships(result, 'CALLS');
const formatCall = calls.find(
(c) => c.target === 'format' && c.source === 'run' && c.targetFilePath?.includes('utils.rb'),
);
expect(formatCall).toBeDefined();
});
it('detects Utils class and format method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Utils');
expect(getNodesByLabel(result, 'Method')).toContain('format');
});
});
// ---------------------------------------------------------------------------
// 5. Constructor inference (User.new)
// ---------------------------------------------------------------------------
describe('Ruby scope: constructor inference via .new', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-ctor-'));
writeFixtureRepo(tmpDir, {
'formatter.rb': `
class Formatter
def format(text)
text.upcase
end
end
def main
f = Formatter.new
f.format("hello")
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects Formatter class and format method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Formatter');
expect(getNodesByLabel(result, 'Method')).toContain('format');
});
it('emits HAS_METHOD edge from Formatter to format', () => {
const edges = getRelationships(result, 'HAS_METHOD');
const fmtEdge = edges.find((e) => e.source === 'Formatter' && e.target === 'format');
expect(fmtEdge).toBeDefined();
});
it('resolves main → f.format() to Formatter#format via constructor inference', () => {
const calls = getRelationships(result, 'CALLS');
const formatCall = calls.find(
(c) =>
c.target === 'format' && c.source === 'main' && c.targetFilePath?.includes('formatter.rb'),
);
expect(formatCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 6. Block scope (do...end with params)
// ---------------------------------------------------------------------------
describe('Ruby scope: block scope with do...end', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-block-'));
writeFixtureRepo(tmpDir, {
'processor.rb': `
class Processor
def run
items = [1, 2, 3]
items.each do |item|
process(item)
end
end
def process(x)
x * 2
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects Processor class', () => {
expect(getNodesByLabel(result, 'Class')).toContain('Processor');
});
it('detects run and process as Method nodes on Processor', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('run');
expect(methods).toContain('process');
});
it('emits HAS_METHOD edges from Processor to run and process', () => {
const edges = getRelationships(result, 'HAS_METHOD');
const procRun = edges.find((e) => e.source === 'Processor' && e.target === 'run');
const procProcess = edges.find((e) => e.source === 'Processor' && e.target === 'process');
expect(procRun).toBeDefined();
expect(procProcess).toBeDefined();
});
it('resolves run → process() as CALLS edge inside block scope', () => {
const calls = getRelationships(result, 'CALLS');
const processCall = calls.find((c) => c.target === 'process' && c.source === 'run');
expect(processCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 7. Class inheritance (EXTENDS)
// ---------------------------------------------------------------------------
describe('Ruby scope: class inheritance via <', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-inherit-'));
writeFixtureRepo(tmpDir, {
'animals.rb': `
class Animal
def speak
"..."
end
end
class Dog < Animal
def bark
speak
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects Animal and Dog as Class nodes', () => {
const classes = getNodesByLabel(result, 'Class');
expect(classes).toContain('Animal');
expect(classes).toContain('Dog');
});
it('emits EXTENDS edge from Dog to Animal', () => {
const extends_ = getRelationships(result, 'EXTENDS');
const edge = extends_.find((e) => e.source === 'Dog' && e.target === 'Animal');
expect(edge).toBeDefined();
});
it('resolves bark → speak as CALLS edge', () => {
const calls = getRelationships(result, 'CALLS');
const speakCall = calls.find((c) => c.target === 'speak' && c.source === 'bark');
expect(speakCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// 8. Super resolution
// ---------------------------------------------------------------------------
describe('Ruby scope: super resolution in subclass', () => {
let result: PipelineResult;
let tmpDir: string;
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-scope-super-'));
writeFixtureRepo(tmpDir, {
'hierarchy.rb': `
class Base
def greet
"hello"
end
end
class Child < Base
def greet
super
end
end
def main
c = Child.new
c.greet
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('detects Base and Child as Class nodes', () => {
const classes = getNodesByLabel(result, 'Class');
expect(classes).toContain('Base');
expect(classes).toContain('Child');
});
it('emits EXTENDS edge from Child to Base', () => {
const extends_ = getRelationships(result, 'EXTENDS');
const edge = extends_.find((e) => e.source === 'Child' && e.target === 'Base');
expect(edge).toBeDefined();
});
it('resolves main → c.greet() as CALLS edge', () => {
const calls = getRelationships(result, 'CALLS');
const greetCall = calls.find((c) => c.target === 'greet' && c.source === 'main');
expect(greetCall).toBeDefined();
});
});