Skip to content

Commit 306ce69

Browse files
committed
fix: resolve merge conflicts with main (docs check acknowledged)
Confirmed the deletion of the old classic-Louvain louvain.rs: main independently added a HashMap->BTreeMap determinism fix there (#1734), but the new leiden.rs port already has its own, more thorough determinism guarantee (explicit index-ordering plus its own #1734 regression test), so nothing is lost. tests/graph/algorithms/louvain.test.ts needed manual reconstruction: git's line-based diff conflated this PR's buildTieGraph/determinism tests with main's structurally-similar buildTwoClusterGraph/parity tests (near-duplicate bodies), producing a corrupted auto-merge that looked resolvable by taking one side but silently duplicated content. Rebuilt from separate clean reads of both branch tips instead. Impact: 47 functions changed, 183 affected
2 parents e7a2255 + 9978678 commit 306ce69

59 files changed

Lines changed: 1521 additions & 296 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: 86 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -791,13 +791,14 @@ fn process_file<'a>(
791791
// of these positions is as likely to be a plain data reference
792792
// (`{ name: SOME_CONSTANT }`) as a real function/class, so drop any
793793
// other-kind match rather than fabricating a "calls" edge to a
794-
// constant. `class` is included alongside function/method because
795-
// `instanceof`'s right operand is always a class/constructor
796-
// (#1784) — unlike the original #1771 object-literal case, which is
797-
// function/method only. Applied once here (after all
798-
// resolve_call_targets tiers), mirroring the
799-
// `dynamicKind === 'value-ref'` filter in resolveFallbackTargets
800-
// (stages/build-edges.ts).
794+
// constant. `class` was added because `instanceof`'s right operand
795+
// is always a class/constructor (#1784). The filter is keyed on
796+
// `dynamic_kind`, not on which site produced the call, so the #1771
797+
// object-literal and #1776 Lua sites also gain class-kind
798+
// resolution as a side effect — not because either idiom commonly
799+
// names a class. Applied once here (after all resolve_call_targets
800+
// tiers), mirroring the `dynamicKind === 'value-ref'` filter in
801+
// resolveFallbackTargets (stages/build-edges.ts).
801802
if call.dynamic_kind.as_deref() == Some("value-ref") {
802803
targets.retain(|t| t.kind == "function" || t.kind == "method" || t.kind == "class");
803804
}
@@ -1626,6 +1627,16 @@ fn is_named_reexport(imp: &ImportInfo) -> bool {
16261627
imp.reexport && !imp.wildcard_reexport
16271628
}
16281629

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

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

19041979
#[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"));

0 commit comments

Comments
 (0)