Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 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
19aa6fd
fix: resolve merge conflicts with main
carlos-alm Jul 8, 2026
156116b
test: add native call-edge preservation check (#1902)
carlos-alm Jul 8, 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
48 changes: 44 additions & 4 deletions crates/codegraph-core/src/extractors/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2507,6 +2507,19 @@ fn handle_object_literal_shorthand_value_ref(node: &Node, source: &[u8], calls:
});
}

/// Extract definitions from destructured object bindings: `const { handleToken,
/// checkPermissions } = initAuth(...)` creates definitions for `handleToken`
/// and `checkPermissions`, kind `constant` — matching the convention for plain
/// `const x = <literal>` bindings and array-pattern destructuring.
///
/// Every call site of this function is already gated to `const` declarations
/// (never `let`/`var`), so `constant` is unconditionally correct here. Prior to
/// #1773 this used `kind: "function"` on the theory that destructured names
/// are usually callbacks, but that miscategorized every non-function
/// destructured value (e.g. `const { dbPath } = workerData`). `constant`-kind
/// nodes remain fully resolvable as call targets — call-target resolution is
/// kind-agnostic — so callback-style destructured bindings still resolve.
/// Mirrors the TS extractor's `extractDestructuredBindings`.
fn extract_destructured_bindings(
pattern: &Node,
source: &[u8],
Expand All @@ -2520,7 +2533,7 @@ fn extract_destructured_bindings(
"shorthand_property_identifier_pattern" | "shorthand_property_identifier" => {
definitions.push(Definition {
name: node_text(&child, source).to_string(),
kind: "function".to_string(),
kind: "constant".to_string(),
line,
end_line: Some(end_line),
decorators: None,
Expand All @@ -2536,7 +2549,7 @@ fn extract_destructured_bindings(
{
definitions.push(Definition {
name: node_text(&value, source).to_string(),
kind: "function".to_string(),
kind: "constant".to_string(),
line,
end_line: Some(end_line),
decorators: None,
Expand Down Expand Up @@ -4565,12 +4578,33 @@ mod tests {

#[test]
fn extracts_destructured_const_bindings() {
// kind is "constant" (#1773), not "function" — matches the plain
// `const x = <literal>` and array-pattern destructuring convention.
// Destructured names remain resolvable as call targets regardless of
// kind (call-target resolution is kind-agnostic), so callback-style
// destructured bindings like `handleToken` still resolve when called.
let s = parse_js("const { handleToken, checkPermissions } = initAuth(config);");
let names: Vec<&str> = s.definitions.iter().map(|d| d.name.as_str()).collect();
assert!(names.contains(&"handleToken"), "should extract handleToken definition");
assert!(names.contains(&"checkPermissions"), "should extract checkPermissions definition");
let ht = s.definitions.iter().find(|d| d.name == "handleToken").unwrap();
assert_eq!(ht.kind, "function");
assert_eq!(ht.kind, "constant");
}

#[test]
fn extracts_non_renamed_destructured_bindings_with_kind_constant() {
// Regression guard for issue #1773: plain (non-renamed) destructured
// bindings from a non-call RHS (e.g. `workerData`) must not default to
// kind "function" — they hold arbitrary values, not callables.
let s = parse_js("const { dbPath, name, force } = workerData;");
for expected in ["dbPath", "name", "force"] {
let def = s
.definitions
.iter()
.find(|d| d.name == expected)
.unwrap_or_else(|| panic!("should extract {expected} definition"));
assert_eq!(def.kind, "constant");
}
}

#[test]
Expand Down Expand Up @@ -4611,7 +4645,13 @@ mod tests {
#[test]
fn extracts_renamed_destructured_binding() {
let s = parse_js("const { original: renamed } = initAuth();");
assert!(s.definitions.iter().any(|d| d.name == "renamed"), "should use the local alias");
let renamed = s
.definitions
.iter()
.find(|d| d.name == "renamed")
.expect("should use the local alias");
// kind is "constant" (#1773) — see comment on extracts_destructured_const_bindings.
assert_eq!(renamed.kind, "constant");
assert!(!s.definitions.iter().any(|d| d.name == "original"), "should not use the original key");
}

Expand Down
27 changes: 22 additions & 5 deletions src/extractors/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,23 @@ function handleTypeAliasDecl(node: TreeSitterNode, ctx: ExtractorOutput): void {
/**
* Extract definitions from destructured object bindings.
* `const { handleToken, checkPermissions } = initAuth(...)` creates definitions
* for handleToken and checkPermissions so they can be resolved as call targets.
* for handleToken and checkPermissions, kind `constant` — matching the
* convention for plain `const x = <literal>` bindings (handleConstIdentifierAssignment)
* and array-pattern destructuring (the sibling branch in the callers below).
*
* Every call site of this function is already gated to `const` declarations
* (never `let`/`var`), so `constant` is unconditionally correct here — there is
* no live binding-mutability to branch on. Prior to #1773 this used `kind:
* 'function'` on the theory that destructured names are usually callbacks, but
* that miscategorized every non-function destructured value (e.g. `const {
* dbPath } = workerData`), which polluted `--kind function` queries and caused
* the dead-code classifier to misjudge them via the wrong kind's heuristics.
* `constant`-kind nodes remain fully resolvable as call targets — call-target
* resolution (`resolveByGlobal`'s exact by-name lookup) is kind-agnostic, and
* `constant` is already in the caller-attribution fallback tier
* (`TOP_LEVEL_BINDING_KINDS` in call-resolver.ts) — so callback-style
* destructured bindings (`const { handleToken } = router; handleToken(req)`)
* still resolve correctly.
*/
function extractDestructuredBindings(
pattern: TreeSitterNode,
Expand All @@ -1128,15 +1144,15 @@ function extractDestructuredBindings(
child.type === 'shorthand_property_identifier'
) {
// { handleToken } — shorthand binding
definitions.push({ name: child.text, kind: 'function', line, endLine });
definitions.push({ name: child.text, kind: 'constant', line, endLine });
} else if (child.type === 'pair_pattern' || child.type === 'pair') {
// { original: renamed } — renamed binding, use the local alias
const value = child.childForFieldName('value');
if (
value &&
(value.type === 'identifier' || value.type === 'shorthand_property_identifier_pattern')
) {
definitions.push({ name: value.text, kind: 'function', line, endLine });
definitions.push({ name: value.text, kind: 'constant', line, endLine });
}
}
}
Expand Down Expand Up @@ -1259,8 +1275,9 @@ function handleConstObjectPatternAssignment(
ctx: ExtractorOutput,
): void {
// Destructured bindings: const { handleToken, checkPermissions } = initAuth(...)
// Each destructured property becomes a function definition so it can be
// resolved when passed as a callback (e.g. router.use(handleToken)).
// Each destructured property becomes a constant definition (#1773) — still
// resolvable when passed as a callback (e.g. router.use(handleToken)), since
// call-target resolution is kind-agnostic (see extractDestructuredBindings).
// Restricted to const to avoid creating spurious definitions for
// transient let/var destructuring (e.g. let { userId } = parseRequest(req)).
// Scope guard mirrors extractDestructuredBindingsWalk (query path) and
Expand Down
185 changes: 185 additions & 0 deletions tests/integration/issue-1773-destructured-binding-kind.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/**
* Integration test for #1773: destructured object-pattern binding targets
* (renamed and non-renamed) were classified with `kind: "function"` instead
* of `kind: "constant"`, regardless of what the destructured value actually
* held. Because these bindings had no call-graph edges pointing at them by
* name, `codegraph roles --role dead` risked flagging them `dead-unresolved`
* (the "genuinely dead callable" bucket) even when read repeatedly elsewhere.
*
* Root cause: `extractDestructuredBindings` (src/extractors/javascript.ts,
* shared by both the walk and query extraction paths) and its native mirror
* `extract_destructured_bindings` (crates/codegraph-core/src/extractors/
* javascript.rs) hardcoded `kind: 'function'` for every object-pattern
* binding target, on the theory that destructured names are usually
* callbacks. That miscategorized any destructured value that wasn't a
* function (e.g. `const { dbPath } = workerData`).
*
* Fix: both engines now emit `kind: 'constant'`, matching the existing
* convention for plain `const x = <literal>` bindings and array-pattern
* destructuring. Constants remain fully resolvable as call targets (call-
* target resolution is kind-agnostic), so callback-style destructured
* bindings still resolve; and constants with active call-graph-connected
* siblings in the same file are classified `leaf`, not `dead-unresolved` —
* exactly like any other same-file constant.
*/

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { isNativeAvailable } from '../../src/infrastructure/native.js';

// Repro 1 (renamed destructuring, issue #1773): a file with other real,
// call-graph-connected functions (giving it "active file siblings") plus a
// renamed destructured binding read repeatedly afterward — mirrors
// scripts/token-benchmark.ts's `const { values: flags } = parseArgs(...)`.
// Repro 2 (non-renamed destructuring, issue #1773): an isolated worker-style
// file with *only* a destructured binding from a non-call RHS and no other
// callables — mirrors tests/unit/snapshot-race-worker.mjs's
// `const { dbPath, name, force } = workerData`.
const FIXTURE = {
'renamed-repro.js': `
function parseArgs(opts) { return { values: computeDefaults(opts) }; }
function computeDefaults(opts) { return { runs: 3, model: opts.model }; }

const { values: flags } = parseArgs({ model: 'x' });

function main() {
console.log(flags.runs, flags.model);
}
main();
`,
'worker-repro.mjs': `
const { dbPath, name, force } = workerData;
save(name, { dbPath, force });
`,
};

function readNode(dbPath: string, file: string, name: string) {
const db = new Database(dbPath, { readonly: true });
try {
return db
.prepare('SELECT name, kind, role FROM nodes WHERE file = ? AND name = ?')
.get(file, name) as { name: string; kind: string; role: string | null } | undefined;
} finally {
db.close();
}
}

function expectFixedKindAndRole(dbPath: string) {
// Repro 1: renamed destructured binding, active file siblings present.
const flags = readNode(dbPath, 'renamed-repro.js', 'flags');
expect(flags, 'flags node not found').toBeDefined();
expect(flags!.kind, 'flags must be kind constant, not function').toBe('constant');
expect(
flags!.role,
`flags was classified as ${flags!.role} — must not be dead-unresolved`,
).not.toBe('dead-unresolved');

// Repro 2: non-renamed destructured bindings, no active file siblings.
for (const varName of ['dbPath', 'name', 'force']) {
const node = readNode(dbPath, 'worker-repro.mjs', varName);
expect(node, `${varName} node not found`).toBeDefined();
expect(node!.kind, `${varName} must be kind constant, not function`).toBe('constant');
// With no other call-graph-connected callable in the file, these fall
// back to 'dead-leaf' — the same honest classification any isolated,
// unreferenced-by-calls constant gets (properties/constants are leaf
// nodes by definition; call-graph reachability can't prove liveness for
// pure value bindings). The bug this test guards against is the far more
// misleading 'dead-unresolved' ("genuinely dead callable") label that a
// wrong kind: 'function' classification used to produce.
expect(
node!.role,
`${varName} was classified as ${node!.role} — must not be dead-unresolved`,
).not.toBe('dead-unresolved');
}
}

describe('destructured binding kind classification (#1773) — WASM', () => {
let tmpDir: string;

beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1773-'));
for (const [rel, content] of Object.entries(FIXTURE)) {
fs.writeFileSync(path.join(tmpDir, rel), content);
}
await buildGraph(tmpDir, { engine: 'wasm', incremental: false, skipRegistry: true });
});

afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('classifies renamed and non-renamed destructured bindings as kind constant, not dead-unresolved', () => {
expectFixedKindAndRole(path.join(tmpDir, '.codegraph', 'graph.db'));
});

it('still resolves calls made through a destructured callback-style binding', () => {
// `flags.runs`/`flags.model` are property reads, not calls, but `flags`
// itself must still show up as the attributed caller of `parseArgs` — the
// fix must not break caller attribution for the top-level binding.
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const db = new Database(dbPath, { readonly: true });
try {
const row = db
.prepare(
`SELECT COUNT(*) AS cnt
FROM edges e
JOIN nodes s ON e.source_id = s.id
JOIN nodes t ON e.target_id = t.id
WHERE s.name = 'flags' AND t.name = 'parseArgs' AND e.kind = 'calls'`,
)
.get() as { cnt: number };
expect(row.cnt, 'expected flags -> parseArgs calls edge to survive the kind fix').toBe(1);
} finally {
db.close();
}
});
});

describe.skipIf(!isNativeAvailable())(
'destructured binding kind classification (#1773) — native',
() => {
let tmpDir: string;

beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1773-native-'));
for (const [rel, content] of Object.entries(FIXTURE)) {
fs.writeFileSync(path.join(tmpDir, rel), content);
}
await buildGraph(tmpDir, { engine: 'native', incremental: false, skipRegistry: true });
}, 60_000);

afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('classifies renamed and non-renamed destructured bindings as kind constant, not dead-unresolved', () => {
expectFixedKindAndRole(path.join(tmpDir, '.codegraph', 'graph.db'));
});

it('still resolves calls made through a destructured callback-style binding', () => {
// `flags.runs`/`flags.model` are property reads, not calls, but `flags`
// itself must still show up as the attributed caller of `parseArgs` — the
// fix must not break caller attribution for the top-level binding.
const dbPath = path.join(tmpDir, '.codegraph', 'graph.db');
const db = new Database(dbPath, { readonly: true });
try {
const row = db
.prepare(
`SELECT COUNT(*) AS cnt
FROM edges e
JOIN nodes s ON e.source_id = s.id
JOIN nodes t ON e.target_id = t.id
WHERE s.name = 'flags' AND t.name = 'parseArgs' AND e.kind = 'calls'`,
)
.get() as { cnt: number };
expect(row.cnt, 'expected flags -> parseArgs calls edge to survive the kind fix').toBe(1);
} finally {
db.close();
}
});
},
);
Comment on lines +142 to +185

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 Native describe block missing call-edge preservation test

The WASM describe block has two assertions — kind correctness (expectFixedKindAndRole) and a flags → parseArgs call-edge preservation check — but the native block only covers the first. If a future change to the native engine's call-attribution for top-level const bindings silently drops that edge, this test suite won't catch it. Parity with the WASM block's second it(...) 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 — added the matching flags → parseArgs call-edge preservation test to the native describe block in 156116b8.

32 changes: 27 additions & 5 deletions tests/parsers/javascript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1002,22 +1002,43 @@ describe('JavaScript parser', () => {

// Destructured bindings
it('extracts definitions from destructured const bindings', () => {
// kind is 'constant' (#1773), not 'function' — matches the plain
// `const x = <literal>` and array-pattern destructuring convention.
// Destructured names remain resolvable as call targets regardless of
// kind (call-target resolution is kind-agnostic), so callback-style
// destructured bindings like `handleToken` still resolve when called.
const symbols = parseJS(`const { handleToken, checkPermissions } = initAuth(config);`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'handleToken', kind: 'function' }),
expect.objectContaining({ name: 'handleToken', kind: 'constant' }),
);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'checkPermissions', kind: 'function' }),
expect.objectContaining({ name: 'checkPermissions', kind: 'constant' }),
);
});

it('extracts definitions from exported destructured const bindings', () => {
const symbols = parseJS(`export const { handleToken, checkPermissions } = initAuth(config);`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'handleToken', kind: 'function' }),
expect.objectContaining({ name: 'handleToken', kind: 'constant' }),
);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'checkPermissions', kind: 'function' }),
expect.objectContaining({ name: 'checkPermissions', kind: 'constant' }),
);
});

it('extracts non-renamed destructured const bindings with kind constant (#1773)', () => {
// Regression guard for issue #1773: plain (non-renamed) destructured
// bindings from a non-call RHS (e.g. `workerData`) must not default to
// kind 'function' — they hold arbitrary values, not callables.
const symbols = parseJS(`const { dbPath, name, force } = workerData;`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'dbPath', kind: 'constant' }),
);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'name', kind: 'constant' }),
);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'force', kind: 'constant' }),
);
});

Expand All @@ -1034,9 +1055,10 @@ describe('JavaScript parser', () => {
});

it('extracts renamed destructured const binding under its local alias', () => {
// kind is 'constant' (#1773) — see comment on the non-renamed case above.
const symbols = parseJS(`const { original: renamed } = initAuth();`);
expect(symbols.definitions).toContainEqual(
expect.objectContaining({ name: 'renamed', kind: 'function' }),
expect.objectContaining({ name: 'renamed', kind: 'constant' }),
);
expect(symbols.definitions).not.toContainEqual(expect.objectContaining({ name: 'original' }));
});
Expand Down
Loading