Skip to content

Commit efd7a0c

Browse files
committed
fix: resolve merge conflicts with main
docs check acknowledged — conflict resolution only, no new functionality. Impact: 47 functions changed, 175 affected
2 parents af17b6d + 004cb3b commit efd7a0c

56 files changed

Lines changed: 1388 additions & 282 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
@@ -1621,6 +1621,16 @@ fn is_named_reexport(imp: &ImportInfo) -> bool {
16211621
imp.reexport && !imp.wildcard_reexport
16221622
}
16231623

1624+
/// True for a genuine wildcard re-export (`export * from 'Y'`). Emitted as a
1625+
/// distinct file-level marker edge (`reexports-wildcard`) alongside the
1626+
/// generic `reexports` edge so the query layer can tell a target reached
1627+
/// only by named specifiers apart from one that's also reached by a
1628+
/// wildcard — even when a *different* statement in the same file names
1629+
/// specific symbols from that exact target (#1849 review).
1630+
fn is_wildcard_reexport(imp: &ImportInfo) -> bool {
1631+
imp.reexport && imp.wildcard_reexport
1632+
}
1633+
16241634
/// For a `type` import or a named re-export targeting a barrel or resolved
16251635
/// file, emit one symbol-level edge per named symbol so the target symbols
16261636
/// receive fan-in credit and aren't misclassified as dead code
@@ -1755,6 +1765,15 @@ fn process_single_import(
17551765
}
17561766
if is_named_reexport(imp) {
17571767
emit_named_symbol_edges(edges, file_input, imp, resolved_path, "reexports", ctx);
1768+
} else if is_wildcard_reexport(imp) {
1769+
edges.push(ComputedEdge {
1770+
source_id: file_input.file_node_id,
1771+
target_id: target_node_id,
1772+
kind: "reexports-wildcard".to_string(),
1773+
confidence: 1.0,
1774+
dynamic: 0,
1775+
dynamic_kind: None,
1776+
});
17581777
}
17591778
emit_barrel_through_edges(edges, file_input, imp, resolved_path, edge_kind, ctx);
17601779
}
@@ -1861,9 +1880,12 @@ mod import_edge_tests {
18611880

18621881
#[test]
18631882
fn wildcard_reexport_emits_no_symbol_level_edge() {
1864-
// `export * from './utils'` carries no specific names, so only the
1865-
// file-level `reexports` edge is emitted — the query layer falls
1866-
// back to the target's full export list for genuine wildcards.
1883+
// `export * from './utils'` carries no specific names, so no
1884+
// symbol-level edge is emitted. It does get the dedicated
1885+
// `reexports-wildcard` file-level marker (alongside the generic
1886+
// `reexports` edge) so the query layer can always apply full-export
1887+
// semantics for genuine wildcards, even when a *different* statement
1888+
// to the same target also names specific symbols (#1849 review).
18671889
let files = vec![make_file("src/index.ts", 1, vec![
18681890
ImportInfo {
18691891
source: "./utils".to_string(),
@@ -1891,9 +1913,61 @@ mod import_edge_tests {
18911913
"/root".to_string(),
18921914
Some(symbol_nodes),
18931915
);
1894-
assert_eq!(edges.len(), 1);
1916+
assert_eq!(edges.len(), 2);
18951917
assert_eq!(edges[0].kind, "reexports");
18961918
assert_eq!(edges[0].target_id, 2);
1919+
assert_eq!(edges[1].kind, "reexports-wildcard");
1920+
assert_eq!(edges[1].target_id, 2);
1921+
}
1922+
1923+
#[test]
1924+
fn named_and_wildcard_reexport_of_same_target_both_marked() {
1925+
// `export { foo } from './utils'` AND `export * from './utils'` in
1926+
// the same file, both targeting utils.ts. The wildcard's full-export
1927+
// semantics must stay independently signalled (via the dedicated
1928+
// `reexports-wildcard` marker) rather than being suppressed by the
1929+
// named specifier's symbol-level edge — otherwise the query layer
1930+
// would report only `foo` and silently drop every other export of
1931+
// utils.ts that the wildcard was meant to surface (#1849 review).
1932+
let files = vec![make_file("src/index.ts", 1, vec![
1933+
make_import("./utils", vec!["foo"], true, false, false),
1934+
ImportInfo {
1935+
source: "./utils".to_string(),
1936+
names: vec![],
1937+
reexport: true,
1938+
type_only: false,
1939+
dynamic_import: false,
1940+
wildcard_reexport: true,
1941+
},
1942+
], vec![])];
1943+
let resolved = vec![make_resolved("/root/src/index.ts", "./utils", "src/utils.ts")];
1944+
let node_ids = vec![make_node_entry("src/index.ts", 1), make_node_entry("src/utils.ts", 2)];
1945+
let symbol_nodes = vec![SymbolNodeEntry {
1946+
name: "foo".to_string(),
1947+
file: "src/utils.ts".to_string(),
1948+
node_id: 99,
1949+
}];
1950+
1951+
let edges = build_import_edges(
1952+
files,
1953+
resolved,
1954+
vec![],
1955+
node_ids,
1956+
vec![],
1957+
"/root".to_string(),
1958+
Some(symbol_nodes),
1959+
);
1960+
assert_eq!(edges.len(), 4);
1961+
// Named statement: file-level `reexports` + symbol-level `reexports` to foo.
1962+
assert_eq!(edges[0].kind, "reexports");
1963+
assert_eq!(edges[0].target_id, 2);
1964+
assert_eq!(edges[1].kind, "reexports");
1965+
assert_eq!(edges[1].target_id, 99);
1966+
// Wildcard statement: file-level `reexports` + the `reexports-wildcard` marker.
1967+
assert_eq!(edges[2].kind, "reexports");
1968+
assert_eq!(edges[2].target_id, 2);
1969+
assert_eq!(edges[3].kind, "reexports-wildcard");
1970+
assert_eq!(edges[3].target_id, 2);
18971971
}
18981972

18991973
#[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: 29 additions & 3 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

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

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

30343039
/// Wrapper node kinds that can sit between a dynamic `import()` call and its
30353040
/// enclosing `variable_declarator` without changing which value gets bound —
3036-
/// `await`, redundant parentheses, and TypeScript `as` casts. Real-world call
3037-
/// sites often combine several of these, e.g.
3041+
/// `await`, redundant parentheses, and TypeScript `as`/`satisfies` casts.
3042+
/// Real-world call sites often combine several of these, e.g.
30383043
/// `const { X } = (await import('./mod.js')) as { X: Fn }` nests
30393044
/// await_expression → parenthesized_expression → as_expression before
3040-
/// reaching the declarator (#1781).
3041-
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] =
3042-
&["await_expression", "parenthesized_expression", "as_expression"];
3045+
/// reaching the declarator (#1781). `satisfies_expression` (TS 4.9+
3046+
/// `... satisfies { X: Fn }`) is structurally identical to `as_expression`
3047+
/// here — Greptile follow-up, mirrors the TS extractor.
3048+
const DYNAMIC_IMPORT_WRAPPER_KINDS: &[&str] = &[
3049+
"await_expression",
3050+
"parenthesized_expression",
3051+
"as_expression",
3052+
"satisfies_expression",
3053+
];
30433054

30443055
/// Extract named bindings from a dynamic `import()` call expression.
30453056
/// Handles: `const { a, b } = await import(...)`, `const mod = await import(...)`,
@@ -4242,6 +4253,17 @@ mod tests {
42424253
assert!(dyn_imports[0].names.contains(&"b".to_string()));
42434254
}
42444255

4256+
#[test]
4257+
fn finds_dynamic_import_with_satisfies_cast_destructuring() {
4258+
// TS 4.9+ `satisfies` is structurally identical to `as` here (Greptile
4259+
// follow-up to #1781) — same walk-up gap would otherwise reproduce.
4260+
let s = parse_ts("const { a, b } = await import('./foo.js') satisfies { a: Fn; b: Fn };");
4261+
let dyn_imports: Vec<_> = s.imports.iter().filter(|i| i.dynamic_import == Some(true)).collect();
4262+
assert_eq!(dyn_imports.len(), 1);
4263+
assert!(dyn_imports[0].names.contains(&"a".to_string()));
4264+
assert!(dyn_imports[0].names.contains(&"b".to_string()));
4265+
}
4266+
42454267
#[test]
42464268
fn finds_dynamic_import_with_parenthesized_as_cast_destructuring() {
42474269
// Exact repro shape from #1781 (native-orchestrator.ts):
@@ -4625,6 +4647,39 @@ mod tests {
46254647
);
46264648
}
46274649

4650+
#[test]
4651+
fn applies_array_from_positional_gate_to_member_expression_args_too() {
4652+
// Mirrors the TS test of the same intent: the old member_expression
4653+
// guard was an explicit `&& memberExprArgsAllowed` inline check; the
4654+
// positional restructuring moved that responsibility to the shared
4655+
// early-return above the loop. `Array.from(arr, obj.mapper)` exercises
4656+
// that a member_expression at the positional index (1) is still
4657+
// emitted with its receiver, while one at index 0 is not.
4658+
let s = parse_js("Array.from(arr, obj.mapper);");
4659+
assert!(
4660+
s.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "mapper" && c.receiver.as_deref() == Some("obj")),
4661+
"Array.from(arr, obj.mapper) must emit mapper with receiver obj; got: {:?}",
4662+
s.calls,
4663+
);
4664+
assert!(
4665+
!s.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "arr"),
4666+
"Array.from(arr, obj.mapper) must not emit `arr` (index 0); got: {:?}",
4667+
s.calls,
4668+
);
4669+
4670+
let s2 = parse_js("Array.from(obj.arrayLike, mapCallback);");
4671+
assert!(
4672+
!s2.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "arrayLike"),
4673+
"Array.from(obj.arrayLike, mapCallback) must not emit `arrayLike` (index 0); got: {:?}",
4674+
s2.calls,
4675+
);
4676+
assert!(
4677+
s2.calls.iter().any(|c| c.dynamic == Some(true) && c.name == "mapCallback"),
4678+
"Array.from(obj.arrayLike, mapCallback) must emit mapCallback; got: {:?}",
4679+
s2.calls,
4680+
);
4681+
}
4682+
46284683
#[test]
46294684
fn no_dynamic_call_for_dynamic_import_arg() {
46304685
// Parity with TS walk path: callback-reference extraction must be skipped

0 commit comments

Comments
 (0)