Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
118 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
1e104f1
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 10, 2026
c90afdf
test(native-db): cover the remaining 3 busyTimeoutMs threading call s…
carlos-alm Jul 10, 2026
4d5285e
Merge branch 'fix/issue-1882-thread-config-db-busytimeoutms-into-the-…
carlos-alm Jul 10, 2026
f122a6d
Merge branch 'fix/issue-1884-computed-string-literal-keys-not-unwrapp…
carlos-alm Jul 10, 2026
cd0f53c
fix: guard native iteration with isNativeAvailable() in definePropert…
carlos-alm Jul 10, 2026
0c721b2
Merge branch 'fix/issue-1887-native-engine-skips-object-definepropert…
carlos-alm Jul 11, 2026
5075d39
Merge branch 'fix/issue-1888-same-file-bare-name-lookup-resolvecallta…
carlos-alm Jul 11, 2026
e6f2e1c
fix: widen resolveCallTargets's targets type to include kind (#2028)
carlos-alm Jul 11, 2026
5733055
fix: use explicit undefined check for CONSTRUCTOR_LOCAL_NAME_BY_EXTEN…
carlos-alm Jul 11, 2026
c7f67cf
fix: use the barrel-resolved true name for constructor attribution (#…
carlos-alm Jul 11, 2026
0ae2ecd
test: cover PHP/Dart/Groovy constructor attribution, close stale dart…
carlos-alm Jul 11, 2026
170854c
fix: resolve merge conflicts with main
carlos-alm Jul 11, 2026
eced589
fix(extractors): resolve Dart new-expression type name through the ty…
carlos-alm Jul 11, 2026
b71e621
fix: exclude constructor calls from CHA virtual-dispatch expansion (#…
carlos-alm Jul 11, 2026
22d032c
test: close stale java/typescript resolution-benchmark ground truth (…
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
106 changes: 106 additions & 0 deletions crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,12 @@ fn resolve_exact_global_match<'a>(
/// `caller_name` is the enclosing function/method name (e.g. `"Shape.describe"`) used to scope
/// `this`/`self`/`super` dispatch to the caller's own class before falling back to a broader scan.
/// Mirrors `resolveCallTargets` / `resolveByMethodOrGlobal` in call-resolver.ts.
///
/// Thin wrapper around `resolve_call_targets_core`: additionally attaches
/// constructor-call attribution (#1892) for bare (no-receiver) calls — see
/// `attach_constructor_targets`. Split out because the core resolver has many
/// early-return tiers, so a single post-processing pass at the call site is
/// simpler than threading the augmentation through every tier.
fn resolve_call_targets<'a>(
ctx: &EdgeContext<'a>,
call: &CallInfo,
Expand All @@ -994,6 +1000,30 @@ fn resolve_call_targets<'a>(
type_map: &HashMap<&str, (&str, f64)>,
caller_name: &str,
imported_original_names: &HashMap<&str, &str>,
) -> Vec<&'a NodeInfo> {
let targets = resolve_call_targets_core(
ctx, call, rel_path, imported_from, type_map, caller_name, imported_original_names,
);
if call.receiver.is_some() {
return targets;
}
let class_name = imported_original_names
.get(call.name.as_str())
.copied()
.unwrap_or(call.name.as_str());
attach_constructor_targets(ctx, targets, class_name)
}

/// Core multi-strategy call target resolution — see `resolve_call_targets` for
/// the public entry point (which additionally applies constructor attribution).
fn resolve_call_targets_core<'a>(
ctx: &EdgeContext<'a>,
call: &CallInfo,
rel_path: &str,
imported_from: Option<&str>,
type_map: &HashMap<&str, (&str, f64)>,
caller_name: &str,
imported_original_names: &HashMap<&str, &str>,
) -> Vec<&'a NodeInfo> {
// Flagged dynamic calls use synthetic names like "<dynamic:eval>". Short-circuit
// so they never accidentally match a real symbol via name lookup.
Expand Down Expand Up @@ -1306,6 +1336,82 @@ fn resolve_call_targets<'a>(
Vec::new()
}

// ── Constructor-call attribution (#1892) ──────────────────────────────────

/// Per-language constructor method identifier, keyed by file extension. Used
/// to build the qualified `ClassName.<ctorLocalName>` lookup key that
/// attributes a `new ClassName()` (or bare `ClassName()`, for the keyword-less
/// languages below) call site to the class's own constructor **method**,
/// rather than only the class declaration node it already resolves to.
/// Returns `None` when the extension is unrecognised (or has no extension at
/// all). For Java/C#/Dart/Groovy the constructor's own identifier equals the
/// class name (`class Foo { Foo(...) {} }`), so those arms return
/// `class_name` itself rather than a fixed keyword. Mirrors
/// `CONSTRUCTOR_LOCAL_NAME_BY_EXTENSION` in strategy.ts.
///
/// Deliberately excludes languages whose extractor does not emit an explicit
/// constructor definition at all (Kotlin, Swift, Scala) or does not track
/// object-construction call sites at all (C++) — for those, the class-node
/// edge already produced by `resolve_call_targets_core` is the only
/// attribution possible.
fn constructor_local_name<'b>(file: &str, class_name: &'b str) -> Option<&'b str> {
let ext = file.rsplit_once('.').map(|(_, e)| e)?;
match ext {
"js" | "mjs" | "cjs" | "jsx" | "ts" | "tsx" | "mts" | "cts" => Some("constructor"),
"py" | "pyi" => Some("__init__"),
"php" | "phtml" => Some("__construct"),
"java" | "cs" | "dart" | "groovy" | "gvy" => Some(class_name),
_ => None,
}
}

/// Resolve the constructor **method** node for a class target, if the class
/// declares one explicitly. Scoped to the class's own file (`file`) so an
/// unrelated same-named constructor elsewhere can never match.
fn resolve_constructor_target<'a>(
ctx: &EdgeContext<'a>,
file: &str,
class_name: &str,
) -> Option<&'a NodeInfo> {
let local_name = constructor_local_name(file, class_name)?;
let qualified = format!("{}.{}", class_name, local_name);
ctx.nodes_by_name_and_file
.get(&(qualified.as_str(), file))
.and_then(|v| v.iter().find(|n| n.kind == "method"))
.copied()
}

/// Additive constructor-call attribution: for every `class`-kind target in
/// `targets`, also resolve that class's own constructor method (if one is
/// explicitly declared) and append it. Mirrors `attachConstructorTargets` in
/// strategy.ts.
///
/// Additive, not a replacement: the class-node target is always left standing
/// — the DB-driven RTA fallback (incremental rebuilds, see `cha.ts`'s
/// `buildChaContextFromDb`) reads instantiation evidence from `calls` edges
/// targeting class-kind nodes, and a class with no explicit constructor
/// legitimately has nothing else to attribute the call to.
fn attach_constructor_targets<'a>(
ctx: &EdgeContext<'a>,
mut targets: Vec<&'a NodeInfo>,
class_name: &str,
) -> Vec<&'a NodeInfo> {
let mut seen_ids: HashSet<u32> = targets.iter().map(|t| t.id).collect();
let mut extra = Vec::new();
for target in &targets {
if target.kind != "class" {
continue;
}
if let Some(ctor) = resolve_constructor_target(ctx, target.file.as_str(), class_name) {
if seen_ids.insert(ctor.id) {
extra.push(ctor);
}
}
}
targets.extend(extra);
targets
}

/// Languages where bare `foo()` calls inside a class method are lexically scoped
/// to the module, not the class — there is no implicit this/class binding.
/// Mirrors `MODULE_SCOPED_BARE_CALL_EXTENSIONS` in call-resolver.ts.
Expand Down
14 changes: 13 additions & 1 deletion crates/codegraph-core/src/extractors/dart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,8 +279,20 @@ fn handle_dart_import(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
}

fn handle_dart_constructor_call(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
// tree-sitter-dart crate versions structure the type name differently:
// 0.2 (crates.io, current) nests it under an intermediate `type` field —
// `new_expression type: (type (type_identifier)) arguments: (...)` —
// while npm's tree-sitter-dart 1.x (used by the WASM engine, see
// check-grammar-versions.mjs's tracked exception for this crate) puts it
// directly under `new_expression` — `(new_expression (type_identifier)
// (arguments))`. Try the direct shape first, then unwrap one `type` level.
let name_node = find_child(node, "type_identifier")
.or_else(|| find_child(node, "identifier"));
.or_else(|| find_child(node, "identifier"))
.or_else(|| {
node.child_by_field_name("type").or_else(|| find_child(node, "type")).and_then(|t| {
find_child(&t, "type_identifier").or_else(|| find_child(&t, "identifier"))
})
});
if let Some(name) = name_node {
symbols.calls.push(Call {
name: node_text(&name, source).to_string(),
Expand Down
32 changes: 26 additions & 6 deletions src/domain/graph/builder/call-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import { CALLABLE_SYMBOL_KINDS } from '../../../shared/kinds.js';
import { computeConfidence, isSameLanguageFamily } from '../resolve.js';
import {
attachConstructorTargets,
isModuleScopedLanguage,
resolveByGlobal,
resolveByReceiver,
Expand Down Expand Up @@ -268,7 +269,10 @@ export function resolveCallTargets(
typeMap: Map<string, unknown>,
callerName?: string | null,
importedOriginalNames?: ReadonlyMap<string, string>,
): { targets: Array<{ id: number; file: string }>; importedFrom: string | undefined } {
): {
targets: Array<{ id: number; file: string; kind?: string }>;
importedFrom: string | undefined;
} {
// Flagged dynamic calls use synthetic names like '<dynamic:eval>'. Short-circuit
// so they never accidentally match a real symbol via lookup.byName.
if (call.name.startsWith('<dynamic:')) {
Expand All @@ -280,14 +284,22 @@ export function resolveCallTargets(
// the imported file's actual symbol is declared under the *original* name
// (X) — look that up instead of the local alias the call site wrote (#1730).
const targetName = importedOriginalNames?.get(call.name) ?? call.name;
let targets: ReadonlyArray<{ id: number; file: string }> | undefined;
// Tracks the name actually used to find `targets`. Usually equal to
// `targetName`, but a barrel hop that itself renames the export
// (`export { Foo as Bar } from './foo'`, resolved below) reports the name
// truly declared in the origin file — the constructor-attribution lookup
// must key on that name, not the call site's (possibly barrel-aliased)
// `targetName`, or it builds a qualified name that doesn't exist (#1892).
let resolvedClassName = targetName;
let targets: ReadonlyArray<{ id: number; file: string; kind?: string }> | undefined;

if (importedFrom) {
targets = lookup.byNameAndFile(targetName, importedFrom);
if (targets.length === 0 && lookup.isBarrel(importedFrom)) {
const resolved = lookup.resolveBarrel(importedFrom, targetName);
if (resolved) {
targets = lookup.byNameAndFile(resolved.name, resolved.file);
const barrelResolved = lookup.resolveBarrel(importedFrom, targetName);
if (barrelResolved) {
targets = lookup.byNameAndFile(barrelResolved.name, barrelResolved.file);
resolvedClassName = barrelResolved.name;
}
}
}
Expand Down Expand Up @@ -322,7 +334,15 @@ export function resolveCallTargets(
}
}

const resolved = [...(targets ?? [])];
let resolved = [...(targets ?? [])];
// #1892: `new ClassName()` / bare `ClassName()` (keyword-less languages)
// always resolves as a bare (no-receiver) call — augment any class-kind
// match with the class's own constructor method, if it declares one.
// Uses `resolvedClassName` (not `targetName`) so a barrel rename doesn't
// make the qualified constructor lookup miss (see comment above).
if (!call.receiver) {
resolved = attachConstructorTargets(lookup, resolved, resolvedClassName);
}
Comment on lines +337 to +345

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 targets declared without kind, but attachConstructorTargets relies on it at runtime

targets is typed as ReadonlyArray<{ id: number; file: string }> (no kind), so resolved inherits that narrower type. When attachConstructorTargets is called, TypeScript infers T = { id: number; file: string }, satisfying the generic constraint only because kind is optional in the bound. At runtime, the actual objects returned by lookup.byNameAndFile do carry kind, so the target.kind !== 'class' guard inside attachConstructorTargets works correctly. However, if downstream code ever tries to read kind from items of resolved after this call, TypeScript won't catch that access as safe. Widening the targets declaration to include kind?: string would close the gap.

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!

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.

Fixed as suggested — widened resolveCallTargets's declared return type (and the internal targets variable) to Array<{ id: number; file: string; kind?: string }> in commit e6f2e1c (fix: widen resolveCallTargets's targets type to include kind). This also let me delete a workaround cast in build-edges.ts's resolveFallbackTargets (the value-ref kind filter) that existed specifically because of this exact gap — that cast's own comment called out "the same gap" you're flagging here, so closing it at the source removed the need for the workaround entirely.

if (resolved.length > 1) {
resolved.sort((a, b) => {
const confA = computeConfidence(relPath, a.file, importedFrom ?? null);
Expand Down
9 changes: 9 additions & 0 deletions src/domain/graph/builder/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {
PathAliases,
SqliteStatement,
} from '../../../types.js';
import { isConstructorMethodSuffix } from '../resolver/strategy.js';

export const BUILTIN_RECEIVERS: Set<string> = new Set([
'console',
Expand Down Expand Up @@ -670,6 +671,14 @@ export function runChaPostPass(db: BetterSqlite3Database): number {
if (dotIdx === -1) continue;
const typeName = method_name.slice(0, dotIdx);
const methodSuffix = method_name.slice(dotIdx + 1);
// #1892: a constructor call is never polymorphically dispatched — `new
// Circle()` always constructs exactly a Circle, never an Ellipse, even
// though Ellipse extends Circle and is separately instantiated
// elsewhere. Without this guard, a constructor-attribution edge
// (`caller -> Circle.constructor`) looks identical to a regular
// qualified-method call edge here, and CHA fabricates edges from the
// *original* caller to unrelated subclasses' constructors.
if (isConstructorMethodSuffix(typeName, methodSuffix)) continue;
expandChaCall(
source_id,
typeName,
Expand Down
9 changes: 1 addition & 8 deletions src/domain/graph/builder/stages/build-edges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1349,14 +1349,7 @@ function resolveFallbackTargets(
// either idiom commonly names a class. Applied once here, after every
// fallback tier above, so it covers whichever tier produced the match.
if (call.dynamicKind === 'value-ref') {
// `targets` is typed without `kind` when it flows straight through from
// resolveCallTargets (call-resolver.ts's declared return type omits it),
// but every underlying CallNodeLookup method actually populates it — the
// same gap the preQualifiedTargets cast above already works around. Kept
// as its own step (not folded into the filter callback) so the type-gap
// workaround and the actual filtering decision stay visually distinct.
const typedTargets = targets as ReadonlyArray<{ id: number; file: string; kind?: string }>;
targets = typedTargets.filter(
targets = targets.filter(
(t) => t.kind === 'function' || t.kind === 'method' || t.kind === 'class',
);
}
Expand Down
10 changes: 10 additions & 0 deletions src/domain/graph/builder/stages/native-orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
patchDataflowResult,
} from '../../../parser.js';
import { computeConfidence } from '../../resolve.js';
import { isConstructorMethodSuffix } from '../../resolver/strategy.js';
import type { CallNodeLookup } from '../call-resolver.js';
import { resolveDefinePropertyAccessorTarget } from '../call-resolver.js';
import type { ChaContext } from '../cha.js';
Expand Down Expand Up @@ -880,6 +881,15 @@ function expandChaEdges(
if (dotIdx === -1) continue;
const typeName = method_name.slice(0, dotIdx);
const methodSuffix = method_name.slice(dotIdx + 1);
// #1892: a constructor call is never polymorphically dispatched — `new
// Circle()` always constructs exactly a Circle, never an Ellipse, even
// though Ellipse extends Circle and is separately instantiated
// elsewhere. Without this guard, a constructor-attribution edge
// (`caller -> Circle.constructor`) looks identical to a regular
// qualified-method call edge here, and CHA fabricates edges from the
// *original* caller to unrelated subclasses' constructors. Mirrors the
// equivalent guard in builder/helpers.ts's runChaPostPass.
if (isConstructorMethodSuffix(typeName, methodSuffix)) continue;

// BFS over the implementors map — handles multi-level hierarchies where
// abstract/non-instantiated classes sit between the call-site type and
Expand Down
Loading
Loading