Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
107 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
75978e2
fix: recognize Lua function nodes in complexity metrics computation (…
carlos-alm Jul 6, 2026
af17b6d
fix: scope global call-resolution fallback to same-language candidate…
carlos-alm Jul 6, 2026
dd447bc
fix: credit instanceof ClassName checks as exports consumers
carlos-alm Jul 6, 2026
a79a8a1
fix: update automated-review workflow to use current claude-code-acti…
carlos-alm Jul 6, 2026
d84f6b5
refactor: widen outputResult signature, remove redundant casts at cal…
carlos-alm Jul 6, 2026
e7a2255
fix: port Leiden algorithm to native Rust for cross-engine community-…
carlos-alm Jul 7, 2026
b54972a
feat: detect exported-symbol loss from full file deletion in checkNoS…
carlos-alm Jul 7, 2026
1821a8b
fix(complexity): scope summary stats to file/target/kind filters
carlos-alm Jul 7, 2026
d45aba7
fix(extractors): label property_signature interface/type members as k…
carlos-alm Jul 7, 2026
69d8a6f
fix(roles): exclude genuine class/struct properties from dead-role cl…
carlos-alm Jul 7, 2026
db08219
fix(resolver): scope extends/implements edges to same-file/import/lan…
carlos-alm Jul 7, 2026
79cd761
fix: track inline per-specifier type-only import modifier
carlos-alm Jul 7, 2026
cbfa954
fix(native): widen NativeRepository file filters to accept string[]
carlos-alm Jul 7, 2026
c0e7eae
fix(native): remove unused source param from get_first_call_arg
carlos-alm Jul 7, 2026
2dabe21
fix(extractors): align native/WASM definitions order for object-liter…
carlos-alm Jul 7, 2026
b1eb9af
fix(extractors): capture top-level const definitions regardless of in…
carlos-alm Jul 7, 2026
4a1e279
fix: exclude PHP scalar type-hint/cast keywords from ast --kind string
carlos-alm Jul 7, 2026
40b5e24
fix: track barrel re-export renames (export { X as Y } from ...)
carlos-alm Jul 7, 2026
1506896
fix: record local alias for dynamic import() destructuring renames
carlos-alm Jul 7, 2026
2dfd6bc
fix: resolve renamed-import receiver calls in qualified-method lookup
carlos-alm Jul 7, 2026
ccea0cb
fix(native): propagate edge/node write failures out of run_pipeline
carlos-alm Jul 7, 2026
93ccfa3
fix(exports): discriminate file-level from symbol-level consumer entries
carlos-alm Jul 7, 2026
e105c26
docs: refresh CONTRIBUTING.md for TypeScript architecture and current…
carlos-alm Jul 7, 2026
5d99bf0
fix(exports): credit plain imports of TypeScript interfaces/type aliases
carlos-alm Jul 7, 2026
e0ab9dc
fix(hooks): point update-graph.sh fallback build path at dist/cli.js
carlos-alm Jul 7, 2026
730b49b
fix(hooks): resolve track-edits.sh's PROJECT_DIR from the edited file…
carlos-alm Jul 7, 2026
0d7e8e6
fix: capture removed files' cross-directory neighbors before purge
carlos-alm Jul 7, 2026
c5b9a34
docs: fix stale codegraph check flag names in recommended-practices.md
carlos-alm Jul 7, 2026
2de6550
fix(cycles): classify cycles whose only closing edges are speculative
carlos-alm Jul 7, 2026
e5fe754
fix(resolver): recognize identifier args to user-defined higher-order…
carlos-alm Jul 8, 2026
4eef28e
fix(native): scope barrel-only import skipping to transient barrel re…
carlos-alm Jul 8, 2026
4090355
refactor(ast-analysis): extract shared CFG/complexity result-merging …
carlos-alm Jul 8, 2026
bf8e969
fix(incremental): port CHA/RTA dispatch, points-to, and dynamic-sink …
carlos-alm Jul 8, 2026
51b9e23
fix(config): derive ENV_LLM_KEYS from ENV_LLM_MAP to prevent drift
carlos-alm Jul 8, 2026
a62bab7
fix(resolver): resolveByGlobal picks the single best match, not every…
carlos-alm Jul 8, 2026
8f52d28
fix(embed): resolve default DB path from positional dir, not cwd
carlos-alm Jul 8, 2026
59220a5
refactor(leiden): extract makePartition's inline getters to cut cyclo…
carlos-alm Jul 8, 2026
2e1aa11
docs: regenerate stale audit/diff-impact example output blocks
carlos-alm Jul 8, 2026
3d436ca
fix(rust): resolve self.field, unit-struct, and constructor-typed locals
carlos-alm Jul 8, 2026
668451c
docs: add missing titan-grind mirror to claude-code-skills examples
carlos-alm Jul 8, 2026
4bccd4b
fix(scripts): migrate ts-resolve-loader.js off deprecated module.regi…
carlos-alm Jul 8, 2026
25ba42f
fix(native): recover renamed import names in the FFI hybrid import-ed…
carlos-alm Jul 8, 2026
431c0e5
fix: reconnect reverse-dep edges correctly when a sibling group's siz…
carlos-alm Jul 8, 2026
ab6a685
fix: derive loadConfig() rootDir from --db path in read-only query fu…
carlos-alm Jul 8, 2026
17e265b
fix(native): thread config.db.busyTimeoutMs into NativeDatabase open …
carlos-alm Jul 8, 2026
fdedff8
fix(extractors): unwrap computed string-literal keys in typeMap/proto…
carlos-alm Jul 8, 2026
6ef1731
fix(native): add Object.defineProperty accessor dispatch post-pass to…
carlos-alm Jul 8, 2026
afca17f
fix(resolver): kind-filter same-file bare-name lookup for receiver-be…
carlos-alm Jul 8, 2026
801d290
fix(resolver): attribute new ClassName() calls to the constructor method
carlos-alm Jul 8, 2026
a45e74d
fix(extractors): attribute same-file ES6 getter/setter property reads…
carlos-alm Jul 8, 2026
453a768
fix(resolver): require invocation evidence for object-literal value-r…
carlos-alm Jul 8, 2026
554efbf
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 11, 2026
ef6492c
fix: correct inaccurate median fan-in/out claim in collectInvokedProp…
carlos-alm Jul 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 123 additions & 2 deletions crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,18 @@ struct EdgeContext<'a> {
nodes_by_file: HashMap<&'a str, Vec<&'a NodeInfo>>,
builtin_set: HashSet<&'a str>,
receiver_kinds: HashSet<&'a str>,
/// Property/method names ever invoked via member-call syntax
/// (`x.name(...)`) across every file in this build pass — see
/// `collect_invoked_property_names` for the #1895 liveness rationale.
invoked_property_names: HashSet<&'a str>,
}

impl<'a> EdgeContext<'a> {
fn new(all_nodes: &'a [NodeInfo], builtin_receivers: &'a [String]) -> Self {
fn new(
all_nodes: &'a [NodeInfo],
builtin_receivers: &'a [String],
files: &'a [FileEdgeInput],
) -> Self {
let mut nodes_by_name: HashMap<&str, Vec<&NodeInfo>> = HashMap::new();
let mut nodes_by_name_and_file: HashMap<(&str, &str), Vec<&NodeInfo>> = HashMap::new();
let mut nodes_by_file: HashMap<&str, Vec<&NodeInfo>> = HashMap::new();
Expand All @@ -177,8 +185,43 @@ impl<'a> EdgeContext<'a> {
nodes_by_file,
builtin_set,
receiver_kinds,
invoked_property_names: collect_invoked_property_names(files),
}
}
}

/// Collect the set of property/method names ever invoked via member-call
/// syntax (`x.name(...)`) across every file currently being processed —
/// regardless of whether the receiver `x` itself resolves to anything.
///
/// Used as the "one hop further" liveness check for object-literal-property
/// value-refs (#1895): a function referenced as `{ resolve: someFn }` should
/// only be credited with a `calls` edge from that reference when something,
/// somewhere, actually invokes a `.resolve(...)`-shaped call — otherwise the
/// property is wired up but never read, and `someFn` is genuinely dead.
///
/// Scope matches whatever `files` the caller passes to `build_call_edges`:
/// the full codebase for a full build, or just the changed file(s) on an
/// incremental one. The incremental case is a narrower, same-build-pass view
/// (a cross-file consumer added in an untouched file won't be seen until the
/// next full rebuild) — the same scoping trade-off already accepted
/// elsewhere in this codebase's incremental classification
/// (`has_active_file_siblings` and exported-via-reexport both recompute from
/// the affected file set only, not the whole graph, in
/// `graph/classifiers/roles.rs`'s incremental path — median fan-in/out is a
/// separate case, deliberately kept as a whole-graph statistic even on the
/// incremental path, for classification-threshold consistency). Mirrors
/// `collectInvokedPropertyNames` in `src/domain/graph/builder/call-resolver.ts`.
fn collect_invoked_property_names(files: &[FileEdgeInput]) -> HashSet<&str> {
let mut names = HashSet::new();
for file in files {
for call in &file.calls {
if call.receiver.is_some() {
names.insert(call.name.as_str());
}
}
}
names
}

// ── Phase 8.3: points-to analysis ─────────────────────────────────────────
Expand Down Expand Up @@ -467,7 +510,7 @@ pub fn build_call_edges(
builtin_receivers: Vec<String>,
max_iterations: u32,
) -> Vec<ComputedEdge> {
let ctx = EdgeContext::new(&all_nodes, &builtin_receivers);
let ctx = EdgeContext::new(&all_nodes, &builtin_receivers, &files);
let mut edges = Vec::new();

for file_input in &files {
Expand Down Expand Up @@ -800,6 +843,17 @@ fn process_file<'a>(
// resolveFallbackTargets (stages/build-edges.ts).
if call.dynamic_kind.as_deref() == Some("value-ref") {
targets.retain(|t| t.kind == "function" || t.kind == "method" || t.kind == "class");
// #1895: object-literal-property value-refs (key_expr set — see
// handle_object_literal_pair_value_ref / shorthand handler)
// additionally require independent evidence that the property is
// actually invoked somewhere (`x.key_expr(...)`) — merely being
// wired into an object literal is not liveness. instanceof/Lua
// value-refs never set key_expr, so they are unaffected.
if let Some(key_expr) = call.key_expr.as_deref() {
if !ctx.invoked_property_names.contains(key_expr) {
targets.clear();
}
}
}
sort_targets_by_confidence(&mut targets, fc.rel_path, imported_from);
emit_call_edges(&targets, caller_id, is_dynamic, fc.rel_path, imported_from, &mut seen_edges, &mut pts_edge_map, edges);
Expand Down Expand Up @@ -1653,6 +1707,7 @@ fn emit_hierarchy_edges(
}
}


// ── Import edges (native) ──────────────────────────────────────────────

#[napi(object)]
Expand Down Expand Up @@ -2989,6 +3044,72 @@ mod call_edge_tests {
assert_eq!(re.target_id, 2, "receiver edge target should be Calculator (id=2)");
}

/// Issue #1895: an object-literal-property value-ref call whose property
/// key (`key_expr`) is never independently confirmed to be invoked
/// anywhere (`x.resolve(...)`) must NOT produce a `calls` edge — merely
/// being wired into the object literal is not liveness. A sibling
/// property whose key IS invoked elsewhere (`table.reject(...)`) keeps
/// its edge.
#[test]
fn value_ref_edge_requires_key_invoked_elsewhere() {
let all_nodes = vec![
node(1, "makeTable", "function", "factory.js", 1),
node(2, "neverRead", "function", "factory.js", 2),
node(3, "isRead", "function", "factory.js", 3),
node(4, "run", "function", "consumer.js", 1),
];

let mut resolve_call = call("neverRead", 5, None);
resolve_call.dynamic = Some(true);
resolve_call.dynamic_kind = Some("value-ref".to_string());
resolve_call.key_expr = Some("resolve".to_string());

let mut reject_call = call("isRead", 6, None);
reject_call.dynamic = Some(true);
reject_call.dynamic_kind = Some("value-ref".to_string());
reject_call.key_expr = Some("reject".to_string());

let factory_file = make_file(
"factory.js",
10,
vec![def("makeTable", "function", 1, 8)],
vec![resolve_call, reject_call],
vec![],
vec![],
);

// Evidence that `.reject(...)` is genuinely invoked somewhere, but
// `.resolve(...)` never is.
let consumer_file = make_file(
"consumer.js",
20,
vec![def("run", "function", 1, 3)],
vec![call("reject", 2, Some("table"))],
vec![],
vec![],
);

let edges = build_call_edges(
vec![factory_file, consumer_file],
all_nodes,
vec![],
MAX_SOLVER_ITERATIONS,
);

let calls_never_read = edges.iter().any(|e| e.kind == "calls" && e.target_id == 2);
let calls_is_read = edges.iter().any(|e| e.kind == "calls" && e.target_id == 3);
assert!(
!calls_never_read,
"expected no calls edge to neverRead (key 'resolve' never invoked); got: {:?}",
edges.iter().map(|e| (&e.kind, e.source_id, e.target_id)).collect::<Vec<_>>()
);
assert!(
calls_is_read,
"expected a calls edge to isRead (key 'reject' invoked in consumer.js); got: {:?}",
edges.iter().map(|e| (&e.kind, e.source_id, e.target_id)).collect::<Vec<_>>()
);
}

/// Regression: when the same file has a `kind="function"` node for the
/// effective receiver created by a destructured import (e.g.
/// `const { Calculator } = require('./utils')`), that import artifact must
Expand Down
81 changes: 81 additions & 0 deletions crates/codegraph-core/src/extractors/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2929,6 +2929,12 @@ fn extract_callback_reference_calls(
/// (`{ name: SOME_CONSTANT }`) naturally fail to resolve into an edge rather
/// than needing a structural allowlist gate here.
///
/// `key_expr` carries the property KEY (e.g. `resolve`), distinct from `name`
/// (the referenced value's own identifier, e.g. `someFunction`) — the
/// downstream "is this property ever invoked" liveness check (#1895) needs
/// the key, since that's the name a dispatch consumer would actually call
/// (`table.resolve(...)`), not the function's own declared name.
///
/// Mirrors `collectObjectLiteralValueRefCall` in `src/extractors/javascript.ts`.
fn handle_object_literal_pair_value_ref(node: &Node, source: &[u8], calls: &mut Vec<Call>) {
let Some(value_n) = node.child_by_field_name("value") else { return };
Expand All @@ -2939,11 +2945,13 @@ fn handle_object_literal_pair_value_ref(node: &Node, source: &[u8], calls: &mut
if JS_BUILTIN_GLOBALS.contains(&text) {
return;
}
let key_expr = node.child_by_field_name("key").and_then(|k| resolve_pair_key_name(&k, source));
calls.push(Call {
name: text.to_string(),
line: start_line(&value_n),
dynamic: Some(true),
dynamic_kind: Some("value-ref".to_string()),
key_expr,
..Default::default()
});
}
Expand All @@ -2955,6 +2963,9 @@ fn handle_object_literal_pair_value_ref(node: &Node, source: &[u8], calls: &mut
/// `shorthand_property_identifier_pattern` kind), so this can't misfire on
/// destructuring targets.
///
/// `key_expr` equals `name` here — the property key and the referenced value
/// are the same identifier in shorthand form (#1895).
///
/// Mirrors the walk path's `shorthand_property_identifier` handling in
/// `src/extractors/javascript.ts`'s `runCollectorWalk` (issue #1771).
fn handle_object_literal_shorthand_value_ref(node: &Node, source: &[u8], calls: &mut Vec<Call>) {
Expand All @@ -2967,6 +2978,7 @@ fn handle_object_literal_shorthand_value_ref(node: &Node, source: &[u8], calls:
line: start_line(node),
dynamic: Some(true),
dynamic_kind: Some("value-ref".to_string()),
key_expr: Some(text.to_string()),
..Default::default()
});
}
Expand Down Expand Up @@ -5202,6 +5214,75 @@ mod tests {
assert!(value_refs.iter().any(|c| c.name == "someFunction"));
}

// #1895: key_expr capture — the property key, distinct from the
// referenced value's own name, is what a dispatch consumer would
// actually call (`table.resolve(...)`).
#[test]
fn value_ref_captures_property_key_distinct_from_referenced_name() {
let s = parse_js("const table = { resolve: someFunction };");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "someFunction")
.expect("expected a value-ref call");
assert_eq!(call.key_expr.as_deref(), Some("resolve"));
}

#[test]
fn value_ref_captures_string_literal_key_with_quotes_stripped() {
let s = parse_js("const table = { 'resolve': someFunction };");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "someFunction")
.expect("expected a value-ref call");
assert_eq!(call.key_expr.as_deref(), Some("resolve"));
}

#[test]
fn value_ref_captures_computed_string_literal_key() {
let s = parse_js("const table = { ['resolve']: someFunction };");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "someFunction")
.expect("expected a value-ref call");
assert_eq!(call.key_expr.as_deref(), Some("resolve"));
}

#[test]
fn value_ref_leaves_key_expr_unset_for_non_string_computed_key() {
let s = parse_js("const table = { [Symbol.iterator]: someFunction };");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "someFunction")
.expect("expected a value-ref call");
assert_eq!(call.key_expr, None);
}

#[test]
fn value_ref_key_expr_equals_name_for_shorthand_property() {
let s = parse_js("const table = { someFunction };");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "someFunction")
.expect("expected a value-ref call");
assert_eq!(call.key_expr.as_deref(), Some("someFunction"));
}

#[test]
fn instanceof_value_ref_leaves_key_expr_unset() {
let s = parse_js("if (err instanceof CodegraphError) {}");
let call = s
.calls
.iter()
.find(|c| c.dynamic_kind.as_deref() == Some("value-ref") && c.name == "CodegraphError")
.expect("expected a value-ref call");
assert_eq!(call.key_expr, None);
}

#[test]
fn no_value_ref_call_for_call_expression_value() {
let s = parse_js("const table = { resolve: someFunction() };");
Expand Down
37 changes: 37 additions & 0 deletions src/domain/graph/builder/call-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,43 @@ export const RECEIVER_KINDS = new Set(['class', 'struct', 'interface', 'type', '
// continue to work without changes (build-edges.ts, etc.).
export { isModuleScopedLanguage };

/**
* Collect the set of property/method names ever invoked via member-call
* syntax (`x.name(...)`) across every file currently being processed —
* regardless of whether the receiver `x` itself resolves to anything.
*
* Used as the "one hop further" liveness check for object-literal-property
* value-refs (#1895): a function referenced as `{ resolve: someFn }` should
* only be credited with a `calls` edge from that reference when something,
* somewhere, actually invokes a `.resolve(...)`-shaped call — otherwise the
* property is wired up but never read, and `someFn` is genuinely dead.
*
* Scope matches whatever set of files the caller passes in: the full
* codebase for a full build (build-edges.ts's `buildCallEdgesJS`, from
* `ctx.fileSymbols`), or just the single file being rebuilt on an incremental
* update (incremental.ts's `buildCallEdges`, from that file's own `calls`).
* The incremental case is a narrower, same-file view — a cross-file consumer
* added in a different, untouched file won't be seen until the next full
* rebuild — the same scoping trade-off already accepted elsewhere in this
* codebase's incremental classification (`hasActiveFileSiblings` and
* exported-via-reexport both recompute from an affected subset, not the
* whole graph, in `graph/classifiers/roles.rs`'s incremental path — median
* fan-in/out is a separate case, deliberately kept as a whole-graph
* statistic even on the incremental path, for classification-threshold
* consistency).
*/
export function collectInvokedPropertyNames(
callsList: Iterable<Iterable<{ name: string; receiver?: string }>>,
): Set<string> {
const names = new Set<string>();
for (const calls of callsList) {
for (const call of calls) {
if (call.receiver) names.add(call.name);
}
}
return names;
Comment on lines +73 to +82

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 Name-only matching can suppress dead-code detection due to unrelated call sites

collectInvokedPropertyNames adds a property name whenever ANY call in the processed files has a non-empty receiver and that name. There is no check that the receiver is plausibly the same dispatch-table object. A completely unrelated logger.resolve() or promise.resolve() call anywhere in the codebase will add resolve to the set and prevent { resolve: neverCalled } from being flagged dead, even if the actual dispatch table is never read. This is the conservative direction of error (false negative for dead-code), so it won't misclassify live code as dead, but it can cause real dead-code entries to escape detection. Given the existing comment explicitly scopes this as "one hop further" heuristic evidence rather than precise analysis, this is understood — just worth noting for future precision work.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this is understood and fine to leave as-is for this PR — making that judgment independently, not just deferring to your framing.

The error direction is the safe one (false negative for dead-code only — a completely unrelated logger.resolve()/promise.resolve() can prevent a genuinely-dead { resolve: neverCalled } from being flagged, but this check can never cause genuinely-live code to be misclassified as dead). This PR's own stated scope was "require any invocation evidence at all" — closing the prior gap where an object-literal value-ref got liveness credit with zero invocation evidence whatsoever — not "require precisely-correlated invocation evidence." Tightening this to require the receiver's inferred type/binding to plausibly match the specific dispatch-table object would mean extending the points-to/type-map machinery to correlate receiver call sites back to the originating object literal, implemented identically in both the WASM/TS and native Rust engines for parity — a real dataflow-precision feature, not a small tweak, and meaningfully larger than this PR's actual diff.

Tracked as a follow-up for future precision work: #2088

}

/**
* Shared by both the full-build (build-edges.ts) and incremental (incremental.ts)
* same-class fallback strategies: derive the enclosing class name from the
Expand Down
11 changes: 11 additions & 0 deletions src/domain/graph/builder/incremental.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from '../resolver/points-to.js';
import {
type CallNodeLookup,
collectInvokedPropertyNames,
findCaller,
isModuleScopedLanguage,
resolveCallTargets,
Expand Down Expand Up @@ -1044,6 +1045,10 @@ function buildCallEdges(
// JS path uses (buildPointsToMapForFile, shared via resolver/points-to.js).
const ptsMap = buildPointsToMapForFile(symbols, importedNames);
const fnRefBindingLhs = new Set(symbols.fnRefBindings?.map((b) => b.lhs) ?? []);
// #1895: scoped to this file's own calls only — see collectInvokedPropertyNames
// doc comment (call-resolver.ts) for why incremental rebuilds use a narrower,
// same-file view rather than a full-codebase one.
const invokedPropertyNames = collectInvokedPropertyNames([symbols.calls]);

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 Incremental rebuild can false-positive dead-code when the invocation is cross-file

collectInvokedPropertyNames([symbols.calls]) only sees calls extracted from the single file currently being rebuilt. If factory.js defines { resolve: neverCalled } and the only table.resolve(1) site lives in consumer.js, an incremental rebuild triggered solely on factory.js will not find resolve in invokedPropertyNames and will drop the edge — classifying neverCalled as dead even though it is genuinely reachable. Before this fix the edge was unconditionally kept, so this is a new false-positive direction introduced on the incremental path.

This is documented as the same scoping trade-off accepted elsewhere, and a full rebuild will correct it. Worth confirming the team is comfortable with incremental builds potentially surfacing "dead" findings that disappear on the next full run, since that could affect CI dead-code checks that run on incremental watches.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verified this is a genuine, accepted trade-off consistent with how this exact incremental-classification subsystem already works — not a hand-wave.

I independently checked the two precedents this PR's own doc comment cites (crates/codegraph-core/src/graph/classifiers/roles.rs): hasActiveFileSiblings and exported-via-reexport reachability (is_barrel_prod_reachable) both genuinely scope to the affected-file subset (changed_files + find_neighbour_files) during do_classify_incremental, not the whole graph — confirmed by reading the code, not just trusting the comment. find_neighbour_files's own doc comment even documents the same performance rationale (#1855: whole-graph CTE cost vs. scoped lookup cost) that motivates this exact kind of trade-off. So collectInvokedPropertyNames taking the same narrower, same-build-pass view on the incremental path is consistent with established convention here, not a new or unprincipled shortcut — and the error direction is safe: a genuinely-live cross-file consumer can transiently look dead only until the next full rebuild corrects it, mirroring the same self-correcting behavior the other two signals already have.

While verifying this, I did find and fix one real inaccuracy in the doc comment itself: it also cited "median fan-in/out" as a third example of this scoping trade-off, but that's backwards — compute_global_medians in roles.rs computes medians as a whole-graph statistic in both the full and incremental paths (no file-scoping at all), by design, for classification-threshold consistency. Corrected the comment in both call-resolver.ts and its Rust mirror in ef6492c1 to drop that incorrect example and keep only the two that actually hold up.

Given the underlying trade-off is real and consistent with existing convention, I'm accepting it as-is rather than building a persistent cross-file index in this PR (that would be a meaningfully larger, separate change — a new persisted evidence table with incremental insert/prune logic on both engines, not a small tweak). Tracked as a follow-up: #2087

let edgesAdded = 0;

for (const call of symbols.calls) {
Expand Down Expand Up @@ -1078,6 +1083,12 @@ function buildCallEdges(
targets = targets.filter(
(t) => t.kind === 'function' || t.kind === 'method' || t.kind === 'class',
);
// #1895: object-literal-property value-refs additionally require
// independent evidence the property is actually invoked somewhere —
// mirrors the same check in resolveFallbackTargets (stages/build-edges.ts).
if (call.keyExpr && !invokedPropertyNames.has(call.keyExpr)) {
targets = [];
}
}

edgesAdded += emitIncrementalCallEdges(
Expand Down
Loading
Loading