Skip to content

fix(javascript): retain TypeScript import-equals module dependencies - #2081

Closed
rekcilyssup wants to merge 11 commits into
morluto:mainfrom
rekcilyssup:fix/typescript-import-equals-dependencies
Closed

rekcilyssup wants to merge 11 commits into
morluto:mainfrom
rekcilyssup:fix/typescript-import-equals-dependencies

Conversation

@rekcilyssup

Copy link
Copy Markdown
Contributor

Summary

import value = require("./dep.cjs") in a .cts source parsed with complete coverage but contributed no import relationship and reported module_format: "unknown", while the TypeScript program it describes really loads the dependency. The TSImportEqualsDeclaration node was parsed but never classified by the binding, semantic module-link, or static reference producers, so the graph silently omitted a dependency the emitted program depends on. Fixes #2058.

Problem and expected behavior

  • Smallest trigger: a .cts file whose only dependency is an import-equals declaration, in a directory that also inventories the target.
  • Violated invariant: source module relationships must cover the dependencies of the emitted program, and the local alias must stay a real immutable binding that references resolve against.
  • Controls from the reported reproduction: tsc --module NodeNext exits 0, and the emitted main.cjs runs console.log(value) printing 42; the companion control.cjs using a plain require is already represented.
  • Expected: retain the value import-equals dependency with require semantics and the original declaration range, keep the immutable local alias, leave type-only declarations and internal namespace aliases free of runtime external dependencies, and keep an .mts source ESM when its import-equals compiles through createRequire.

Change and scope

  • bindInnerDeclaration (src/domain/javascript/javascriptSemanticAnalysis.ts) binds import-equals as an immutable import alias. Value external module references carry a module origin; type-only declarations and import alias = Some.Namespace aliases keep the local name with no origin, because TypeScript emits no load for either form.
  • collectSemanticModuleLink (src/domain/javascript/javascriptSemanticProjection.ts) projects a value external module reference as a kind: "require" link with importedName: "*", localName bound to the declaration and location equal to the declaration range, mirroring const x = require(...).
  • inspectNode (src/domain/javascript/javascriptStaticAnalysis.ts) emits the matching static require reference, so the legacy reference producer and the semantic producer agree.
  • moduleFormat (src/domain/javascript/JavaScriptModuleRelationships.ts) now treats .mts as ESM and .cts as CommonJS alongside .mjs/.cjs, because Node and TypeScript fix the module system by extension. Without this, the newly recovered require link would have flipped an .mts source to commonjs or mixed instead of staying ESM.
  • Intentionally not included: no change to import type { T } from ESM imports, namespace re-exports, package exports resolution, or the reference-source subsystem, which already parses import-equals separately.

Contract and boundary impact

  • Semantic owner and earliest changed stage: domain/javascript definition binding and module-link projection for TSImportEqualsDeclaration, then application/javascript module format classification.
  • CLI and MCP/tool-catalog contract: none — no schema, operation, or catalog change; new module_link_kind/kind edges and module_format values use existing vocabularies.
  • Provider, bridge, target-format, or platform compatibility: none; analysis stays static and reads no target.
  • Evidence, artifact, provenance, or reconstruction contract: the dependency edge keeps the declared specifier and the declaration's source range and file SHA; type-only and namespace-alias forms keep their local alias while reporting no dependency instead of an invented one.
  • Process execution, authorization, cleanup, or containment impact: none.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Evidence and regression coverage

  • Tests added or updated: a domain test in javascriptSemanticAnalysis.require_links.test.ts covering the require link, the three immutable aliases, retained origin for the value form and empty origins for the erased forms, and reference resolution; an end-to-end test in JavaScriptApplicationTypeScript.test.ts covering edges, resolved_path, and module_format for .cts and .mts.
  • Base reproduction or other evidence: both new tests fail on base 7c207c79 when only the source changes are stashed (2 failed | 28 passed), and pass with the fix. TypeScript emission was executed as the loader control: .cts value form emits const value = require("./dep.cjs"), .cts type-only form emits no load at all, and .mts emits createRequire(import.meta.url) inside a .mjs output.
  • User-visible CLI/MCP output (if applicable): main.cts now reports two imports edges for ./dep.cjs (semantic module_link_kind: require, resolution_status: resolved, resolved_path: dep.cjs, plus the static kind: require edge) and module_format: "commonjs"; esm.mts reports the same dependency with module_format: "esm"; type.cts and alias.cts report no import edges; coverage.status stays complete.
  • Remaining proof gaps: tests do not invoke tsc; the emission facts above were executed once while developing the fix and are stated as derived evidence.

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

  • npx vitest run src/domain/javascript/ src/application/javascript/ — 62 files, 1129 tests passed.
  • npx vitest run src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts src/application/javascript/JavaScriptApplicationTypeScript.test.ts — 30 tests passed; with the source changes stashed, the 2 new tests fail.
  • npx vitest run tests/boundary/filesystem/javascriptPackageExportTargets.test.ts tests/boundary/javascript/packageConditionalExports.test.ts tests/composition/javascript-applications/electronApplicationAnalysis.test.ts tests/acceptance/applications/electronPreloadOverridesCli.test.ts tests/acceptance/applications/packageSubpathsCli.test.ts — 5 files, 128 tests passed.
  • npx vitest run src/domain/referenceSourceGraph.test.ts — 13 tests passed.
  • npm run check:fast — typecheck and lint passed.
  • Issue reproduction probe (scripts/rea.mjs analyze-javascript-application) — main.cts two resolved require edges with module_format: "commonjs", esm.mts dependency with module_format: "esm", type.cts and alias.cts zero import edges, coverage.status complete.

Compatibility, safety, and release

  • Breaking changes or migration steps: none for valid input. Callers gain edges that were previously missing and see module_format move from unknown (or a content-derived guess) to the extension-fixed value for .mts and .cts sources.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable — static TypeScript source analysis only. Node.js and tsc were executed as controls.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: none; the change only adds classification of an already-parsed declaration and keeps resolution confined to the inventoried container.

Review checklist

  • This PR addresses a concrete problem or an agreed enhancement.
  • 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.

import value = require("./dep.cjs") in a .cts source parsed with
complete coverage but produced no import relationship and reported
module_format unknown, while the emitted program loads the dependency.

Bind the declaration as an immutable import alias, project it as a
require module link, and emit the matching static require reference so
both graph producers keep the dependency. Type-only declarations and
internal namespace aliases keep their local alias without a module
origin because TypeScript emits no load for either form. Module format
now follows Node and TypeScript's extension rule for mts and cts, so an
mts source stays ESM when its import-equals compiles through
createRequire.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 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-13T18:48:09.132549Z 4778c70 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.

@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: 827ff567ad

ℹ️ 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".

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

@greptileai review

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5 Tier: plus

[Medium impact] Refactors TypeScript import-equals and namespace scope handling.

Correct the new source-range assertion before merging; it fails for valid dependency output.

Findings

  1. P1 Correct dependency test fails ▶
Fix with agent prompt
### Issue 1
tests/boundary/filesystem/javascript-applications/javascriptApplicationTypeScript.test.ts:204
Both fixtures contain `import value = require("./dep.cjs");`, which ends at column 35. This assertion expects `end.column` to be 36. `range` copies Babel’s end column, and graph evidence keeps it unchanged, so the new test fails for both files even when their dependency edges are correct. Expect 35, or derive the range from the fixture.

```suggestion
            end: { line: 1, column: 35 },
```

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

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

Summary

The changes retain origins for internal TypeScript import aliases and give namespaces separate private scopes with shared exported names.

  • Import-equals aliases keep their module origins in semantic analysis.
  • TypeScript namespace names resolve across matching blocks without leaking private names.

Verification was source-only; tests were not run. git diff --check passed. Supersession could not be checked because GitHub authentication was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  D[TypeScript declaration] --> K{Declaration kind}
  K -->|External value import| M[Require origin]
  K -->|Internal alias| I[Initializer and qualified path]
  K -->|Type-only import| T[No runtime binding]
  I --> L[Resolve private names first]
  L --> E[Then shared namespace exports]
  L --> P[Then enclosing scopes]
  G[Global augmentation] --> O[Outer global scope]
  P --> O
Loading

Reviews (11) · Last reviewed commit: "Merge branch 'main' into fix/typescript-..." · Reviewed by Greptile

Pinned main already implements import-equals via owning helper; removed duplicate merged producers and obsolete redundant unit regression, retained contributor filesystem regression. Review fixes preserve internal alias provenance from TSQualifiedName, add namespace scope ownership, and verify per-source require edges and declaration ranges.

Source inspection and git diff --check. Further tests/typechecks/builds skipped by explicit user instruction; canceled validations are not passes.

@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: 719d87778a

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Admit immutable import-equals initializers to the shared stable-initializer owner. Namespace blocks retain private lexical scope while a shared exported-member owner resolves repeated namespace declarations; all binding lookup paths reuse that owner.

Source inspection and git diff --check only. Tests, builds and typechecks skipped by explicit user request. GitHub review writes paused globally.

@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: e6f89a2247

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open.

  1. thread 1, thread 2

Fixed in e6f89a2.

Root cause and structural fix: The shared stable-initializer owner now admits immutable import-equals aliases while excluding runtime ESM imports. Electron classification can reach the existing qualified-alias provenance instead of stopping at the initializer gate.

Validation: source inspection and git diff --check only. Tests, builds and typechecks were skipped by the user's explicit request; no runtime or real-provider pass is claimed. No directly related cleanup remains identified.

  1. thread 1, thread 2

Fixed in e6f89a2.

Root cause and structural fix: Each namespace block retains its private lexical environment, and repeated declarations reuse a shared exported-member owner. All binding lookup paths consult that owner while preserving lexical parents and private shadowing; the IR retains the exported-scope link.

Validation: source inspection and git diff --check only. Tests, builds and typechecks were skipped by the user's explicit request; no runtime or real-provider pass is claimed. No directly related cleanup remains identified.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open.

  1. thread 1

Fixed in 553efb8. Babel represents export-import ownership on TSImportEqualsDeclaration.isExport, so checking only an ExportNamedDeclaration parent kept these aliases private. namespaceDeclarationScope now recognizes that producer flag and routes the declaration through the same shared exported-member owner used by exported variables/functions/classes. Both alias binding and name/provenance lookup continue using that owner; private aliases retain their separate lexical block. A reopened-namespace Electron provenance regression was authored, not run. Source inspection followed Babel declaration handling, binding ownership and Electron call classification; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. No downstream provenance workaround was added.

  1. thread 1

Fixed in 553efb8. Only the final TSModuleBlock previously created a namespace owner, dropping earlier dotted declaration segments and colliding A.B with top-level B. The owning scope builder now walks the TSModuleDeclaration chain and interns each segment under its actual parent owner. This also makes dotted A.B and nested exported A/B declarations share the same identity, while an unrelated top-level B remains distinct. Regression source covers all three forms and both positive and negative Electron provenance; it was not run. Source inspection followed parent indexing, export ownership and semantic binding lookup; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. The superseded final-name-only key path is removed.

@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: 553efb800c

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@morluto morluto added bug Something isn't working area: domain Domain logic, errors, and pure functions P2: medium Medium priority issue labels Oct 13, 2026

@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: e3306333a5

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Source fixes and publication evidence for the review findings below. Tests and executable checks were skipped at the maintainer's request. Findings that still require a decision or execution evidence remain open.

review thread

Dotted namespace bodies resolve outer exports through the shared namespace owner chain after private lexical lookup. semanticScopedBinding now traverses those parent owners while retaining private shadowing; producer and consumer regression source covers inherited exports, hidden private names, and repeated nested namespaces. Source inspection and git diff --check passed; tests were not run.

…mport

The call root is the shared Electron module alias itself, so the proven
root path is empty, matching the established require("electron")
.ipcMain.handle classification. The authored expectation ipcMain was
never run and made the reopened-namespace regression fail on the
correct behavior.

Validated with typecheck and the javascript domain and application
suites.
The shared-owner walk in semanticScopedBinding consulted every owner
binding before the lexical climb resumed, so a nested exported namespace
resolved names against its containing namespace's export owner before
the enclosing block's private bindings. A private ipcRenderer binding in
a reopened namespace block lost to the shared ipcMain export, and an
enclosing namespace private lost to a same-named program binding.

Stop the owner walk at any owner that an enclosing lexical scope claims
as its namespaceExportScopeId (or reaches as its parent), so each
enclosing scope resolves its own private bindings first while dotted
bodies still read outer-segment exports that their lexical parent skips.

The strict worker scope schema also lacked the "namespace" kind and
namespaceExportScopeId that immutableSemanticScopes now emits, so any
TSModuleBlock scope failing the record parse would abort a transfer.
Extend the schema with a round-trip test that retains namespace scopes
and their export owners across writeJavaScriptAnalysisTransfer.

@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: d22f2fc826

ℹ️ 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".

parent = state.parentsByNode.get(declaration);
}
if (
(t.isExportNamedDeclaration(parent) && parent.declaration === declaration)

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 Route ambient namespace members to the shared owner

For a reopened ambient namespace such as declare namespace N { const require: (s: string) => unknown; } namespace N { export const x = require("not-a-module"); }, ambient members are implicitly exported even without an ExportNamedDeclaration, so this predicate leaves require in the first block's private scope. The second block then records it unbound and collectUnboundRequireLink invents a dependency on not-a-module, although TypeScript emits N.require(...); route declarations in an ambient namespace context to the shared owner as well.

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

Useful? React with 👍 / 👎.

namespaceDeclarationScope only recognized an ExportNamedDeclaration
wrapper, but ambient namespace and module bodies export every member
implicitly. A reopened ambient block therefore kept its members private:
declare namespace N { const require: ... } followed by namespace N bound
the second block's require() call to nothing, so collectUnboundRequireLink
invented a dependency on the call's string argument even though
TypeScript emits N.require(...) and no module is loaded.

Route declarations whose ancestor chain includes a declare-marked
TSModuleDeclaration to the shared exported-member owner, matching the
TypeScript rule that ambient members are exported by default at any
nesting depth. The shared owner keeps the reopened block's reference
resolved, which suppresses the fabricated require link at its source.

@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: dcf804e57e

ℹ️ 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".

parent: t.Node | null,
): JavaScriptSemanticScopeState["kind"] | undefined => {
if (t.isFunction(node)) return "function";
if (t.isTSModuleBlock(node)) return "namespace";

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 Expose global augmentations to program lookups

When an external-module source uses a global augmentation such as export {}; declare global { const require: (s: string) => unknown; } require("not-a-module"), Babel represents the body as a TSModuleBlock under a TSModuleDeclaration with global: true, but this unconditional branch models it as an ordinary namespace scope. The augmented binding is consequently stored under the namespace export owner while the following program reference never traverses that owner, so collectUnboundRequireLink invents a runtime dependency (and other augmented globals remain unbound); global-augmentation members need to participate in global name lookup rather than named-namespace lookup.

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

Useful? React with 👍 / 👎.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Source fixes and publication evidence for the review findings below. Tests and executable checks were skipped at the maintainer's request. Findings that still require a decision or execution evidence remain open.

review thread, review thread

Status: Current live source already contains namespace schema shape and private-before-shared lookup; inspected at live head. Validation is source-only; no tests/builds/checks/CI reruns were run. Root cause, owner-level fix, and any residual cleanup are recorded in the per-PR result. This is not a claim of exact CI reproduction.

A top-level `declare global` block was modeled as an ordinary named
namespace, so its members landed under a synthesized exports:["global"]
owner that program-name lookup never traverses. The augmented binding
was recorded unbound and collectUnboundRequireLink invented a runtime
dependency on the call's string argument.

Babel 8 marks no global flag, so a global augmentation is identified by
declare: true with an Identifier id of global directly under the
Program; a nested `declare namespace global` keeps its namespace owner.
Route the augmentation block's namespaceExportScopeId to the enclosing
program scope so its members participate in global name lookup.

The ambient walk in ambientNamespaceContext also now starts at the
declaration itself: a declaration that is itself ambient (`declare
namespace B`) exports its own name, so its owner matches the one
reopened dotted declarations create instead of leaving them unbound.
@greptile-apps

greptile-apps Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@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: fd5019b506

ℹ️ 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 +950 to +953
t.isTSModuleDeclaration(node) &&
node.declare === true &&
t.isIdentifier(node.id, { name: "global" }) &&
t.isProgram(state.parentsByNode.get(node) ?? null);

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 module kind before treating global as an augmentation

When a valid file contains declare function require(...); declare namespace global { const require: ...; } require("./dep"), Babel marks the namespace declaration as kind: "namespace", but this predicate matches it solely because it is declared, named global, and top-level. Its member is consequently installed in the program scope, so collectUnboundRequireLink sees a false binding and omits the ./dep edge even though TypeScript emits the unqualified call unchanged; gate this on the parsed module kind rather than the name/position heuristic.

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

Useful? React with 👍 / 👎.

Comment on lines +989 to +992
names.unshift(t.isIdentifier(id) ? id.name : id.value);
let owner = namespaceDeclarationScope(parent, parentScope, state);
for (const [index, name] of names.entries()) {
const key = JSON.stringify([owner.scopeId, name]);

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 Tag quoted modules in namespace owner keys

When declare module "N" { const require: ... } and runtime namespace N { export const x = require("./dep") } coexist, TypeScript keeps the string-literal external module and identifier namespace distinct, but these lines reduce both IDs to N and reuse the same owner key. The runtime namespace then resolves its call to the ambient module's require, causing collectUnboundRequireLink to suppress the real dependency even though TypeScript emits an unqualified require("./dep"); retain an identifier-vs-string tag in the owner identity.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

Distinguish `declare global` by Babel's exact `kind: "global"`
discriminator instead of the identifier name: a top-level
`declare namespace global` carries `kind: "namespace"` and declares an
ordinary namespace whose later require() calls keep their dependency
links. The name heuristic misclassified it and hid its dependencies.

Bind augmentation members in a lazily created outer scope, parented
above the program scope, rather than in the program scope itself.
Augmentation members live outside the module scope, so file-local
bindings now shadow them instead of merging: an `import ipc` keeps its
single definition beside a global `var ipc`, and the local call still
classifies. The outer scope participates in ordinary lexical lookup,
so global-only names keep resolving from any program position.

@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: 7dbe0fd6d0

ℹ️ 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 (
(t.isExportNamedDeclaration(parent) &&
parent.declaration === declaration) ||
ambientNamespaceContext(declaration, state)

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 ambient import aliases private unless explicitly exported

Fresh evidence after the ambient-member fix is that TypeScript does not implicitly export import aliases: with a program binding ipc = electron.ipcRenderer, declare namespace N { import ipc = electron.ipcMain; }, and a reopened namespace N { ipc.send(...) }, the final ipc resolves to the program binding. This blanket ambient branch instead stores the alias in N's shared owner, so Electron classification attributes the call to ipcMain rather than ipcRenderer; only explicitly exported ambient import aliases should use the shared owner.

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

Useful? React with 👍 / 👎.

Comment on lines +951 to +953
node.declare === true &&
node.kind === "global" &&
t.isProgram(state.parentsByNode.get(node) ?? null);

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 Recognize global augmentations nested in ambient modules

Fresh evidence after the top-level-global guard is the valid inherited-ambient form declare module "x" { global { const require: (s: string) => unknown; } }: its global declaration is parented by a TSModuleBlock, not the program, and has no inner declare modifier. These predicates therefore leave its members under module x, so a following require("not-a-module") is recorded unbound and collectUnboundRequireLink invents a dependency; route kind: "global" declarations nested directly in ambient module declarations to the program-global owner while continuing to exclude ordinary namespaces named global.

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

Useful? React with 👍 / 👎.

@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: 4778c70b45

ℹ️ 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".

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

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

definitionNode: node.id,
initializer: null,
directOrigin: { specifier, importedPath: [], resolutionMode: "require" },
initializer: specifier === null ? node.moduleReference : null,

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 type-space aliases out of runtime bindings

When an internal import alias resolves only in TypeScript's type namespace but a same-named value declaration supplies the runtime value—for example, const ipc = electron.ipcRenderer; namespace T { export interface ipc {} } import ipc = T.ipc; ipc.send(...)—TypeScript accepts the merge and erases the alias. Recording T.ipc as another initializer on the value binding makes semanticStableInitializer reject the otherwise stable ipc binding, so Electron classification drops the valid ipcRenderer call and the IR loses its module provenance; model the type and value identities separately instead.

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

Useful? React with 👍 / 👎.

kind: "source-range",
source: path,
start: { line: 1, column: 0 },
end: { line: 1, column: 36 },

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 Correct dependency test fails

Both fixtures contain import value = require("./dep.cjs");, which ends at column 35. This assertion expects end.column to be 36. range copies Babel’s end column, and graph evidence keeps it unchanged, so the new test fails for both files even when their dependency edges are correct. Expect 35, or derive the range from the fixture.

Suggested change
end: { line: 1, column: 36 },
end: { line: 1, column: 35 },
Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/boundary/filesystem/javascript-applications/javascriptApplicationTypeScript.test.ts
Line: 204

Comment:
**Correct dependency test fails**

Both fixtures contain `import value = require("./dep.cjs");`, which ends at column 35. This assertion expects `end.column` to be 36. `range` copies Babel’s end column, and graph evidence keeps it unchanged, so the new test fails for both files even when their dependency edges are correct. Expect 35, or derive the range from the fixture.

```suggestion
            end: { line: 1, column: 35 },
```

---

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

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The first fix in this PR is already on main, and main gives the same output as the head on the issue's example. The namespace work is still new: 15 of the PR's tests fail on main and pass on the head, and a 16th fails on both. One PR test fails because its expected count is wrong, and one file fails the format check.

I tested head 4778c70 as pushed. GitHub says it conflicts with main 4692bb3, which is 368 commits ahead of the merge base.

Results

Check Node 24.18.0 Node 26.11.1
The PR's 4 test files, on head (55 tests) 54 pass, 1 fails 54 pass, 1 fails
The same 4 files, on main 4692bb3 39 pass, 16 fail not run
Main's own versions of those 4 files, on main (48 tests) all pass not run
The 1 failing test, with its count changed from 2 to 4 passes (9 of 9) not run
Format check on head fails on one file not run

On main, 16 tests fail. One is the line-216 test, which fails on head too. The other 15 are namespace and alias tests.

The failing test sits at line 216 of the TypeScript boundary test. It expects 2 resolved edges. The head makes 4: one meaning link and one static link for each of main.cts and esm.mts. Every edge has the right file, range and resolved path, so the count looks wrong, not the code. This matches the failing CI shard.

Greptile asked for end column 35 on the same test. The head emits 36 and the test expects 36, so they agree. Greptile's 35 does not match what the head emits.

Before and after, on the CLI (Node 24.18.0):

Example Main Head
The issue's import-equals example (.cts and .mts) 4 edges, formats commonjs and esm same 4 edges, same formats
import alias = electron.ipcMain; alias.handle(...) IPC call missed IPC call found
A name private to namespace B, used outside B Main treats it as ipcMain Head ignores it
export const shared in one namespace A, used in a reopened namespace A found found

Not run

  • Node 22, and Node 26 on main.
  • The before and after runs on the CLI, and every run on main, used Node 24.18.0 only.
  • The head merged onto current main. I did not check which files conflict.
  • The full test suite and the acceptance tests.
  • Windows and macOS.

Thanks, Aravind Rao and morluto, for the fix and the namespace tests.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 24.18.0, 26.11.1
  • Head: 4778c70
  • Base: 2895a18
  • Other: main 4692bb3; both trees built with Node 24.18.0
Commands
npm ci && npm run build && npm run test:prepare
npm run format:check

The format check flags this file:

src/domain/javascript/javascriptSemanticProjection.ts
node scripts/run-development-tests.mjs focused \
  src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts \
  src/domain/javascript/javascriptSemanticAnalysisSteps.test.ts \
  tests/boundary/filesystem/javascript-applications/javascriptApplicationTypeScript.test.ts \
  tests/boundary/javascript/javascriptAnalysisTransferBudgets.test.ts
node scripts/rea.mjs analyze-javascript-application <fixture> --json

For the main rows, I copied the head's 4 test files onto the main tree. Each fixture is a folder with a package.json and one .cts file. Every run sat under nice -n 19 and systemd-run --user --scope -p MemoryMax=6G.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

@morluto

morluto commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Superseded by the delivered change on main: 86fab11fb. Runtime TypeScript import-equals links are retained through require resolution, with producer and public workflow coverage. This closure does not claim the separate type-only import-equals report #3932 is resolved. Closing this earlier proposal. Current main qualification passed: https://github.com/morluto/rea/actions/runs/38690953281.

@morluto morluto closed this Oct 15, 2026
@morluto

morluto commented Oct 15, 2026

Copy link
Copy Markdown
Owner

@rekcilyssup, thank you for identifying the runtime import-equals gap. Main now retains import-equals declaration and export evidence; this thanks is for that runtime case.

@morluto morluto added the area: evidence Evidence, artifacts, and reconstruction label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: domain Domain logic, errors, and pure functions area: evidence Evidence, artifacts, and reconstruction bug Something isn't working P2: medium Medium priority issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] TypeScript import-equals declarations lose their module dependency during analysis

3 participants