Skip to content

Commit 9bb778a

Browse files
committed
fix: resolve merge conflicts with main (docs check acknowledged)
Also removes a duplicate importNamePairs definition in incremental.ts left behind by the merge: main extracted it to import-utils.ts and incremental.ts already imports it, but the local definition from this branch's stacked history wasn't touched by the 3-way merge (no overlapping diff region), so both survived until removed here. Impact: 47 functions changed, 183 affected
2 parents dd447bc + 74e29d4 commit 9bb778a

57 files changed

Lines changed: 1438 additions & 281 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.claude/skills/titan-grind/SKILL.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ Forge shapes the metal. Grind smooths the rough edges. Your goal: find helpers t
109109

110110
12. **Capture dead-symbol baseline** (only if `grind.deadSymbolBaseline` is null):
111111
```bash
112-
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count,byRole:data.summary}));})"
112+
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{try{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count??0,byRole:data.summary??{}}));}catch(e){console.error('Failed to parse roles --json output: '+e.message);process.exit(1);}})"
113113
```
114114
`codegraph roles --json` returns `{ count, summary, symbols }` (not a bare array) — `summary` is already the per-role breakdown (e.g. `dead-leaf`, `dead-entry`, `dead-ffi`, `dead-unresolved`), so no manual reduce is needed.
115115
Store the total in `grind.deadSymbolBaseline`. Write `titan-state.json` immediately.
@@ -580,7 +580,7 @@ After all targets in the phase are processed:
580580
581581
```bash
582582
codegraph build
583-
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count,byRole:data.summary}));})"
583+
codegraph roles --role dead -T --json | node -e "const d=[];process.stdin.on('data',c=>d.push(c));process.stdin.on('end',()=>{try{const data=JSON.parse(Buffer.concat(d));console.log(JSON.stringify({total:data.count??0,byRole:data.summary??{}}));}catch(e){console.error('Failed to parse roles --json output: '+e.message);process.exit(1);}})"
584584
```
585585
586586
Store in `grind.deadSymbolCurrent`. Write `titan-state.json`.

crates/codegraph-core/src/ast_analysis/complexity.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1748,6 +1748,22 @@ mod tests {
17481748
assert_eq!(m.cyclomatic, 3);
17491749
}
17501750

1751+
#[test]
1752+
fn lua_method_declaration() {
1753+
// Greptile follow-up to #1782: colon-syntax method declarations
1754+
// (`function Obj:method(x)`) have a `method_index_expression` name
1755+
// field but are still `function_declaration` nodes, so `function_nodes`
1756+
// already covers them — this pins that native/TS parity explicitly.
1757+
// Mirrors the TS test 'method declaration (colon syntax) is
1758+
// recognized as a function'.
1759+
let m = compute_lua(
1760+
"local Obj = {}\nfunction Obj:method(x)\n if x > 0 then\n return x\n end\nend",
1761+
);
1762+
assert_eq!(m.cognitive, 1);
1763+
assert_eq!(m.cyclomatic, 2);
1764+
assert_eq!(m.max_nesting, 1);
1765+
}
1766+
17511767
#[test]
17521768
fn lua_nested_if() {
17531769
let m = compute_lua(

crates/codegraph-core/src/db/connection.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -880,10 +880,13 @@ impl NativeDatabase {
880880
let insert_ok = insert_nodes::do_insert_nodes(conn, &batches, &removed_files)
881881
.inspect_err(|e| eprintln!("[NativeDatabase] bulk_insert_nodes failed: {e}"))
882882
.is_ok();
883+
if !insert_ok {
884+
return Ok(false);
885+
}
883886
let hashes_ok = insert_nodes::commit_file_hashes(conn, &file_hashes)
884887
.inspect_err(|e| eprintln!("[NativeDatabase] bulk_insert_nodes hash commit failed: {e}"))
885888
.is_ok();
886-
Ok(insert_ok && hashes_ok)
889+
Ok(hashes_ok)
887890
}
888891

889892
/// Bulk-insert edge rows using chunked multi-value INSERT statements.

crates/codegraph-core/src/domain/graph/builder/stages/build_edges.rs

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1626,6 +1626,16 @@ fn is_named_reexport(imp: &ImportInfo) -> bool {
16261626
imp.reexport && !imp.wildcard_reexport
16271627
}
16281628

1629+
/// True for a genuine wildcard re-export (`export * from 'Y'`). Emitted as a
1630+
/// distinct file-level marker edge (`reexports-wildcard`) alongside the
1631+
/// generic `reexports` edge so the query layer can tell a target reached
1632+
/// only by named specifiers apart from one that's also reached by a
1633+
/// wildcard — even when a *different* statement in the same file names
1634+
/// specific symbols from that exact target (#1849 review).
1635+
fn is_wildcard_reexport(imp: &ImportInfo) -> bool {
1636+
imp.reexport && imp.wildcard_reexport
1637+
}
1638+
16291639
/// For a `type` import or a named re-export targeting a barrel or resolved
16301640
/// file, emit one symbol-level edge per named symbol so the target symbols
16311641
/// receive fan-in credit and aren't misclassified as dead code
@@ -1760,6 +1770,15 @@ fn process_single_import(
17601770
}
17611771
if is_named_reexport(imp) {
17621772
emit_named_symbol_edges(edges, file_input, imp, resolved_path, "reexports", ctx);
1773+
} else if is_wildcard_reexport(imp) {
1774+
edges.push(ComputedEdge {
1775+
source_id: file_input.file_node_id,
1776+
target_id: target_node_id,
1777+
kind: "reexports-wildcard".to_string(),
1778+
confidence: 1.0,
1779+
dynamic: 0,
1780+
dynamic_kind: None,
1781+
});
17631782
}
17641783
emit_barrel_through_edges(edges, file_input, imp, resolved_path, edge_kind, ctx);
17651784
}
@@ -1866,9 +1885,12 @@ mod import_edge_tests {
18661885

18671886
#[test]
18681887
fn wildcard_reexport_emits_no_symbol_level_edge() {
1869-
// `export * from './utils'` carries no specific names, so only the
1870-
// file-level `reexports` edge is emitted — the query layer falls
1871-
// back to the target's full export list for genuine wildcards.
1888+
// `export * from './utils'` carries no specific names, so no
1889+
// symbol-level edge is emitted. It does get the dedicated
1890+
// `reexports-wildcard` file-level marker (alongside the generic
1891+
// `reexports` edge) so the query layer can always apply full-export
1892+
// semantics for genuine wildcards, even when a *different* statement
1893+
// to the same target also names specific symbols (#1849 review).
18721894
let files = vec![make_file("src/index.ts", 1, vec![
18731895
ImportInfo {
18741896
source: "./utils".to_string(),
@@ -1896,9 +1918,61 @@ mod import_edge_tests {
18961918
"/root".to_string(),
18971919
Some(symbol_nodes),
18981920
);
1899-
assert_eq!(edges.len(), 1);
1921+
assert_eq!(edges.len(), 2);
19001922
assert_eq!(edges[0].kind, "reexports");
19011923
assert_eq!(edges[0].target_id, 2);
1924+
assert_eq!(edges[1].kind, "reexports-wildcard");
1925+
assert_eq!(edges[1].target_id, 2);
1926+
}
1927+
1928+
#[test]
1929+
fn named_and_wildcard_reexport_of_same_target_both_marked() {
1930+
// `export { foo } from './utils'` AND `export * from './utils'` in
1931+
// the same file, both targeting utils.ts. The wildcard's full-export
1932+
// semantics must stay independently signalled (via the dedicated
1933+
// `reexports-wildcard` marker) rather than being suppressed by the
1934+
// named specifier's symbol-level edge — otherwise the query layer
1935+
// would report only `foo` and silently drop every other export of
1936+
// utils.ts that the wildcard was meant to surface (#1849 review).
1937+
let files = vec![make_file("src/index.ts", 1, vec![
1938+
make_import("./utils", vec!["foo"], true, false, false),
1939+
ImportInfo {
1940+
source: "./utils".to_string(),
1941+
names: vec![],
1942+
reexport: true,
1943+
type_only: false,
1944+
dynamic_import: false,
1945+
wildcard_reexport: true,
1946+
},
1947+
], vec![])];
1948+
let resolved = vec![make_resolved("/root/src/index.ts", "./utils", "src/utils.ts")];
1949+
let node_ids = vec![make_node_entry("src/index.ts", 1), make_node_entry("src/utils.ts", 2)];
1950+
let symbol_nodes = vec![SymbolNodeEntry {
1951+
name: "foo".to_string(),
1952+
file: "src/utils.ts".to_string(),
1953+
node_id: 99,
1954+
}];
1955+
1956+
let edges = build_import_edges(
1957+
files,
1958+
resolved,
1959+
vec![],
1960+
node_ids,
1961+
vec![],
1962+
"/root".to_string(),
1963+
Some(symbol_nodes),
1964+
);
1965+
assert_eq!(edges.len(), 4);
1966+
// Named statement: file-level `reexports` + symbol-level `reexports` to foo.
1967+
assert_eq!(edges[0].kind, "reexports");
1968+
assert_eq!(edges[0].target_id, 2);
1969+
assert_eq!(edges[1].kind, "reexports");
1970+
assert_eq!(edges[1].target_id, 99);
1971+
// Wildcard statement: file-level `reexports` + the `reexports-wildcard` marker.
1972+
assert_eq!(edges[2].kind, "reexports");
1973+
assert_eq!(edges[2].target_id, 2);
1974+
assert_eq!(edges[3].kind, "reexports-wildcard");
1975+
assert_eq!(edges[3].target_id, 2);
19021976
}
19031977

19041978
#[test]

crates/codegraph-core/src/domain/graph/builder/stages/import_edges.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,17 @@ fn is_named_reexport(imp: &crate::types::Import) -> bool {
266266
imp.reexport.unwrap_or(false) && !imp.wildcard_reexport.unwrap_or(false)
267267
}
268268

269+
/// True for a genuine wildcard re-export (`export * from 'Y'`). Emitted as a
270+
/// distinct file-level marker edge (`reexports-wildcard`) alongside the
271+
/// generic `reexports` edge so the query layer can tell a target reached
272+
/// only by named specifiers apart from one that's also reached by a
273+
/// wildcard — even when a *different* statement in the same file names
274+
/// specific symbols from that exact target (#1849 review). Mirrors
275+
/// `is_wildcard_reexport` in build_edges.rs (FFI fallback path).
276+
fn is_wildcard_reexport(imp: &crate::types::Import) -> bool {
277+
imp.reexport.unwrap_or(false) && imp.wildcard_reexport.unwrap_or(false)
278+
}
279+
269280
/// Walk type-only imports and named re-exports in `ctx.file_symbols` and
270281
/// return the distinct `(name, file)` pairs that `build_import_edges` will
271282
/// need to look up. Resolves barrel files the same way the edge-building
@@ -450,6 +461,14 @@ fn emit_edges_for_import(
450461
ctx,
451462
symbol_node_ids,
452463
);
464+
} else if is_wildcard_reexport(imp) {
465+
edges.push(EdgeRow {
466+
source_id: file_node_id,
467+
target_id,
468+
kind: "reexports-wildcard".to_string(),
469+
confidence: 1.0,
470+
dynamic: 0,
471+
});
453472
}
454473
emit_barrel_through_rows(
455474
edges,

crates/codegraph-core/src/domain/graph/resolve.rs

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,22 @@ fn ancestor_chain(dir: &str) -> Vec<String> {
260260
chain
261261
}
262262

263+
// directory_distance is on the hot path for every call-edge confidence
264+
// score, invoked from inside compute_confidence's rayon `.par_iter()` caller
265+
// (line ~330 below). The same directory pairs recur constantly across a
266+
// build, so memoizing avoids rebuilding both ancestor chains and the lookup
267+
// map every call. Thread-local (not a shared Mutex/DashMap) because rayon's
268+
// worker pool is reused across the whole build — each worker accumulates its
269+
// own useful cache with zero lock contention, at the cost of some redundant
270+
// computation the first time a given pair is seen on each thread.
271+
// distance(a, b) === distance(b, a) (symmetric tree distance), so the key is
272+
// order-independent to halve the effective cache size per thread (#1769
273+
// perf regression).
274+
thread_local! {
275+
static DIRECTORY_DISTANCE_CACHE: std::cell::RefCell<std::collections::HashMap<(String, String), usize>> =
276+
std::cell::RefCell::new(std::collections::HashMap::new());
277+
}
278+
263279
/// Directory-tree distance between two directories: hops up from `a` to the
264280
/// nearest ancestor shared with `b`, plus hops down from there to `b`.
265281
///
@@ -272,14 +288,24 @@ fn ancestor_chain(dir: &str) -> Vec<String> {
272288
/// so e.g. a file in `graph/algorithms/*.rs` calling a method declared in
273289
/// the shallower `graph/model.rs` was scored as maximally distant (issue #1769).
274290
fn directory_distance(a: &str, b: &str) -> usize {
291+
let key = if a <= b { (a.to_string(), b.to_string()) } else { (b.to_string(), a.to_string()) };
292+
if let Some(cached) = DIRECTORY_DISTANCE_CACHE.with(|c| c.borrow().get(&key).copied()) {
293+
return cached;
294+
}
295+
275296
let chain_a = ancestor_chain(a);
276297
let chain_b = ancestor_chain(b);
298+
let index_in_b: std::collections::HashMap<&str, usize> =
299+
chain_b.iter().enumerate().map(|(j, d)| (d.as_str(), j)).collect();
300+
let mut dist = usize::MAX;
277301
for (i, dir_a) in chain_a.iter().enumerate() {
278-
if let Some(j) = chain_b.iter().position(|dir_b| dir_b == dir_a) {
279-
return i + j;
302+
if let Some(&j) = index_in_b.get(dir_a.as_str()) {
303+
dist = i + j;
304+
break;
280305
}
281306
}
282-
usize::MAX
307+
DIRECTORY_DISTANCE_CACHE.with(|c| c.borrow_mut().insert(key, dist));
308+
dist
283309
}
284310

285311
/// Coarse "language family" for a file, derived from its extension via
@@ -291,8 +317,21 @@ fn directory_distance(a: &str, b: &str) -> usize {
291317
/// separate families would reject huge amounts of legitimate same-project
292318
/// resolution. Every other `LanguageKind` variant keeps its own family,
293319
/// preserving `from_extension`'s existing per-language extension groupings
294-
/// (e.g. C's `.c`+`.h`, C++'s `.cpp`/`.cc`/`.cxx`/`.hpp`).
320+
/// (e.g. C's `.c`+`.h`, C++'s `.cpp`/`.cc`/`.cxx`/`.hpp`) — EXCEPT `.h`,
321+
/// treated as ambiguous (returns `None`) rather than inheriting
322+
/// `from_extension`'s C-only mapping: `from_extension` needs one canonical
323+
/// grammar per extension, but a `.h` header is real-world ambiguous between
324+
/// C and C++, and the extremely common case of a `.cpp` file calling into
325+
/// its own project's `.h` header would otherwise be misclassified as
326+
/// cross-language and rejected outright — a real regression from the
327+
/// pre-#1783 same-directory score of 0.7 (Greptile review). This keeps the
328+
/// C/C++-header case working without merging C and C++ source-file families
329+
/// wholesale (`.c` vs `.cpp` intentionally do NOT merge — see
330+
/// is_same_language_family_does_not_merge_c_and_cpp).
295331
fn language_family(file: &str) -> Option<LanguageKind> {
332+
if file.to_ascii_lowercase().ends_with(".h") {
333+
return None;
334+
}
296335
match LanguageKind::from_extension(file) {
297336
Some(LanguageKind::TypeScript) | Some(LanguageKind::Tsx) => Some(LanguageKind::JavaScript),
298337
other => other,
@@ -609,6 +648,15 @@ mod tests {
609648
assert!(is_same_language_family("src/a.c", "src/a.h"));
610649
}
611650

651+
#[test]
652+
fn is_same_language_family_treats_h_as_ambiguous_with_cpp() {
653+
// Greptile follow-up to #1783: `.h` is real-world ambiguous between C
654+
// and C++ (LANGUAGE_REGISTRY/from_extension assigns it to C alone for
655+
// grammar-selection purposes), so a `.cpp` file calling into its own
656+
// project's `.h` header must not be rejected as cross-language.
657+
assert!(is_same_language_family("src/widget.cpp", "src/widget.h"));
658+
}
659+
612660
#[test]
613661
fn is_same_language_family_merges_cpp_source_and_header_variants() {
614662
assert!(is_same_language_family("src/a.cpp", "src/a.hpp"));

crates/codegraph-core/src/extractors/javascript.rs

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,6 +2335,11 @@ const HTTP_VERB_CALLEES: &[&str] = &[
23352335
/// separate `CALLBACK_ACCEPTING_CALLEES` entry needed); only the arg at its
23362336
/// listed index is eligible.
23372337
///
2338+
/// Invariant: this map and `CALLBACK_ACCEPTING_CALLEES` must stay disjoint.
2339+
/// A callee name present in both would have its any-position intent silently
2340+
/// narrowed to the single listed index (positional wins — see the gate in
2341+
/// `extract_callback_reference_calls`), with no error or warning.
2342+
///
23382343
/// Name-based, not receiver-typed, so it can't distinguish `Array.from(x,
23392344
/// mapFn)` from an unrelated `.from(x, y)` shaped differently (e.g.
23402345
/// `Buffer.from(data, encoding)`) — that residual risk is far narrower than
@@ -3076,13 +3081,19 @@ fn find_parent_class_no_fn_boundary(node: &Node, source: &[u8]) -> Option<String
30763081

30773082
/// Wrapper node kinds that can sit between a dynamic `import()` call and its
30783083
/// enclosing `variable_declarator` without changing which value gets bound —
3079-
/// `await`, redundant parentheses, and TypeScript `as` casts. Real-world call
3080-
/// sites often combine several of these, e.g.
3084+
/// `await`, redundant parentheses, and TypeScript `as`/`satisfies` casts.
3085+
/// Real-world call sites often combine several of these, e.g.
30813086
/// `const { X } = (await import('./mod.js')) as { X: Fn }` nests
30823087
/// await_expression → parenthesized_expression → as_expression before
3083-
/// reaching the declarator (#1781).
3084-
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] =
3085-
&["await_expression", "parenthesized_expression", "as_expression"];
3088+
/// reaching the declarator (#1781). `satisfies_expression` (TS 4.9+
3089+
/// `... satisfies { X: Fn }`) is structurally identical to `as_expression`
3090+
/// here — Greptile follow-up, mirrors the TS extractor.
3091+
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] = &[
3092+
"await_expression",
3093+
"parenthesized_expression",
3094+
"as_expression",
3095+
"satisfies_expression",
3096+
];
30863097

30873098
/// Extract named bindings from a dynamic `import()` call expression.
30883099
/// Handles: `const { a, b } = await import(...)`, `const mod = await import(...)`,
@@ -4285,6 +4296,17 @@ mod tests {
42854296
assert!(dyn_imports[0].names.contains(&"b".to_string()));
42864297
}
42874298

4299+
#[test]
4300+
fn finds_dynamic_import_with_satisfies_cast_destructuring() {
4301+
// TS 4.9+ `satisfies` is structurally identical to `as` here (Greptile
4302+
// follow-up to #1781) — same walk-up gap would otherwise reproduce.
4303+
let s = parse_ts("const { a, b } = await import('./foo.js') satisfies { a: Fn; b: Fn };");
4304+
let dyn_imports: Vec<_> = s.imports.iter().filter(|i| i.dynamic_import == Some(true)).collect();
4305+
assert_eq!(dyn_imports.len(), 1);
4306+
assert!(dyn_imports[0].names.contains(&"a".to_string()));
4307+
assert!(dyn_imports[0].names.contains(&"b".to_string()));
4308+
}
4309+
42884310
#[test]
42894311
fn finds_dynamic_import_with_parenthesized_as_cast_destructuring() {
42904312
// Exact repro shape from #1781 (native-orchestrator.ts):
@@ -4731,6 +4753,39 @@ mod tests {
47314753
);
47324754
}
47334755

4756+
#[test]
4757+
fn applies_array_from_positional_gate_to_member_expression_args_too() {
4758+
// Mirrors the TS test of the same intent: the old member_expression
4759+
// guard was an explicit `&& memberExprArgsAllowed` inline check; the
4760+
// positional restructuring moved that responsibility to the shared
4761+
// early-return above the loop. `Array.from(arr, obj.mapper)` exercises
4762+
// that a member_expression at the positional index (1) is still
4763+
// emitted with its receiver, while one at index 0 is not.
4764+
let s = parse_js("Array.from(arr, obj.mapper);");
4765+
assert!(
4766+
s.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "mapper" && c.receiver.as_deref() == Some("obj")),
4767+
"Array.from(arr, obj.mapper) must emit mapper with receiver obj; got: {:?}",
4768+
s.calls,
4769+
);
4770+
assert!(
4771+
!s.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "arr"),
4772+
"Array.from(arr, obj.mapper) must not emit `arr` (index 0); got: {:?}",
4773+
s.calls,
4774+
);
4775+
4776+
let s2 = parse_js("Array.from(obj.arrayLike, mapCallback);");
4777+
assert!(
4778+
!s2.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "arrayLike"),
4779+
"Array.from(obj.arrayLike, mapCallback) must not emit `arrayLike` (index 0); got: {:?}",
4780+
s2.calls,
4781+
);
4782+
assert!(
4783+
s2.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "mapCallback"),
4784+
"Array.from(obj.arrayLike, mapCallback) must emit mapCallback; got: {:?}",
4785+
s2.calls,
4786+
);
4787+
}
4788+
47344789
#[test]
47354790
fn no_dynamic_call_for_dynamic_import_arg() {
47364791
// Parity with TS walk path: callback-reference extraction must be skipped

0 commit comments

Comments
 (0)