1use anyhow::{Context, Result};
19use serde::Deserialize;
20use std::collections::HashMap;
21
22use crate::cache::CacheManager;
23use crate::models::SearchResult;
24
25const ANCHOR_SYMBOLS_PER_MODULE: usize = 5;
27
28const MAX_MODULES_IN_EVIDENCE: usize = 25;
31
32#[derive(Debug, Clone)]
34pub struct Concept {
35 pub name: String,
37 pub definition: String,
39 pub related_modules: Vec<String>,
42 pub category: Option<String>,
44}
45
46#[derive(Debug, Clone, Default)]
48pub struct GlossaryData {
49 pub concepts: Vec<Concept>,
50 pub intro: Option<String>,
52}
53
54#[derive(Debug, Clone)]
56pub struct ModuleEvidence {
57 pub path: String,
59 pub file_count: usize,
61 pub anchor_symbols: Vec<String>,
63}
64
65#[derive(Debug, Clone, Default)]
67pub struct GlossaryEvidence {
68 pub total_files: usize,
69 pub total_lines: usize,
70 pub language_mix: Vec<(String, usize)>,
71 pub dependency_edges: usize,
72 pub hotspot_files: Vec<String>,
73 pub modules: Vec<ModuleEvidence>,
74}
75
76#[derive(Debug, Clone, Deserialize)]
79pub struct ConceptsResponse {
80 #[serde(default)]
81 pub intro: Option<String>,
82 #[serde(default)]
83 pub concepts: Vec<RawConcept>,
84}
85
86#[derive(Debug, Clone, Deserialize)]
87pub struct RawConcept {
88 pub name: String,
89 #[serde(default)]
90 pub definition: String,
91 #[serde(default)]
92 pub category: Option<String>,
93 #[serde(default)]
94 pub related_modules: Vec<String>,
95}
96
97impl From<RawConcept> for Concept {
98 fn from(raw: RawConcept) -> Self {
99 Concept {
100 name: raw.name,
101 definition: raw.definition,
102 category: raw.category,
103 related_modules: raw.related_modules,
104 }
105 }
106}
107
108impl From<ConceptsResponse> for GlossaryData {
109 fn from(resp: ConceptsResponse) -> Self {
110 GlossaryData {
111 concepts: resp.concepts.into_iter().map(Into::into).collect(),
112 intro: resp.intro,
113 }
114 }
115}
116
117fn module_of(file_path: &str) -> String {
123 let parts: Vec<&str> = file_path.split('/').collect();
124 match parts.len() {
125 0 | 1 => String::new(),
126 2 => parts[0].to_string(),
127 _ => format!("{}/{}", parts[0], parts[1]),
128 }
129}
130
131fn module_slug(module_path: &str) -> String {
133 module_path.replace('/', "-")
134}
135
136fn anchor_priority(kind: &str) -> u8 {
141 match kind.to_lowercase().as_str() {
142 "struct" | "class" | "trait" | "interface" | "enum" | "type" | "typedef" => 0,
143 "function" | "method" | "macro" | "module" => 1,
144 "constant" | "property" | "event" | "attribute" | "export" => 2,
145 _ => 3,
148 }
149}
150
151pub fn collect_glossary_evidence(cache: &CacheManager) -> Result<Option<GlossaryEvidence>> {
158 let db_path = cache.path().join("meta.db");
159 let conn = crate::cache::open_meta_db(&db_path).context("Failed to open meta.db")?;
160
161 let has_symbols: bool = conn
162 .query_row(
163 "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='symbols'",
164 [],
165 |row| row.get::<_, i64>(0),
166 )
167 .map(|c| c > 0)
168 .unwrap_or(false);
169
170 if !has_symbols {
171 return Ok(None);
172 }
173
174 let total_files: usize = conn
175 .query_row("SELECT COUNT(*) FROM files", [], |r| r.get(0))
176 .unwrap_or(0);
177 let total_lines: usize = conn
178 .query_row("SELECT COALESCE(SUM(line_count), 0) FROM files", [], |r| {
179 r.get(0)
180 })
181 .unwrap_or(0);
182
183 let mut language_mix: Vec<(String, usize)> = Vec::new();
185 if let Ok(mut stmt) = conn.prepare(
186 "SELECT COALESCE(language, 'other'), COUNT(*) FROM files \
187 GROUP BY language ORDER BY COUNT(*) DESC LIMIT 10",
188 ) && let Ok(rows) = stmt.query_map([], |row| {
189 Ok((row.get::<_, String>(0)?, row.get::<_, usize>(1)?))
190 }) {
191 language_mix = rows.flatten().collect();
192 }
193
194 let dependency_edges: usize = conn
196 .query_row::<usize, _, _>("SELECT COUNT(*) FROM import_edges", [], |row| row.get(0))
197 .unwrap_or(0);
198
199 let mut hotspot_files: Vec<String> = Vec::new();
201 if dependency_edges > 0
202 && let Ok(mut stmt) = conn.prepare(
203 "SELECT f.path, COUNT(DISTINCT e.src) as dep_count, MIN(f.walk_seq) AS ws \
204 FROM import_edges e JOIN files f ON e.dst = f.id \
205 GROUP BY e.dst ORDER BY dep_count DESC, ws LIMIT 8",
206 )
207 && let Ok(rows) = stmt.query_map([], |row| row.get::<_, String>(0))
208 {
209 hotspot_files = rows.flatten().collect();
210 }
211
212 let mut stmt = conn.prepare(
216 "SELECT s.symbols_json, f.path, f.line_count \
217 FROM symbols s JOIN files f ON s.file_id = f.id AND s.file_hash = f.hash",
218 )?;
219 let rows: Vec<(Vec<u8>, String, usize)> = stmt
220 .query_map([], |row| {
221 Ok((
222 crate::symbol_cache::read_symbols_column(row, 0)?,
223 row.get::<_, String>(1)?,
224 row.get::<_, usize>(2).unwrap_or(0),
225 ))
226 })?
227 .filter_map(|r| r.ok())
228 .collect();
229
230 #[derive(Default)]
231 struct ModuleBucket {
232 file_count: usize,
233 candidates: Vec<(u8, String)>,
235 }
236
237 let mut by_module: HashMap<String, ModuleBucket> = HashMap::new();
238
239 for (symbols_json, file_path, _line_count) in rows {
240 let module = module_of(&file_path);
241 if module.is_empty() {
242 continue;
243 }
244 let bucket = by_module.entry(module.clone()).or_default();
245 bucket.file_count += 1;
246
247 let symbols: Vec<SearchResult> = match crate::symbol_cache::decode_symbols(&symbols_json) {
248 Ok(s) => s,
249 Err(_) => continue,
250 };
251
252 for sr in symbols {
253 let Some(name) = sr.symbol else { continue };
254 if name.len() < 3 {
255 continue;
256 }
257 let kind_str = sr.kind.to_string();
258 let kl = kind_str.to_lowercase();
260 if kl == "variable" || kl == "import" || kl == "export" || kl == "unknown" {
261 continue;
262 }
263 let priority = anchor_priority(&kind_str);
264 bucket.candidates.push((priority, name));
265 }
266 }
267
268 let mut modules: Vec<ModuleEvidence> = by_module
271 .into_iter()
272 .map(|(path, mut bucket)| {
273 bucket
274 .candidates
275 .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
276 let mut anchors: Vec<String> = Vec::new();
277 let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
278 for (_, name) in bucket.candidates {
279 if seen.insert(name.clone()) {
280 anchors.push(name);
281 if anchors.len() >= ANCHOR_SYMBOLS_PER_MODULE {
282 break;
283 }
284 }
285 }
286 ModuleEvidence {
287 path,
288 file_count: bucket.file_count,
289 anchor_symbols: anchors,
290 }
291 })
292 .collect();
293
294 modules.sort_by(|a, b| {
296 b.file_count
297 .cmp(&a.file_count)
298 .then_with(|| a.path.cmp(&b.path))
299 });
300 modules.truncate(MAX_MODULES_IN_EVIDENCE);
301
302 Ok(Some(GlossaryEvidence {
303 total_files,
304 total_lines,
305 language_mix,
306 dependency_edges,
307 hotspot_files,
308 modules,
309 }))
310}
311
312pub fn build_concepts_context(evidence: &GlossaryEvidence, project_name: &str) -> String {
316 let mut ctx = String::new();
317
318 ctx.push_str(&format!("Project: {}\n", project_name));
319 ctx.push_str(&format!(
320 "Scale: {} files, {} lines, {} modules, {} dependency edges\n",
321 evidence.total_files,
322 evidence.total_lines,
323 evidence.modules.len(),
324 evidence.dependency_edges,
325 ));
326
327 if !evidence.language_mix.is_empty() {
328 let langs: Vec<String> = evidence
329 .language_mix
330 .iter()
331 .map(|(lang, count)| format!("{} ({})", lang, count))
332 .collect();
333 ctx.push_str(&format!("Languages: {}\n", langs.join(", ")));
334 }
335 ctx.push('\n');
336
337 ctx.push_str("Top-level modules (with anchor symbol names):\n");
338 for m in &evidence.modules {
339 if m.anchor_symbols.is_empty() {
340 ctx.push_str(&format!("- {} ({} files)\n", m.path, m.file_count));
341 } else {
342 ctx.push_str(&format!(
343 "- {} ({} files) — key symbols: {}\n",
344 m.path,
345 m.file_count,
346 m.anchor_symbols.join(", ")
347 ));
348 }
349 }
350 ctx.push('\n');
351
352 if !evidence.hotspot_files.is_empty() {
353 ctx.push_str("Dependency hotspots (most-imported files):\n");
354 for path in &evidence.hotspot_files {
355 ctx.push_str(&format!("- {}\n", path));
356 }
357 ctx.push('\n');
358 }
359
360 ctx
361}
362
363pub fn parse_concepts_response(raw: &str) -> Result<ConceptsResponse> {
370 let trimmed = raw.trim();
371
372 let cleaned: &str = if let Some(rest) = trimmed.strip_prefix("```json") {
374 rest.trim_start().trim_end_matches("```").trim()
375 } else if let Some(rest) = trimmed.strip_prefix("```") {
376 rest.trim_start().trim_end_matches("```").trim()
377 } else {
378 trimmed
379 };
380
381 let slice = if cleaned.starts_with('{') {
384 cleaned
385 } else if let (Some(start), Some(end)) = (cleaned.find('{'), cleaned.rfind('}')) {
386 &cleaned[start..=end]
387 } else {
388 cleaned
389 };
390
391 serde_json::from_str::<ConceptsResponse>(slice)
392 .context("Failed to parse concepts JSON response from LLM")
393}
394
395pub fn render_glossary_markdown(data: &GlossaryData) -> String {
399 if data.concepts.is_empty() {
400 return "*Concepts are generated by the LLM narration pipeline. \
401 Re-run `rfx pulse generate` with LLM enabled to populate this page.*\n"
402 .to_string();
403 }
404
405 let mut md = String::new();
406
407 if let Some(ref intro) = data.intro {
408 md.push_str(intro.trim());
409 md.push_str("\n\n");
410 }
411
412 let mut order: Vec<String> = Vec::new();
415 let mut grouped: HashMap<String, Vec<&Concept>> = HashMap::new();
416 for concept in &data.concepts {
417 let cat = concept
418 .category
419 .clone()
420 .unwrap_or_else(|| "Concepts".to_string());
421 if !grouped.contains_key(&cat) {
422 order.push(cat.clone());
423 }
424 grouped.entry(cat).or_default().push(concept);
425 }
426
427 md.push_str(&format!(
428 "**{}** core concepts across {} {}.\n\n",
429 data.concepts.len(),
430 order.len(),
431 if order.len() == 1 {
432 "category"
433 } else {
434 "categories"
435 },
436 ));
437
438 for cat in &order {
439 md.push_str(&format!("## {}\n\n", cat));
440 if let Some(items) = grouped.get(cat) {
441 for concept in items {
442 md.push_str(&format!("### {}\n\n", concept.name));
443
444 for line in concept.definition.trim().lines() {
446 md.push_str("> ");
447 md.push_str(line);
448 md.push('\n');
449 }
450 md.push('\n');
451
452 if !concept.related_modules.is_empty() {
453 let links: Vec<String> = concept
454 .related_modules
455 .iter()
456 .map(|m| format!("[`{}`](/wiki/{}/)", m.trim(), module_slug(m.trim())))
457 .collect();
458 md.push_str(&format!("*Implemented in {}*\n\n", links.join(", ")));
459 }
460 }
461 }
462 }
463
464 md
465}
466
467pub fn render_glossary_no_llm(evidence: &GlossaryEvidence) -> String {
471 let mut md = String::new();
472 md.push_str(
473 "*Concepts are generated by the LLM narration pipeline. \
474 Re-run `rfx pulse generate` with LLM enabled to populate this page.*\n\n",
475 );
476
477 if evidence.modules.is_empty() {
478 return md;
479 }
480
481 md.push_str("**Modules in this codebase:**\n\n");
482 for m in &evidence.modules {
483 md.push_str(&format!(
484 "- [`{}`](/wiki/{}/) ({} files)\n",
485 m.path,
486 module_slug(&m.path),
487 m.file_count
488 ));
489 }
490 md.push('\n');
491 md
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497 use crate::cache::CacheManager;
498 use tempfile::TempDir;
499
500 fn empty_cache() -> (TempDir, CacheManager) {
501 let tmp = TempDir::new().unwrap();
502 let cache = CacheManager::new(tmp.path().to_str().unwrap());
503 cache.init().unwrap();
504 (tmp, cache)
505 }
506
507 #[test]
508 fn test_module_of() {
509 assert_eq!(module_of("src/models.rs"), "src");
510 assert_eq!(module_of("src/pulse/wiki.rs"), "src/pulse");
511 assert_eq!(module_of("src/parsers/rust/mod.rs"), "src/parsers");
512 assert_eq!(module_of("README.md"), "");
513 }
514
515 #[test]
516 fn test_module_slug() {
517 assert_eq!(module_slug("src"), "src");
518 assert_eq!(module_slug("src/pulse"), "src-pulse");
519 assert_eq!(module_slug("src/parsers/rust"), "src-parsers-rust");
520 }
521
522 #[test]
523 fn test_anchor_priority_orders_types_first() {
524 assert!(anchor_priority("struct") < anchor_priority("function"));
525 assert!(anchor_priority("trait") < anchor_priority("constant"));
526 assert!(anchor_priority("enum") < anchor_priority("variable"));
527 }
528
529 #[test]
530 fn test_collect_glossary_evidence_empty_cache() {
531 let (_tmp, cache) = empty_cache();
532 let result = collect_glossary_evidence(&cache).unwrap();
533 assert!(result.is_none());
535 }
536
537 #[test]
538 fn test_build_concepts_context_includes_modules() {
539 let evidence = GlossaryEvidence {
540 total_files: 120,
541 total_lines: 18_500,
542 language_mix: vec![("rust".to_string(), 110), ("toml".to_string(), 10)],
543 dependency_edges: 340,
544 hotspot_files: vec!["src/models.rs".to_string()],
545 modules: vec![
546 ModuleEvidence {
547 path: "src".to_string(),
548 file_count: 42,
549 anchor_symbols: vec![
550 "Cli".to_string(),
551 "SearchResult".to_string(),
552 "run".to_string(),
553 ],
554 },
555 ModuleEvidence {
556 path: "src/pulse".to_string(),
557 file_count: 18,
558 anchor_symbols: vec!["generate_site".to_string(), "PulseReport".to_string()],
559 },
560 ModuleEvidence {
561 path: "src/query".to_string(),
562 file_count: 9,
563 anchor_symbols: vec!["QueryEngine".to_string()],
564 },
565 ],
566 };
567 let ctx = build_concepts_context(&evidence, "Reflex");
568
569 assert!(ctx.contains("Project: Reflex"));
570 assert!(ctx.contains("120 files"));
571 assert!(ctx.contains("src (42 files)"));
572 assert!(ctx.contains("src/pulse"));
573 assert!(ctx.contains("src/query"));
574 assert!(ctx.contains("SearchResult"));
575 assert!(ctx.contains("QueryEngine"));
576 assert!(ctx.contains("Languages: rust (110)"));
577 assert!(ctx.contains("Dependency hotspots"));
578 }
579
580 #[test]
581 fn test_parse_concepts_response_valid_json() {
582 let raw = r#"{
583 "intro": "Reflex catalogs search primitives and indexing building blocks.",
584 "concepts": [
585 {
586 "name": "Trigram Index",
587 "category": "Core Capabilities",
588 "definition": "A fast inverted index built from three-character substrings.",
589 "related_modules": ["src/index", "src/query"]
590 },
591 {
592 "name": "Symbol Cache",
593 "category": "Data Model",
594 "definition": "A persistent store of parsed language symbols keyed by content hash.",
595 "related_modules": ["src/cache"]
596 }
597 ]
598 }"#;
599
600 let parsed = parse_concepts_response(raw).expect("should parse");
601 assert_eq!(parsed.concepts.len(), 2);
602 assert_eq!(parsed.concepts[0].name, "Trigram Index");
603 assert_eq!(
604 parsed.concepts[0].related_modules,
605 vec!["src/index", "src/query"]
606 );
607 assert!(parsed.intro.as_ref().unwrap().contains("search primitives"));
608 }
609
610 #[test]
611 fn test_parse_concepts_response_strips_markdown_fence() {
612 let raw = "```json\n{\"intro\":\"x\",\"concepts\":[]}\n```";
613 let parsed = parse_concepts_response(raw).expect("should parse");
614 assert_eq!(parsed.concepts.len(), 0);
615 assert_eq!(parsed.intro.as_deref(), Some("x"));
616 }
617
618 #[test]
619 fn test_parse_concepts_response_extracts_embedded_json() {
620 let raw = "Here is the output you requested:\n\
621 {\"intro\":\"y\",\"concepts\":[{\"name\":\"X\",\"definition\":\"d\"}]}\n\
622 Hope that helps!";
623 let parsed = parse_concepts_response(raw).expect("should parse");
624 assert_eq!(parsed.concepts.len(), 1);
625 assert_eq!(parsed.concepts[0].name, "X");
626 }
627
628 #[test]
629 fn test_parse_concepts_response_rejects_malformed() {
630 let raw = "this is definitely not JSON at all";
631 assert!(parse_concepts_response(raw).is_err());
632 }
633
634 #[test]
635 fn test_render_with_concepts() {
636 let data = GlossaryData {
637 intro: Some(
638 "Reflex catalogs the core pieces of a local code-search engine.".to_string(),
639 ),
640 concepts: vec![
641 Concept {
642 name: "Trigram Index".to_string(),
643 definition: "A fast inverted index built from three-character substrings."
644 .to_string(),
645 category: Some("Core Capabilities".to_string()),
646 related_modules: vec!["src/index".to_string(), "src/query".to_string()],
647 },
648 Concept {
649 name: "Symbol Cache".to_string(),
650 definition: "A persistent store of parsed language symbols.".to_string(),
651 category: Some("Data Model".to_string()),
652 related_modules: vec!["src/cache".to_string()],
653 },
654 ],
655 };
656
657 let md = render_glossary_markdown(&data);
658
659 assert!(md.contains("Reflex catalogs"));
661 assert!(md.contains("## Core Capabilities"));
662 assert!(md.contains("## Data Model"));
663 assert!(md.contains("### Trigram Index"));
664 assert!(md.contains("### Symbol Cache"));
665 assert!(md.contains("> A fast inverted index"));
666 assert!(md.contains("[`src/index`](/wiki/src-index/)"));
667 assert!(md.contains("[`src/query`](/wiki/src-query/)"));
668 assert!(md.contains("Implemented in"));
669
670 assert!(!md.contains("```rust"), "no signature code blocks");
672 assert!(!md.contains(":1"), "no file:line markers (cheap check)");
673 assert!(!md.contains("| Symbol | Kind"), "no flat table");
674 }
675
676 #[test]
677 fn test_render_no_llm_fallback() {
678 let data = GlossaryData::default();
679 let md = render_glossary_markdown(&data);
680 assert!(md.contains("LLM narration pipeline"));
681 assert!(md.contains("rfx pulse generate"));
682 }
683
684 #[test]
685 fn test_render_no_llm_fallback_with_evidence_lists_modules() {
686 let evidence = GlossaryEvidence {
687 total_files: 10,
688 total_lines: 500,
689 language_mix: vec![],
690 dependency_edges: 0,
691 hotspot_files: vec![],
692 modules: vec![
693 ModuleEvidence {
694 path: "src".to_string(),
695 file_count: 5,
696 anchor_symbols: vec![],
697 },
698 ModuleEvidence {
699 path: "src/pulse".to_string(),
700 file_count: 3,
701 anchor_symbols: vec![],
702 },
703 ],
704 };
705 let md = render_glossary_no_llm(&evidence);
706 assert!(md.contains("LLM narration pipeline"));
707 assert!(md.contains("[`src`](/wiki/src/)"));
708 assert!(md.contains("[`src/pulse`](/wiki/src-pulse/)"));
709 assert!(md.contains("(5 files)"));
710 }
711
712 #[test]
713 fn test_concepts_response_into_glossary_data() {
714 let resp = ConceptsResponse {
715 intro: Some("hi".to_string()),
716 concepts: vec![RawConcept {
717 name: "Concept".to_string(),
718 definition: "def".to_string(),
719 category: Some("Cat".to_string()),
720 related_modules: vec!["src".to_string()],
721 }],
722 };
723 let data: GlossaryData = resp.into();
724 assert_eq!(data.concepts.len(), 1);
725 assert_eq!(data.concepts[0].name, "Concept");
726 assert_eq!(data.intro.as_deref(), Some("hi"));
727 }
728}