mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-14 23:22:54 +00:00
* fix(ingestion): reduce parse-phase memory for huge repos (#1983)
Stop retaining full parse-cache chunks in RAM alongside the merged graph,
slim on-disk shards, defer worker ParsedFile emission for scope-resolver
languages, and add GITNEXUS_DEBUG_HEAP probes for OOM diagnosis.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(ingestion): address #2038 tri-review findings (parse-phase memory)
Resolves the confirmed review findings on PR #2038:
- P1: thread exportedTypeMap through the sequential parse path
(processParsingSequential) so a no-worker run over a partially-warm
cache no longer silently drops the sequential-miss files' exported
types. Cache hits made exportedTypeMap.size > 0, suppressing the
end-of-loop buildExportedTypeMapFromGraph rebuild, but the sequential
path never populated the map. Regression test added (fails on the
pre-fix tree, passes after) plus a fully-sequential differential oracle.
- P2: saveParseCache builds its on-disk index from hashes actually
written/copied (writtenKeys), never a usedKeys hash whose shard write
or copy was skipped — no more phantom index entries.
- P2: add a unit test asserting SCOPE_RESOLUTION_LANGUAGES stays in sync
with SCOPE_RESOLVERS (asymmetric drift would lose a language's ParsedFile).
- Backfill cache coverage: loadParseCacheChunk missing/corrupt -> undefined,
pruneCache onDiskKeys branch, slim preserves nodes, saveParseCache
copy-evicted-shard round-trip.
- Cleanups: single-source heap-probe gating via isDebugHeapEnabled();
hoist the per-chunk mkdir in persistParseCacheChunk behind a
process-scoped Set; gate COBOL's unused worker-side ParsedFile
extraction (graph nodes still come from cobolPhase) while keeping
fileCount/progress unconditional.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(ingestion): remove dead worker-side ParsedFile extraction
After #2038 gated worker `ParsedFile` emission behind `!isScopeResolutionLanguage(language)`, and with all 16 SupportedLanguages registered in SCOPE_RESOLVERS, that gate was structurally always true — the worker already produced no ParsedFiles and scope-resolution re-extracts each file from source on the main thread (run.ts). Remove the now-dead machinery:
- Drop both worker `extractParsedFile` call-sites (tree-sitter processFileGroup + the standalone-provider branch) and the `result.parsedFiles.push`. The standalone branch keeps fileCount/onFileProcessed per file. `result.parsedFiles` stays declared but empty (field removal deferred).
- Remove the now-orphaned `scopeSourceKind` var + `ScopeCaptureSourceKind`/`extractParsedFile`/`isScopeResolutionLanguage` imports.
- Delete the consumerless `migrated-languages.ts` (isScopeResolutionLanguage + SCOPE_RESOLUTION_LANGUAGES) and its drift-guard test — parse-worker was their only importer. Also improves AGENTS.md "shared ingestion code must not name languages" compliance.
`extractParsedFile` and the scope-extractor-bridge stay (scope-resolution/run.ts + Vue resolver use them). Behavior-preserving: worker-sequential-parity passes before and after; tsc/eslint clean; no baseline/golden drift.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* refactor(ingestion): worker-pool-only parsing; remove sequential parser (#1983)
Completes the #1983 huge-repo parse-OOM effort by making the worker pool
GitNexus's sole parse path.
Parallel serialization (the perf core): workers serialize their ParsedFiles to
a disk store in parallel and stream them back to scope-resolution, so the main
thread no longer re-parses every file (the tree-sitter native-memory leak that
caused the OOM). Adds chunk merge-pipelining + work-proportional chunk sizing so
the pool stays saturated.
Remove the sequential parser: `--workers 0`, `GITNEXUS_WORKER_POOL_SIZE=0`, and
`skipWorkers` now hard-error (no silent degrade — #1741); the small-repo
threshold no longer selects an in-process path; pool creation stays lazy /
cache-miss-gated so warm all-hit runs never spawn workers.
Worker-path parity fixes — removing sequential surfaced two pre-existing gaps
that tiny-fixture tests had masked by running below the worker threshold, both
fixed by carrying per-file metadata as DATA across the worker boundary (never
re-parsing on the main thread, preserving the OOM fix):
- C++: templateConstraints wired into worker node identity (SFINAE overload
disambiguation) + ADL / inline-namespace capture side-channel serialized
onto the ParsedFile.
- Kotlin: companion-scope side-channel serialized the same way (companion /
static dispatch).
Validation: tsc + build clean; full suite green (10,190 pass — the only
deterministic failures were the now-fixed C++/Kotlin worker-path gaps; the 2
remaining full-run failures are pre-existing load flakiness, green in
isolation); cpp-pipeline benchmark stays linear on a 1-worker pool.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(ingestion): wire C static-linkage side-channel + ADL O(1) collect + tri-review cleanups (#1983)
Follow-up to the worker-pool-only refactor, from a tri-review of the parse path.
- C static-linkage side-channel (P1): cProvider had no collect/applyCaptureSideChannel,
so on the now-sole worker path C `static` file-local marks were lost across the worker
boundary -> false cross-file CALLS edges + over-broad #include wildcard visibility on
every C analysis (the Linux kernel is C). Mirror the C++/Kotlin wiring: serialize
`staticNames` per file onto ParsedFile.captureSideChannel and restore it on the main
thread (no re-parse). + a worker-path regression test (the existing c-static-isolation
fixture passed vacuously — its collision resolves via #include before the global
free-call fallback ever consults static-linkage).
- captureSideChannel `kind` discriminant: add `kind:'cpp'`/`kind:'c'` tags + guards
(Kotlin already had one) now that C/C++/Kotlin share the single generic field.
- Perf: collectCppAdlSideChannel scanned the whole argInfoBySite/noAdlSites maps per file
(O(F^2) per sub-batch, ~100M parseSiteKey calls at kernel scale). Add per-filePath
lockstep indexes -> O(1) collect; serialized snapshot byte-identical.
- Cleanups: inline the one-line processParsingWithWorkers wrapper into processParsing;
drop the always-empty WorkerExtractedData.calls/assignments/constructorBindings fields;
remove the voided astCache param from processParsing; refresh stale "sequential
fallback" JSDoc.
Validation: tsc + build clean; cpp 297/297, c 8/8 (incl. the new worker-path
static-linkage guard), typescript + parsedfile-store green; cpp ADL benchmark stays linear.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(scope-resolution): index C/C++ #include resolution in finalize (O(n²)→O(n))
Kernel-scale C/C++ analysis ground in finalizeScopeModel because three
per-#include operations each did a full O(F) scan with no index — the
finalize O(n²) that surfaced once the #1983 parse-phase OOM was fixed:
- expand{C,Cpp}WildcardNames: parsedFiles.find() per wildcard edge → O(R·F)
- resolveImportTarget: new Set(allFilePaths) rebuilt per #include
- resolveCImportTarget: suffix-match scanned all workspace paths
Each is replaced with a WeakMap-per-pass index keyed on the stable
parsedFiles/allFilePaths references that scope-resolution run.ts passes
once per pass:
- Map<ScopeId,ParsedFile> for wildcard expansion (c/static-linkage.ts +
cpp/file-local-linkage.ts)
- memoized augmented header set (c/scope-resolver.ts + cpp/scope-resolver.ts)
- basename-bucketed suffix index in resolveCImportTarget (c/import-target.ts),
shared by C and C++ since resolveCppImportTarget delegates to it
Collapses the C/C++ finalize from O(R·F) to O(R+F). Pure-perf, byte-identical
edge output: 962 targeted tests green (490 C + 472 C/C++ scope-resolution);
the basename index preserves the exact endsWith('/'+target) match and the
fewest-path-components-then-lexicographic tie-break.
The kernel's ~25-30k .h headers are classified C++, so both providers must
be fixed. Proven on the Linux kernel: the C finalize completed
(sr-post-finalize lang=c → sr-end lang=c), which the pre-fix run never
reached in 16+ min of grinding.
Build-independent follow-ups (separate from this finalize fix), documented
for later: emitFreeCallFallback same-name buckets (emit phase),
buildGraphNodeLookup + precount global setup, the ParsedFile store-load,
the dart/go/ruby expand-wildcards .find siblings, and the ~26GB
scope-resolution memory floor (full kernel completion needs >~40GB RAM).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* test(bench): regenerate C scope-capture baseline for the #1983 c-static-linkage-worker fixture
bench/scope-capture/measure.mjs fingerprints emitCScopeCaptures over the
lang-resolution/c-* fixture corpus. The #1983 PR added the
c-static-linkage-worker fixture (caller.c/lib.c/lib.h/local.c — the
worker-path static-linkage side-channel test) but did not regenerate the C
baseline, so `--check` has been red on this branch (main, lacking the
fixture, still matches 0de009b).
Pure fixture-corpus drift — no c/captures.ts or query change branch-vs-main,
existing fixtures' captures byte-identical (c-captures.test.ts 45/45),
scaling stays linear (~0.97). Regenerated: 0de009b -> 39f3a83. Bench now
PASS (14 languages). Unrelated to the finalize O(n²) fix.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(scope-resolution): lower kernel-scale resident memory floor + setup cost
Reduce the scope-resolution resident-memory floor and setup throughput on
huge repos (Linux kernel), the wall that remains after #1983 (parse OOM) and
the finalize O(n^2) fix (b71c77b8). Five units; all preserve byte-identical
edge output (C fixture 177n/255e + c/cpp/cross-file/php/static-linkage suites
green, 619 tests).
U1 (src/cli/analyze.ts): RAM-aware auto heap-cap. Replace the hardcoded
16384MB cap with computeHeapCapMb = max(16384, floor(0.75*effectiveRAM)),
where effectiveRAM = min(os.totalmem(), process.constrainedMemory()) with the
unconstrained-sentinel guard. Add --max-semi-space-size=128 on the respawn.
A user-supplied NODE_OPTIONS heap still wins (no re-exec). Verified: 23973MB
on a 31964MB box, 16384 floor on small machines, cgroup-aware, sentinel safe.
U2 (src/storage/parsedfile-store.ts, .../pipeline/phase.ts): export forceGc()
and call it at the per-language eviction boundary, so a finished language's
ParsedFiles are reclaimed before the next language's store-load instead of
collected lazily under the next pass's allocation pressure (which at cap>=RAM
degrades into swap-thrash). Measured on a real drivers/net/ethernet run:
C 2113->894MB and C++ 1754->1057MB reclaimed at the boundary (no fragmentation
defeat). Answers the plan's Open Question 1.
U3 (src/storage/parsedfile-store.ts): intern def objects by nodeId in the load
reviver so a SymbolDefinition's three serialized copies (localDefs /
scope.ownedDefs / scope.bindings[].def) collapse to one shared object on load.
Per-shard def pool (a def's copies are shard-local). Measured ~42% off the
def-object retained heap (3->1; 1.8M->600k distinct objects on 600k defs).
U4 (.../passes/free-call-fallback.ts): memoize pickUniqueGlobalCallable's
post-filter candidate list per (name, callerFilePath), only when no per-caller
visibility filter applies (the list is then a pure function of name+file), so
repeated free calls of one name from a file reuse the same-name-bucket scan
instead of re-walking a potentially huge bucket per site. The cached array is
read-only-consumed by the .filter()-based arity/overload narrowers. Exported
pickUniqueGlobalCallable + buildGlobalCallableIndex and added an equivalence
test (memoized == un-memoized reference for every (name, file, arity),
including warm-cache repeats and cross-file file-local exclusion).
U5 (.../pipeline/phase.ts): replace the O(L*F) per-language precount + repeated
scannedFiles.filter() with a single O(F) partition-by-language pass; bracket
buildGraphNodeLookup with scope-setup-nodeLookup heap probes so the long setup
is no longer silent.
Plan: docs/plans/2026-06-06-001-perf-kernel-scope-resolution-memory-plan.md
(U6 out-of-core global index deferred). Note: the kernel's full C++ pass floor
(~20k headers + the 8.8GB graph) likely still exceeds 24GB by itself, which is
why U6 remains the only unit that clears the wall.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(test): match OOM-guidance e2e assertions to the U1 reworded hint
The analyze-heap-oom-e2e real-child-OOM test still asserted the pre-U1
wording ('...out of memory.' + a hardcoded 24576 cap). U1 reworded the hint
to mention the auto heap-cap and use a <MB> placeholder, so the three
toContain substrings no longer matched (the assertion at line 62 failed on
all platforms). Update them to the current message. The unit twin
(analyze-heap-respawn) was already updated in 85bfc216; this integration
test was missed by the targeted local run.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(lbug): U6a — deterministic id-sorted graph output behind GITNEXUS_SORT_GRAPH_OUTPUT
First increment of U6 (out-of-core scope-resolution). Adds an optional
deterministic ordering of node + relationship CSV rows by their unique graph
id, behind GITNEXUS_SORT_GRAPH_OUTPUT (default OFF = today's graph-insertion
order, byte-identical — the iterator is returned untouched). With the flag ON
the CSV becomes a pure function of the node/edge SET rather than of emit order.
This is the structural enabler for the windowed/out-of-core resolve (U6b-U6d):
csv-generator.ts:518 currently iterates graph.iterRelationships() in insertion
order with NO terminal sort, so any deviation from parsedFiles-order emit would
change bytes. With U6a on, a windowed emit need only reproduce the same edge
SET, not the global insertion order — removing the single largest byte-identical
hazard from every later windowing step.
Verified: default off keeps the existing csv-pipeline suite byte-identical; on,
node rows are id-sorted and output is independent of graph insertion order
(set-build) with the same node/edge set.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(storage): U6d foundation — disk-backed scope store + lazy ScopeTree
Adds scope-index-store.ts: persistScopeShards (per-file scope shards via the
proven mapReplacer + def-interning reviver) + DiskBackedScopeTree, a lazy
ScopeTree that serves getScope from a bounded LRU of decoded shards plus a small
resident skeleton (scopeId -> {shard, childIds, parent}). Exports
makeInterningReviver from parsedfile-store for reuse.
This is the contained, highest-risk mechanism of U6d (out-of-core scope
resolution): the emit passes reach the heavy per-Scope binding payload
(~17-20GB on the kernel) ONLY through scopeTree.getScope (a point lookup) and
getChildren — they never read parsed.scopes directly — so moving that payload to
disk behind getScope is transparent. Every consumer reads a Scope BY VALUE, so a
value-faithful disk round-trip is byte-identical to resolution.
Proven in isolation: DiskBackedScopeTree is value-identical to buildScopeTree
for getScope/getChildren/getParent/getAncestors/has/size across multiple files
and after LRU eviction, and preserves the def-identity collapse (ownedDefs[i]
=== binding.def). Nothing wires it yet (the resolution-pipeline integration is
the next increment) — zero production impact; default off.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(scope-resolution): U6d integration — seal scopeTree to disk before emit (GITNEXUS_DISK_SCOPE_INDEX)
Wires the U6d out-of-core scope index into the live pipeline behind
GITNEXUS_DISK_SCOPE_INDEX (default OFF = byte-identical). When on:
- finalize-orchestrator builds a TransitionalScopeTree (validated, fully
resident) instead of buildScopeTree, so finalize/propagate/resolve are
unchanged.
- After resolve, before emit, run.ts seals it: persists the scopes to a
file-sharded scope-index-store, swaps the model's scopeTree to disk-backed
serving from the inside (the frozen bundle can't be reassigned, but the
wrapper nulls its own resident backing), and drops the heavy Scope.bindings
payload from all THREE holders — the model's tree (seal), the caller's
preExtractedParsedFiles, and run.ts's own parsedFiles (scope-stripped copies
for emit). Emit reads scopes only via scopeTree.getScope (a point lookup,
now disk-backed + LRU) — verified it never reads parsed.scopes.
Purpose: lower the per-language resident PEAK (kernel C pass ~20→~12 GB by
moving the ~8-9 GB scope payload to disk) so the analysis fits on smaller-RAM
machines. At >=24 GB the full kernel already fits with U1-U5 (U2's 8.7 GB
inter-language forceGc reclaim keeps each pass under cap) — empirically
confirmed — so this is the sub-24 GB lever, not needed at 24 GB.
Byte-identical evidence: DiskBackedScopeTree/TransitionalScopeTree return
value-identical scopes vs buildScopeTree (getScope/getChildren/getParent/
getAncestors, across files + after LRU eviction + post-seal); emit reads only
getScope + referenceSites; flag-off (394 tests) and flag-on-resident (91 tests)
resolver suites stay green; an end-to-end A/B on a 212-file C+cpp+rust subset
produced identical 17,444 nodes / 31,343 edges with the seal firing per language
(c: 410→141 MB reclaimed). Kernel-scale peak-drop measurement pending the
in-flight verdict run freeing memory.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(scope-resolution): U6d — id-back workspaceIndex so the disk seal can reclaim scopes
The kernel run revealed the contained scopeTree seal didn't lower the heap:
WorkspaceResolutionIndex held Scope OBJECTS (classScopeByDefId / moduleScopeByFile),
built from every ParsedFile and live through emit, so the ~28k module + class
scopes stayed pinned past the seal (sr-seal-pre 17,583 -> sr-seal-post 17,771 MB,
no drop). It was the sole residual Scope-object holder (SemanticModel holds none).
Fix: classScopeByDefId / moduleScopeByFile become id-backed ScopeByKeyView
instances — a ReadonlyMap<K, Scope> facade over a K->ScopeId map + the scopeTree,
whose .get fetches via scopeTree.getScope(id). The index now pins only ids, so
once the tree seals to disk the scopes become collectible. Byte-identical: the
view returns the same Scope the resident tree holds (or a value-identical revived
one in disk mode), and iteration keeps the old insertion order. buildWorkspace
ResolutionIndex takes an optional scopeTree (live pipeline passes it); without it
(unit tests) the legacy direct Scope-object maps are returned unchanged.
Verified byte-identical: 733 tests across workspace-index / imported-return-types
/ c / cpp / cross-file / go / java. Kernel peak-drop re-measurement to follow.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* perf(scope-resolution): U6d — precompute exportedCallableByName (fix disk-getScope thrash)
The workspaceIndex id-backing freed the kernel scopes but exposed a throughput
collapse: findExportedDefByName's workspace fallback (walkers.ts:1019) scanned
EVERY module scope's bindings per unresolved free call, and under the U6d
disk-backed scopeTree each module-scope access faulted a shard in from disk —
lib ON went ~1min -> ~7.5min.
Fix: precompute the fallback result once into
WorkspaceResolutionIndex.exportedCallableByName (simpleName -> first module-local
callable def, first-file-wins — the exact semantics the scan returned), built
from the resident module-scope bindings at index-build time. findExportedDefByName
now does an O(1) lookup with zero disk reads.
Result: lib ON ~7.5min -> 21s (cache-warm), byte-identical 17,444/31,343; 758
tests green across workspace-index + c/cpp/cross-file/go/python.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: rename cryptic U-unit codes to descriptive names in comments
The plan-unit shorthand (U3/U4/U6a/U6d/...) was meaningless in the code.
Renamed in comments + test descriptions (no behavior change, byte-identical):
out-of-core scope index (was U6)
deterministic output (was U6a)
disk-backed scope seal (was U6d)
def-object interning (was U3)
free-call candidate cache (was U4)
Also renamed throughout the PR title/summary. Pushed commit messages keep
their original U-codes as historical record.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(ingestion): durable ParsedFile shards for warm-cache coverage (#2038)
On a warm re-analyze where every chunk is a parse-cache HIT, no parse worker
runs, the run-scoped ParsedFile store is cleared at parse start, and the cached
ParseWorkerResult carries no ParsedFiles (the worker writes them to the store
and empties them from the message). Scope-resolution then found an empty store
and fell back to main-thread extractParsedFile — re-opening the #1983
tree-sitter native-leak OOM the disk store closes (abhigyanpatwari review on
parse-cache.ts).
Fix: workers ALSO write their ParsedFiles to a durable, content-addressed store
(parsedfile-cache/) keyed by chunk hash, mirroring the parse cache's lifecycle
(version-gated by PARSE_CACHE_VERSION, pruned in lockstep to the surviving
keys). On a warm hit the chunk's durable shards are byte-COPIED into the
run-scoped store (no re-parse, no re-serialize -> byte-identical), so
scope-resolution streams them exactly as on a cold run. A coherence gate
re-dispatches the worker whenever a cached chunk's durable shards are missing
(migration / pruned / version-stale) -- never the main-thread extract.
- worker-pool/parse-worker: thread chunkHash through dispatch->job->flush
(incl. split/requeue) so the worker tags its durable shard by content
- parsedfile-store: durable persist / restore / index / prune API (sibling
dir, never cleared per run); content-addressing makes stale reuse impossible
- parse-impl: load durable index, gate the cache hit on durable coverage,
restore on hit, dispatch chunkHash on miss
- run-analyze: prune+save the durable store to the parse cache's surviving keys
- saveParseCache returns its written keys (the durable keepKeys)
Verified on linux/lib: warm preExtractedHits = full coverage (520/207/1, zero
main-thread re-parse), byte-identical cold==warm (17,456n/31,353e), warm 8.5x
faster. New two-run + mixed-mode + coherence-gate regression test.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(ingestion): clear stale scope-index-store shards on each seal (#2038)
The disk-backed scope index writes sequential s<n>.json shards into a shared
<storagePath>/scope-index-store/ dir, with the index resetting per
persistScopeShards call. A seal that writes fewer shards than a previous one
(a later language with fewer files, or a re-run of a shrunken repo) left stale
tail shards on disk indefinitely -- never read by the disk-backed tree, but
multi-GB on kernel-scale repos.
Add clearScopeIndexStore() and clear at the start of persistScopeShards: the
previously sealed language has finished emit and been released before the next
seal runs, so its DiskBackedScopeTree never reads those shards again. Unit
tests: a stale prior-run shard is removed, a fewer-files re-seal leaves no tail
shards, and the helper is idempotent.
Addresses abhigyanpatwari review on run.ts (disk hygiene for the
GITNEXUS_DISK_SCOPE_INDEX path).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1780 lines
73 KiB
TypeScript
1780 lines
73 KiB
TypeScript
/**
|
|
* Ruby: require_relative imports, include heritage (mixins), attr_* properties,
|
|
* calls, member calls, ambiguous disambiguation, local shadow,
|
|
* constructor-inferred type resolution
|
|
*/
|
|
import { describe, it, expect, beforeAll } from 'vitest';
|
|
import path from 'path';
|
|
import {
|
|
FIXTURES,
|
|
CROSS_FILE_FIXTURES,
|
|
getRelationships,
|
|
getNodesByLabel,
|
|
getNodesByLabelFull,
|
|
findDanglingEdges,
|
|
edgeSet,
|
|
runPipelineFromRepo,
|
|
type PipelineResult,
|
|
} from './helpers.js';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Heritage: require_relative imports + include heritage + attr_* properties + calls
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby require_relative, heritage & property resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-app'), () => {});
|
|
}, 60000);
|
|
|
|
// --- Node detection ---
|
|
|
|
it('detects 3 classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'User', 'UserService']);
|
|
});
|
|
|
|
it('detects 3 modules (labeled as Trait for class-like registry lookup)', () => {
|
|
// Ruby `module` declarations are relabeled to `Trait` during ingestion so
|
|
// they participate in `lookupClassByName` and scope-resolution's heritage
|
|
// resolution. This is the single source of truth for Ruby module detection
|
|
// in the graph.
|
|
expect(getNodesByLabel(result, 'Trait')).toEqual(['Cacheable', 'Loggable', 'Serializable']);
|
|
expect(getNodesByLabel(result, 'Module')).toEqual([]);
|
|
});
|
|
|
|
it('detects methods on classes and modules', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('persist');
|
|
expect(methods).toContain('run_validations');
|
|
expect(methods).toContain('greet_user');
|
|
expect(methods).toContain('serialize_data');
|
|
expect(methods).toContain('create_user');
|
|
});
|
|
|
|
it('detects singleton method (def self.factory) as Method', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('factory');
|
|
});
|
|
|
|
it('emits CALLS from singleton method: factory → run_validations', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'factory' && e.target === 'run_validations',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
expect(calls[0].sourceLabel).toBe('Method');
|
|
});
|
|
|
|
// --- Import resolution via require_relative ---
|
|
|
|
it('resolves 5 require_relative imports to IMPORTS edges', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
const importEdges = edgeSet(imports);
|
|
expect(importEdges).toContain('user.rb → base_model.rb');
|
|
expect(importEdges).toContain('user.rb → serializable.rb');
|
|
expect(importEdges).toContain('user.rb → loggable.rb');
|
|
expect(importEdges).toContain('user.rb → cacheable.rb');
|
|
expect(importEdges).toContain('service.rb → user.rb');
|
|
});
|
|
|
|
it('resolves bare require to IMPORTS edge', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
const bareRequire = imports.find(
|
|
(e) =>
|
|
e.sourceFilePath.includes('base_model.rb') && e.targetFilePath.includes('serializable.rb'),
|
|
);
|
|
expect(bareRequire).toBeDefined();
|
|
});
|
|
|
|
// --- Heritage: include → IMPLEMENTS ---
|
|
|
|
it('emits IMPLEMENTS edge for include Serializable with reason "include"', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const edge = implements_.find((e) => e.source === 'User' && e.target === 'Serializable');
|
|
expect(edge).toBeDefined();
|
|
expect(edge!.rel.reason).toBe('include');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge for extend Loggable with reason "extend"', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const edge = implements_.find((e) => e.source === 'User' && e.target === 'Loggable');
|
|
expect(edge).toBeDefined();
|
|
expect(edge!.rel.reason).toBe('extend');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge for prepend Cacheable with reason "prepend"', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const edge = implements_.find((e) => e.source === 'User' && e.target === 'Cacheable');
|
|
expect(edge).toBeDefined();
|
|
expect(edge!.rel.reason).toBe('prepend');
|
|
});
|
|
|
|
// --- Extends: class inheritance ---
|
|
|
|
it('emits EXTENDS edge: User → BaseModel', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(1);
|
|
const edges = edgeSet(extends_);
|
|
expect(edges).toContain('User → BaseModel');
|
|
});
|
|
|
|
// --- Property nodes: attr_accessor, attr_reader, attr_writer ---
|
|
|
|
it('creates Property nodes for attr_accessor :id and :created_at', () => {
|
|
const props = getNodesByLabel(result, 'Property');
|
|
expect(props).toContain('id');
|
|
expect(props).toContain('created_at');
|
|
});
|
|
|
|
it('creates Property nodes for attr_reader :name and attr_writer :email', () => {
|
|
const props = getNodesByLabel(result, 'Property');
|
|
expect(props).toContain('name');
|
|
expect(props).toContain('email');
|
|
});
|
|
|
|
it('emits HAS_PROPERTY from User to attr_reader :name', () => {
|
|
const hasProperty = getRelationships(result, 'HAS_PROPERTY');
|
|
const edge = hasProperty.find((e) => e.source === 'User' && e.target === 'name');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
it('emits HAS_PROPERTY from BaseModel to attr_accessor :id', () => {
|
|
const hasProperty = getRelationships(result, 'HAS_PROPERTY');
|
|
const edge = hasProperty.find((e) => e.source === 'BaseModel' && e.target === 'id');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
// --- Call resolution: method-level attribution ---
|
|
|
|
it('emits method-level CALLS: create_user → persist (member call)', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'create_user' && e.target === 'persist',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
expect(calls[0].sourceLabel).toBe('Method');
|
|
expect(calls[0].targetLabel).toBe('Method');
|
|
});
|
|
|
|
it('emits method-level CALLS: create_user → greet_user (member call)', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'create_user' && e.target === 'greet_user',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
expect(calls[0].sourceLabel).toBe('Method');
|
|
expect(calls[0].targetLabel).toBe('Method');
|
|
});
|
|
|
|
it('emits method-level CALLS: greet_user → persist (bare call)', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'greet_user' && e.target === 'persist',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
});
|
|
|
|
it('emits method-level CALLS: greet_user → serialize_data (bare call)', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'greet_user' && e.target === 'serialize_data',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
});
|
|
|
|
it('emits method-level CALLS: persist → run_validations (bare call)', () => {
|
|
const calls = getRelationships(result, 'CALLS').filter(
|
|
(e) => e.source === 'persist' && e.target === 'run_validations',
|
|
);
|
|
expect(calls.length).toBe(1);
|
|
});
|
|
|
|
// --- Heritage edges point to real graph nodes ---
|
|
|
|
it('all heritage edges point to real graph nodes', () => {
|
|
for (const edge of [
|
|
...getRelationships(result, 'EXTENDS'),
|
|
...getRelationships(result, 'IMPLEMENTS'),
|
|
]) {
|
|
const target = result.graph.getNode(edge.rel.targetId);
|
|
expect(target).toBeDefined();
|
|
}
|
|
});
|
|
|
|
// --- No OVERRIDES edges target Property nodes ---
|
|
|
|
it('no OVERRIDES edges target Property nodes', () => {
|
|
const overrides = getRelationships(result, 'METHOD_OVERRIDES');
|
|
for (const edge of overrides) {
|
|
const target = result.graph.getNode(edge.rel.targetId);
|
|
expect(target).toBeDefined();
|
|
expect(target!.label).not.toBe('Property');
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Calls: arity-based disambiguation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby call resolution with arity filtering', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-calls'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves run_task → write_audit to one_arg.rb via arity narrowing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const auditCall = calls.find((c) => c.target === 'write_audit');
|
|
expect(auditCall).toBeDefined();
|
|
expect(auditCall!.source).toBe('run_task');
|
|
expect(auditCall!.targetFilePath).toContain('one_arg.rb');
|
|
expect(auditCall!.rel.reason).toBe('import-resolved');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Member-call resolution: obj.method() resolves through pipeline
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby member-call resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-member-calls'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves process_user → persist_record as a member call on User', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'persist_record');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.source).toBe('process_user');
|
|
expect(saveCall!.targetFilePath).toContain('user.rb');
|
|
});
|
|
|
|
it('detects User class and persist_record method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('persist_record');
|
|
});
|
|
|
|
it('emits HAS_METHOD edge from User to persist_record', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const edge = hasMethod.find((e) => e.source === 'User' && e.target === 'persist_record');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
describe('Ruby qualified class names', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-qualified-types'), () => {});
|
|
}, 60000);
|
|
|
|
it('stores distinct qualified names for same-named classes across modules', () => {
|
|
const users = getNodesByLabelFull(result, 'Class').filter((node) => node.name === 'User');
|
|
expect(users).toHaveLength(2);
|
|
expect(users.map((node) => node.properties.qualifiedName).sort()).toEqual([
|
|
'Admin.User',
|
|
'Services.Auth.User',
|
|
]);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Qualified-base heritage: `class C < Outer::Super` (scope_resolution super-
|
|
// class) must emit EXTENDS (#1951). The bare control `class D < Base` keeps the
|
|
// original path unchanged, and `include Mixin` flows through the unchanged
|
|
// mixin → IMPLEMENTS lane. Scope-resolution owns these edges since #942.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby qualified-base heritage resolution (#1951)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-qualified-base'), () => {});
|
|
}, 60000);
|
|
|
|
it('emits EXTENDS for scoped (C < Outer::Super) and bare (D < Base) bases', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
const edges = edgeSet(extends_);
|
|
// Scoped superclass resolves by its trailing bare name (Outer::Super → Super).
|
|
expect(edges).toContain('C → Super');
|
|
// Bare control resolves unchanged.
|
|
expect(edges).toContain('D → Base');
|
|
});
|
|
|
|
it('emits IMPLEMENTS for the include Mixin (unchanged mixin lane): C → Mixin', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const edge = implements_.find((e) => e.source === 'C' && e.target === 'Mixin');
|
|
expect(edge).toBeDefined();
|
|
expect(edge!.rel.reason).toBe('include');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ambiguous: Handler in two dirs, require_relative disambiguates
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby ambiguous symbol resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-ambiguous'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects 2 Handler classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes.filter((n) => n === 'Handler').length).toBe(2);
|
|
expect(classes).toContain('UserHandler');
|
|
});
|
|
|
|
it('resolves EXTENDS to models/handler.rb (not other/handler.rb)', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(1);
|
|
expect(extends_[0].source).toBe('UserHandler');
|
|
expect(extends_[0].target).toBe('Handler');
|
|
expect(extends_[0].targetFilePath).toBe('models/handler.rb');
|
|
});
|
|
|
|
it('import edge points to models/ not other/', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
expect(imports.length).toBe(1);
|
|
expect(imports[0].targetFilePath).toBe('models/handler.rb');
|
|
});
|
|
|
|
it('all heritage edges point to real graph nodes', () => {
|
|
for (const edge of getRelationships(result, 'EXTENDS')) {
|
|
const target = result.graph.getNode(edge.rel.targetId);
|
|
expect(target).toBeDefined();
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Local shadow: same-file definition takes priority over imported name
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby local definition shadows import', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-local-shadow'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves run_app → do_work to same-file definition, not the imported one', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const doWorkCall = calls.find((c) => c.target === 'do_work' && c.source === 'run_app');
|
|
expect(doWorkCall).toBeDefined();
|
|
expect(doWorkCall!.targetFilePath).toContain('app.rb');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Constructor-inferred type resolution: user = User.new; user.save → User.save
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby constructor-inferred type resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-constructor-type-inference'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects User, Repo, and AppService classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('AppService');
|
|
});
|
|
|
|
it('detects save on User and Repo, cleanup on all three', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods.filter((m) => m === 'save').length).toBe(2);
|
|
expect(methods.filter((m) => m === 'cleanup').length).toBe(3);
|
|
});
|
|
|
|
it('resolves user.save to models/user.rb via constructor-inferred type', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'save' && c.targetFilePath === 'models/user.rb',
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
expect(userSave!.source).toBe('process_entities');
|
|
});
|
|
|
|
it('resolves repo.save to models/repo.rb via constructor-inferred type', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'save' && c.targetFilePath === 'models/repo.rb',
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
expect(repoSave!.source).toBe('process_entities');
|
|
});
|
|
|
|
it('emits exactly 2 save CALLS edges (one per receiver type)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((c) => c.target === 'save');
|
|
expect(saveCalls.length).toBe(2);
|
|
});
|
|
|
|
it('resolves self.process_entities to services/app.rb (unique method)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const selfCall = calls.find((c) => c.source === 'greet' && c.target === 'process_entities');
|
|
expect(selfCall).toBeDefined();
|
|
expect(selfCall!.targetFilePath).toContain('app.rb');
|
|
});
|
|
|
|
it('resolves self.cleanup to services/app.rb, not models/user.rb or models/repo.rb', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const selfCleanup = calls.find((c) => c.source === 'greet' && c.target === 'cleanup');
|
|
expect(selfCleanup).toBeDefined();
|
|
expect(selfCleanup!.targetFilePath).toContain('app.rb');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// self.save resolves to enclosing class's own save method
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby self resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-self-this-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes, each with a save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Repo', 'User']);
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves self.save inside User#process to User#save, not Repo#save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'process');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.targetFilePath).toBe('lib/models/user.rb');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Parent class resolution: < BaseModel + include Module
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby parent resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-parent-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects BaseModel and User classes plus Serializable module (Trait)', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'User']);
|
|
// Ruby modules are labeled Trait — see the "detects 3 modules" test above.
|
|
expect(getNodesByLabel(result, 'Trait')).toEqual(['Serializable']);
|
|
});
|
|
|
|
it('emits EXTENDS edge: User < BaseModel', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(1);
|
|
expect(extends_[0].source).toBe('User');
|
|
expect(extends_[0].target).toBe('BaseModel');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge: User includes Serializable', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const includeEdge = implements_.find((e) => e.source === 'User' && e.target === 'Serializable');
|
|
expect(includeEdge).toBeDefined();
|
|
expect(includeEdge!.rel.reason).toBe('include');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ruby super: standalone keyword calls same-named method on parent
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby super resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-super-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects BaseModel, User, and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'Repo', 'User']);
|
|
});
|
|
|
|
it('emits EXTENDS edge: User < BaseModel', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(1);
|
|
expect(extends_[0].source).toBe('User');
|
|
expect(extends_[0].target).toBe('BaseModel');
|
|
});
|
|
|
|
it('detects save methods on all three classes', () => {
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'save');
|
|
expect(saveMethods.length).toBe(3);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ruby constant constructor: SERVICE = UserService.new; SERVICE.process
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby constant constructor binding resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-constant-constructor'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects UserService class with process and validate methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('process');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('validate');
|
|
});
|
|
|
|
it('resolves SERVICE.process() via constant constructor binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const processCall = calls.find(
|
|
(c) => c.target === 'process' && c.targetFilePath === 'models.rb',
|
|
);
|
|
expect(processCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves SERVICE.validate() via constant constructor binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const validateCall = calls.find(
|
|
(c) => c.target === 'validate' && c.targetFilePath === 'models.rb',
|
|
);
|
|
expect(validateCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// YARD annotation type resolution: @param repo [UserRepo] → repo.save resolves
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby YARD annotation type resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-yard-annotations'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects UserRepo, User, and UserService classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserRepo');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
});
|
|
|
|
it('detects save, find_by_name, greet, and create methods', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('save');
|
|
expect(methods).toContain('find_by_name');
|
|
expect(methods).toContain('greet');
|
|
expect(methods).toContain('create');
|
|
});
|
|
|
|
it('resolves repo.save to UserRepo#save via YARD @param annotation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'create');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.targetFilePath).toContain('models.rb');
|
|
});
|
|
|
|
it('resolves user.greet to User#greet via YARD @param annotation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCall = calls.find((c) => c.target === 'greet' && c.source === 'create');
|
|
expect(greetCall).toBeDefined();
|
|
expect(greetCall!.targetFilePath).toContain('models.rb');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Namespaced constructor: svc = Models::UserService.new; svc.process()
|
|
// Tests scope_resolution receiver handling for Ruby namespaced classes.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby namespaced constructor resolution (Models::UserService.new)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-namespaced-constructor'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects UserService class with process and validate methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('process');
|
|
expect(methods).toContain('validate');
|
|
});
|
|
|
|
it('resolves svc.process() via namespaced constructor Models::UserService.new', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const processCall = calls.find(
|
|
(c) => c.target === 'process' && c.targetFilePath.includes('user_service.rb'),
|
|
);
|
|
expect(processCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves svc.validate() via namespaced constructor Models::UserService.new', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const validateCall = calls.find(
|
|
(c) => c.target === 'validate' && c.targetFilePath.includes('user_service.rb'),
|
|
);
|
|
expect(validateCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Return type inference: user = get_user('alice'); user.save
|
|
// Ruby's scanConstructorBinding captures assignment nodes with call RHS.
|
|
// Combined with YARD @return annotation parsing, the pipeline resolves
|
|
// `user.save` to User#save (not Repo#save) via return type disambiguation.
|
|
// The fixture has BOTH User#save and Repo#save — fuzzy matching alone
|
|
// cannot disambiguate, so return type inference must be working.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby return type inference via function call', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-return-type'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('detects get_user and get_repo methods', () => {
|
|
expect(getNodesByLabel(result, 'Method')).toContain('get_user');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('get_repo');
|
|
});
|
|
|
|
it('detects save method on both User and Repo (disambiguation required)', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
// Both classes have save — fuzzy match alone cannot resolve this
|
|
expect(methods.filter((m) => m === 'save').length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.save to User#save via YARD @return [User] on get_user()', () => {
|
|
// With both User#save and Repo#save in scope, resolving user.save
|
|
// requires return type inference: get_user() → @return [User] → user is User
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'save' &&
|
|
c.source === 'process_user' &&
|
|
c.targetFilePath.includes('models.rb'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves repo.save to Repo#save via YARD @return [Repo] on get_repo()', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'save' && c.source === 'process_repo' && c.targetFilePath.includes('repo.rb'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ruby constant LHS factory call: SERVICE = build_service() with YARD @return
|
|
// Verifies that constant assignments (uppercase LHS) from plain function calls
|
|
// are captured by scanConstructorBinding, not just identifier assignments.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby constant factory call resolution (SERVICE = build_service())', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-constant-factory-call'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects UserService and AdminService classes with process and validate methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('AdminService');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('process');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('validate');
|
|
});
|
|
|
|
it('resolves SERVICE.process() to UserService#process via constant factory call', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const processCall = calls.find(
|
|
(c) => c.target === 'process' && c.targetFilePath.includes('user_service.rb'),
|
|
);
|
|
expect(processCall).toBeDefined();
|
|
const wrongCall = calls.find(
|
|
(c) =>
|
|
c.target === 'process' &&
|
|
c.sourceFilePath?.includes('app.rb') &&
|
|
c.targetFilePath.includes('admin_service.rb'),
|
|
);
|
|
expect(wrongCall).toBeUndefined();
|
|
});
|
|
|
|
it('resolves SERVICE.validate() to UserService#validate via constant factory call', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const validateCall = calls.find(
|
|
(c) => c.target === 'validate' && c.targetFilePath.includes('user_service.rb'),
|
|
);
|
|
expect(validateCall).toBeDefined();
|
|
const wrongCall = calls.find(
|
|
(c) =>
|
|
c.target === 'validate' &&
|
|
c.sourceFilePath?.includes('app.rb') &&
|
|
c.targetFilePath.includes('admin_service.rb'),
|
|
);
|
|
expect(wrongCall).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('Ruby YARD generic type annotations (Hash<Symbol, User>)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-yard-generics'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects UserRepo, AdminRepo, and DataService classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserRepo');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('AdminRepo');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('DataService');
|
|
});
|
|
|
|
it('detects save and find_all on both repos, plus sync and audit methods', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('save');
|
|
expect(methods).toContain('find_all');
|
|
expect(methods).toContain('sync');
|
|
expect(methods).toContain('audit');
|
|
});
|
|
|
|
it('resolves repo.save in sync() to UserRepo#save via @param repo [UserRepo]', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'save' && c.source === 'sync' && c.targetFilePath.includes('models.rb'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('does NOT resolve cache param to a class (Hash<Symbol, UserRepo> is a generic container)', () => {
|
|
// The @param cache [Hash<Symbol, UserRepo>] should extract type "Hash" — not "UserRepo".
|
|
// Since Hash is not a class in the fixture, no type binding is created for cache.
|
|
// This verifies the bracket-balanced split doesn't break on the inner comma.
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// No calls should originate from cache.* since cache has no resolved type
|
|
const cacheCall = calls.find(
|
|
(c) => c.source === 'sync' && c.target === 'save' && c.targetFilePath.includes('admin'),
|
|
);
|
|
expect(cacheCall).toBeUndefined();
|
|
});
|
|
|
|
it('resolves admin_repo.save in audit() to AdminRepo#save via alternate @param [AdminRepo] order', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// audit() calls admin_repo.save — should resolve via the alternate YARD format
|
|
const saveCall = calls.find((c) => c.target === 'save' && c.source === 'audit');
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves admin_repo.find_all in audit() to AdminRepo#find_all', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const findCall = calls.find((c) => c.target === 'find_all' && c.source === 'audit');
|
|
expect(findCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Chained method calls: svc.get_user.save
|
|
// Tests that Ruby's `call` node uses `method` and `receiver` fields correctly
|
|
// for chain extraction — the tree-sitter-ruby grammar differs from other languages.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby chained method call resolution (Phase 5 review fix)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-chain-call'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User, Repo, UserService and App classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('User');
|
|
expect(classes).toContain('Repo');
|
|
expect(classes).toContain('UserService');
|
|
expect(classes).toContain('App');
|
|
});
|
|
|
|
it('detects save methods on both User and Repo', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
const saveMethods = methods.filter((m) => m === 'save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('detects get_user method on UserService', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('get_user');
|
|
});
|
|
|
|
it('resolves svc.get_user.save to User#save via chain resolution', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath?.includes('user.rb'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT resolve svc.get_user.save to Repo#save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath?.includes('repo.rb'),
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ruby for-in loop: for user in users — YARD @param resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby for-in loop resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-for-in-loop'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User class with save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
});
|
|
|
|
it('resolves user.save in for-in to User#save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'save' && c.source === 'process_users' && c.targetFilePath?.includes('user'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT resolve user.save to Repo#save (negative)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongSave = calls.find(
|
|
(c) =>
|
|
c.target === 'save' && c.source === 'process_users' && c.targetFilePath?.includes('repo'),
|
|
);
|
|
expect(wrongSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 8: Field/property type resolution via YARD @return annotations
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Field type resolution (Ruby)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-field-types'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects classes: Address, User', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Address', 'User']);
|
|
});
|
|
|
|
it('detects Property nodes for attr_accessor fields', () => {
|
|
const properties = getNodesByLabel(result, 'Property');
|
|
expect(properties).toContain('address');
|
|
expect(properties).toContain('name');
|
|
expect(properties).toContain('city');
|
|
});
|
|
|
|
it('emits HAS_PROPERTY edges linking properties to classes', () => {
|
|
const propEdges = getRelationships(result, 'HAS_PROPERTY');
|
|
expect(propEdges.length).toBe(3);
|
|
expect(edgeSet(propEdges)).toContain('User → address');
|
|
expect(edgeSet(propEdges)).toContain('User → name');
|
|
expect(edgeSet(propEdges)).toContain('Address → city');
|
|
});
|
|
|
|
it('resolves user.address.save → Address#save via YARD @return [Address]', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((e) => e.target === 'save');
|
|
const addressSave = saveCalls.find(
|
|
(e) => e.source === 'process_user' && e.targetFilePath.includes('models'),
|
|
);
|
|
expect(addressSave).toBeDefined();
|
|
});
|
|
|
|
it('Property nodes contain expected field names', () => {
|
|
const properties = getNodesByLabelFull(result, 'Property');
|
|
|
|
const city = properties.find((p) => p.name === 'city');
|
|
expect(city).toBeDefined();
|
|
|
|
const name = properties.find((p) => p.name === 'name');
|
|
expect(name).toBeDefined();
|
|
|
|
const addr = properties.find((p) => p.name === 'address');
|
|
expect(addr).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 8: Field type disambiguation — both User and Address have save()
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Field type disambiguation (Ruby)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-field-type-disambig'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects both User#save and Address#save', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
const saveMethods = methods.filter((m) => m === 'save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.address.save → Address#save (not User#save)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((e) => e.target === 'save' && e.source === 'process_user');
|
|
expect(saveCalls.length).toBe(1);
|
|
expect(saveCalls[0].targetFilePath).toContain('address');
|
|
expect(saveCalls[0].targetFilePath).not.toContain('user');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// ACCESSES write edges from assignment expressions
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Write access tracking (Ruby)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-write-access'), () => {});
|
|
}, 60000);
|
|
|
|
it('emits ACCESSES write edges for setter assignments', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writes = accesses.filter((e) => e.rel.reason === 'write');
|
|
expect(writes.length).toBe(3);
|
|
const nameWrite = writes.find((e) => e.target === 'name');
|
|
const addressWrite = writes.find((e) => e.target === 'address');
|
|
const scoreWrite = writes.find((e) => e.target === 'score');
|
|
expect(nameWrite).toBeDefined();
|
|
expect(nameWrite!.source).toBe('update_user');
|
|
expect(addressWrite).toBeDefined();
|
|
expect(addressWrite!.source).toBe('update_user');
|
|
expect(scoreWrite).toBeDefined();
|
|
expect(scoreWrite!.source).toBe('update_user');
|
|
});
|
|
|
|
it('emits ACCESSES write edge for compound assignment (operator_assignment)', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writes = accesses.filter((e) => e.rel.reason === 'write');
|
|
const scoreWrite = writes.find((e) => e.target === 'score');
|
|
expect(scoreWrite).toBeDefined();
|
|
expect(scoreWrite!.source).toBe('update_user');
|
|
});
|
|
|
|
it('write ACCESSES edges have confidence 1.0', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writes = accesses.filter((e) => e.rel.reason === 'write');
|
|
for (const edge of writes) {
|
|
expect(edge.rel.confidence).toBe(1.0);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Call-result variable binding (Phase 9): user = get_user(); user.save
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby call-result variable binding (Tier 2b)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-call-result-binding'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves user.save to User#save via call-result binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'save' && c.source === 'process_user' && c.targetFilePath.includes('app'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Method chain binding (Phase 9C): get_user() → .get_address() → .get_city() → .save
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby method chain binding via unified fixpoint (Phase 9C)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-method-chain-binding'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves city.save to City#save via method chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'save' && c.source === 'process_chain' && c.targetFilePath.includes('app'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase B: Deep MRO — walkParentChain() at depth 2 (C→B→A)
|
|
// greet is defined on A, accessed via C. Tests BFS depth-2 parent traversal.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby grandparent method resolution via MRO (Phase B)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-grandparent-resolution'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects A, B, C, Greeting classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('A');
|
|
expect(classes).toContain('B');
|
|
expect(classes).toContain('C');
|
|
expect(classes).toContain('Greeting');
|
|
});
|
|
|
|
it('emits EXTENDS edges: B→A, C→B', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(edgeSet(extends_)).toContain('B → A');
|
|
expect(edgeSet(extends_)).toContain('C → B');
|
|
});
|
|
|
|
it('resolves c.greet.save to Greeting#save via depth-2 MRO lookup', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'save' && c.targetFilePath.includes('greeting'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves c.greet to A#greet (method found via MRO walk)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCall = calls.find((c) => c.target === 'greet' && c.targetFilePath.includes('a.rb'));
|
|
expect(greetCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ruby default parameter arity resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby default parameter arity resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-default-params'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves greet("Alice") with 1 arg to greet with 2 params (1 default)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCalls = calls.filter((c) => c.source === 'process' && c.target === 'greet');
|
|
expect(greetCalls.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 14: Cross-file binding propagation (via synthesized wildcard imports)
|
|
// models/user.rb exports User class with save and get_name methods
|
|
// models/user_factory.rb exports UserFactory with self.get_user -> User.new
|
|
// app.rb requires both, calls UserFactory.get_user then .save / .get_name
|
|
// → user is typed User via cross-file return type propagation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby cross-file binding propagation', () => {
|
|
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 UserFactory class and get_user method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserFactory');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('get_user');
|
|
});
|
|
|
|
it('emits IMPORTS edge from app.rb to models', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
const edge = imports.find(
|
|
(e) => e.sourceFilePath.includes('app') && e.targetFilePath.includes('models'),
|
|
);
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
it('resolves user.save in process to User#save via cross-file propagation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'save' && c.source === 'process' && c.targetFilePath.includes('models'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves user.get_name in process to User#get_name via cross-file propagation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const getNameCall = calls.find(
|
|
(c) =>
|
|
c.target === 'get_name' && c.source === 'process' && c.targetFilePath.includes('models'),
|
|
);
|
|
expect(getNameCall).toBeDefined();
|
|
});
|
|
|
|
it('emits HAS_METHOD edges linking save and get_name 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 === 'get_name');
|
|
expect(saveEdge).toBeDefined();
|
|
expect(getNameEdge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Method Enrichment: visibility (private/protected), isStatic (singleton),
|
|
// parameters, HAS_METHOD edges, member call resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby method enrichment (visibility, isStatic, parameters)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-method-enrichment'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Animal and Dog classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Animal', 'Dog']);
|
|
});
|
|
|
|
it('detects all methods including singleton', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('speak');
|
|
expect(methods).toContain('classify');
|
|
expect(methods).toContain('from_habitat');
|
|
expect(methods).toContain('internal_state');
|
|
expect(methods).toContain('energy_level');
|
|
});
|
|
|
|
it('emits HAS_METHOD edges for Animal and Dog', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
// Animal has speak, classify, from_habitat, internal_state
|
|
expect(hasMethod.find((e) => e.source === 'Animal' && e.target === 'speak')).toBeDefined();
|
|
expect(hasMethod.find((e) => e.source === 'Animal' && e.target === 'classify')).toBeDefined();
|
|
expect(
|
|
hasMethod.find((e) => e.source === 'Animal' && e.target === 'from_habitat'),
|
|
).toBeDefined();
|
|
expect(
|
|
hasMethod.find((e) => e.source === 'Animal' && e.target === 'internal_state'),
|
|
).toBeDefined();
|
|
// Dog has speak, energy_level
|
|
expect(hasMethod.find((e) => e.source === 'Dog' && e.target === 'speak')).toBeDefined();
|
|
expect(hasMethod.find((e) => e.source === 'Dog' && e.target === 'energy_level')).toBeDefined();
|
|
});
|
|
|
|
it('marks internal_state as private (when enriched)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const internalState = methods.find(
|
|
(m) => m.name === 'internal_state' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(internalState).toBeDefined();
|
|
// Visibility enrichment requires the MethodExtractor path (worker mode).
|
|
// Sequential fallback (small repos) does not populate visibility.
|
|
if (internalState!.properties.visibility !== undefined) {
|
|
expect(internalState!.properties.visibility).toBe('private');
|
|
}
|
|
});
|
|
|
|
it('marks energy_level as protected (when enriched)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const energyLevel = methods.find(
|
|
(m) => m.name === 'energy_level' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(energyLevel).toBeDefined();
|
|
if (energyLevel!.properties.visibility !== undefined) {
|
|
expect(energyLevel!.properties.visibility).toBe('protected');
|
|
}
|
|
});
|
|
|
|
it('marks classify as static (when enriched)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const classify = methods.find(
|
|
(m) => m.name === 'classify' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(classify).toBeDefined();
|
|
if (classify!.properties.isStatic !== undefined) {
|
|
expect(classify!.properties.isStatic).toBe(true);
|
|
}
|
|
});
|
|
|
|
it('marks from_habitat (class << self) as static and public (when enriched)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const fromHabitat = methods.find(
|
|
(m) => m.name === 'from_habitat' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(fromHabitat).toBeDefined();
|
|
if (fromHabitat!.properties.isStatic !== undefined) {
|
|
expect(fromHabitat!.properties.isStatic).toBe(true);
|
|
}
|
|
if (fromHabitat!.properties.visibility !== undefined) {
|
|
expect(fromHabitat!.properties.visibility).toBe('public');
|
|
}
|
|
});
|
|
|
|
it('extracts parameterCount for from_habitat(habitat)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const fromHabitat = methods.find(
|
|
(m) => m.name === 'from_habitat' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(fromHabitat).toBeDefined();
|
|
expect(fromHabitat!.properties.parameterCount).toBe(1);
|
|
});
|
|
|
|
it('marks speak as public (when enriched)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const speak = methods.find(
|
|
(m) => m.name === 'speak' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(speak).toBeDefined();
|
|
// When the MethodExtractor enrichment runs, visibility defaults to public
|
|
if (speak!.properties.visibility !== undefined) {
|
|
expect(speak!.properties.visibility).toBe('public');
|
|
}
|
|
});
|
|
|
|
it('extracts parameterCount for classify(name)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const classify = methods.find(
|
|
(m) => m.name === 'classify' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(classify).toBeDefined();
|
|
expect(classify!.properties.parameterCount).toBe(1);
|
|
});
|
|
|
|
it('resolves dog.speak member call from main to Dog#speak', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const speakCall = calls.find(
|
|
(c) => c.source === 'main' && c.target === 'speak' && c.targetFilePath.includes('animal'),
|
|
);
|
|
expect(speakCall).toBeDefined();
|
|
});
|
|
|
|
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('detects main as top-level Method in app.rb', () => {
|
|
// Ruby top-level def is parsed as a method node (tree-sitter `method` type)
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('main');
|
|
});
|
|
});
|
|
|
|
describe('Ruby singleton_class handling (worker path)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-method-enrichment'), () => {});
|
|
}, 60000);
|
|
|
|
it('keeps Animal as the owner for class << self methods', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
expect(
|
|
hasMethod.find((e) => e.source === 'Animal' && e.target === 'from_habitat'),
|
|
).toBeDefined();
|
|
});
|
|
|
|
it('marks from_habitat as static', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const fromHabitat = methods.find(
|
|
(m) => m.name === 'from_habitat' && m.properties.filePath?.includes('animal'),
|
|
);
|
|
expect(fromHabitat).toBeDefined();
|
|
expect(fromHabitat!.properties.isStatic).toBe(true);
|
|
expect(fromHabitat!.properties.parameterCount).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Overload Dispatch: methods with different arity resolve via receiver type
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby overload dispatch (format vs format_with_prefix)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-overload-dispatch'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Formatter class', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Formatter');
|
|
});
|
|
|
|
it('detects format and format_with_prefix methods', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('format');
|
|
expect(methods).toContain('format_with_prefix');
|
|
});
|
|
|
|
it('emits HAS_METHOD edges for both methods on Formatter', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
expect(hasMethod.find((e) => e.source === 'Formatter' && e.target === 'format')).toBeDefined();
|
|
expect(
|
|
hasMethod.find((e) => e.source === 'Formatter' && e.target === 'format_with_prefix'),
|
|
).toBeDefined();
|
|
});
|
|
|
|
it('extracts arity for format(value) — 1 parameter', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const format = methods.find((m) => m.name === 'format');
|
|
expect(format).toBeDefined();
|
|
expect(format!.properties.parameterCount).toBe(1);
|
|
});
|
|
|
|
it('extracts arity for format_with_prefix(value, prefix) — 2 parameters', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const fwp = methods.find((m) => m.name === 'format_with_prefix');
|
|
expect(fwp).toBeDefined();
|
|
expect(fwp!.properties.parameterCount).toBe(2);
|
|
});
|
|
|
|
it('resolves f.format call from run to Formatter#format', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const formatCall = calls.find(
|
|
(c) => c.source === 'run' && c.target === 'format' && c.targetFilePath.includes('formatter'),
|
|
);
|
|
expect(formatCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves f.format_with_prefix call from run to Formatter#format_with_prefix', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const fwpCall = calls.find(
|
|
(c) =>
|
|
c.source === 'run' &&
|
|
c.target === 'format_with_prefix' &&
|
|
c.targetFilePath.includes('formatter'),
|
|
);
|
|
expect(fwpCall).toBeDefined();
|
|
});
|
|
|
|
it('detects run as top-level Method in app.rb', () => {
|
|
// Ruby top-level def is parsed as a method node (tree-sitter `method` type)
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('run');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// SM-9/SM-10: inherited method resolution — Ruby first-wins inheritance walk
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby Child extends Parent — inherited method resolution (SM-9)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-child-extends-parent'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Parent and Child classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('Parent');
|
|
expect(classes).toContain('Child');
|
|
});
|
|
|
|
it('resolves c.parent_method to Parent#parent_method via first-wins MRO walk', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const parentMethodCall = calls.find(
|
|
(c) => c.target === 'parent_method' && c.targetFilePath.includes('parent.rb'),
|
|
);
|
|
expect(parentMethodCall).toBeDefined();
|
|
expect(parentMethodCall!.source).toBe('run');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Namespaced class/module declarations — GRAPH NODE materialization (issue #1975)
|
|
//
|
|
// Follow-up to PR #1972 (F62): the scope query captures the tail constant for
|
|
// `class Foo::Bar` / `module Baz::Qux`, but the legacy structure query never
|
|
// matched the scope_resolution name, so no Class/Trait node was created and the
|
|
// declaration's methods got dangling HAS_METHOD edges. These pipeline-level
|
|
// tests assert the target behavior (a real node + a resolving HAS_METHOD edge).
|
|
// They fail on the pre-fix base — see plan docs/plans/2026-06-02-002-*.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby namespaced class/module definitions — graph nodes (issue #1975)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-namespaced'), () => {});
|
|
}, 60000);
|
|
|
|
// R1/R3: a distinct Class node is materialized for the namespaced class,
|
|
// keyed by its full scoped name (so Foo::Bar and Baz::Bar never collide).
|
|
// The node id matches the HAS_METHOD owner id derived from the same name field;
|
|
// qualifiedName carries the dotted path (Foo.Bar).
|
|
it('materializes a Class node for class Foo::Bar', () => {
|
|
const classes = getNodesByLabelFull(result, 'Class');
|
|
expect(classes.some((c) => c.properties.qualifiedName === 'Foo.Bar')).toBe(true);
|
|
});
|
|
|
|
// R1: deep chain Outer::Middle::Inner → qualifiedName Outer.Middle.Inner.
|
|
it('materializes a Class node for class Outer::Middle::Inner', () => {
|
|
const classes = getNodesByLabelFull(result, 'Class');
|
|
expect(classes.some((c) => c.properties.qualifiedName === 'Outer.Middle.Inner')).toBe(true);
|
|
});
|
|
|
|
// R1: module → Trait (Ruby modules are relabeled Trait for class-like lookup).
|
|
it('materializes a Trait node for module Baz::Qux', () => {
|
|
expect(getNodesByLabel(result, 'Trait')).toContain('Baz::Qux');
|
|
});
|
|
|
|
// R2: methods of namespaced declarations must not produce dangling HAS_METHOD edges.
|
|
it('emits no dangling HAS_METHOD edges for namespaced declarations', () => {
|
|
expect(findDanglingEdges(result, ['HAS_METHOD'])).toEqual([]);
|
|
});
|
|
|
|
// R2: the method resolves to a real owner node (not an 'unknown' dangling source).
|
|
it('owns bar_method under a resolving namespaced class node', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const edge = hasMethod.find((e) => e.target === 'bar_method');
|
|
expect(edge).toBeDefined();
|
|
expect(edge!.sourceLabel).toBe('Class');
|
|
});
|
|
});
|
|
|
|
describe('Ruby cross-namespace tail collision — distinct nodes (issue #1975)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-tail-collision'), () => {});
|
|
}, 60000);
|
|
|
|
// R3: Foo::Bar and Baz::Bar share the tail `Bar` but must NOT merge — keying by
|
|
// the full scoped name keeps them two distinct Class nodes.
|
|
it('keeps Foo::Bar and Baz::Bar as two distinct Class nodes', () => {
|
|
const qns = getNodesByLabelFull(result, 'Class')
|
|
.map((c) => c.properties.qualifiedName)
|
|
.filter((q) => q === 'Foo.Bar' || q === 'Baz.Bar')
|
|
.sort();
|
|
expect(qns).toEqual(['Baz.Bar', 'Foo.Bar']);
|
|
});
|
|
|
|
// R2/R3: each namespaced class owns its own method through a resolving node.
|
|
it('owns each method under its own namespaced class (no dangling, no cross-wire)', () => {
|
|
expect(findDanglingEdges(result, ['HAS_METHOD'])).toEqual([]);
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
expect(hasMethod.some((e) => e.target === 'from_foo' && e.sourceLabel === 'Class')).toBe(true);
|
|
expect(hasMethod.some((e) => e.target === 'from_baz' && e.sourceLabel === 'Class')).toBe(true);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Inline module-nested same-tail collision — distinct nodes (issue #1978)
|
|
//
|
|
// `module Outer; class Inner; end; end` + `module Other; class Inner; end; end`
|
|
// must own their methods through TWO distinct Class nodes (qn Outer.Inner vs
|
|
// Other.Inner). On the pre-fix base both Inner classes merge into one
|
|
// simple-keyed node and from_outer/from_other cross-wire (dangling:0 but wrong).
|
|
// Asserts positive owner-identity by the resolved node's qualifiedName (R7).
|
|
// (Distinct from the compact `Foo::Bar` collision block above, which #1977 fixed.)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby inline module-nested same-tail collision — distinct nodes (issue #1978)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-nested-tail-collision'), () => {});
|
|
}, 60000);
|
|
|
|
it('owns from_outer / from_other through distinct Outer.Inner / Other.Inner nodes (R7)', () => {
|
|
expect(findDanglingEdges(result, ['HAS_METHOD'])).toEqual([]);
|
|
const hm = getRelationships(result, 'HAS_METHOD');
|
|
const ownerQn = (target: string) => {
|
|
const e = hm.find((x) => x.target === target);
|
|
expect(e, `HAS_METHOD -> ${target}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName;
|
|
};
|
|
expect(ownerQn('from_outer')).toBe('Outer.Inner');
|
|
expect(ownerQn('from_other')).toBe('Other.Inner');
|
|
});
|
|
|
|
// attr_accessor routes through the property-registration pre-pass — a SEPARATE
|
|
// code path from `def` methods: call-processor.ts (sequential/legacy) and the
|
|
// parse-worker `kind === 'properties'` block (worker). Under qualifiedNodeId the
|
|
// owner must resolve to the QUALIFIED class node (Shapes.Circle); the pre-fix
|
|
// simple `Class:f.rb:Circle` no longer exists and would dangle. Exercised here
|
|
// on an UNAMBIGUOUS nested class (no same-tail sibling) so the assertion is
|
|
// exact on both legs.
|
|
//
|
|
// NOTE: exact owner identity for a routed property under SAME-TAIL nested types
|
|
// (e.g. two `Inner` classes) is a separate resolution-side concern — the
|
|
// registry-primary `emitRubyMixinEdges` bridge resolves the owner by simple
|
|
// tail name (last-wins) and the worker path can emit a duplicate cross-wired
|
|
// edge. That is deferred to the #1978 resolution-side follow-up; the
|
|
// structure-phase HAS_METHOD ownership above is already exact on both legs.
|
|
it('owns radius (attr_accessor) under the qualified Shapes.Circle node, no dangling (R7)', () => {
|
|
expect(findDanglingEdges(result, ['HAS_PROPERTY'])).toEqual([]);
|
|
const hp = getRelationships(result, 'HAS_PROPERTY');
|
|
const e = hp.find((x) => x.target === 'radius');
|
|
expect(e, 'HAS_PROPERTY -> radius').toBeDefined();
|
|
expect(result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName).toBe('Shapes.Circle');
|
|
});
|
|
|
|
// #1982 resolution-side: SAME-TAIL routed-property owner identity. The
|
|
// pre-fix emitRubyMixinEdges keys its owner map by simple tail (last-wins),
|
|
// so outer_attr / other_attr both attach to whichever `Inner` was processed
|
|
// last. Asserts each routes to its OWN qualified node by qualifiedName, with
|
|
// exactly one (non-duplicated) edge. Registry-primary only.
|
|
it('owns outer_attr / other_attr under their OWN qualified Inner node (same-tail attr_accessor, R7)', () => {
|
|
const hp = getRelationships(result, 'HAS_PROPERTY');
|
|
const ownerQnOf = (prop: string) => {
|
|
const e = hp.find((x) => x.target === prop);
|
|
expect(e, `HAS_PROPERTY -> ${prop}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName;
|
|
};
|
|
expect(ownerQnOf('outer_attr')).toBe('Outer.Inner');
|
|
expect(ownerQnOf('other_attr')).toBe('Other.Inner');
|
|
expect(hp.filter((x) => x.target === 'outer_attr')).toHaveLength(1);
|
|
expect(hp.filter((x) => x.target === 'other_attr')).toHaveLength(1);
|
|
});
|
|
|
|
// #1982 resolution-side: SAME-TAIL mixin owner identity (IMPLEMENTS).
|
|
it('routes include OuterMix / OtherMix to their OWN qualified Inner owner (same-tail mixin, R7)', () => {
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const ownerQnOfMixin = (mixinName: string) => {
|
|
const e = impl.find((x) => x.target === mixinName);
|
|
expect(e, `IMPLEMENTS -> ${mixinName}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName;
|
|
};
|
|
expect(ownerQnOfMixin('OuterMix')).toBe('Outer.Inner');
|
|
expect(ownerQnOfMixin('OtherMix')).toBe('Other.Inner');
|
|
});
|
|
});
|
|
|
|
// Same fixture through the WORKER pool. The deferred note flagged that the worker
|
|
// path could emit a DUPLICATE cross-wired same-tail owner edge (the worker emits
|
|
// the __property__/__heritage__ markers, which must now carry the full qualified
|
|
// owner). Asserts worker == sequential: each attr owns its OWN qualified node with
|
|
// exactly one edge (#1982 R7). Registry-primary only.
|
|
describe('Ruby inline module-nested same-tail collision — worker path parity (issue #1982)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-nested-tail-collision'),
|
|
() => {},
|
|
{
|
|
workerPoolSize: 2,
|
|
},
|
|
);
|
|
}, 120000);
|
|
|
|
it('genuinely used the worker pool for the same-tail Ruby fixture', () => {
|
|
expect(result.usedWorkerPool).toBe(true);
|
|
});
|
|
|
|
it('owns outer_attr / other_attr under their OWN qualified Inner node on the worker path (no duplicate, R7)', () => {
|
|
const hp = getRelationships(result, 'HAS_PROPERTY');
|
|
const ownerQnOf = (prop: string) => {
|
|
const e = hp.find((x) => x.target === prop);
|
|
expect(e, `HAS_PROPERTY -> ${prop}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName;
|
|
};
|
|
expect(ownerQnOf('outer_attr')).toBe('Outer.Inner');
|
|
expect(ownerQnOf('other_attr')).toBe('Other.Inner');
|
|
expect(hp.filter((x) => x.target === 'outer_attr')).toHaveLength(1);
|
|
expect(hp.filter((x) => x.target === 'other_attr')).toHaveLength(1);
|
|
});
|
|
|
|
// Worker-path parity for the MIXIN (IMPLEMENTS) path — the __heritage__ marker
|
|
// owner must survive worker serialization (not only attr_accessor / HAS_PROPERTY).
|
|
it('routes include OuterMix / OtherMix to their OWN qualified Inner owner on the worker path (IMPLEMENTS, R7)', () => {
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const ownerQnOfMixin = (mixinName: string) => {
|
|
const e = impl.find((x) => x.target === mixinName);
|
|
expect(e, `IMPLEMENTS -> ${mixinName}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.sourceId)?.properties.qualifiedName;
|
|
};
|
|
expect(ownerQnOfMixin('OuterMix')).toBe('Outer.Inner');
|
|
expect(ownerQnOfMixin('OtherMix')).toBe('Other.Inner');
|
|
expect(impl.filter((x) => x.target === 'OuterMix')).toHaveLength(1);
|
|
expect(impl.filter((x) => x.target === 'OtherMix')).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Same-tail NESTED mixin MODULE collision — distinct Trait nodes (issue #1991)
|
|
//
|
|
// `module App; module Loggable; class S; include Loggable; end; end` +
|
|
// `module Web; module Loggable; class T; include Loggable; end; end`. The
|
|
// structure phase never qualified `module` (Trait) node ids, so both Loggable
|
|
// modules collapsed onto one Trait:app.rb:Loggable node and the bare-name mixin
|
|
// reference cross-wired IMPLEMENTS (first-wins tail). Asserts two distinct Trait
|
|
// nodes and each class IMPLEMENTS its OWN module (positive target identity), not
|
|
// just dangle-free. The IMPLEMENTS routing is registry-primary.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby same-tail nested mixin-module collision — distinct Trait nodes (issue #1991)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-nested-mixin-tail-collision'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('materializes App.Loggable and Web.Loggable as two distinct Trait nodes', () => {
|
|
const qns = getNodesByLabelFull(result, 'Trait')
|
|
.map((n) => n.properties.qualifiedName)
|
|
.filter((q) => q === 'App.Loggable' || q === 'Web.Loggable')
|
|
.sort();
|
|
expect(qns).toEqual(['App.Loggable', 'Web.Loggable']);
|
|
});
|
|
|
|
it('routes S -> App.Loggable and T -> Web.Loggable (no cross-wire, R2)', () => {
|
|
expect(findDanglingEdges(result, ['IMPLEMENTS', 'HAS_METHOD'])).toEqual([]);
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const targetQnOf = (className: string) => {
|
|
const e = impl.find((x) => x.source === className && x.target === 'Loggable');
|
|
expect(e, `IMPLEMENTS from ${className}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.targetId)?.properties.qualifiedName;
|
|
};
|
|
expect(targetQnOf('S')).toBe('App.Loggable');
|
|
expect(targetQnOf('T')).toBe('Web.Loggable');
|
|
expect(impl.filter((x) => x.source === 'S')).toHaveLength(1);
|
|
expect(impl.filter((x) => x.source === 'T')).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
// Same fixture through the WORKER pool — the __heritage__ marker owner + the
|
|
// qualified module node id must survive worker serialization (#1991 R2/R15).
|
|
describe('Ruby same-tail nested mixin-module collision — worker path parity (issue #1991)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-nested-mixin-tail-collision'),
|
|
() => {},
|
|
{ workerPoolSize: 2 },
|
|
);
|
|
}, 120000);
|
|
|
|
it('genuinely used the worker pool for the same-tail mixin-module fixture', () => {
|
|
expect(result.usedWorkerPool).toBe(true);
|
|
});
|
|
|
|
it('routes S -> App.Loggable and T -> Web.Loggable on the worker path (no cross-wire)', () => {
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const targetQnOf = (className: string) => {
|
|
const e = impl.find((x) => x.source === className && x.target === 'Loggable');
|
|
expect(e, `IMPLEMENTS from ${className}`).toBeDefined();
|
|
return result.graph.getNode(e!.rel.targetId)?.properties.qualifiedName;
|
|
};
|
|
expect(targetQnOf('S')).toBe('App.Loggable');
|
|
expect(targetQnOf('T')).toBe('Web.Loggable');
|
|
expect(impl.filter((x) => x.source === 'S')).toHaveLength(1);
|
|
expect(impl.filter((x) => x.source === 'T')).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Nested mixin included by SHORT name — IMPLEMENTS edge must not drop (#1982).
|
|
//
|
|
// `module App; module Loggable; end; class Service; include Loggable; end; end`
|
|
// — `Loggable` is nested (qn App.Loggable) but included by its bare short name.
|
|
// The structure phase materializes a distinct App.Loggable node, but
|
|
// emitRubyMixinEdges keys graphIdByName by FULL qualifiedName while the
|
|
// __heritage__ marker carries the bare arg.text ('Loggable'), so the
|
|
// mixin-target lookup missed and the IMPLEMENTS edge was silently dropped
|
|
// (0 dangling, undetectable). The shipped same-tail fixture only uses TOP-LEVEL
|
|
// mixin modules (full qn == bare name), so it cannot catch this. Asserts the
|
|
// edge exists and resolves by NODE ID (KTD3 — not the normalized qualifiedName
|
|
// property). Registry-primary only (emitRubyMixinEdges is the registry bridge).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby nested mixin by short name — IMPLEMENTS not dropped (issue #1982)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'ruby-nested-mixin-shortname'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('emits App.Service -IMPLEMENTS-> App.Loggable for a short-name nested mixin (R1)', () => {
|
|
expect(findDanglingEdges(result, ['IMPLEMENTS'])).toEqual([]);
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const e = impl.find((x) => x.target === 'Loggable');
|
|
expect(e, 'IMPLEMENTS -> Loggable (nested mixin by short name)').toBeDefined();
|
|
// KTD3: discriminate on the resolved node id, not the normalized property.
|
|
// The owner resolves to the QUALIFIED `App.Service` class node — the pre-fix
|
|
// bug dropped the edge entirely, so its presence + qualified owner is the
|
|
// discriminator. (The mixin module is a Trait node keyed by its simple name
|
|
// `Loggable`; Trait-node qualification under same-tail modules is a separate
|
|
// structure-phase concern, deferred.)
|
|
expect(e!.rel.sourceId).toContain('App.Service');
|
|
expect(e!.rel.targetId).toContain('Loggable');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Qualified mixin argument — `::` must not corrupt the __heritage__ marker (#1982).
|
|
//
|
|
// `class Consumer; include Outer::Mixin; end` — the `::` in `arg.text`
|
|
// (`Outer::Mixin`) collided with the ':'-delimited __heritage__ marker field
|
|
// separator (`__heritage__:include:Outer::Mixin:Consumer`), so emitRubyMixinEdges
|
|
// mis-split it and dropped the edge. The marker now embeds the dotted form
|
|
// (`Outer.Mixin`), which both parses correctly and matches the mixin def's
|
|
// qualifiedName. Registry-primary only.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Ruby qualified mixin arg — IMPLEMENTS not corrupted by :: (issue #1982)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'ruby-qualified-mixin'), () => {});
|
|
}, 60000);
|
|
|
|
it('emits Consumer -IMPLEMENTS-> Outer.Mixin for include Outer::Mixin (R2)', () => {
|
|
expect(findDanglingEdges(result, ['IMPLEMENTS'])).toEqual([]);
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const e = impl.find((x) => x.target === 'Mixin');
|
|
expect(e, 'IMPLEMENTS -> Mixin (qualified mixin arg)').toBeDefined();
|
|
// KTD3: discriminate on the resolved node id (the pre-fix bug dropped the edge).
|
|
expect(e!.rel.sourceId).toContain('Consumer');
|
|
expect(e!.rel.targetId).toContain('Mixin');
|
|
});
|
|
});
|