codelore-lib 0.26.0

CodeLore — Behavioral Code Analyzer library
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
#![allow(clippy::doc_markdown, clippy::items_after_statements)]
//! T8 — `knowledge-islands` analysis tests.
//!
//! Tests the bus-factor / knowledge-loss risk indicator: per-file
//! identification of cases where the primary author (by LoC) has
//! effectively departed (no commits in `--departed-threshold-days`)
//! AND no other contributor owns a substantial share.

use codelore_lib::Options;
use codelore_lib::analyses::knowledge_islands::{owner_activity_for_paths, run_knowledge_islands};
use codelore_lib::facts::FactsDb;
use codelore_lib::repo::GixRepo;

/// Build a deliberately-aged test repo: one file authored entirely by
/// Alice in early-2024, then no Alice commits since. Bob makes a
/// trivial 1-line edit (insufficient ownership share).
///
/// With `--age-time-now 2026-06-01` and `--departed-threshold-days 30`:
///   - Alice's last commit: ~2024-03-01 → days_since ~ 730 days → departed
///   - Bob's tiny contribution: 1 LoC out of Alice's much-larger total
///     → ownership_pct(Bob) ≈ 1% → below the 10% substantial threshold
///   - `alice_owned.txt` SHOULD appear as a knowledge-island
///   - `bob_dominates.txt`: Bob owns 100% → Bob's last_at (if recent)
///     → NOT departed → SHOULD NOT appear
fn build_fixture() -> tempfile::TempDir {
    use std::process::Command;
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path();
    fn run(path: &std::path::Path, date: &str, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(args)
            .env("GIT_AUTHOR_DATE", date)
            .env("GIT_COMMITTER_DATE", date)
            .status()
            .expect("git");
        assert!(status.success());
    }
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["init", "-b", "main", "--quiet"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.email", "init@x"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.name", "Init"],
    );

    // Alice writes a substantial file in 2024.
    std::fs::write(
        path.join("alice_owned.txt"),
        "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n",
    )
    .unwrap();
    run(path, "2024-03-01T12:00:00Z", &["add", "alice_owned.txt"]);
    run(
        path,
        "2024-03-01T12:00:00Z",
        &[
            "commit",
            "-m",
            "alice",
            "--author",
            "Alice <alice@old.com>",
            "--quiet",
        ],
    );

    // Bob writes his own small file 7 days before the anchor (well
    // within any reasonable departure threshold — he's "active") AND
    // makes a 1-line touch to alice_owned.txt (insufficient ownership).
    std::fs::write(path.join("bob_dominates.txt"), "x\n").unwrap();
    run(path, "2026-05-25T12:00:00Z", &["add", "bob_dominates.txt"]);
    run(
        path,
        "2026-05-25T12:00:00Z",
        &[
            "commit",
            "-m",
            "bob solo",
            "--author",
            "Bob <bob@active.com>",
            "--quiet",
        ],
    );
    std::fs::write(
        path.join("alice_owned.txt"),
        "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\n",
    )
    .unwrap();
    run(path, "2026-05-26T12:00:00Z", &["add", "alice_owned.txt"]);
    run(
        path,
        "2026-05-26T12:00:00Z",
        &[
            "commit",
            "-m",
            "bob 1-liner",
            "--author",
            "Bob <bob@active.com>",
            "--quiet",
        ],
    );
    dir
}

#[test]
fn knowledge_islands_surfaces_departed_main_author_solo_owner() {
    let fixture = build_fixture();
    let repo = GixRepo::open(fixture.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    // Anchor 2026-06-01 → Alice last 2024-03-01 → ~822 days departed
    //                  → Bob   last 2025-06-02 → ~365 days NOT departed
    // Threshold 30 days.
    let opts = Options {
        repo_path: fixture.path().to_path_buf(),
        min_revs: 1,
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        departed_threshold_days: 30,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let rows = run_knowledge_islands(&db, &opts).expect("run");
    let alice_row = rows
        .iter()
        .find(|r| r.entity == "alice_owned.txt")
        .expect("alice_owned.txt surfaces as knowledge-island");
    assert_eq!(alice_row.main_author, "alice@old.com");
    assert!(
        alice_row.ownership_pct > 80.0,
        "Alice owns ~91% (10/11 lines); got {}",
        alice_row.ownership_pct,
    );
    assert!(
        alice_row.days_since_main_active > 800,
        "should reflect ~822-day gap; got {}",
        alice_row.days_since_main_active,
    );
    assert_eq!(
        alice_row.total_loc, 11,
        "total_loc must disclose the ownership_pct denominator (10 Alice + 1 Bob), got {}",
        alice_row.total_loc,
    );

    // Bob's solo file should NOT appear — Bob isn't departed at the anchor.
    assert!(
        !rows.iter().any(|r| r.entity == "bob_dominates.txt"),
        "bob_dominates.txt should NOT surface; Bob's last commit is recent",
    );
}

#[test]
fn knowledge_islands_threshold_gates_inclusion() {
    let fixture = build_fixture();
    let repo = GixRepo::open(fixture.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    // High threshold (10 years) → nobody is "departed" → empty output.
    let opts = Options {
        repo_path: fixture.path().to_path_buf(),
        min_revs: 1,
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        departed_threshold_days: 365 * 10,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    let rows = run_knowledge_islands(&db, &opts).expect("run");
    assert!(
        rows.is_empty(),
        "10-year departure threshold → no rows; got {} rows",
        rows.len(),
    );
}

#[test]
fn knowledge_islands_excludes_deleted_files() {
    // Knowledge-islands uses the same live-paths CTE
    // pattern; deleted files shouldn't surface even with departed
    // authors.
    use std::process::Command;
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path();
    fn run(path: &std::path::Path, date: &str, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(args)
            .env("GIT_AUTHOR_DATE", date)
            .env("GIT_COMMITTER_DATE", date)
            .status()
            .expect("git");
        assert!(status.success());
    }
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["init", "-b", "main", "--quiet"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.email", "t@t"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.name", "Tiny"],
    );
    std::fs::write(path.join("gone.txt"), "x\ny\nz\n").unwrap();
    run(path, "2024-03-01T12:00:00Z", &["add", "gone.txt"]);
    run(
        path,
        "2024-03-01T12:00:00Z",
        &[
            "commit",
            "-m",
            "add",
            "--author",
            "Alice <alice@old.com>",
            "--quiet",
        ],
    );
    std::fs::remove_file(path.join("gone.txt")).unwrap();
    run(path, "2024-04-01T12:00:00Z", &["add", "-A"]);
    run(
        path,
        "2024-04-01T12:00:00Z",
        &[
            "commit",
            "-m",
            "delete",
            "--author",
            "Alice <alice@old.com>",
            "--quiet",
        ],
    );

    let repo = GixRepo::open(path).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: path.to_path_buf(),
        min_revs: 1,
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        departed_threshold_days: 30,
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");
    let rows = run_knowledge_islands(&db, &opts).expect("run");
    assert!(
        !rows.iter().any(|r| r.entity == "gone.txt"),
        "deleted files must not appear in knowledge-islands; got {rows:?}",
    );
}

/// `owner_activity_for_paths` surfaces the same ownership/activity
/// primitive as `run_knowledge_islands`, but un-thresholded and scoped to
/// a caller-supplied path list: Alice's departed ownership on
/// `alice_owned.txt` shows up even though no `departed_threshold_days` is
/// ever applied, Bob's recent activity on `bob_dominates.txt` shows up
/// too, and a path with no history at all is simply absent (Inconclusive)
/// rather than erroring.
#[test]
fn owner_activity_for_paths_returns_unthresholded_activity_and_omits_unknown() {
    let fixture = build_fixture();
    let repo = GixRepo::open(fixture.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fixture.path().to_path_buf(),
        min_revs: 1,
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let paths = vec![
        "alice_owned.txt".to_string(),
        "bob_dominates.txt".to_string(),
        "no_such_file.txt".to_string(),
    ];
    let map = owner_activity_for_paths(&db, &opts, &paths).expect("helper");

    // canonical_author resolves to the raw commit email here (no
    // author_aliases display-name override configured by this fixture) —
    // matching `knowledge_islands_surfaces_departed_main_author_solo_owner`'s
    // `alice_row.main_author == "alice@old.com"` assertion above.
    let alice = map.get("alice_owned.txt").expect("alice file present");
    assert_eq!(alice.main_author, "alice@old.com");
    assert!(
        alice.days_since_main_active > 800,
        "Alice last committed 2024-03-01; got {}",
        alice.days_since_main_active
    );

    let bob = map.get("bob_dominates.txt").expect("bob file present");
    assert!(
        bob.days_since_main_active < 30,
        "Bob is active; got {}",
        bob.days_since_main_active
    );

    assert!(
        !map.contains_key("no_such_file.txt"),
        "unknown path = no entry = Inconclusive"
    );
    assert_eq!(map.len(), 2, "no extra paths leak into the result");
}

/// Empty `paths` must short-circuit to an empty map without querying —
/// the same contract `top_active_shares_by_path` (marginal_owner_risk)
/// gives for a batched path-list helper.
#[test]
fn owner_activity_for_paths_empty_paths_returns_empty_map_without_querying() {
    let fixture = build_fixture();
    let repo = GixRepo::open(fixture.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    let opts = Options {
        repo_path: fixture.path().to_path_buf(),
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        ..Options::default()
    };
    db.ingest(&repo, &opts).expect("ingest");

    let map = owner_activity_for_paths(&db, &opts, &[]).expect("empty paths");
    assert!(map.is_empty());
}

/// Build a single-file, single-commit repo whose sole author is
/// long-departed by the test anchor — the minimal fixture to isolate the
/// `--min-revs` floor from every other gating condition (departure,
/// substantial-others, liveness).
fn build_single_commit_fixture() -> tempfile::TempDir {
    use std::process::Command;
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path();
    fn run(path: &std::path::Path, date: &str, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(args)
            .env("GIT_AUTHOR_DATE", date)
            .env("GIT_COMMITTER_DATE", date)
            .status()
            .expect("git");
        assert!(status.success());
    }
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["init", "-b", "main", "--quiet"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.email", "init@x"],
    );
    run(
        path,
        "2024-01-01T00:00:00Z",
        &["config", "user.name", "Init"],
    );

    std::fs::write(path.join("solo.txt"), "a\nb\nc\n").unwrap();
    run(path, "2024-03-01T12:00:00Z", &["add", "solo.txt"]);
    run(
        path,
        "2024-03-01T12:00:00Z",
        &[
            "commit",
            "-m",
            "solo add",
            "--author",
            "Old <old@dev.com>",
            "--quiet",
        ],
    );
    dir
}

/// `--min-revs` must gate `knowledge-islands` per-path exactly like
/// every other per-path analysis (`hotspots`, `revisions`) — a file
/// touched by only one commit is invisible under a `--min-revs 2` floor
/// even though its sole author is long-departed and 100%-owns the file
/// (every other inclusion condition is satisfied), but surfaces once the
/// floor drops to 1.
#[test]
fn knowledge_islands_min_revs_gates_single_commit_files() {
    let fixture = build_single_commit_fixture();
    let repo = GixRepo::open(fixture.path()).expect("open");
    let db = FactsDb::new_in_memory().expect("db");
    // Old's one commit (2024-03-01) is ~822 days before the 2026-06-01
    // anchor → departed at any threshold well below that; solo ownership
    // → n_substantial_others = 0. Both conditions satisfied regardless of
    // min_revs, isolating the assertion to the revision-count floor.
    let ingest_opts = Options {
        repo_path: fixture.path().to_path_buf(),
        age_time_now: Some(time::macros::date!(2026 - 06 - 01)),
        departed_threshold_days: 30,
        ..Options::default()
    };
    db.ingest(&repo, &ingest_opts).expect("ingest");

    let opts_min_revs_2 = Options {
        min_revs: 2,
        ..ingest_opts.clone()
    };
    let rows_at_2 = run_knowledge_islands(&db, &opts_min_revs_2).expect("run min_revs=2");
    assert!(
        !rows_at_2.iter().any(|r| r.entity == "solo.txt"),
        "solo.txt has 1 revision; must be excluded under min_revs=2, got {rows_at_2:?}",
    );

    let opts_min_revs_1 = Options {
        min_revs: 1,
        ..ingest_opts
    };
    let rows_at_1 = run_knowledge_islands(&db, &opts_min_revs_1).expect("run min_revs=1");
    let solo_row = rows_at_1
        .iter()
        .find(|r| r.entity == "solo.txt")
        .expect("solo.txt must surface under min_revs=1");
    assert_eq!(solo_row.main_author, "old@dev.com");
    assert!(
        (solo_row.ownership_pct - 100.0).abs() < f64::EPSILON,
        "solo author owns 100%; got {}",
        solo_row.ownership_pct,
    );
    assert_eq!(
        solo_row.total_loc, 3,
        "solo.txt's single commit adds exactly 3 lines; total_loc must disclose that \
         thin denominator behind the 100% ownership figure, got {}",
        solo_row.total_loc,
    );
}