GitNexus/gitnexus/test/integration/resolvers/javascript-object-properties.test.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

497 lines
24 KiB
TypeScript

/**
* A1/A5 — property access on a PLAIN OBJECT LITERAL must be answerable.
*
* Verified root cause: `Property` definition nodes are created only for
* DECLARED CLASS FIELDS. Object-literal keys mint no node, so `ACCESSES` has
* no target and "who reads/writes this config field?" returns a confident
* zero. Capture and emission are already correct and language-neutral — a
* `read`/`write` site maps to `ACCESSES` for any resolved target — so this is
* purely definition-node coverage plus receiver resolution.
*
* Two receiver shapes, deliberately separated:
* - through the holding variable (`exitRules.exitMinAtrMult`) — the receiver
* is typeable, so this must resolve precisely.
* - through an untyped param (`cfg.exitMinAtrMult`) — the option-bag shape
* that dominates idiomatic JS. Not precisely solvable without types;
* covered by name-based fallback at reduced confidence.
*
* Both halves now land. Object-literal keys bound to a variable mint the graph
* `Property` node (JAVASCRIPT_QUERIES) and the scope-resolution def
* (languages/javascript/query.ts), and the ACCESSES edges resolve for both
* receiver shapes: precisely where the receiver is typeable, and by
* workspace-unique name where it is not — at reduced confidence, refusing to
* choose when two properties share a name (see the ambiguity cases below).
*
* TRAP, learned the hard way and recorded so the next reader does not repeat
* it: under vitest the PARSE WORKER runs the BUILT `dist/` code, because
* `parse-impl.ts` resolves `../workers/parse-worker.js`, which does not exist
* under `src/`, and falls back to dist. Scope resolution runs from `src`. So a
* change to TYPESCRIPT/JAVASCRIPT_QUERIES is invisible to tests until
* `npm run build` — it reads exactly like a failed hypothesis.
*/
import { describe, it, expect, beforeAll } from 'vitest';
import path from 'path';
import {
FIXTURES,
getRelationships,
hasAccessesAtSite,
runPipelineFromRepo,
suppressionReasonsAt,
type OutcomeSite,
type PipelineResult,
} from './helpers.js';
describe('JavaScript plain-object property access (A1/A5)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'javascript-object-properties'),
() => {},
);
}, 60000);
const propertyNames = (): string[] =>
Array.from(
(result as unknown as { graph: { iterNodes(): Iterable<PropNode> } }).graph.iterNodes(),
)
.filter((n) => n.label === 'Property')
.map((n) => String(n.properties.name));
const readersOf = (field: string): string[] =>
getRelationships(result, 'ACCESSES')
.filter((e) => e.target === field)
.map((e) => e.source);
it('indexes object-literal keys as Property nodes', () => {
const props = propertyNames();
expect(props).toContain('exitMinAtrMult');
expect(props).toContain('stopAtrMult');
});
it('gives every indexed key a distinct node, not one merged symbol', () => {
// Asserted on the RAW array, not on a Set of it. `new Set([...]).size === 2`
// over two different literal strings can only ever be 2 — it cannot detect
// the merge the title promises, which is a difference in COUNT.
const props = propertyNames().filter((n) => n === 'exitMinAtrMult' || n === 'stopAtrMult');
expect(props).toHaveLength(2);
expect(new Set(props).size).toBe(2);
});
it('emits ACCESSES for a read through the holding variable', () => {
expect(readersOf('exitMinAtrMult')).toContain('readViaVariable');
});
it('emits ACCESSES for the property WRITE (A5)', () => {
const writes = getRelationships(result, 'ACCESSES').filter(
(e) => e.target === 'exitMinAtrMult' && (e.rel.reason ?? '').includes('write'),
);
expect(writes.map((e) => e.source)).toContain('tightenExit');
});
it('emits ACCESSES for a read through an untyped param (option bag)', () => {
expect(readersOf('exitMinAtrMult')).toContain('applyRules');
});
// The safety property. Name inference is only defensible because it refuses
// to choose between candidates: two objects sharing a key name means a read
// through an untyped receiver could mean either, and a wrong edge in the
// pre-edit safety gate is worse than a missing one. Without this, the pass
// would silently link generic keys (id, name, data) across unrelated objects.
it('emits NOTHING when two objects share the key name', () => {
expect(readersOf('sharedTimeoutMs')).toEqual([]);
});
it('still indexes both ambiguous keys as nodes — only the EDGE is withheld', () => {
// The symbols must remain findable; it is the inference that is unsafe,
// not the definitions.
expect(propertyNames().filter((n) => n === 'sharedTimeoutMs')).toHaveLength(2);
});
it('marks a name-inferred edge at reduced confidence, not as precise', () => {
const inferred = getRelationships(result, 'ACCESSES').filter(
(e) => e.target === 'exitMinAtrMult' && (e.rel.reason ?? '').includes('unique-name'),
);
expect(inferred.length).toBeGreaterThan(0);
for (const e of inferred) expect(e.rel.confidence).toBeLessThan(0.85);
});
// R2-1c. The function that implements a behaviour usually destructures its
// settings out of the argument rather than reaching through a receiver, so
// the most relevant reader was the one shape with no read site at all.
describe('destructured parameters (R2-1c)', () => {
it('emits ACCESSES for a destructured key with a default', () => {
expect(readersOf('destructuredOnlyField')).toContain('appliesDestructured');
});
it('emits ACCESSES for bare shorthand destructuring', () => {
expect(readersOf('destructuredOnlyField')).toContain('appliesShorthand');
});
// `{ field: alias }` reads `field` and binds `alias`; the READ is of the
// key, so the edge must point at the key rather than the local name.
it('follows the key, not the local alias, when renamed', () => {
expect(readersOf('destructuredOnlyField')).toContain('appliesRenamed');
expect(propertyNames()).not.toContain('aliased');
});
});
// R2-1b. The read side answered well while "who SETS this field?" missed the
// code that stamps the value, because a record built inline is bound to no
// variable and so mints no definition to point at.
describe('record construction writes (R2-1b)', () => {
const writersOf = (field: string): string[] =>
getRelationships(result, 'ACCESSES')
.filter((e) => e.target === field && (e.rel.reason ?? '').includes('write'))
.map((e) => e.source);
it('emits a WRITE for a literal nested under a key', () => {
expect(writersOf('destructuredOnlyField')).toContain('buildPlan');
});
it('emits a WRITE for a returned literal', () => {
expect(writersOf('destructuredOnlyField')).toContain('buildFlat');
});
// This asserted `toHaveLength(1)` — no new definition — until R3-4 began
// anchoring returned literals, which mints exactly one here (`buildFlat`'s
// return shape). The assertion was the right instinct expressed as the
// wrong invariant: what R2-1b actually protects is that adding definitions
// must not move an answer that already resolved, and node count was a proxy
// for that. The property itself is now asserted directly, and it holds
// because narrowing ranks declared anchors above return shapes.
it('keeps the DECLARED definition winning despite a return-shape sibling', () => {
const nodes = propertyNames().filter((n) => n === 'destructuredOnlyField');
expect(nodes.length).toBeGreaterThan(1);
// Every reader still resolves, and to the declared home — a read that had
// dropped to ambiguous would show up as a missing edge here.
for (const reader of ['appliesDestructured', 'appliesShorthand', 'appliesRenamed']) {
expect(readersOf('destructuredOnlyField')).toContain(reader);
}
});
it('leaves an inline call-argument prop bag alone', () => {
expect(propertyNames()).not.toContain('notAConstructedField');
expect(writersOf('notAConstructedField')).toEqual([]);
});
// The capture makes the ENCLOSING LITERAL the receiver, and the
// receiver-bound pass treats any receiver text holding a `.` or `(` as a
// compound expression to fold — which `{ x: row.a }`, `{ r: 0.5 }` and
// `{ ...seed, extra }` all do. The fold cannot type a literal, so each of
// these keys was recorded as a `receiver-unresolved` drop, and the drop
// stayed after the unique-name pass answered the same site with an edge.
// Each row pins both halves: the edge exists at THIS site, and no drop does.
it.each<readonly [OutcomeSite, string, string]>([
[
['destructured.js', 26, 4, 'exitContract', 'write'],
'Function:destructured.js:buildPlan',
'Property:destructured.js:buildPlan.exitContract@25:4',
],
[
['destructured.js', 27, 6, 'destructuredOnlyField', 'write'],
'Function:destructured.js:buildPlan',
'Property:destructured.js:destructuredDefaults.destructuredOnlyField',
],
[
['destructured.js', 34, 4, 'destructuredOnlyField', 'write'],
'Function:destructured.js:buildFlat',
'Property:destructured.js:buildFlat.destructuredOnlyField@33:4',
],
[
['frozen.js', 26, 20, 'extra', 'write'],
'Function:frozen.js:buildRules',
'Property:frozen.js:buildRules.extra@25:20',
],
[
['return-shape-typed.js', 6, 4, 'ambiguousProducedField', 'write'],
'Function:return-shape-typed.js:producerAlpha',
'Property:return-shape-typed.js:producerAlpha.ambiguousProducedField@5:4',
],
[
['return-shape-typed.js', 12, 4, 'ambiguousProducedField', 'write'],
'Function:return-shape-typed.js:producerBeta',
'Property:return-shape-typed.js:producerBeta.ambiguousProducedField@11:4',
],
[
['return-shape.js', 8, 4, 'returnShapeOnlyField', 'write'],
'Function:return-shape.js:formatAlert',
'Property:return-shape.js:formatAlert.returnShapeOnlyField@7:4',
],
[
['return-shape.js', 9, 4, 'sharedWithDeclared', 'write'],
'Function:return-shape.js:formatAlert',
'Property:return-shape.js:formatAlert.sharedWithDeclared@8:4',
],
[
['return-shape.js', 20, 4, 'summaryOnlyField', 'write'],
'Function:return-shape.js:formatSummary',
'Property:return-shape.js:formatSummary.summaryOnlyField@19:4',
],
[
['return-shape.js', 45, 13, 'anonReturnKey', 'write'],
'File:return-shape.js',
'Property:return-shape.js:fn@43:2.anonReturnKey@44:13',
],
[
['return-shape.js', 53, 4, 'productionAndTestField', 'write'],
'Function:return-shape.js:buildProductionShape',
'Property:return-shape.js:buildProductionShape.productionAndTestField@52:4',
],
])('answers %j with an edge and records no drop for it', (site, sourceId, targetId) => {
expect({
edge: hasAccessesAtSite(result, sourceId, targetId, site[1], site[2]),
suppressions: suppressionReasonsAt(result, site),
}).toEqual({ edge: true, suppressions: [] });
});
});
// R3-4. The dominant shape in idiomatic JS and the one with no anchor at all:
// 437 `return {` sites in a single backend directory of the reporting repo,
// including the ~25-field payload of its whole signal pipeline. The literal
// binds to nothing, so its keys could not even be named.
describe('anonymous returned object literals (R3-4)', () => {
it('indexes keys of a literal returned from a named function', () => {
expect(propertyNames()).toContain('returnShapeOnlyField');
});
it('resolves a read of a return-shape key', () => {
expect(readersOf('returnShapeOnlyField')).toContain('readsReturnShape');
});
// `{ symbol, interval, score }` is the commonest spelling of all and
// `(pair)` does not match it — tree-sitter models it as
// `shorthand_property_identifier`, where the key IS the value. Caught by
// dumping the golden fixture and seeing that a literal returning
// `{ level, message, timestamp: Date.now() }` had indexed only `timestamp`.
it('indexes SHORTHAND keys, not just explicit pairs', () => {
expect(propertyNames()).toContain('shorthandOnlyField');
});
// Qualified by the owning function, so two functions returning the same key
// are two shapes rather than one merged symbol — the same collision
// `ownerName` prevents for variable-bound literals.
it('qualifies by the owning function', () => {
const ids = Array.from(
(result as unknown as { graph: { iterNodes(): Iterable<PropNode> } }).graph.iterNodes(),
)
.filter((n) => n.label === 'Property')
.map((n) => String(n.id));
expect(ids.some((id) => id.includes('formatAlert.returnShapeOnlyField'))).toBe(true);
expect(ids.some((id) => id.includes('formatSummary.summaryOnlyField'))).toBe(true);
});
// Production code outranks test fixtures. Measured on the reporting repo:
// four of the seven JavaScript anchors for one field were in `tests/`,
// competing with the three real ones and making every production read
// ambiguous. A test builds throwaway shapes with production field names; a
// read in shipped code cannot mean one.
it('does not let a test fixture compete with the production anchor', () => {
expect(readersOf('productionAndTestField')).toContain('readsProductionShape');
const ids = Array.from(
(result as unknown as { graph: { iterNodes(): Iterable<PropNode> } }).graph.iterNodes(),
)
.filter((n) => n.label === 'Property')
.map((n) => String(n.id));
// Both anchors exist — it is the RANKING that differs, not the indexing.
expect(ids.some((id) => id.includes('buildProductionShape.productionAndTestField'))).toBe(
true,
);
expect(ids.some((id) => id.includes('buildTestFixture.productionAndTestField'))).toBe(true);
});
// THE GUARANTEE that reconciles this with R2-1b. `sharedWithDeclared` is
// both a named-object key and a return-shape key; a read must still resolve
// to the DECLARED one, or indexing return shapes would silently move
// answers that already worked.
it('never outranks a declared anchor', () => {
expect(readersOf('sharedWithDeclared')).toContain('readsShared');
const declaredWins = getRelationships(result, 'ACCESSES').filter(
(e) => e.target === 'sharedWithDeclared' && e.source === 'readsShared',
);
expect(declaredWins.length).toBeGreaterThan(0);
});
});
// R3-5. The question three rounds of reports could not answer: a field
// produced by SEVERAL functions. Name inference must refuse it — the name
// alone cannot say which shape is meant — so this replaces inference with
// evidence, joining the call-result type binding (which already existed) to
// the return-shape owner (which R3-4 created).
describe('return-shape members via the call result (R3-5)', () => {
const targetOf = (source: string): string[] =>
getRelationships(result, 'ACCESSES')
.filter((e) => e.target === 'ambiguousProducedField' && e.source === source)
.map((e) => String((e.rel as { targetId?: string }).targetId ?? ''));
it('resolves to the producer the receiver actually holds', () => {
expect(targetOf('readsAlpha').some((id) => id.includes('producerAlpha.'))).toBe(true);
expect(targetOf('readsBeta').some((id) => id.includes('producerBeta.'))).toBe(true);
});
// The discriminator. Both producers own a field of this name, so a name
// match cannot tell them apart — getting the RIGHT one is only possible
// because the receiver's binding names the producer.
it('does not cross the two producers', () => {
expect(targetOf('readsAlpha').some((id) => id.includes('producerBeta.'))).toBe(false);
expect(targetOf('readsBeta').some((id) => id.includes('producerAlpha.'))).toBe(false);
});
// Scoped to the READERS. The producer itself also touches this field — it
// constructs the key — and that edge is a different claim reached a
// different way (see the own-return-shape case below), so folding both into
// one "every edge must be precise" assertion would either forbid a correct
// write or force it to lie about its tier.
it('marks the reader edges as precise, not as name inference', () => {
const readerEdges = getRelationships(result, 'ACCESSES').filter(
(e) =>
e.target === 'ambiguousProducedField' &&
(e.source === 'readsAlpha' || e.source === 'readsBeta'),
);
expect(readerEdges.length).toBeGreaterThan(0);
for (const e of readerEdges) {
expect(String(e.rel.reason ?? '')).toContain('return-shape member');
expect(e.rel.confidence).toBeGreaterThan(0.85);
}
});
// Review finding 3, the telemetry half. `workspace-unique` is a claim that
// exactly one node in the workspace carries this name — a fact about the
// graph, and the label a reader trusts most. An answer reached by FILTERING
// (tests down-ranked, return shapes down-ranked) is a weaker claim, and
// reporting it under the same label said "unambiguous workspace-wide match"
// for something that was narrowed. The edge is unchanged; what it is allowed
// to say about itself is not.
it('does not claim workspace-uniqueness for an answer reached by ranking', () => {
// `sharedWithDeclared` is carried by BOTH a declared object key and a
// return-shape key, so the workspace is not unique in it. The read
// resolves only because declared anchors outrank return shapes — a
// ranking decision — and the edge must say so.
const ranked = getRelationships(result, 'ACCESSES').filter(
(e) => e.target === 'sharedWithDeclared' && e.source === 'readsShared',
);
expect(ranked.length).toBeGreaterThan(0);
for (const e of ranked) {
expect(String(e.rel.reason ?? '')).not.toContain('(workspace-unique)');
}
});
// Review finding 3, the half that was a real wrong edge. A function that
// returns `{ field: … }` WRITES the key that is its own return shape. The
// declared-outranks-return-shape ranking is right for a read through a
// receiver, but applied to this site it handed the write to a same-named
// declared const the producer never touches — and left the node the key
// actually defines with no writer at all.
it('binds a producer writing its own returned key to that key', () => {
const own = getRelationships(result, 'ACCESSES').filter(
(e) => e.source === 'producerAlpha' && e.target === 'ambiguousProducedField',
);
expect(own.length).toBeGreaterThan(0);
for (const e of own) expect(e.targetFilePath ?? '').toBeTruthy();
// Never the OTHER producer's key: the owner qualifier is the evidence.
expect(targetOf('producerAlpha').some((id) => id.includes('producerBeta.'))).toBe(false);
});
// THE BOUND, asserted so the mechanism is not mistaken for something it is
// not. A bare parameter has no binding here — typing it needs the CALLER's
// type to flow in, which is inter-procedural — so it falls through to name
// inference, which refuses because two producers share the name.
it('leaves an unbound receiver to name inference, which refuses it', () => {
expect(targetOf('readsUnbound')).toEqual([]);
});
});
// R2. Strict workspace uniqueness was measurably too blunt: in the reporting
// repo `exitMinAtrMult` had 26 definitions, 16 of them in one-off scripts the
// backend has no relationship with, so every backend read was refused because
// of competitors the reader cannot even see.
describe('scope narrowing for multi-candidate names (R2)', () => {
const reasonsFor = (field: string): string[] =>
getRelationships(result, 'ACCESSES')
.filter((e) => e.target === field)
.map((e) => String(e.rel.reason ?? ''));
it('still sees two definitions of the narrowed name', () => {
// Precondition. Without this the narrowing assertions below would pass
// trivially by there being nothing to narrow.
expect(propertyNames().filter((n) => n === 'narrowedTimeoutMs')).toHaveLength(2);
});
it('resolves an untyped read using direct-import evidence', () => {
expect(readersOf('narrowedTimeoutMs')).toContain('readsNarrowed');
});
it('records which tier resolved it, not just that something did', () => {
expect(reasonsFor('narrowedTimeoutMs').some((r) => r.includes('imported-file'))).toBe(true);
});
// The bound. Narrowing exists to USE scope evidence, not to lower the bar
// for guessing — a reader that can see both candidates is exactly as stuck
// as before, and must stay refused.
it('still refuses when the reader imports BOTH candidates', () => {
expect(readersOf('narrowedTimeoutMs')).not.toContain('readsBothVisible');
});
// Same-file evidence that is itself ambiguous must stop the walk rather
// than fall through to a weaker tier.
it('keeps refusing two same-named keys in the reading file', () => {
expect(readersOf('sharedTimeoutMs')).toEqual([]);
});
// This assertion was VACUOUS when written: it read the stat off a
// `scopeResolution` field that PipelineResult does not have, so the
// `undefined` guard swallowed it and the whole test passed with the
// production code deleted. The facts are now published as
// `propertyInference`, and the guard is an assertion rather than an escape.
it('reports the names it could not resolve, not only a count', () => {
const inference = result.propertyInference;
expect(inference).toBeDefined();
// Both halves. Asserting only the empty edge set is satisfied equally by
// "the ambiguity gate fired" and "the name was never looked up at all",
// so the counter must be shown to have MOVED.
expect(inference!.ambiguous).toBeGreaterThan(0);
expect(inference!.ambiguousNames).toContain('sharedTimeoutMs');
});
});
// R2-1a. Reported as the cheapest remaining win and it is: freezing a config
// object is how JS publishes an immutable contract, so the shape whose fields
// are most worth querying was the one shape the rule could not see.
describe('identity-preserving wrappers (R2-1a)', () => {
it('indexes keys of a literal wrapped in Object.freeze', () => {
const props = propertyNames();
expect(props).toContain('frozenExitModel');
expect(props).toContain('frozenMaxHoldMs');
});
it('indexes keys wrapped in Object.seal', () => {
expect(propertyNames()).toContain('sealedMaxNotional');
});
it('resolves a read through the frozen binding', () => {
expect(readersOf('frozenMaxHoldMs')).toContain('readsFrozen');
});
// The bound of the fix. Only freeze/seal/preventExtensions return the
// argument they were given; for any other call the literal is an argument
// and the binding holds the callee's return value, so minting members here
// would attribute fields to an object that does not have them.
it('does NOT index a literal passed to a non-identity call', () => {
expect(propertyNames()).not.toContain('notAMemberOfDerived');
});
// The case above is rejected structurally (identifier callee), so it holds
// even with no allowlist at all. `Object.entries` differs from
// `Object.freeze` by name alone, so this is the assertion that actually
// pins the predicate.
it('does NOT index Object.entries — same shape, non-identity name', () => {
expect(propertyNames()).not.toContain('notAMemberOfEntries');
});
});
});
interface PropNode {
readonly id: string;
readonly label: string;
readonly properties: Record<string, unknown>;
}