GitNexus/gitnexus/test/integration/resolvers/helpers.ts
Abhigyan Patwari 2b44565534
Some checks are pending
Gitleaks / gitleaks (push) Waiting to run
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
fix(resolution): correct receiver drops and property ownership (#3653)
* 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 `<Label>:<file>:`
without the `#<arity>` suffix. It also stops cutting a positioned id
(`outer.parse@25:2`) down to its column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(js): type a static field from its initializer for class-level receivers

`Config.DEFAULT.validate()` with `static DEFAULT = new Config()` produced no
CALLS edge. JS and TS keep a static field's type binding out of the class
scope on purpose: the scope has one binding map for static and instance
members, so the static binding would retype an instance field of the same
name. The class-level receiver route (`declaredTypeOfClassLevelField`) reads
the static Property node instead, but only its annotation-derived
`declaredType`, and an unannotated field has none. The type had nowhere to
live.

The field extractor now records `initializerType` for a field that declares
no type and is initialized by `new X()` / `new ns.X()` (the same two shapes
the scope queries bind), the parse worker stamps it on the Property node, and
the class-level route falls back to it after `declaredType`. The binding still
never enters the shared class-scope map, so the instance-twin hazard does not
return.

This resolves one hop: `Host.q.m()` now reaches `Alien.m`. A longer chain off
the field still goes through the compound fold, which types a field step only
from the class-scope map, so it stays unresolved. The matrix known-gap row
`static-read-without-a-twin-loses-its-type` flips to a positive row for TS,
with a JS twin added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(js): keep CommonJS module.exports declarations out of receiver drops

`module.exports.arrowRequest = (url) => fetch(url)` declares this module's
`arrowRequest` export; the CJS capture rules already bind it like
`exports.memberRequest = …`. The same line also yields a write reference
whose receiver is `module.exports`, and because that text has a dot the
receiver-bound pass folded it as a compound value, failed, and recorded the
declaration as a `receiver-unresolved` write. The bare `exports.x = …`
spelling never reached that path.

A new ScopeResolver hook, `isModuleExportAssignment`, lets a language say a
write site is a module-export declaration. The receiver-bound pass consults
it only at the drop guard, after every case has failed, so it records no
drop and changes nothing else: the site is not marked handled, no edge is
added, and the existing module-level write edge stays. The JS and TS
resolvers implement it for a receiver of exactly `module.exports` (from the
minted chain, or the text when no chain was minted) when `module` resolves
to nothing in scope. A `module` parameter, as in a UMD wrapper, or a write
into a value hanging off the export object still records its drop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ts): record an owned-`this` chain receiver as owned-but-unbound

`this.route.go()` inside an object-literal method was filed as a generic
`receiver-unresolved` drop (or, depending on site order, as nothing). The
method scope owns `this` and gives it no type, which the pass detects with
`isReceiverOwnedButUnbound`, but that check was handed the whole receiver
text `this.route`. No scope owns a chain, so the call fell through to Case 0,
whose fold cannot type an owned `this` either.

The check now receives the receiver's base (from the minted chain, else the
text before the first `.`/`(`), the same base the `suppressReceiverLookup`
check already used. The call is recorded as `receiver-owned-but-unbound`,
its real reason, and still emits no edge: the dynamic-this negative control
holds. On the fixture corpus this moves only that site; no edge changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(resolution): preserve receiver ownership

Bind a return key's declaration write by exact file and position so
unrelated input accesses keep their ordinary candidate ranking. Stop at
untyped static overrides and resolve constructor initializers as values.

Preserve the combined drop guards after rebasing onto main, cover the
binding regressions, and refresh the receiver baseline after #3654.

Key answered sites by their full range to retain repeated-name outer
reads. Keep owned-but-unbound calls in the persisted completeness signal.

* fix(resolution): address feedback (#3653)

Classify module-export declarations using captured module kind before
suppressing receiver drops. Match same-named field metadata by source
position, including declarations on one line.

Require reference kinds in suppression assertions and guard temporary
fixture cleanup. Cover the reported failures with regression tests.

* perf(parser): index repeated field declarations

Sort private field buckets once and use binary search to avoid
quadratic scans while preserving declaration disambiguation.

* fix(ingestion): preserve capture metadata

Record module kind from the parsed tree on worker and main-thread paths.
Match Ruby field metadata at the accessor call instead of its argument.

* fix(ingestion): harden capture metadata

Keep Ruby reader/writer properties writable. Walk module-kind ASTs iteratively so deep expressions cannot abort extraction.

* test(ingestion): clarify worker metadata scope

* docs(ingestion): state capture metadata effects

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 05:59:59 +01:00

210 lines
6.8 KiB
TypeScript

/**
* Shared test helpers for language resolution integration tests.
*/
import fs from 'node:fs';
import path from 'path';
import { runPipelineFromRepo } from '../../../src/core/ingestion/pipeline.js';
import type { PipelineOptions } from '../../../src/core/ingestion/pipeline.js';
import type { PipelineResult } from '../../../src/types/pipeline.js';
import type { GraphRelationship, ReferenceKind } from 'gitnexus-shared';
export const FIXTURES = path.resolve(__dirname, '..', '..', 'fixtures', 'lang-resolution');
export const CROSS_FILE_FIXTURES = path.resolve(
__dirname,
'..',
'..',
'fixtures',
'cross-file-binding',
);
/**
* Materialize an in-memory fixture repo under `root`, creating parent
* directories as needed.
*
* Writes in `Object.entries` order, i.e. the literal's own key order — some
* callers depend on that (a fixture whose second file must be written after
* the first for the property under test to mean anything), so this must stay
* insertion-ordered rather than sorting or parallelizing the writes.
*/
export function writeFixtureRepo(root: string, files: Record<string, string>): void {
for (const [relPath, content] of Object.entries(files)) {
const fullPath = path.join(root, relPath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content, 'utf8');
}
}
export type RelEdge = {
source: string;
target: string;
sourceLabel: string;
targetLabel: string;
sourceFilePath: string;
targetFilePath: string;
rel: GraphRelationship;
};
export function getRelationships(result: PipelineResult, type: string): RelEdge[] {
const edges: RelEdge[] = [];
for (const rel of result.graph.iterRelationships()) {
if (rel.type === type) {
const sourceNode = result.graph.getNode(rel.sourceId);
const targetNode = result.graph.getNode(rel.targetId);
edges.push({
source: sourceNode?.properties.name ?? rel.sourceId,
target: targetNode?.properties.name ?? rel.targetId,
sourceLabel: sourceNode?.label ?? 'unknown',
targetLabel: targetNode?.label ?? 'unknown',
sourceFilePath: sourceNode?.properties.filePath ?? '',
targetFilePath: targetNode?.properties.filePath ?? '',
rel,
});
}
}
return edges;
}
export function getResolutionOutcomes(result: PipelineResult) {
return result.resolutionOutcomes ?? [];
}
/** File, 1-based start line, column, member name, and reference kind. */
export type OutcomeSite = readonly [
filePath: string,
line: number,
col: number,
name: string,
kind: ReferenceKind,
];
/**
* Reasons recorded for the requested kind and member at this start position.
*
* A call and a read can share both their member name and start position.
*/
export function suppressionReasonsAt(
result: PipelineResult,
[filePath, line, col, name, siteKind]: OutcomeSite,
): string[] {
return getResolutionOutcomes(result)
.flatMap((outcome) =>
outcome.kind === 'suppressed' &&
outcome.filePath === filePath &&
outcome.range.startLine === line &&
outcome.range.startCol === col &&
outcome.name === name &&
outcome.siteKind === siteKind
? [outcome.reason]
: [],
)
.sort();
}
/**
* True when an `ACCESSES` edge `sourceId -> targetId` was emitted for the site
* at `line:col`. The name-inference and return-shape passes key each edge id by
* the site position, which is what ties the edge to one site rather than to any
* access between the same two nodes.
*/
export function hasAccessesAtSite(
result: PipelineResult,
sourceId: string,
targetId: string,
line: number,
col: number,
): boolean {
return getRelationships(result, 'ACCESSES').some(
(edge) =>
edge.rel.sourceId === sourceId &&
edge.rel.targetId === targetId &&
edge.rel.id.endsWith(`:${line}:${col}`),
);
}
/**
* Relationships whose source or target id does not resolve to a live graph node.
* A non-empty result means the graph has dangling edges (an endpoint that was
* never materialized) — e.g. a HAS_METHOD edge owned by a class node that the
* structure phase failed to create. Pass `types` to scope the check to specific
* relationship types (e.g. `['HAS_METHOD']`).
*/
export function findDanglingEdges(
result: PipelineResult,
types?: string[],
): Array<{
type: string;
sourceId: string;
targetId: string;
missing: 'source' | 'target' | 'both';
}> {
const out: Array<{
type: string;
sourceId: string;
targetId: string;
missing: 'source' | 'target' | 'both';
}> = [];
for (const rel of result.graph.iterRelationships()) {
if (types && !types.includes(rel.type)) continue;
const src = result.graph.getNode(rel.sourceId);
const tgt = result.graph.getNode(rel.targetId);
if (src && tgt) continue;
out.push({
type: rel.type,
sourceId: rel.sourceId,
targetId: rel.targetId,
missing: !src && !tgt ? 'both' : !src ? 'source' : 'target',
});
}
return out;
}
export function getNodesByLabel(result: PipelineResult, label: string): string[] {
const names: string[] = [];
result.graph.forEachNode((n) => {
if (n.label === label) names.push(n.properties.name);
});
return names.sort();
}
/**
* Every node a single fixture file contributed, as sorted `Label:name` and
* `Label:qualifiedName` strings — for exact `toEqual` assertions on the whole
* file's output rather than spot checks.
*/
export function getNodesForFile(
result: PipelineResult,
filePathSuffix: string,
): { names: string[]; labelled: string[]; qualified: string[] } {
const names: string[] = [];
const labelled: string[] = [];
const qualified: string[] = [];
result.graph.forEachNode((n) => {
if (!String(n.properties.filePath ?? '').endsWith(filePathSuffix)) return;
const name = n.properties.name;
names.push(name);
labelled.push(`${n.label}:${name}`);
qualified.push(`${n.label}:${String(n.properties.qualifiedName ?? name)}`);
});
return { names: names.sort(), labelled: labelled.sort(), qualified: qualified.sort() };
}
export function edgeSet(edges: Array<{ source: string; target: string }>): string[] {
return edges.map((e) => `${e.source} → ${e.target}`).sort();
}
/** Get graph nodes by label with full properties (for parameterTypes assertions). */
export function getNodesByLabelFull(
result: PipelineResult,
label: string,
): Array<{ name: string; properties: Record<string, any> }> {
const nodes: Array<{ name: string; properties: Record<string, any> }> = [];
result.graph.forEachNode((n) => {
if (n.label === label) nodes.push({ name: n.properties.name, properties: n.properties });
});
return nodes.sort((a, b) => a.name.localeCompare(b.name));
}
// Tests can pass { skipGraphPhases: true } as third arg for faster runs
// (skips MRO, community detection, and process extraction).
export { runPipelineFromRepo };
export type { PipelineOptions, PipelineResult };