Skip to content

fix(reference): drop replaced CommonJS loaders from reference-source edges - #4072

Closed
VarunGore36 wants to merge 7 commits into
morluto:mainfrom
VarunGore36:fix/3982-shadowed-require-reference-source
Closed

VarunGore36 wants to merge 7 commits into
morluto:mainfrom
VarunGore36:fix/3982-shadowed-require-reference-source

Conversation

@VarunGore36

@VarunGore36 VarunGore36 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #3982.

import-reference-source reported a parsed internal requires edge when the apparent loader call targeted a replaced local function: a for-in/of var head initializes its binding on every iteration, and an assignment inside with leaves the binding identity unknown. Both now fail closed like a plain assignment, while a truly uninitialized top-level var require retains its edge.

Problem and expected behavior

Trigger: for (var require of [() => "local"]) {} or with ({}) { require = () => "local"; } followed by require("./dep.cjs") in a .cjs file. Node prints only local; the importer reported a parsed internal edge to dep.cjs.

  • Wrong outcome: {"from_path": "main.cjs", "to": "dep.cjs", "kind": "requires", "resolution": "internal", "parse_state": "parsed"}.
  • Expected: no edge, as the existing ordinary-assignment control produces. The uninitialized var require control keeps its edge.

Change and scope

Two changes in src/domain/referenceSourceRequireBindings.ts, the single owner of loader attribution:

  • hasUninitializedTopLevelVarRequire treats a var declarator binding require as initialized when it is the head of a for-in/of statement. A bare for (var require;;) head stays uninitialized.
  • requireLoaderWasWritten counts unknown-resolution writes alongside unbound ones, so an assignment under dynamic scope (with) fails closed instead of reading as an intact loader.

Genuinely absent bindings, shadowing declarations, member overwrites, and calls lexically inside with are unchanged. Test-only additions otherwise.

Contribution scope fit and linked maintainer decision: ordinary fix within existing boundaries; not applicable.

Contract and boundary impact

  • Semantic owner and earliest changed stage: referenceSourceRequireBindings.unshadowedReferenceSourceRequireCalls (reference-source import parsing).
  • CLI and MCP/tool-catalog contract: fewer false requires relationships; no schema changes.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: replaced loaders no longer produce dependency facts.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable.
  • Generated metadata, package, or installation impact: none.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: for-of-var, for-in-var, and with-write fixtures in tests/boundary/filesystem/referenceSourceShadowedRequire.test.ts, each with a Node-oracle stdout check, excluded from the expected dependency list. The existing valid controls are unchanged.
  • Base reproduction: the extended test fails on the base revision (false edges reported); it passes with the fix. Verified via the issue's CLI reproduction (4-case matrix) before and after.
  • User-visible CLI/MCP output: relationships array in the import result; no CLI flag changes.
  • Remaining proof gaps: MCP path not executed (same import service; source-derived). Only Linux x64 exercised.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run test:focused -- tests/boundary/filesystem/referenceSourceShadowedRequire.test.ts — 2 passed.
  • npm run test:focused -- <referenceSourceImport, ReferenceSourceImportEntries, referenceSourceGraph, referenceSourceSummary> — 51 passed.
  • npm run check:fast (typecheck + lint) — green.
  • git diff --check — clean.
  • Real Hopper/Ghidra, browser, or OS coverage beyond Linux x64: unavailable.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Callers matching on the two false edges will stop seeing them.
  • Real Hopper/Ghidra, browser, or OS coverage: none.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: none; no target execution, no new I/O.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

…edges

import-reference-source kept a parsed internal requires edge when the
apparent loader call targeted a replaced local function: a for-in/of var
head initializes its binding on every iteration, and an assignment inside
with leaves the binding identity unknown. Both now fail closed like a
plain assignment, while a truly uninitialized top-level var require
retains its edge.

Fixes morluto#3982
@VarunGore36
VarunGore36 marked this pull request as ready for review October 15, 2026 10:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T14:17:14.028234Z c04ab26 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 2/5

[Medium impact] Refactors require binding detection logic for edge cases.

The PR should not merge until the two dependency-loss cases and the remaining skipped-property case are fixed.

Findings

  1. P1 Real dependencies disappear ▶
  2. P1 Empty loops hide dependencies ▶
  3. P1 Skipped properties hide loader writes ▶
Fix with agent prompt
### Issue 1
src/domain/referenceSourceRequireBindings.ts:348-349
A non-object `Symbol.unscopables` value now causes real dependencies to be dropped. For example, `with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs');` leaves Node's loader unchanged: the assignment updates the object's `require` property.

This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.

### Issue 2
src/domain/referenceSourceRequireBindings.ts:542-543
The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, `for (var require in { __proto__: 0 }) {} require('./dep.cjs');` still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns `require`.

This helper instead returns `false`, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.

### Issue 3
src/domain/referenceSourceRequireBindings.ts:320-326
`withObjectDeclaresRequire` treats a literal `require` property as proof that a write cannot reach Node's loader. But `with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; }` replaces the loader because `Symbol.unscopables` makes the object skip that property.

The shortcut hides this write, so a later `require('./dep.cjs')` produces a false dependency. Only shield the write when the object is known to capture it.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR changes how the importer decides whether require still refers to Node's loader.

  • The importer keeps require edges only when Node’s loader remains intact.
  • Loop-head require declarations keep edges only when the loop never assigns.

Reviews (8) · Last reviewed commit: "fix(reference): close shield gaps for un..." · Reviewed by Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f16dffda12

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

reference.name === "require" &&
reference.role === "write" &&
(reference.resolution === "unbound" ||
reference.resolution === "unknown" ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep shadowed dynamic writes from invalidating the loader

When a with assignment sits inside a function that already shadows require—for example, function f(require) { with ({}) { require = () => "local"; } }—the semantic reference is unknown only because the with-object may receive the write; its lexical fallback is the parameter, so it cannot modify Node's program loader. Counting every such reference in this file-wide flag suppresses a separate top-level require("./dep") relationship, regressing the shadowed-loader behavior this module preserves. Restrict unknown writes to dynamic scopes whose fallback can actually reach the program or unbound loader.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

@VarunGore36

Copy link
Copy Markdown
Contributor Author

Addressed the P1 in 3c8c340: unknown-resolution writes now kill the loader flag only when no lexical require binding intervenes between the write and program scope (function params and body var declarations, catch params, block and loop-head lexical declarations). The reported control keeps its edge and is now a regression fixture alongside a function-var variant; the issue's top-level cases still fail closed. Validation: shadowed-require suite plus the adjacent import/graph/summary suites green (53 tests), check:fast green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3c8c34047b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const functionBodyBindsRequire = (body: t.Node | null | undefined): boolean => {
if (body === null || body === undefined || !t.isBlockStatement(body))
return false;
return body.body.some(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve nested var bindings before invalidating the loader

The fresh evidence after the posted fix is functionBodyBindsRequire's direct body.body.some scan: in function patch() { if (false) { var require; } with ({}) { require = () => "local"; } }, the nested var is still hoisted to patch's function scope, so the dynamic write can target only the with-object or that local binding. This helper misses it, marks the program loader written, and drops a separate top-level require("./dep") edge even though Node's loader is untouched. Resolve the fallback through the existing semantic scope owner (or traverse all function-owned vars while excluding nested scopes) rather than duplicating only direct declarations.

AGENTS.md reference: AGENTS.md:L23-L23

Useful? React with 👍 / 👎.

Comment on lines +321 to +322
((t.isForInStatement(parent) || t.isForOfStatement(parent)) &&
parent.left === node);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the loader across zero-iteration var loops

For for (var require of []) {} (and other heads that execute zero iterations), the head never assigns the CommonJS wrapper parameter, so a following require("./dep") still loads dep. These lines set initialized solely from the syntactic parent, making hasUninitializedTopLevelVarRequire false and silently dropping that real relationship despite no loader replacement. Preserve the uninitialized case when the iterable is statically empty (and uncertainty when cardinality is not known) instead of treating every loop head as an executed assignment.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

return;
}
if (
reference.resolution === "unknown" &&

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small follow-up to consider: writes the analyzer marks ambiguous (rather than unknown) with a non-program binding still never kill the flag. If a dynamic-scope write can come out ambiguous instead of unknown, the same false edge returns through this branch. Worth either extending the treatment or noting it as explicitly out of scope.

programRequireBinding: string,
): boolean => {
let reached = false;
traverseJavaScriptAst(program, {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perf note, non-blocking: this is now a second full AST walk per file where the old code scanned the references map. Fine for typical inputs, but worth knowing for very large generated files since the traversal has no early exit once reached is set.

);
};

const functionBodyBindsRequire = (body: t.Node | null | undefined): boolean => {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Direct-child let/const (and using) in the function body also bind the function scope in all modes, so they shield just like var does here. Consider including non-var declarations — otherwise function f() { let require; with (O) { require = 1; } } still drops a valid top-level edge.

"patch(null);",
"console.log(require('./loaded.cjs'));",
].join("\n"),
"local-fn-var.cjs": [

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage locks the shield on the uninitialized and param sides. Consider one companion fixture on the initialized side — e.g. function patch() { var require = () => 1; with ({}) { require = () => 2; } } — to pin that an initialized function-body binding also shields the top-level edge.

An unknown- or ambiguous-resolution write kills the CommonJS loader
flag only when no lexical require binding intervenes between the write
and program scope. Function params and direct body declarations, catch
params, and block or loop-head lexical declarations shield the loader,
so a dynamic write that can only reach a local binding keeps the real
edge. A dynamic write with no such shield still fails closed. The full
write traversal runs only when a require write exists.

Adds local-binding shield fixtures and keeps the invalid cases edgeless.
@VarunGore36
VarunGore36 force-pushed the fix/3982-shadowed-require-reference-source branch from 26db13f to 40d7a86 Compare October 15, 2026 11:13
@VarunGore36

Copy link
Copy Markdown
Contributor Author

Addressed the review threads in 40d7a86 (squashed): unknown- and ambiguous-resolution writes now kill the loader flag only when no lexical require binding intervenes (function params and direct body declarations, catch params, block and loop-head lexical declarations); the reported local-param control keeps its edge and is a regression fixture with three shield variants. The traversal runs only when a require write exists. Validation: 3/3 shadowed-require tests plus the adjacent import/graph/summary suites green, check:fast green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 40d7a86347

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (scope === undefined) continue;
if (t.isProgram(scope)) return false;
if (t.isFunction(scope)) {
if (bindsRequireIdentifier(scope.params)) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude computed method keys from parameter shielding

When a with assignment is evaluated from a computed object-method key and that method declares a require parameter (for example, ({ [(() => { with ({}) { require = () => "local"; } })()](require) {} }); require("./dep")), the parameter is not in scope while the key runs; collectDefinitionsSteps already models this at src/domain/javascript/javascriptSemanticAnalysis.ts:749-755. This check nevertheless treats the method as an enclosing lexical scope and returns true, so the assignment that actually replaces the CommonJS wrapper loader is ignored and the later require is emitted as a real edge. Resolve the write through the shared semantic scope instead of AST ancestry.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

…oops

Function-body var bindings do not exist while parameter defaults run,
and computed method keys evaluate in the outer scope, so neither shields
a dynamic write there. Nested function-owned vars shield through
hoisting, and heads over statically empty iterables never assign.
Adds drop/keep fixtures for default params, computed keys, nested vars,
and empty loops.
@VarunGore36

Copy link
Copy Markdown
Contributor Author

Addressed the latest threads in this push: parameter-default and computed-key writes no longer inherit body bindings (verified against Node execution semantics), nested function-owned vars shield through hoisting, and statically empty loop heads stay uninitialized. Regression fixtures cover all four shapes with Node oracles; the new cases fail without the source changes. Suites green (3/3 file tests, 51 adjacent), check:fast green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9e7f223d14

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (bindsRequireIdentifier(scope.params)) return true;
if (child === scope.body) {
if (functionBodyBindsRequire(scope.body)) return true;
} else if (functionDeclarationsBindRequire(scope.body)) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not shield parameter-default writes with body functions

When a parameter default performs the dynamic write, declarations in the function body are not in scope during that parameter evaluation. The fresh final-tree counterexample function patch(x = (() => { with ({}) { require = () => "local"; } })()) { function require() {} } is nevertheless treated as shielded by this else, so a later top-level require("./dep") produces a false requires edge even though the default replaced the CommonJS loader; resolve this from the semantic scope owner rather than body syntax.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

child = scope;
continue;
}
if (!t.isBlockStatement(scope) && !t.isStaticBlock(scope)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor switch scopes when shielding dynamic writes

When a with assignment follows let require; in a switch case inside a function, that switch-wide lexical binding prevents the write from reaching the CommonJS wrapper loader. A fresh final-tree case such as switch (0) { case 0: let require; with ({}) { require = () => "local"; } } is missed because this ancestry scan skips SwitchCase/SwitchStatement, causing a separate real top-level require("./dep") edge to be dropped; use the existing semantic scope facts instead.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

};

const isStaticallyEmptyIterable = (node: t.Node | null | undefined): boolean =>
(t.isArrayExpression(node) && node.elements.length === 0) ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve loaders across sparse zero-iteration for-in loops

The post-fix counterexample for (var require in [,]) {} executes zero iterations with ordinary prototypes because for-in skips array holes, so a following require("./dep") still invokes the wrapper loader. Testing only elements.length === 0 treats the hole as an iteration, marks the binding initialized at line 383, and drops that real edge; emptiness needs to account for the loop kind and absent array elements.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 3299ed1 (verified locally; CI on this push pending): emptiness is now loop-kind aware — for-in counts present elements because it skips holes, for-of keeps length because it yields them. Fixture for (var require in [,]) {} keeps its edge (Node oracle loads the dep); for (var require of [,]) {} drops its (yields undefined, throws TypeError at the call — oracle-verified). Both live in the new test, which fails with the src hunk reverted.

}
if (bindsRequireIdentifier(scope.params)) return true;
if (child === scope.body) {
if (functionBodyBindsRequire(scope.body)) return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cache local-binding scans across dynamic writes

When a large generated CJS function contains many with assignments plus one local var require, every unknown write calls functionBodyBindsRequire and fully traverses the same function body; setting found only short-circuits callback work and does not prune traversal. With the number of writes proportional to body size this makes reference import quadratic, so derive or cache the function binding fact once (preferably from the existing semantic owner).

AGENTS.md reference: AGENTS.md:L46-L48

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 3299ed1 (verified locally; CI on this push pending): per-function binding facts memoize in a WeakMap keyed by body node, and the write walk is additionally gated on a require write existing (provably equivalent — no write references means reached stays false). Measured ad hoc on a synthetic file (one var require, 1500 with writes): ~2000ms before, ~70-130ms after on this machine — the per-write body rescan dominated, and the pollution scan adds one linear pass. No committed timing test (flaky by nature); the suites below are the standing proof.

Parameter defaults run before body var bindings exist, and computed
method keys evaluate in the outer scope, so neither inherits the other
side's shield. Switch cases contribute their direct lexical bindings.
Adds fixtures for default functions, computed keys, switch lets, and
the empty-loop keep.
@VarunGore36

Copy link
Copy Markdown
Contributor Author

pushed fixes for the new threads. i verified all four shapes against node first: body function declarations do not exist yet when defaults run, computed keys run outside, switch lets do shield, and empty loops keep the loader. i scoped the shields to the write's own region, added fixtures for each, and left prototype pollution out since static analysis trusts intact intrinsics everywhere. 3/3 file tests and 51 adjacent pass, check:fast is green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 74f9c436d2

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (
(reference.resolution === "unknown" ||
reference.resolution === "ambiguous") &&
!writeShieldedByLocalBinding(node, readAncestors())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve loaders when a with object captures the write

For a fresh binding object such as with ({ __proto__: null, require: null }) { require = () => 'local'; }, lookup must resolve to the object's own property, so the CommonJS wrapper parameter is untouched and a later top-level require('./dep') remains a real edge. This unknown-resolution branch only checks lexical shields, marks the program loader written, and drops that edge; the semantic with scope needs to retain a provable object binding instead of treating every such write as a fallback write.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +285 to +286
t.isVariableDeclaration(statement) &&
statement.kind !== "var" &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include block class bindings in dynamic-write shields

The fresh final-tree counterexample after the local-binding fixes is function patch() { { class require {}; with ({}) { require = () => 'local'; } } }: the assignment updates the block-local class binding, but this predicate recognizes only non-var variable declarations. Calling patch() therefore causes loaderWriteReachesProgramScope to suppress a separate top-level require('./dep') edge even though the wrapper loader is intact; use the semantic scope's declarations rather than this declaration-kind subset.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +306 to +308
if (bindsRequireIdentifier(scope.params)) return true;
if (child === scope.body && functionBodyBindsRequire(scope.body))
return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor named function-expression bindings

The fresh final-tree counterexample const patch = function require() { with ({}) { require = () => 'local'; } }; patch(); require('./dep') leaves Node's wrapper loader unchanged because the write resolves to the function expression's private name binding. This branch checks parameters and body declarations but never the function's own name, so it marks the program loader written and loses the real top-level relationship; resolve the fallback through the existing function-name semantic scope.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

}
if (t.isCatchClause(scope) && bindsRequireIdentifier([scope.param]))
return true;
if (t.isSwitchCase(scope) && blockBindsLexicalRequire(scope.consequent))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Search the whole switch scope for require bindings

The fresh final-tree evidence after the posted switch fix is that this scans only the current case, although javascriptSemanticAnalysis.ts:1189-1191 models all cases as one lexical scope. In switch (1) { case 1: let require; case 0: with ({}) { require = () => 'local'; } }, execution initializes the switch-local binding and falls through before the write, so the wrapper loader is untouched; because the declaration is in a sibling case, this check misses it and drops a subsequent real top-level require('./dep') edge.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.


const isStaticallyEmptyIterable = (node: t.Node | null | undefined): boolean =>
(t.isArrayExpression(node) && node.elements.length === 0) ||
(t.isObjectExpression(node) && node.properties.length === 0) ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not assume empty object literals make for-in empty

When an inherited enumerable property exists, for example Object.prototype.inherited = 1; for (var require in {}) {}, the loop executes and replaces the wrapper parameter with the property name, so a following apparent require('./dep') call is not a loader call. Treating every zero-property object literal as statically empty instead leaves hasUninitializedTopLevelVarRequire true and emits a false requires edge; for-in emptiness must retain prototype/enumeration uncertainty rather than considering only own literal properties.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

@VarunGore36

Copy link
Copy Markdown
Contributor Author

Latest threads addressed in 3299ed1 (verified locally; CI on this push pending):

  • Greptile P1 prototype pollution (r4282482148): emptiness no longer reasons from literal contents alone — loop-kind aware (for-in counts present elements, for-of keeps length) plus a file-wide X.prototype/proto member-write scan (via semanticWriteTargets) disabling the exemption. Fixtures: polluted for-in/for-of drop (Node oracle confirms the loader is replaced), sparse for-in keeps, for-of holes drop (yields undefined, throws). New test fails with the src hunk reverted.
  • Codex sparse for-in (r4282506473): same fix, same fixtures — length counted holes, for-in skips them.
  • Codex scan caching (r4282506477): WeakMap memo per body plus hasRequireWrite gating (provably equivalent). Ad-hoc measurement on a 1500-write synthetic file: ~2000ms before, ~70-130ms after; no committed timing test.
  • Codex param-default (r4282506450) and switch scopes (r4282506457): already closed by 74f9c43 in this branch — verified still green here, not re-litigated.

Validation: 4/4 shadowed-require tests, 53 green across the five adjacent suites (dynamic imports, import, summary, graph), check:fast green (tsc+lint, 0 errors). Residual, stated in code: reflective prototype mutation (defineProperty/Reflect/setPrototypeOf) is not scanned — member writes are the realistic shape; the rest is a documented follow-up.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3299ed11d8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +406 to +407
const site = semanticWriteSiteTarget(node);
if (site === null) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat reflective prototype mutation as iteration pollution

When a CJS file calls Object.defineProperty(Object.prototype, "x", { enumerable: true, value: 1 }) before for (var require in {}) {}, the loop executes and overwrites the wrapper parameter. The fresh final-tree evidence after the earlier prototype fix is that this scanner returns immediately because the call has no semanticWriteSiteTarget, then classifies {} as empty and emits a later require("./dep") as a loader edge; reflective or otherwise unproved prototype mutation must remain pollution/unknown rather than absence.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

return isForIn
? node.elements.every((element) => element === null)
: node.elements.length === 0;
if (t.isObjectExpression(node)) return node.properties.length === 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore prototype setters when counting for-in keys

For for (var require in { __proto__: null }) {}, the non-computed __proto__ entry sets the literal's prototype and creates no enumerable own property, so the loop runs zero iterations and the wrapper loader remains intact. Testing properties.length nevertheless marks this binding initialized and drops a following real require("./dep") edge; determine whether the literal has enumerable string keys instead of counting this special setter as one.

Useful? React with 👍 / 👎.

let initialized = false;
// Computed once per file: the exemption below infers non-iteration from
// literal contents, which holds only while shared prototypes are intact.
const mayPollute = fileMayPolluteIteration(program);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip the pollution scan without a candidate loop

Every non-explicit-module source invokes fileMayPolluteIteration before this helper has established that the file even contains a top-level var require in a potentially empty loop, adding a complete AST traversal to ordinary .js/.cjs files that cannot use its result. On large reference-source imports this is avoidable linear CPU work per file; collect pollution during the existing traversal or defer the extra pass until a candidate empty loop is found.

AGENTS.md reference: AGENTS.md:L49-L49

Useful? React with 👍 / 👎.

A with object that statically declares require captures the write, so
it shields. Block class declarations and named function expression ids
shield like other lexical bindings, and switch lets shield across sibling
cases. Prototype pollution is now loop-kind aware: plain member writes
affect for-in only, iterator and proto changes affect for-of, reflective
mutation affects both. A non-computed __proto__ entry creates no key.
The pollution scan runs only when a candidate empty loop exists.
@VarunGore36

Copy link
Copy Markdown
Contributor Author

pushed fixes for the new threads. i ran every shape in node first: with-objects holding require capture the write, block classes and named function ids shield, switch lets cover sibling cases, and plain member writes dont touch for-of iteration. i also split the pollution check by loop kind, added the reflective calls, and the scan now runs only when a candidate loop exists. 4/4 file tests and 51 adjacent pass, check:fast is green, new fixtures fail without the fix.

Comment on lines +320 to +326
return object.properties.some(
(property) =>
(t.isObjectProperty(property) || t.isObjectMethod(property)) &&
!property.computed &&
((t.isIdentifier(property.key) && property.key.name === "require") ||
(t.isStringLiteral(property.key) &&
property.key.value === "require")),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Skipped properties hide loader writes

withObjectDeclaresRequire treats a literal require property as proof that a write cannot reach Node's loader. But with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; } replaces the loader because Symbol.unscopables makes the object skip that property.

The shortcut hides this write, so a later require('./dep.cjs') produces a false dependency. Only shield the write when the object is known to capture it.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 320-326

Comment:
**Skipped properties hide loader writes**

`withObjectDeclaresRequire` treats a literal `require` property as proof that a write cannot reach Node's loader. But `with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; }` replaces the loader because `Symbol.unscopables` makes the object skip that property.

The shortcut hides this write, so a later `require('./dep.cjs')` produces a false dependency. Only shield the write when the object is known to capture it.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a297eaecee

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +435 to +437
t.isIdentifier(object) &&
ITERATION_PROTOTYPES.has(object.name) &&
key === "prototype"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve prototype aliases before declaring for-in inputs empty

The fresh final-tree case const proto = Object.prototype; proto.inherited = 1; for (var require in {}) {} is not recognized because this predicate only accepts a receiver literally named Object, Array, or String. The loop does execute and replaces the CommonJS wrapper parameter, yet isStaticallyEmptyIterable reports {} empty and a following require('./dep') is emitted as a false edge; resolve the receiver through the existing semantic binding/provenance facts before declaring no pollution.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +440 to +442
return landedComputed === true
? FULL_ITERATION_POLLUTION
: { forIn: true, forOf: false };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use resolved computed keys for for-of pollution

For Array.prototype['helper'] = () => 1; for (var require of []) {}, semanticStaticPropertyKey has already proven that the key is helper, which neither changes the array iterator nor adds an element, so the loop still executes zero iterations. landedComputed nevertheless forces full pollution solely because the syntax is computed, causing the valid following require edge to be dropped; determine the for-of effect from the resolved key instead of the computed bit.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +506 to +510
const isNonComputedProtoSetter = (property: t.Node): boolean =>
t.isObjectProperty(property) &&
!property.computed &&
((t.isIdentifier(property.key) && property.key.name === "__proto__") ||
(t.isStringLiteral(property.key) && property.key.value === "__proto__"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prove proto-setter prototypes before declaring objects empty

The final predicate treats every non-computed __proto__ entry as evidence that an object is empty, but for (var require in { __proto__: { inherited: 1 } }) {} executes once through the inherited enumerable key and replaces the CommonJS wrapper parameter. This leaves hasUninitializedTopLevelVarRequire true and emits a false later require edge; only classify the literal as empty when the setter value or resulting prototype's enumerable state is actually proven empty.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

if (!t.isWithStatement(scope)) continue;
const object = scope.object;
if (!t.isObjectExpression(object)) continue;
return object.properties.some(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Continue through outer with environments

With nested scopes such as with ({ require: null }) { with ({}) { require = () => 'local'; } }, lookup misses the inner object and is then captured by the outer object, so the wrapper loader remains intact. This returns false immediately for the inner object literal instead of examining the remaining ancestors, making loaderWriteReachesProgramScope drop a later real require('./dep') edge; continue the environment lookup through enclosing with scopes.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +322 to +326
(t.isObjectProperty(property) || t.isObjectMethod(property)) &&
!property.computed &&
((t.isIdentifier(property.key) && property.key.name === "require") ||
(t.isStringLiteral(property.key) &&
property.key.value === "require")),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor unscopables when proving with-object capture

The property-name test treats an own require property as unconditional capture, but with ({ require: null, [Symbol.unscopables]: { require: true } }) { require = () => 'local'; } explicitly excludes that property from the environment, so the assignment falls through and replaces the CommonJS wrapper loader. Shielding this write causes the later apparent loader call to be emitted as a false edge; account for Symbol.unscopables or retain the capture as unknown.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

Comment on lines +301 to +305
(t.isVariableDeclaration(statement) &&
statement.kind !== "var" &&
statement.declarations.some((declaration) =>
bindsRequireIdentifier([declaration.id]),
)) ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include block functions in lexical write shields

The final-tree case function patch() { { function require() {}; with ({}) { require = () => 'local'; } } } leaves the wrapper loader untouched because the write resolves to the block's function binding. blockBindsLexicalRequire recognizes lexical variables and classes but omits FunctionDeclaration, while the function-body scan also ignores this declaration because it is not a direct child of the function body, so a later real top-level edge is dropped; use the semantic scope's declaration facts here.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

… keyed protos

Symbol.unscopables entries opt the name back out, so a capturing object
with one no longer shields. Switch case bindings do not cover the
discriminant expression. Only keyless prototype chains keep an object
literal empty for for-in. Adds fixtures for all three with Node oracles.
@VarunGore36

Copy link
Copy Markdown
Contributor Author

pushed fixes for the latest threads. i verified each one in node: unscopables with a require entry really does opt back out, discriminant writes run before case bindings exist, and only keyless proto chains iterate nothing. i also fixed my own unscopables matcher which never matched. 4/4 file tests and 51 adjacent pass, check:fast is green, new fixtures fail without the fix.

Comment on lines +348 to +349
!t.isObjectProperty(unscopables) ||
!t.isObjectExpression(unscopables.value) ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Real dependencies disappear

A non-object Symbol.unscopables value now causes real dependencies to be dropped. For example, with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs'); leaves Node's loader unchanged: the assignment updates the object's require property.

This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 348-349

Comment:
**Real dependencies disappear**

A non-object `Symbol.unscopables` value now causes real dependencies to be dropped. For example, `with ({ require: null, [Symbol.unscopables]: null }) { require = () => 'local'; } require('./dep.cjs');` leaves Node's loader unchanged: the assignment updates the object's `require` property.

This check rejects that protection, marks the loader as written, and drops the real dependency. Recognize known non-object values as leaving the object's bindings available, and add a regression control.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +542 to +543
if (t.isNullLiteral(node)) return true;
if (!t.isObjectExpression(node)) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Empty loops hide dependencies

The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, for (var require in { __proto__: 0 }) {} require('./dep.cjs'); still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns require.

This helper instead returns false, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/referenceSourceRequireBindings.ts
Line: 542-543

Comment:
**Empty loops hide dependencies**

The new recursive check drops real dependencies when a prototype setter has a primitive value. For example, `for (var require in { __proto__: 0 }) {} require('./dep.cjs');` still calls Node's loader. JavaScript ignores the primitive prototype value, so the loop has no keys and never assigns `require`.

This helper instead returns `false`, causing the importer to treat the loader as replaced. Preserve the empty-loop result for known primitive prototype values and add a regression control.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c04ab26a49

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +341 to +344
if (!t.isWithStatement(scope)) continue;
const object = scope.object;
if (!t.isObjectExpression(object)) continue;
if (!object.properties.some(isRequireKey)) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict with-object captures to active statement bodies

When a write occurs while evaluating an enclosing with object's expression, that outer environment is not active yet. In with ({ require: (() => { with ({}) { require = () => 'local'; } return null; })() }) {}; require('./dep'), the inner assignment replaces the CommonJS loader, but this ancestor-only scan sees the outer object's require property and calls the write shielded, so the later local call is emitted as a false requires edge. Restrict this check to nodes contained in scope.body, matching the shared semantic scope owner.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +501 to +505
callee.property.name === "defineProperty" ||
callee.property.name === "defineProperties" ||
callee.property.name === "setPrototypeOf"
)
return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check reflective mutation targets before polluting iteration

When a file also contains a reflective write unrelated to a shared prototype—for example, Object.defineProperty(module.exports, 'x', { value: 1 }); for (var require of []) {}; require('./dep')—the empty loop never assigns require and Node still loads dep. These lines classify the call as full iteration pollution solely from the callee name, making hasUninitializedTopLevelVarRequire report the loader initialized and dropping that real edge. Inspect the mutation target (and relevant key/descriptor) before setting pollution instead of treating unresolved applicability as shared-prototype mutation.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

Comment on lines +54 to +56
const requireLoaderWasWritten =
hasRequireWrite &&
loaderWriteReachesProgramScope(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Limit loader writes to calls they can precede

For a top-level call that precedes a dynamic write, such as require('./dep'); with ({}) { require = () => 'local'; }, the dependency is loaded before replacement. loaderWriteReachesProgramScope nevertheless sees the later unknown write, and this one file-wide boolean is applied to every call by the condition at line 98, so the commit drops the real earlier edge. Compute reachability relative to each call (at least preserving direct top-level source order) rather than globally.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

morluto added a commit that referenced this pull request Oct 16, 2026
Model the CommonJS wrapper binding and query shared lexical identity, mutation, and evaluation timing at each call. Remove duplicate importer interpretation and preserve uncertainty for with scopes, prototypes, repeated writes, and opaque object escapes.

Validate generated fixtures against bounded Node oracles; no analyzed target execution is added.

Refs: #3982, #4072

Co-authored-by: Geronimo <[email protected]>
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

Conflict check from the CI & conflict-fix track: this branch conflicts with main, and main's 1b9b725 ("fix(javascript): unify loader binding and mutation ownership") references #4072 and is co-authored from this PR, so the change has already landed there. Resolving the conflict would reduce this branch to main's version, so I left it untouched. A maintainer may want to close this as superseded.

@VarunGore36

Copy link
Copy Markdown
Contributor Author

Sounds good. Thanks for letting me know :D

@VarunGore36
VarunGore36 deleted the fix/3982-shadowed-require-reference-source branch October 16, 2026 17:18
@morluto morluto added the bug Something isn't working label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Reference-source import reports dependencies after CommonJS require is replaced

3 participants