From f6e42092b3c3038189e4726c40999182dd62ff64 Mon Sep 17 00:00:00 2001 From: Abhigyan Patwari <126312502+abhigyanpatwari@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:54:26 +0530 Subject: [PATCH 1/6] fix(zig): resolve import-alias, forwarding-constructor, anonymous-container and type-application receivers (#3652) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(zig): bind the module of a one-member @import alias as a receiver `const X = @import("f.zig").X;` reads `X` off an `@import(...)` receiver. The named-import rule claims that builtin, so the inline-import branch skipped it and never emitted the receiver-keyed namespace binding the deep form (`@import("lib.zig").B.work`) and member-call receivers already get. Every such read was recorded as a receiver-unresolved drop; the ones whose alias shares the member's name only produced an edge through the lexical read fallback, and a renaming alias (`const Gauge = ...DEFAULT_NS;`) produced nothing. `isZigInlineImportReceiver` now also accepts the value read of a keyword one-member import declaration (never a type annotation), and a claimed builtin that is a receiver gets the namespace binding instead of being dropped. The named import itself is unchanged, so `Gauge` stays an import binding. Clears the 9 F-A rows of the #3498 drop triage; the reads now resolve through the written module (`import-resolved`). Co-Authored-By: Claude Opus 5.5 * fix(zig): type a forwarding type constructor as the type it forwards to `fn Bridge(comptime T: type) type { return Builder(T); }` (Lightpanda's `js.Bridge(T)`) names no container of its own. `zigReturnTypeIsNominal` drops `type` returns and `zigTypeConstructorOf` only names a container returned directly, so a receiver typed `Bridge(X)` reached a Function that owns no members and every call on it was lost. A type constructor whose body is a single `return ` (and whose callee is not one of its own parameters) now binds `Bridge ↦ Builder` through its return-type binding. The binding is declared in Bridge's own scope, so a chain followed from an importer still looks `Builder` up where it is visible. The new aliases.zig `b12` case (a named import of the forwarding constructor, bound and inline spellings) resolves into generic.zig's Builder. The namespace-qualified spelling of the #3498 F-B rows (`generic.Bridge(Local)`) additionally needs the `ns.f` return-type fold, which this binding feeds. Co-Authored-By: Claude Opus 5.5 * fix(zig): resolve a member read off an anonymous container in place `struct { fn lessThan ... }.lessThan` (the comparator handed to `std.sort.pdq`) and `const byteSize = struct { fn it ... }.it;` read a fn value off an anonymous container. The receiver capture was the container's whole body, which names nothing, so each read was a receiver-unresolved drop and the qualified-argument value reference declined. The only edge came from the lexical read fallback at the site's anchor, which starts at `struct` and therefore inside the container's own Class scope: the container "accessed" its own fn. A reference group whose receiver is a container node now carries the identity that container is minted under (`Sorter.sortBoth$1`, via `zigContainerName`), and its site anchor moves to the member, which is evaluated in the enclosing scope. The reads resolve as ACCESSES from the fn that evaluates them (and, for the pdq argument, a value-ref USES); no CALLS edge. Clears the 3 F-C rows of the #3498 drop triage. Co-Authored-By: Claude Opus 5.5 * fix(zig): type a type-constructor call used as a receiver `Stack(u8).init()` calls `init` on the TYPE `Stack(u8)`. The free-call branch of `resolveCompoundReceiverClass` found `fn Stack`, found no return binding (it returns `type`), and fell into the construction path, which declines for a language without `constructionSyntax`. The call and its callee-position read were dropped, while the bound form `var t = Stack(u8).init(); t.top()` resolved. Add a language-neutral `ScopeResolver.isTypeApplicationCall(callee)` hook. When it answers true, the construction path types the receiver as the class the callee names (direct or namespace-qualified), exactly as a bare construction does; the callee's return-type binding still wins. Zig answers with `isZigTypeConstructorCallee`, the text twin of `isZigTypeConstructorCall` (a TitleCase last identifier). Clears the 2 F-D rows of the #3498 drop triage (main.zig:42 call + read). Co-Authored-By: Claude Opus 5.5 * test(bench): re-baseline receiver resolution for the Zig receiver fixes The four Zig fixes clear 14 receiver-unresolved sites in the corpus: all-kind drops 192 -> 178, reads 44 -> 31, calls 128 -> 127 (Zig 11 -> 10, no-chain 27 -> 26, in-program 55 -> 54). Nine one-member `@import(...).X` reads, three anonymous-container reads and the `Stack(u8).init()` call and read now resolve. Writes and every shape-arm state are unchanged; no new drop was introduced. BASELINE.md records the per-site breakdown. Co-Authored-By: Claude Opus 5.5 * fix(zig): keep type applications lexical * fix(zig): bind typed inline imports --------- Co-authored-by: Gergo Magyar Co-authored-by: Claude Opus 5.5 --- .../bench/receiver-resolution/BASELINE.md | 29 ++ .../bench/receiver-resolution/baseline.json | 14 +- .../core/ingestion/languages/zig/captures.ts | 147 +++++++++- .../src/core/ingestion/languages/zig/index.ts | 1 + .../ingestion/languages/zig/scope-resolver.ts | 14 +- .../contract/scope-resolver.ts | 23 ++ .../passes/compound-receiver.ts | 29 +- .../passes/receiver-bound-calls.ts | 2 + .../zig-filestruct/src/aliases.zig | 9 + .../test/integration/resolvers/zig.test.ts | 271 ++++++++++++++++++ gitnexus/test/unit/zig-extractors.test.ts | 163 ++++++++++- 11 files changed, 675 insertions(+), 27 deletions(-) diff --git a/gitnexus/bench/receiver-resolution/BASELINE.md b/gitnexus/bench/receiver-resolution/BASELINE.md index 09bd31166b..67bcd76184 100644 --- a/gitnexus/bench/receiver-resolution/BASELINE.md +++ b/gitnexus/bench/receiver-resolution/BASELINE.md @@ -1,5 +1,34 @@ # Receiver-resolution baseline +## Zig receiver gaps from the #3498 drop triage + +Measured against main `2b6542737`, the four Zig fixes clear 18 +`receiver-unresolved` sites: all-kind drops move from 200 to 182, reads from +42 to 27 and calls from 138 to 135. Writes and every shape-arm state are +unchanged. + +- 9 reads of `const X = @import("f.zig").X;` (zig-hub `stdx.zig:2-4`, + zig-receivers `stdx.zig:2`, zig-idioms `holder.zig:6`, `main.zig:6`, + `Element.zig:35`, `hub.zig:9-10`): the `@import(…)` receiver is now bound as a + namespace, so the read resolves through the written module (`import-resolved`). +- 3 reads off an anonymous container (`Sorter.zig:16`, `:23`, `:28`): + the receiver names the container's minted identity. The site is now anchored + on the member, so it moves off the reported `struct` position and resolves + from the scope that evaluates it. +- 1 call and its callee-position read at zig-idioms `main.zig:42` + (`Stack(u8).init()`): the new `isTypeApplicationCall` hook types the receiver + as `Stack`. +- 2 calls and their callee-position reads at zig-filestruct `aliases.zig:86` + and `:88` (`JsApi.Meta.prototype_chain` and `JsApi.value`): the + `bridge = generic.Bridge(Local)` alias reaches `Builder` through the + forwarding return type. These were lines 77 and 79 on the measured main. + +Forwarding type constructors (`Bridge ↦ Builder`) also work through the +namespace-factory lookup already merged in #3648. The combined result clears +more sites than the original standalone branch, which cleared 14. The `b12` +alias control resolves. Zig call drops fall from 13 to 10; `no-chain` call +drops move from 34 to 31 and `in-program` calls from 60 to 57. + ## Go module visibility and qualified receiver refusal Local imports now select the importer's own module or a module selected by its diff --git a/gitnexus/bench/receiver-resolution/baseline.json b/gitnexus/bench/receiver-resolution/baseline.json index 9deb7c6c94..8d48c513ad 100644 --- a/gitnexus/bench/receiver-resolution/baseline.json +++ b/gitnexus/bench/receiver-resolution/baseline.json @@ -199,18 +199,18 @@ } }, "countArm": { - "callDrops": 138, - "totalDropsAllKinds": 200, + "callDrops": 135, + "totalDropsAllKinds": 182, "bySiteKind": { - "call": 138, - "read": 42, + "call": 135, + "read": 27, "write": 20 }, "callDropsByExtension": { ".java": 49, ".py": 24, ".ts": 17, - ".zig": 13, + ".zig": 10, ".cs": 8, ".tsx": 6, ".go": 4, @@ -223,13 +223,13 @@ }, "callDropsByShape": { "chain-field": 59, - "no-chain": 34, + "no-chain": 31, "chain-call": 31, "<>": 13, "chain-unwrap": 1 }, "callDropsByOrigin": { - "in-program": 60, + "in-program": 57, "external": 44, "unknown": 32, "<>": 2 diff --git a/gitnexus/src/core/ingestion/languages/zig/captures.ts b/gitnexus/src/core/ingestion/languages/zig/captures.ts index 1e6b1c03de..721f4a2547 100644 --- a/gitnexus/src/core/ingestion/languages/zig/captures.ts +++ b/gitnexus/src/core/ingestion/languages/zig/captures.ts @@ -28,6 +28,13 @@ const STATIC_GATED_MARKER: Capture = Object.freeze({ text: '', }); const NO_IMPORT_ALIASES: ZigImportAliasMap = new Map(); +/** The site anchors of the query's receiver-bearing reference rules. */ +const ZIG_RECEIVER_SITE_ANCHORS = [ + '@reference.read', + '@reference.value-ref', + '@reference.call.member', + '@reference.call.constructor', +] as const; /** Stamp `@reference.static-gated` onto every call capture whose anchor sits * in a statically dead range. File-local constants only for now (v1): the @@ -83,15 +90,30 @@ export function zigImportRootOf(value: SyntaxNode | null): SyntaxNode | null { * `@import("dump.zig").root(...)` — or of a qualified construction — * `@import("a.zig").Thing{…}` — i.e. the `object` of a `field_expression` * that is the `function` of a `call_expression` or the type of a - * `struct_initializer`? A deeper chain (`@import("x.zig").Foo.init()`) is - * not: its receiver is `….Foo`, and the builtin is only the module the chain - * starts from (the namespace chain walk resolves it from there). */ + * `struct_initializer`? Or of the member READ a one-member import + * declaration makes — `const X = @import("f.zig").X;` — which the deep form + * (`@import("lib.zig").B.work`, `collectZigDeepAliases`) already binds: the + * named import records `X`, but the `.X` read beside it had a receiver + * nothing was bound to, so it was a receiver drop, and a renaming alias + * (`const Gauge = @import("u.zig").DEFAULT_NS;`) reached nothing at all + * (#3498 triage, F-A). Any other deeper chain (`@import("x.zig").Foo.init()`) + * is not: its receiver is `….Foo`, and the builtin is only the module the + * chain starts from (the namespace chain walk resolves it from there). */ export function isZigInlineImportReceiver(importNode: SyntaxNode): boolean { const field = importNode.parent; if (field?.type !== 'field_expression') return false; if (field.childForFieldName('object')?.id !== importNode.id) return false; const use = field.parent; if (use === null || use === undefined) return false; + if (use.type === 'variable_declaration') { + // The VALUE only: `var x: @import("m.zig").T = undefined;` types a + // variable and imports nothing (`isZigTypePositionImport`). + return ( + isZigKeywordDeclaration(use) && + use.childForFieldName('type')?.id !== field.id && + use.namedChildren.filter((child) => child !== null).at(-1)?.id === field.id + ); + } if (use.type === 'call_expression') return use.childForFieldName('function')?.id === field.id; // `@import("a.zig").Thing{…}` — the module is the receiver of a qualified // CONSTRUCTION (the `@reference.call.constructor` rule with a receiver, see @@ -601,6 +623,37 @@ export function zigTypeConstructorOf(containerNode: SyntaxNode): SyntaxNode | nu return fn.childForFieldName('type')?.text === 'type' ? fn : null; } +/** For a type constructor that FORWARDS to another — `fn Bridge(comptime T: + * type) type { return Builder(T); }`, Lightpanda's `js.Bridge(T)` — the + * callee as written (`Builder`, `other.Builder`); undefined for any other + * fn. `Bridge(X)` IS `Builder(X)`, but neither `zigReturnTypeIsNominal` (a + * `type` return) nor `zigTypeConstructorOf` (no container in the body) gives + * `Bridge` a type, so a receiver typed `Bridge(X)` reached a Function that + * owns no members (#3498 triage, F-B). Only the literal shape counts: a body + * that is ONE `return ` (comments aside), whose callee is not + * a parameter of the fn (`return F(u8)` applies the caller's choice). */ +export function zigForwardedTypeConstructor(fn: SyntaxNode): string | undefined { + if (fn.type !== 'function_declaration' || fn.childForFieldName('type')?.text !== 'type') { + return undefined; + } + const statements = (fn.childForFieldName('body')?.namedChildren ?? []).filter( + (c): c is SyntaxNode => c !== null && c.type !== 'comment', + ); + const [only] = statements; + if (statements.length !== 1 || only?.type !== 'expression_statement') return undefined; + const ret = only.namedChild(0); + const value = ret?.type === 'return_expression' ? ret.namedChild(0) : null; + if (value === null || value === undefined || !isZigTypeConstructorCall(value)) return undefined; + const callee = value.childForFieldName('function'); + const head = callee === null ? null : zigChainHead(callee); + if (callee === null || head === null) return undefined; + const params = fn.namedChildren.find((c): c is SyntaxNode => c?.type === 'parameters'); + const appliesParameter = (params?.namedChildren ?? []).some( + (p) => p?.type === 'parameter' && p.childForFieldName('name')?.text === head.text, + ); + return appliesParameter ? undefined : callee.text; +} + /** F7 — is `call` an instantiation of a generic type constructor — * `List(u8)`, `util.List(u8)`, `js.Bridge(T)`, `std.AutoHashMapUnmanaged(K, V)`? * Zig spells a generic type as a CALL, and the grammar cannot separate it @@ -615,6 +668,14 @@ export function isZigTypeConstructorCall(call: SyntaxNode): boolean { return /^[A-Z]/.test(callee.text); } +/** The text twin of `isZigTypeConstructorCall`, for the resolver's + * `isTypeApplicationCall` hook, which sees a receiver call's callee as + * written (`Stack`, `util.List`) rather than as a node: its last + * identifier is TitleCase. Same heuristic, same caveat. */ +export function isZigTypeConstructorCallee(callee: string): boolean { + return /^[A-Z]\w*$/.test(callee.slice(callee.lastIndexOf('.') + 1)); +} + /** A `fn` nested in a struct/enum/union/opaque container is a method. Single * predicate shared between the provider's `labelOverride` (worker * structure phase) and the scope-capture relabel below, so the graph @@ -1328,13 +1389,18 @@ export function emitZigScopeCaptures( // `root` in dump.zig exactly as it would for `const dump = // @import("dump.zig"); dump.root(...)`. Anything else is a side-effect // import (file edge only), emitted once per distinct source per file. + // A one-member import declaration's builtin is claimed by its binding + // rule (the named import owns the file edge) and is still a receiver: it + // gets the namespace binding and nothing else. const inlineImport = nodeMap['@import.inline']; if (inlineImport !== undefined) { const source = nodeMap['@import.source']!; - if (claimedImportSourceIds.has(source.id)) continue; + const isReceiver = + isZigInlineImportReceiver(inlineImport) || deepAliases.inlineRoots.has(inlineImport.id); + if (claimedImportSourceIds.has(source.id) && !isReceiver) continue; const sourceCapture = grouped['@import.source']!; - if (isZigInlineImportReceiver(inlineImport) || deepAliases.inlineRoots.has(inlineImport.id)) { - const key = `receiver:${zigLexicalHost(inlineImport)?.id}:${source.text}`; + if (isReceiver) { + const key = `receiver:${zigLexicalHost(inlineImport)?.id}:${inlineImport.text}`; if (importedSourceTexts.has(key)) continue; importedSourceTexts.add(key); out.push({ @@ -1369,7 +1435,7 @@ export function emitZigScopeCaptures( ); const source = nodeMap['@import.source']; if (importRoot !== null && source !== undefined) { - const key = `receiver:${zigLexicalHost(importRoot)?.id}:${source.text}`; + const key = `receiver:${zigLexicalHost(importRoot)?.id}:${importRoot.text}`; if (!importedSourceTexts.has(key)) { importedSourceTexts.add(key); out.push({ @@ -1521,8 +1587,20 @@ export function emitZigScopeCaptures( // Only nominal returns bind (see `zigReturnTypeIsNominal`); a bare // `@This()` return names the enclosing container by name (the alias // rewrite below handles the `Self` spelling of the same thing). + // A forwarding type constructor (`fn Bridge(…) type { return Builder(T); + // }`) binds `Bridge ↦ Builder` instead of its `type` return — declared in + // Bridge's own scope, so a chain followed from another file still looks + // `Builder` up where it is visible (see `zigForwardedTypeConstructor`). const returnAnchor = nodeMap['@type-binding.return']; - if (returnAnchor !== undefined) { + const forwardedType = + returnAnchor === undefined ? undefined : zigForwardedTypeConstructor(returnAnchor); + if (returnAnchor !== undefined && forwardedType !== undefined) { + grouped['@type-binding.type'] = syntheticCapture( + '@type-binding.type', + nodeMap['@type-binding.type'] ?? returnAnchor, + forwardedType, + ); + } else if (returnAnchor !== undefined) { const retType = nodeMap['@type-binding.type']; if (retType === undefined || !zigReturnTypeIsNominal(retType)) continue; if (retType.text.includes('@This()')) { @@ -1638,6 +1716,37 @@ export function emitZigScopeCaptures( ) { Object.assign(grouped, republishMarker(nodeMap['@import.statement'])); } + + // F8 — a member of an ANONYMOUS container used in place: `std.sort.pdq(…, + // struct { fn lessThan … }.lessThan)`, `const byteSize = struct { fn it … + // }.it;`. The receiver text is the container's whole body, which names + // nothing, so every such site was a receiver drop (#3498 triage, F-C). + // Name the receiver by the identity the container is minted under + // (`Sorter.sortBoth$1`, see `zigContainerName`), and anchor the site on the + // member: from `struct` on it lies inside the container's own Class scope, + // which made the container the "caller" of its own fn, while the member is + // evaluated in the enclosing scope (the fn that hands the comparator on). + const receiverNode = nodeMap['@reference.receiver']; + const memberNode = nodeMap['@reference.name']; + if ( + receiverNode !== undefined && + memberNode !== undefined && + ZIG_CONTAINER_TYPES.has(receiverNode.type) + ) { + const identity = zigContainerName(receiverNode, _filePath); + if (identity !== undefined) { + grouped['@reference.receiver'] = syntheticCapture( + '@reference.receiver', + receiverNode, + identity, + ); + const memberRange = zigNodeRange(memberNode); + for (const tag of ZIG_RECEIVER_SITE_ANCHORS) { + const anchor = grouped[tag]; + if (anchor !== undefined) grouped[tag] = { ...anchor, range: memberRange }; + } + } + } out.push(grouped); // F5 — field types. `session: *Session,` declares the TYPE of the member @@ -1872,12 +1981,22 @@ function zigRangeKey(range: ZigRange): string { function addZigLexicalFacts(out: CaptureMatch[], root: SyntaxNode): void { const nodes = new Map(); const declarations: SyntaxNode[] = []; + const typeConstructors = new Set(); const visit = (node: SyntaxNode): void => { const key = zigRangeKey(zigNodeRange(node)); const peers = nodes.get(key); if (peers === undefined) nodes.set(key, [node]); else peers.push(node); - if (node.type === 'variable_declaration' || node.type === 'parameter') declarations.push(node); + if ( + node.type === 'variable_declaration' || + node.type === 'parameter' || + node.type === 'function_declaration' + ) + declarations.push(node); + if (ZIG_CONTAINER_TYPES.has(node.type)) { + const constructor = zigTypeConstructorOf(node); + if (constructor !== null) typeConstructors.add(constructor.id); + } for (const child of node.namedChildren) if (child !== null) visit(child); }; visit(root); @@ -1937,8 +2056,16 @@ function addZigLexicalFacts(out: CaptureMatch[], root: SyntaxNode): void { } for (const node of declarations) { if (importedDeclarations.has(zigRangeKey(zigNodeRange(node)))) continue; + if (node.type === 'function_declaration' && node.childForFieldName('type')?.text !== 'type') + continue; + // A modeled constructor also binds its returned container under this name, + // with a different declaration range. Preserve that dual binding. + if (node.type === 'function_declaration' && typeConstructors.has(node.id)) continue; if (node.type === 'variable_declaration' && !isZigKeywordDeclaration(node)) continue; - const name = node.type === 'parameter' ? node.childForFieldName('name') : node.namedChild(0); + const name = + node.type === 'parameter' || node.type === 'function_declaration' + ? node.childForFieldName('name') + : node.namedChild(0); const owner = zigLexicalHost(node); if (owner !== null && name?.type === 'identifier') { // A file's @This() alias names the synthetic Struct declaration, whose diff --git a/gitnexus/src/core/ingestion/languages/zig/index.ts b/gitnexus/src/core/ingestion/languages/zig/index.ts index 10d47336bb..86db140215 100644 --- a/gitnexus/src/core/ingestion/languages/zig/index.ts +++ b/gitnexus/src/core/ingestion/languages/zig/index.ts @@ -6,6 +6,7 @@ export { isZigFileThisAlias, isZigKeywordDeclaration, isZigRedundantContainerCapture, + isZigTypeConstructorCallee, isZigTypeShadowingBinding, zigCallableQualifiedName, zigContainerAnchor, diff --git a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts index 675f6e1a89..50f29322b4 100644 --- a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts @@ -22,7 +22,12 @@ import { } from '../../language-config.js'; import { resolveZigImportInternal } from '../../import-resolvers/zig.js'; import { zigProvider } from '../zig.js'; -import { expandZigWildcardNames, zigArityCompatibility, zigMergeBindings } from './index.js'; +import { + expandZigWildcardNames, + isZigTypeConstructorCallee, + zigArityCompatibility, + zigMergeBindings, +} from './index.js'; import { populateZigRangeBindings } from './range-binding.js'; import { populateZigWorkspaceStaticGating } from './workspace-static-gating.js'; @@ -51,6 +56,13 @@ export const zigScopeResolver: ScopeResolver = { // import; a one-hop split at the last dot resolved none of them. resolveNamespaceChains: true, + // Zig spells a generic type as a call: `Stack(u8).init()` calls `init` on + // the TYPE `Stack(u8)`. `Stack` returns `type`, which binds nothing, so the + // inline receiver typed nothing while `var t = Stack(u8).init()` resolved. + // A TitleCase callee is a type constructor by Zig's naming convention — the + // same heuristic as `isZigTypeConstructorCall`. + isTypeApplicationCall: isZigTypeConstructorCallee, + // The whole workspace, not just the root package. A Zig module's import table // is declared by the `build.zig` of the package the file belongs to, so a repo // laying its packages out as `packages//build.zig` has as many import diff --git a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts index 3925355558..38c664d1ef 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts @@ -1187,6 +1187,29 @@ export interface ScopeResolver { readonly selector?: string; }; + /** + * Optional: does a CALL written as a receiver apply a type constructor — + * yield a TYPE — rather than invoke a function? `callee` is the call's + * function expression as written (`Stack`, `util.List`). + * + * A language that spells a generic type as a call (`Stack(u8).init()` + * calls `init` on the type `Stack(u8)`) has no return-type binding for the + * callee — it returns `type` — and no construction syntax, so the inline + * receiver typed nothing even though the bound form (`var t = + * Stack(u8).init()`, whose binding drops the type arguments) resolved. When + * this answers true, the compound resolver types the receiver as the class + * the callee names through a lexical or import binding, including a + * namespace-qualified callee. A unique workspace name is insufficient. The + * callee's return-type binding is consulted first and still wins. + * + * A predicate rather than a flag so the language decides WHICH calls are + * type applications, for example by its naming convention for types. + * + * Only affects receiver TYPING, like `constructionSyntax`. + * Default: undefined (no call is a type application). + */ + readonly isTypeApplicationCall?: (callee: string) => boolean; + /** * Optional per-slot conversion-rank function for overload resolution. * When provided, `narrowOverloadCandidates` uses ranked scoring as a diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts index 4bc6465a6d..e945b73d4b 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts @@ -137,6 +137,9 @@ interface ResolveCompoundReceiverOptions { * rather than re-declared, so a future sub-field cannot be added there * and silently ignored here (#2708). */ readonly constructionSyntax?: ScopeResolver['constructionSyntax']; + /** `ScopeResolver.isTypeApplicationCall`: a call whose callee names a type + * constructor yields that TYPE, typed like a bare construction. */ + readonly isTypeApplicationCall?: ScopeResolver['isTypeApplicationCall']; /** Verified namespace handles visible in the current file. */ readonly namespaceTargets?: ReadonlyMap; /** A namespace member may be a name the target module imported and @@ -224,10 +227,14 @@ function escapeForRegExp(literal: string): string { * `isConstructionSelectorHop` (the `Class.new` spelling), this is where the * rule "constructing a class yields an instance of it" lives; the * per-language surface syntax arrives via `constructionSyntax` (#2708). + * A type application (`Stack(u8)`, `isTypeApplicationCall`) names + * its class the same way a bare construction does: the expression is the + * TYPE rather than an instance, which receiver typing does not distinguish. * - * Returns undefined when the language declares no construction syntax, - * when the callee names no class-like symbol reachable from `inScope`, - * or when the keyword is required but absent — never a guess. + * Returns undefined when the language declares no construction syntax and + * the call is no type application, when the callee names no class-like + * symbol reachable from `inScope`, or when the keyword is required but + * absent — never a guess. */ function resolveConstructionExpressionClass( fnExpr: string, @@ -237,7 +244,8 @@ function resolveConstructionExpressionClass( options: ResolveCompoundReceiverOptions, ): SymbolDefinition | undefined { const syntax = options.constructionSyntax; - if (syntax === undefined) return undefined; + const typeApplication = options.isTypeApplicationCall?.(fnExpr) === true; + if (syntax === undefined && !typeApplication) return undefined; let calleeName: string | undefined; // The keyword is separated from the type by whatever trivia the source @@ -246,12 +254,12 @@ function resolveConstructionExpressionClass( // rather than by exactly one space (#2708). `newService()` keeps failing // the match, which is the point: it is an ordinary call. const keywordMatch = - syntax.keyword === undefined + syntax?.keyword === undefined ? null : new RegExp(`^${escapeForRegExp(syntax.keyword)}\\s+`).exec(fnExpr); if (keywordMatch !== null) { calleeName = fnExpr.slice(keywordMatch[0].length).trim(); - } else if (syntax.bare === true) { + } else if (syntax?.bare === true || typeApplication) { calleeName = fnExpr; } // A `new`-keyword language reaching here without the keyword is an @@ -304,6 +312,7 @@ function resolveConstructionExpressionClass( onNameFallback: options.onNameFallback, position: options.lookupPosition, purpose: 'value', + uniqueQualifiedNameFallback: typeApplication ? false : undefined, }); if (direct !== undefined && isClassLike(direct.type)) return direct; @@ -312,6 +321,7 @@ function resolveConstructionExpressionClass( onNameFallback: options.onNameFallback, position: options.lookupPosition, purpose: 'value', + uniqueQualifiedNameFallback: typeApplication ? false : undefined, }); if (viaBaseName !== undefined && isClassLike(viaBaseName.type)) return viaBaseName; } @@ -319,7 +329,8 @@ function resolveConstructionExpressionClass( // Qualified callee — `new ns.Service()` / `new Outer.Inner()`. Prefer an // unambiguous qualified-name match, then fall back to the trailing simple // name the way receiver resolution does elsewhere (#2708). - if (lastDot === -1) return undefined; + // Type-application syntax alone cannot justify a workspace-name guess. + if (lastDot === -1 || typeApplication) return undefined; const root = baseName.slice(0, baseName.indexOf('.')); const claim = lookupNameClaim(inScope, root, scopes, { position: options.lookupPosition, @@ -1102,7 +1113,9 @@ export function resolveCompoundReceiverClass( // The constructed value IS the receiver, so there is no binding to // read a type off; the return-type path above cannot help either, // because a class has no return-type binding. Type it from the - // class the callee names (#2708). + // class the callee names (#2708). A type application (`Stack(u8) + // .init()`) reaches here too: its callee returns `type`, which binds + // nothing. return resolveConstructionExpressionClass(fnExpr, inScope, scopes, index, options); } diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts index 79d43545b9..d44910f414 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts @@ -189,6 +189,7 @@ type ReceiverBoundProviderSubset = Pick< | 'hoistTypeBindingsToModule' | 'stripReceiverCastExpressions' | 'constructionSyntax' + | 'isTypeApplicationCall' | 'stripTypePreservingDecoration' | 'qualifiedTypeLookupSpelling' | 'resolveQualifiedReceiverMember' @@ -645,6 +646,7 @@ export function emitReceiverBoundCalls( hoistTypeBindingsToModule, stripReceiverCastExpressions: provider.stripReceiverCastExpressions === true, constructionSyntax: provider.constructionSyntax, + isTypeApplicationCall: provider.isTypeApplicationCall, stripTypePreservingDecoration: provider.stripTypePreservingDecoration, qualifiedTypeLookupSpelling: provider.qualifiedTypeLookupSpelling, resolveThisViaEnclosingClass: provider.resolveThisViaEnclosingClass, diff --git a/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig b/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig index 007132c1ea..f55bc8106a 100644 --- a/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig +++ b/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig @@ -68,6 +68,15 @@ fn b11(orig: *Local) void { var cur = orig; cur.go(); } +// b12 — a FORWARDING type constructor imported by name. `generic.Bridge(T)` +// is `return Builder(T);`, so `Bridge(Local)` is `Builder(Local)` — a type +// only generic.zig can name. +const Bridge = generic.Bridge; +fn b12() void { + const bound = Bridge(Local); + bound.accessor("bound"); + Bridge(Local).prototypeChain(); +} // b9 — Lightpanda's `JsApi` shape: a container-level alias of a forwarding // type constructor, used by every member declaration of the container. diff --git a/gitnexus/test/integration/resolvers/zig.test.ts b/gitnexus/test/integration/resolvers/zig.test.ts index 84f6027aff..4f796b7316 100644 --- a/gitnexus/test/integration/resolvers/zig.test.ts +++ b/gitnexus/test/integration/resolvers/zig.test.ts @@ -3,16 +3,21 @@ */ import { describe, it, expect, beforeAll } from 'vitest'; import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; import { edgeSet, FIXTURES, getNodesByLabel, getNodesByLabelFull, getRelationships, + getResolutionOutcomes, runPipelineFromRepo, + writeFixtureRepo, type PipelineResult, } from './helpers.js'; import { SupportedLanguages } from '../../../src/config/supported-languages.js'; +import type { ResolutionOutcome } from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js'; import { describeGrammarPresence, optionalGrammarGate } from '../../helpers/optional-grammar.js'; // Vendored `tree-sitter-zig`: on a platform without a prebuild the grammar @@ -25,6 +30,48 @@ const zigAvailable = zig.available; describeGrammarPresence(zig); +/** The CALLS / ACCESSES / USES edges the reference site at `file:line:col` + * produced, as ` -> | `. A site edge's + * id ends with the site's `::` (see `tryEmitEdge`). */ +function edgesAtSite(result: PipelineResult, file: string, line: number, col: number): string[] { + return ['CALLS', 'ACCESSES', 'USES'] + .flatMap((type) => getRelationships(result, type)) + .filter((e) => e.sourceFilePath === file && e.rel.id.endsWith(`:${line}:${col}`)) + .map((e) => `${e.rel.type} ${e.rel.sourceId} -> ${e.rel.targetId} | ${e.rel.reason}`) + .sort(); +} + +/** Every CALLS / ACCESSES / USES edge into `targetId`, as + * ` | `. */ +function referencesInto(result: PipelineResult, targetId: string): string[] { + return ['CALLS', 'ACCESSES', 'USES'] + .flatMap((type) => getRelationships(result, type)) + .filter((e) => e.rel.targetId === targetId) + .map((e) => `${e.rel.type} ${e.rel.sourceId} | ${e.rel.reason}`) + .sort(); +} + +/** The `receiver-unresolved` drops recorded at `file:line:col`, as + * ` ` — the rows of the #3498 drop triage. */ +function receiverDropsAt( + result: PipelineResult, + file: string, + line: number, + col: number, +): string[] { + return getResolutionOutcomes(result) + .filter( + (o): o is Extract => + o.kind === 'suppressed' && + o.reason === 'receiver-unresolved' && + o.filePath === file && + o.range.startLine === line && + o.range.startCol === col, + ) + .map((o) => `${o.siteKind} ${o.name}`) + .sort(); +} + describe.skipIf(!zigAvailable)('Zig basic resolution', () => { let result: PipelineResult; @@ -675,6 +722,59 @@ describe.skipIf(!zigAvailable)('Zig idioms (zig-idioms fixture)', () => { expect(calls).toContain('viaAlias → get'); expect(calls).toContain('viaAlias → twice'); }); + + // #3498 drop triage, F-A: `const X = @import("f.zig").X;` reads `X` off the + // module it names. The `@import(…)` receiver had no namespace binding (the + // named-import rule claims the builtin), so every such read was recorded as + // a receiver drop, and a renaming alias (`const Gauge = ….DEFAULT_NS;`) + // emitted nothing at all. `Element.zig:35` is the `Gauge` shadow case above: + // `Gauge` stays an import binding, only the `.DEFAULT_NS` read resolves. + it.each([ + ['src/holder.zig', 6, 16, 'File:src/holder.zig', 'Struct:src/counter.zig:Counter'], + ['src/main.zig', 6, 14, 'File:src/main.zig', 'Struct:src/counter.zig:Stack'], + [ + 'src/webapi/Element.zig', + 35, + 14, + 'Struct:src/webapi/Element.zig:Element', + 'Const:src/webapi/dom_utils.zig:DEFAULT_NS', + ], + [ + 'src/webapi/hub.zig', + 9, + 18, + 'File:src/webapi/hub.zig', + 'Function:src/webapi/dom_utils.zig:scale', + ], + [ + 'src/webapi/hub.zig', + 10, + 23, + 'File:src/webapi/hub.zig', + 'Const:src/webapi/dom_utils.zig:DEFAULT_NS', + ], + ])( + 'reads the member of a one-member `@import(…).X` alias at %s:%i:%i through the module', + (file, line, col, source, target) => { + expect(receiverDropsAt(result, file, line, col)).toEqual([]); + expect(edgesAtSite(result, file, line, col)).toEqual([ + `ACCESSES ${source} -> ${target} | import-resolved`, + ]); + }, + ); + + it('types a type-constructor call used as a receiver (`Stack(u8).init()`) as the type it instantiates (#3498 F-D)', () => { + // `Stack` is a function returning `type`, so the inline call has no + // return-type binding to read and Zig declares no construction syntax: + // the receiver typed nothing and the call was dropped, while the bound + // form (`var t = Stack(u8).init(); t.top()`) resolved. Zig's + // `isTypeApplicationCall` hook says a TitleCase callee applies a type + // constructor, so the receiver is the class `Stack` names. + expect(receiverDropsAt(result, 'src/main.zig', 42, 12)).toEqual([]); + expect(edgesAtSite(result, 'src/main.zig', 42, 12)).toEqual([ + 'CALLS Function:src/main.zig:main -> Method:src/counter.zig:Stack.init#0 | import-resolved', + ]); + }); }); /** @@ -873,6 +973,23 @@ describe.skipIf(!zigAvailable)('Zig type aliases (zig-filestruct fixture, aliase expect(calls).toContain('b11 → go'); }); + it('types through a FORWARDING type constructor, in the scope that declared it (`Bridge(T)` is `Builder(T)`, #3498 F-B)', () => { + // `fn Bridge(comptime T: type) type { return Builder(T); }` names no + // container, and a `type` return binds nothing, so `Bridge(Local)` typed a + // Function that owns no members. The forwarding binding `Bridge ↦ Builder` + // is declared in generic.zig, which is where `Builder` is visible — not in + // aliases.zig. Bound (`const bound = Bridge(Local)`) and inline + // (`Bridge(Local).prototypeChain()`) spellings both reach Builder. + const fromB12 = getRelationships(result, 'CALLS') + .filter((e) => e.source === 'b12' && e.targetLabel === 'Method') + .map((e) => e.rel.targetId) + .sort(); + expect(fromB12).toEqual([ + 'Method:src/generic.zig:Builder.accessor#1', + 'Method:src/generic.zig:Builder.prototypeChain#0', + ]); + }); + it('a value const / value call is not a type alias and gains no edge', () => { // `const helperResult = generic.Thing.make();` is a call, not an alias; // `const max = 5;` is a literal. Neither may bind a phantom type that @@ -1095,6 +1212,47 @@ describe.skipIf(!zigAvailable)('Zig function-local and anonymous containers (F8) 'Function:src/Sorter.zig:Sorter."Sorter: local state" → Method:src/Sorter.zig:Sorter.test@L41$State.kill#0', ); }); + + // #3498 drop triage, F-C: `struct { fn lessThan … }.lessThan` (the comparator + // handed to `std.sort.pdq`) and `const byteSize = struct { fn it … }.it;` + // read a fn VALUE off an anonymous container. Its receiver text was the + // container's whole body, which names nothing, so each read was a receiver + // drop — and the only edge came from the read's position, which lies inside + // the container, so the container "accessed" its own fn. The receiver is the + // identity the container is minted under, and the read is attributed to the + // scope it is evaluated in. A value, so a reference: never CALLS. + it.each([ + [ + 16, + 17, + 'Method:src/Sorter.zig:Sorter$2.it#1', + ['ACCESSES Struct:src/Sorter.zig:Sorter | read'], + ], + [ + 23, + 38, + 'Method:src/Sorter.zig:Sorter.sortBoth$1.lessThan#3', + [ + 'ACCESSES Method:src/Sorter.zig:Sorter.sortBoth#0 | read', + 'USES Method:src/Sorter.zig:Sorter.sortBoth#0 | scope-resolution: value-ref', + ], + ], + [ + 28, + 38, + 'Method:src/Sorter.zig:Sorter.sortBoth$2.lessThan#3', + [ + 'ACCESSES Method:src/Sorter.zig:Sorter.sortBoth#0 | read', + 'USES Method:src/Sorter.zig:Sorter.sortBoth#0 | scope-resolution: value-ref', + ], + ], + ])( + 'reads the fn value of an anonymous container (Sorter.zig:%i:%i) from where it is evaluated', + (line, col, target, expected) => { + expect(receiverDropsAt(result, 'src/Sorter.zig', line, col)).toEqual([]); + expect(referencesInto(result, target)).toEqual(expected); + }, + ); }); describe.skipIf(!zigAvailable)( @@ -1227,6 +1385,23 @@ describe.skipIf(!zigAvailable)('Zig hub modules (`pub const X = @import(…)` re const intoUtil = calls.filter((c) => c.endsWith('@ src/stdx/util.zig')); expect(intoUtil).toEqual(['c11_hub_reexported_fn → helper @ src/stdx/util.zig']); }); + + // #3498 drop triage, F-A: the hub's own `pub const X = @import("x.zig").X;` + // reads `X` off the module it names, through that module — not by the + // lexical accident that the alias happens to share the member's name. + it.each([ + [2, 18, 'Struct:src/stdx/thing.zig:Thing'], + [3, 29, 'Struct:src/stdx/bounded_array.zig:BoundedArrayType'], + [4, 19, 'Function:src/stdx/util.zig:helper'], + ])( + 'reads the re-exported member at src/stdx/stdx.zig:%i:%i through its module', + (line, col, target) => { + expect(receiverDropsAt(result, 'src/stdx/stdx.zig', line, col)).toEqual([]); + expect(edgesAtSite(result, 'src/stdx/stdx.zig', line, col)).toEqual([ + `ACCESSES File:src/stdx/stdx.zig -> ${target} | import-resolved`, + ]); + }, + ); }); describe.skipIf(!zigAvailable)( @@ -1331,6 +1506,13 @@ describe.skipIf(!zigAvailable)( ]), ); }); + + it('reads the member of `pub const X = @import("x.zig").X;` through its module (#3498 F-A)', () => { + expect(receiverDropsAt(result, 'src/stdx/stdx.zig', 2, 29)).toEqual([]); + expect(edgesAtSite(result, 'src/stdx/stdx.zig', 2, 29)).toEqual([ + 'ACCESSES File:src/stdx/stdx.zig -> Struct:src/stdx/bounded_array.zig:BoundedArrayType | import-resolved', + ]); + }); }, ); @@ -1623,3 +1805,92 @@ describe.skipIf(!zigAvailable)('Zig namespace factory result types (#3498)', () ).toEqual(targets); }); }); + +describe.skipIf(!zigAvailable)('Zig type-constructor receiver boundaries', () => { + let result: PipelineResult; + + beforeAll(async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-zig-type-boundaries-')); + try { + writeFixtureRepo(root, { + 'src/Math.zig': `count: u32 = 0, + +pub fn Wrapper(comptime T: type) type { + return if (@sizeOf(T) == 0) struct {} else struct { + pub fn get() void {} + }; +} +pub fn Bridge(comptime T: type) type { return Wrapper(T); } +pub fn use() void { Wrapper(u8).get(); } +pub fn use2() void { const b = Bridge(u8); b.get(); } +`, + 'src/other.zig': 'pub const Wrapper = struct { pub fn get() void {} };\n', + 'src/third.zig': 'pub const Unrelated = struct { pub fn get() void {} };\n', + 'src/lib.zig': 'pub const Counter = struct {};\npub fn work() void {}\n', + 'src/other_work.zig': 'pub fn work() void {}\n', + 'src/typed.zig': `pub fn typedImport() void { + const Counter: type = @import("lib.zig").Counter; + _ = Counter; +} +`, + 'src/other_local.zig': 'pub const Local = struct { pub fn get() void {} };\n', + 'src/namespaced.zig': `const local = @import("local.zig"); +pub fn namespacePositive() void { local.Local(u8).get(); } +`, + 'src/whitespace.zig': `pub fn entry() void { + const Counter = @import("lib.zig").Counter; + _ = Counter; + @import( "lib.zig" ).work(); +} +`, + 'src/local.zig': `pub fn Local(comptime T: type) type { + _ = T; + return struct { pub fn get() void {} }; +} +pub fn positive() void { Local(u8).get(); } +`, + }); + result = await runPipelineFromRepo(root, () => {}); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }, 120000); + + it.each(['use', 'use2'])('%s cannot borrow a class from an unimported file', (caller) => { + const externalTargets = getRelationships(result, 'CALLS') + .filter( + (edge) => + edge.source === caller && edge.target === 'get' && edge.targetFilePath !== 'src/Math.zig', + ) + .map((edge) => edge.rel.targetId); + expect(externalTargets).toEqual([]); + }); + + it('keeps the lexically bound type-application receiver', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'positive' && edge.target === 'get') + .map((edge) => edge.targetFilePath); + expect(targets).toEqual(['src/local.zig']); + }); + + it('resolves a differently spaced inline import after a member alias', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'entry' && edge.target === 'work') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/lib.zig', reason: 'import-resolved' }]); + }); + + it('reads a member through an explicitly typed import alias initializer', () => { + const targets = getRelationships(result, 'ACCESSES') + .filter((edge) => edge.source === 'typedImport' && edge.target === 'Counter') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/lib.zig', reason: 'import-resolved' }]); + }); + + it('keeps a namespace-qualified type application despite an unrelated namesake', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'namespacePositive' && edge.target === 'get') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/local.zig', reason: 'import-resolved' }]); + }); +}); diff --git a/gitnexus/test/unit/zig-extractors.test.ts b/gitnexus/test/unit/zig-extractors.test.ts index 0854f5fa7c..86c3322835 100644 --- a/gitnexus/test/unit/zig-extractors.test.ts +++ b/gitnexus/test/unit/zig-extractors.test.ts @@ -51,6 +51,7 @@ import { import { createFieldExtractor } from '../../src/core/ingestion/field-extractors/generic.js'; import { zigFieldConfig } from '../../src/core/ingestion/field-extractors/configs/zig.js'; import { zigProvider } from '../../src/core/ingestion/languages/zig.js'; +import { zigScopeResolver } from '../../src/core/ingestion/languages/zig/scope-resolver.js'; import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.js'; import { extract as extractScopes } from '../../src/core/ingestion/scope-extractor.js'; import { populateClassOwnedMembers } from '../../src/core/ingestion/scope-resolution/scope/walkers.js'; @@ -372,7 +373,9 @@ describeZig('Zig scope captures — `@import` in TYPE position is not an import const importNames = matches .filter((m) => m['@import.name'] !== undefined) .map((m) => `${m['@import.name']!.text}<-${m['@import.imported']?.text ?? '*'}`); - expect(importNames).toEqual(['z<-T']); + // `z`'s value reads `T` off `@import("n.zig")`, so that module is bound + // under its own text too (#3498 F-A); the type-position one is not. + expect(importNames).toEqual(['@import("n.zig")<-*', 'z<-T']); const variables = matches .filter((m) => m['@declaration.variable'] !== undefined) .map((m) => m['@declaration.name']!.text); @@ -831,6 +834,15 @@ test { importedName: 'Counter', targetRaw: 'net/counter.zig', }, + // The module a one-member import reads its member off, bound under the + // builtin's own text so the `.Counter` / `.Same` reads resolve through + // it (#3498 F-A) — once per distinct source per scope. + { + kind: 'namespace', + localName: '@import("counter.zig")', + importedName: 'counter', + targetRaw: 'counter.zig', + }, { kind: 'alias', localName: 'Renamed', @@ -964,6 +976,72 @@ pub fn f() !void { ]); }); + it.each([ + [ + 'a file-level re-export', + 'pub const Thing = @import("thing.zig").Thing;\n', + 'Thing', + 'thing.zig', + 'Thing', + ], + [ + 'a renaming alias', + 'const Gauge = @import("dom_utils.zig").DEFAULT_NS;\n', + 'Gauge', + 'dom_utils.zig', + 'DEFAULT_NS', + ], + [ + 'a fn-local alias', + 'fn f() void {\n const Counter = @import("counter.zig").Counter;\n _ = Counter;\n}\n', + 'Counter', + 'counter.zig', + 'Counter', + ], + ])( + 'binds the module of a one-member import (%s) under its own text, as the deep form already is', + (_shape, src, alias, file, member) => { + // `const X = @import("f.zig").X;` reads `X` off an `@import(…)` receiver. + // The named-import rule claims that builtin, so the receiver binding the + // deep form (`@import("lib.zig").B.work`) gets was never emitted and the + // read was a receiver drop (#3498 triage, F-A). The named import itself + // is unchanged; the module handle is added beside it. + const groups = emitZigScopeCaptures(src, 'x.zig'); + const handle = `@import("${file}")`; + const imports = groups + .filter((m) => m['@import.source'] !== undefined) + .map((m) => `${m['@import.name']?.text}<-${m['@import.imported']?.text ?? '*'}`); + expect(imports.sort()).toEqual([`${handle}<-*`, `${alias}<-${member}`]); + const reads = groups + .filter((m) => m['@reference.read'] !== undefined && m['@reference.name']?.text === member) + .map((m) => m['@reference.receiver']?.text); + expect(reads).toEqual([handle]); + }, + ); + + it('binds the namespace receiver of an explicitly typed member alias', () => { + const source = 'const Thing: type = @import("thing.zig").Thing;'; + const groups = emitZigScopeCaptures(source, 'main.zig'); + const handles = groups + .map(interpretZigImport) + .filter((imp) => imp?.kind === 'namespace') + .map((imp) => imp?.localName); + expect(handles).toEqual(['@import("thing.zig")']); + }); + + it('keeps both namespace handles when repeated inline imports use different whitespace', () => { + const source = `pub fn entry() void { + const Counter = @import("lib.zig").Counter; + _ = Counter; + @import( "lib.zig" ).work(); + }`; + const handles = emitZigScopeCaptures(source, 'main.zig') + .map(interpretZigImport) + .filter((imp) => imp?.kind === 'namespace') + .map((imp) => imp?.localName); + expect(handles.sort()).toEqual(['@import( "lib.zig" )', '@import("lib.zig")'].sort()); + }); + it('a function-scoped @import is not deferred: Zig imports are compile-time (importsExecuteWhereWritten: false)', () => { // C `#include` and Rust `use` answer the same. Without the flag the scope // extractor marks a body-level `@import` `runsOnlyWhenCalled`, hiding a @@ -1666,6 +1744,22 @@ const R = struct { pub fn go(self: *R) void { const q = self.current(); } }; ]); }); + it.each([ + ['Stack', true], + ['util.List', true], + ['@import("x.zig").Foo', true], + ['makeThing', false], + ['std.mem.eql', false], + ['self.items', false], + ])( + 'the resolver reads a receiver call of `%s` as a type application: %s (#3498 F-D)', + (callee, expected) => { + // The text twin of `isZigTypeConstructorCall`, for the compound + // resolver: `Stack(u8).init()` calls `init` on the TYPE `Stack(u8)`. + expect(zigScopeResolver.isTypeApplicationCall?.(callee)).toBe(expected); + }, + ); + it('emits nothing for a TitleCase callee (type constructor), a decl literal, an identifier or a field chain', () => { const src = ` fn f() void { @@ -1708,6 +1802,45 @@ pub fn make3() !List(u8) {} ]); }); + it.each([ + [ + 'a same-file constructor', + 'pub fn Bridge(comptime T: type) type {\n return Builder(T);\n}\n', + [ret('Bridge', 'Builder')], + ], + [ + 'a qualified constructor, past a comment', + 'pub fn Bridge(comptime T: type) type {\n // forwards\n return other.Builder(T);\n}\n', + [ret('Bridge', 'other.Builder')], + ], + [ + 'a body that is more than the return', + 'pub fn Bridge(comptime T: type) type {\n const U = T;\n return Builder(U);\n}\n', + [], + ], + [ + 'a value call (camelCase callee)', + 'pub fn Bridge(comptime T: type) type {\n return make(T);\n}\n', + [], + ], + [ + 'a call of a parameter', + 'pub fn Apply(comptime F: fn (type) type) type {\n return F(u8);\n}\n', + [], + ], + ['a container return', 'pub fn List(comptime T: type) type {\n return struct {};\n}\n', []], + ])( + 'binds a FORWARDING type constructor to the type it forwards to — %s', + (_shape, src, expected) => { + // `fn Bridge(comptime T: type) type { return Builder(T); }` (Lightpanda's + // `js.Bridge(T)`) names no container of its own: `type` returns bind + // nothing, so a receiver typed `Bridge(X)` reached a Function that owns + // no members (#3498 triage, F-B). `Bridge(X)` IS `Builder(X)`, so the + // return binding names the callee, declared in Bridge's own scope. + expect(bindingsOf(src)).toEqual(expected); + }, + ); + it('a file-struct’s `@This()` return names the file stem', () => { const src = ` count: u32 = 0, @@ -1906,6 +2039,34 @@ test "Page: local state" { expect(lts.every((d) => d.ownerId !== undefined)).toBe(true); }); + it('a member read off an anonymous container names it by its identity and sits at the member (#3498 F-C)', () => { + // `struct { fn lessThan … }.lessThan`: the receiver capture was the whole + // container body, which names nothing, and the site's anchor started at + // `struct` — INSIDE the container's own Class scope, so the read was + // attributed to the container itself. The receiver is the identity the + // container is minted under, and the site is anchored on the member, which + // is evaluated in the enclosing scope. + const sites = emitZigScopeCaptures(src, 'src/Page.zig') + .map((m) => ({ m, kind: ['@reference.read', '@reference.value-ref'].find((k) => k in m) })) + .filter( + ({ m, kind }) => + kind !== undefined && ['lessThan', 'it'].includes(m['@reference.name']?.text ?? ''), + ) + .map(({ m, kind }) => ({ + site: `${kind} ${m['@reference.receiver']?.text} . ${m['@reference.name']?.text}`, + atMember: + JSON.stringify(m[kind ?? '']?.range) === JSON.stringify(m['@reference.name']?.range), + })); + expect(sites.map((s) => s.site).sort()).toEqual([ + '@reference.read Page$1 . it', + '@reference.read Page.sortBoth$1 . lessThan', + '@reference.read Page.sortBoth$2 . lessThan', + '@reference.value-ref Page.sortBoth$1 . lessThan', + '@reference.value-ref Page.sortBoth$2 . lessThan', + ]); + expect(sites.every((s) => s.atMember)).toBe(true); + }); + it('a `@This()` alias inside a local container rewrites to the BINDING name (`R`), which is what the scope binds', () => { const localAliasSrc = ` pub fn string() void { From d57f570dffcc2b8e5455c691f5c2f6c655991aec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerg=C5=91=20Magyar?= Date: Thu, 22 Oct 2026 06:49:35 +0300 Subject: [PATCH 2/6] refactor(ingestion): colocate import resolution rules (#3670) * refactor(ingestion): remove dormant import resolvers Remove the unused LanguageProvider importResolver contract, factory and strategy chain. Keep active scope resolver helpers and their semantic tests. Verified 5,309 corpus edges unchanged, 7,411 focused tests, typechecks, build and resolver benchmarks. Full local suite is still running; graph analysis remains partial on deleted and comment-only regions. * refactor: colocate language import helpers Keep import policy beside language resolvers and share only generic indexes. Pass the existing ordered candidates explicitly so lookup behavior and cache identities stay unchanged. * fix: defer MCP imports and narrow Python paths * fix(python): prefer packages in relative imports * test(python): pin package-first import lookup * test(python): use a valid parent-relative import --------- Co-authored-by: Gergely Magyar Co-authored-by: Gergo Magyar --- .github/workflows/ci-tests.yml | 2 +- ARCHITECTURE.md | 20 +- gitnexus/bench/import-target/baselines.json | 2 +- gitnexus/bench/import-target/measure.mjs | 10 +- .../baseline-import-target-fingerprint.txt | 2 +- .../swift-package-imports/baselines.json | 10 +- .../bench/swift-package-imports/measure.mjs | 48 +- .../group/extractors/http-patterns/php.ts | 2 +- .../group/extractors/include-extractor.ts | 2 +- .../src/core/ingestion/asyncapi/document.ts | 2 +- .../src/core/ingestion/di-extractors/types.ts | 2 - .../import-resolvers/configs/c-cpp.ts | 18 - .../import-resolvers/configs/csharp.ts | 56 -- .../import-resolvers/configs/dart.ts | 58 -- .../ingestion/import-resolvers/configs/go.ts | 35 - .../ingestion/import-resolvers/configs/jvm.ts | 115 --- .../ingestion/import-resolvers/configs/php.ts | 26 - .../import-resolvers/configs/python.ts | 47 -- .../import-resolvers/configs/ruby.ts | 20 - .../import-resolvers/configs/rust.ts | 56 -- .../import-resolvers/configs/swift.ts | 123 ---- .../configs/typescript-javascript.ts | 28 - .../ingestion/import-resolvers/configs/zig.ts | 36 - .../src/core/ingestion/import-resolvers/go.ts | 80 --- .../core/ingestion/import-resolvers/jvm.ts | 127 ---- .../ingestion/import-resolvers/pass-cache.ts | 79 --- .../import-resolvers/resolver-factory.ts | 35 - .../core/ingestion/import-resolvers/rust.ts | 87 --- .../ingestion/import-resolvers/standard.ts | 219 ------ .../core/ingestion/import-resolvers/types.ts | 66 -- .../core/ingestion/import-target-adapter.ts | 124 ---- .../src/core/ingestion/language-config.ts | 84 +-- .../src/core/ingestion/language-provider.ts | 3 - .../src/core/ingestion/languages/c-cpp.ts | 4 - .../ingestion/languages/c/import-target.ts | 2 +- .../ingestion/languages/c/scope-resolver.ts | 5 +- .../ingestion/languages/c/static-linkage.ts | 2 +- .../src/core/ingestion/languages/cobol.ts | 1 - .../ingestion/languages/cobol/copy-target.ts | 2 +- .../languages/cpp/file-local-linkage.ts | 2 +- .../ingestion/languages/cpp/scope-resolver.ts | 6 +- .../src/core/ingestion/languages/csharp.ts | 3 - .../csharp/import-helpers.ts} | 51 +- .../languages/csharp/import-target.ts | 21 +- .../csharp/namespace-gate.ts} | 8 +- .../languages/csharp/resolution-config.ts | 2 +- gitnexus/src/core/ingestion/languages/dart.ts | 3 - .../ingestion/languages/dart/import-target.ts | 2 +- gitnexus/src/core/ingestion/languages/go.ts | 3 - .../ingestion/languages/go/import-target.ts | 6 +- .../languages/go/workspace-config.ts | 11 +- .../ingestion/languages/import-candidates.ts | 51 ++ gitnexus/src/core/ingestion/languages/java.ts | 3 - .../ingestion/languages/java/import-target.ts | 2 +- .../languages/javascript/import-target.ts | 2 +- .../languages/javascript/scope-resolver.ts | 2 +- .../src/core/ingestion/languages/kotlin.ts | 5 +- .../languages/kotlin/import-target.ts | 2 +- .../languages/kotlin/import-wildcard.ts | 14 + .../core/ingestion/languages/objective-c.ts | 4 - .../languages/objective-c/import-target.ts | 2 +- gitnexus/src/core/ingestion/languages/php.ts | 3 - .../php/import-helpers.ts} | 11 +- .../ingestion/languages/php/import-target.ts | 10 +- .../src/core/ingestion/languages/python.ts | 3 - .../python/import-file-index.ts} | 4 +- .../python/import-helpers.ts} | 13 +- .../languages/python/import-target.ts | 10 +- gitnexus/src/core/ingestion/languages/ruby.ts | 3 - .../ruby/import-helpers.ts} | 10 +- .../ingestion/languages/ruby/import-target.ts | 4 +- gitnexus/src/core/ingestion/languages/rust.ts | 3 - .../languages/rust/qualified-call.ts | 7 +- .../src/core/ingestion/languages/swift.ts | 3 - .../languages/swift/import-target.ts | 2 +- .../core/ingestion/languages/typescript.ts | 7 - .../languages/typescript/file-candidates.ts | 2 +- .../languages/typescript/import-target.ts | 2 +- .../languages/typescript/module-resolution.ts | 6 +- .../languages/typescript/scope-resolver.ts | 5 +- .../typescript/workspace-packages.ts} | 8 +- gitnexus/src/core/ingestion/languages/vue.ts | 3 - .../ingestion/languages/vue/import-target.ts | 2 +- .../ingestion/languages/vue/scope-resolver.ts | 2 +- gitnexus/src/core/ingestion/languages/zig.ts | 5 +- .../zig/import-helpers.ts} | 2 +- .../ingestion/languages/zig/scope-resolver.ts | 2 +- .../languages/zig/workspace-static-gating.ts | 2 +- .../route-extractors/js-const-resolver.ts | 2 +- .../route-extractors/spring-shared.ts | 2 +- .../package-dir-index.ts | 28 +- .../per-file-set.ts | 6 +- .../utils.ts => utils/suffix-index.ts} | 81 +-- .../workspace-file-index.ts | 7 +- gitnexus/src/core/run-analyze.ts | 2 +- gitnexus/src/mcp/local/local-backend.ts | 20 +- .../csharp-import-index-reuse.test.ts | 2 +- .../php-import-index-reuse.test.ts | 2 +- .../python-import-index-reuse.test.ts | 2 +- .../typescript-esm-js-extension.test.ts | 2 +- .../ruby-import-index-reuse.test.ts | 2 +- ...analyze-invalidates-workspace-memo.test.ts | 4 +- .../test/unit/dart-import-resolver.test.ts | 148 ---- .../unit/esm-extension-resolution.test.ts | 226 ------ .../test/unit/import-path-candidates.test.ts | 23 + .../test/unit/import-resolver-factory.test.ts | 655 ------------------ .../csharp-csproj-parity.test.ts | 37 +- .../go-package-resolve.test.ts | 171 ----- .../python-importer-prefixes.test.ts | 94 +-- .../suffix-index-lazy-dir-map.test.ts | 9 +- .../node-workspace-memo-rejection.test.ts | 2 +- .../unit/node-workspace-nested-roots.test.ts | 2 +- .../test/unit/node-workspace-packages.test.ts | 2 +- .../node-workspace-repo-root-race.test.ts | 2 +- .../unit/node-workspace-review-fixes.test.ts | 2 +- .../node-workspace-scan-determinism.test.ts | 2 +- .../test/unit/node-workspace-scope.test.ts | 2 +- ...node-workspace-vite-entry-comments.test.ts | 2 +- .../node-workspace-vite-structure.test.ts | 2 +- .../test/unit/python-relative-imports.test.ts | 52 ++ .../csharp/csharp-imports.test.ts | 2 +- .../external-import-conformance.test.ts | 4 +- .../import-target-adapter.test.ts | 152 ---- .../import-target-index-parity.test.ts | 6 +- ...import-target-index-reuse.contract.test.ts | 5 +- .../php-import-target-parity.test.ts | 6 +- .../python/python-import-probe-count.test.ts | 2 +- .../python/python-importer-ancestors.test.ts | 2 +- .../typescript/typescript-imports.test.ts | 2 +- .../test/unit/suffix-index-ambiguity.test.ts | 84 +-- .../test/unit/zig-import-resolver.test.ts | 2 +- 131 files changed, 342 insertions(+), 3499 deletions(-) delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/go.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/php.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/python.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/go.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/jvm.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/rust.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/standard.ts delete mode 100644 gitnexus/src/core/ingestion/import-resolvers/types.ts delete mode 100644 gitnexus/src/core/ingestion/import-target-adapter.ts rename gitnexus/src/core/ingestion/{import-resolvers/csharp.ts => languages/csharp/import-helpers.ts} (93%) rename gitnexus/src/core/ingestion/{csharp-namespace-gate.ts => languages/csharp/namespace-gate.ts} (93%) create mode 100644 gitnexus/src/core/ingestion/languages/import-candidates.ts create mode 100644 gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts rename gitnexus/src/core/ingestion/{import-resolvers/php.ts => languages/php/import-helpers.ts} (95%) rename gitnexus/src/core/ingestion/{import-resolvers/python-file-index.ts => languages/python/import-file-index.ts} (99%) rename gitnexus/src/core/ingestion/{import-resolvers/python.ts => languages/python/import-helpers.ts} (93%) rename gitnexus/src/core/ingestion/{import-resolvers/ruby.ts => languages/ruby/import-helpers.ts} (71%) rename gitnexus/src/core/ingestion/{import-resolvers/node-workspace-packages.ts => languages/typescript/workspace-packages.ts} (99%) rename gitnexus/src/core/ingestion/{import-resolvers/zig.ts => languages/zig/import-helpers.ts} (99%) rename gitnexus/src/core/ingestion/{import-resolvers => utils}/package-dir-index.ts (87%) rename gitnexus/src/core/ingestion/{import-resolvers => utils}/per-file-set.ts (94%) rename gitnexus/src/core/ingestion/{import-resolvers/utils.ts => utils/suffix-index.ts} (89%) rename gitnexus/src/core/ingestion/{import-resolvers => utils}/workspace-file-index.ts (96%) delete mode 100644 gitnexus/test/unit/esm-extension-resolution.test.ts create mode 100644 gitnexus/test/unit/import-path-candidates.test.ts delete mode 100644 gitnexus/test/unit/import-resolver-factory.test.ts delete mode 100644 gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts create mode 100644 gitnexus/test/unit/python-relative-imports.test.ts delete mode 100644 gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 83fbe37349..96146dbb40 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -833,7 +833,7 @@ jobs: if: ${{ !cancelled() }} # Build-free: same baseline approach as parse-dispatch-rounds — # exact declared/SDK/undeclared floors plus a fingerprint, then - # ratio timing only (resolveSwiftImportTarget, swiftPackageStrategy, + # ratio timing only (resolveSwiftImportTarget, # parseSwiftPackageManifest 4n/n). Pins declaration-only resolve, # https:// factory survival, and #2931 segment-boundary membership. # See bench/swift-package-imports/measure.mjs. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 56c8062136..bed040e683 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,7 +69,7 @@ Group-mode `trace` (`gitnexus/src/core/group/cross-trace.ts`) stitches a path th | Embeddings | `src/core/embeddings/` + `src/core/run-analyze.ts` | | Wiki generation | `src/core/wiki/` | | Language support | `src/core/ingestion/languages/` + `tree-sitter-queries.ts` + `gitnexus-shared/src/languages.ts` | -| Import resolution | `src/core/ingestion/import-processor.ts` + `import-resolvers/configs/` + `model/resolution-context.ts` | +| Import resolution | `src/core/ingestion/scope-resolution/pipeline/run.ts` + per-language `ScopeResolver.resolveImportTarget` hooks | | Call resolution/inheritance/MRO | `src/core/ingestion/scope-resolution/` (pipeline, passes, graph-bridge) | | Type extraction | `src/core/ingestion/type-extractors/` | | Worker pool | `src/core/ingestion/workers/` | @@ -455,7 +455,6 @@ Each language implements `LanguageProvider` (`language-provider.ts`). Key fields | `id`, `extensions` | Language identity and file matching | | `treeSitterQueries` | S-expression queries for AST extraction | | `importSemantics` | `named` / `wildcard-leaf` / `wildcard-transitive` / `namespace` | -| `importResolver` | Language-specific path → file resolution | | `exportChecker` | Public/exported symbol detection | | `typeConfig` | Type annotation extraction rules | | `mroStrategy` | `first-wins` / `c3` / `none` | @@ -470,22 +469,9 @@ Per-language tree-sitter queries use different AST node names but produce the ** ### Import resolution -Per-language import resolution uses the **configs + factory** pattern (like call/method/class extractors). Each language declares an `ImportResolutionConfig` in `import-resolvers/configs/`, listing an ordered chain of `ImportResolverStrategy` functions. `createImportResolver()` (in `resolver-factory.ts`) composes them: first non-null result wins. Low-level helpers shared across strategies live alongside the configs in `import-resolvers/` (e.g. `go.ts`, `rust.ts`, `python.ts`). +Per-language import resolution runs through `ScopeResolver.resolveImportTarget`, registered in `SCOPE_RESOLVERS`. The shared orchestrator (`scope-resolution/pipeline/run.ts`) passes each language's workspace configuration to the resolver hook. The hook maps a parsed import to its target file or files; finalization links imports and materializes bindings for scope lookup. -Unified 3-tier algorithm (`model/resolution-context.ts`), per-language `importSemantics` controls which tier activates: - -| Tier | Confidence | Mechanism | -| ----------------- | ---------- | ---------------------------------------------------------------------- | -| 1 — same-file | 0.95 | Symbol table for caller's file | -| 2 — import-scoped | 0.9 | `NamedImportMap` chains (named) or all files in `importMap` (wildcard) | -| 3 — global | 0.5 | O(1) index lookups: class, impl, callable. Fallback only | - -| Import strategy | Languages | Behavior | -| --------------------- | ----------------------------------- | ---------------------------------------------- | -| `named` | TS, JS, Java, C#, Rust, PHP, Kotlin | Only explicitly imported names visible | -| `wildcard-leaf` | Go, Ruby, Swift, Dart | Whole-package import, no transitive re-exports | -| `wildcard-transitive` | C, C++ | `#include` closure chains through re-exports | -| `namespace` | Python | Module aliases resolved at call site | +Language-specific import helpers and namespace rules live beside each resolver in `languages//`. Language-neutral package-directory and suffix indexes, workspace indexes, and per-file-set caches live in `ingestion/utils/`; suffix lookups receive their ordered extension candidates from callers. The dormant `LanguageProvider.importResolver` field, adapter, and strategy factory have been removed; new languages implement the `ScopeResolver` hook. ### Chunked parse-and-resolve diff --git a/gitnexus/bench/import-target/baselines.json b/gitnexus/bench/import-target/baselines.json index b032f8f428..ab34328ac0 100644 --- a/gitnexus/bench/import-target/baselines.json +++ b/gitnexus/bench/import-target/baselines.json @@ -7,7 +7,7 @@ "_php_composer_gate_2962": "The canonical PHP arm supplies an authoritative App PSR-4 mapping. A deterministic Vendor0 suffix decoy makes deletion of the external gate change every timing fingerprint, while the heap arm separately pins a mapped miss, the rendered mapping, and the external null result. Three serial samples measured depth ratios 1.058, 1.114, and 1.158; the 1.8 budget is 1.55x the observed maximum. The mapped-miss heap reading peaked at 39607216 retained bytes at 32000 files.", "_fingerprint_note": "Per-language sha256 over every distinct fromFile|target -> resolved target. A change here is a BEHAVIOUR change: the resolver returned a different target set, and IMPORTS/CALLS edges moved. Explain it, never re-baseline to make CI green. For the languages these PRs changed, the pre-change implementations produce these same values on this corpus at both 400 and 1600 files \u2014 that is what makes the index hoist a performance change. The tie-break-level proof lives in test/unit/scope-resolution/import-target-index-parity.test.ts (verbatim copies of the pre-change code, diffed) for Kotlin's current declared-package behavior in test/unit/kotlin-module-resolution.test.ts, and for the four resolvers added there in test/unit/scope-resolution/{php,java,cobol}-import-target-parity.test.ts and test/unit/import-resolvers/csharp-csproj-parity.test.ts, and for JavaScript in test/unit/scope-resolution/javascript-import-target-parity.test.ts (a differential over 211200 old-vs-new pairs, PR #2911). The eight languages added last have no per-language parity harness against a pre-change implementation and do NOT need one: nothing about their resolution changed, so there is no before to diff against. Their fingerprints are pure forward guards, minted from the current implementations, and their adapter-boundary index reuse is covered for every registered language at once by test/unit/scope-resolution/import-target-index-reuse.contract.test.ts. NOTE for csharp_csproj: on this corpus the #2902 indexed leg (step 3 of resolveCSharpImportInternal) is reached by 2221 of the 3200 small-arm imports but answers null for every one of them \u2014 the 979 that resolve do so at step 2 \u2014 so this fingerprint pins that legs cost and its null answers, while its positive tie-breaks (unanchored substring, iteration order) are pinned by csharp-csproj-parity.test.ts. NOTE for kotlin, go, csharp and java: twenty fingerprints across these four languages were re-baselined in #2881, the one deliberate behaviour change any language in this file has had. It landed in two steps and the second is the reason the first is not a special case: Kotlin first, then the shared package-dir-index (go, java, csharp) and the csproj namespace index once the same rule was found live there. `getKotlinFileIndex` no longer requires a file's package directory to be the FIRST occurrence of that name in its own path, so the unique arm's `d % 7` nested slice (`mod{d}/src/main/kotlin/com/example/pkg{d}/inner/pkg{d}`) now belongs to package `pkg{d}` and its wildcard imports resolve: resolved 1100 -> 1153 small and deep, 4456 -> 4681 large. The collide arm needed a CORPUS edit alongside it, not just a new number \u2014 its `d % 7` slice deliberately imported `com.example.vendor{d}`, a package that exists nowhere, purely to mirror the unique arm's nested-slice MISS, so leaving it would have left collide at 1100 against small's 1153 and broken the same-workload invariant the arm is built on (that assertion is what caught it). It now uses the same `com.example.models.*` spelling as the rest of the arm, which is why its distinct_outcomes fell (2775 -> 2744, 11087 -> 10961): one shared target instead of one per d. The record-level evidence for the resolver change \u2014 235 of 19968 records moved, 54 null -> resolved, 0 buckets losing a member \u2014 is in bench/kotlin-import-target/baselines.json `_provenance`. The kotlin heap_reading_bytes and heap_ceiling_bytes moved with it, together as `_heap_reading_note` requires: 48073096 -> 48200224 bytes_large (+127128, +0.264%), ceiling still exactly 1.5x. Small, and it is worth saying WHY it is small rather than reading the number as evidence that the change is cheap. `dirChildren` grows by one entry per component-suffix the old rule used to skip, and this arm can only see part of that: the heap corpus is built with HEAP_PAD 8, which prefixes every path with `d0/\u2026/d7/`, so no path can begin with a suffix of its own directory and the leading-segment half of the old rule is structurally invisible here. What moves the reading is the `d % 7` nested slice alone. Read +0.264% as this arm's ceiling on the effect, not as the effect. GO NEEDED A CORPUS EDIT TO BE GATED AT ALL. Its nested slice was `src/pkg{d}/internal/pkg{d}`, repeating only the LAST segment, while a Go query addresses the whole package path `src/pkg{d}` \u2014 so the directory never even ended with the query and the first-occurrence rule was never reached. Every go arm sat unchanged through the resolver fix. `uniqueDir`/`collideDir` now repeat the shape at the granularity Go actually queries (`src/pkg{d}/internal/src/pkg{d}`, `svc{d}/internal/sub/svc{d}/internal`), which is what moved go from 979 to 1153 resolved and bumped `languages.go.heap.path_segments` 13 -> 14. The general lesson: a corpus that carries a shape the QUERY cannot express does not gate that shape. CSHARP AND JAVA HIT THE SAME COLLIDE-ARM TRAP AS KOTLIN. Both collide arms sent their `d % 7` slice to a namespace that exists nowhere (`App.Src{d}.Vendor`, `com.svc{d}.vendor`) purely to MIRROR the unique arm's nested-slice miss; once that miss became a hit, collide sat at 979/1100 against small's 1153 and the same-workload assertion failed. Both now use the same spelling as the rest of their arm. HEAP: no reading here moved for the resolver change. An earlier revision of this branch re-recorded `csharp_csproj` 73703384 -> 73116520 as a -0.79% effect of the step-2 filter; review measured base and branch three times each and got the same 73.10e6 on BOTH sides \u2014 the recorded 73703384 was simply not reproducible on this box, and re-recording it would have dropped that language's derived floor by 0.8% for no reason belonging to this change. Reverted. Everything else sat within +/-0.03%. Note that `_heap_reading_note`'s claim that these readings 'reproduce to the byte across processes on one box' did NOT hold on the box this was measured on: go, dart, ruby, python, php and cpp all wandered by a few hundred to a few thousand bytes between processes with no code change touching them. Treat sub-0.05% movement as jitter, not signal. HEAP, kotlin, second movement: 48200224 -> 42802456 (-11.20%), re-recorded with its ceiling. `getKotlinFileIndex` now compacts each `dirChildren` bucket as it freezes it. `addChild` mints a bucket as `[raw]` and pushes the rest, and V8 grows a backing store by `old + old/2 + 16`, so the second child takes a 1-slot store to 17: 61144 buckets, 52.9% of their slots empty, 88 B each. Same fix and same accounting as the python `byBasename` sentence above. Note what this means for the gate: a memory WIN of this size passes every arm \u2014 it is under the ceiling and over the 0.5x floor \u2014 so it is recorded because the convention says a reading and its ceiling move together, not because anything went red. kotlin now reads 40.82 MiB. The prose in measure.mjs calling it '45.85 MiB, the second-largest reading in this file' is corrected with it \u2014 and was already wrong on the ranking before this change, since csharp_csproj (69.73) and php (47.28) both read higher; kotlin was third. A measurement written into prose is not re-taken, which is the finding `_heap_bound_note` records about this very file. One further corpus edit, made in review and MEASURED rather than assumed: kotlin's collide layout repeated only the `models` leaf (`\u2026/com/example/models/inner/models`) while a Kotlin query addresses the whole dotted path, so a full revert of the Kotlin guards left both collide fingerprints UNMOVED \u2014 the arm was blind to the rule it was re-baselined for. Deepening it to `\u2026/models/inner/com/example/models` makes the revert move both, and those two fingerprints are the only ones that changed for it. The same deepening was applied to the java and kotlin UNIQUE arms and REVERTED: it moved ten more fingerprints, grew java's heap reading 43%, and bought nothing \u2014 progressive stripping lands those queries on the same file with or without the rule, so the control still failed only on go.", "_shape_note": "files/imports/resolved/distinct_outcomes AND the fingerprint are asserted exactly, per scale. A fingerprint alone cannot tell a legitimate resolution change from a corpus quietly shrunk below the size at which the timing arms can see anything; conversely the counts alone cannot see a defect confined to one arm, because the arms differ only in path padding and directory layout and both of those are count-neutral by design. Two cross-arm assertions close the remaining hole: the deep and collide arms must resolve exactly what small resolves (they are the same workload), and each of their fingerprints must DIFFER from small's (they are not the same corpus). Without the second, setting DEEP_PAD to 0 \u2014 which deletes the entire depth arm \u2014 moves no asserted number and prints PASS; the same is true of a collideDir that forwards to uniqueDir. THE HEAP ARM IS ASSERTED THE SAME WAY, by the same loop, and was not before: files_small, files_large, path_segments and probe decide WHAT it measures, and every one of them was reported and compared to nothing. Swapping HEAP_PROBE_TARGET.csharp_csproj for a target matching no CSPROJ_CONFIGS rootNamespace skips the whole config loop, so the getFilesInDir and getInsensitive legs never run and the arm the header calls the witness that the read pattern IS the footprint quietly becomes a two-map arm \u2014 73703384 -> 59921216 B, ratio 1.017 -> 1.011, ceiling and floor both still passing and --check still exiting 0. Setting HEAP_SMALL equal to HEAP_LARGE is the same hole from the other side: ratio goes to ~1.0 by construction and bytes_large never moves. bytes_small and bytes_large are deliberately NOT asserted for equality \u2014 heap_ceiling_bytes and the heap_reading_bytes floor bound them with ~50% either way, because heapUsed accounting moves across platforms and Node majors and an exact byte assertion would be a re-baseline per runner. THE CONTEXT ARM IS ASSERTED THE SAME WAY, by the same loop, and more strictly than either: target, with_context and without_context are exact strings with no tolerance at all, because the arm resolves one import over a three-file corpus and has no measurement noise to tolerate. A separate check requires the last two to DIFFER, for the same reason deep.fingerprint must differ from small.fingerprint \u2014 a probe on which both call shapes agree asserts one number twice. Both halves run through resolveOne, so what the arm gates is this bench threading run.ts's fifth argument, not the resolvers' behaviour.", - "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT \u2014 the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) emits one entry per component, while Kotlin's declared-package index is depth-free while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x \u2014 and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION \u2014 this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number \u2014 measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 \u2014 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 \u2014 no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all \u2014 harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it \u2014 same corpus, same getWorkspaceFileIndex, three maps instead of one \u2014 it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release \u2014 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths \u2014 37% of what this arm used to read was empty array slots \u2014 the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE \u2014 do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% \u2014 identical to the byte \u2014 on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way \u2014 true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs \u2014 tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost \u2014 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in import-resolvers/python.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` \u2014 the package probe's recursion re-ran the whole tail on identical inputs \u2014 and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 \u2014 its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 \u2014 python 1.097, javascript 1.083, typescript 1.053, vue 1.079 \u2014 and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) \u2014 the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 \u2014 a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter \u2014 if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK \u2014 ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s \u2014 see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another \u2014 i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) \u2014 its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms \u2014 which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL \u2014 the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP now runs its sole timing, depth, collision and heap workloads with Composer's PSR-4 config. The canonical recording is small_ms 12.515, collide_ms 13.684, scaling_ratio 1.077, collide_scaling_ratio 0.994, depth_ratio 1.536 and 13407592 retained bytes. Its ceilings are 55/60 ms, 2.4 depth and 20200000 bytes, preserving normal cross-run headroom without splitting PHP into benchmark identities. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later \u2014 which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch \u2014 the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x \u2014 far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 \u2014 both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles \u2014 see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", + "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT \u2014 the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) emits one entry per component, while Kotlin's declared-package index is depth-free while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x \u2014 and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION \u2014 this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number \u2014 measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 \u2014 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 \u2014 no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all \u2014 harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it \u2014 same corpus, same getWorkspaceFileIndex, three maps instead of one \u2014 it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release \u2014 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths \u2014 37% of what this arm used to read was empty array slots \u2014 the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE \u2014 do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% \u2014 identical to the byte \u2014 on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way \u2014 true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs \u2014 tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost \u2014 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in languages/python/import-helpers.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` \u2014 the package probe's recursion re-ran the whole tail on identical inputs \u2014 and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 \u2014 its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 \u2014 python 1.097, javascript 1.083, typescript 1.053, vue 1.079 \u2014 and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) \u2014 the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 \u2014 a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter \u2014 if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK \u2014 ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s \u2014 see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another \u2014 i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) \u2014 its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms \u2014 which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL \u2014 the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP now runs its sole timing, depth, collision and heap workloads with Composer's PSR-4 config. The canonical recording is small_ms 12.515, collide_ms 13.684, scaling_ratio 1.077, collide_scaling_ratio 0.994, depth_ratio 1.536 and 13407592 retained bytes. Its ceilings are 55/60 ms, 2.4 depth and 20200000 bytes, preserving normal cross-run headroom without splitting PHP into benchmark identities. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later \u2014 which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch \u2014 the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x \u2014 far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 \u2014 both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles \u2014 see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", "_triage": "Every ratio and ms ceiling here is a TIMING signal \u2014 re-run on an idle machine before investigating; runner contention dominates. depth_ratio is the noisiest of them by a wide margin (it divides two sub-3 ms numbers, and Dart's are sub-1 ms): if exactly one arm fails and it is that one, suspect the machine first. N is 15 for every language whose cheapest arm is under 5 ms, rather than this bench's original 5, specifically to hold that arm's peak-to-peak swing under 1.26x \u2014 see _arms_note for the measured distributions and for why the six languages that drop to 7-8 are the ones where cell size makes it safe \u2014 so a depth_ratio failure that REPRODUCES is a real signal, not noise. Each language's chosen N is printed as `reps`; read it before blaming the estimator. The fingerprint, shape and heap arms are the opposite: deterministic (over 4 runs the heap arm's widest spread was 0.11% on python and 0.00% on java, javascript and c), a re-run never changes them, and they must never be wished away. TWO heap failures mean the arm STOPPED MEASURING rather than that memory grew, and both are deterministic: a heap floor failure says the probe no longer forces the index it used to (this is how four arms read 0 B when buildSuffixIndex went lazy, and 0 B passes every ceiling), and a `heap probe ... resolved` throw says a probe target that must MISS now hits, so the reading is a materialized answer and the legs past it were never reached. A heap BOUND failure is deterministic in the same way and means one specific thing: a language excluded from the budgeted tier has grown a structure, or started asking its index a question it did not ask when the exclusion was recorded \u2014 never a timing signal, never a re-run, and never fixed by raising the bound without saying what grew. The context arm is deterministic too, and a failure there means one specific thing rather than a range of them: run.ts's fifth argument is not reaching that resolver from this bench, or the leg behind it stopped running. Never a timing signal, never a re-run. TIGHTENED IN #2881, because the measurements they bound got faster and a budget left alone while its reading falls is a gate loosening without anyone deciding to. Each new value holds the headroom the old one expressed over the old reading, computed from `_measured` on both sides: kotlin depth 3.4 -> 2.8 (reading 2.219 -> 1.813), go depth 1.6 -> 1.4 (1.169 -> 0.999), csharp depth 2.2 -> 2.0 (1.438 -> 1.279), java depth 2.2 -> 2.1 (1.402 -> 1.354), kotlin collide_scaling 1.8 -> 1.65 (1.179 -> 1.081), go collide_scaling 5.5 -> 5.1 (3.763 -> 3.465). The ABSOLUTE ms ceilings were deliberately NOT tightened by the same reasoning: they carry runner-contention headroom rather than measurement headroom, and a ratio is runner-speed-invariant where a millisecond is not.", "_floor": "Measured against the pre-change implementations on THIS corpus at 150/600 files: go 3.36, csharp 4.10, dart 3.32, ruby 3.87. The issues report 4.00 / 3.43 / 4.05 on their own corpora; those are DIFFERENT numbers from different repositories and are not reproduced here \u2014 what they and these share is that both independently land in the quadratic band, well clear of the ~1.0 a linear result gives. Note also that this floor was taken at 150/600 while the gate runs at 400/1600, so it is a lower bound on what the pre-change code would score today. Kotlin's own bench measured its pre-index floor at 3.737. The four resolvers added later were NOT re-floored on this corpus, and the reason is that they do not need to be: every one of their pre-change legs walked the whole file set per import (PHP one findIndex per path part per extension, Java one scan per stripped prefix, COBOL two full scans per COPY, C# csproj one normalizedFileList pass per import per matching config), so their scaling_ratio is ~4 by construction rather than by measurement. Their per-import costs were measured on their own issue corpora instead: PHP 96.40 ms -> 0.036 ms, Java 8.05 ms -> 0.62 ms, COBOL 3879 us -> 10.5 us, C# csproj 1103 us -> 7.6 us. The 1.8 budget sits well above the linear result and well below every one of those. The eight languages added last were NOT floored either, and for a different reason again: they are not fixes, so there is no pre-change implementation to floor against. Their scaling budgets are the global linear 1.8 and the point of the arms is to hold the current numbers (measured 1.01-1.13) rather than to separate a fix from a break. The one exception is javascript, which IS a fix and does have a floor: 6448.9 us per import at 2000 files and 25972.6 us at 8000 \u2014 4.12x the per-import cost for 4x the files, i.e. O(imports x files) \u2014 against 28.5 / 27.4 us with the index PR #2911 gave it, and 25.0 / 27.0 us for TypeScript over the identical corpus.", "_rebaselined_2910_java_declared_packages": "#2910 replaces Java path-suffix fallback with declared-package resolution. The benchmark now restores package capture side channels, threads parsedFiles through javaScopeResolver, proves the context leg with a positive path/package-mismatch probe, and models the collide arm as one package declared across service paths. External imports now remain unresolved; local exact and wildcard imports preserve the 1153/4681 workload. Java's index is package/type maps rather than suffix maps: bytes_large 34958600 -> 3676984, with its floor and ceiling re-recorded together. Depth and collision scaling budgets tighten to the shared linear 1.8 gate.", diff --git a/gitnexus/bench/import-target/measure.mjs b/gitnexus/bench/import-target/measure.mjs index 1b7e2b00b8..a4d87ba382 100644 --- a/gitnexus/bench/import-target/measure.mjs +++ b/gitnexus/bench/import-target/measure.mjs @@ -365,7 +365,7 @@ * toward the noise floor would only buy flaky CI; see `_blind_spot` in * baselines.json. PR #2911 is the proof that this blind spot is real rather * than theoretical: JavaScript's missing index was a scan of - * `ImportPassCache.normalizedFileList` on EVERY import, which the Set counter + * a cached normalized file array on EVERY import, which the Set counter * could not see, and it took a differential parity test over 211 200 pairs plus * this bench's arrival to pin it. * @@ -485,7 +485,7 @@ import { javaScopeResolver } from '../../src/core/ingestion/languages/java/scope import { cobolScopeResolver } from '../../src/core/ingestion/languages/cobol/scope-resolver.ts'; import { resolveSwiftImportTarget } from '../../src/core/ingestion/languages/swift/import-target.ts'; import { resolveRustImportTarget } from '../../src/core/ingestion/languages/rust/import-target.ts'; -import { resolveZigImportInternal } from '../../src/core/ingestion/import-resolvers/zig.ts'; +import { resolveZigImportInternal } from '../../src/core/ingestion/languages/zig/import-helpers.ts'; import { resolvePythonImportTarget } from '../../src/core/ingestion/languages/python/import-target.ts'; import { makeJsResolveImportTarget } from '../../src/core/ingestion/languages/javascript/import-target.ts'; import { makeVueResolveImportTarget } from '../../src/core/ingestion/languages/vue/import-target.ts'; @@ -1736,7 +1736,7 @@ function buildRepo(lang, fileCount, pad = 0, shape = 'unique') { * `resolutionConfig` the orchestrator threads beside it. * * `allFilePaths` is a FRESH Set per pass on purpose — every per-file-set memo - * in `import-resolvers/per-file-set.ts` is keyed on that object's identity, so + * in `utils/per-file-set.ts` is keyed on that object's identity, so * reusing one Set across passes would hide the index build after the first and * let a rebuilt-per-import index look free from rep 2 onward. * @@ -1927,8 +1927,8 @@ function resolveOne(lang, from, target, pass) { contextFor(pass, { kind: 'named', localName: 'X', importedName: 'X', targetRaw: target }), ); } - // Quotes already stripped — `configs/zig.ts` strips them before this call in - // production too. `null` build config: this arm pins the path walk alone + // Quotes are already stripped from the parsed import target. + // `null` build config: this arm pins the path walk alone // (see the header); the config legs are gated by their own unit tests. if (lang === 'zig') return resolveZigImportInternal(from, target, allFilePaths, null); if (lang === 'python') { diff --git a/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt b/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt index 6eb8287381..e172a35acc 100644 --- a/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt +++ b/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt @@ -1 +1 @@ -d51ea9edd1902fc20dd888f3fc51907c8119a4692b92c32a427801ac7f41d451 +99ec4434eb21b3212425eb92f5652e4955380ab27b705727b422b86e7e0be368 diff --git a/gitnexus/bench/swift-package-imports/baselines.json b/gitnexus/bench/swift-package-imports/baselines.json index d52e9da11e..850d842d31 100644 --- a/gitnexus/bench/swift-package-imports/baselines.json +++ b/gitnexus/bench/swift-package-imports/baselines.json @@ -1,7 +1,7 @@ { "_what": "Baselines for bench/swift-package-imports/measure.mjs --check. Guards Swift Package.swift declaration resolve after #2964 / #2931: declared-target hits, SDK and undeclared-folder misses, empty declaredTargets fail-closed, @_exported union, #2931 nested-prefix membership, first-wins grouping, and https:// factory survival. Same approach as bench/parse-dispatch-rounds/baselines.json — exact floors and a fingerprint first; the only timing arms are ratios.", - "_triage": "READ THIS BEFORE RE-RUNNING. targets, files, imports, declared_resolved, sdk_external, undeclared_external, empty_declared_external, reexport_extra, nested_repeat_resolved, first_wins, parse_targets, parse_binary_skipped, url_comment_targets, parse_complete and layout_fingerprint are DETERMINISTIC: a re-run never changes them, and none may be re-baselined to make CI green. resolve_scaling_ratio, strategy_scaling_ratio and parse_scaling_ratio are the only timing arms; runner contention dominates them, so re-run on an idle machine before investigating and read the reported `reps` first. If exactly one arm fails and it is a timing arm, suspect the machine.", + "_triage": "READ THIS BEFORE RE-RUNNING. targets, files, imports, declared_resolved, sdk_external, undeclared_external, empty_declared_external, reexport_extra, nested_repeat_resolved, first_wins, parse_targets, parse_binary_skipped, url_comment_targets, parse_complete and layout_fingerprint are DETERMINISTIC: a re-run never changes them, and none may be re-baselined to make CI green. resolve_scaling_ratio and parse_scaling_ratio are the only timing arms; runner contention dominates them, so re-run on an idle machine before investigating and read the reported `reps` first. If exactly one arm fails and it is a timing arm, suspect the machine.", "targets": 16, "files": 260, @@ -27,23 +27,17 @@ "_layout_fingerprint_note": "sha256 over sorted from|target->files rows on the unique query set. A change here is a BEHAVIOUR change — the resolver returned a different target set. Explain it, never re-baseline it alone.", "resolve_scaling_budget": 1.9, - "strategy_scaling_budget": 1.6, "parse_scaling_budget": 1.9, "_resolve_scaling_note": "(t_4n / t_n) / 4 for resolveSwiftImportTarget over the declared corpus; ~1.0 is linear. A RATIO rather than a millisecond ceiling, deliberately: wall-clock is runner-speed-dependent, and this repo has already been bitten by a fixed ms budget. A per-import allFilePaths scan scores ~4. Budget is 1.9, i.e. 1.51x the measured maximum 1.261 — this file's siblings use ~1.5x on ratios. min-of-15 estimator.", - "_strategy_scaling_note": "(t_4n / t_n) / 4 for swiftPackageStrategy (the import-config WeakMap index). Measured maximum 1.030; budget 1.6 is 1.55x, matching parse-dispatch-rounds' pack_scaling_budget.", - "_parse_scaling_note": "(t_4n / t_n) / 4 for parseSwiftPackageManifest over 256 vs 1024 factories. Measured maximum 1.276; budget 1.9 is 1.49x. The small cell is still sub-millisecond, so this budget is looser than strategy on purpose.", + "_parse_scaling_note": "(t_4n / t_n) / 4 for parseSwiftPackageManifest over 256 vs 1024 factories. Measured maximum 1.276; budget 1.9 is 1.49x. The small cell is still sub-millisecond, so the budget allows timing variance.", "_measured": { "resolve_scaling_ratio": 1.261, "resolve_scaling_ratio_samples": [1.261, 1.201, 1.182, 1.241, 1.212], - "strategy_scaling_ratio": 1.03, - "strategy_scaling_ratio_samples": [1.019, 0.994, 0.97, 1.015, 1.03], "parse_scaling_ratio": 1.276, "parse_scaling_ratio_samples": [1.25, 1.276, 1.215, 1.224, 1.227], "resolve_ms": 3.5, "resolve_ms_4x": 17.16, - "strategy_ms": 0.67, - "strategy_ms_4x": 2.65, "parse_ms": 0.41, "parse_ms_4x": 2.01, "reps": 15 diff --git a/gitnexus/bench/swift-package-imports/measure.mjs b/gitnexus/bench/swift-package-imports/measure.mjs index efaed2ddd6..e20c7dd767 100644 --- a/gitnexus/bench/swift-package-imports/measure.mjs +++ b/gitnexus/bench/swift-package-imports/measure.mjs @@ -37,7 +37,7 @@ * rows on the unique query set. Catches a target-set change that leaves * the counts intact. * - * - `resolve_scaling_ratio` / `strategy_scaling_ratio` / `parse_scaling_ratio` + * - `resolve_scaling_ratio` / `parse_scaling_ratio` * — the only timing arms, RATIOS not millisecond ceilings. * `(t_4n / t_n) / 4` divides the machine out; ~1.0 is linear. * Files-per-target is FIXED while target count (and therefore files and @@ -54,7 +54,6 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { performance } from 'node:perf_hooks'; import { parseSwiftPackageManifest } from '../../src/core/ingestion/language-config.ts'; -import { swiftPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/swift.ts'; import { resolveSwiftImportTarget } from '../../src/core/ingestion/languages/swift/import-target.ts'; import { groupSwiftFilesByModule } from '../../src/core/ingestion/languages/swift/target-grouping.ts'; @@ -173,23 +172,6 @@ function resolveOne(query, allFilePaths, config, parsedFiles) { }); } -function strategyCtx(files, config) { - return { - allFilePaths: new Set(files), - allFileList: files, - normalizedFileList: files.map((p) => p.replace(/\\/g, '/')), - index: {}, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: config, - csharpConfigs: [], - }, - }; -} - function resolvePass(corpus) { const allFilePaths = new Set(corpus.files); let resolved = 0; @@ -199,15 +181,6 @@ function resolvePass(corpus) { return resolved; } -function strategyPass(corpus) { - const ctx = strategyCtx(corpus.files, corpus.config); - let resolved = 0; - for (const query of corpus.queries) { - if (swiftPackageStrategy(query.raw, query.from, ctx) != null) resolved++; - } - return resolved; -} - function manifestFor(targetCount) { const rows = []; for (let i = 0; i < targetCount; i++) { @@ -327,10 +300,6 @@ const smallResolveMs = fastest(() => resolvePass(small), REPS); const largeResolveMs = fastest(() => resolvePass(large), REPS); const resolveScaling = largeResolveMs / smallResolveMs / SCALE; -const smallStrategyMs = fastest(() => strategyPass(small), REPS); -const largeStrategyMs = fastest(() => strategyPass(large), REPS); -const strategyScaling = largeStrategyMs / smallStrategyMs / SCALE; - const parseSmallSrc = manifestFor(PARSE_TARGETS); const parseLargeSrc = manifestFor(PARSE_TARGETS * SCALE); const parseSmall = parseSwiftPackageManifest(parseSmallSrc); @@ -376,14 +345,11 @@ console.log(`layout_fingerprint : ${shape.fingerprint}`); console.log( `resolve_scaling_ratio : ${resolveScaling.toFixed(3)} (budget <= ${baselines.resolve_scaling_budget}; ~1.0 is linear)`, ); -console.log( - `strategy_scaling_ratio : ${strategyScaling.toFixed(3)} (budget <= ${baselines.strategy_scaling_budget}; ~1.0 is linear)`, -); console.log( `parse_scaling_ratio : ${parseScaling.toFixed(3)} (budget <= ${baselines.parse_scaling_budget}; ~1.0 is linear)`, ); console.log( - `reps : ${REPS} resolve ${smallResolveMs.toFixed(2)}ms / 4x ${largeResolveMs.toFixed(2)}ms strategy ${smallStrategyMs.toFixed(2)}ms / 4x ${largeStrategyMs.toFixed(2)}ms parse ${smallParseMs.toFixed(2)}ms / 4x ${largeParseMs.toFixed(2)}ms`, + `reps : ${REPS} resolve ${smallResolveMs.toFixed(2)}ms / 4x ${largeResolveMs.toFixed(2)}ms parse ${smallParseMs.toFixed(2)}ms / 4x ${largeParseMs.toFixed(2)}ms`, ); console.log( `parse_scale_shape : ${parseSmall.targets.size} -> ${parseLarge.targets.size} targets (expect ${PARSE_TARGETS} -> ${PARSE_TARGETS * SCALE})`, @@ -457,16 +423,6 @@ if (process.argv.includes('--check')) { ); } - if (strategyScaling > baselines.strategy_scaling_budget) { - failed = true; - console.error( - `\nFAIL strategy_scaling_ratio: ${strategyScaling.toFixed(3)} exceeds ` + - `${baselines.strategy_scaling_budget} (~1.0 is linear).\n` + - ` swiftPackageStrategy grew superlinearly — usually the WeakMap target\n` + - ` index falling back to O(imports × files). Re-run idle; check \`reps\`.`, - ); - } - if (parseScaling > baselines.parse_scaling_budget) { failed = true; console.error( diff --git a/gitnexus/src/core/group/extractors/http-patterns/php.ts b/gitnexus/src/core/group/extractors/http-patterns/php.ts index 65a1896c9a..8a72052f00 100644 --- a/gitnexus/src/core/group/extractors/http-patterns/php.ts +++ b/gitnexus/src/core/group/extractors/http-patterns/php.ts @@ -42,7 +42,7 @@ import type { HttpDetection, HttpLanguagePlugin } from './types.js'; * `python-const-resolver.ts` / `js-const-resolver.ts`). PHP has no such * binding yet — adding one is a real, separate project (this repo's PHP * import resolution for `use`-statements is its own multi-file subsystem - * under `ingestion/import-resolvers/php.ts`, built for symbol/scope + * under `ingestion/languages/php/import-helpers.ts`, built for symbol/scope * resolution, not constant extraction) and is intentionally out of scope * here. Tracked as a follow-up, not silently punted. */ diff --git a/gitnexus/src/core/group/extractors/include-extractor.ts b/gitnexus/src/core/group/extractors/include-extractor.ts index d7993c0f4d..bd11a388d5 100644 --- a/gitnexus/src/core/group/extractors/include-extractor.ts +++ b/gitnexus/src/core/group/extractors/include-extractor.ts @@ -21,7 +21,7 @@ try { import type { ContractExtractor, CypherExecutor } from '../contract-extractor.js'; import type { ExtractedContract, RepoHandle } from '../types.js'; import { readSafe } from './fs-utils.js'; -import { buildSuffixIndex, type SuffixIndex } from '../../ingestion/import-resolvers/utils.js'; +import { buildSuffixIndex, type SuffixIndex } from '../../ingestion/utils/suffix-index.js'; import { createIgnoreFilter } from '../../../config/ignore-service.js'; import { getMaxFileSizeBytes } from '../../ingestion/utils/max-file-size.js'; import { parseSourceSafe } from '../../tree-sitter/safe-parse.js'; diff --git a/gitnexus/src/core/ingestion/asyncapi/document.ts b/gitnexus/src/core/ingestion/asyncapi/document.ts index 282e579175..5932db5a10 100644 --- a/gitnexus/src/core/ingestion/asyncapi/document.ts +++ b/gitnexus/src/core/ingestion/asyncapi/document.ts @@ -60,7 +60,7 @@ import path from 'node:path'; import { brokerForBindingKey, brokerForProtocol, isNonDestinationBroker } from './protocol.js'; // `js-yaml` is CJS; the rest of this repository reaches it the same way -// (`pipeline-phases/spring-config.ts`, `import-resolvers/node-workspace-packages.ts`). +// (`pipeline-phases/spring-config.ts`, `languages/typescript/workspace-packages.ts`). const _require = createRequire(import.meta.url); const yaml = _require('js-yaml') as typeof import('js-yaml'); diff --git a/gitnexus/src/core/ingestion/di-extractors/types.ts b/gitnexus/src/core/ingestion/di-extractors/types.ts index 5a06212639..ea91dc5500 100644 --- a/gitnexus/src/core/ingestion/di-extractors/types.ts +++ b/gitnexus/src/core/ingestion/di-extractors/types.ts @@ -9,8 +9,6 @@ * consumers of the registry read them off its results; `DiResolver` is not * re-exported, since only implementations need it and they import it from here * directly. - * - * Mirrors the `import-resolvers/types.ts` split of contract from registry. */ import type { GraphNode } from 'gitnexus-shared'; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts deleted file mode 100644 index bcfddee0ba..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * C / C++ import resolution configs. - * Both use standard resolution for #include directives. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; - -export const cImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.C, - strategies: [createStandardStrategy(SupportedLanguages.C)], -}; - -export const cppImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.CPlusPlus, - strategies: [createStandardStrategy(SupportedLanguages.CPlusPlus)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts deleted file mode 100644 index 24e9e6cfa0..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * C# import resolution config. - * Namespace-based strategy via .csproj configs, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveCSharpImportInternal, resolveCSharpNamespaceDir } from '../csharp.js'; -import { csharpSuffixFallbackAllowed } from '../../csharp-namespace-gate.js'; - -/** C# namespace-based resolution strategy via .csproj configs. */ -export const csharpNamespaceStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const csharpConfigs = ctx.configs.csharpConfigs; - const evidence = ctx.configs.csharpNamespaces; - if (csharpConfigs.length === 0) { - // No csproj → there's no namespace→directory mapping to apply, so the - // generic strategy would normally take over. But that generic suffix match - // is UNGATED: it re-introduces the BCL→local spurious match the #1881 gate - // exists to stop. Mirror the registry leg's no-csproj path — defer to the - // generic strategy ONLY for imports that align with an in-repo declared - // namespace; for everything else (BCL usings) return an authoritative empty - // result that STOPS the chain (#2 parity). With no evidence threaded the - // gate fails open, so behavior is unchanged when the scan didn't run. - if (!csharpSuffixFallbackAllowed(rawImportPath, evidence)) { - return { kind: 'files', files: [] }; - } - return null; - } - - const resolvedFiles = resolveCSharpImportInternal( - rawImportPath, - csharpConfigs, - // The Set, not `ctx.normalizedFileList`/`ctx.allFileList`: the resolver - // derives both from it through the same per-pass memo the ctx's own arrays - // come from, so this is the identical pair by a shorter route. - ctx.allFilePaths, - ctx.index, - evidence, - ); - if (resolvedFiles.length > 1) { - const dirSuffix = resolveCSharpNamespaceDir(rawImportPath, csharpConfigs); - if (dirSuffix) { - return { kind: 'package', files: resolvedFiles, dirSuffix }; - } - } - // Authoritative once csproj configs exist: return even an empty result to - // STOP the chain, so the generic suffix fallback can't re-introduce the - // gated BCL→local match this resolver just suppressed (#1881). - return { kind: 'files', files: resolvedFiles }; -}; - -export const csharpImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.CSharp, - strategies: [csharpNamespaceStrategy, createStandardStrategy(SupportedLanguages.CSharp)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts deleted file mode 100644 index 06dcea98a3..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Dart import resolution config. - * SDK/package strategy first, then relative import strategy (with ./ prepending). - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolveStandard } from '../standard.js'; - -/** - * Dart SDK and package: import strategy. - * Absorbs dart: SDK imports and external packages (returns empty result to stop chain). - * Returns null for relative imports to let the next strategy handle them. - */ -export const dartPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - // Strip surrounding quotes from configurable_uri capture - const stripped = rawImportPath.replace(/^['"]|['"]$/g, ''); - - // Skip dart: SDK imports (dart:async, dart:io, etc.) - if (stripped.startsWith('dart:')) return { kind: 'files', files: [] }; - - // Local package: imports → resolve to lib/ - if (stripped.startsWith('package:')) { - const slashIdx = stripped.indexOf('/'); - if (slashIdx === -1) return { kind: 'files', files: [] }; - const relPath = stripped.slice(slashIdx + 1); - const candidates = [`lib/${relPath}`, relPath]; - const files: string[] = []; - for (const candidate of candidates) { - for (const fp of ctx.allFileList) { - if (fp.endsWith('/' + candidate) || fp === candidate) { - files.push(fp); - break; - } - } - if (files.length > 0) break; - } - if (files.length > 0) return { kind: 'files', files }; - return { kind: 'files', files: [] }; // external package - } - - return null; -}; - -/** - * Dart relative import strategy — prepends "./" for bare relative paths, - * then delegates to standard resolution. - */ -export const dartRelativeStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - const stripped = rawImportPath.replace(/^['"]|['"]$/g, ''); - const relPath = stripped.startsWith('.') ? stripped : './' + stripped; - return resolveStandard(relPath, filePath, ctx, SupportedLanguages.Dart); -}; - -export const dartImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Dart, - strategies: [dartPackageStrategy, dartRelativeStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts deleted file mode 100644 index 7eee179884..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Go import resolution config. - * Go-specific package strategy (go.mod), then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveGoPackageDir, resolveGoPackage } from '../go.js'; - -/** Go-specific package resolution strategy — resolves go.mod-based package imports. */ -export const goPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const goModule = ctx.configs.goModule; - if (goModule && rawImportPath.startsWith(goModule.modulePath)) { - const pkgSuffix = resolveGoPackageDir(rawImportPath, goModule); - if (pkgSuffix) { - const pkgFiles = resolveGoPackage( - rawImportPath, - goModule, - ctx.normalizedFileList, - ctx.allFileList, - ); - if (pkgFiles.length > 0) { - return { kind: 'package', files: pkgFiles, dirSuffix: pkgSuffix }; - } - } - // Fall through if no files found (package might be external) - } - return null; -}; - -export const goImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Go, - strategies: [goPackageStrategy, createStandardStrategy(SupportedLanguages.Go)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts deleted file mode 100644 index 47e590fe87..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Java / Kotlin import resolution configs. - * JVM-specific wildcard/member strategy, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveJvmWildcard, resolveJvmMemberImport, KOTLIN_EXTENSIONS } from '../jvm.js'; - -/** Java JVM resolution strategy — wildcard and member import resolution. */ -export const javaJvmStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - if (rawImportPath.endsWith('.*')) { - const matchedFiles = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (matchedFiles.length > 0) return { kind: 'files', files: matchedFiles }; - } else { - const memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (memberResolved) return { kind: 'files', files: [memberResolved] }; - } - return null; -}; - -/** - * Kotlin JVM resolution strategy — wildcard/member with Java-interop + top-level function imports. - */ -export const kotlinJvmStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - if (rawImportPath.endsWith('.*')) { - const matchedFiles = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (matchedFiles.length === 0) { - const javaMatches = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (javaMatches.length > 0) return { kind: 'files', files: javaMatches }; - } - if (matchedFiles.length > 0) return { kind: 'files', files: matchedFiles }; - } else { - let memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (!memberResolved) { - memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - } - if (memberResolved) return { kind: 'files', files: [memberResolved] }; - - // Kotlin: top-level function imports (e.g. import models.getUser) have only 2 segments, - // which resolveJvmMemberImport skips (requires >=3). Fall back to package-directory scan - // for lowercase last segments (function/property imports). Uppercase last segments - // (class imports like models.User) fall through to standard suffix resolution. - const segments = rawImportPath.split('.'); - const lastSeg = segments[segments.length - 1]; - if (segments.length >= 2 && lastSeg[0] && lastSeg[0] === lastSeg[0].toLowerCase()) { - const pkgWildcard = segments.slice(0, -1).join('.') + '.*'; - let dirFiles = resolveJvmWildcard( - pkgWildcard, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (dirFiles.length === 0) { - dirFiles = resolveJvmWildcard( - pkgWildcard, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - } - if (dirFiles.length > 0) return { kind: 'files', files: dirFiles }; - } - } - return null; -}; - -export const javaImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Java, - strategies: [javaJvmStrategy, createStandardStrategy(SupportedLanguages.Java)], -}; - -export const kotlinImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Kotlin, - strategies: [kotlinJvmStrategy, createStandardStrategy(SupportedLanguages.Kotlin)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts deleted file mode 100644 index 5a8446f25c..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * PHP import resolution config. - * PSR-4 strategy via composer.json — no standard fallback (PSR-4 includes its own suffix matching). - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolvePhpImportInternal } from '../php.js'; - -/** PHP PSR-4 resolution strategy via composer.json autoload mappings. */ -export const phpPsr4Strategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const resolved = resolvePhpImportInternal( - rawImportPath, - ctx.configs.composerConfig, - ctx.allFilePaths, - ctx.normalizedFileList, - ctx.allFileList, - ctx.index, - ); - return resolved ? { kind: 'files', files: [resolved] } : null; -}; - -export const phpImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.PHP, - strategies: [phpPsr4Strategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts deleted file mode 100644 index d983045611..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Python import resolution config. - * PEP 328 relative + proximity-based strategy, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolvePythonImportInternal } from '../python.js'; - -/** - * Python import resolution strategy — PEP 328 relative + proximity-based bare imports. - * Returns null to continue chain for non-relative imports. - * Absorbs unresolved relative imports (returns empty result to stop the chain). - */ -export const pythonImportStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - const resolved = resolvePythonImportInternal(filePath, rawImportPath, ctx.allFilePaths); - if (resolved) { - ctx.resolveCache.set(`${filePath}::${rawImportPath}`, resolved); - return { kind: 'files', files: [resolved] }; - } - // PEP 328: unresolved relative imports should not fall through to suffix matching - if (rawImportPath.startsWith('.')) return { kind: 'files', files: [] }; - - // External dotted imports like `django.apps` should not fall through to generic - // suffix matching when the repo has unrelated local files such as `accounts/apps.py`. - // Keep suffix fallback only when the leading segment appears somewhere in-repo, - // which preserves existing internal absolute-import behavior like `accounts.models`. - const pathLike = rawImportPath.replace(/\./g, '/'); - if (pathLike.includes('/')) { - const [leadingSegment] = pathLike.split('/').filter(Boolean); - const hasRepoCandidate = - !!leadingSegment && - (ctx.index.get(`${leadingSegment}.py`) !== undefined || - ctx.index.get(`${leadingSegment}/__init__.py`) !== undefined || - ctx.index.getFilesInDir(leadingSegment, '.py').length > 0); - - if (!hasRepoCandidate) return { kind: 'files', files: [] }; - } - - return null; -}; - -export const pythonImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Python, - strategies: [pythonImportStrategy, createStandardStrategy(SupportedLanguages.Python)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts deleted file mode 100644 index bf2507f705..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Ruby import resolution config. - * Require/require_relative suffix matching — no standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { suffixResolve } from '../utils.js'; - -/** Ruby require/require_relative resolution strategy. */ -export const rubyRequireStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const pathParts = rawImportPath.replace(/^\.\//, '').split('/').filter(Boolean); - const resolved = suffixResolve(pathParts, ctx.normalizedFileList, ctx.allFileList, ctx.index); - return resolved ? { kind: 'files', files: [resolved] } : null; -}; - -export const rubyImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Ruby, - strategies: [rubyRequireStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts deleted file mode 100644 index daa2173e71..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Rust import resolution config. - * Rust module strategy (grouped imports, crate/super/self paths), then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveRustImportInternal } from '../rust.js'; - -/** Rust module resolution strategy — handles grouped imports and crate/super/self paths. */ -export const rustModuleStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - // Top-level grouped: use {crate::a, crate::b} - if (rawImportPath.startsWith('{') && rawImportPath.endsWith('}')) { - const inner = rawImportPath.slice(1, -1); - const parts = inner - .split(',') - .map((p) => p.trim()) - .filter(Boolean); - const resolved: string[] = []; - for (const part of parts) { - const r = resolveRustImportInternal(filePath, part, ctx.allFilePaths); - if (r) resolved.push(r); - } - return resolved.length > 0 ? { kind: 'files', files: resolved } : null; - } - - // Scoped grouped: use crate::models::{User, Repo} - const braceIdx = rawImportPath.indexOf('::{'); - if (braceIdx !== -1 && rawImportPath.endsWith('}')) { - const pathPrefix = rawImportPath.substring(0, braceIdx); - const braceContent = rawImportPath.substring(braceIdx + 3, rawImportPath.length - 1); - const items = braceContent - .split(',') - .map((s) => s.trim()) - .filter(Boolean); - const resolved: string[] = []; - for (const item of items) { - // Handle `use crate::models::{User, Repo as R}` — strip alias for resolution - const itemName = item.includes(' as ') ? item.split(' as ')[0].trim() : item; - const r = resolveRustImportInternal(filePath, `${pathPrefix}::${itemName}`, ctx.allFilePaths); - if (r) resolved.push(r); - } - if (resolved.length > 0) return { kind: 'files', files: resolved }; - // Fallback: resolve the prefix path itself (e.g. crate::models -> models.rs) - const prefixResult = resolveRustImportInternal(filePath, pathPrefix, ctx.allFilePaths); - if (prefixResult) return { kind: 'files', files: [prefixResult] }; - } - - return null; -}; - -export const rustImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Rust, - strategies: [rustModuleStrategy, createStandardStrategy(SupportedLanguages.Rust)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts deleted file mode 100644 index 1081a5aabe..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Swift import resolution config. - * Package.swift target map strategy — no standard fallback (unresolved = external framework). - * - * ## Performance (anti-O(imports × files)) - * - * The previous implementation rescanned the whole `normalizedFileList` - * on every import to collect the `.swift` files under the requested - * target's directory — O(imports × files) per run, the exact hot path - * fixed for Python in PR #1918. We now build a `target → files` index - * ONCE per run, memoized on the stable `allFileList` array reference - * (the same `ResolveCtx` — and therefore the same array — is passed to - * every strategy invocation, per `import-processor`'s build-once - * context). Lookup per import is then O(1). - * - * A file is attributed to a target iff its **forward-slash - * (backslash-normalized), case-sensitive** path matches at a - * **segment boundary**: it starts with `/` or contains - * `//`. `normalizedFileList` is - * only backslash→forward-slash normalized — NOT lowercased — so the - * match is case-sensitive. The returned paths are the original-case - * `allFileList` entries, and the per-target file ORDER follows - * `allFileList`. - * - * Import-config fans a file to every matching declared target. Module - * grouping (`groupSwiftFilesByModule`) anchors target paths at the repo root - * and picks the deepest. That divergence is intentional: this legacy - * strategy only sees the root declaration map. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import { coerceDeclaredSwiftTargets, swiftDeclaredTargetPrefix } from '../../language-config.js'; -import type { ImportResolutionConfig, ImportResolverStrategy, ResolveCtx } from '../types.js'; - -interface SwiftTargetIndex { - /** Target name → original-case `.swift` file paths under that target dir. */ - readonly byTarget: ReadonlyMap; -} - -/** - * Memoized on the `allFileList` array identity. `import-processor` builds - * the `ResolveCtx` once per run and threads the same object (and the same - * `allFileList`) through every strategy call, so the WeakMap is keyed on a - * stable reference and the index is built once — not once per import. A - * fresh run produces a fresh array → a fresh index, so cross-run staleness - * is impossible. - * - * DELIBERATELY NOT ON `import-resolvers/per-file-set.ts` (#2909 sweep): this is - * a TWO-input memo keyed on ONE of them. The index is a function of both - * `ctx` (`allFileList` + the index-aligned `normalizedFileList`) and `targets`, - * but the key is only `ctx.allFileList`, and `perFileSet`'s `build: (key) => T` - * hands the builder nothing but the key. It is sound here only because of an - * invariant OUTSIDE the memo — `targets` is `ctx.configs.swiftPackageConfig - * .targets`, so it shares `ctx`'s lifetime and cannot vary while - * `ctx.allFileList` is fixed — and `perFileSet` has no way to express "and this - * other input is pinned by the same lifetime". Re-keying on `ctx` to make - * `targets` derivable from the key would change what the cache is keyed on and - * force an unreachable null-config arm into the builder, so it is a behaviour - * change rather than a consolidation. Leave it hand-rolled. - */ -const SWIFT_TARGET_INDEX_CACHE = new WeakMap(); - -function getSwiftTargetIndex( - ctx: ResolveCtx, - targets: ReadonlyMap, -): SwiftTargetIndex { - const key = ctx.allFileList as object; - const cached = SWIFT_TARGET_INDEX_CACHE.get(key); - if (cached !== undefined) return cached; - - // Pre-compute each target's directory prefix once (original case, to - // match the legacy comparison against the forward-slash-normalized, - // case-sensitive file list — see module docstring). - const targetDirs: { name: string; prefix: string }[] = []; - const byTarget = new Map(); - for (const [name, dir] of targets) { - targetDirs.push({ name, prefix: swiftDeclaredTargetPrefix(dir) }); - byTarget.set(name, []); - } - - // Single pass over the file list. `normalizedFileList` is forward-slash - // (backslash-normalized), case-sensitive, and index-aligned with - // `allFileList`; attribute the original-case path to every target whose - // prefix the normalized path starts with (a file under a nested target - // dir can legitimately belong to multiple configured targets — the - // legacy per-import scan would have returned it for each). - for (let i = 0; i < ctx.allFileList.length; i++) { - const norm = ctx.normalizedFileList[i]; - if (!norm.endsWith('.swift')) continue; - for (const { name, prefix } of targetDirs) { - if (!norm.startsWith(prefix) && !norm.includes(`/${prefix}`)) continue; - const bucket = byTarget.get(name); - if (bucket !== undefined) bucket.push(ctx.allFileList[i]); - } - } - - const index: SwiftTargetIndex = { byTarget }; - SWIFT_TARGET_INDEX_CACHE.set(key, index); - return index; -} - -/** Swift Package.swift target map resolution strategy. */ -export const swiftPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const swiftPackageConfig = ctx.configs.swiftPackageConfig; - if (swiftPackageConfig == null) return null; - const declared = coerceDeclaredSwiftTargets(swiftPackageConfig); - if (declared == null) return null; - const moduleName = rawImportPath.split('.')[0]; - if (moduleName === '' || !declared.has(moduleName)) { - return null; - } - const index = getSwiftTargetIndex(ctx, declared); - const files = index.byTarget.get(moduleName); - if (files !== undefined && files.length > 0) { - return { kind: 'files', files: [...files] }; - } - return null; -}; - -export const swiftImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Swift, - strategies: [swiftPackageStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts deleted file mode 100644 index b86b365fd2..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * TypeScript / JavaScript / Vue import resolution configs. - * All use standard resolution — TS/JS with tsconfig path aliases, - * Vue delegates to TypeScript's resolver. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; - -export const typescriptImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.TypeScript, - strategies: [createStandardStrategy(SupportedLanguages.TypeScript)], -}; - -export const javascriptImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.JavaScript, - strategies: [createStandardStrategy(SupportedLanguages.JavaScript)], -}; - -// Vue SFCs are preprocessed into TypeScript upstream of import resolution, -// so the resolver intentionally runs as TypeScript. `language: Vue` here is -// documentation-only metadata (see `ImportResolutionConfig.language` JSDoc -// and ARCHITECTURE.md §Vue); it is not consumed by `createImportResolver`. -export const vueImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Vue, - strategies: [createStandardStrategy(SupportedLanguages.TypeScript)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts deleted file mode 100644 index a191df9b6b..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Zig import resolution. - * - * Local-file imports (`@import("./foo.zig")`, `@import("foo.zig")`) resolve - * relative to the importer. Bare names (`@import("bar")`) resolve through - * build.zig.zon `.path` deps when a parsed ZigBuildZonConfig is available - * (see language-config.ts `loadZigBuildConfig`). Everything unresolvable — - * `std`, `builtin`, `root`, `.url`-based deps — returns an empty result so - * it doesn't produce ghost import edges. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolveZigImportInternal } from '../zig.js'; - -const stripQuotes = (s: string): string => s.replace(/^['"]|['"]$/g, ''); - -export const zigImportStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - // tree-sitter-zig captures the string with surrounding quotes. - const stripped = stripQuotes(rawImportPath); - const resolved = resolveZigImportInternal( - filePath, - stripped, - ctx.allFilePaths, - ctx.configs.zigBuildZon ?? null, - ); - // Unresolvable (stdlib / builtin / .url dep / missing file): stop the - // chain with an empty result rather than falling through to suffix - // matching, which could ghost-match an unrelated same-named file. - return { kind: 'files', files: resolved ? [resolved] : [] }; -}; - -export const zigImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Zig, - strategies: [zigImportStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/go.ts b/gitnexus/src/core/ingestion/import-resolvers/go.ts deleted file mode 100644 index eb87b09973..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/go.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Go package import resolution — internal helpers. - * - * Strategy lives in configs/go.ts. - * This file contains the shared helpers used by the strategy. - * - * **Reachability, as of #2929:** nothing in production calls either export - * today. The only path in is `configs/go.ts` → `createImportResolver` → - * the `importResolver` field on Go's `LanguageProvider`, and that field is - * read at exactly two lines — `import-target-adapter.ts:74-75` — whose two - * exports (`buildImportTargetWorkspace`, - * `resolveImportTargetAcrossLanguages`) have no importer anywhere but their - * own unit test. So this is a live-looking but currently unwired leg; the - * tests in `test/unit/import-resolvers/go-package-resolve.test.ts` are the - * only thing watching it. - */ - -import type { GoModuleConfig } from '../language-config.js'; - -/** `'/'`, for the parent-directory boundary check in `resolveGoPackage`. */ -const SLASH_CODE = 47; - -/** - * Extract the package directory suffix from a Go import path. - * Returns the suffix string (e.g., "/internal/auth/") or null if invalid. - */ -export function resolveGoPackageDir(importPath: string, goModule: GoModuleConfig): string | null { - if (!importPath.startsWith(goModule.modulePath)) return null; - const relativePkg = importPath.slice(goModule.modulePath.length + 1); - if (!relativePkg) return null; - return '/' + relativePkg + '/'; -} - -/** - * Resolve a Go internal package import to all .go files in the package directory. - * Returns an array of file paths. - */ -export function resolveGoPackage( - importPath: string, - goModule: GoModuleConfig, - normalizedFileList: readonly string[], - allFileList: readonly string[], -): string[] { - // Identical to the six lines this used to re-derive; `resolveGoPackageDir` - // returns the '/'-wrapped form and the scan wants the bare path, so unwrap. - const pkgDir = resolveGoPackageDir(importPath, goModule); - if (pkgDir === null) return []; - const relativePkg = pkgDir.slice(1, -1); // "/internal/auth/" → "internal/auth" - - const pkgLen = relativePkg.length; // >= 1: `resolveGoPackageDir` rejects empty - const matches: string[] = []; - - for (let i = 0; i < normalizedFileList.length; i++) { - const normalized = normalizedFileList[i]; - if (!normalized.endsWith('.go') || normalized.endsWith('_test.go')) continue; - // The file's PARENT directory ends with the package path — the same - // predicate `package-dir-index.ts` states. This used to ask `indexOf` for - // the FIRST `//` and then check that nothing after it held a slash, - // which made `a/pkg/b/pkg/x.go` not a member of `pkg` (#2881). - // - // Expressed as "`relativePkg` sits immediately before the last slash, on a - // segment boundary". The boundary is either the start of the path (an - // import matching from index 0, `internal/auth/x.go`) or a `/` — which is - // what the old `'/' + path` cons bought, at the price of a per-file - // concatenation the first `endsWith` forced V8 to flatten (#2929). - // - // Rewriting this as `endsWith(relativePkg, lastSlash)` buys nothing: the - // two-argument overload measured a wash against `startsWith(needle, pos)` - // here (10.28 ns vs 9.82 ns), so it trades the clarity of an explicit start - // index for no gain. A "the 2-arg overload leaves V8's fast path, 20x" - // claim from review did not reproduce on Node 22.18 — its baseline was a - // one-argument call that early-exited on the length precheck. - const start = normalized.lastIndexOf('/') - pkgLen; // < 0 when there is no parent dir - if (start < 0 || !normalized.startsWith(relativePkg, start)) continue; - if (start > 0 && normalized.charCodeAt(start - 1) !== SLASH_CODE) continue; - matches.push(allFileList[i]); - } - - return matches; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/jvm.ts b/gitnexus/src/core/ingestion/import-resolvers/jvm.ts deleted file mode 100644 index b6723b8e24..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/jvm.ts +++ /dev/null @@ -1,127 +0,0 @@ -/** - * JVM import resolution — internal helpers (Java + Kotlin). - * - * Strategies live in configs/jvm.ts. - * This file contains shared helpers for wildcard/member resolution - * and the Kotlin wildcard preprocessor. - */ - -import type { SuffixIndex } from './utils.js'; -import type { SyntaxNode } from '../utils/ast-helpers.js'; - -/** Kotlin file extensions for JVM resolver reuse */ -export const KOTLIN_EXTENSIONS: readonly string[] = ['.kt', '.kts']; - -/** - * Append .* to a Kotlin import path if the AST has a wildcard_import sibling node. - * Pure function — returns a new string without mutating the input. - */ -export const appendKotlinWildcard = (importPath: string, importNode: SyntaxNode): string => { - for (let i = 0; i < importNode.childCount; i++) { - if (importNode.child(i)?.type === 'wildcard_import') { - return importPath.endsWith('.*') ? importPath : `${importPath}.*`; - } - } - return importPath; -}; - -/** - * Resolve a JVM wildcard import (com.example.*) to all matching files. - * Works for both Java (.java) and Kotlin (.kt, .kts). - */ -export function resolveJvmWildcard( - importPath: string, - normalizedFileList: readonly string[], - allFileList: readonly string[], - extensions: readonly string[], - index?: SuffixIndex, -): string[] { - // "com.example.util.*" -> "com/example/util" - const packagePath = importPath.slice(0, -2).replace(/\./g, '/'); - - if (index) { - const candidates = extensions.flatMap((ext) => index.getFilesInDir(packagePath, ext)); - // Filter to only direct children (no subdirectories) - const packageSuffix = '/' + packagePath + '/'; - const packagePrefix = packagePath + '/'; - return candidates.filter((f) => { - const normalized = f.replace(/\\/g, '/'); - // Match both nested (src/models/User.kt) and root-level (models/User.kt) packages - let afterPkg: string; - const idx = normalized.lastIndexOf(packageSuffix); - if (idx >= 0) { - afterPkg = normalized.substring(idx + packageSuffix.length); - } else if (normalized.startsWith(packagePrefix)) { - afterPkg = normalized.substring(packagePrefix.length); - } else { - return false; - } - return !afterPkg.includes('/'); - }); - } - - // Fallback: linear scan - const packageSuffix = '/' + packagePath + '/'; - const packagePrefix = packagePath + '/'; - const matches: string[] = []; - for (let i = 0; i < normalizedFileList.length; i++) { - const normalized = normalizedFileList[i]; - if (!extensions.some((ext) => normalized.endsWith(ext))) continue; - // Match both nested (src/models/User.kt) and root-level (models/User.kt) packages - let afterPackage: string | null = null; - if (normalized.includes(packageSuffix)) { - afterPackage = normalized.substring( - normalized.lastIndexOf(packageSuffix) + packageSuffix.length, - ); - } else if (normalized.startsWith(packagePrefix)) { - afterPackage = normalized.substring(packagePrefix.length); - } - if (afterPackage !== null && !afterPackage.includes('/')) { - matches.push(allFileList[i]); - } - } - return matches; -} - -/** - * Try to resolve a JVM member/static import by stripping the member name. - * Java: "com.example.Constants.VALUE" -> resolve "com.example.Constants" - * Kotlin: "com.example.Constants.VALUE" -> resolve "com.example.Constants" - */ -export function resolveJvmMemberImport( - importPath: string, - normalizedFileList: readonly string[], - allFileList: readonly string[], - extensions: readonly string[], - index?: SuffixIndex, -): string | null { - // Member imports: com.example.Constants.VALUE or com.example.Constants.* - // The last segment is a member name if it starts with lowercase, is ALL_CAPS, or is a wildcard - const segments = importPath.split('.'); - if (segments.length < 3) return null; - - const lastSeg = segments[segments.length - 1]; - if (lastSeg === '*' || /^[a-z]/.test(lastSeg) || /^[A-Z_]+$/.test(lastSeg)) { - const classPath = segments.slice(0, -1).join('/'); - - for (const ext of extensions) { - const classSuffix = classPath + ext; - if (index) { - const result = index.get(classSuffix) || index.getInsensitive(classSuffix); - if (result) return result; - } else { - const fullSuffix = '/' + classSuffix; - for (let i = 0; i < normalizedFileList.length; i++) { - if ( - normalizedFileList[i].endsWith(fullSuffix) || - normalizedFileList[i].toLowerCase().endsWith(fullSuffix.toLowerCase()) - ) { - return allFileList[i]; - } - } - } - } - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts b/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts deleted file mode 100644 index 4c307cfd04..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { buildSuffixIndex, type SuffixIndex } from './utils.js'; - -/** - * Everything the standard `resolveTsTarget` path derives from one workspace - * file set: the file list, the lower-cased file list, the suffix index and the - * per-pass `resolveCache`. - * - * Without this memoization the resolver re-derived `allFileList` and - * `normalizedFileList` (both O(N_files)), rebuilt the index and threw away the - * `resolveCache` on every import — O(N_files × N_imports) total work for what - * should be O(N_files + N_imports). - */ -export interface ImportPassCache { - readonly allFilePaths: Set; - readonly allFileList: readonly string[]; - readonly normalizedFileList: readonly string[]; - readonly index: SuffixIndex; - readonly resolveCache: Map; -} - -/** - * Build that state. Shared by every adapter whose resolution runs through - * `resolveTsTarget`. - * - * Not a dedup of identical copies, and the difference is the point. At - * 49c5b7d81 each of those adapters carried this record inline and they did NOT - * agree: `languages/typescript/scope-resolver.ts` and - * `languages/vue/import-target.ts` held six byte-identical fields built around - * `index: buildSuffixIndex(normalizedFileList, allFileList)`, while - * `languages/javascript/import-target.ts` held five and never called - * `buildSuffixIndex` at all. That one missing field IS the O(imports × files) - * defect PR #2911 fixed — `resolveTsTarget` fell back to `suffixResolve`'s - * linear scan for every JavaScript import — and the header of - * `languages/javascript/import-target.ts` carries the measurements. Hoisting - * the builder is what makes a fourth adapter unable to omit it again: `index` - * is not optional on `ImportPassCache`. - * - * The BUILDER is shared; the MEMO deliberately is not. Each adapter wraps this - * in its own `perFileSet(...)`, so each gets its own `WeakMap`, its own index - * instance and — the one that would be a behaviour change — its own - * `resolveCache`. The languages disagree about what a specifier resolves to - * (`tsconfigPaths` is read from config for TypeScript and Vue, pinned to `null` - * for JavaScript, and the tried extension list differs), so one shared resolve - * cache across them would hand a language another language's answers. - * - * Sharing the builder is a code dedup and nothing more: it buys no runtime - * reuse, because there is none to buy. Each provider pass builds its own - * `allFilePaths` Set (`scope-resolution/pipeline/run.ts`, per provider), so - * TypeScript's set and JavaScript's set are different objects and therefore - * different `WeakMap` keys even where the two memos are the same code. - */ -export function buildImportPassCache(allFilePaths: ReadonlySet): ImportPassCache { - const allFileList = Array.from(allFilePaths); - // LOWERCASED, not slash-normalized — unlike every other caller of - // `buildSuffixIndex`. That is what `alreadyLowercased` below records. - const normalizedFileList = allFileList.map((f) => f.toLowerCase()); - return { - // Copied ONCE per file set, not once per import: `TsResolveContext` wants a - // mutable `Set` and the orchestrator hands us a `ReadonlySet`. The copy is - // not the #1918 hazard because the cache KEY is the caller's original Set. - allFilePaths: new Set(allFilePaths), - allFileList, - normalizedFileList, - // Every suffix of an all-lowercase path is itself lowercase, so the index's - // case-folded map came out a byte-for-byte copy of its exact map — same - // keys, same values, same insertion order — one per `ImportPassCache`, so - // once per adapter per pass. Measured 14.00 MiB at 32 000 paths, 29.8% of - // the retained `ImportPassCache`. The flag drops the copy; it does not change - // what `getInsensitive` answers, because the copy was the identity (see - // `SuffixIndexOptions`). Checked, not assumed: over 474 524 probes on four - // mixed-case corpora — Vue PascalCase plus alias specifiers, case-colliding - // twins, a 600-file deep monorepo, and Unicode paths carrying final sigma, - // dotted-I and sharp-S — the two maps came out byte-identical, the exact - // map was the sole answerer 0 times, and `get(s) || getInsensitive(s)` - // returned the same file 474 524 times out of 474 524. - index: buildSuffixIndex(normalizedFileList, allFileList, { alreadyLowercased: true }), - resolveCache: new Map(), - }; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts b/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts deleted file mode 100644 index 4caf748a78..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Import resolver factory — creates a composable import resolver from - * an ordered list of strategies. - * - * Mirrors the method-extractors/generic.ts and call-extractors/generic.ts - * pattern: declare a config per language, produce a runtime resolver via factory. - * - * Each strategy is tried in order. The first non-null result wins. - * A result with an empty `files` array is treated as "handled but unresolved" - * (stops the chain without producing import edges). - */ - -import type { ImportResolverFn, ImportResolutionConfig } from './types.js'; - -/** - * Create an ImportResolverFn from a declarative config. - * - * Chains strategies in declaration order — first non-null result wins. - * Returns null only if every strategy returns null. - * - * Error behaviour: if a strategy throws, the error propagates immediately - * and remaining strategies are not tried. Strategies are expected to be - * pure data transforms that never throw; any unexpected exception indicates - * a bug in the strategy implementation. - */ -export function createImportResolver(config: ImportResolutionConfig): ImportResolverFn { - const { strategies } = config; - return (rawImportPath, filePath, ctx) => { - for (const strategy of strategies) { - const result = strategy(rawImportPath, filePath, ctx); - if (result) return result; - } - return null; - }; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/rust.ts b/gitnexus/src/core/ingestion/import-resolvers/rust.ts deleted file mode 100644 index 41ac608cf6..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/rust.ts +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Rust module import resolution — internal helpers. - * - * Strategy lives in configs/rust.ts. - * This file contains shared helpers used by the strategy and standard.ts. - */ - -/** - * Resolve Rust use-path to a file (low-level helper). - * Handles crate::, super::, self:: prefixes and :: path separators. - */ -export function resolveRustImportInternal( - currentFile: string, - importPath: string, - allFiles: ReadonlySet, -): string | null { - let rustPath: string; - - if (importPath.startsWith('crate::')) { - // crate:: resolves from src/ directory (standard Rust layout) - rustPath = importPath.slice(7).replace(/::/g, '/'); - - // Try from src/ (standard layout) - const fromSrc = tryRustModulePath('src/' + rustPath, allFiles); - if (fromSrc) return fromSrc; - - // Try from repo root (non-standard) - const fromRoot = tryRustModulePath(rustPath, allFiles); - if (fromRoot) return fromRoot; - - return null; - } - - if (importPath.startsWith('super::')) { - // super:: = parent directory of current file's module - const currentDir = currentFile.split('/').slice(0, -1); - currentDir.pop(); // Go up one level for super:: - rustPath = importPath.slice(7).replace(/::/g, '/'); - const fullPath = [...currentDir, rustPath].join('/'); - return tryRustModulePath(fullPath, allFiles); - } - - if (importPath.startsWith('self::')) { - // self:: = current module's directory - const currentDir = currentFile.split('/').slice(0, -1); - rustPath = importPath.slice(6).replace(/::/g, '/'); - const fullPath = [...currentDir, rustPath].join('/'); - return tryRustModulePath(fullPath, allFiles); - } - - // Bare path without prefix (e.g., from a use in a nested module) - // Convert :: to / and try suffix matching - if (importPath.includes('::')) { - rustPath = importPath.replace(/::/g, '/'); - return tryRustModulePath(rustPath, allFiles); - } - - return null; -} - -/** - * Try to resolve a Rust module path to a file. - * Tries: path.rs, path/mod.rs, and with the last segment stripped - * (last segment might be a symbol name, not a module). - */ -export function tryRustModulePath( - modulePath: string, - allFiles: ReadonlySet, -): string | null { - // Try direct: path.rs - if (allFiles.has(modulePath + '.rs')) return modulePath + '.rs'; - // Try directory: path/mod.rs - if (allFiles.has(modulePath + '/mod.rs')) return modulePath + '/mod.rs'; - // Try path/lib.rs (for crate root) - if (allFiles.has(modulePath + '/lib.rs')) return modulePath + '/lib.rs'; - - // The last segment might be a symbol (function, struct, etc.), not a module. - // Strip it and try again. - const lastSlash = modulePath.lastIndexOf('/'); - if (lastSlash > 0) { - const parentPath = modulePath.substring(0, lastSlash); - if (allFiles.has(parentPath + '.rs')) return parentPath + '.rs'; - if (allFiles.has(parentPath + '/mod.rs')) return parentPath + '/mod.rs'; - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/standard.ts b/gitnexus/src/core/ingestion/import-resolvers/standard.ts deleted file mode 100644 index 4cc4c1c603..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/standard.ts +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Standard import path resolution. - * Handles relative imports, path alias rewriting, and generic suffix matching. - * Used as the fallback when language-specific resolvers don't match. - */ - -import type { SuffixIndex } from './utils.js'; -import { tryResolveWithExtensions, suffixResolve } from './utils.js'; -import { resolveRustImportInternal } from './rust.js'; -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResult, ImportResolverStrategy, ResolveCtx } from './types.js'; -import type { TsconfigPaths } from '../language-config.js'; - -/** Max entries in the resolve cache. Beyond this, entries are evicted. - * 100K entries ≈ 15MB — covers the most common import patterns. */ -export const RESOLVE_CACHE_CAP = 100_000; - -/** - * Resolve an import path to a file path in the repository. - * - * Language-specific preprocessing is applied before the generic resolution: - * - TypeScript/JavaScript: rewrites tsconfig path aliases - * - Rust: converts crate::/super::/self:: to relative paths - * - * Java wildcards and Go package imports are handled by the scope-resolution - * phase because they resolve to multiple files. - */ -export const resolveImportPath = ( - currentFile: string, - importPath: string, - allFiles: Set, - allFileList: readonly string[], - normalizedFileList: readonly string[], - resolveCache: Map, - language: SupportedLanguages, - tsconfigPaths: TsconfigPaths | null, - index?: SuffixIndex, -): string | null => { - const cacheKey = `${currentFile}::${importPath}`; - if (resolveCache.has(cacheKey)) return resolveCache.get(cacheKey) ?? null; - - const cache = (result: string | null): string | null => { - // Evict oldest 20% when cap is reached instead of clearing all - if (resolveCache.size >= RESOLVE_CACHE_CAP) { - const evictCount = Math.floor(RESOLVE_CACHE_CAP * 0.2); - const iter = resolveCache.keys(); - for (let i = 0; i < evictCount; i++) { - const key = iter.next().value; - if (key !== undefined) resolveCache.delete(key); - } - } - resolveCache.set(cacheKey, result); - return result; - }; - - // ---- TypeScript/JavaScript: rewrite path aliases ---- - if ( - (language === SupportedLanguages.TypeScript || language === SupportedLanguages.JavaScript) && - tsconfigPaths && - !importPath.startsWith('.') - ) { - for (const [aliasPrefix, targetPrefix] of tsconfigPaths.aliases) { - if (importPath.startsWith(aliasPrefix)) { - const remainder = importPath.slice(aliasPrefix.length); - // Build the rewritten path relative to baseUrl - const rewritten = - tsconfigPaths.baseUrl === '.' - ? targetPrefix + remainder - : tsconfigPaths.baseUrl + '/' + targetPrefix + remainder; - - // Try direct resolution from repo root - const resolved = tryResolveWithExtensions(rewritten, allFiles); - if (resolved) return cache(resolved); - - // ESM fallback: strip .js/.jsx/.mjs/.cjs and retry with TS equivalents - const strippedAlias = stripJsExtension(rewritten); - if (strippedAlias !== null) { - const esmResolved = tryResolveWithExtensions(strippedAlias, allFiles); - if (esmResolved) return cache(esmResolved); - } - - // Try suffix matching as fallback - const parts = rewritten.split('/').filter(Boolean); - const suffixResult = suffixResolve(parts, normalizedFileList, allFileList, index); - if (suffixResult) return cache(suffixResult); - } - } - } - - // ---- Rust: convert module path syntax to file paths ---- - if (language === SupportedLanguages.Rust) { - // Handle grouped imports: use crate::module::{Foo, Bar, Baz} - // Extract the prefix path before ::{...} and resolve the module, not the symbols - let rustImportPath = importPath; - const braceIdx = importPath.indexOf('::{'); - if (braceIdx !== -1) { - rustImportPath = importPath.substring(0, braceIdx); - } else if (importPath.startsWith('{') && importPath.endsWith('}')) { - // Top-level grouped imports: use {crate::a, crate::b} - // Iterate each part and return the first that resolves. This function returns a single - // string, so callers that need ALL edges must intercept before reaching here (the - // scope-resolution phase handles Rust grouped-import blocks). This fallback - // handles any path that reaches resolveImportPath directly. - const inner = importPath.slice(1, -1); - const parts = inner - .split(',') - .map((p) => p.trim()) - .filter(Boolean); - for (const part of parts) { - const partResult = resolveRustImportInternal(currentFile, part, allFiles); - if (partResult) return cache(partResult); - } - return cache(null); - } - - const rustResult = resolveRustImportInternal(currentFile, rustImportPath, allFiles); - if (rustResult) return cache(rustResult); - // Fall through to generic resolution if Rust-specific didn't match - } - - // ---- Generic relative import resolution (./ and ../) ---- - const currentDir = currentFile.split('/').slice(0, -1); - const parts = importPath.split('/'); - - for (const part of parts) { - if (part === '.') continue; - if (part === '..') { - currentDir.pop(); - } else { - currentDir.push(part); - } - } - - const basePath = currentDir.join('/'); - - if (importPath.startsWith('.')) { - const resolved = tryResolveWithExtensions(basePath, allFiles); - if (resolved) return cache(resolved); - - // TypeScript ESM: imports use .js/.jsx/.mjs/.cjs but source files are - // .ts/.tsx/.mts/.cts. Strip the JS-family extension and re-resolve. - if (language === SupportedLanguages.TypeScript || language === SupportedLanguages.JavaScript) { - const stripped = stripJsExtension(basePath); - if (stripped !== null) { - return cache(tryResolveWithExtensions(stripped, allFiles)); - } - } - - return cache(null); - } - - // ---- Generic package/absolute import resolution (suffix matching) ---- - // Java wildcards are handled by the scope-resolution phase, not here; this - // resolver returns null for `.*` so it never produces a single-file match. - if (importPath.endsWith('.*')) { - return cache(null); - } - - // C/C++ includes use actual file paths (e.g. "animal.h") — don't convert dots to slashes - const isCpp = language === SupportedLanguages.C || language === SupportedLanguages.CPlusPlus; - const pathLike = importPath.includes('/') || isCpp ? importPath : importPath.replace(/\./g, '/'); - const pathParts = pathLike.split('/').filter(Boolean); - - const resolved = suffixResolve(pathParts, normalizedFileList, allFileList, index); - return cache(resolved); -}; - -// ============================================================================ -// Per-language dispatch functions (moved from import-resolution.ts) -// ============================================================================ - -/** - * Standard single-file resolution (TS/JS/C/C++ and fallback for other languages). - * Handles relative imports, tsconfig path aliases, and suffix matching. - */ -export function resolveStandard( - rawImportPath: string, - filePath: string, - ctx: ResolveCtx, - language: SupportedLanguages, -): ImportResult { - const resolvedPath = resolveImportPath( - filePath, - rawImportPath, - ctx.allFilePaths, - ctx.allFileList, - ctx.normalizedFileList, - ctx.resolveCache, - language, - ctx.configs.tsconfigPaths, - ctx.index, - ); - return resolvedPath ? { kind: 'files', files: [resolvedPath] } : null; -} - -// ============================================================================ -// Strategy factory — composable hook for ImportResolutionConfig -// ============================================================================ - -/** Create a reusable standard-resolution strategy for a given language. */ -export function createStandardStrategy(language: SupportedLanguages): ImportResolverStrategy { - return (raw, fp, ctx) => resolveStandard(raw, fp, ctx, language); -} - -// ============================================================================ -// ESM extension helpers -// ============================================================================ - -/** JS-family extensions that TypeScript ESM maps to TS equivalents. */ -const JS_EXTENSION_PATTERN = /\.(js|jsx|mjs|cjs)$/; - -/** - * Strip a JS-family extension from a path, returning the stem. - * Returns `null` if the path does not end with a JS-family extension. - */ -export function stripJsExtension(path: string): string | null { - const match = JS_EXTENSION_PATTERN.exec(path); - return match ? path.slice(0, -match[0].length) : null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/types.ts b/gitnexus/src/core/ingestion/import-resolvers/types.ts deleted file mode 100644 index 081972b77d..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/types.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Import resolution types — shared across all per-language resolvers. - * - * Extracted from import-resolution.ts to co-locate types with their consumers. - */ - -import type { ImportConfigs } from '../language-config.js'; -import type { SuffixIndex } from './utils.js'; -import type { SupportedLanguages } from 'gitnexus-shared'; - -/** - * Result of resolving an import via language-specific dispatch. - * - 'files': resolved to one or more files -> add to ImportMap - * - 'package': resolved to a directory -> add graph edges + store dirSuffix in PackageMap - * - null: no resolution (external dependency, etc.) - */ -export type ImportResult = - | { kind: 'files'; files: string[] } - | { kind: 'package'; files: string[]; dirSuffix: string } - | null; - -/** Pre-built lookup structures for import resolution. Build once, reuse across chunks. */ -export interface ImportResolutionContext { - allFilePaths: Set; - allFileList: string[]; - normalizedFileList: string[]; - index: SuffixIndex; - resolveCache: Map; -} - -/** Full context for import resolution: file lookups + language configs. */ -export interface ResolveCtx extends ImportResolutionContext { - configs: ImportConfigs; -} - -/** Per-language import resolver -- function alias matching ExportChecker/CallRouter pattern. */ -export type ImportResolverFn = ( - rawImportPath: string, - filePath: string, - resolveCtx: ResolveCtx, -) => ImportResult; - -/** - * A single import resolution strategy — one step in a composable chain. - * Same signature as ImportResolverFn. Returns null to let the next strategy - * in the chain try; returns a result (even with empty files) to stop the chain. - */ -export type ImportResolverStrategy = ImportResolverFn; - -/** - * Declarative config for composable import resolution — mirrors the - * MethodExtractionConfig / CallExtractionConfig pattern. - * - * Each language declares an ordered list of strategies to try. - * The factory (`createImportResolver`) chains them: first non-null result wins. - */ -export interface ImportResolutionConfig { - /** - * Documentation-only metadata identifying which language this config serves. - * **Not used by `createImportResolver`** — the factory only iterates `strategies`. - * Useful for logging, debugging, and compile-time exhaustiveness checks when - * mapping `SupportedLanguages → ImportResolutionConfig` in language providers. - */ - readonly language: SupportedLanguages; - readonly strategies: readonly ImportResolverStrategy[]; -} diff --git a/gitnexus/src/core/ingestion/import-target-adapter.ts b/gitnexus/src/core/ingestion/import-target-adapter.ts deleted file mode 100644 index 80a5a265e5..0000000000 --- a/gitnexus/src/core/ingestion/import-target-adapter.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Bridge between CLI-package per-language `ImportResolverFn`s and the - * shared `FinalizeHooks.resolveImportTarget` contract - * (RFC §5.2; Ring 2 PKG #922). - * - * The shared finalize algorithm (#915) asks one question: - * - * resolveImportTarget(targetRaw, fromFile, workspaceIndex): string | null - * - * The CLI already has 16 language-specific resolvers satisfying a - * richer signature: - * - * ImportResolverFn(rawImportPath, filePath, resolveCtx): ImportResult - * - * This module builds a dispatch adapter — one FinalizeHook implementation - * that looks up the file's language from its path and delegates to the - * right per-language resolver. Callers package per-language resolvers + - * a shared `ResolveCtx` into an opaque `ImportTargetWorkspace` and pass - * it as `workspaceIndex` to `finalizeScopeModel`. - * - * ## What's deliberately NOT here - * - * - **Re-implementation of any per-language resolver.** We wrap the - * existing `importResolver` field on each `LanguageProvider` — the - * same code path the legacy DAG uses today. - * - **Dynamic-import handling.** The shared finalize algorithm short- - * circuits `ParsedImport { kind: 'dynamic-unresolved' }` before - * calling `resolveImportTarget`, so the adapter never sees those. - * - **`importPathPreprocessor`.** Preprocessing belongs inside the - * provider's `interpretImport` hook (which writes the final - * `ParsedImport.targetRaw`). By the time finalize passes a - * `targetRaw` to this adapter, it is the string the provider wants - * resolved verbatim. - */ - -import { - getLanguageFromFilename, - type SupportedLanguages, - type WorkspaceIndex, -} from 'gitnexus-shared'; -import type { ImportResolverFn, ImportResult, ResolveCtx } from './import-resolvers/types.js'; -import type { LanguageProvider } from './language-provider.js'; - -/** A single language's resolver bundled with the context it needs. */ -export interface LanguageResolverEntry { - readonly resolver: ImportResolverFn; - readonly ctx: ResolveCtx; -} - -/** - * The opaque `workspaceIndex` shape recognized by - * `resolveImportTargetAcrossLanguages`. Built once per ingestion run via - * `buildImportTargetWorkspace`, threaded through `finalizeScopeModel`. - */ -export interface ImportTargetWorkspace { - readonly perLanguage: ReadonlyMap; -} - -/** - * Build the workspace index from a map of language → provider. Providers - * whose `importResolver` is absent are silently skipped (no language will - * ever hit that branch at dispatch time). - * - * The `resolveCtx` is shared across all languages. Callers assemble it - * once per run (the existing pipeline already does this for the legacy - * DAG) and hand it to both the legacy resolution path and this factory. - */ -export function buildImportTargetWorkspace( - providers: ReadonlyMap, - resolveCtx: ResolveCtx, -): ImportTargetWorkspace { - const perLanguage = new Map(); - for (const [lang, provider] of providers) { - if (provider.importResolver === undefined) continue; - perLanguage.set(lang, { resolver: provider.importResolver, ctx: resolveCtx }); - } - return { perLanguage }; -} - -/** - * The FinalizeHooks-compatible implementation. Dispatches on `fromFile`'s - * extension → per-language resolver. Returns the first resolved file, - * or `null` if the resolver returns `null` or doesn't know about the - * language. - * - * Picks the first entry of `files[]` for both `'files'` and `'package'` - * result kinds — the legacy pipeline uses the whole array, but the - * shared `finalize()` hook contract is single-file. If the workspace - * later needs richer semantics (split-target packages), this is the - * single site to extend. - */ -export function resolveImportTargetAcrossLanguages( - targetRaw: string, - fromFile: string, - workspaceIndex: WorkspaceIndex, -): string | null { - const workspace = workspaceIndex as ImportTargetWorkspace | undefined; - if (workspace === undefined || workspace.perLanguage === undefined) return null; - - const lang = getLanguageFromFilename(fromFile); - if (lang === null) return null; - - const entry = workspace.perLanguage.get(lang); - if (entry === undefined) return null; - - let result: ImportResult; - try { - result = entry.resolver(targetRaw, fromFile, entry.ctx); - } catch { - // Existing resolvers can throw on malformed inputs (e.g., Python - // relative paths above the workspace root). Swallow — the shared - // algorithm treats a null here as `linkStatus: 'unresolved'`, which - // is the right fallback. - return null; - } - if (result === null) return null; - - // Both `files` and `package` variants expose a `files` array; the - // package variant also carries `dirSuffix` which we ignore at the - // FinalizeHook boundary (single-file contract). Legacy consumers - // continue to see the full result via `importResolver` directly. - const first = result.files[0]; - return first ?? null; -} diff --git a/gitnexus/src/core/ingestion/language-config.ts b/gitnexus/src/core/ingestion/language-config.ts index 1c8bafa03a..fdc3ea7bc5 100644 --- a/gitnexus/src/core/ingestion/language-config.ts +++ b/gitnexus/src/core/ingestion/language-config.ts @@ -21,12 +21,6 @@ export interface TsconfigPaths { baseUrl: string; } -/** Go module config parsed from go.mod */ -export interface GoModuleConfig { - /** Module path (e.g., "github.com/user/repo") */ - modulePath: string; -} - /** PHP Composer PSR-4 autoload config */ export interface ComposerConfig { /** Map of namespace prefix -> directory (e.g., "App\\" -> "app/") */ @@ -161,11 +155,7 @@ export interface CSharpProjectScan { readonly truncated: boolean; } -/** Project the one-pass {@link CSharpProjectScan} into the - * {@link CSharpNamespaceEvidence} both import-resolution legs thread to the - * #1881 gate — one shape, two carriers (`ImportConfigs.csharpNamespaces` for - * the legacy DAG, `CsharpResolutionConfig.namespaces` for the scope resolver). - * Keeps the field mapping in one place so the two carriers can't drift. */ +/** Project a workspace scan into the namespace evidence used by import resolution. */ export function csharpScanToEvidence(scan: CSharpProjectScan): CSharpNamespaceEvidence { return { declaredNamespaces: scan.declaredNamespaces, @@ -410,26 +400,6 @@ export async function loadTsconfigPaths(repoRoot: string): Promise { - try { - const goModPath = path.join(repoRoot, 'go.mod'); - const content = await fs.readFile(goModPath, 'utf-8'); - const match = content.match(/^module\s+(\S+)/m); - if (match) { - if (isDev) { - logger.info(`📦 Loaded Go module path: ${match[1]}`); - } - return { modulePath: match[1] }; - } - } catch { - // No go.mod - } - return null; -} - /** Parse composer.json to extract PSR-4 autoload mappings (including autoload-dev). */ export async function loadComposerConfig(repoRoot: string): Promise { try { @@ -466,9 +436,8 @@ const CSHARP_ROOT_NAMESPACE_RE = /\s*([^<]+)\s*<\/RootNamespace>/ // scanner shared with the scope-resolution namespace-siblings pass // (`extractCsharpStructureViaScanner`), not a bare regex: a regex matches // `namespace` inside comments and string literals, seeding the #1881 gate -// with phantom namespaces. Imported lazily (and memoized) so the always-on -// `loadImportConfigs` path — every repo, every language — doesn't eagerly -// pull tree-sitter-c-sharp in via `namespace-siblings.ts` → `query.ts`. +// with phantom namespaces. Imported lazily (and memoized) so loading unrelated +// configs does not pull tree-sitter-c-sharp in via namespace-siblings.ts. let csharpScannerFactoryPromise: Promise<() => CsharpStructureLineScanner> | undefined; function getCsharpStructureScannerFactory(): Promise<() => CsharpStructureLineScanner> { if (csharpScannerFactoryPromise === undefined) { @@ -1925,10 +1894,7 @@ export function zigPackageFor( * * Called from `ScopeResolver.loadResolutionConfig`, which the orchestrator runs * once per LANGUAGE workspace pass — so the walk happens only for repos that - * actually contain Zig. `loadImportConfigs`, which runs unconditionally for - * every repo, keeps calling `loadZigBuildConfig` for the root package alone; - * that is the same split TypeScript already has between the cheap - * `loadTsconfigPaths` and the repo-walking `loadTsconfigIndex`. + * actually contain Zig. */ export async function loadZigWorkspaceIndex(repoRoot: string): Promise { const dirs = await findZigPackageDirs(repoRoot); @@ -2611,45 +2577,3 @@ export function parseZigBuildZon(raw: string): ZigBuildZonConfig | null { } return { pathDeps }; } - -// ============================================================================ -// BUNDLED CONFIG LOADER -// ============================================================================ - -/** - * Bundled language-specific configs loaded once per ingestion run — the - * result of {@link loadImportConfigs}, and every field's type is declared - * above in this module. - * - * It lives here rather than in `import-resolvers/types.ts` (its consumer, via - * `ResolveCtx`) so the dependency runs one way: the import-resolver types - * import this bundle, and this module imports nothing from them. Homing the - * producer's result type with the producer also keeps `import-resolvers/ - * types.ts` free of per-language names. - */ -export interface ImportConfigs { - tsconfigPaths: TsconfigPaths | null; - goModule: GoModuleConfig | null; - composerConfig: ComposerConfig | null; - swiftPackageConfig: SwiftPackageConfig | null; - csharpConfigs: CSharpProjectConfig[]; - /** In-repo namespace evidence gating C# suffix-fallback resolution (#1881). */ - csharpNamespaces?: CSharpNamespaceEvidence; - /** Zig `.path` deps from build.zig.zon. Optional so call sites that - * hand-build ImportConfigs (tests) don't have to supply it. */ - zigBuildZon?: ZigBuildZonConfig | null; -} - -/** Load all language-specific configs once for an ingestion run. */ -export async function loadImportConfigs(repoRoot: string): Promise { - const csharpScan = await scanCSharpProject(repoRoot); - return { - tsconfigPaths: await loadTsconfigPaths(repoRoot), - goModule: await loadGoModulePath(repoRoot), - composerConfig: await loadComposerConfig(repoRoot), - swiftPackageConfig: await loadSwiftPackageConfig(repoRoot), - csharpConfigs: csharpScan.configs, - csharpNamespaces: csharpScanToEvidence(csharpScan), - zigBuildZon: await loadZigBuildConfig(repoRoot), - }; -} diff --git a/gitnexus/src/core/ingestion/language-provider.ts b/gitnexus/src/core/ingestion/language-provider.ts index e8acc6f1ce..9f1f61fff4 100644 --- a/gitnexus/src/core/ingestion/language-provider.ts +++ b/gitnexus/src/core/ingestion/language-provider.ts @@ -35,7 +35,6 @@ import type { ExportChecker } from './export-detection.js'; import type { FieldExtractor } from './field-extractor.js'; import type { MethodExtractor } from './method-types.js'; import type { VariableExtractor } from './variable-types.js'; -import type { ImportResolverFn } from './import-resolvers/types.js'; import type { SyntaxNode } from './utils/ast-helpers.js'; import type { CfgVisitor } from './cfg/types.js'; import type { CollectedCfgs } from './cfg/collect.js'; @@ -354,8 +353,6 @@ interface LanguageProviderConfig { readonly typeConfig: LanguageTypeConfig; /** Export detection: is this AST node a public/exported symbol? */ readonly exportChecker: ExportChecker; - /** Import resolution: resolves raw import path to file system path */ - readonly importResolver: ImportResolverFn; // ── Calls & Imports (optional) ──────────────────────────────────── /** Call routing for languages that express imports/heritage as calls (e.g., Ruby). diff --git a/gitnexus/src/core/ingestion/languages/c-cpp.ts b/gitnexus/src/core/ingestion/languages/c-cpp.ts index c6e01ac6ef..d436fa4fde 100644 --- a/gitnexus/src/core/ingestion/languages/c-cpp.ts +++ b/gitnexus/src/core/ingestion/languages/c-cpp.ts @@ -17,8 +17,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as cCppConfig } from '../type-extractors/c-cpp.js'; import { cCppExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { cImportConfig, cppImportConfig } from '../import-resolvers/configs/c-cpp.js'; import { C_QUERIES, CPP_QUERIES } from '../tree-sitter-queries.js'; /** @@ -397,7 +395,6 @@ export const cProvider = defineLanguage({ `, typeConfig: cCppConfig, exportChecker: cCppExportChecker, - importResolver: createImportResolver(cImportConfig), callExtractor: createCallExtractor(cCallConfig), fieldExtractor: createFieldExtractor(cFieldConfig), methodExtractor: createMethodExtractor({ @@ -492,7 +489,6 @@ export const cppProvider = defineLanguage({ preprocessSource: stripUeMacros, typeConfig: cCppConfig, exportChecker: cCppExportChecker, - importResolver: createImportResolver(cppImportConfig), mroStrategy: 'leftmost-base', callExtractor: createCallExtractor(cppCallConfig), fieldExtractor: createFieldExtractor(cppFieldConfig), diff --git a/gitnexus/src/core/ingestion/languages/c/import-target.ts b/gitnexus/src/core/ingestion/languages/c/import-target.ts index 07f79df3c1..068041440f 100644 --- a/gitnexus/src/core/ingestion/languages/c/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/c/import-target.ts @@ -1,5 +1,5 @@ import { dirname, join } from 'path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { collapseRepoPath, nearestScope, diff --git a/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts index 60fbb085db..d74a4dc00e 100644 --- a/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts @@ -13,7 +13,7 @@ import { } from './resolution-config.js'; import { expandCWildcardNames, isStaticName, clearStaticNames } from './static-linkage.js'; import { applyCStaticLinkageSideChannel } from './capture-side-channel.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * Per-pass memo of the augmented `#include`-resolution file set @@ -35,8 +35,7 @@ import { perFileSet } from '../../import-resolvers/per-file-set.js'; * byte-identical. The augmented set's IDENTITY is load-bearing downstream — * C++ delegates to `resolveCImportTarget`, whose `suffixIndex` memo is keyed on * exactly this set — so one memo shared across the two languages would hand - * each the other's index. Same builder-shared/memo-separate rule as - * `import-resolvers/pass-cache.ts`. + * each the other's index. Sharing a builder must not share its memo. */ const augmentedFilePathsFor = perFileSet((allFilePaths: ReadonlySet) => perFileSet((headerPaths: ReadonlySet): ReadonlySet => { diff --git a/gitnexus/src/core/ingestion/languages/c/static-linkage.ts b/gitnexus/src/core/ingestion/languages/c/static-linkage.ts index a81398354d..ebc461d39d 100644 --- a/gitnexus/src/core/ingestion/languages/c/static-linkage.ts +++ b/gitnexus/src/core/ingestion/languages/c/static-linkage.ts @@ -1,5 +1,5 @@ import type { ParsedFile, ScopeId, SymbolDefinition } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * Per-file set of function names declared with `static` storage class. diff --git a/gitnexus/src/core/ingestion/languages/cobol.ts b/gitnexus/src/core/ingestion/languages/cobol.ts index ea754f1e9a..08b5b66e5c 100644 --- a/gitnexus/src/core/ingestion/languages/cobol.ts +++ b/gitnexus/src/core/ingestion/languages/cobol.ts @@ -34,7 +34,6 @@ export const cobolProvider = defineLanguage({ extractParameter: () => null, }, exportChecker: () => false, - importResolver: () => null, rename: cobolRenameProvider, // Standalone source provider: program regions preserve paragraph fallthrough diff --git a/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts b/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts index 7b0bde4c41..d7901e7be4 100644 --- a/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts +++ b/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts @@ -24,7 +24,7 @@ * per-name arrays, so a pass still scans the set once. */ import path from 'node:path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; const COPYBOOK_EXTENSIONS = new Set(['.cpy', '.copybook']); const COBOL_SOURCE_EXTENSIONS = new Set(['.cbl', '.cob', '.cobol']); diff --git a/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts b/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts index e11f32b8d4..cfa83a9f0c 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts @@ -1,5 +1,5 @@ import type { ParsedFile, Scope, ScopeId, SymbolDefinition } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { isCppInlineNamespaceScope } from './inline-namespaces.js'; /** diff --git a/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts index 8dc8752d80..ec6921112c 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts @@ -57,7 +57,7 @@ import { resolveCppReceiverMember, } from './member-lookup.js'; import { stripCppSpecifiers } from './interpret.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { clearCppUsingDeclarations, populateCppIncludedUsingClaims, @@ -85,8 +85,8 @@ const CPP_SIMPLE_POINTEE_RE = /^[A-Za-z_]\w*$/; * (Twin of the C resolver's `augmentedFilePathsFor`.) The two memos stay * SEPARATE deliberately. C++ delegates to `resolveCImportTarget`, whose * `suffixIndex` memo is keyed on the augmented set, so a single memo shared - * with C would hand each language the other's index — same - * builder-shared/memo-separate rule as `import-resolvers/pass-cache.ts`. + * with C would hand each language the other's index. Sharing a builder must + * not share its memo. */ const augmentedFilePathsFor = perFileSet((allFilePaths: ReadonlySet) => perFileSet((headerPaths: ReadonlySet): ReadonlySet => { diff --git a/gitnexus/src/core/ingestion/languages/csharp.ts b/gitnexus/src/core/ingestion/languages/csharp.ts index 90fbc7c287..6fccd810f9 100644 --- a/gitnexus/src/core/ingestion/languages/csharp.ts +++ b/gitnexus/src/core/ingestion/languages/csharp.ts @@ -13,8 +13,6 @@ import { csharpClassConfig } from '../class-extractors/configs/csharp.js'; import { defineLanguage } from '../language-provider.js'; import { typeConfig as csharpConfig } from '../type-extractors/csharp.js'; import { csharpExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { csharpImportConfig } from '../import-resolvers/configs/csharp.js'; import { CSHARP_QUERIES } from '../tree-sitter-queries.js'; import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; @@ -195,7 +193,6 @@ export const csharpProvider = defineLanguage({ `, typeConfig: csharpConfig, exportChecker: csharpExportChecker, - importResolver: createImportResolver(csharpImportConfig), mroStrategy: 'implements-split', callExtractor: createCallExtractor(csharpCallConfig), fieldExtractor: createFieldExtractor(csharpFieldConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts b/gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts similarity index 93% rename from gitnexus/src/core/ingestion/import-resolvers/csharp.ts rename to gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts index e8d6fdf7ab..fd7d7f2e47 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts @@ -1,16 +1,17 @@ /** * C# namespace import resolution — internal helpers. * - * Strategy lives in configs/csharp.ts. + * Used by the C# ScopeResolver.resolveImportTarget hook. * This file contains shared helpers for namespace-based resolution. */ -import { perFileSet } from './per-file-set.js'; -import { getWorkspaceFileIndex } from './workspace-file-index.js'; -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; -import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../language-config.js'; -import { csharpSuffixFallbackAllowed } from '../csharp-namespace-gate.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../../language-config.js'; +import { csharpSuffixFallbackAllowed } from './namespace-gate.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** * Directory index backing the namespace-directory fallback below (step 3). @@ -397,40 +398,6 @@ export function resolveCSharpImportInternal( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } - -/** - * Compute the directory suffix for a C# namespace import (for PackageMap). - * Returns a suffix like "/ProjectDir/Models/" or null if no config matches. - */ -export function resolveCSharpNamespaceDir( - importPath: string, - csharpConfigs: CSharpProjectConfig[], -): string | null { - const namespacePath = importPath.replace(/\./g, '/'); - - for (const config of csharpConfigs) { - const nsPath = config.rootNamespace.replace(/\./g, '/'); - let relative: string; - if (namespacePath.startsWith(nsPath + '/')) { - relative = namespacePath.slice(nsPath.length + 1); - } else if (namespacePath === nsPath) { - relative = ''; - } else { - continue; - } - - const dirPrefix = config.projectDir - ? relative - ? config.projectDir + '/' + relative - : config.projectDir - : relative; - - if (!dirPrefix) continue; - return '/' + dirPrefix + '/'; - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/languages/csharp/import-target.ts b/gitnexus/src/core/ingestion/languages/csharp/import-target.ts index 68f1e484d5..424b3d6cb7 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/import-target.ts @@ -21,18 +21,18 @@ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../../language-config.js'; -import { resolveCSharpImportInternal } from '../../import-resolvers/csharp.js'; +import { resolveCSharpImportInternal } from './import-helpers.js'; import { getWorkspaceFileIndex, type WorkspaceFileIndex, -} from '../../import-resolvers/workspace-file-index.js'; +} from '../../utils/workspace-file-index.js'; import { buildPackageDirIndex, firstFileDirectlyInPkgDir, type PackageDirIndex, -} from '../../import-resolvers/package-dir-index.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { csharpSuffixFallbackAllowed } from '../../csharp-namespace-gate.js'; +} from '../../utils/package-dir-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { csharpSuffixFallbackAllowed } from './namespace-gate.js'; export interface CsharpResolveContext { readonly fromFile: string; @@ -44,7 +44,7 @@ export interface CsharpResolveContext { /** * Namespace-directory index over the `.cs` files, memoized on the Set's * identity. Feeds `firstFileDirectlyInPkgDir` (in - * `import-resolvers/package-dir-index.ts`), which the no-csproj path calls once + * `utils/package-dir-index.ts`), which the no-csproj path calls once * for the direct match and then up to once per stripped namespace prefix. */ const getCsharpDirIndex = perFileSet( @@ -74,8 +74,7 @@ export function resolveCsharpImportTarget( evidence, ); if (fromCsproj.length > 0) return fromCsproj[0]!; - // csproj configs are authoritative: mirror legacy `configs/csharp.ts`, - // which returns an empty result to STOP the chain. Falling through to the + // csproj configs are authoritative. Falling through to the // ungated `resolveDirectMatch` would re-introduce the BCL→local match the // internal resolver's gate just suppressed (#1881 parity, #2). return null; @@ -87,10 +86,8 @@ export function resolveCsharpImportTarget( // Gate the WHOLE no-csproj path on declared in-repo namespaces — the direct // path/suffix match INCLUDED — so a BCL using can't resolve to a // coincidentally path-aligned local file (e.g. `Legacy/System/Threading/ - // Tasks.cs` satisfying `using System.Threading.Tasks;`). Running the gate - // before `resolveDirectMatch` mirrors the legacy leg's gate-first ordering - // (`import-resolvers/configs/csharp.ts`), so the two legs are equivalent - // (#1881 parity, Codex F2). The gate keeps its fail-open for + // Tasks.cs` satisfying `using System.Threading.Tasks;`). The gate runs + // before `resolveDirectMatch` and keeps its fail-open for // undefined/truncated evidence, so legitimate edges in unscanned repos are // unaffected. if (!csharpSuffixFallbackAllowed(targetRaw, evidence)) { diff --git a/gitnexus/src/core/ingestion/csharp-namespace-gate.ts b/gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts similarity index 93% rename from gitnexus/src/core/ingestion/csharp-namespace-gate.ts rename to gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts index df806bf2b7..ca8913aad2 100644 --- a/gitnexus/src/core/ingestion/csharp-namespace-gate.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts @@ -3,13 +3,11 @@ * (e.g. `System.Threading.Tasks`) can't match a coincidentally-named local * file (#1881). * - * Lives in the shared `ingestion/` layer — NOT under `languages/csharp/` — so - * BOTH the registry-primary scope resolver (`languages/csharp/import-target.ts`) - * and the legacy DAG resolver (`import-resolvers/csharp.ts`) can import it - * without an `import-resolvers/ -> languages/` dependency inversion (#5). + * Shared by this provider's import-target adapter and namespace-directory + * helpers. The legacy DAG resolver has been removed. */ -import type { CSharpNamespaceEvidence } from './language-config.js'; +import type { CSharpNamespaceEvidence } from '../../language-config.js'; /** * Top-level namespace segments that clearly belong to the BCL / runtime / a diff --git a/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts b/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts index 714be8c1fc..63dbb3a7a2 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts @@ -3,7 +3,7 @@ * * Loaded once per analyze pass via `csharpScopeResolver.loadResolutionConfig` * and threaded into `resolveCsharpImportTarget`. The pure gate predicates live - * in `../../csharp-namespace-gate.ts` (shared with the legacy DAG resolver). + * in `./namespace-gate.ts`. */ import { diff --git a/gitnexus/src/core/ingestion/languages/dart.ts b/gitnexus/src/core/ingestion/languages/dart.ts index d6eafd701e..16f15307d9 100644 --- a/gitnexus/src/core/ingestion/languages/dart.ts +++ b/gitnexus/src/core/ingestion/languages/dart.ts @@ -23,8 +23,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as dartConfig } from '../type-extractors/dart.js'; import { dartExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { dartImportConfig } from '../import-resolvers/configs/dart.js'; import { DART_QUERIES } from '../tree-sitter-queries.js'; import { createDartCfgVisitor } from '../cfg/visitors/dart.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -124,7 +122,6 @@ export const dartProvider = defineLanguage({ treeSitterQueries: DART_QUERIES, typeConfig: dartConfig, exportChecker: dartExportChecker, - importResolver: createImportResolver(dartImportConfig), callExtractor: createCallExtractor(dartCallConfig), fieldExtractor: createFieldExtractor(dartFieldConfig), methodExtractor: createMethodExtractor(dartMethodConfig), diff --git a/gitnexus/src/core/ingestion/languages/dart/import-target.ts b/gitnexus/src/core/ingestion/languages/dart/import-target.ts index 602ea5ce49..e4c7f80b44 100644 --- a/gitnexus/src/core/ingestion/languages/dart/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/dart/import-target.ts @@ -12,7 +12,7 @@ * `targetRaw` arrives already quote-stripped from `interpretDartImport`. */ -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { DART_HERITAGE_PREFIX } from './interpret.js'; import type { DartPackageConfig } from './package-config.js'; import { DART_PACKAGE_SCHEME, dartPackageImportName } from './package-uri.js'; diff --git a/gitnexus/src/core/ingestion/languages/go.ts b/gitnexus/src/core/ingestion/languages/go.ts index 3f2502a320..dd6ea6895f 100644 --- a/gitnexus/src/core/ingestion/languages/go.ts +++ b/gitnexus/src/core/ingestion/languages/go.ts @@ -17,8 +17,6 @@ import { createGoCfgVisitor } from '../cfg/visitors/go.js'; import { defineLanguage } from '../language-provider.js'; import { typeConfig as goConfig } from '../type-extractors/go.js'; import { goExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { goImportConfig } from '../import-resolvers/configs/go.js'; import { GO_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -141,7 +139,6 @@ export const goProvider = defineLanguage({ treeSitterQueries: GO_QUERIES, typeConfig: goConfig, exportChecker: goExportChecker, - importResolver: createImportResolver(goImportConfig), callExtractor: createCallExtractor(goCallConfig), fieldExtractor: createFieldExtractor(goFieldConfig), methodExtractor: createMethodExtractor(goMethodConfig), diff --git a/gitnexus/src/core/ingestion/languages/go/import-target.ts b/gitnexus/src/core/ingestion/languages/go/import-target.ts index c41c7d18aa..1d2c133714 100644 --- a/gitnexus/src/core/ingestion/languages/go/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/go/import-target.ts @@ -4,8 +4,8 @@ import { filesInDir, sortedRootFiles, type PackageDirIndex, -} from '../../import-resolvers/package-dir-index.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +} from '../../utils/package-dir-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { isGoWorkspaceConfig, locateGoImport } from './workspace-config.js'; /** @@ -80,7 +80,7 @@ function isGoPackageFile(normalized: string): boolean { * * The orchestrator hands the same Set to every import in a pass, so the index * is built once per run. `resolveGoImportTarget` must therefore never copy the - * Set before this point — see `import-resolvers/workspace-file-index.ts`. + * Set before this point — see `utils/workspace-file-index.ts`. */ const getGoPackageIndex = perFileSet( (allFilePaths: ReadonlySet): PackageDirIndex => diff --git a/gitnexus/src/core/ingestion/languages/go/workspace-config.ts b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts index 9c3dfa6ecb..a9dc25c6e3 100644 --- a/gitnexus/src/core/ingestion/languages/go/workspace-config.ts +++ b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts @@ -1,14 +1,9 @@ /** * Go module discovery: every `go.mod` and `go.work` in the repository. * - * `loadGoModulePath` reads only the ROOT `go.mod`. A monorepo with one module - * per service (`services/orders/go.mod`), a root module with nested modules - * (`tools/go.mod`, k8s-style `staging/`), or a repo with no root module at all - * then answers every import from the wrong place: with no root `go.mod` the - * GOPATH suffix match runs, so two modules' `internal/repository` both answer - * `…/internal/repository`; with one, imports of a nested module are "not ours" - * and drop, while the root module's own imports match any directory ENDING in - * the package path — the nested modules' included. + * Every module needs its own root: services may have separate `go.mod` files, + * and nested modules own subtrees that an enclosing module cannot import as + * its own packages. * * Go itself resolves an import against modules, not directory names: * diff --git a/gitnexus/src/core/ingestion/languages/import-candidates.ts b/gitnexus/src/core/ingestion/languages/import-candidates.ts new file mode 100644 index 0000000000..61b35c2cad --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/import-candidates.ts @@ -0,0 +1,51 @@ +/** Ordered fallback candidates supplied by import-resolution providers. */ +export const EXTENSIONS = [ + '', + // TypeScript/JavaScript + '.tsx', + '.ts', + '.mts', + '.cts', + '.jsx', + '.js', + '.mjs', + '.cjs', + '.vue', + '/index.tsx', + '/index.ts', + '/index.jsx', + '/index.js', + // Python + '.py', + '/__init__.py', + // Java + '.java', + // Kotlin + '.kt', + '.kts', + // C/C++ + '.c', + '.h', + '.cpp', + '.hpp', + '.cc', + '.cxx', + '.hxx', + '.hh', + '.cu', + '.cuh', + // C# + '.cs', + // Go + '.go', + // Rust + '.rs', + '/mod.rs', + // PHP + '.php', + '.phtml', + // Swift + '.swift', + // Ruby + '.rb', +]; diff --git a/gitnexus/src/core/ingestion/languages/java.ts b/gitnexus/src/core/ingestion/languages/java.ts index 80851ee4ea..9a308edaae 100644 --- a/gitnexus/src/core/ingestion/languages/java.ts +++ b/gitnexus/src/core/ingestion/languages/java.ts @@ -23,8 +23,6 @@ import { prepareJavaRouteConstants, } from '../route-extractors/java-const-resolver.js'; import { javaExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { javaImportConfig } from '../import-resolvers/configs/jvm.js'; import { JAVA_QUERIES } from '../tree-sitter-queries.js'; import { createCallExtractor } from '../call-extractors/generic.js'; import { javaCallConfig } from '../call-extractors/configs/jvm.js'; @@ -198,7 +196,6 @@ export const javaProvider = defineLanguage({ treeSitterQueries: JAVA_QUERIES, typeConfig: javaTypeConfig, exportChecker: javaExportChecker, - importResolver: createImportResolver(javaImportConfig), mroStrategy: 'implements-split', callExtractor: createCallExtractor(javaCallConfig), fieldExtractor: createFieldExtractor(javaConfig), diff --git a/gitnexus/src/core/ingestion/languages/java/import-target.ts b/gitnexus/src/core/ingestion/languages/java/import-target.ts index 4843e854dd..ec1fd0a360 100644 --- a/gitnexus/src/core/ingestion/languages/java/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/java/import-target.ts @@ -40,7 +40,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { getJavaPackageFact } from './package-facts.js'; import { buildJavaPackageIndex, diff --git a/gitnexus/src/core/ingestion/languages/javascript/import-target.ts b/gitnexus/src/core/ingestion/languages/javascript/import-target.ts index 47b8e9fa89..0342e70d95 100644 --- a/gitnexus/src/core/ingestion/languages/javascript/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/javascript/import-target.ts @@ -22,7 +22,7 @@ * mapping or a package manifest, and otherwise not at all. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { resolveTsTarget } from '../typescript/import-target.js'; import type { TsconfigIndex } from '../typescript/tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts index 65bc834eb1..9d9639b3ae 100644 --- a/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts @@ -46,7 +46,7 @@ import { jsArityCompatibility } from './arity.js'; import { makeJsResolveImportTarget } from './import-target.js'; import { loadTsconfigIndex } from '../typescript/tsconfig.js'; import { typescriptModuleExports } from '../typescript/module-exports.js'; -import { loadNodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { isJsSelfBoundCallableFallbackPlausible } from './callable-visibility.js'; async function loadResolutionConfig(repoPath: string, fresh = false) { diff --git a/gitnexus/src/core/ingestion/languages/kotlin.ts b/gitnexus/src/core/ingestion/languages/kotlin.ts index 4ffda436dc..bf4b4daf30 100644 --- a/gitnexus/src/core/ingestion/languages/kotlin.ts +++ b/gitnexus/src/core/ingestion/languages/kotlin.ts @@ -16,9 +16,7 @@ import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; import { assertCloneable } from '../workers/clone-safety.js'; import { kotlinTypeConfig } from '../type-extractors/jvm.js'; import { kotlinExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { kotlinImportConfig } from '../import-resolvers/configs/jvm.js'; -import { appendKotlinWildcard } from '../import-resolvers/jvm.js'; +import { appendKotlinWildcard } from './kotlin/import-wildcard.js'; import { KOTLIN_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import type { SyntaxNode } from '../utils/ast-helpers.js'; @@ -178,7 +176,6 @@ export const kotlinProvider = defineLanguage({ treeSitterQueries: KOTLIN_QUERIES, typeConfig: kotlinTypeConfig, exportChecker: kotlinExportChecker, - importResolver: createImportResolver(kotlinImportConfig), importPathPreprocessor: appendKotlinWildcard, mroStrategy: 'implements-split', callExtractor: createCallExtractor(kotlinCallConfig), diff --git a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts index 7fb8b74100..695c104889 100644 --- a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts @@ -5,7 +5,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { getKotlinPackageFact } from './package-facts.js'; import { buildKotlinPackageIndex, diff --git a/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts b/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts new file mode 100644 index 0000000000..8121da87ae --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts @@ -0,0 +1,14 @@ +import type { SyntaxNode } from '../../utils/ast-helpers.js'; + +/** + * Append .* to a Kotlin import path if the AST has a wildcard_import sibling node. + * Pure function — returns a new string without mutating the input. + */ +export const appendKotlinWildcard = (importPath: string, importNode: SyntaxNode): string => { + for (let i = 0; i < importNode.childCount; i++) { + if (importNode.child(i)?.type === 'wildcard_import') { + return importPath.endsWith('.*') ? importPath : `${importPath}.*`; + } + } + return importPath; +}; diff --git a/gitnexus/src/core/ingestion/languages/objective-c.ts b/gitnexus/src/core/ingestion/languages/objective-c.ts index 6a86e9dd72..c1daac9933 100644 --- a/gitnexus/src/core/ingestion/languages/objective-c.ts +++ b/gitnexus/src/core/ingestion/languages/objective-c.ts @@ -8,7 +8,6 @@ import { import Parser from 'tree-sitter'; import { defineLanguage } from '../language-provider.js'; import { createObjectiveCCfgVisitor } from '../cfg/visitors/objective-c.js'; -import type { ImportResolverFn } from '../import-resolvers/types.js'; import { getLanguageGrammar } from '../../tree-sitter/parser-loader.js'; import { parseSourceSafe } from '../../tree-sitter/safe-parse.js'; import { assertCloneable } from '../workers/clone-safety.js'; @@ -31,8 +30,6 @@ const EMPTY_TYPE_CONFIG = { extractParameter: () => null, }; -const noImportResolution: ImportResolverFn = () => null; - function normalizedExt(filePath: string): string { return path.extname(filePath).toLowerCase(); } @@ -318,7 +315,6 @@ export const objectiveCProvider = defineLanguage({ treeSitterQueries: OBJECTIVE_C_SCOPE_QUERY, typeConfig: EMPTY_TYPE_CONFIG, exportChecker: () => true, - importResolver: noImportResolution, classifyFileContent: classifyObjectiveCFileContent, shouldClassifyFileContent: isHeaderPath, preprocessSource: preprocessObjectiveCMacroMarkers, diff --git a/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts b/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts index fb493e466d..20fefe37f9 100644 --- a/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts @@ -10,7 +10,7 @@ */ import path from 'path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { coerceObjectiveCResolutionConfig, normalizeRepoPath, diff --git a/gitnexus/src/core/ingestion/languages/php.ts b/gitnexus/src/core/ingestion/languages/php.ts index 644b6d3522..4fd5a84825 100644 --- a/gitnexus/src/core/ingestion/languages/php.ts +++ b/gitnexus/src/core/ingestion/languages/php.ts @@ -29,8 +29,6 @@ import { } from '../language-provider.js'; import { typeConfig as phpConfig } from '../type-extractors/php.js'; import { phpExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { phpImportConfig } from '../import-resolvers/configs/php.js'; import { PHP_QUERIES } from '../tree-sitter-queries.js'; import { findDescendant, @@ -308,7 +306,6 @@ export const phpProvider = defineLanguage({ treeSitterQueries: PHP_QUERIES, typeConfig: phpConfig, exportChecker: phpExportChecker, - importResolver: createImportResolver(phpImportConfig), callExtractor: createCallExtractor(phpCallConfig), fieldExtractor: createFieldExtractor(phpFieldConfig), methodExtractor: createMethodExtractor(phpMethodConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/php.ts b/gitnexus/src/core/ingestion/languages/php/import-helpers.ts similarity index 95% rename from gitnexus/src/core/ingestion/import-resolvers/php.ts rename to gitnexus/src/core/ingestion/languages/php/import-helpers.ts index 72acba2f09..f112a1031e 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/php.ts +++ b/gitnexus/src/core/ingestion/languages/php/import-helpers.ts @@ -1,13 +1,14 @@ /** * PHP PSR-4 import resolution — internal helpers. * - * Strategy lives in configs/php.ts. + * Used by the PHP ScopeResolver.resolveImportTarget hook. * This file contains the shared helper for PSR-4 resolution via composer.json. */ -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; -import type { ComposerConfig } from '../language-config.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import type { ComposerConfig } from '../../language-config.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** Get or compute the sorted PSR-4 entries (cached after first call). */ function getSortedPsr4(config: ComposerConfig): readonly [string, string][] { @@ -142,5 +143,5 @@ export function resolvePhpImportInternal( // Fallback: suffix matching (works without composer.json) const pathParts = normalized.split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } diff --git a/gitnexus/src/core/ingestion/languages/php/import-target.ts b/gitnexus/src/core/ingestion/languages/php/import-target.ts index ae7783b674..2a9513a744 100644 --- a/gitnexus/src/core/ingestion/languages/php/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/php/import-target.ts @@ -17,10 +17,10 @@ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; import type { ImportResolutionContext } from '../../scope-resolution/contract/scope-resolver.js'; -import { resolvePhpImportInternal } from '../../import-resolvers/php.js'; -import type { SuffixIndex } from '../../import-resolvers/utils.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { getWorkspaceFileIndex } from '../../import-resolvers/workspace-file-index.js'; +import { resolvePhpImportInternal } from './import-helpers.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; import { mergeComposerConfigs, parseComposerConfig, @@ -305,7 +305,7 @@ const getPhpWorkspaceIndex = perFileSet((allFilePaths: ReadonlySet): Php * * DEFERRED for the same reason as the shared `dirMap` (#2903), and here the * case is stronger: `getFilesInDir` has exactly one caller, - * `import-resolvers/php.ts`'s PSR-4 function/constant fallback, and that + * `import-helpers.ts`'s PSR-4 function/constant fallback, and that * caller sits inside `if (composerConfig) { … }`. `resolvePhpImportTarget` * hard-codes `composerConfig: null`, so on the LanguageProvider path the map * is statically unreachable; on the ScopeResolver path it is reachable only diff --git a/gitnexus/src/core/ingestion/languages/python.ts b/gitnexus/src/core/ingestion/languages/python.ts index cd7230abb5..23afcf0052 100644 --- a/gitnexus/src/core/ingestion/languages/python.ts +++ b/gitnexus/src/core/ingestion/languages/python.ts @@ -16,8 +16,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as pythonConfig } from '../type-extractors/python.js'; import { pythonExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { pythonImportConfig } from '../import-resolvers/configs/python.js'; import { PYTHON_QUERIES } from '../tree-sitter-queries.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; import { pythonConfig as pythonFieldConfig } from '../field-extractors/configs/python.js'; @@ -130,7 +128,6 @@ export const pythonProvider = defineLanguage({ treeSitterQueries: PYTHON_QUERIES, typeConfig: pythonConfig, exportChecker: pythonExportChecker, - importResolver: createImportResolver(pythonImportConfig), mroStrategy: 'c3', callExtractor: createCallExtractor(pythonCallConfig), fieldExtractor: createFieldExtractor(pythonFieldConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts b/gitnexus/src/core/ingestion/languages/python/import-file-index.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts rename to gitnexus/src/core/ingestion/languages/python/import-file-index.ts index d624bb45a6..751a28d149 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-file-index.ts @@ -6,7 +6,7 @@ * * Everything here is derived from `allFilePaths` and nothing here is specific * to either CALLER, and there are two of them on opposite sides of a layer - * boundary: `import-resolvers/python.ts` resolves the single-segment bare tier + * boundary: `languages/python/import-helpers.ts` resolves the single-segment bare tier * and `languages/python/import-target.ts` resolves the dotted tiers. The second * imports the first, so the index could not live in either without the other * reaching back through a cycle — it used to live in `import-target.ts`, which @@ -18,7 +18,7 @@ * query functions taking the index. */ -import { perFileSet } from './per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * The importer's ancestor directories, CLOSEST FIRST and excluding the diff --git a/gitnexus/src/core/ingestion/import-resolvers/python.ts b/gitnexus/src/core/ingestion/languages/python/import-helpers.ts similarity index 93% rename from gitnexus/src/core/ingestion/import-resolvers/python.ts rename to gitnexus/src/core/ingestion/languages/python/import-helpers.ts index 9914a76133..e61574d9bb 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/python.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-helpers.ts @@ -2,8 +2,7 @@ * Python import resolution — PEP 328 relative imports and proximity-based bare imports. * Import system spec: PEP 302 (original), PEP 451 (current). * - * Strategy lives in configs/python.ts. - * This file contains the shared internal helper used by the strategy and tests. + * Used by the Python ScopeResolver.resolveImportTarget hook and tests. */ import { @@ -11,8 +10,10 @@ import { importerBarePrefixes, importerDirOf, pythonSegmentAbsent, -} from './python-file-index.js'; -import { tryResolveWithExtensions } from './utils.js'; +} from './import-file-index.js'; +import { tryResolveWithExtensions } from '../../utils/suffix-index.js'; + +const RELATIVE_IMPORT_EXTENSIONS = ['/__init__.py', '.py'] as const; /** * Resolve a Python import to a file path (low-level helper). @@ -22,8 +23,6 @@ import { tryResolveWithExtensions } from './utils.js'; * Approximates the common case where co-located files find each other without an installed package. * Single-segment only — multi-segment (e.g. `os.path`) falls through to suffixResolve. * Checks package (__init__.py) before module (.py), matching CPython's finder order (PEP 451 §4). - * Coexistence of both is physically impossible (same name = file vs directory), so the order - * only matters for spec compliance. * Note: implicit namespace packages (Python 3.3+, directory without __init__.py) are not handled. * * Returns null to let the caller fall through to suffixResolve. @@ -50,7 +49,7 @@ export function resolvePythonImportInternal( dirParts.push(...modulePart.replace(/\./g, '/').split('/')); } - return tryResolveWithExtensions(dirParts.join('/'), allFiles); + return tryResolveWithExtensions(dirParts.join('/'), allFiles, RELATIVE_IMPORT_EXTENSIONS); } // Proximity bare import — single-segment only; package before module (PEP 451 §4) diff --git a/gitnexus/src/core/ingestion/languages/python/import-target.ts b/gitnexus/src/core/ingestion/languages/python/import-target.ts index f48359c1b2..9158094b25 100644 --- a/gitnexus/src/core/ingestion/languages/python/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-target.ts @@ -11,13 +11,9 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { - getPythonFileIndex, - importerAncestors, - importerDirOf, -} from '../../import-resolvers/python-file-index.js'; -import { resolvePythonImportInternal } from '../../import-resolvers/python.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getPythonFileIndex, importerAncestors, importerDirOf } from './import-file-index.js'; +import { resolvePythonImportInternal } from './import-helpers.js'; export interface PythonResolveContext { readonly fromFile: string; diff --git a/gitnexus/src/core/ingestion/languages/ruby.ts b/gitnexus/src/core/ingestion/languages/ruby.ts index 7daebcf0c9..3f6c0aab4a 100644 --- a/gitnexus/src/core/ingestion/languages/ruby.ts +++ b/gitnexus/src/core/ingestion/languages/ruby.ts @@ -23,8 +23,6 @@ import { createLeadingDocDescriptionExtractor, type SyntaxNode } from '../utils/ import { typeConfig as rubyConfig } from '../type-extractors/ruby.js'; import { routeRubyCall } from '../call-routing.js'; import { rubyExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { rubyImportConfig } from '../import-resolvers/configs/ruby.js'; import { RUBY_QUERIES } from '../tree-sitter-queries.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; import { rubyConfig as rubyFieldConfig } from '../field-extractors/configs/ruby.js'; @@ -214,7 +212,6 @@ export const rubyProvider = defineLanguage({ `, typeConfig: rubyConfig, exportChecker: rubyExportChecker, - importResolver: createImportResolver(rubyImportConfig), callRouter: routeRubyCall, callExtractor: createCallExtractor(rubyCallConfig), resolveEnclosingOwner: rubyResolveEnclosingOwner, diff --git a/gitnexus/src/core/ingestion/import-resolvers/ruby.ts b/gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts similarity index 71% rename from gitnexus/src/core/ingestion/import-resolvers/ruby.ts rename to gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts index b19a6b3c31..141cf7a5fd 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/ruby.ts +++ b/gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts @@ -1,12 +1,12 @@ /** * Ruby require/require_relative import resolution — internal helpers. * - * Strategy lives in configs/ruby.ts. - * This file only contains the low-level helper used by the strategy. + * Used by the Ruby ScopeResolver.resolveImportTarget hook. */ -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** * Resolve a Ruby require/require_relative path to a matching .rb file (low-level helper). @@ -21,5 +21,5 @@ export function resolveRubyImportInternal( index?: SuffixIndex, ): string | null { const pathParts = importPath.replace(/^\.\//, '').split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } diff --git a/gitnexus/src/core/ingestion/languages/ruby/import-target.ts b/gitnexus/src/core/ingestion/languages/ruby/import-target.ts index eae1f56e3b..402f60fdf6 100644 --- a/gitnexus/src/core/ingestion/languages/ruby/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/ruby/import-target.ts @@ -8,8 +8,8 @@ * - Known external gems → null, even if an unrelated repo file suffix matches */ -import { resolveRubyImportInternal } from '../../import-resolvers/ruby.js'; -import { getWorkspaceFileIndex } from '../../import-resolvers/workspace-file-index.js'; +import { resolveRubyImportInternal } from './import-helpers.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; import { isHeritageMarker } from '../../utils/heritage-marker.js'; import { findRubyResolutionScope, diff --git a/gitnexus/src/core/ingestion/languages/rust.ts b/gitnexus/src/core/ingestion/languages/rust.ts index 85a4ad1a06..cc01ade725 100644 --- a/gitnexus/src/core/ingestion/languages/rust.ts +++ b/gitnexus/src/core/ingestion/languages/rust.ts @@ -17,8 +17,6 @@ import { defineLanguage } from '../language-provider.js'; import { createLeadingDocDescriptionExtractor, type SyntaxNode } from '../utils/ast-helpers.js'; import { typeConfig as rustConfig } from '../type-extractors/rust.js'; import { rustExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { rustImportConfig } from '../import-resolvers/configs/rust.js'; import { RUST_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -168,7 +166,6 @@ export const rustProvider = defineLanguage({ treeSitterQueries: RUST_QUERIES, typeConfig: rustConfig, exportChecker: rustExportChecker, - importResolver: createImportResolver(rustImportConfig), mroStrategy: 'qualified-syntax', callExtractor: createCallExtractor(rustCallConfig), fieldExtractor: createFieldExtractor(rustFieldConfig), diff --git a/gitnexus/src/core/ingestion/languages/rust/qualified-call.ts b/gitnexus/src/core/ingestion/languages/rust/qualified-call.ts index 54047c6ff7..ce3743f927 100644 --- a/gitnexus/src/core/ingestion/languages/rust/qualified-call.ts +++ b/gitnexus/src/core/ingestion/languages/rust/qualified-call.ts @@ -33,7 +33,7 @@ */ import type { ParsedFile, Scope, ScopeId, SymbolDefinition } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { isOverloadableCallable } from '../../utils/callable-labels.js'; import { lookupBindingsAt } from '../../scope-resolution/scope/walkers.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; @@ -202,8 +202,7 @@ function* candidateModules( // // The binding must name a MODULE, not a symbol inside one. Import // resolution deliberately strips a trailing symbol segment when probing for - // a file ("the last segment might be a symbol, not a module" — - // import-resolvers/rust.ts), so `use crate::client::ClientBuilder;` also + // a file, so `use crate::client::ClientBuilder;` also // lands on `client/mod.rs`. Taking that at face value made the imported // TYPE look like the module `client`, and `ClientBuilder::new()` then // resolved against `client`'s module members — binding an associated @@ -483,7 +482,7 @@ interface PassModuleIndex { } /** - * DELIBERATELY NOT ON `import-resolvers/per-file-set.ts` (#2909 sweep), unlike + * DELIBERATELY NOT ON `utils/per-file-set.ts` (#2909 sweep), unlike * {@link moduleIndexFor} above. {@link passIndexFor} takes THREE inputs — * `workspaceIndex`, `index` and `scopes` — and keys on the first alone; the * builder reads `scopes.defs.byId` and `index`, neither of which is derivable diff --git a/gitnexus/src/core/ingestion/languages/swift.ts b/gitnexus/src/core/ingestion/languages/swift.ts index d0092c47b3..57d06ee674 100644 --- a/gitnexus/src/core/ingestion/languages/swift.ts +++ b/gitnexus/src/core/ingestion/languages/swift.ts @@ -14,8 +14,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as swiftConfig } from '../type-extractors/swift.js'; import { swiftExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { swiftImportConfig } from '../import-resolvers/configs/swift.js'; import { SWIFT_QUERIES } from '../tree-sitter-queries.js'; import type { SyntaxNode } from '../utils/ast-helpers.js'; import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; @@ -239,7 +237,6 @@ export const swiftProvider = defineLanguage({ treeSitterQueries: SWIFT_QUERIES, typeConfig: swiftConfig, exportChecker: swiftExportChecker, - importResolver: createImportResolver(swiftImportConfig), callExtractor: createCallExtractor(swiftCallConfig), fieldExtractor: createFieldExtractor(swiftFieldConfig), methodExtractor: createMethodExtractor({ diff --git a/gitnexus/src/core/ingestion/languages/swift/import-target.ts b/gitnexus/src/core/ingestion/languages/swift/import-target.ts index 85add32095..a2e8479fcb 100644 --- a/gitnexus/src/core/ingestion/languages/swift/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/swift/import-target.ts @@ -19,7 +19,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { coerceDeclaredSwiftTargets, swiftDeclaredTargetPrefix, diff --git a/gitnexus/src/core/ingestion/languages/typescript.ts b/gitnexus/src/core/ingestion/languages/typescript.ts index 56aae341fd..9b5b573de6 100644 --- a/gitnexus/src/core/ingestion/languages/typescript.ts +++ b/gitnexus/src/core/ingestion/languages/typescript.ts @@ -76,11 +76,6 @@ const memberAssignmentLabel = (node: SyntaxNode): NodeLabel | null => { import { createTypeScriptCfgVisitor } from '../cfg/visitors/typescript.js'; import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js'; import { tsExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { - typescriptImportConfig, - javascriptImportConfig, -} from '../import-resolvers/configs/typescript-javascript.js'; import { TYPESCRIPT_QUERIES, JAVASCRIPT_QUERIES } from '../tree-sitter-queries.js'; import { typescriptFieldExtractor } from '../field-extractors/typescript.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -491,7 +486,6 @@ export const typescriptProvider = defineLanguage({ typeConfig: typescriptConfig, scopeOwnsReceivers: tsScopeOwnsReceivers, exportChecker: tsExportChecker, - importResolver: createImportResolver(typescriptImportConfig), callExtractor: createCallExtractor(typescriptCallConfig), fieldExtractor: typescriptFieldExtractor, methodExtractor: createMethodExtractor({ @@ -592,7 +586,6 @@ export const javascriptProvider = defineLanguage({ typeConfig: typescriptConfig, scopeOwnsReceivers: tsScopeOwnsReceivers, exportChecker: tsExportChecker, - importResolver: createImportResolver(javascriptImportConfig), callExtractor: createCallExtractor(javascriptCallConfig), fieldExtractor: createFieldExtractor(javascriptConfig), methodExtractor: createMethodExtractor({ diff --git a/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts b/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts index 421959788f..963814be74 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts @@ -4,7 +4,7 @@ * Shared by `module-resolution.ts` and the package-manifest resolver so both * try the same three shapes — exact path, extension, directory index — and, as * importantly, the same NARROW extension list. The repo-wide `EXTENSIONS` in - * `import-resolvers/utils.ts` carries ~39 entries spanning every language the + * `languages/import-candidates.ts` carries ~39 entries spanning every language the * indexer supports; a TypeScript import cannot resolve to a `.py` or `.rb` * file, and letting it try was part of how the old suffix matcher found files * that had nothing to do with the import. diff --git a/gitnexus/src/core/ingestion/languages/typescript/import-target.ts b/gitnexus/src/core/ingestion/languages/typescript/import-target.ts index 2100a77176..9f1ad105f9 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/import-target.ts @@ -18,7 +18,7 @@ */ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from './workspace-packages.js'; import { resolveTsModule } from './module-resolution.js'; import type { TsconfigIndex } from './tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts b/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts index ea8d2d637e..88c986324f 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts @@ -2,7 +2,7 @@ * TypeScript / JavaScript module resolution (#2953). * * This is the algorithm `tsc` and Node actually run, in the order they run it. - * It replaces `import-resolvers/utils.ts:suffixResolve` on the TS/JS/Vue path, + * It replaces `utils/suffix-index.ts:suffixResolve` on the TS/JS/Vue path, * which answered a different question — "does any file in this repo have a path * ending in this specifier?" — and answered it by dropping leading segments * until something matched. That is why `@acme/telemetry/nest`, a registry @@ -31,14 +31,14 @@ * 6. anything else — external. `null`. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from './workspace-packages.js'; import { matchSubpathMap, nodePackageNameOf, owningPackage, resolveNodeWorkspaceImport, substituteStar, -} from '../../import-resolvers/node-workspace-packages.js'; +} from './workspace-packages.js'; import { resolveFile } from './file-candidates.js'; import { tsconfigFor, type TsconfigIndex, type TsPathMapping } from './tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts index 9d75676b9d..be5f7a8cf0 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts @@ -25,10 +25,7 @@ import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexe import { typescriptProvider } from '../typescript.js'; import { typescriptModuleExports } from './module-exports.js'; import { loadTsconfigIndex, type TsconfigIndex } from './tsconfig.js'; -import { - loadNodeWorkspacePackages, - type NodeWorkspacePackages, -} from '../../import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages, type NodeWorkspacePackages } from './workspace-packages.js'; import { indexOnlyElementType } from '../../type-extractors/shared.js'; import { typescriptArityCompatibility, typescriptMergeBindings, resolveTsTarget } from './index.js'; import { diff --git a/gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts b/gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts rename to gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts index 2f36e35e27..c3c4392c98 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts @@ -20,9 +20,9 @@ import path from 'path'; import { createRequire } from 'node:module'; import type Parser from 'tree-sitter'; -import { isHardcodedIgnoredDirectoryAtPath } from '../../../config/ignore-service.js'; -import { logger } from '../../logger.js'; -import { resolveFile } from '../languages/typescript/file-candidates.js'; +import { isHardcodedIgnoredDirectoryAtPath } from '../../../../config/ignore-service.js'; +import { logger } from '../../../logger.js'; +import { resolveFile } from './file-candidates.js'; // `js-yaml` is CJS; the rest of this repository reaches it the same way // (`core/group/config-parser.ts`, `cli/group.ts`). @@ -830,7 +830,7 @@ async function staticViteEntry(text: string): Promise { const [{ default: TreeSitter }, { default: grammar }, { parseSourceSafe }] = await Promise.all([ import('tree-sitter'), import('tree-sitter-typescript'), - import('../../tree-sitter/safe-parse.js'), + import('../../../tree-sitter/safe-parse.js'), ]); const parser = new TreeSitter(); parser.setLanguage(grammar.typescript); diff --git a/gitnexus/src/core/ingestion/languages/vue.ts b/gitnexus/src/core/ingestion/languages/vue.ts index 9475d8a7be..ca8d49c041 100644 --- a/gitnexus/src/core/ingestion/languages/vue.ts +++ b/gitnexus/src/core/ingestion/languages/vue.ts @@ -17,8 +17,6 @@ import { vueClassConfig } from '../class-extractors/configs/typescript-javascrip import { defineLanguage } from '../language-provider.js'; import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js'; import { tsExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { vueImportConfig } from '../import-resolvers/configs/typescript-javascript.js'; import { TYPESCRIPT_QUERIES } from '../tree-sitter-queries.js'; import { typescriptFieldExtractor } from '../field-extractors/typescript.js'; import { BUILT_INS as TS_BUILT_INS } from './typescript.js'; @@ -86,7 +84,6 @@ export const vueProvider = defineLanguage({ treeSitterQueries: TYPESCRIPT_QUERIES, typeConfig: typescriptConfig, exportChecker: tsExportChecker, - importResolver: createImportResolver(vueImportConfig), callExtractor: createCallExtractor(typescriptCallConfig), fieldExtractor: typescriptFieldExtractor, variableExtractor: createVariableExtractor(typescriptVariableConfig), diff --git a/gitnexus/src/core/ingestion/languages/vue/import-target.ts b/gitnexus/src/core/ingestion/languages/vue/import-target.ts index 886580b0ef..2e7d363a15 100644 --- a/gitnexus/src/core/ingestion/languages/vue/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/vue/import-target.ts @@ -8,7 +8,7 @@ * Vue-specific guessing is required — the exact-path branch finds them first. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { resolveTsTarget } from '../typescript/import-target.js'; import type { TsconfigIndex } from '../typescript/tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts index f9021631d9..4d64953352 100644 --- a/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts @@ -63,7 +63,7 @@ import { simpleKey } from '../../scope-resolution/graph-bridge/node-lookup.js'; import { vueProvider } from '../vue.js'; import { loadTsconfigIndex } from '../typescript/tsconfig.js'; import { typescriptModuleExports } from '../typescript/module-exports.js'; -import { loadNodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { typescriptArityCompatibility, typescriptMergeBindings } from '../typescript/index.js'; import { makeVueResolveImportTarget } from './import-target.js'; import { extractVueTemplateEdgeData } from '../../vue-sfc-extractor.js'; diff --git a/gitnexus/src/core/ingestion/languages/zig.ts b/gitnexus/src/core/ingestion/languages/zig.ts index 9b5c9eff9e..da28085a37 100644 --- a/gitnexus/src/core/ingestion/languages/zig.ts +++ b/gitnexus/src/core/ingestion/languages/zig.ts @@ -8,7 +8,7 @@ import { zigRenameProvider } from './zig/rename.js'; * `@heritage.*` captures). * - exportChecker: walks to the enclosing variable_declaration / * function_declaration and looks for a `pub` or `export` keyword child. - * - importResolver: resolves local `@import("./foo.zig")` paths and + * - ScopeResolver.resolveImportTarget: resolves local `@import("./foo.zig")` paths and * build.zig.zon `.path` deps (root the dep's build.zig declares, then * src/root.zig, src/.zig, src/main.zig); `@import("std")` and * `.url` packages are deliberately external. @@ -35,8 +35,6 @@ import { SupportedLanguages } from 'gitnexus-shared'; import { defineLanguage } from '../language-provider.js'; import { ZIG_QUERIES } from '../tree-sitter-queries.js'; import { zigExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { zigImportConfig } from '../import-resolvers/configs/zig.js'; import { createCallExtractor } from '../call-extractors/generic.js'; import { zigCallConfig } from '../call-extractors/configs/zig.js'; import { createClassExtractor } from '../class-extractors/generic.js'; @@ -79,7 +77,6 @@ export const zigProvider = defineLanguage({ typeConfig: zigTypeConfig, cfgVisitor: createZigCfgVisitor(), exportChecker: zigExportChecker, - importResolver: createImportResolver(zigImportConfig), callExtractor: createCallExtractor(zigCallConfig), classExtractor: createClassExtractor(zigClassConfig), fieldExtractor: createFieldExtractor(zigFieldConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/zig.ts b/gitnexus/src/core/ingestion/languages/zig/import-helpers.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/zig.ts rename to gitnexus/src/core/ingestion/languages/zig/import-helpers.ts index 8b66a26265..cb999c1800 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/zig.ts +++ b/gitnexus/src/core/ingestion/languages/zig/import-helpers.ts @@ -29,7 +29,7 @@ import { normalizeZigDepPath, type ZigBuildModule, type ZigBuildZonConfig, -} from '../language-config.js'; +} from '../../language-config.js'; const ZIG_STDLIB_NAMES = new Set(['std', 'builtin', 'root']); diff --git a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts index 50f29322b4..9e0665747e 100644 --- a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts @@ -20,7 +20,7 @@ import { zigPackageFor, type ZigWorkspaceIndex, } from '../../language-config.js'; -import { resolveZigImportInternal } from '../../import-resolvers/zig.js'; +import { resolveZigImportInternal } from './import-helpers.js'; import { zigProvider } from '../zig.js'; import { expandZigWildcardNames, diff --git a/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts b/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts index 11c13b2596..9b5a6f633e 100644 --- a/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts +++ b/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts @@ -1,7 +1,7 @@ import type { ParsedFile, ReferenceSite } from 'gitnexus-shared'; import { getTreeSitterBufferSize } from '../../constants.js'; import { zigPackageFor, type ZigWorkspaceIndex } from '../../language-config.js'; -import { resolveZigImportInternal } from '../../import-resolvers/zig.js'; +import { resolveZigImportInternal } from './import-helpers.js'; import { buildZigBoolConstMap, collectZigStaticGatedRanges, diff --git a/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts b/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts index 131055deb9..a948250acf 100644 --- a/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts +++ b/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts @@ -131,7 +131,7 @@ export interface JsRepoFacts { * * A tail lookup only ever matches keys whose last segment equals the * candidate's last segment, so the bucket is the entire search space — turning - * an O(files) sweep per candidate into one map hit. `import-resolvers/utils.ts` + * an O(files) sweep per candidate into one map hit. `utils/suffix-index.ts` * already ships `buildSuffixIndex` for the same job, but it keeps only a first * winner per suffix; this index has to SEE a collision to refuse it (below), so * it keeps the whole bucket. diff --git a/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts b/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts index 6224a16c96..39734fa886 100644 --- a/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts +++ b/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts @@ -12,7 +12,7 @@ * This module lives in `ingestion/` (the lower layer); the group layer imports * from it, matching the existing `group → ingestion` dependency direction * (e.g. `group/extractors/include-extractor.ts` already imports - * `ingestion/import-resolvers/utils.ts`). It MUST NOT import anything from + * `ingestion/utils/suffix-index.ts`). It MUST NOT import anything from * `group/` to avoid a dependency cycle. */ diff --git a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts b/gitnexus/src/core/ingestion/utils/package-dir-index.ts similarity index 87% rename from gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts rename to gitnexus/src/core/ingestion/utils/package-dir-index.ts index 30c4c2d96a..163e9ac865 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts +++ b/gitnexus/src/core/ingestion/utils/package-dir-index.ts @@ -30,30 +30,10 @@ * (`languages/kotlin/import-target.ts`); this index, the C# csproj index and * the legacy `go.ts` scan followed. * - * The strongest evidence that the rule was accidental is that a sixth - * implementation of the same question never had it. `import-resolvers/jvm.ts` - * answers "files directly inside a directory ending with " for - * Java and Kotlin wildcard imports, and has used `lastIndexOf` since #488. - * - * That is evidence about how the predicate was WRITTEN, not about live - * behaviour, and the distinction matters enough to spell out. `jvm.ts` is - * reached only through `provider.importResolver`, which `languages/java.ts` and - * `languages/kotlin.ts` do wire — but that field currently has no production - * READER. Its only reader anywhere is `import-target-adapter.ts`, whose own - * docblock says it is "threaded through `finalizeScopeModel`"; nothing threads - * it, and neither that module nor its two exports - * (`buildImportTargetWorkspace`, `resolveImportTargetAcrossLanguages`) is - * referenced outside its own unit test. So `jvm.ts`'s `resolveJvmWildcard` and - * `import-resolvers/go.ts`'s `resolveGoPackage` are dormant, while THIS index, - * `csharp.ts`'s `resolveCSharpImportInternal` and Kotlin's `dirChildren` are - * the ones that run. Whether those two dormant resolvers should be deleted or - * actually wired up is an open question and wants its own issue; it is not - * settled here. - * - * The argument survives that correction intact, because it never needed the - * resolvers to be live: an independent implementation of the same question, - * written without reference to the pre-index scan, reached for `lastIndexOf`. - * The extra clause was never a rule anyone chose. All six spellings now agree. + * The former JVM wildcard helper independently used `lastIndexOf` since #488, + * which helped identify the first-occurrence restriction as accidental. + * That dormant helper has been removed; this index and the active namespace + * resolvers retain the corrected suffix predicate. * * The length guard the `indexOf` form needed is gone with it: `endsWith` is * false for a shorter `D` instead of comparing -1 to -1. diff --git a/gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts b/gitnexus/src/core/ingestion/utils/per-file-set.ts similarity index 94% rename from gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts rename to gitnexus/src/core/ingestion/utils/per-file-set.ts index 4de0ee3612..f3d10aeead 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts +++ b/gitnexus/src/core/ingestion/utils/per-file-set.ts @@ -41,7 +41,7 @@ * `CountingSet`, driven by the contract test's `minimumParsedFileReads`. * * A THIRD shape — an array materialized from the file set — is what the type - * exists to reject. `import-resolvers/csharp.ts` used one until #2911, and it + * exists to reject. `languages/csharp/import-helpers.ts` used one until #2911, and it * is worth a compile error rather than a rule: copying an array mints a fresh * `WeakMap` key while traversing the Set zero extra times, so every * scan-counting guard stays green at its correct value while the index rebuilds @@ -49,9 +49,7 @@ * above and was caught only by a timing ratio in `bench/import-target/`. Derive * the array inside the builder from `getWorkspaceFileIndex(allFilePaths)` * instead. `string[]` is not assignable to `K`, so the shape cannot come back - * silently — `configs/swift.ts` keeps the one hand-rolled `WeakMap` on - * `ctx.allFileList` in the tree, deliberately and with its reasons written - * down, and it is deliberately NOT on this primitive. + * silently. * * `T extends object` is deliberate, chosen over probing `has` before `get`. * `WeakMap.get` returning `undefined` cannot distinguish "not built yet" from diff --git a/gitnexus/src/core/ingestion/import-resolvers/utils.ts b/gitnexus/src/core/ingestion/utils/suffix-index.ts similarity index 89% rename from gitnexus/src/core/ingestion/import-resolvers/utils.ts rename to gitnexus/src/core/ingestion/utils/suffix-index.ts index 5dec720bc2..262565d5a6 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/utils.ts +++ b/gitnexus/src/core/ingestion/utils/suffix-index.ts @@ -2,58 +2,6 @@ * Suffix-index helpers for import path resolution. */ -/** All file extensions to try during resolution */ -export const EXTENSIONS = [ - '', - // TypeScript/JavaScript - '.tsx', - '.ts', - '.mts', - '.cts', - '.jsx', - '.js', - '.mjs', - '.cjs', - '.vue', - '/index.tsx', - '/index.ts', - '/index.jsx', - '/index.js', - // Python - '.py', - '/__init__.py', - // Java - '.java', - // Kotlin - '.kt', - '.kts', - // C/C++ - '.c', - '.h', - '.cpp', - '.hpp', - '.cc', - '.cxx', - '.hxx', - '.hh', - '.cu', - '.cuh', - // C# - '.cs', - // Go - '.go', - // Rust - '.rs', - '/mod.rs', - // PHP - '.php', - '.phtml', - // Swift - '.swift', - // Ruby - '.rb', -]; - /** * Try to match a path (with extensions) against the known file set. * Returns the matched file path or null. @@ -61,8 +9,9 @@ export const EXTENSIONS = [ export function tryResolveWithExtensions( basePath: string, allFiles: ReadonlySet, + extensions: readonly string[], ): string | null { - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const candidate = basePath + ext; if (allFiles.has(candidate)) return candidate; } @@ -100,7 +49,7 @@ export interface SuffixIndex { * `dirSuffix` is matched as a SEGMENT-aligned directory suffix — every * returned file is a direct child of a directory `D` with * `D === dirSuffix || D.endsWith('/' + dirSuffix)`. Callers may rely on this - * and skip a direct-child re-check; `import-resolvers/csharp.ts` step 2 does + * and skip a direct-child re-check; `languages/csharp/import-helpers.ts` step 2 does * exactly that. It bounds what may be RETURNED, not what must be found: an * implementation is free to answer with fewer files, and the root-anchored * index in `languages/php/import-target.ts` answers only the `D === dirSuffix` @@ -128,14 +77,11 @@ export interface SuffixIndexOptions { * for every `i` — i.e. the "normalized" list is a LOWERCASED file list, not * merely a slash-normalized one. * - * `import-resolvers/pass-cache.ts` is the one caller that can make it: it - * builds `normalizedFileList` as `allFileList.map((f) => f.toLowerCase())`. * Every suffix of an all-lowercase path is itself lowercase, so * `suffix.toLowerCase() === suffix` and the case-folded map came out a * byte-identical copy of the exact one — same keys, same values, same * insertion order. Measured 14.00 MiB at 32 000 paths, 29.8% of the retained - * `ImportPassCache` — and one `ImportPassCache` is built per ts-family - * adapter per pass, so the waste was carried once for each of them. + * former ts-family cache. A caller supplying such a list can skip the copy. * * With this set, `getInsensitive` reads the exact map directly instead. It is * the same map the derivation below would have produced, so this is a skipped @@ -280,9 +226,8 @@ export function buildSuffixIndex( * churn. Measured on the 32k-path arms of `bench/import-target/`, it is * ~15% of the retained C# index and ~19% of the retained Ruby one. * - * Only `getFilesInDir` reads it, and only four call sites reach that: - * `import-resolvers/{php,csharp,jvm}.ts` and `import-resolvers/configs/ - * python.ts`. Every other consumer of this index — `workspace-file-index.ts` + * Only `getFilesInDir` reads it, through `languages/{php,csharp}/import-helpers.ts`. + * Every other consumer of this index — `workspace-file-index.ts` * serving Ruby, `languages/typescript/scope-resolver.ts`, * `languages/vue/import-target.ts`, `group/extractors/include-extractor.ts` * — asks only suffix questions and was paying the whole footprint for a map @@ -369,12 +314,9 @@ export function buildSuffixIndex( // imports is the whole pass — which is why the interface makes the result // `readonly` and the compiler refuses the mutation at the call site. // - // Sharing beats copying because no caller keeps the array: two only measure - // it and two build a fresh array from it, so a defensive copy would - // allocate a whole bucket per import on the path this index exists to keep - // flat. `package-dir-index.ts` reached the same conclusion the same way — - // read-only containers, plus one copy where a bucket genuinely LEAVES - // (`sortedRootFiles`), which is the case `configs/swift.ts` is in. + // Neither caller mutates the bucket: one checks its length, the other + // filters into a fresh result. A defensive copy would allocate a bucket + // per import without protecting any mutation boundary. getFilesInDir: (dirSuffix: string, extension: string) => { return getDirMap().get(`${dirSuffix}:${extension}`) || []; }, @@ -388,12 +330,13 @@ export function suffixResolve( pathParts: string[], normalizedFileList: readonly string[], allFileList: readonly string[], + extensions: readonly string[], index?: SuffixIndex, ): string | null { if (index) { for (let i = 0; i < pathParts.length; i++) { const suffix = pathParts.slice(i).join('/'); - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const suffixWithExt = suffix + ext; const result = index.get(suffixWithExt) || index.getInsensitive(suffixWithExt); if (result) return result; @@ -405,7 +348,7 @@ export function suffixResolve( // Fallback: linear scan (for backward compatibility) for (let i = 0; i < pathParts.length; i++) { const suffix = pathParts.slice(i).join('/'); - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const suffixWithExt = suffix + ext; const suffixPattern = '/' + suffixWithExt; const matchIdx = normalizedFileList.findIndex( diff --git a/gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts b/gitnexus/src/core/ingestion/utils/workspace-file-index.ts similarity index 96% rename from gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts rename to gitnexus/src/core/ingestion/utils/workspace-file-index.ts index ad5c882eca..d050a9310f 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts +++ b/gitnexus/src/core/ingestion/utils/workspace-file-index.ts @@ -39,7 +39,7 @@ */ import { perFileSet } from './per-file-set.js'; -import { buildSuffixIndex, type SuffixIndex } from './utils.js'; +import { buildSuffixIndex, type SuffixIndex } from './suffix-index.js'; /** * `normalized` and `all` are `readonly string[]`, and — like @@ -49,10 +49,9 @@ import { buildSuffixIndex, type SuffixIndex } from './utils.js'; * pass, and these two are the largest shared arrays here (one element per file, * read by C#, Java, PHP and Ruby). `readonly` on the field is what makes the * compiler refuse the mutation at the call site instead of leaving it to a - * comment. `ImportPassCache` (`pass-cache.ts`) states the same contract the - * same way for the ts-family lists. + * comment. * - * The positional pairing is load-bearing too and depends on it: `csharp.ts` + * The positional pairing is load-bearing too and depends on it: the C# import helper * caches POSITIONS into `normalized` and reads the answer out of `all`, so a * reordering of either array alone silently re-points every cached position. */ diff --git a/gitnexus/src/core/run-analyze.ts b/gitnexus/src/core/run-analyze.ts index f1e0b9f017..7cec865c21 100644 --- a/gitnexus/src/core/run-analyze.ts +++ b/gitnexus/src/core/run-analyze.ts @@ -44,7 +44,7 @@ import { sweepStagingArtifacts, } from '../storage/index-lock.js'; import { resolveEmbeddingRecovery } from '../storage/embedding-recovery.js'; -import { invalidateNodeWorkspacePackages } from './ingestion/import-resolvers/node-workspace-packages.js'; +import { invalidateNodeWorkspacePackages } from './ingestion/languages/typescript/workspace-packages.js'; import { logNameFallbackSummary, summarizeNameFallback, diff --git a/gitnexus/src/mcp/local/local-backend.ts b/gitnexus/src/mcp/local/local-backend.ts index 673ebb0235..9b697f79a6 100644 --- a/gitnexus/src/mcp/local/local-backend.ts +++ b/gitnexus/src/mcp/local/local-backend.ts @@ -162,7 +162,6 @@ import { foldNumericToolArgumentAliases } from '../tool-arguments.js'; import { findImportCycles, IMPORT_CYCLE_LIMIT } from '../../core/graph/import-cycles.js'; import { decodeTaintPath } from '../../core/ingestion/taint/path-codec.js'; import { decodeReachingDefReason } from '../../core/ingestion/cfg/reaching-def-reason-codec.js'; -import { EXTENSIONS } from '../../core/ingestion/import-resolvers/utils.js'; import { compareCodeUnits } from '../../lib/utils.js'; import { lookupExternalCallCount, @@ -301,21 +300,14 @@ function ambiguityReport( }; } -/** Real source-file extensions (`.ts`, `.py`, …) from the resolver's list, - * excluding the empty entry and the `/index.*` forms — used to decide whether - * an `explain` target is a file path vs a (possibly dotted) symbol name. */ -const SOURCE_FILE_EXTENSIONS: readonly string[] = EXTENSIONS.filter( - (e) => e.startsWith('.') && !e.includes('/'), -); /** Recognize indexed source files and existing import suffixes; a bare dotted * symbol (`UserController.create`) remains a symbol target. */ -function looksLikeFilePath(target: string): boolean { - if (/[\\/]/.test(target)) return true; +async function looksLikeFilePath(target: string): Promise { + if (/[\\/]/.test(target) || getLanguageFromFilename(target) !== null) return true; + // Keep analyze-only language modules out of the MCP startup closure (#2802). + const { EXTENSIONS } = await import('../../core/ingestion/languages/import-candidates.js'); const lower = target.toLowerCase(); - return ( - getLanguageFromFilename(target) !== null || - SOURCE_FILE_EXTENSIONS.some((ext) => lower.endsWith(ext)) - ); + return EXTENSIONS.some((ext) => ext.startsWith('.') && !ext.includes('/') && lower.endsWith(ext)); } /** @@ -5911,7 +5903,7 @@ export class LocalBackend { anchor: { file: string; symbol?: string; startLine?: number; endLine?: number }; early?: Record; }> { - if (looksLikeFilePath(target)) { + if (await looksLikeFilePath(target)) { return { anchorClause: '(a.id STARTS WITH $idPrefix OR a.filePath = $targetPath OR a.filePath ENDS WITH $targetSuffix)', diff --git a/gitnexus/test/integration/csharp-import-index-reuse.test.ts b/gitnexus/test/integration/csharp-import-index-reuse.test.ts index 8f4978260e..eeea90a4d8 100644 --- a/gitnexus/test/integration/csharp-import-index-reuse.test.ts +++ b/gitnexus/test/integration/csharp-import-index-reuse.test.ts @@ -3,7 +3,7 @@ * * The no-csproj `using` path reads TWO per-file-set indexes, each memoized on * the `allFilePaths` Set identity via its own WeakMap: the shared - * `getWorkspaceFileIndex` (`import-resolvers/workspace-file-index.ts`, used by + * `getWorkspaceFileIndex` (`utils/workspace-file-index.ts`, used by * both the csproj and no-csproj legs) and `getCsharpDirIndex` * (`languages/csharp/import-target.ts`, the namespace-directory index behind * `firstFileDirectlyInPkgDir`). A four-segment `using` used to cost up to eight diff --git a/gitnexus/test/integration/php-import-index-reuse.test.ts b/gitnexus/test/integration/php-import-index-reuse.test.ts index 439e2a0c31..3538628a32 100644 --- a/gitnexus/test/integration/php-import-index-reuse.test.ts +++ b/gitnexus/test/integration/php-import-index-reuse.test.ts @@ -7,7 +7,7 @@ * `index` of `undefined`, dropping it onto `suffixResolve`'s linear `findIndex` * — a pass over every file per path-part × per extension, 98 ms per import at * 20k files. They now read the shared `getWorkspaceFileIndex` - * (`import-resolvers/workspace-file-index.ts`), memoized on the `allFilePaths` + * (`utils/workspace-file-index.ts`), memoized on the `allFilePaths` * Set identity via a WeakMap, through a PHP-specific parity view that keeps the * three index-fed fast paths answering exactly what the scans answered (see the * `#2901` header in `import-target.ts` — passing the raw shared index straight diff --git a/gitnexus/test/integration/python-import-index-reuse.test.ts b/gitnexus/test/integration/python-import-index-reuse.test.ts index 46b07afd9b..59a930d759 100644 --- a/gitnexus/test/integration/python-import-index-reuse.test.ts +++ b/gitnexus/test/integration/python-import-index-reuse.test.ts @@ -2,7 +2,7 @@ * Production-path regression guard for PR #1918 review finding P1. * * The Python file index (`getPythonFileIndex` in - * `import-resolvers/python-file-index.ts`) is + * `languages/python/import-file-index.ts`) is * memoized on the `allFilePaths` Set identity via a WeakMap. The registry- * primary path reaches it through `pythonScopeResolver.resolveImportTarget` * (the orchestrator adapter) — NOT by calling `resolvePythonImportTarget` diff --git a/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts b/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts index cf752761e7..98496a5e56 100644 --- a/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts +++ b/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts @@ -1,7 +1,7 @@ /** * Integration test: TypeScript ESM .js extension imports produce CALLS edges. * - * Verifies the full pipeline: .js import → resolveImportPath strips .js → + * Verifies the full pipeline: .js import → import-target resolution strips .js → * resolves to .ts → scope-resolver emits CALLS edge. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; diff --git a/gitnexus/test/integration/ruby-import-index-reuse.test.ts b/gitnexus/test/integration/ruby-import-index-reuse.test.ts index aae9147f0f..25e5661c9c 100644 --- a/gitnexus/test/integration/ruby-import-index-reuse.test.ts +++ b/gitnexus/test/integration/ruby-import-index-reuse.test.ts @@ -2,7 +2,7 @@ * Production-path regression guard for the Ruby import-resolution index (#2880). * * Ruby's bare `require` leg reads the shared `getWorkspaceFileIndex` - * (`import-resolvers/workspace-file-index.ts`), memoized on the `allFilePaths` + * (`utils/workspace-file-index.ts`), memoized on the `allFilePaths` * Set identity via a WeakMap. Before #2880 every single `require` materialized * two arrays AND built a whole `buildSuffixIndex` over the repo, then threw it * away — the most expensive of the four resolvers hoisted. diff --git a/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts b/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts index a9293c50c2..1e7ccd173d 100644 --- a/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts +++ b/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts @@ -13,14 +13,14 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; type Workspace = - typeof import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + typeof import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); type Lock = typeof import('../../src/storage/index-lock.js'); const ctx = vi.hoisted(() => ({ invalidate: vi.fn(), acquire: vi.fn(), })); vi.mock( - '../../src/core/ingestion/import-resolvers/node-workspace-packages.js', + '../../src/core/ingestion/languages/typescript/workspace-packages.js', async (importOriginal) => { const actual = await importOriginal(); ctx.invalidate.mockImplementation(actual.invalidateNodeWorkspacePackages); diff --git a/gitnexus/test/unit/dart-import-resolver.test.ts b/gitnexus/test/unit/dart-import-resolver.test.ts index 938c88913d..d38ec555cb 100644 --- a/gitnexus/test/unit/dart-import-resolver.test.ts +++ b/gitnexus/test/unit/dart-import-resolver.test.ts @@ -1,154 +1,6 @@ -/** - * Unit tests for the production Dart import resolution strategies. - * - * Tests dartPackageStrategy and dartRelativeStrategy from configs/dart.ts — - * the actual strategies composed by createImportResolver(dartImportConfig). - * - * Key behavioral note: - * - dartPackageStrategy returns { kind: 'files', files: [] } (absorbing sentinel) - * for dart: SDK imports and unresolved external packages, which stops the - * strategy chain. This differs from the old monolithic resolver that returned null. - * Both produce zero import edges at runtime (applyImportResult treats them identically). - */ - import { describe, it, expect } from 'vitest'; import { emitDartScopeCaptures } from '../../src/core/ingestion/languages/dart/captures.js'; import { interpretDartImport } from '../../src/core/ingestion/languages/dart/interpret.js'; -import { - dartPackageStrategy, - dartRelativeStrategy, -} from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { createImportResolver } from '../../src/core/ingestion/import-resolvers/resolver-factory.js'; -import { dartImportConfig } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import type { ResolveCtx } from '../../src/core/ingestion/import-resolvers/types.js'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; - -function makeCtx(files: string[]): ResolveCtx { - const allFileList = files; - const normalizedFileList = files.map((f) => f.replace(/\\/g, '/')); - const index = buildSuffixIndex(normalizedFileList, allFileList); - return { - allFilePaths: new Set(files), - allFileList, - normalizedFileList, - index, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, - }; -} - -// --------------------------------------------------------------------------- -// dartPackageStrategy — absorbs SDK / external package imports -// --------------------------------------------------------------------------- - -describe('dartPackageStrategy', () => { - describe('dart: SDK imports', () => { - it('absorbs dart:async with empty-files sentinel', () => { - const result = dartPackageStrategy("'dart:async'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs dart:io with empty-files sentinel', () => { - const result = dartPackageStrategy("'dart:io'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); - - describe('package: imports', () => { - it('resolves local package import to lib/', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = dartPackageStrategy("'package:my_app/models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('absorbs external package imports with empty-files sentinel', () => { - const ctx = makeCtx(['lib/main.dart']); - const result = dartPackageStrategy("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs malformed package import (no slash) with empty-files sentinel', () => { - const result = dartPackageStrategy("'package:http'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); - - describe('relative imports', () => { - it('returns null for relative imports (chains to dartRelativeStrategy)', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'models.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); - }); - - describe('quote stripping', () => { - it('strips single quotes', () => { - const result = dartPackageStrategy("'dart:core'", 'lib/main.dart', makeCtx([])); - // dart: is absorbed, proving quotes were stripped - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('strips double quotes', () => { - const result = dartPackageStrategy('"dart:core"', 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); -}); - -// --------------------------------------------------------------------------- -// dartRelativeStrategy — bare relative paths via standard resolution -// --------------------------------------------------------------------------- - -describe('dartRelativeStrategy', () => { - it('resolves bare relative path by prepending ./', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = dartRelativeStrategy("'./models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('returns null for unresolvable relative import', () => { - const ctx = makeCtx([]); - const result = dartRelativeStrategy("'nonexistent.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Full resolver — dartImportConfig composed via factory -// --------------------------------------------------------------------------- - -describe('Dart import resolver (full config)', () => { - const resolve = createImportResolver(dartImportConfig); - - it('absorbs dart: SDK imports', () => { - const result = resolve("'dart:async'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('resolves local package: import', () => { - const ctx = makeCtx(['lib/models/user.dart']); - const result = resolve("'package:my_app/models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('absorbs external package: import', () => { - const ctx = makeCtx(['lib/main.dart']); - const result = resolve("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('resolves relative import via second strategy', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = resolve("'./models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); -}); describe('Dart import prefix semantic captures', () => { it('keeps prefixed imports as namespace handles and ordinary imports as wildcards', () => { diff --git a/gitnexus/test/unit/esm-extension-resolution.test.ts b/gitnexus/test/unit/esm-extension-resolution.test.ts deleted file mode 100644 index 7948880498..0000000000 --- a/gitnexus/test/unit/esm-extension-resolution.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Unit tests for TypeScript ESM .js extension resolution. - * - * TypeScript ESM requires imports to use .js extensions even when source - * files are .ts. The resolver must map .js → .ts (and .jsx → .tsx, - * .mjs → .mts, .cjs → .cts) when the literal .js file does not exist. - */ - -import { describe, it, expect } from 'vitest'; -import { resolveImportPath } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { stripJsExtension } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; -import { SupportedLanguages } from 'gitnexus-shared'; - -function makeCtx(files: string[]) { - // Match production normalization: only replace backslashes with forward slashes - const normalized = files.map((f) => f.replace(/\\/g, '/')); - const allFilesSet = new Set(files); - const index = buildSuffixIndex(normalized, files); - const cache = new Map(); - return { files, normalized, allFilesSet, index, cache }; -} - -function resolve( - currentFile: string, - importPath: string, - language: SupportedLanguages, - ctx: ReturnType, -): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - language, - null, - ctx.index, - ); -} - -describe('TypeScript ESM .js extension resolution', () => { - it('resolves ./utils.js to ./utils.ts when .js does not exist', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.ts']); - const result = resolve('src/index.ts', './utils.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/utils.ts'); - }); - - it('resolves ./component.jsx to ./component.tsx', () => { - const ctx = makeCtx(['src/app.ts', 'src/component.tsx']); - const result = resolve('src/app.ts', './component.jsx', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/component.tsx'); - }); - - it('resolves ./config.mjs to ./config.mts', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.mts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.mts'); - }); - - it('resolves ./legacy.cjs to ./legacy.cts', () => { - const ctx = makeCtx(['src/index.ts', 'src/legacy.cts']); - const result = resolve('src/index.ts', './legacy.cjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/legacy.cts'); - }); - - it('prefers actual .js file when it exists', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.js', 'src/utils.ts']); - const result = resolve('src/index.ts', './utils.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/utils.js'); - }); - - it('resolves relative path with ../ and .js extension', () => { - const ctx = makeCtx(['src/helpers/token.ts', 'src/core/engine.ts']); - const result = resolve( - 'src/core/engine.ts', - '../helpers/token.js', - SupportedLanguages.TypeScript, - ctx, - ); - expect(result).toBe('src/helpers/token.ts'); - }); - - it('works for JavaScript language too', () => { - const ctx = makeCtx(['src/index.js', 'src/utils.ts']); - const result = resolve('src/index.js', './utils.js', SupportedLanguages.JavaScript, ctx); - expect(result).toBe('src/utils.ts'); - }); - - it('does NOT apply ESM fallback for non-TS/JS languages', () => { - const ctx = makeCtx(['src/main.py', 'src/utils.ts']); - const result = resolve('src/main.py', './utils.js', SupportedLanguages.Python, ctx); - expect(result).toBeNull(); - }); - - it('returns null when neither .js nor .ts exists', () => { - const ctx = makeCtx(['src/index.ts']); - const result = resolve('src/index.ts', './missing.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBeNull(); - }); -}); - -describe('ESM extension resolution — .mjs/.cjs with competing siblings', () => { - it('resolves ./config.mjs to .ts when only .ts exists (no .mts)', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.ts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - // .ts wins because EXTENSIONS order tries .ts before .mts - expect(result).toBe('src/config.ts'); - }); - - it('resolves ./config.mjs to .mts when both .ts and .mts exist', () => { - // Note: EXTENSIONS order is .tsx, .ts, .mts, .cts — so .ts wins over .mts. - // This is intentional for a source-analysis tool: we resolve to the first - // matching source file. In practice, having both config.ts and config.mts - // in the same directory is extremely rare. - const ctx = makeCtx(['src/index.ts', 'src/config.ts', 'src/config.mts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.ts'); - }); - - it('resolves ./config.cjs to .cts when only .cts exists', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.cts']); - const result = resolve('src/index.ts', './config.cjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.cts'); - }); -}); - -describe('ESM extension resolution — directory index boundary', () => { - it('resolves ./dir.js to dir/index.ts when dir/ exists (bundler-mode)', () => { - // After stripping .js from "dir.js" → "dir", tryResolveWithExtensions probes - // "/index.ts" suffix. This matches bundler-mode behavior where bare directory - // imports resolve to index files. Intentional for source-analysis compatibility. - const ctx = makeCtx(['src/index.ts', 'src/dir/index.ts']); - const result = resolve('src/index.ts', './dir.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/dir/index.ts'); - }); - - it('resolves ./dir/index.js to dir/index.ts', () => { - const ctx = makeCtx(['src/index.ts', 'src/dir/index.ts']); - const result = resolve('src/index.ts', './dir/index.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/dir/index.ts'); - }); -}); - -describe('stripJsExtension', () => { - it('strips .js', () => expect(stripJsExtension('foo/bar.js')).toBe('foo/bar')); - it('strips .jsx', () => expect(stripJsExtension('foo/bar.jsx')).toBe('foo/bar')); - it('strips .mjs', () => expect(stripJsExtension('foo/bar.mjs')).toBe('foo/bar')); - it('strips .cjs', () => expect(stripJsExtension('foo/bar.cjs')).toBe('foo/bar')); - it('returns null for .ts', () => expect(stripJsExtension('foo/bar.ts')).toBeNull()); - it('returns null for no extension', () => expect(stripJsExtension('foo/bar')).toBeNull()); -}); - -describe('ESM extension resolution — path aliases with .js extensions', () => { - const aliasAtToSrc = new Map([['@/', 'src/']]); - const aliasTildeToSrc = new Map([['~/', 'src/']]); - - function resolveWithAlias( - currentFile: string, - importPath: string, - ctx: ReturnType, - aliases: Map, - baseUrl = '.', - ): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - SupportedLanguages.TypeScript, - { aliases, baseUrl }, - ctx.index, - ); - } - - it('resolves @/utils.js to src/utils.ts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.ts']); - const result = resolveWithAlias('src/index.ts', '@/utils.js', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/utils.ts'); - }); - - it('resolves @/component.jsx to src/component.tsx via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/component.tsx']); - const result = resolveWithAlias('src/index.ts', '@/component.jsx', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/component.tsx'); - }); - - it('resolves @/config.mjs to src/config.mts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.mts']); - const result = resolveWithAlias('src/index.ts', '@/config.mjs', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/config.mts'); - }); - - it('resolves @/legacy.cjs to src/legacy.cts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/legacy.cts']); - const result = resolveWithAlias('src/index.ts', '@/legacy.cjs', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/legacy.cts'); - }); - - it('prefers actual .js file over TS fallback in alias resolution', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.js', 'src/utils.ts']); - const result = resolveWithAlias('src/index.ts', '@/utils.js', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/utils.js'); - }); - - it('resolves alias with baseUrl prefix', () => { - const ctx = makeCtx(['app/src/index.ts', 'app/src/helpers/token.ts']); - const result = resolveWithAlias( - 'app/src/index.ts', - '~/helpers/token.js', - ctx, - aliasTildeToSrc, - 'app', - ); - expect(result).toBe('app/src/helpers/token.ts'); - }); - - it('returns null when alias .js import has no matching source', () => { - const ctx = makeCtx(['src/index.ts']); - const result = resolveWithAlias('src/index.ts', '@/missing.js', ctx, aliasAtToSrc, '.'); - expect(result).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/import-path-candidates.test.ts b/gitnexus/test/unit/import-path-candidates.test.ts new file mode 100644 index 0000000000..fd5fbe0bc8 --- /dev/null +++ b/gitnexus/test/unit/import-path-candidates.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import { + buildSuffixIndex, + suffixResolve, + tryResolveWithExtensions, +} from '../../src/core/ingestion/utils/suffix-index.js'; + +describe('caller-owned import path candidates', () => { + const files = ['pkg/item.alpha', 'pkg/item.beta']; + const extensions = ['.beta', '.alpha']; + + it('uses the caller priority and refuses extensions the caller did not select', () => { + const paths = new Set(files); + expect(tryResolveWithExtensions('pkg/item', paths, extensions)).toBe('pkg/item.beta'); + expect(tryResolveWithExtensions('pkg/item', paths, ['.missing'])).toBeNull(); + }); + + it.each(['indexed', 'linear'])('uses the same candidate policy for %s suffix lookup', (mode) => { + const index = mode === 'indexed' ? buildSuffixIndex(files, files) : undefined; + expect(suffixResolve(['item'], files, files, extensions, index)).toBe('pkg/item.beta'); + expect(suffixResolve(['item'], files, files, ['.missing'], index)).toBeNull(); + }); +}); diff --git a/gitnexus/test/unit/import-resolver-factory.test.ts b/gitnexus/test/unit/import-resolver-factory.test.ts deleted file mode 100644 index 90c0c5d955..0000000000 --- a/gitnexus/test/unit/import-resolver-factory.test.ts +++ /dev/null @@ -1,655 +0,0 @@ -/** - * Unit tests for the import resolver factory and per-strategy composition. - * - * Validates that: - * - createImportResolver chains strategies in order - * - First non-null result wins - * - Empty files array stops the chain (absorbing sentinel) - * - All per-language configs produce valid resolvers - */ - -import { describe, it, expect } from 'vitest'; -import { createImportResolver } from '../../src/core/ingestion/import-resolvers/resolver-factory.js'; -import { createStandardStrategy } from '../../src/core/ingestion/import-resolvers/standard.js'; -import type { - ImportResolutionConfig, - ImportResolverStrategy, - ResolveCtx, -} from '../../src/core/ingestion/import-resolvers/types.js'; -import { SupportedLanguages } from 'gitnexus-shared'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; - -// ── Per-language strategy imports (from config files) ────────────────── -import { goPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/go.js'; -import { - javaJvmStrategy, - kotlinJvmStrategy, -} from '../../src/core/ingestion/import-resolvers/configs/jvm.js'; -import { pythonImportStrategy } from '../../src/core/ingestion/import-resolvers/configs/python.js'; -import { csharpNamespaceStrategy } from '../../src/core/ingestion/import-resolvers/configs/csharp.js'; -import { dartPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { rustModuleStrategy } from '../../src/core/ingestion/import-resolvers/configs/rust.js'; -import { phpPsr4Strategy } from '../../src/core/ingestion/import-resolvers/configs/php.js'; -import { swiftPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/swift.js'; -import { rubyRequireStrategy } from '../../src/core/ingestion/import-resolvers/configs/ruby.js'; - -// ── Per-language config imports ──────────────────────────────────────── -import { - typescriptImportConfig, - javascriptImportConfig, - vueImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/typescript-javascript.js'; -import { - cImportConfig, - cppImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/c-cpp.js'; -import { goImportConfig } from '../../src/core/ingestion/import-resolvers/configs/go.js'; -import { - javaImportConfig, - kotlinImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/jvm.js'; -import { pythonImportConfig } from '../../src/core/ingestion/import-resolvers/configs/python.js'; -import { rustImportConfig } from '../../src/core/ingestion/import-resolvers/configs/rust.js'; -import { csharpImportConfig } from '../../src/core/ingestion/import-resolvers/configs/csharp.js'; -import { phpImportConfig } from '../../src/core/ingestion/import-resolvers/configs/php.js'; -import { swiftImportConfig } from '../../src/core/ingestion/import-resolvers/configs/swift.js'; -import { dartImportConfig } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { rubyImportConfig } from '../../src/core/ingestion/import-resolvers/configs/ruby.js'; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -function makeCtx(files: string[], overrides: Partial = {}): ResolveCtx { - const allFileList = files; - const normalizedFileList = files.map((p) => p.replace(/\\/g, '/')); - const allFilePaths = new Set(allFileList); - const index = buildSuffixIndex(normalizedFileList, allFileList); - return { - allFilePaths, - allFileList, - normalizedFileList, - index, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - ...overrides, - }, - }; -} - -// --------------------------------------------------------------------------- -// createImportResolver — factory behavior -// --------------------------------------------------------------------------- - -describe('createImportResolver', () => { - it('returns null when no strategies match', () => { - const config: ImportResolutionConfig = { - language: SupportedLanguages.TypeScript, - strategies: [], - }; - const resolver = createImportResolver(config); - expect(resolver('./foo', 'src/index.ts', makeCtx([]))).toBeNull(); - }); - - it('returns first non-null result from strategy chain', () => { - const strategyA: ImportResolverStrategy = () => null; - const strategyB: ImportResolverStrategy = () => ({ kind: 'files', files: ['b.ts'] }); - const strategyC: ImportResolverStrategy = () => ({ kind: 'files', files: ['c.ts'] }); - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [strategyA, strategyB, strategyC], - }); - - const result = resolver('./foo', 'src/index.ts', makeCtx(['b.ts', 'c.ts'])); - expect(result).toEqual({ kind: 'files', files: ['b.ts'] }); - }); - - it('stops chain when strategy returns result with empty files (absorbing sentinel)', () => { - const absorber: ImportResolverStrategy = () => ({ kind: 'files', files: [] }); - const shouldNotRun: ImportResolverStrategy = () => ({ - kind: 'files', - files: ['should-not.ts'], - }); - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [absorber, shouldNotRun], - }); - - const result = resolver('./foo', 'src/index.ts', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('passes correct arguments to strategies', () => { - const ctx = makeCtx(['src/utils.ts']); - const captured: { raw: string; fp: string }[] = []; - - const spy: ImportResolverStrategy = (raw, fp) => { - captured.push({ raw, fp }); - return null; - }; - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [spy], - }); - - resolver('./utils', 'src/index.ts', ctx); - expect(captured).toEqual([{ raw: './utils', fp: 'src/index.ts' }]); - }); -}); - -// --------------------------------------------------------------------------- -// Per-language strategies — behavioral coverage -// -// The previous `typeof strategy === 'function'` assertions were tautological: -// TypeScript's `ImportResolverStrategy` type enforces the function shape at -// compile time, so those tests could never fail. Each strategy now has at -// least one behavioral assertion below; the Go and C# full-chain tests also -// double as strategy-order guards because their `kind: 'package'` output is -// unreachable through `createStandardStrategy`. -// --------------------------------------------------------------------------- - -describe('goPackageStrategy', () => { - it('resolves go.mod package imports to a package result with dirSuffix', () => { - const files = ['cmd/server/main.go', 'cmd/server/handler.go']; - const ctx = makeCtx(files, { goModule: { modulePath: 'example.com/app' } }); - - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - // `kind: 'package'` + `dirSuffix` is unique to goPackageStrategy — the - // standard strategy always returns `kind: 'files'`. Asserting the exact - // shape makes format regressions observable (e.g. prefix/suffix slash - // normalization) and makes strategy ordering observable via the - // full-chain test in `goImportConfig` below. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/cmd/server/', - }); - }); - - it('returns null for imports outside the go module (allows chain to continue)', () => { - const ctx = makeCtx(['vendor/other/pkg/foo.go'], { - goModule: { modulePath: 'example.com/app' }, - }); - const result = goPackageStrategy('github.com/other/pkg', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('returns null when goModule is not configured', () => { - const ctx = makeCtx(['cmd/server/main.go']); - expect(ctx.configs.goModule).toBeNull(); - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('returns null when module prefix matches but package directory has no .go files', () => { - // Documented fall-through in configs/go.ts:27 — when resolveGoPackageDir - // returns non-null but resolveGoPackage returns an empty files list - // (external module coincidentally sharing the prefix, or a subpackage with - // no .go sources), the strategy returns null so the chain can continue. - const ctx = makeCtx(['README.md', 'cmd/server/config.yaml'], { - goModule: { modulePath: 'example.com/app' }, - }); - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('goImportConfig full chain produces the package-kind result (strategy-order guard)', () => { - const files = ['cmd/server/main.go', 'cmd/server/handler.go']; - const ctx = makeCtx(files, { goModule: { modulePath: 'example.com/app' } }); - - const resolver = createImportResolver(goImportConfig); - const result = resolver('example.com/app/cmd/server', 'main.go', ctx); - // If goPackageStrategy were moved after createStandardStrategy, the - // standard strategy's suffix resolution would return a single file with - // `kind: 'files'` (or null), not `kind: 'package'` with a dirSuffix. - // Asserting the full shape (not just kind) guards against a future - // regression that emits `kind: 'package'` with mismatched files. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/cmd/server/', - }); - }); -}); - -describe('javaJvmStrategy', () => { - it('resolves wildcard imports to .java files in the package directory', () => { - const files = [ - 'src/main/java/com/example/foo/Bar.java', - 'src/main/java/com/example/foo/Baz.java', - 'src/main/java/com/example/other/Unrelated.java', - ]; - const ctx = makeCtx(files); - const result = javaJvmStrategy('com.example.foo.*', 'App.java', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'src/main/java/com/example/foo/Bar.java', - 'src/main/java/com/example/foo/Baz.java', - ]), - ); - expect(result?.files).not.toContain('src/main/java/com/example/other/Unrelated.java'); - }); - - it('resolves member imports to the owning class file', () => { - const files = ['src/main/java/com/example/Constants.java']; - const ctx = makeCtx(files); - // JVM member import: last segment is an ALL_CAPS constant / lowercase - // member; resolver walks back to the class path `com/example/Constants`. - const result = javaJvmStrategy('com.example.Constants.VALUE', 'App.java', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no matching .java files exist', () => { - const ctx = makeCtx(['src/main/java/other/Foo.java']); - const result = javaJvmStrategy('com.example.missing.*', 'App.java', ctx); - expect(result).toBeNull(); - }); -}); - -describe('kotlinJvmStrategy', () => { - it('resolves wildcard imports to files in the package directory', () => { - const files = [ - 'src/main/kotlin/com/example/foo/Bar.kt', - 'src/main/kotlin/com/example/foo/Baz.kt', - 'src/main/kotlin/com/example/other/Unrelated.kt', - ]; - const ctx = makeCtx(files); - - const result = kotlinJvmStrategy('com.example.foo.*', 'App.kt', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'src/main/kotlin/com/example/foo/Bar.kt', - 'src/main/kotlin/com/example/foo/Baz.kt', - ]), - ); - expect(result?.files).not.toContain('src/main/kotlin/com/example/other/Unrelated.kt'); - }); - - it('resolves member imports to the owning class file', () => { - const files = ['src/main/kotlin/com/example/Constants.kt']; - const ctx = makeCtx(files); - const result = kotlinJvmStrategy('com.example.Constants.VALUE', 'App.kt', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null for wildcard with no matching files (allows chain to continue)', () => { - const ctx = makeCtx(['src/main/kotlin/com/example/other/Foo.kt']); - const result = kotlinJvmStrategy('com.example.missing.*', 'App.kt', ctx); - expect(result).toBeNull(); - }); - - it('kotlinImportConfig full chain resolves wildcard via the JVM strategy', () => { - // Note: this is a behavioral smoke test, NOT a strategy-order guard. - // `createStandardStrategy(Kotlin)` explicitly returns null for any import - // ending in `.*` (see standard.ts:137), so reordering `kotlinImportConfig` - // strategies would still produce the same result — the standard strategy - // would return null and the chain would fall through to kotlinJvmStrategy - // regardless of position. A genuine ordering guard for Kotlin would need - // a non-wildcard fixture where both strategies resolve to different files. - const files = ['src/main/kotlin/com/example/foo/Bar.kt']; - const ctx = makeCtx(files); - const resolver = createImportResolver(kotlinImportConfig); - const result = resolver('com.example.foo.*', 'App.kt', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); -}); - -describe('rustModuleStrategy', () => { - it('resolves scoped grouped imports to per-item files', () => { - const files = ['src/models/User.rs', 'src/models/Repo.rs']; - const ctx = makeCtx(files); - // `use crate::models::{User, Repo}` — the strategy resolves each item - // individually against the allFilePaths set via resolveRustImportInternal. - const result = rustModuleStrategy('crate::models::{User, Repo}', 'src/lib.rs', ctx); - // Exact file discovery depends on resolveRustImportInternal's search - // heuristics; we assert the shape + that at least one item resolved. - expect(result?.kind).toBe('files'); - expect(result?.files.length).toBeGreaterThan(0); - }); - - it('returns null for non-grouped imports (delegates to standard fallback)', () => { - const ctx = makeCtx(['src/models.rs']); - // Plain `use crate::models` — rustModuleStrategy only handles grouped - // forms; standard strategy handles the crate:: -> path translation. - const result = rustModuleStrategy('crate::models', 'src/lib.rs', ctx); - expect(result).toBeNull(); - }); -}); - -describe('csharpNamespaceStrategy', () => { - it('resolves namespace imports via .csproj root-namespace mapping', () => { - const files = ['src/Services/Auth/AuthService.cs', 'src/Services/Auth/TokenService.cs']; - const ctx = makeCtx(files, { - csharpConfigs: [{ rootNamespace: 'MyCo', projectDir: 'src' }], - }); - - const result = csharpNamespaceStrategy('MyCo.Services.Auth', 'App.cs', ctx); - // Multi-file namespace resolution produces `kind: 'package'` with - // dirSuffix — unique to csharpNamespaceStrategy; the standard strategy - // always emits `kind: 'files'`. Asserting the full shape (including the - // exact dirSuffix format) guards against format regressions. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/src/Services/Auth/', - }); - }); - - it('returns null when no csharpConfigs are configured', () => { - const ctx = makeCtx(['src/Services/Auth/AuthService.cs']); - expect(ctx.configs.csharpConfigs).toEqual([]); - const result = csharpNamespaceStrategy('MyCo.Services.Auth', 'App.cs', ctx); - expect(result).toBeNull(); - }); - - it('no csproj + non-aligned BCL import: stops the chain instead of the ungated standard strategy (#2)', () => { - // Parity with the registry leg's no-csproj path. Without csproj configs the - // generic strategy would suffix-match `System.Threading.Tasks` onto the - // coincidental local `Legacy/Tasks.cs`. The gate sees the import aligns - // with no declared namespace, so the strategy returns an absorbing sentinel - // (`{ kind: 'files', files: [] }`) that STOPS the chain — the standard - // strategy never runs and no spurious edge is emitted. - const ctx = makeCtx(['Services/OrderService.cs', 'Legacy/Tasks.cs'], { - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Services', 'MyApp.Legacy']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy( - 'System.Threading.Tasks', - 'Services/OrderService.cs', - ctx, - ); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('no csproj + in-repo-aligned import: keeps delegating to the standard strategy (#2)', () => { - // An import that DOES align with a declared namespace must keep returning - // null so the generic strategy resolves it — legitimate no-csproj behavior - // is unchanged; only non-aligned (BCL) imports are stopped. - const ctx = makeCtx(['Services/OrderService.cs', 'Models/User.cs'], { - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Models', 'MyApp.Services']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy('MyApp.Models', 'Services/OrderService.cs', ctx); - expect(result).toBeNull(); - }); - - it('returns an empty files result (chain-stop) for a gated BCL import when csproj configs exist (#1881, #8)', () => { - // Legacy DAG leg of #1881: with csproj configs present, a BCL using like - // `System.Threading.Tasks` must NOT suffix-match the coincidental local - // `Legacy/Tasks.cs`. The strategy returns `{ kind: 'files', files: [] }` - // (absorbing sentinel) to STOP the chain, NOT null — null would let the - // generic suffix fallback re-introduce the spurious edge. - const ctx = makeCtx(['Services/OrderService.cs', 'Legacy/Tasks.cs'], { - csharpConfigs: [{ rootNamespace: 'MyApp', projectDir: '' }], - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Services', 'MyApp.Legacy']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy( - 'System.Threading.Tasks', - 'Services/OrderService.cs', - ctx, - ); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('csharpImportConfig full chain produces package-kind (strategy-order guard)', () => { - const files = ['src/Services/Auth/AuthService.cs', 'src/Services/Auth/TokenService.cs']; - const ctx = makeCtx(files, { - csharpConfigs: [{ rootNamespace: 'MyCo', projectDir: 'src' }], - }); - - const resolver = createImportResolver(csharpImportConfig); - const result = resolver('MyCo.Services.Auth', 'App.cs', ctx); - // If csharpNamespaceStrategy were reordered after createStandardStrategy, - // the result would be `kind: 'files'` (suffix match) or null, never - // `kind: 'package'` with a dirSuffix. Asserting the full shape (not just - // kind) guards against a regression that emits `kind: 'package'` with - // mismatched files. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/src/Services/Auth/', - }); - }); -}); - -describe('phpPsr4Strategy', () => { - it('resolves PSR-4 namespace imports via composer.json autoload map', () => { - const files = ['app/Services/UserService.php']; - const ctx = makeCtx(files, { - composerConfig: { - psr4: new Map([['App\\', 'app/']]), - }, - }); - const result = phpPsr4Strategy('App\\Services\\UserService', 'index.php', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no file matches the namespace via PSR-4 or suffix fallback', () => { - const ctx = makeCtx(['app/Services/OtherService.php'], { - composerConfig: { psr4: new Map([['App\\', 'app/']]) }, - }); - const result = phpPsr4Strategy('App\\Services\\UserService', 'index.php', ctx); - expect(result).toBeNull(); - }); -}); - -describe('swiftPackageStrategy', () => { - it('resolves SwiftPM target imports to files in the target directory', () => { - const files = [ - 'Package/Sources/SiuperModel/Foo.swift', - 'Package/Sources/SiuperModel/Bar.swift', - 'Package/Sources/Other/Unrelated.swift', - ]; - const ctx = makeCtx(files, { - swiftPackageConfig: { - targets: new Map([['SiuperModel', 'Package/Sources/SiuperModel']]), - }, - }); - const result = swiftPackageStrategy('SiuperModel', 'App.swift', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'Package/Sources/SiuperModel/Foo.swift', - 'Package/Sources/SiuperModel/Bar.swift', - ]), - ); - expect(result?.files).not.toContain('Package/Sources/Other/Unrelated.swift'); - }); - - it('returns null for unknown targets (external frameworks like Foundation)', () => { - const ctx = makeCtx(['Package/Sources/SiuperModel/Foo.swift'], { - swiftPackageConfig: { - targets: new Map([['SiuperModel', 'Package/Sources/SiuperModel']]), - }, - }); - const result = swiftPackageStrategy('Foundation', 'App.swift', ctx); - expect(result).toBeNull(); - }); - - it('does not resolve inferred grouping folders when the declaration is empty', () => { - const ctx = makeCtx(['Sources/Foundation/Thing.swift', 'Sources/App/main.swift'], { - swiftPackageConfig: { - origin: 'package.swift', - targets: new Map([ - ['Foundation', 'Sources/Foundation'], - ['App', 'Sources/App'], - ]), - declaredTargets: new Map(), - }, - }); - expect(swiftPackageStrategy('Foundation', 'Sources/App/main.swift', ctx)).toBeNull(); - expect(swiftPackageStrategy('App', 'Sources/App/main.swift', ctx)).toBeNull(); - }); - - it('ignores an inferred directories origin', () => { - const ctx = makeCtx(['Sources/Models/User.swift'], { - swiftPackageConfig: { - origin: 'directories', - targets: new Map([['Models', 'Sources/Models']]), - }, - }); - expect(swiftPackageStrategy('Models', 'Sources/App/main.swift', ctx)).toBeNull(); - }); -}); - -describe('rubyRequireStrategy', () => { - it('resolves require_relative paths via suffix matching', () => { - const files = ['lib/models/user.rb']; - const ctx = makeCtx(files); - const result = rubyRequireStrategy('./models/user', 'lib/app.rb', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no file matches the require path', () => { - const ctx = makeCtx(['lib/models/user.rb']); - const result = rubyRequireStrategy('./missing/file', 'lib/app.rb', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Per-language configs — all construct cleanly -// --------------------------------------------------------------------------- - -describe('per-language import configs', () => { - const configs: { name: string; config: ImportResolutionConfig }[] = [ - { name: 'TypeScript', config: typescriptImportConfig }, - { name: 'JavaScript', config: javascriptImportConfig }, - { name: 'Vue', config: vueImportConfig }, - { name: 'C', config: cImportConfig }, - { name: 'C++', config: cppImportConfig }, - { name: 'Go', config: goImportConfig }, - { name: 'Java', config: javaImportConfig }, - { name: 'Kotlin', config: kotlinImportConfig }, - { name: 'Python', config: pythonImportConfig }, - { name: 'Rust', config: rustImportConfig }, - { name: 'C#', config: csharpImportConfig }, - { name: 'PHP', config: phpImportConfig }, - { name: 'Swift', config: swiftImportConfig }, - { name: 'Dart', config: dartImportConfig }, - { name: 'Ruby', config: rubyImportConfig }, - ]; - - for (const { name, config } of configs) { - it(`${name} config has strategies and constructs a resolver`, () => { - expect(config.strategies.length).toBeGreaterThan(0); - expect(() => createImportResolver(config)).not.toThrow(); - }); - } -}); - -// --------------------------------------------------------------------------- -// createStandardStrategy — reusable across languages -// --------------------------------------------------------------------------- - -describe('createStandardStrategy', () => { - it('creates a reusable strategy from a language', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - expect(typeof strategy).toBe('function'); - }); - - it('resolves relative imports', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - const ctx = makeCtx(['src/utils.ts']); - const result = strategy('./utils', 'src/index.ts', ctx); - expect(result).toEqual({ kind: 'files', files: ['src/utils.ts'] }); - }); - - it('returns null for unresolvable imports', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - const ctx = makeCtx([]); - const result = strategy('./nonexistent', 'src/index.ts', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Python strategy — absorbs unresolved relative imports -// --------------------------------------------------------------------------- - -describe('pythonImportStrategy', () => { - it('absorbs unresolved relative imports with empty-files sentinel', () => { - const ctx = makeCtx([]); - const result = pythonImportStrategy('.nonexistent', 'src/app.py', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('returns null for non-relative imports (allows chain to continue)', () => { - const ctx = makeCtx([]); - const result = pythonImportStrategy('os', 'src/app.py', ctx); - expect(result).toBeNull(); - }); - - it('absorbs unresolved external dotted imports instead of suffix-matching local basename files', () => { - const ctx = makeCtx(['accounts/apps.py', 'billing/apps.py']); - const result = pythonImportStrategy('django.apps', 'accounts/apps.py', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs unresolved nested external dotted imports like django.urls and django.core.*', () => { - const ctx = makeCtx(['config/asgi.py', 'config/urls.py', 'config/wsgi.py']); - - expect(pythonImportStrategy('django.urls', 'config/urls.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - expect(pythonImportStrategy('django.core.asgi', 'config/asgi.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - expect(pythonImportStrategy('django.core.wsgi', 'config/wsgi.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - }); - - it('keeps dotted internal imports unresolved here when the leading package exists in-repo', () => { - const ctx = makeCtx(['accounts/models.py', 'billing/models.py']); - const result = pythonImportStrategy('accounts.models', 'billing/models.py', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Dart strategies — absorbs SDK / external package imports -// --------------------------------------------------------------------------- - -describe('dartPackageStrategy', () => { - it('absorbs dart: SDK imports', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'dart:async'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs external package: imports', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('returns null for relative imports (chains to dartRelativeStrategy)', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'models.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts index d3ed9b42da..989f563214 100644 --- a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts +++ b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts @@ -34,32 +34,28 @@ * below pins that: it drives the naive cleanup and asserts it CHANGES answers. * * The arms all assert the full `string[]` and its order — this resolver returns - * every match, not one, and `configs/csharp.ts` turns a multi-file result into a - * `kind: 'package'` edge set whose order reaches the graph. + * every match, not one, and the active scope resolver selects the first match. */ import { describe, expect, it } from 'vitest'; -import { - resolveCSharpImportInternal, - resolveCSharpNamespaceDir, -} from '../../../src/core/ingestion/import-resolvers/csharp.js'; +import { resolveCSharpImportInternal } from '../../../src/core/ingestion/languages/csharp/import-helpers.js'; import { buildSuffixIndex, suffixResolve, type SuffixIndex, -} from '../../../src/core/ingestion/import-resolvers/utils.js'; -import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/csharp-namespace-gate.js'; +} from '../../../src/core/ingestion/utils/suffix-index.js'; +import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; import type { CSharpProjectConfig, CSharpNamespaceEvidence, } from '../../../src/core/ingestion/language-config.js'; +import { EXTENSIONS } from '../../../src/core/ingestion/languages/import-candidates.js'; // ─── verbatim pre-change implementation ────────────────────────────────────── -// `git show HEAD~:gitnexus/src/core/ingestion/import-resolvers/csharp.ts`, body -// copied unchanged. Its helpers (`suffixResolve`, `csharpSuffixFallbackAllowed`, -// `SuffixIndex`) are imported from production because this PR does not touch -// them; only the function below changed. +// Frozen implementation from before the direct-child probe optimization. +// Its helpers (`suffixResolve`, `csharpSuffixFallbackAllowed`, `SuffixIndex`) +// are imported from production; the frozen function retains the original probe. /** * The direct-child probe the frozen copies below run — four call sites, two in @@ -164,7 +160,7 @@ function legacyResolveCSharpImportInternal( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } @@ -245,7 +241,7 @@ function skipStep3WhenIndexed( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } @@ -458,19 +454,6 @@ describe('C# csproj leg — directory index vs the pre-change linear scan (#2902 } expect(current).toEqual(legacy); }); - - it('leaves `resolveCSharpNamespaceDir` — the sibling that shares the dirPrefix maths — alone', () => { - const dirs: Record = {}; - for (const [shape, configs] of CONFIG_SHAPES) { - for (const importPath of IMPORTS) { - dirs[`${shape} | ${importPath}`] = resolveCSharpNamespaceDir(importPath, configs); - } - } - expect(dirs['projectDir=src | App.Models']).toBe('/src/Models/'); - expect(dirs['no projectDir | App']).toBeNull(); - expect(dirs['no projectDir | App.Models']).toBe('/Models/'); - expect(dirs['no config matches | App.Models']).toBeNull(); - }); }); describe('C# csproj leg — the answers only step 3 can give (#2902)', () => { diff --git a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts deleted file mode 100644 index bf2d0e6534..0000000000 --- a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Coverage for `resolveGoPackage` (`import-resolvers/go.ts`), which had none. - * - * Go resolves package imports through two independent legs. The ScopeResolver - * leg (`languages/go/import-target.ts`) answers from `buildPackageDirIndex`; - * this one is the LanguageProvider leg, wired through `configs/go.ts`, and it - * is still a per-import scan. #2881 changed its membership rule — a directory - * whose name repeats higher in the path is now a member — and review found the - * change reached production with nothing watching it: `bench/import-target`'s - * go arm drives the indexed leg only, and no test called this function. - * - * These cases pin the rule and the two legs' agreement on it, so a revert fails - * here rather than silently moving Go IMPORTS edges in every repository that - * nests a package name inside itself (`internal/…/internal` is the shape Go - * actually produces). - * - * One caveat on "the LanguageProvider leg", recorded in #2929 review: nothing - * in production reads that field today. `configs/go.ts` reaches this function - * through `createImportResolver` → `LanguageProvider.importResolver`, and the - * only readers of `importResolver` are `import-target-adapter.ts:74-75`, whose - * two exports have no importer outside their own unit test. So the leg is wired - * but unreached, and this file is the only thing exercising it. - */ -import { describe, expect, it } from 'vitest'; -import { - resolveGoPackage, - resolveGoPackageDir, -} from '../../../src/core/ingestion/import-resolvers/go.js'; -import type { GoModuleConfig } from '../../../src/core/ingestion/language-config.js'; -import { - buildPackageDirIndex, - filesDirectlyInPkgDir, -} from '../../../src/core/ingestion/import-resolvers/package-dir-index.js'; - -const MOD: GoModuleConfig = { modulePath: 'example.com/mod' }; - -function resolve(files: readonly string[], importPath: string): string[] { - const normalized = files.map((f) => f.replace(/\\/g, '/')); - return resolveGoPackage(importPath, MOD, normalized, files); -} - -/** - * The indexed membership rule, for the agreement arm: the package-dir index - * the ScopeResolver leg's GOPATH match answers from, asked the module-relative - * path this leg asks. Not `resolveGoImportTarget` itself any more — its module - * leg now names the exact directory under the module root, deliberately unlike - * this leg's suffix match (see `languages/go/workspace-config.ts`). - */ -function indexed(files: readonly string[], importPath: string): readonly string[] { - const index = buildPackageDirIndex( - new Set(files), - (normalized) => normalized.endsWith('.go') && !normalized.endsWith('_test.go'), - ); - return filesDirectlyInPkgDir(index, importPath.slice(MOD.modulePath.length + 1)); -} - -describe('resolveGoPackage', () => { - it('returns every .go file directly inside the package directory', () => { - const files = ['internal/auth/service.go', 'internal/auth/token.go', 'internal/auth/sub/x.go']; - expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ - 'internal/auth/service.go', - 'internal/auth/token.go', - ]); - }); - - it('a package directory nested inside a same-named one IS a member (#2881)', () => { - // The scan asked `indexOf` for the FIRST `/pkg/` and then required nothing - // after it to hold a slash, so this resolved to nothing. Both halves of the - // shape: the repeat leading the path, and the repeat mid-path. - expect(resolve(['pkg/src/go/pkg/repo.go'], 'example.com/mod/pkg')).toEqual([ - 'pkg/src/go/pkg/repo.go', - ]); - expect(resolve(['a/pkg/b/pkg/x.go'], 'example.com/mod/pkg')).toEqual(['a/pkg/b/pkg/x.go']); - expect(resolve(['svc/internal/sub/internal/x.go'], 'example.com/mod/internal')).toEqual([ - 'svc/internal/sub/internal/x.go', - ]); - }); - - it('a repeated name that is not the parent directory is still not a member', () => { - // The rule is "the parent directory ends with the package path", not - // "the package path appears anywhere". - expect(resolve(['a/pkg/b/x.go'], 'example.com/mod/pkg')).toEqual([]); - expect(resolve(['internal/auth/sub/x.go'], 'example.com/mod/internal/auth')).toEqual([]); - }); - - it('multi-segment package paths match on the whole run, not the last segment', () => { - const files = ['a/internal/models/b/internal/models/user.go', 'a/models/other.go']; - expect(resolve(files, 'example.com/mod/internal/models')).toEqual([ - 'a/internal/models/b/internal/models/user.go', - ]); - }); - - it('_test.go files are a different package and never match', () => { - expect( - resolve( - ['internal/auth/service.go', 'internal/auth/service_test.go'], - 'example.com/mod/internal/auth', - ), - ).toEqual(['internal/auth/service.go']); - }); - - it('non-.go files never match, and the RAW path is returned for backslashes', () => { - expect( - resolve(['internal/auth/README.md', 'internal/auth/x.go'], 'example.com/mod/internal/auth'), - ).toEqual(['internal/auth/x.go']); - expect(resolve(['internal\\auth\\x.go'], 'example.com/mod/internal/auth')).toEqual([ - 'internal\\auth\\x.go', - ]); - }); - - it('an import outside the module, or the module root itself, resolves to nothing here', () => { - expect(resolve(['internal/auth/x.go'], 'github.com/other/repo/internal/auth')).toEqual([]); - // The root package is the caller's `findRootPackageFiles` leg, not this one. - expect(resolve(['main.go'], 'example.com/mod')).toEqual([]); - expect(resolveGoPackageDir('example.com/mod', MOD)).toBeNull(); - expect(resolveGoPackageDir('example.com/mod/internal/auth', MOD)).toBe('/internal/auth/'); - }); - - it('vendor/, testdata/ and nested-module directories all merge in (unmodelled)', () => { - // Go excludes all three from a package: `vendor/` is a dependency tree - // resolved against the vendoring module, the go tool ignores `testdata/` - // entirely, and a directory carrying its own `go.mod` is a separate module - // whose packages this module's import paths never name. - // - // This resolver models NONE of that — it matches on the parent directory's - // path suffix alone. That is unchanged by #2881: the pre-#2881 rule - // (first `//`, nothing but a filename after it) accepted all three - // shapes too. These assertions record what the function actually does so - // the gap is visible and a change to it is deliberate; they document the - // behaviour rather than endorse it. - const files = [ - 'go.mod', - 'internal/auth/service.go', - 'vendor/example.com/dep/internal/auth/vendored.go', - 'testdata/internal/auth/fixture.go', - 'sub/go.mod', // `sub/` is its own module; its packages are not ours - 'sub/internal/auth/other_module.go', - ]; - expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ - 'internal/auth/service.go', - 'vendor/example.com/dep/internal/auth/vendored.go', - 'testdata/internal/auth/fixture.go', - 'sub/internal/auth/other_module.go', - ]); - // A `go.mod` beside the files changes nothing — it is not read here. - expect(resolve(['sub/go.mod', 'sub/pkg/x.go'], 'example.com/mod/pkg')).toEqual([ - 'sub/pkg/x.go', - ]); - }); - - it('agrees with the indexed membership rule on the repeated-name shapes', () => { - // The two are independent implementations of one rule. Before #2881 they - // agreed on the wrong answer; they must agree on the right one, or this - // leg and the GOPATH match disagree about which files a package holds. - for (const files of [ - ['pkg/src/go/pkg/repo.go'], - ['a/pkg/b/pkg/x.go'], - ['a/pkg/b/x.go'], - ['internal/auth/service.go', 'internal/auth/token.go'], - ['a/internal/models/b/internal/models/user.go'], - ]) { - for (const target of [ - 'example.com/mod/pkg', - 'example.com/mod/internal/auth', - 'example.com/mod/internal/models', - ]) { - expect(resolve(files, target)).toEqual([...indexed(files, target)]); - } - } - }); -}); diff --git a/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts b/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts index c6e2fcc224..ce0e9f0a5e 100644 --- a/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts +++ b/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts @@ -1,6 +1,6 @@ /** * Gate for the single-segment bare-import ancestor walk in - * `import-resolvers/python.ts`: Python bare-import resolution must not scale + * `languages/python/import-helpers.ts`: Python bare-import resolution must not scale * with the importer's path depth. * * #2913 memoized the ancestor chains inside `languages/python/import-target.ts` @@ -34,11 +34,8 @@ * again, and with a non-vacuity assertion, because a perfect count is equally * true of a resolver that stopped resolving anything. * - * Both production surfaces are driven, not the helper: `pythonScopeResolver - * .resolveImportTarget` (the scope-resolution orchestrator's adapter, the one - * that pays the walk twice) and `pythonImportStrategy` (the import-resolver - * pipeline's, via `ImportTargetWorkspace`'s shared `ResolveCtx`). They thread - * different objects around the same Set, and the memo is keyed on the Set. + * The production entry point is `pythonScopeResolver.resolveImportTarget`, + * which can reach the walk twice. The memo is keyed on the shared file Set. * * `legacyPrefixes` is a verbatim copy of the pre-change inline code, in the * house style of `python-importer-ancestors.test.ts`: it is the specification, @@ -58,18 +55,12 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import type { ImportResolutionContext } from '../../../src/core/ingestion/scope-resolution/contract/scope-resolver.js'; import { pythonScopeResolver } from '../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { resolvePythonImportInternal } from '../../../src/core/ingestion/import-resolvers/python.js'; -import { getPythonFileIndex } from '../../../src/core/ingestion/import-resolvers/python-file-index.js'; +import { resolvePythonImportInternal } from '../../../src/core/ingestion/languages/python/import-helpers.js'; +import { getPythonFileIndex } from '../../../src/core/ingestion/languages/python/import-file-index.js'; /** The bare-import prefix memo, which lives inside the shared per-file-set index. */ const prefixMemo = (files: ReadonlySet): ReadonlyMap => getPythonFileIndex(files).bareImportPrefixesByDir; -import { pythonImportStrategy } from '../../../src/core/ingestion/import-resolvers/configs/python.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; -import type { - ImportResult, - ResolveCtx, -} from '../../../src/core/ingestion/import-resolvers/types.js'; import { IMPORTER_PATH_SHAPES, NO_PARSED_FILES, @@ -101,44 +92,11 @@ function legacyPrefixes(currentFile: string): string[] { // ─── surfaces ──────────────────────────────────────────────────────────────── -/** - * A `ResolveCtx` for the import-resolver pipeline surface. `allFilePaths` is - * the caller's Set passed THROUGH — the memo is keyed on its identity, so a - * copy here would measure nothing. - */ -function makeResolveCtx(allFilePaths: Set): ResolveCtx { - const allFileList = [...allFilePaths]; - const normalizedFileList = allFileList.map((file) => file.replace(/\\/g, '/')); - return { - allFilePaths, - allFileList, - normalizedFileList, - index: buildSuffixIndex(normalizedFileList, allFileList), - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, - }; -} - const ctxFor = (parsedImport: ParsedImport): ImportResolutionContext => ({ parsedFiles: NO_PARSED_FILES, parsedImport, }); -/** - * An `ImportResult` as the arms read it: the resolved path, or `null` for a - * miss. A stop-the-chain result carrying no files joins to `''`, which is - * neither the hit nor a miss — the same distinction the pre-collapse arm drew - * with `value?.kind === 'files' && value.files.join() === HIT_RESULT`. - */ -const resolvedPath = (result: ImportResult): ChainMemoResult => - result === null ? null : result.files.join(); - // ─── the workspace the surfaces are driven against ─────────────────────────── /** @@ -175,15 +133,11 @@ const WALK_TARGET = 'probe'; const ABSENT_TARGET = 'ghostmod'; /** - * The spelling sequence BOTH surfaces are driven with, `perImporter` rounds of + * The spelling sequence the adapter is driven with, `perImporter` rounds of * it plus the one spelling that must resolve: one target that walks the whole * chain and misses, one that the absence proof retires before the walk, and one * that hits at the workspace root. No spelling is varied per round — the Python * chain keeps no per-target cache, so a repeated target really is re-resolved. - * - * `resolve` is the only thing that differs between the orchestrator adapter and - * the import-resolver pipeline; everything about the sequence is shared, which - * is why the two used to be the same loop written twice. */ function drive( fromFile: string, @@ -209,25 +163,6 @@ const adapterArm = (mkImport: (targetRaw: string) => ParsedImport): ChainMemoArm hitResult: HIT_RESULT, }); -/** - * The import-resolver pipeline surface. One `ResolveCtx` per drive rather than - * one for the run, on purpose: everything the strategy reads off it is derived - * from the same Set (and `pythonImportStrategy` only ever WRITES - * `resolveCache`), so a fresh ctx around the same Set is exactly the "different - * objects, same Set" case the memo has to survive. - */ -const strategyArm: ChainMemoArm = { - memoOf: prefixMemo, - drive: (files, fromFile, perImporter) => { - const ctx = makeResolveCtx(files); - return drive(fromFile, perImporter, (target, from) => - resolvedPath(pythonImportStrategy(target, from, ctx)), - ); - }, - legacyChain: legacyPrefixes, - hitResult: HIT_RESULT, -}; - describe('Python bare-import prefix memo', () => { it.each([ { perImporter: 1, kind: 'namespace', mkImport: pythonNamespaceImport }, @@ -241,16 +176,6 @@ describe('Python bare-import prefix memo', () => { }, ); - it.each([ - { perImporter: 1, label: 'one import per importer' }, - { perImporter: 40, label: 'forty imports per importer' }, - ])( - 'holds one chain per importer DIRECTORY on the import-resolver surface too — $label', - ({ perImporter }) => { - expectOneChainPerImporterDir(strategyArm, new Set(WORKSPACE), perImporter); - }, - ); - it('reuses the SAME chain object, rather than rebuilding and re-storing it', () => { expectSameChainObjectReused(adapterArm(pythonNamedImport), new Set(WORKSPACE)); }); @@ -387,16 +312,11 @@ describe('Python bare-import ancestor walk — resolution', () => { }, ])('$why', ({ files, fromFile, expected }) => { const set = new Set(files); - // The helper, the scope-resolution adapter and the import-resolver - // strategy must agree: all three reach the same walk. + // The helper and scope-resolution adapter must reach the same walk. expect(resolvePythonImportInternal(fromFile, 'user', set)).toBe(expected); expect( resolveImportTarget('user', fromFile, set, undefined, ctxFor(pythonNamespaceImport('user'))), ).toBe(expected); - expect(pythonImportStrategy('user', fromFile, makeResolveCtx(set))).toEqual({ - kind: 'files', - files: [expected], - }); }); it.each([ diff --git a/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts b/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts index 3e4188c9c7..fe7bd4da92 100644 --- a/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts +++ b/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts @@ -20,9 +20,8 @@ * * All of it is memory. `dirMap` is the array-valued map — one entry and one * array push per file per directory component, O(files × depth) in entries and - * in churn — and only four call sites ever read it - * (`import-resolvers/{php,csharp,jvm}.ts`, `import-resolvers/configs/ - * python.ts`), yet `workspace-file-index.ts` serving Ruby, + * in churn — and only `languages/{php,csharp}/import-helpers.ts` read it, yet + * `workspace-file-index.ts` serving Ruby, * `languages/typescript/scope-resolver.ts`, `languages/vue/import-target.ts` * and `group/extractors/include-extractor.ts` all built it and never touched * it: ~15% of the retained C# index and ~19% of the retained Ruby one on @@ -79,7 +78,7 @@ import { describe, expect, it } from 'vitest'; import { buildSuffixIndex, type SuffixIndex, -} from '../../../src/core/ingestion/import-resolvers/utils.js'; +} from '../../../src/core/ingestion/utils/suffix-index.js'; // ─── verbatim pre-change implementations ───────────────────────────────────── @@ -438,7 +437,7 @@ const ONE_PASS = RAW_FILES.length; /** Lookups driven bare before a count is read — the count must not move. */ const LOOKUP_REPEATS = 20; -/** `import-resolvers/pass-cache.ts` builds exactly this: lowercased, not slash-normalized. */ +/** A lowercased input list, rather than a slash-normalized one. */ const LOWERCASED_FILES: string[] = ALL_FILES.map((f) => f.toLowerCase()); // ─── parity: the directory map ─────────────────────────────────────────────── diff --git a/gitnexus/test/unit/node-workspace-memo-rejection.test.ts b/gitnexus/test/unit/node-workspace-memo-rejection.test.ts index 90dfac825d..67f52b8bad 100644 --- a/gitnexus/test/unit/node-workspace-memo-rejection.test.ts +++ b/gitnexus/test/unit/node-workspace-memo-rejection.test.ts @@ -85,7 +85,7 @@ describe('node-workspace-packages memo: a rejected invalidated load keeps the ne it('load B survives load A rejecting after invalidation', async () => { const { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const key = path.resolve(repo); ctx.gateRoot = key; diff --git a/gitnexus/test/unit/node-workspace-nested-roots.test.ts b/gitnexus/test/unit/node-workspace-nested-roots.test.ts index fca04a4385..d5cf47e8d5 100644 --- a/gitnexus/test/unit/node-workspace-nested-roots.test.ts +++ b/gitnexus/test/unit/node-workspace-nested-roots.test.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { loadNodeWorkspacePackages, resolveNodeWorkspaceImport, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; /** * C3 — a workspace declared BELOW the repo root (keycloak: `js/pnpm-workspace.yaml`). diff --git a/gitnexus/test/unit/node-workspace-packages.test.ts b/gitnexus/test/unit/node-workspace-packages.test.ts index ecfd8ef033..77439301a0 100644 --- a/gitnexus/test/unit/node-workspace-packages.test.ts +++ b/gitnexus/test/unit/node-workspace-packages.test.ts @@ -13,7 +13,7 @@ import { nodePackageNameOf, substituteStar, type NodeWorkspacePackages, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; import { resolveTsModule } from '../../src/core/ingestion/languages/typescript/module-resolution.js'; import type { TsconfigIndex } from '../../src/core/ingestion/languages/typescript/tsconfig.js'; diff --git a/gitnexus/test/unit/node-workspace-repo-root-race.test.ts b/gitnexus/test/unit/node-workspace-repo-root-race.test.ts index 5b9f9f7f4c..c684fde4bc 100644 --- a/gitnexus/test/unit/node-workspace-repo-root-race.test.ts +++ b/gitnexus/test/unit/node-workspace-repo-root-race.test.ts @@ -106,7 +106,7 @@ describe('node-workspace-packages: entry discovery is safe under concurrent scan it("repo B finishing mid-scan does not corrupt repo A's in-flight source-entry discovery", async () => { const { loadNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const pA = loadNodeWorkspacePackages(repoA); // Wait until A is blocked right before checking pkg2's real source file. diff --git a/gitnexus/test/unit/node-workspace-review-fixes.test.ts b/gitnexus/test/unit/node-workspace-review-fixes.test.ts index 881e08845f..288ae38936 100644 --- a/gitnexus/test/unit/node-workspace-review-fixes.test.ts +++ b/gitnexus/test/unit/node-workspace-review-fixes.test.ts @@ -13,7 +13,7 @@ import { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages, resolveNodeWorkspaceImport, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; import { _captureLogger } from '../../src/core/logger.js'; function mkRepo(prefix: string) { diff --git a/gitnexus/test/unit/node-workspace-scan-determinism.test.ts b/gitnexus/test/unit/node-workspace-scan-determinism.test.ts index 77192baee7..602142d998 100644 --- a/gitnexus/test/unit/node-workspace-scan-determinism.test.ts +++ b/gitnexus/test/unit/node-workspace-scan-determinism.test.ts @@ -128,7 +128,7 @@ vi.mock('fs/promises', async (importOriginal) => { describe('M7 — workspace-root scan: sorted readdir + a cap that warns (50,010-directory synthetic tree)', () => { it('trips the cap and warns, and the run still completes deterministically for a result outside the capped subtree', async () => { const { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const results: { warned: boolean; diff --git a/gitnexus/test/unit/node-workspace-scope.test.ts b/gitnexus/test/unit/node-workspace-scope.test.ts index 1073305abe..8ee4fcf4a1 100644 --- a/gitnexus/test/unit/node-workspace-scope.test.ts +++ b/gitnexus/test/unit/node-workspace-scope.test.ts @@ -15,7 +15,7 @@ import { describe, it, expect, afterAll } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; const roots: string[] = []; diff --git a/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts b/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts index 9f99eed9e5..d6a0f38b6f 100644 --- a/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts +++ b/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; describe('vite lib.entry discovery ignores comments and refuses disagreeing entries', () => { let dir: string; diff --git a/gitnexus/test/unit/node-workspace-vite-structure.test.ts b/gitnexus/test/unit/node-workspace-vite-structure.test.ts index 87816eb3d6..b5f002dec6 100644 --- a/gitnexus/test/unit/node-workspace-vite-structure.test.ts +++ b/gitnexus/test/unit/node-workspace-vite-structure.test.ts @@ -2,7 +2,7 @@ import { afterAll, describe, expect, it } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; const roots: string[] = []; afterAll(() => { diff --git a/gitnexus/test/unit/python-relative-imports.test.ts b/gitnexus/test/unit/python-relative-imports.test.ts new file mode 100644 index 0000000000..ad19eb78b3 --- /dev/null +++ b/gitnexus/test/unit/python-relative-imports.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { resolvePythonImportInternal } from '../../src/core/ingestion/languages/python/import-helpers.js'; +import { resolvePythonImportTarget } from '../../src/core/ingestion/languages/python/import-target.js'; + +/** Both the helper and the public adapter must respect Python's file boundary. */ +function resolveBoth(files: string[], target = '.peer', fromFile = 'pkg/main.py') { + const allFilePaths = new Set([fromFile, ...files]); + return [ + resolvePythonImportInternal(fromFile, target, allFilePaths), + resolvePythonImportTarget( + { kind: 'namespace', targetRaw: target, localName: 'peer', importedName: '*' }, + { fromFile, allFilePaths }, + ), + ]; +} + +describe('Python relative import file candidates', () => { + it.each(['.ts', '.tsx', '.js', '.php', '.rb', ''])( + 'leaves a relative import unresolved when only peer%s exists', + (extension) => { + expect(resolveBoth([`pkg/peer${extension}`])).toEqual([null, null]); + }, + ); + + it('selects the Python module despite a same-named TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer.py'])).toEqual(['pkg/peer.py', 'pkg/peer.py']); + }); + + it('selects a Python package despite a same-named TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer/__init__.py'])).toEqual([ + 'pkg/peer/__init__.py', + 'pkg/peer/__init__.py', + ]); + }); + + it.each([ + ['.peer', 'pkg/main.py'], + ['..peer', 'pkg/child/main.py'], + ])('prefers a package over a module for %s from %s', (target, fromFile) => { + expect(resolveBoth(['pkg/peer.py', 'pkg/peer/__init__.py'], target, fromFile)).toEqual([ + 'pkg/peer/__init__.py', + 'pkg/peer/__init__.py', + ]); + }); + + it('resolves a parent-relative Python module without borrowing a TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer.py'], '..peer', 'pkg/child/main.py')).toEqual([ + 'pkg/peer.py', + 'pkg/peer.py', + ]); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts b/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts index d7b7084dd4..a69499504d 100644 --- a/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts +++ b/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts @@ -18,7 +18,7 @@ import { getMaxFileSizeBytes } from '../../../../src/core/ingestion/utils/max-fi import { csharpSuffixFallbackAllowed, importAlignsWithDeclaredNamespaces, -} from '../../../../src/core/ingestion/csharp-namespace-gate.js'; +} from '../../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { csharpScopeResolver } from '../../../../src/core/ingestion/languages/csharp/scope-resolver.js'; import type { CSharpProjectConfig } from '../../../../src/core/ingestion/language-config.js'; import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; diff --git a/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts b/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts index e52d8c3c90..0d38a1f177 100644 --- a/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts +++ b/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts @@ -11,8 +11,8 @@ * reports a blast radius into code that cannot be affected. The reporter * measured 44 of 74 cross-package edges landing on two such files. * - * The mechanism is shared, which is why this file is: `import-resolvers/ - * utils.ts:suffixResolve` asks "does any file in this repo have a path ending + * The shared `utils/suffix-index.ts:suffixResolve` helper asks + * "does any file in this repo have a path ending * in this specifier?", retrying with each leading segment dropped, and most * languages still end their resolution chain there. * diff --git a/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts b/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts deleted file mode 100644 index 8459fc4bad..0000000000 --- a/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Unit tests for `import-target-adapter` (RFC #909 Ring 2 PKG #922). - * - * Exercises the language-dispatching FinalizeHook. We don't need the - * real per-language resolvers here — mock `ImportResolverFn`s let each - * branch be tested in isolation. Real-resolver integration is covered - * by the existing per-language import-resolver test suites. - */ - -import { describe, it, expect } from 'vitest'; -import { SupportedLanguages } from 'gitnexus-shared'; -import { - buildImportTargetWorkspace, - resolveImportTargetAcrossLanguages, - type ImportTargetWorkspace, -} from '../../../src/core/ingestion/import-target-adapter.js'; -import type { - ImportResolverFn, - ResolveCtx, -} from '../../../src/core/ingestion/import-resolvers/types.js'; -import type { LanguageProvider } from '../../../src/core/ingestion/language-provider.js'; - -// ─── Helpers ─────────────────────────────────────────────────────────────── - -const emptyCtx: ResolveCtx = { - allFilePaths: new Set(), - allFileList: [], - normalizedFileList: [], - index: { bySuffix: new Map() } as unknown as ResolveCtx['index'], - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, -}; - -function fakeProvider(importResolver: ImportResolverFn | undefined): LanguageProvider { - return { importResolver } as unknown as LanguageProvider; -} - -function workspace( - entries: Array<[SupportedLanguages, ImportResolverFn | undefined]>, -): ImportTargetWorkspace { - const providers = new Map(); - for (const [lang, resolver] of entries) providers.set(lang, fakeProvider(resolver)); - return buildImportTargetWorkspace(providers, emptyCtx); -} - -// ─── buildImportTargetWorkspace ──────────────────────────────────────────── - -describe('buildImportTargetWorkspace', () => { - it('registers languages that expose an importResolver', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(ws.perLanguage.has(SupportedLanguages.Python)).toBe(true); - }); - - it("skips providers whose importResolver is absent (defensive — shouldn't happen in practice)", () => { - const ws = workspace([[SupportedLanguages.Python, undefined]]); - expect(ws.perLanguage.size).toBe(0); - }); - - it('threads the shared ResolveCtx into every entry', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['x.py'] }); - const tsResolver: ImportResolverFn = () => ({ kind: 'files', files: ['x.ts'] }); - const ws = workspace([ - [SupportedLanguages.Python, pyResolver], - [SupportedLanguages.TypeScript, tsResolver], - ]); - expect(ws.perLanguage.get(SupportedLanguages.Python)!.ctx).toBe(emptyCtx); - expect(ws.perLanguage.get(SupportedLanguages.TypeScript)!.ctx).toBe(emptyCtx); - }); -}); - -// ─── resolveImportTargetAcrossLanguages ──────────────────────────────────── - -describe('resolveImportTargetAcrossLanguages', () => { - it('dispatches to the resolver for the fromFile extension', () => { - let seenPath: string | undefined; - const pyResolver: ImportResolverFn = (raw, _file) => { - seenPath = raw; - return { kind: 'files', files: ['models/user.py'] }; - }; - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - const result = resolveImportTargetAcrossLanguages('models.user', 'src/app.py', ws); - expect(seenPath).toBe('models.user'); - expect(result).toBe('models/user.py'); - }); - - it('routes to different resolvers based on the fromFile extension', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const tsResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.ts'] }); - const ws = workspace([ - [SupportedLanguages.Python, pyResolver], - [SupportedLanguages.TypeScript, tsResolver], - ]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBe('resolved.py'); - expect(resolveImportTargetAcrossLanguages('x', 'a.ts', ws)).toBe('resolved.ts'); - }); - - it('returns null when the resolver returns null', () => { - const pyResolver: ImportResolverFn = () => null; - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(resolveImportTargetAcrossLanguages('external_pkg', 'app.py', ws)).toBeNull(); - }); - - it('takes the first file from a package-kind result', () => { - const resolver: ImportResolverFn = () => ({ - kind: 'package', - files: ['pkg/index.py', 'pkg/other.py'], - dirSuffix: 'pkg', - }); - const ws = workspace([[SupportedLanguages.Python, resolver]]); - expect(resolveImportTargetAcrossLanguages('pkg', 'app.py', ws)).toBe('pkg/index.py'); - }); - - it('returns null when a result has kind=files but an empty files[]', () => { - // Defensive: resolvers shouldn't return this shape, but tolerate it. - const resolver: ImportResolverFn = () => ({ kind: 'files', files: [] }); - const ws = workspace([[SupportedLanguages.Python, resolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); - - it('returns null when no resolver is registered for the language', () => { - const ws = workspace([]); // empty - // .py file but no Python resolver registered - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); - - it('returns null when fromFile has an unknown extension', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'README.xyz', ws)).toBeNull(); - }); - - it('returns null when workspaceIndex is undefined / malformed', () => { - expect(resolveImportTargetAcrossLanguages('x', 'a.py', undefined)).toBeNull(); - // Cast to exercise the runtime guard against caller misuse. - expect(resolveImportTargetAcrossLanguages('x', 'a.py', {} as unknown)).toBeNull(); - }); - - it('swallows resolver exceptions and returns null (treated upstream as unresolved)', () => { - const throwingResolver: ImportResolverFn = () => { - throw new Error('resolver boom'); - }; - const ws = workspace([[SupportedLanguages.Python, throwingResolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts index c01867847b..c23312a90f 100644 --- a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts @@ -68,10 +68,10 @@ import { clearKotlinPackageFacts, setKotlinPackageFact, } from '../../../src/core/ingestion/languages/kotlin/package-facts.js'; -import { resolveRubyImportInternal } from '../../../src/core/ingestion/import-resolvers/ruby.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; +import { resolveRubyImportInternal } from '../../../src/core/ingestion/languages/ruby/import-helpers.js'; +import { buildSuffixIndex } from '../../../src/core/ingestion/utils/suffix-index.js'; import { isHeritageMarker } from '../../../src/core/ingestion/utils/heritage-marker.js'; -import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/csharp-namespace-gate.js'; +import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { DART_HERITAGE_PREFIX } from '../../../src/core/ingestion/languages/dart/interpret.js'; import { CountingSet, countedParsedFilesWith } from '../../helpers/counting-file-set.js'; diff --git a/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts b/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts index f4053a2c59..658820f141 100644 --- a/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts +++ b/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts @@ -418,9 +418,8 @@ const FIXTURES: ReadonlyMap = new Map< // `App\Legacy\Ghost`, whose directory does not exist — costs one // traversal per import: swapping this fixture onto that spelling posts // 201 traversals for 200 imports against 3 for two (measured). The - // residual is real and is out of this file's reach — it lives in - // `import-resolvers/php.ts`, which the #2901 hoist does not touch — so it - // is pinned by name in `php-import-target-parity.test.ts` and this + // residual lives in `languages/php/import-helpers.ts` and is pinned by + // name in `php-import-target-parity.test.ts`. This // fixture takes the leg that IS indexed rather than restating it. missTarget: (i) => `Vendor${i}\\Ghost\\Missing`, hitTarget: 'App\\Models\\User', diff --git a/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts b/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts index 25118b542e..0c8e50d55f 100644 --- a/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts @@ -54,8 +54,8 @@ import { resolvePhpImportTargetInternal, type PhpResolveContext, } from '../../../src/core/ingestion/languages/php/import-target.js'; -import { resolvePhpImportInternal } from '../../../src/core/ingestion/import-resolvers/php.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; +import { resolvePhpImportInternal } from '../../../src/core/ingestion/languages/php/import-helpers.js'; +import { buildSuffixIndex } from '../../../src/core/ingestion/utils/suffix-index.js'; import type { ComposerConfig } from '../../../src/core/ingestion/language-config.js'; import type { ImportResolutionContext } from '../../../src/core/ingestion/scope-resolution/contract/scope-resolver.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; @@ -434,7 +434,7 @@ const GENERATED_CASES: readonly Case[] = generatedTargets().flatMap((target) => * - the PSR-4 namespace-directory fallback is NOT gated on the imported symbol * kind. It fires for a class import too, whenever the class-style path * misses, and returns the FIRST `.php` file directly in the namespace - * directory — see the "known limitation" note atop `import-resolvers/php.ts`. + * directory — see the "known limitation" note atop `languages/php/import-helpers.ts`. * Cases that lean on it are marked; their answers are order-dependent in * general and deterministic here only because the fixture pins the order. */ diff --git a/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts b/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts index 94a22f98cf..2c7e2697fa 100644 --- a/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts +++ b/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts @@ -46,7 +46,7 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import { pythonScopeResolver } from '../../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { resolvePythonImportInternal } from '../../../../src/core/ingestion/import-resolvers/python.js'; +import { resolvePythonImportInternal } from '../../../../src/core/ingestion/languages/python/import-helpers.js'; import { NO_PARSED_FILES, pythonNamedImport, diff --git a/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts b/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts index f29ac144f7..e80926f351 100644 --- a/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts +++ b/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts @@ -53,7 +53,7 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import { pythonScopeResolver } from '../../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { getPythonFileIndex } from '../../../../src/core/ingestion/import-resolvers/python-file-index.js'; +import { getPythonFileIndex } from '../../../../src/core/ingestion/languages/python/import-file-index.js'; import { IMPORTER_PATH_SHAPES, countedParsedFiles, diff --git a/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts b/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts index bb41357b7e..e77e6272bb 100644 --- a/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts +++ b/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts @@ -14,7 +14,7 @@ import { resolveTsImportTarget, type TsResolveContext, } from '../../../../src/core/ingestion/languages/typescript/import-target.js'; -import * as importResolverUtils from '../../../../src/core/ingestion/import-resolvers/utils.js'; +import * as importResolverUtils from '../../../../src/core/ingestion/utils/suffix-index.js'; import { typescriptScopeResolver } from '../../../../src/core/ingestion/languages/typescript/scope-resolver.js'; import type { SyntaxNode } from '../../../../src/core/ingestion/utils/ast-helpers.js'; import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; diff --git a/gitnexus/test/unit/suffix-index-ambiguity.test.ts b/gitnexus/test/unit/suffix-index-ambiguity.test.ts index fd786c045a..cf196effae 100644 --- a/gitnexus/test/unit/suffix-index-ambiguity.test.ts +++ b/gitnexus/test/unit/suffix-index-ambiguity.test.ts @@ -8,13 +8,9 @@ */ import { describe, it, expect } from 'vitest'; -import { - buildSuffixIndex, - suffixResolve, -} from '../../src/core/ingestion/import-resolvers/utils.js'; -import { resolvePythonImportInternal } from '../../src/core/ingestion/import-resolvers/python.js'; -import { resolveImportPath } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { SupportedLanguages } from '../../src/config/supported-languages.js'; +import { buildSuffixIndex, suffixResolve } from '../../src/core/ingestion/utils/suffix-index.js'; +import { resolvePythonImportInternal } from '../../src/core/ingestion/languages/python/import-helpers.js'; +import { EXTENSIONS } from '../../src/core/ingestion/languages/import-candidates.js'; // --------------------------------------------------------------------------- // Helpers @@ -24,8 +20,7 @@ function makeCtx(files: string[]) { const normalized = files.map((f) => f.replace(/\\/g, '/')); const allFilesSet = new Set(files); const index = buildSuffixIndex(normalized, files); - const cache = new Map(); - return { files, normalized, allFilesSet, index, cache }; + return { files, normalized, allFilesSet, index }; } /** Simulate the full dispatch: resolvePythonImport first, then suffixResolve fallback. */ @@ -39,27 +34,7 @@ function resolvePython( if (importPath.startsWith('.')) return null; const pathLike = importPath.replace(/\./g, '/'); const parts = pathLike.split('/').filter(Boolean); - return suffixResolve(parts, ctx.normalized, ctx.files, ctx.index); -} - -/** For non-Python languages, delegate directly to standard resolveImportPath. */ -function resolve( - currentFile: string, - importPath: string, - language: SupportedLanguages, - ctx: ReturnType, -): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - language, - null, - ctx.index, - ); + return suffixResolve(parts, ctx.normalized, ctx.files, EXTENSIONS, ctx.index); } // --------------------------------------------------------------------------- @@ -171,52 +146,3 @@ describe('resolvePythonImport — namespace packages (no __init__.py)', () => { expect(result).toBe('app/services/user/model.py'); }); }); - -// --------------------------------------------------------------------------- -// Ruby: bare require does NOT use proximity -// --------------------------------------------------------------------------- - -describe('resolveImportPath — Ruby bare require does not use proximity', () => { - it('returns first-indexed file for bare require (Ruby $LOAD_PATH excludes current directory)', () => { - const ctx = makeCtx([ - 'lib/core/helpers.rb', // indexed first - 'lib/utils/helpers.rb', - 'lib/utils/formatter.rb', - ]); - - // Ruby bare `require 'helpers'` searches $LOAD_PATH — current directory not included. - // No proximity bias; first-indexed file is returned, same as before. - const result = resolve('lib/utils/formatter.rb', 'helpers', SupportedLanguages.Ruby, ctx); - expect(result).toBe('lib/core/helpers.rb'); - }); - - it('resolves require_relative (dot-prefixed) to same-directory file via generic relative resolver', () => { - const ctx = makeCtx(['lib/utils/helpers.rb', 'lib/utils/formatter.rb']); - - // require_relative arrives as "./" — caught by generic relative resolver, not proximity - const result = resolve('lib/utils/formatter.rb', './helpers', SupportedLanguages.Ruby, ctx); - expect(result).toBe('lib/utils/helpers.rb'); - }); -}); - -// --------------------------------------------------------------------------- -// Other languages: no proximity applied -// --------------------------------------------------------------------------- - -describe('resolveImportPath — no proximity for Java or TypeScript', () => { - it('Java: fully-qualified import resolves to the correct file via unique suffix', () => { - const ctx = makeCtx(['src/com/a/User.java', 'src/com/b/User.java', 'src/com/b/Service.java']); - - // "com.b.User" → "com/b/User" → unique suffix; no ambiguity - const result = resolve('src/com/b/Service.java', 'com.b.User', SupportedLanguages.Java, ctx); - expect(result).toBe('src/com/b/User.java'); - }); - - it('TypeScript: relative import resolves via generic relative resolver', () => { - const ctx = makeCtx(['src/services/user.ts', 'src/services/auth.ts', 'src/models/user.ts']); - - // "./user" is explicit relative — resolved before proximity is checked - const result = resolve('src/services/auth.ts', './user', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/services/user.ts'); - }); -}); diff --git a/gitnexus/test/unit/zig-import-resolver.test.ts b/gitnexus/test/unit/zig-import-resolver.test.ts index 932012d187..1078a2a330 100644 --- a/gitnexus/test/unit/zig-import-resolver.test.ts +++ b/gitnexus/test/unit/zig-import-resolver.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect } from 'vitest'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { resolveZigImportInternal } from '../../src/core/ingestion/import-resolvers/zig.js'; +import { resolveZigImportInternal } from '../../src/core/ingestion/languages/zig/import-helpers.js'; import { loadZigBuildConfig, loadZigWorkspaceIndex, From 2b44565534d470df27030bd6f5a41507f0d41f35 Mon Sep 17 00:00:00 2001 From: Abhigyan Patwari <126312502+abhigyanpatwari@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:29:59 +0530 Subject: [PATCH 3/6] fix(resolution): correct receiver drops and property ownership (#3653) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(js): withdraw receiver drops for object-literal key writes a later pass answers The JS capture makes the enclosing object literal the receiver of each key it writes (`return { wickRatio: row.a }`). Case 0 of the receiver-bound pass treats any receiver text holding `.` or `(` as a compound expression, and a literal holding `row.a`, `0.5` or `...seed` does, so the fold failed and the site was recorded as a `receiver-unresolved` drop. The return-shape and unique-name passes run later and answered 17 of these 19 writes with an ACCESSES edge, but nothing withdrew the earlier drop. Both passes now report the sites they emitted an edge for, keyed by file, position, site kind and member name (position alone is shared by `a.b` and `a.b.c()`), and run.ts withdraws the matching `receiver-unresolved` drops once they have run. A site they leave unanswered keeps its drop. The other two writes, in `SignalService.make()`, had no edge at all: the own-return-shape tier read the caller's owner qualifier as `SignalService.make#0`, so it never matched the method's keys (`SignalService.make.secretFlag`) and three same-named candidates were refused. The qualifier is now the qualified name after `