Skip to content

fix(js): treat require() outside a declaration as an import (#5731) - #5799

Open
ishyverma wants to merge 1 commit into
Graphify-Labs:v8from
ishyverma:fix/js-require-in-expression-5731
Open

ishyverma wants to merge 1 commit into
Graphify-Labs:v8from
ishyverma:fix/js-require-in-expression-5731

Conversation

@ishyverma

Copy link
Copy Markdown

What does this PR do?

Fixes #5731.

Only const x = require('./m') (and require('./m').y) produced an imports_from edge. Any other position gave nothing. On current v8:

// main.cjs
const one = require('./a.cjs');
const rules = [
  require('./b.cjs'),        // no edge
];
require('./c.cjs');           // no edge
use(require('./d.cjs'));      // no edge
module.exports.e = require('./e.cjs');  // no edge
function lazy() { return require('./h.cjs'); }  // no edge

After this change each of these gets an imports_from edge (EXTRACTED, same shape as the declared form).

How:

  • extractors/engine.py:
    • The edge construction moves out of _require_imports_js into _js_require_import_edge, unchanged, so all forms build the same edge (unresolved specifiers keep the ref: id, target_file set when resolved).
    • _js_free_require_call matches a require(...) call with an identifier callee that is not a declarator's value (the form _require_imports_js already handles), so that form still gets exactly one edge.
    • The module-level JS scan (_scan_js_module_dispatch, which already stops at function and class boundaries) emits the edge from the file node.
    • walk_calls emits it from the enclosing callable, the same attribution a declared require in a body already gets.
  • ARCHITECTURE.md: a short paragraph documenting the rule.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a require('<string literal>') call is an import of that module wherever the call appears, and only a literal specifier creates one.

Bug cases (fail before, pass after):

  • a require in an array literal (the issue's case);
  • a bare statement, a call argument, an object value, an assignment's right side and a require(...).x on that side;
  • a require returned from a function, attributed to the function.

Guards (pass before and after):

  • the declared forms (const a = require(), require().x, and a declared require in a function) still give exactly one edge each;
  • a computed specifier (require(name)), require.resolve('./a') and obj.require('./a') give no edge.

Limitations:

  • Like the declared form, a locally shadowed require (a parameter or function named require) is not detected; the call is still read as CommonJS require.
  • A require only gets an edge where the existing passes already walk: module level, and function bodies walk_calls visits. Template-literal specifiers stay unsupported, as in the declared form.
  • When a file both imports a module statically and requires it, the build already collapses the two into one edge and keeps the other location in also_seen; the primary source_location can now be the require line. No edge is lost (checked on mem0 below).

Cache: the JS/TS extractor output changes (new edges), so it needs an AST cache schema bump. I've left that to the maintainers' release step, as with other extractor changes.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

How was this tested?

uv run pytest tests/test_js_require_in_expression.py   # 5 passed
# without the source change: 3 failed (bug cases), 2 passed (guards)
uv run pytest tests -n auto                            # 13027 passed, 166 skipped, 5 xfailed
uv run pytest tests/test_architecture_doc.py           # 38 passed
uv run ruff check .                                    # All checks passed!
uv run pyright                                         # 784 errors, same as v8; engine.py 20 before and after
graphify extract <mem0> --code-only                    # 18 new imports_from pairs + 8 follow-on calls edges, all at real require() sites;
                                                       # 3 existing pairs now located at the require line (old line kept in also_seen); no pair lost

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (n/a)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

…-Labs#5731)

Only `const x = require('./m')` (and `require('./m').y`) produced an
`imports_from` edge. The same call as an array element, a call
argument, an object value, an assignment, a bare statement or a return
value gave no edge, so rule/plugin registries such as
`const rules = [require('./b.cjs')]` lost their dependencies in `path`
and `affected`.

The edge construction moves out of `_require_imports_js` into
`_js_require_import_edge`, shared with two new call sites: the
module-level JS scan (edge from the file) and `walk_calls` (edge from
the enclosing callable, as for a declared require in a body).
`_js_free_require_call` skips the declarator form so it still gets one
edge. A computed specifier, `require.resolve()` and `obj.require()`
give no edge.

Tests: tests/test_js_require_in_expression.py; the three bug cases fail
without this change, the two guards pass both ways.

Co-Authored-By: Claude Opus 5.5
@ishyverma
ishyverma requested a review from safishamsi as a code owner December 5, 2026 10:42

@graphify-labs graphify-labs 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.

Graphify review View in Graphify

Review before merging · Merge confidence 4/5

1 bug · High impact

The change factors literal require() edge creation into a helper and adds extraction for calls outside variable declarations.

P2  Shadowed require calls create false import edges · engine.py:6709

What this review covered
  • We didn't review 1 file that isn't source code, such as docs, config, images, or generated or third-party code.
  • 2 of 2 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 5056 functions depend on this change
  • 693 of 693 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed 4f66c6d

Comment on lines +6706 to +6709
if node.type != "call_expression":
return False
fn = node.child_by_field_name("function")
if fn is None or fn.type != "identifier" or _read_text(fn, source) != "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  Shadowed require calls create false import edges

A function that uses its own require parameter can be shown as importing a local file it never loads.

Check that require resolves to the CommonJS loader before emitting edges in _js_free_require_call and declaration-form handling.

Evidence · checked against the code

Expected: Only calls to the CommonJS loader should create an imports_from edge.
Actually: The extractor treats the bare identifier spelling require as sufficient and emits an edge without checking which binding the call resolves to.

  • Independent source review: The test covers obj.require(...) and verifies that it adds no edge, but this only rules out member-expression callees. It does not guard a bare identifier shadowed by a parameter or local binding. The other tests exercise unshadowed bare require calls, so they do not refute the reported false edge.
  • The added tests cover obj.require(...) but do not cover a bare require identifier shadowed by a parameter or local binding.
Prompt to fix with AI
In graphify/extractors/engine.py, _js_free_require_call (lines 6706-6709):
Problem: Shadowed `require` calls create false import edges
Expected: Only calls to the CommonJS loader should create an `imports_from` edge.
Actually: The extractor treats the bare identifier spelling `require` as sufficient and emits an edge without checking which binding the call resolves to.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

require() inside an array literal is not extracted (no module edge)

1 participant