1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! Test-to-code mapping: link tests to tested symbols, identify untested public functions.
use super::EnrichResult;
use crate::CodememEngine;
use codemem_core::{CodememError, Edge, GraphNode, NodeKind, RelationshipType};
use serde_json::json;
use std::collections::{HashMap, HashSet};
impl CodememEngine {
/// Map test functions to the code they test and identify untested public functions.
///
/// For Test-kind nodes, infers tested symbols by naming convention (`test_foo` -> `foo`)
/// and by CALLS edges. Creates RELATES_TO edges between test and tested symbols.
/// Produces Insight memories for files with untested public functions.
pub fn enrich_test_mapping(
&self,
namespace: Option<&str>,
) -> Result<EnrichResult, CodememError> {
let all_nodes;
let mut test_edges_info: Vec<(String, String)> = Vec::new();
{
let graph = self.lock_graph()?;
all_nodes = graph.get_all_nodes();
// Collect test nodes and non-test function/method nodes
let test_nodes: Vec<&GraphNode> = all_nodes
.iter()
.filter(|n| n.kind == NodeKind::Test)
.collect();
// Index by simple name (last segment of qualified name)
let mut fn_by_simple_name: HashMap<String, Vec<&GraphNode>> = HashMap::new();
for node in all_nodes
.iter()
.filter(|n| matches!(n.kind, NodeKind::Function | NodeKind::Method))
{
let simple = node
.label
.rsplit("::")
.next()
.unwrap_or(&node.label)
.to_string();
fn_by_simple_name.entry(simple).or_default().push(node);
}
for test_node in &test_nodes {
// Extract what this test might be testing from its name
let test_name = test_node
.label
.rsplit("::")
.next()
.unwrap_or(&test_node.label);
// Convention: test_foo tests foo, test_foo_bar tests foo_bar
let tested_name = test_name
.strip_prefix("test_")
.or_else(|| test_name.strip_prefix("test"))
.unwrap_or("");
if !tested_name.is_empty() {
// Check by simple name
if let Some(targets) = fn_by_simple_name.get(tested_name) {
for target in targets {
test_edges_info.push((test_node.id.clone(), target.id.clone()));
}
}
}
// Also check CALLS edges from the test to find tested symbols
if let Ok(edges) = graph.get_edges(&test_node.id) {
for edge in &edges {
if edge.relationship == RelationshipType::Calls && edge.src == test_node.id
{
// Only link to function/method nodes
if let Ok(Some(dst_node)) = graph.get_node(&edge.dst) {
if matches!(dst_node.kind, NodeKind::Function | NodeKind::Method) {
test_edges_info
.push((test_node.id.clone(), dst_node.id.clone()));
}
}
}
}
}
}
}
// Dedup edges
let unique_edges: HashSet<(String, String)> = test_edges_info.into_iter().collect();
// Create RELATES_TO edges for test mappings
let mut edges_created = 0;
{
let mut graph = self.lock_graph()?;
let now = chrono::Utc::now();
for (test_id, target_id) in &unique_edges {
let edge_id = format!("test-map:{test_id}->{target_id}");
// Skip if edge already exists
if graph.get_node(test_id).ok().flatten().is_none()
|| graph.get_node(target_id).ok().flatten().is_none()
{
continue;
}
let edge = Edge {
id: edge_id,
src: test_id.clone(),
dst: target_id.clone(),
relationship: RelationshipType::RelatesTo,
weight: 0.8,
properties: HashMap::from([("test_mapping".into(), json!(true))]),
created_at: now,
valid_from: None,
valid_to: None,
};
let _ = self.storage.insert_graph_edge(&edge);
if graph.add_edge(edge).is_ok() {
edges_created += 1;
}
}
}
// Identify untested public functions per file
let tested_ids: HashSet<String> = unique_edges.iter().map(|(_, t)| t.clone()).collect();
let mut untested_by_file: HashMap<String, Vec<String>> = HashMap::new();
for node in &all_nodes {
if !matches!(node.kind, NodeKind::Function | NodeKind::Method) {
continue;
}
let visibility = node
.payload
.get("visibility")
.and_then(|v| v.as_str())
.unwrap_or("private");
if visibility != "public" {
continue;
}
if tested_ids.contains(&node.id) {
continue;
}
let file_path = node
.payload
.get("file_path")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
untested_by_file
.entry(file_path)
.or_default()
.push(node.label.clone());
}
let mut insights_stored = 0;
for (file_path, untested) in &untested_by_file {
if untested.is_empty() {
continue;
}
let names: Vec<&str> = untested.iter().take(10).map(|s| s.as_str()).collect();
let suffix = if untested.len() > 10 {
format!(" (and {} more)", untested.len() - 10)
} else {
String::new()
};
let content = format!(
"Untested public functions in {}: {}{}",
file_path,
names.join(", "),
suffix
);
if self
.store_insight(
&content,
"testing",
&[],
0.6,
namespace,
&[format!("file:{file_path}")],
)
.is_some()
{
insights_stored += 1;
}
}
self.save_index();
Ok(EnrichResult {
insights_stored,
details: json!({
"test_edges_created": edges_created,
"files_with_untested": untested_by_file.len(),
"insights_stored": insights_stored,
}),
})
}
}