Skip to content

feat(javascript): fold constant values and recover Electron boundaries through wrappers - #2094

Open
coleleavitt wants to merge 50 commits into
morluto:mainfrom
coleleavitt:pr/javascript-constant-folding-electron-ipc
Open

coleleavitt wants to merge 50 commits into
morluto:mainfrom
coleleavitt:pr/javascript-constant-folding-electron-ipc

Conversation

@coleleavitt

Copy link
Copy Markdown

Depends on #2092 — this branch is based on it, so its first five commits are that PR's; review the commits listed below.

Branch: pr/javascript-constant-folding-electron-ipc
Base: pr/javascript-semantic-budget (depends on it; see below). Merge that PR first.

Commits (on top of pr/javascript-semantic-budget):

  • 428ef76 feat(javascript): fold primitive operators, join, and fromCharCode
  • aadf79d feat(javascript): report folded constants in Electron, IPC, and endpoint findings
  • 2375e53 feat(javascript): fold semantic request endpoints and configuration defaults
  • 2cf4d02 feat(javascript): report URL, host, and path values present in data
  • 4caa76a docs(javascript): describe folded values and data endpoints
  • 6c2c5f7 fix(javascript): report files whose static values stay literal-only
  • b300f75 feat(electron): infer Electron APIs passed through one wrapper parameter
  • 0ab2a6b feat(electron): enumerate contextBridge APIs bound to object literals
  • a352d04 feat(electron): report WebContentsView/BrowserView and will-attach-webview hardening
  • 315e063 feat(electron): infer Electron APIs from local fallback alternatives
  • 26b69f1 feat(electron): resolve native add-ons loaded through createRequire, bindings, node-gyp-build and process.dlopen
  • 12df9c6 feat(electron): report Content-Security-Policy declarations and broad sources
  • b60f2d8 fix(electron): follow createRequire aliases used as parameter defaults
  • 79dd864 refactor(javascript): give the constant lattice one leaf-parameterized operator folder
  • 8eed2c4 feat(javascript): fold wrapped Electron values with the shared operator folder
  • 2c6bef6 feat(javascript): recover generated IPC channels across wrapper chains and linked sources

Problem

REA's static Electron model misses most of what a minified, wrapper-heavy Electron
app exposes. REA_REPORT.md §2 lists the gaps found by manual reading of Grok Bot 0.68.1
(REA 6.3.0), and they persist on current origin/main b3dec00:

  • No constant folding. Minified !0/!1 options were reported as dynamic;
    channels and endpoints built with +, templates, join or String.fromCharCode
    stayed unresolved.
  • Electron APIs passed as parameters were invisible. The WebAuthn consent window is
    new t({…}) where t is BrowserWindow passed to a wrapper
    (main-app.cjs:369:807). The whole app RPC layer (dune-rpc:${edge}:m:${method})
    registers handlers through ipcMain passed as a parameter, with template channels.
  • contextBridge.exposeInMainWorld("desktop", lp) with lp bound to an object
    literal reported members: [].
  • No WebContentsView/BrowserView, no will-attach-webview hardening, no CSP.
  • Native add-ons loaded through createRequire, bindings or node-gyp-build were
    not resolved.
  • URL/host constants in data tables (API hosts, MCP/OAuth provider tables) were not
    reported; the endpoint model only saw call sites.

What changed

  • Constant lattice: void, typeof, !, ~, arithmetic, comparison, shift and
    bitwise operators over exact primitives, templates, Array.prototype.join and
    String.fromCharCode fold through one leaf-parameterized operator folder
    (foldSemanticOperands) shared by static values and wrapper substitution. Only
    JSON-representable results become values. Folded values report status: "derived"
    with the source expression; IPC pairing treats derived channels as exact
    (unique-exact-derived-channel). A file whose member-write recovery exceeds a
    resource limit keeps literal-only values and says so in limitations.
  • Data endpoints: URL, host and path strings in data (literals, object keys,
    template text, folded expressions) are reported as endpoint_kind: "data" with
    url_class, host and property_path. Host-only values must be lowercase DNS names
    under a two-letter IANA ccTLD or a common gTLD.
  • Electron API identity: a callee that is a wrapper parameter (or destructured
    parameter key) resolves when every same-file call site passes the same proven
    Electron export (basis: "wrapper-parameter"); a local ??/||/&&/conditional/
    object-literal binding resolves when its proving branches agree
    (basis: "local-alternatives"). Relationships that depend on an inferred identity
    are inferences with medium/low confidence.
  • contextBridge APIs bound to one stable object literal list their members
    (api_status: "object-binding", conditional_members for known conditional spreads).
  • BrowserView/WebContentsView constructions, and will-attach-webview writes and
    deletions on webPreferences/params plus the last static preload path.
  • Native loaders: module.createRequire functions, bindings, node-gyp-build and
    process.dlopen, directly, through one alias, or through a parameter default.
  • Content-Security-Policy from <meta http-equiv>, header properties/assignments,
    [...].join directive lists and string/template literals, with per-directive
    concerns. Runtime parts stay ${…} and are not judged.
  • Wrapper substitution follows computed IPC channels from the outermost same-file
    callers through up to eight wrapper levels, iterates exact arrays in for…of,
    links a unique globalThis[Symbol.for(key)] publication in another source of the
    artifact, and reports operations reached only under unresolved predicates with
    guard_alternatives (counted as guarded_renderer_transmissions, no pairing edge).
  • New finding keys use compositeKey (no NUL-joined keys).

Why it depends on pr/javascript-semantic-budget

Both change the worker protocol and schemas (JavaScriptAnalysisWorker*.ts),
JavaScriptArtifactAnalysis.ts and the semantic projection signature
(projectJavaScriptSemanticFileSteps(file, ir, graphByteBudget, nodeBudget, callPaths)).
Splitting them would need a second, conflicting version of those files.

Breaking changes

None intended. Output additions only: new optional/added fields (electron_identity,
resolution_basis, guard_alternatives, linked_operation, url_class, host,
property_path, web_contents_views, webview_attachments,
content_security_policies, loader fields on native bindings) and summary counters.
One behaviour change consumers may notice: values that were reported as dynamic
(for example !0, "a" + "b") are now derived, with the value and the source
expression.

Verification

On this branch (A + this PR), tree identical to the integration branch minus the
jsbeautify PR:

  • npm run check — pass.
  • npm run test:changed -- --base origin/main — 109 files, 2005 passed, 3 skipped.
  • npm run test:focused on 60 javascript/electron boundary and acceptance files —
    453 tests passed.
  • npx tsc --noEmit passes on every commit.
  • Real CLI run, Grok Bot app.asar, default heap (3:14 wall, 1.33 GB peak RSS,
    579/579 parsed). summary compared with origin/main b3dec00:
origin/main this branch
browser_windows / web_contents_views / webview_attach_handlers 3 / – / – 5 / 1 / 1
explicit_web_preferences 7 13
context_bridge_apis / exposed_api_members 6 / 95 7 / 381
IPC operations / literal channels 15 / 2 673 / 355
main handlers / renderer transmissions 6 / 5 319 / 312
paired / guarded transmissions 0 / – 24 / 279
native bindings (resolved) 2 (2) 4 (4)
inferred API identity findings – 15
CSP policies / concerns – 5 / 8
  • dune-rpc: handlers recovered for every method the report counted by hand —
    main 281/281, desktop-mount 10/10, sand-dev 10/10, box-vnc 2/2, plus the
    probes (REA 6.3.0 and origin/main: 0). 278/281 renderer main-edge invokes are
    recovered as guarded (behind the sand:main-edge-served gate), 20 desktop-mount
    invokes pair.
  • The WebAuthn consent window (main-app.cjs:369:806, basis: wrapper-parameter),
    a dialog parent window found through local alternatives, and the avatar
    WebContentsView (main-app.cjs:386:27105) are reported; will-attach-webview
    is reported with its forced nodeIntegration/contextIsolation/sandbox and
    preload writes.
  • The desktop bridge object lp now lists its members (381 members over 7
    bridge APIs, vs 95 on origin/main).
  • Data endpoints: all 9 hosts the report found only by manual grep (§2.6:
    api.x.ai, api.x.com, mcp.money.x.com, connectors-gateway.grok.com,
    downloads.cursor.com, prod.authentication.cursor.sh, api2.cursor.sh,
    grok.com, cursor.com) are reported; origin/main and the budget PR alone
    report 0 of them.
  • The 5 CSPs include the renderer index.html and panel panel.html meta
    policies from §2.7 with their img-src https:/connect-src ws:/
    style-src 'unsafe-inline' concerns.

Limitations

  • Everything is static inference from inert syntax: runtime registration,
    reachability and guard outcomes are not proven; inferred identities are marked
    as inferences.
  • Wrapper-parameter identity looks at same-file call sites only; one wrapper level
    for identity, eight for channel substitution.
  • Global-symbol linking assumes the two sources share one realm.
  • Folding assumes unmodified String.fromCharCode and Array.prototype.join.
  • Data-endpoint host classification is syntactic; dotted identifiers under a real
    TLD can still match.
  • The REA_REPORT !0/!1 fix is delivered by the constant lattice
    (status: "derived", expression !0), not by a literal special case.

…nsion

The parent charged 8x transfer bytes, 6x static checkpoints and an 8x
application-projection forecast against half of its heap. On the Grok Bot
app.asar at the default 4 GB heap this rejected application relationships
for 492 of 579 sources and semantic analysis for 491, although the same
run with a 28 GB heap peaked at 1.5 GB RSS.

Measured retained heap is 1.23x-1.42x of the parsed JSON, and the summed
application forecast was 9.7x the retained application graph. Use those
measurements; the halved heap budget still covers sealing copies. The
default-heap run now projects every source (3:07, 1.55 GB peak RSS).
Replace the default 100,000-node graph ceiling and 20,000-node file
ceiling with a byte budget derived from resources. One application
Evidence may occupy the parent heap divided by twelve (at most one V8
string): measured consumers peak at about six times the Evidence bytes,
and compare_application_versions holds two records. Each source is
offered the remaining budget in proportion to its share of unanalyzed
source bytes, capped by the parent's free result heap. Caller-selected
max_semantic_nodes and max_semantic_nodes_per_file still apply and close
admission the same way; omitted, only the byte budget bounds the graph.

Within a source, nodes are charged only when an admitted relation,
fingerprint or unknown frontier references them, and frontiers are offered
after every relation, so unknowns no longer flood the budget and a
truncated source keeps a connected, source-ordered prefix. Refused facts
are counted exactly.

The ceiling truncated the Grok Bot app.asar to its first 58 of 579
sources without naming the omitted ones. Every source is now projected
and reported in semantic_graph.coverage.files with its retained bytes,
exact omitted node/relation/fingerprint counts and unknown totals by
family and reason. The per-source byte budget derives from the analyzing
process's V8 heap, so graph_byte_budget is recorded only for truncated
sources; complete sources keep identical Evidence identities across
hosts with different heaps.

BREAKING CHANGE: semantic_graph.coverage.families[].unknown_ids is
replaced by retained_unknowns and omitted_unknowns, coverage.files is
added, the default semantic_graph_node_ceiling and
semantic_graph_file_node_ceiling limits are removed (they appear only
when the caller selects a node capacity), and truncation by the byte
budget reports javascript_analysis_evidence_budget_bytes.
Grok Bot's main-app.cjs failed semantic analysis with "Maximum call stack
size exceeded". Its undici classes read `this[symbol].name` in about
twenty getters. The unknown key selected every getter again on each hop,
so class lookups enumerated every ordering of getter names and spread the
resulting arrays into push().

After one unknown-key hop, escape every field value and getter result of
the receiver class instead of enumerating paths; an escape covers effects
at any depth, so writes through those getters stay conservative.
Duplicate references are dropped and results are appended without
spreads. main-app.cjs now completes in 7 s under a 1 GiB heap.
…CP boundary

The resource boundary test relied on the former 8x application-projection forecast. Twelve thousand findings still exceed a 512 MiB parent's result budget under the measured forecast.
…ontiers

Add semantic_files and semantic_unknowns page collections for JavaScript
application Evidence. semantic_files returns each source's semantic byte
budget, retained bytes, exact omitted counts and unknown totals by family
and reason; semantic_unknowns returns retained frontiers ordered by
source, family and reason. The summary reports source counts by status
instead of repeating every file, and its unknowns name both pages.

Document the serialized-byte budget and its coverage, and verify the
budget, exact counts and both pages through the public CLI.
The semantic value lattice now folds void, typeof, ~, arithmetic, comparison, shift and bitwise operators over exact primitive operands, plus Array.prototype.join over exact arrays and String.fromCharCode. Operands may be undefined, NaN, infinite or negative zero while folding; only JSON-representable results become literals, so void 0 and 1/0 alone stay unknown with an explicit reason.
…int findings

Static findings now read values through the semantic value lattice instead of literal syntax alone. Electron webPreferences, contextBridge world IDs and sender checks gain a derived status that keeps the source expression; IPC channels and contextBridge keys built from constants carry both the exact value and the expression, and derived channels pair with handlers. Network endpoint arguments built by concatenation, templates, join or fromCharCode become exact values with their expression and a derived-value limitation.

When member-mutation recovery exhausts a resource limit, the file keeps literal-only values and records why.
…efaults

Request operations and configuration defaults read exact values through the semantic value lattice, so concatenated endpoints and folded defaults are complete. A literal null default is now an exact value rather than a partial one. The literal-only default reader is removed.
Static analysis now records URL-like strings that no recognized call site or route consumes as data endpoints: string literals and object keys, template text, and maximal folded expressions. Every endpoint carries a syntactic url_class (http, websocket, host, path, data, blob, file) and host; data endpoints also carry the property path from their nearest named container and are projected as exact module containment. Values already reported at a network call or route are not repeated.

Host-only values must be lowercase DNS names under a two-letter IANA country code or a common generic top-level domain, which excludes dotted attribute keys such as k8s.pod.name or team.billing.read.

Endpoint projection moves to its own module, and endpointArgument takes the call facts as one value.
Static analysis records whether constant folding was available. When member-write recovery exceeds a resource limit, the application analysis now lists the file and reason among its limitations instead of leaving the gap in per-file static limitations that the graph does not project.
Callee roots that are parameters (or destructured parameter keys) of a named function now resolve when its same-file direct call sites pass a proven Electron export, an object-literal member holding one, or a ??/||/&&/conditional branch of those. Every window, contextBridge, IPC and utility finding carries electron_identity with the basis, wrapper, parameter, call-site count, proven argument locations and unresolved argument count. Relationships that depend on an inferred identity are inferences with medium or low confidence.
contextBridge exposure arguments that are identifiers bound to one stable object-literal initializer now report their members (api_status object-binding), following member values that are such bindings. Keys from conditional object spreads with known branches are reported as conditional_members. Visible member writes to a bound object add an unknown member.
…bview hardening

BrowserView and WebContentsView constructions are reported with the BrowserWindow surface (api field) and project to web-contents-view graph nodes. will-attach-webview listeners record writes and deletions through their webPreferences and params parameters and the last static preload path, which becomes an electron-preload role. The summary adds web_contents_views, webview_attach_handlers and wrapper_inferred_api_findings; Electron finding counts now share one helper.
A callee root bound once to a ??, ||, &&, conditional or object literal of Electron values, such as options.electron ?? { BrowserWindow: electron.BrowserWindow }, now resolves when its proving branches agree. electron_identity records basis local-alternatives with the proving value locations and the unresolved alternatives. The summary count is renamed to inferred_api_identity_findings and covers every inferred basis.
…bindings, node-gyp-build and process.dlopen

Calls to a module.createRequire function, the bindings and node-gyp-build loaders, and process.dlopen are classified directly, through one stable alias, or through a parameter default. Loader bindings record loader, loader_basis and specifier_status. bindings and node-gyp-build add-ons are resolved to the single .node file in the build or prebuild trees of the nearest package root, with the candidates listed and low confidence. Summary and graph now share one native resolver.
… sources

Policies are recovered from <meta http-equiv> elements in HTML files, from Content-Security-Policy header properties and assignments such as onHeadersReceived responseHeaders, from [...].join directive lists, and from string or template literals including meta markup. Each policy lists its directives and concerns (wildcard and network-scheme sources, data:/blob: script sources, unsafe-inline, unsafe-eval, missing script or plugin fallbacks). Runtime parts are kept as a placeholder and not judged. The summary adds content_security_policies and content_security_policy_concerns.
A loader parameter whose default is an identifier bound to a createRequire result, as in function load(requireAddon = createdRequire), now resolves through that binding, so its calls become require references or native bindings.
…d operator folder

Move primitive operator, template, String.fromCharCode and
Array.prototype.join folding into javascriptSemanticOperators as
foldSemanticOperands, which reads every non-operator expression through
caller-supplied leaves. The constant lattice supplies its once-bound
binding leaves, so its values are unchanged.

`void` now folds to undefined without reading its argument, so
`"a" + void runtimeValue()` folds to "aundefined".
…or folder

Symbolic call-path substitution now reads literals with
readExactJavaScriptLiteral and folds operators, templates,
String.fromCharCode and Array.prototype.join through the constant
lattice's foldSemanticOperands, with operands read from its call-site
environment. Branch conditions on operands carry over to the result;
alternatives with different conditions mark it unresolved.

Electron identity for imports and unbound parameters now comes from the
shared identity index: an import keeps its module binding, and a
parameter that no call site on the path binds uses the wrapper-parameter
or local-alternatives fact, which substituted IPC and bridge findings
record as their electron_identity. The two parameter mechanisms stay
separate: the summary belongs to the identity index the substitution
reads and records proving argument locations that substituted values do
not carry.

Call arguments are read only for callees that consume them, so
unresolved reads inside calls of unrelated callees no longer mark a
file partial.
…s and linked sources

Wrapper substitution now starts from the outermost same-file callers of
wrappers that forward a computed channel to an IPC-named call, following
forwarded parameters and enclosing wrappers up to eight levels. The symbolic
engine folds templates and concatenation, iterates exact arrays in for...of
(Object.entries/keys/values, Array.prototype.map), keeps members written per
iterated key or by ordered direct writes, evaluates literal getters, reads an
absent key of a closed literal as undefined, binds destructured parameters
and defaults, and recognizes esbuild __commonJS and __toESM structurally.

Substituted values fold through the constant lattice's foldSemanticOperands.
An operand whose alternatives carry predicates is folded once per
alternative, so each result keeps its own predicates. An operand known
only to be an object compares exactly under strict equality with a
primitive and loose equality with null or undefined; every coercing
operator on it stays unknown. A non-index member of array syntax is
unknown without evaluating the elements. Call arguments stay lazy in the
symbolic engine and the wrapped call walker. analyzeAndProjectJavaScriptArtifactFiles
forwards each file's Electron call paths to the semantic projection, as
the worker already does.

A top-level globalThis[Symbol.for(key)] publication in another source of the
artifact is linked when it is the only publication of a key a source reads;
the worker receives candidate companion sources and parses them only when the
key is read. Linked steps carry source_path, and IPC operations found there
keep the local reaching call as location and the linked call as
linked_operation.

Guarded substituted IPC operations are reported with guard_alternatives;
conjunctions differing only by one complementary predicate of the same
activation merge, so operations reached on both branches are unconditional.
Unique matches involving a guarded operation are counted as
guarded_renderer_transmissions without a pairing edge. Handler bodies are
traced after all registrations as event-loop dispatches with fair budget
shares; promise fulfillment callbacks run under an explicit predicate.

On Grok Bot this recovers all four dune-rpc edges: main 281/281, desktop-mount
10/10, sand-dev 10/10 and box-vnc 2/2 handlers plus probes, 278/281
renderer main-edge invokes (guarded by the main-edge-served gate) and 20
paired desktop-mount invokes; IPC paired 2 -> 24.
@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 ⚠️ Failed 2026-10-12T07:53:01.713373Z 2c6bef6 PR opened
ℹ️ 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.

@dandgabr dandgabr left a comment

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.

Review suggestion

  • P2 — Bound global-symbol companion linking. globalSymbolRegistryCompanions() compares every keyed source with every other source, then JavaScriptAnalysisWorker.analyze() writes each matching companion’s full text again for every analyzed file. A crafted application with many files naming the same Symbol.for key causes quadratic comparisons and repeated disk I/O, potentially exhausting analysis time and temporary storage. Build a key-to-source index and cap total companion edges/bytes per artifact; report incomplete linking when that cap is reached.

@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: 0/5

[High impact] Refactors JavaScript analysis for Electron boundaries and constant folding.

The PR needs fixes before merging because it can report wrong IPC channels, collapse real listeners, and follow stale registry values.

Findings

  1. P1 Earlier calls get later values ▶
  2. P1 Loop listeners collapse ▶
  3. P1 Replaced registry values stay linked ▶
  4. P1 Local directories resolve elsewhere ▶
  5. P1 Unstarted generators invent IPC calls ▶
  6. P2 Known promise channels disappear ▶
  7. P2 Unknown policies raise definite warnings ▶
  8. P2 Skipped sources understate missing nodes ▶
Fix with agent prompt
### Issue 1
src/domain/javascript/javascriptSemanticAnalysis.ts:265
The new constant reader uses later initializers for earlier reads. For `ipcMain.handle("app:" + suffix, handler); var suffix = "open";`, JavaScript registers `app:undefined`, but the report derives `app:open`. That can pair a renderer call with the wrong handler.

Check whether the initializer has run at the read point before using it as an exact value.

### Issue 2
src/domain/javascript/electronWrappedCallPaths.ts:448-458
For ``function setup(names, ipc) { for (const name of names) ipc.on(`same`, () => electron.clipboard[name]()); } setup(["readText", "readHTML"], electron.ipcMain)``, both iterations have the same channel and source ranges, so this key merges them. The second iteration also skips `handlerBodies.push`, losing its captured `name`.

The report shows one handler and can call the channel match unique, although two listeners were registered. Preserve the loop activation in registration identity and trace each distinct handler closure.

### Issue 3
src/domain/javascript/javascriptGlobalSymbolRegistry.ts:37-43
A companion containing `globalThis[Symbol.for("api")] = first; 0, globalThis[Symbol.for("api")] = second;` contributes only `first`. The second statement is a sequence, so this loop ignores it. Reads in another file then follow `first` as the unique publication and can report its Electron calls instead of `second`'s.

Keep the narrow shape for selecting a publication, but reject the link when any other write or deletion can target the same slot.

### Issue 4
src/domain/javascript/javascriptStaticAnalysisHelpers.ts:190-195
The new directory reader treats a local parameter named `__dirname` as the source directory. In `function load(__dirname) { return require("node-gyp-build")(__dirname); } load("/opt/plugin")`, it records `"."` and searches beside the calling source. If that directory has one add-on, the report marks that unrelated file as resolved.

Check which declared variable the argument refers to before treating it as the source directory. Otherwise leave the directory unresolved.

### Issue 5
src/domain/javascript/electronWrappedCallPaths.ts:654-657
This walk bypasses the generator check in `#invoke` and enters every function body directly. For `function* gen(name) { electron.ipcRenderer.invoke("app:" + name); } gen("open")`, it now reports an exact `app:open` operation even though the generator is never advanced. The new folding turns a previously unresolved channel into a pairing candidate.

Apply the generator check to body tracing too. Only trace a generator body when supported iteration actually reaches it.

### Issue 6
src/domain/javascript/electronWrappedCallPaths.ts:640
The new `.then` walk discards known promise values. Inside an exposed method, `Promise.resolve("open").then(name => ipcRenderer.invoke("app:" + name))` passes an unknown value to the callback even though the promise stores `"open"`. The analyzer therefore misses `app:open`.

Pass the known final fulfillment to the callback, and keep it unknown only when that value cannot be established.

### Issue 7
src/domain/javascript/contentSecurityPolicy.ts:118-120
For a declared header `` `${extra}; object-src 'none'` ``, the runtime placeholder becomes a directive name with no sources. This check only looks at sources, so it treats the policy as fully static and reports unrestricted scripts-even when `extra` supplies `script-src 'none'`.

Check names as well as sources, or use `dynamic_parts`, before judging missing directives. This avoids sending reviewers after a restriction that may already exist.

### Issue 8
src/application/javascript/JavaScriptSemanticGraphConstruction.ts:undefined-307
When the module root cannot fit, `projectFileSteps` returns before counting the source's remaining nodes. This field then reports only the rejected root. A source offered zero remaining capacity can therefore show `omitted_nodes: 1` regardless of its size.

Count the skipped nodes, or report the count as unknown instead of exact, so users inspecting coverage can judge how much work is missing.

---

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

Summary

The PR adds shared constant folding and recovers more Electron calls through wrappers and linked sources.

  • Static findings now include folded values and URL-like data.
  • Electron findings now follow wrapped APIs and report more boundaries.
  • Semantic graph reports when a source reaches its fact budget.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Inert source text] --> B[Lexical bindings and writes]
  B --> C[Shared constant folder]
  B --> D[Wrapper substitutions]
  E[Companion sources] --> D
  C --> F[Static findings]
  D --> F
  F --> G[Application graph]
  D --> H[Bounded semantic projection]
  H --> I[Verified worker transfer]
  I --> J[Semantic graph]
Loading

Reviews (9) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

`await` read a promise's fulfillment only when an async call recorded one.
`Promise.resolve(x)` recorded no value, so `await Promise.resolve(false)`
returned the promise object. A promise object is truthy, so an `if` that
never runs was treated as taken and its IPC call was reported.

`Promise.resolve` now records a literal argument as its fulfillment and
returns a promise argument unchanged. `await` flattens nested promises to
their final value. A promise whose fulfillment is unknown, and an object
that has or may have a `then` member, now read as unknown instead of as a
truthy object. The resolver owns this step, because the thenable check
needs its member facts.
resolveElectronNativeAddon treated node-gyp-build like bindings: it searched
the nearest package root of the calling file and ignored the loader's
directory argument. For `node-gyp-build(path.join(__dirname, "plugin"))` it
could resolve an unrelated add-on in the caller's build/Release tree and miss
plugin/build/Release.

The classifier now records the node-gyp-build directory when it is __dirname
or a path built from it, relative to the source file's directory. Resolution
searches that directory's build and prebuild trees
(`resolution_basis: loader-directory`). A process-relative, dynamic or
out-of-artifact directory stays unresolved
(`loader-directory-unavailable`). bindings keeps its package-root search.
resolveElectronApiObjects flagged member writes only on the exposed
binding itself. With `const alias = api; alias.tools = {}` the exposed `api`
still listed `tools.copy` with no unknown member. The later bridge pass keeps
that object-binding finding, so the removed method was reported without any
warning.

The member-write flag now covers the binding's alias component from
javascriptBindingAliasComponents, the shared owner the symbolic resolver
already uses. A write through an alias now adds the same unknown member as a
direct write. Exact member lists are still not rebuilt from writes.
@coleleavitt

Copy link
Copy Markdown
Author

Changes pushed to this branch (fast-forward b4acf1e..e3570c2):

  • 005f150: merges origin/main. No conflicts.
  • d6dd3d1: await reads only known promise fulfillments. Promise.resolve keeps its value, nested promises flatten to their final value, and an unknown fulfillment or a possible thenable is unknown.
  • 22ad26e: node-gyp-build searches the __dirname-based directory it receives. Otherwise the binding stays unresolved.
  • e3570c2: member writes through a direct reference alias now mark a bound contextBridge object as incomplete.

Checks run: npx tsc --noEmit -p ., oxfmt --check ., and oxlint on the touched files (no errors); npm run test:changed -- --base origin/main (2488 passed; the 1 failure, analysisView "message-count cutoff", also fails on origin/main); and npm run test:focused on the 18 Electron/JavaScript acceptance and boundary files (90/90).

Comment on lines +448 to +458
const key = JSON.stringify([
finding.side,
finding.operation,
channel,
location,
descriptor.mode === "send" || descriptor.mode === "invoke"
? null
: (invocationLocation ?? null),
finding.handler_kind,
finding.handler_location,
finding.linked_operation ?? null,

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 Loop listeners collapse

For function setup(names, ipc) { for (const name of names) ipc.on(`same`, () => electron.clipboard[name]()); } setup(["readText", "readHTML"], electron.ipcMain), both iterations have the same channel and source ranges, so this key merges them. The second iteration also skips handlerBodies.push, losing its captured name.

The report shows one handler and can call the channel match unique, although two listeners were registered. Preserve the loop activation in registration identity and trace each distinct handler closure.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/electronWrappedCallPaths.ts
Line: 448-458

Comment:
**Loop listeners collapse**

For ``function setup(names, ipc) { for (const name of names) ipc.on(`same`, () => electron.clipboard[name]()); } setup(["readText", "readHTML"], electron.ipcMain)``, both iterations have the same channel and source ranges, so this key merges them. The second iteration also skips `handlerBodies.push`, losing its captured `name`.

The report shows one handler and can call the channel match unique, although two listeners were registered. Preserve the loop activation in registration identity and trace each distinct handler closure.

---

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

Comment on lines +37 to +43
for (const statement of program.body) {
if (!t.isExpressionStatement(statement)) continue;
const expression = statement.expression;
if (!t.isAssignmentExpression(expression, { operator: "=" })) continue;
const key = globalSymbolRegistryKey(expression.left, state);
if (key === undefined) continue;
published.set(key, published.has(key) ? null : expression.right);

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 Replaced registry values stay linked

A companion containing globalThis[Symbol.for("api")] = first; 0, globalThis[Symbol.for("api")] = second; contributes only first. The second statement is a sequence, so this loop ignores it. Reads in another file then follow first as the unique publication and can report its Electron calls instead of second's.

Keep the narrow shape for selecting a publication, but reject the link when any other write or deletion can target the same slot.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptGlobalSymbolRegistry.ts
Line: 37-43

Comment:
**Replaced registry values stay linked**

A companion containing `globalThis[Symbol.for("api")] = first; 0, globalThis[Symbol.for("api")] = second;` contributes only `first`. The second statement is a sequence, so this loop ignores it. Reads in another file then follow `first` as the unique publication and can report its Electron calls instead of `second`'s.

Keep the narrow shape for selecting a publication, but reject the link when any other write or deletion can target the same slot.

---

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

Comment on lines +190 to +195
export const sourceDirectoryPath = (node: t.Node): string | undefined =>
isDirectoryIdentity(node)
? "."
: isFilesystemPathExpression(node)
? staticPath(node)
: undefined;

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 Local directories resolve elsewhere

The new directory reader treats a local parameter named __dirname as the source directory. In function load(__dirname) { return require("node-gyp-build")(__dirname); } load("/opt/plugin"), it records "." and searches beside the calling source. If that directory has one add-on, the report marks that unrelated file as resolved.

Check which declared variable the argument refers to before treating it as the source directory. Otherwise leave the directory unresolved.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptStaticAnalysisHelpers.ts
Line: 190-195

Comment:
**Local directories resolve elsewhere**

The new directory reader treats a local parameter named `__dirname` as the source directory. In `function load(__dirname) { return require("node-gyp-build")(__dirname); } load("/opt/plugin")`, it records `"."` and searches beside the calling source. If that directory has one add-on, the report marks that unrelated file as resolved.

Check which declared variable the argument refers to before treating it as the source directory. Otherwise leave the directory unresolved.

---

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

Comment on lines 654 to +657
if (callee.kind === "function") {
functionBody(
callee,
args,
callArguments(),

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 Unstarted generators invent IPC calls

This walk bypasses the generator check in #invoke and enters every function body directly. For function* gen(name) { electron.ipcRenderer.invoke("app:" + name); } gen("open"), it now reports an exact app:open operation even though the generator is never advanced. The new folding turns a previously unresolved channel into a pairing candidate.

Apply the generator check to body tracing too. Only trace a generator body when supported iteration actually reaches it.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/electronWrappedCallPaths.ts
Line: 654-657

Comment:
**Unstarted generators invent IPC calls**

This walk bypasses the generator check in `#invoke` and enters every function body directly. For `function* gen(name) { electron.ipcRenderer.invoke("app:" + name); } gen("open")`, it now reports an exact `app:open` operation even though the generator is never advanced. The new folding turns a previously unresolved channel into a pairing candidate.

Apply the generator check to body tracing too. Only trace a generator body when supported iteration actually reaches it.

---

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

Comment on lines +118 to +120
const dynamic = effective.some(({ sources }) =>
sources.some((source) => source.includes(DYNAMIC_SOURCE)),
);

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.

P2 Unknown policies raise definite warnings

For a declared header `${extra}; object-src 'none'`, the runtime placeholder becomes a directive name with no sources. This check only looks at sources, so it treats the policy as fully static and reports unrestricted scripts—even when extra supplies script-src 'none'.

Check names as well as sources, or use dynamic_parts, before judging missing directives. This avoids sending reviewers after a restriction that may already exist.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/contentSecurityPolicy.ts
Line: 118-120

Comment:
**Unknown policies raise definite warnings**

For a declared header `` `${extra}; object-src 'none'` ``, the runtime placeholder becomes a directive name with no sources. This check only looks at sources, so it treats the policy as fully static and reports unrestricted scripts—even when `extra` supplies `script-src 'none'`.

Check names as well as sources, or use `dynamic_parts`, before judging missing directives. This avoids sending reviewers after a restriction that may already exist.

---

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

// keeps identical complete results identical across hosts.
graph_byte_budget: truncated ? budget.limit : null,
retained_graph_bytes: budget.used,
omitted_nodes: budget.omittedNodes,

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.

P2 Skipped sources understate missing nodes

When the module root cannot fit, projectFileSteps returns before counting the source's remaining nodes. This field then reports only the rejected root. A source offered zero remaining capacity can therefore show omitted_nodes: 1 regardless of its size.

Count the skipped nodes, or report the count as unknown instead of exact, so users inspecting coverage can judge how much work is missing.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/javascript/JavaScriptSemanticGraphConstruction.ts
Line: 307

Comment:
**Skipped sources understate missing nodes**

When the module root cannot fit, `projectFileSteps` returns before counting the source's remaining nodes. This field then reports only the rejected root. A source offered zero remaining capacity can therefore show `omitted_nodes: 1` regardless of its size.

Count the skipped nodes, or report the count as unknown instead of exact, so users inspecting coverage can judge how much work is missing.

---

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

}
return {
status: "available",
evaluate: (node) => evaluateSemanticExpression(node, state),

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 Earlier calls get later values

The new constant reader uses later initializers for earlier reads. For ipcMain.handle("app:" + suffix, handler); var suffix = "open";, JavaScript registers app:undefined, but the report derives app:open. That can pair a renderer call with the wrong handler.

Check whether the initializer has run at the read point before using it as an exact value.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticAnalysis.ts
Line: 265

Comment:
**Earlier calls get later values**

The new constant reader uses later initializers for earlier reads. For `ipcMain.handle("app:" + suffix, handler); var suffix = "open";`, JavaScript registers `app:undefined`, but the report derives `app:open`. That can pair a renderer call with the wrong handler.

Check whether the initializer has run at the read point before using it as an exact value.

---

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

if (fulfilled !== null)
functionBody(
fn,
[symbolicUnknown("fulfillment 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.

P2 Known promise channels disappear

The new .then walk discards known promise values. Inside an exposed method, Promise.resolve("open").then(name => ipcRenderer.invoke("app:" + name)) passes an unknown value to the callback even though the promise stores "open". The analyzer therefore misses app:open.

Pass the known final fulfillment to the callback, and keep it unknown only when that value cannot be established.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/electronWrappedCallPaths.ts
Line: 640

Comment:
**Known promise channels disappear**

The new `.then` walk discards known promise values. Inside an exposed method, `Promise.resolve("open").then(name => ipcRenderer.invoke("app:" + name))` passes an unknown value to the callback even though the promise stores `"open"`. The analyzer therefore misses `app:open`.

Pass the known final fulfillment to the callback, and keep it unknown only when that value cannot be established.

---

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

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The new analysis works on Linux with Node 24 and 26. The PR's 36 test files pass, except one flaky failure in one Node 24 run, and a test app shows the new findings. One review bug from Greptile still reproduces on this head, and the head now conflicts with main.

I tested head 84fe44e as pushed. GitHub says it conflicts with main 4692bb3 (#3801). Main has moved 327 commits since the PR's base aa6f74a (#2096), and 52 of the PR's 124 changed files were also changed on main. This head includes the commits of #2092.

Results

Check Node 24.18.0 Node 26.11.1
PR's 36 test files, head (565 tests) pass on 1 of 2 full runs pass
PR's 3 CLI test files, main (6 tests) 6 fail not run
Test app, head vs main differs, see below same output as Node 24

One test failed in the first full run on head. It was javascriptSemanticBudgetCli, and a CLI call in it exited with code 1. The test passed alone and in a second full run. I did not find the cause.

Test app, written from the PR body. It holds !0 options and a template channel. It passes BrowserWindow through a wrapper. It has a contextBridge object, a WebContentsView and a will-attach-webview handler. It also has a CSP meta tag and a data table with a host. Main 4692bb3 (#3801) and the PR base aa6f74a (#2096) gave the same counts.

Summary counter Main Head
browser windows / web contents views 1 / none 2 / 1
explicit web preferences 4 8
exposed bridge members 4 6
IPC operations / literal channels 5 / 1 8 / 4
main handlers 2 5
renderer calls paired with a handler 0 3
CSP policies / concerns none 2 / 5
inferred API identity findings none 2
data endpoints none 2

On main, !0 was reported as dynamic. On head, it is derived: true. Node 24 and Node 26 gave byte-identical output on both trees.

Open review bug, reproduced. Greptile's first finding on this head ("Earlier calls get later values") is real. With ipcMain.handle("app:" + suffix, ...) followed by var suffix = "open", JavaScript registers app:undefined. Head reports app:open and pairs it with a renderer call. Main leaves that call unpaired.

Not run

  • The Grok Bot app from the PR body. It is closed source and not on this box.
  • Node 22.
  • Time and memory, before and after.
  • The other open Greptile findings, one by one.
  • Head merged onto current main.
  • Windows and macOS.

Thanks, Cole Leavitt, for the work and the quick fixes.

Test setup
Commands
npm ci && npm run build && npm run test:prepare
node scripts/run-development-tests.mjs focused <the 36 test files the PR adds or changes>
node scripts/rea.mjs analyze-javascript-application <test app> --format json

Each run sat under nice -n 19 and systemd-run --user --scope -p MemoryMax=6G. The three CLI test files for the main row were copied from the head into the main tree, because main does not have them.

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

@morluto morluto added the provider: electron Analysis provider / engine: electron label Nov 23, 2026
@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@coleleavitt thanks for the PR — there are 8 open review threads here:

Could you address or reply to these? Once they're resolved and CI is green we can take another look.
cc @gensokyo-dev @dandgabr

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@coleleavitt also, this branch has merge conflicts with main — please resolve those along with the open threads.

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

area: domain Domain logic, errors, and pure functions area: evidence Evidence, artifacts, and reconstruction area: server Server layer and tool wiring enhancement New feature or request P2: medium Medium priority issue provider: electron Analysis provider / engine: electron

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants