reflex-search 1.5.1

A local-first, structure-aware code search engine for AI agents
Documentation
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Git Intelligence: Timeline page with development activity history
//!
//! Extracts git log data to show recent activity, contributor patterns,
//! file churn, and weekly summaries.

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;

/// Complete git intelligence data
#[derive(Debug, Clone)]
pub struct GitIntel {
    pub commits: Vec<CommitInfo>,
    pub contributors: Vec<Contributor>,
    pub churn: Vec<FileChurn>,
    pub weekly_summaries: Vec<WeekSummary>,
    pub module_activity: Vec<ModuleActivity>,
    pub narration: Option<String>,
}

/// A single commit
#[derive(Debug, Clone)]
pub struct CommitInfo {
    pub hash: String,
    pub author: String,
    pub email: String,
    pub timestamp: i64,
    pub subject: String,
}

/// Contributor stats
#[derive(Debug, Clone)]
pub struct Contributor {
    pub name: String,
    pub email: String,
    pub commit_count: usize,
}

/// File churn: how often a file changes
#[derive(Debug, Clone)]
pub struct FileChurn {
    pub path: String,
    pub change_count: usize,
    pub primary_author: String,
}

/// Weekly activity summary
#[derive(Debug, Clone)]
pub struct WeekSummary {
    pub week_start: String,
    pub commit_count: usize,
    pub files_changed: usize,
    pub contributors: Vec<String>,
    pub top_modules: Vec<String>,
}

/// Per-module activity
#[derive(Debug, Clone)]
pub struct ModuleActivity {
    pub module_path: String,
    pub commit_count: usize,
    pub files_changed: usize,
    pub primary_contributor: String,
}

/// Extract git log data for the last 6 months
pub fn extract_git_intel(root: impl AsRef<Path>) -> Result<GitIntel> {
    let root = root.as_ref();

    // Check if this is a git repo
    if !root.join(".git").exists() {
        return Ok(GitIntel {
            commits: vec![],
            contributors: vec![],
            churn: vec![],
            weekly_summaries: vec![],
            module_activity: vec![],
            narration: None,
        });
    }

    let commits = extract_commits(root)?;
    let contributors = compute_contributors(&commits);
    let churn = extract_file_churn(root)?;
    let weekly_summaries = compute_weekly_summaries(root, &commits)?;
    let module_activity = compute_module_activity(&churn);

    Ok(GitIntel {
        commits,
        contributors,
        churn,
        weekly_summaries,
        module_activity,
        narration: None,
    })
}

/// Parse git log into commits
fn extract_commits(root: &Path) -> Result<Vec<CommitInfo>> {
    let output = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["log", "--format=%H|%an|%ae|%at|%s", "--since=6 months ago"])
        .output()
        .context("Failed to run git log")?;

    if !output.status.success() {
        return Ok(vec![]);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let commits: Vec<CommitInfo> = stdout
        .lines()
        .filter_map(|line| {
            let parts: Vec<&str> = line.splitn(5, '|').collect();
            if parts.len() < 5 {
                return None;
            }
            Some(CommitInfo {
                hash: parts[0].to_string(),
                author: parts[1].to_string(),
                email: parts[2].to_string(),
                timestamp: parts[3].parse().unwrap_or(0),
                subject: parts[4].to_string(),
            })
        })
        .collect();

    Ok(commits)
}

/// Compute contributor stats from commits (deduplicated by name)
fn compute_contributors(commits: &[CommitInfo]) -> Vec<Contributor> {
    let mut by_name: HashMap<String, (String, usize)> = HashMap::new();
    for commit in commits {
        let entry = by_name
            .entry(commit.author.clone())
            .or_insert_with(|| (commit.email.clone(), 0));
        entry.1 += 1;
    }

    let mut contributors: Vec<Contributor> = by_name
        .into_iter()
        .map(|(name, (email, count))| Contributor {
            name,
            email,
            commit_count: count,
        })
        .collect();

    contributors.sort_by(|a, b| b.commit_count.cmp(&a.commit_count));
    contributors
}

/// Extract file change frequency using git log --name-only
fn extract_file_churn(root: &Path) -> Result<Vec<FileChurn>> {
    // Get file change counts with author info
    let output = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["log", "--format=%an", "--name-only", "--since=6 months ago"])
        .output()
        .context("Failed to run git log --name-only")?;

    if !output.status.success() {
        return Ok(vec![]);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut file_counts: HashMap<String, usize> = HashMap::new();
    let mut file_authors: HashMap<String, HashMap<String, usize>> = HashMap::new();
    let mut current_author = String::new();

    for line in stdout.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Lines without path separators and not starting with spaces are author names
        // (from the %an format), file paths contain / or .
        if !trimmed.contains('/') && !trimmed.contains('.') && !trimmed.starts_with(' ') {
            current_author = trimmed.to_string();
        } else if !current_author.is_empty() {
            *file_counts.entry(trimmed.to_string()).or_default() += 1;
            *file_authors
                .entry(trimmed.to_string())
                .or_default()
                .entry(current_author.clone())
                .or_default() += 1;
        }
    }

    let mut churn: Vec<FileChurn> = file_counts
        .into_iter()
        .map(|(path, count)| {
            let primary = file_authors
                .get(&path)
                .and_then(|authors| authors.iter().max_by_key(|(_, c)| *c))
                .map(|(name, _)| name.clone())
                .unwrap_or_default();
            FileChurn {
                path,
                change_count: count,
                primary_author: primary,
            }
        })
        .collect();

    churn.sort_by(|a, b| b.change_count.cmp(&a.change_count));
    churn.truncate(50); // Top 50 most-changed files

    Ok(churn)
}

/// Compute weekly summaries from commits and file changes
fn compute_weekly_summaries(root: &Path, commits: &[CommitInfo]) -> Result<Vec<WeekSummary>> {
    if commits.is_empty() {
        return Ok(vec![]);
    }

    // Group commits by ISO week
    let mut weeks: HashMap<String, (usize, Vec<String>, HashMap<String, usize>)> = HashMap::new();

    for commit in commits {
        // Convert timestamp to week start date (Monday)
        let ts = commit.timestamp;
        // Simple week computation: round down to nearest Monday
        let days_since_epoch = ts / 86400;
        // 1970-01-01 was a Thursday (day 4), so Monday of that week = day -3
        let week_day = ((days_since_epoch + 3) % 7) as i64; // 0=Monday
        let monday = days_since_epoch - week_day;
        let week_key = format!("{}", monday); // Use epoch-day of Monday as key

        let entry = weeks
            .entry(week_key)
            .or_insert_with(|| (0, vec![], HashMap::new()));
        entry.0 += 1;
        if !entry.1.contains(&commit.author) {
            entry.1.push(commit.author.clone());
        }
    }

    // Get file changes per week (using git log with date ranges)
    // Instead of running git for each week, use the commit data we already have
    let output = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["log", "--format=%at", "--name-only", "--since=6 months ago"])
        .output();

    let mut week_files: HashMap<String, HashMap<String, bool>> = HashMap::new();

    if let Ok(output) = output {
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let mut current_ts: i64 = 0;
            for line in stdout.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue;
                }
                if let Ok(ts) = trimmed.parse::<i64>() {
                    current_ts = ts;
                } else if current_ts > 0 {
                    let days = current_ts / 86400;
                    let week_day = ((days + 3) % 7) as i64;
                    let monday = days - week_day;
                    let week_key = format!("{}", monday);
                    week_files
                        .entry(week_key)
                        .or_default()
                        .insert(trimmed.to_string(), true);
                }
            }
        }
    }

    // Build summaries
    let mut summaries: Vec<WeekSummary> = weeks
        .into_iter()
        .map(|(week_key, (count, contributors, _))| {
            let files_changed = week_files.get(&week_key).map(|f| f.len()).unwrap_or(0);

            // Compute top modules from changed files
            let mut module_counts: HashMap<String, usize> = HashMap::new();
            if let Some(files) = week_files.get(&week_key) {
                for file in files.keys() {
                    if let Some(module) = file.split('/').next() {
                        *module_counts.entry(module.to_string()).or_default() += 1;
                    }
                }
            }
            let mut top_modules: Vec<(String, usize)> = module_counts.into_iter().collect();
            top_modules.sort_by(|a, b| b.1.cmp(&a.1));
            let top_modules: Vec<String> =
                top_modules.into_iter().take(3).map(|(m, _)| m).collect();

            // Convert monday epoch-days back to date string
            let monday_days: i64 = week_key.parse().unwrap_or(0);
            let monday_ts = monday_days * 86400;
            let week_start = epoch_to_date_string(monday_ts);

            WeekSummary {
                week_start,
                commit_count: count,
                files_changed,
                contributors,
                top_modules,
            }
        })
        .collect();

    summaries.sort_by(|a, b| b.week_start.cmp(&a.week_start));
    summaries.truncate(12); // Last 12 weeks

    Ok(summaries)
}

/// Compute per-module activity from file churn
fn compute_module_activity(churn: &[FileChurn]) -> Vec<ModuleActivity> {
    let mut by_module: HashMap<String, (usize, usize, HashMap<String, usize>)> = HashMap::new();

    for file in churn {
        let module = file.path.split('/').next().unwrap_or("root").to_string();
        let entry = by_module.entry(module).or_default();
        entry.0 += file.change_count;
        entry.1 += 1;
        *entry.2.entry(file.primary_author.clone()).or_default() += file.change_count;
    }

    let mut activity: Vec<ModuleActivity> = by_module
        .into_iter()
        .map(|(module, (commits, files, authors))| {
            let primary = authors
                .into_iter()
                .max_by_key(|(_, c)| *c)
                .map(|(name, _)| name)
                .unwrap_or_default();
            ModuleActivity {
                module_path: module,
                commit_count: commits,
                files_changed: files,
                primary_contributor: primary,
            }
        })
        .collect();

    activity.sort_by(|a, b| b.commit_count.cmp(&a.commit_count));
    activity
}

/// Convert epoch seconds to YYYY-MM-DD string
pub fn epoch_to_date_string(epoch_secs: i64) -> String {
    // Simple date calculation without external deps
    let days = epoch_secs / 86400;
    let (year, month, day) = days_to_ymd(days);
    format!("{:04}-{:02}-{:02}", year, month, day)
}

/// Convert days since epoch to (year, month, day)
pub fn days_to_ymd(days: i64) -> (i64, u32, u32) {
    // Algorithm from http://howardhinnant.github.io/date_algorithms.html
    let z = days + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = (z - era * 146097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

/// Build structural context for LLM narration
pub fn build_timeline_context(data: &GitIntel) -> String {
    let mut ctx = String::new();

    ctx.push_str(&format!(
        "Total commits (last 6 months): {}\n",
        data.commits.len()
    ));
    ctx.push_str(&format!("Contributors: {}\n\n", data.contributors.len()));

    // Top contributors
    ctx.push_str("Top contributors:\n");
    for c in data.contributors.iter().take(10) {
        ctx.push_str(&format!("- {} ({} commits)\n", c.name, c.commit_count));
    }
    ctx.push('\n');

    // Hottest files
    ctx.push_str("Most-changed files:\n");
    for f in data.churn.iter().take(15) {
        ctx.push_str(&format!(
            "- {} ({} changes, primarily by {})\n",
            f.path, f.change_count, f.primary_author
        ));
    }
    ctx.push('\n');

    // Module activity
    ctx.push_str("Module activity:\n");
    for m in data.module_activity.iter().take(10) {
        ctx.push_str(&format!(
            "- {} ({} changes across {} files, led by {})\n",
            m.module_path, m.commit_count, m.files_changed, m.primary_contributor
        ));
    }
    ctx.push('\n');

    // Recent weeks
    ctx.push_str("Recent weekly activity:\n");
    for w in data.weekly_summaries.iter().take(4) {
        ctx.push_str(&format!(
            "- Week of {}: {} commits, {} files changed by {} contributors\n",
            w.week_start,
            w.commit_count,
            w.files_changed,
            w.contributors.len()
        ));
        if !w.top_modules.is_empty() {
            ctx.push_str(&format!("  Most active: {}\n", w.top_modules.join(", ")));
        }
    }

    ctx
}

/// Render timeline data as markdown
pub fn render_timeline_markdown(data: &GitIntel) -> String {
    let mut md = String::new();

    if data.commits.is_empty() {
        md.push_str("*No git history available.*\n");
        return md;
    }

    // Narration
    if let Some(ref narration) = data.narration {
        md.push_str(narration);
        md.push_str("\n\n");
    }

    // Activity chart — plain ASCII bar chart (terminal-safe, no Zola template syntax)
    if !data.weekly_summaries.is_empty() {
        md.push_str("## Weekly Activity\n\n");
        let weeks: Vec<&WeekSummary> = data.weekly_summaries.iter().rev().collect();
        let max_commits = weeks
            .iter()
            .map(|w| w.commit_count)
            .max()
            .unwrap_or(1)
            .max(1);
        const BAR_WIDTH: usize = 24;
        for w in &weeks {
            let label = if w.week_start.len() >= 10 {
                &w.week_start[5..10]
            } else {
                &w.week_start
            };
            let bar_len = if w.commit_count == 0 {
                0
            } else {
                (w.commit_count * BAR_WIDTH / max_commits).max(1)
            };
            let bar = "".repeat(bar_len);
            md.push_str(&format!("{} {:>3}  {}\n", label, w.commit_count, bar));
        }
        md.push('\n');
    }

    // Contributors table
    if !data.contributors.is_empty() {
        md.push_str("## Contributors\n\n");
        md.push_str("| Author | Commits |\n|---|---|\n");
        for c in data.contributors.iter().take(15) {
            md.push_str(&format!("| {} | {} |\n", c.name, c.commit_count));
        }
        md.push('\n');
    }

    // Hot files
    if !data.churn.is_empty() {
        md.push_str("## Most-Changed Files\n\n");
        md.push_str("| File | Changes | Primary Author |\n|---|---|---|\n");
        for f in data.churn.iter().take(20) {
            md.push_str(&format!(
                "| `{}` | {} | {} |\n",
                f.path, f.change_count, f.primary_author
            ));
        }
        md.push('\n');
    }

    // Module activity
    if !data.module_activity.is_empty() {
        md.push_str("## Module Activity\n\n");
        md.push_str("| Module | Changes | Files | Primary Contributor |\n|---|---|---|---|\n");
        for m in &data.module_activity {
            md.push_str(&format!(
                "| `{}` | {} | {} | {} |\n",
                m.module_path, m.commit_count, m.files_changed, m.primary_contributor
            ));
        }
        md.push('\n');
    }

    md
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_epoch_to_date_string() {
        // 2024-01-01 00:00:00 UTC = 1704067200
        assert_eq!(epoch_to_date_string(1704067200), "2024-01-01");
    }

    #[test]
    fn test_days_to_ymd() {
        let (y, m, d) = days_to_ymd(0); // 1970-01-01
        assert_eq!((y, m, d), (1970, 1, 1));
    }

    #[test]
    fn test_compute_contributors() {
        let commits = vec![
            CommitInfo {
                hash: "a".into(),
                author: "Alice".into(),
                email: "a@x.com".into(),
                timestamp: 1,
                subject: "test".into(),
            },
            CommitInfo {
                hash: "b".into(),
                author: "Alice".into(),
                email: "a@x.com".into(),
                timestamp: 2,
                subject: "test2".into(),
            },
            CommitInfo {
                hash: "c".into(),
                author: "Bob".into(),
                email: "b@x.com".into(),
                timestamp: 3,
                subject: "test3".into(),
            },
        ];
        let contributors = compute_contributors(&commits);
        assert_eq!(contributors.len(), 2);
        assert_eq!(contributors[0].name, "Alice");
        assert_eq!(contributors[0].commit_count, 2);
    }

    #[test]
    fn test_render_empty_timeline() {
        let data = GitIntel {
            commits: vec![],
            contributors: vec![],
            churn: vec![],
            weekly_summaries: vec![],
            module_activity: vec![],
            narration: None,
        };
        let md = render_timeline_markdown(&data);
        assert!(md.contains("No git history"));
    }
}