1use crate::core::content_chunk::ContentChunk;
15
16#[derive(Debug, Clone)]
18pub struct ExtractedFact {
19 pub origin: crate::core::knowledge::FactOrigin,
20 pub category: String,
21 pub key: String,
22 pub value: String,
23 pub confidence: f32,
24}
25
26pub fn extract_facts(chunks: &[ContentChunk]) -> Vec<ExtractedFact> {
28 let mut facts = Vec::new();
29
30 for chunk in chunks {
31 if !chunk.is_external() {
32 continue;
33 }
34
35 let provider = chunk.provider_id().unwrap_or("unknown");
36 let start = facts.len();
37 match chunk.kind {
38 crate::core::bm25_index::ChunkKind::Issue
39 | crate::core::bm25_index::ChunkKind::Ticket => {
40 extract_issue_facts(chunk, provider, &mut facts);
41 }
42 crate::core::bm25_index::ChunkKind::PullRequest => {
43 extract_pr_facts(chunk, provider, &mut facts);
44 }
45 crate::core::bm25_index::ChunkKind::WikiPage => {
46 extract_wiki_facts(chunk, provider, &mut facts);
47 }
48 crate::core::bm25_index::ChunkKind::DbSchema => {
49 extract_db_facts(chunk, provider, &mut facts);
50 }
51 _ => {}
52 }
53 for fact in &mut facts[start..] {
54 fact.origin = chunk
55 .origin
56 .clone()
57 .map_or(crate::core::knowledge::FactOrigin::Unverified, |origin| {
58 crate::core::knowledge::FactOrigin::Provider(Box::new(origin))
59 });
60 }
61 }
62
63 facts
64}
65
66fn extract_issue_facts(chunk: &ContentChunk, provider: &str, facts: &mut Vec<ExtractedFact>) {
67 let state = chunk
68 .metadata
69 .as_ref()
70 .and_then(|m| m["state"].as_str())
71 .unwrap_or("unknown");
72
73 let labels: Vec<&str> = chunk
74 .metadata
75 .as_ref()
76 .and_then(|m| m["labels"].as_array())
77 .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
78 .unwrap_or_default();
79
80 let category = if labels.iter().any(|l| {
81 let lower = l.to_lowercase();
82 lower.contains("bug") || lower.contains("defect")
83 }) {
84 "known_bugs"
85 } else if labels.iter().any(|l| {
86 let lower = l.to_lowercase();
87 lower.contains("feature") || lower.contains("enhancement")
88 }) {
89 "known_features"
90 } else {
91 "known_issues"
92 };
93
94 let issue_id = chunk
95 .file_path
96 .rsplit('/')
97 .next()
98 .unwrap_or(&chunk.file_path);
99
100 facts.push(ExtractedFact {
101 origin: crate::core::knowledge::FactOrigin::Unverified,
102 category: category.to_string(),
103 key: format!("{provider}#{issue_id}"),
104 value: format!("{} [{}]", chunk.symbol_name, state),
105 confidence: if state == "open" { 0.9 } else { 0.7 },
106 });
107
108 for ref_path in &chunk.references {
109 facts.push(ExtractedFact {
110 origin: crate::core::knowledge::FactOrigin::Unverified,
111 category: "file_mentions".to_string(),
112 key: ref_path.clone(),
113 value: format!(
114 "Referenced in {} {provider}#{issue_id}: {}",
115 category, chunk.symbol_name
116 ),
117 confidence: 0.85,
118 });
119 }
120}
121
122fn extract_pr_facts(chunk: &ContentChunk, provider: &str, facts: &mut Vec<ExtractedFact>) {
123 let state = chunk
124 .metadata
125 .as_ref()
126 .and_then(|m| m["state"].as_str())
127 .unwrap_or("unknown");
128
129 let pr_id = chunk
130 .file_path
131 .rsplit('/')
132 .next()
133 .unwrap_or(&chunk.file_path);
134
135 facts.push(ExtractedFact {
136 origin: crate::core::knowledge::FactOrigin::Unverified,
137 category: "recent_changes".to_string(),
138 key: format!("{provider}#PR{pr_id}"),
139 value: format!("{} [{}]", chunk.symbol_name, state),
140 confidence: if state == "open" { 0.95 } else { 0.8 },
141 });
142
143 for ref_path in &chunk.references {
144 facts.push(ExtractedFact {
145 origin: crate::core::knowledge::FactOrigin::Unverified,
146 category: "changed_files".to_string(),
147 key: ref_path.clone(),
148 value: format!("Changed in PR {provider}#{pr_id}: {}", chunk.symbol_name),
149 confidence: 0.9,
150 });
151 }
152}
153
154fn extract_wiki_facts(chunk: &ContentChunk, provider: &str, facts: &mut Vec<ExtractedFact>) {
155 let page_id = chunk
156 .file_path
157 .rsplit('/')
158 .next()
159 .unwrap_or(&chunk.file_path);
160
161 facts.push(ExtractedFact {
162 origin: crate::core::knowledge::FactOrigin::Unverified,
163 category: "documentation".to_string(),
164 key: format!("{provider}#{page_id}"),
165 value: chunk.symbol_name.clone(),
166 confidence: 0.85,
167 });
168
169 for ref_path in &chunk.references {
170 facts.push(ExtractedFact {
171 origin: crate::core::knowledge::FactOrigin::Unverified,
172 category: "documented_files".to_string(),
173 key: ref_path.clone(),
174 value: format!("Documented in {provider}#{page_id}: {}", chunk.symbol_name),
175 confidence: 0.8,
176 });
177 }
178}
179
180fn extract_db_facts(chunk: &ContentChunk, provider: &str, facts: &mut Vec<ExtractedFact>) {
181 let table_id = chunk
182 .file_path
183 .rsplit('/')
184 .next()
185 .unwrap_or(&chunk.file_path);
186
187 facts.push(ExtractedFact {
188 origin: crate::core::knowledge::FactOrigin::Unverified,
189 category: "data_model".to_string(),
190 key: format!("{provider}#{table_id}"),
191 value: chunk.symbol_name.clone(),
192 confidence: 0.95,
193 });
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199 use crate::core::bm25_index::ChunkKind;
200 use crate::core::content_chunk::ContentChunk;
201
202 fn issue_with_labels(id: &str, title: &str, labels: &[&str], refs: Vec<&str>) -> ContentChunk {
203 ContentChunk::from_provider(
204 "github",
205 "issues",
206 id,
207 title,
208 ChunkKind::Issue,
209 format!("Body of {title}"),
210 refs.into_iter().map(String::from).collect(),
211 Some(serde_json::json!({
212 "state": "open",
213 "labels": labels,
214 })),
215 )
216 }
217
218 #[test]
219 fn bug_label_creates_known_bugs_fact() {
220 let chunk = issue_with_labels("42", "Auth crash", &["bug", "p1"], vec!["src/auth.rs"]);
221 let facts = extract_facts(&[chunk]);
222
223 let bug_fact = facts.iter().find(|f| f.category == "known_bugs");
224 assert!(bug_fact.is_some());
225 assert!(bug_fact.unwrap().key.contains("42"));
226 assert!(bug_fact.unwrap().value.contains("Auth crash"));
227 assert!(bug_fact.unwrap().value.contains("[open]"));
228 }
229
230 #[test]
231 fn feature_label_creates_known_features_fact() {
232 let chunk = issue_with_labels("10", "Dark mode", &["enhancement"], vec![]);
233 let facts = extract_facts(&[chunk]);
234
235 assert!(facts.iter().any(|f| f.category == "known_features"));
236 }
237
238 #[test]
239 fn generic_issue_creates_known_issues_fact() {
240 let chunk = issue_with_labels("5", "Question about API", &["question"], vec![]);
241 let facts = extract_facts(&[chunk]);
242
243 assert!(facts.iter().any(|f| f.category == "known_issues"));
244 }
245
246 #[test]
247 fn issue_with_refs_creates_file_mentions() {
248 let chunk = issue_with_labels(
249 "42",
250 "Auth crash",
251 &["bug"],
252 vec!["src/auth.rs", "src/db.rs"],
253 );
254 let facts = extract_facts(&[chunk]);
255
256 let mentions: Vec<_> = facts
257 .iter()
258 .filter(|f| f.category == "file_mentions")
259 .collect();
260 assert_eq!(mentions.len(), 2);
261 assert!(mentions.iter().any(|f| f.key == "src/auth.rs"));
262 assert!(mentions.iter().any(|f| f.key == "src/db.rs"));
263 }
264
265 #[test]
266 fn pr_creates_recent_changes_and_changed_files() {
267 let chunk = ContentChunk::from_provider(
268 "github",
269 "pull_requests",
270 "100",
271 "Fix auth token expiry",
272 ChunkKind::PullRequest,
273 "Fixes token expiry".into(),
274 vec!["src/auth.rs".into()],
275 Some(serde_json::json!({"state": "open"})),
276 );
277
278 let facts = extract_facts(&[chunk]);
279 assert!(facts.iter().any(|f| f.category == "recent_changes"));
280 assert!(
281 facts
282 .iter()
283 .any(|f| f.category == "changed_files" && f.key == "src/auth.rs")
284 );
285 }
286
287 #[test]
288 fn wiki_creates_documentation_facts() {
289 let chunk = ContentChunk::from_provider(
290 "confluence",
291 "wikis",
292 "auth-guide",
293 "Authentication Guide",
294 ChunkKind::WikiPage,
295 "How auth works".into(),
296 vec!["src/auth/mod.rs".into()],
297 None,
298 );
299
300 let facts = extract_facts(&[chunk]);
301 assert!(facts.iter().any(|f| f.category == "documentation"));
302 assert!(facts.iter().any(|f| f.category == "documented_files"));
303 }
304
305 #[test]
306 fn db_creates_data_model_facts() {
307 let chunk = ContentChunk::from_provider(
308 "postgres",
309 "schemas",
310 "users",
311 "public.users",
312 ChunkKind::DbSchema,
313 "CREATE TABLE users (id serial, email varchar)".into(),
314 vec![],
315 None,
316 );
317
318 let facts = extract_facts(&[chunk]);
319 assert_eq!(facts.len(), 1);
320 assert_eq!(facts[0].category, "data_model");
321 assert_eq!(facts[0].confidence, 0.95);
322 }
323
324 #[test]
325 fn code_chunks_are_skipped() {
326 let chunk = ContentChunk::from(crate::core::bm25_index::CodeChunk {
327 file_path: "src/main.rs".into(),
328 symbol_name: "main".into(),
329 kind: ChunkKind::Function,
330 start_line: 1,
331 end_line: 5,
332 content: "fn main() {}".into(),
333 tokens: vec![],
334 token_count: 0,
335 });
336
337 let facts = extract_facts(&[chunk]);
338 assert!(facts.is_empty());
339 }
340
341 #[test]
342 fn closed_issues_have_lower_confidence() {
343 let chunk = ContentChunk::from_provider(
344 "github",
345 "issues",
346 "99",
347 "Old bug",
348 ChunkKind::Issue,
349 "Fixed".into(),
350 vec![],
351 Some(serde_json::json!({"state": "closed", "labels": ["bug"]})),
352 );
353
354 let facts = extract_facts(&[chunk]);
355 let fact = facts.iter().find(|f| f.category == "known_bugs").unwrap();
356 assert!(fact.confidence < 0.9);
357 }
358}