codelore-lib 0.27.3

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
//! Markdown emitters for the hotspot and code-health family: hotspots,
//! velocity, code health, health trend, effort exposure, refactoring targets,
//! the per-function x-ray, finding overlap, and defect validation.

use super::{escape_md_cell, header};
use crate::analyses::code_health::CodeHealthRow;
use crate::analyses::hotspots::HotspotRow;
use crate::{CodeLoreError, Result};
use std::io::Write;

/// `hotspot-velocity` markdown emitter — files ranked by change
/// acceleration (heating up first).
pub fn write_hotspot_velocity_markdown<W: Write>(
    rows: &[crate::analyses::hotspot_velocity::HotspotVelocityRow],
    w: &mut W,
) -> Result<()> {
    header(w, "CodeLore hotspot velocity")?;
    if rows.is_empty() {
        writeln!(w, "_No files changed in the recent window._").map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(
        w,
        "| Path | Trend | Revs (recent) | Revs (baseline) | Recent/wk | Baseline/wk | Acceleration |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|:---:|---:|---:|---:|---:|---:|").map_err(CodeLoreError::Io)?;
    for row in rows {
        let trend = if row.acceleration > 0.0 {
            "▲ heating"
        } else if row.acceleration < 0.0 {
            "▼ cooling"
        } else {
            "– steady"
        };
        writeln!(
            w,
            "| `{}` | {} | {} | {} | {:.2} | {:.2} | {:+.2} |",
            escape_md_cell(&row.path),
            trend,
            row.revs_recent,
            row.revs_baseline,
            row.recent_per_week,
            row.baseline_per_week,
            row.acceleration,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

pub fn write_hotspots_markdown<W: Write>(rows: &[HotspotRow], w: &mut W) -> Result<()> {
    header(w, "CodeLore hotspots")?;
    // The MI cell renders `value (band, rank%)` when the file has a known
    // file-level MI; `—` otherwise. Bands are repo-relative — see
    // `crates/codelore-lib/src/analyses/mi.rs` for why we don't use the
    // literature's absolute Coleman/SEI thresholds.
    //
    // The AI cell is the share of commits with AI-attribution signal
    // (ai-assisted | ai-authored), rendered as `X.X%` or `—`.
    //
    // `Score (anchored)` is `Score` with its cognitive terms anchored to the
    // calibration corpus (see `HotspotRow::hotspot_score_anchored`); `—` when no
    // corpus is active or the file's language is uncovered.
    writeln!(
        w,
        "| Entity | Revisions | Cognitive | Cognitive Health | Score | MI | AI % | Score (anchored) |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|---|---|---|---|---|---|").map_err(CodeLoreError::Io)?;
    for row in rows {
        let mi_cell = match (row.mi, row.mi_rank) {
            (Some(v), Some(rank)) if rank.is_finite() => {
                let band = crate::analyses::mi::MiBand::from_rank(rank);
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                // rank is in [0.0,1.0] and guarded is_finite(); after *100+round the value is in [0,100] — fits u32 exactly
                let rank_pct = (rank * 100.0).round() as u32;
                format!("{v:.2} ({}, {rank_pct}%)", band.as_str())
            }
            (Some(v), _) => format!("{v:.2}"),
            (None, _) => "".to_owned(),
        };
        let ai_cell = match row.ai_pct {
            Some(v) if v.is_finite() => format!("{v:.1}%"),
            _ => "".to_owned(),
        };
        // Same `{:.4}` scale as the `Score` column; `—` when absent.
        let anchored_cell = row
            .hotspot_score_anchored
            .map_or_else(|| "".to_owned(), |v| format!("{v:.4}"));
        writeln!(
            w,
            "| `{}` | {} | {:.2} | {:.2} | {:.4} | {} | {} | {} |",
            escape_md_cell(&row.path),
            row.revisions,
            row.cognitive,
            row.cognitive_health,
            row.hotspot_score,
            mi_cell,
            ai_cell,
            anchored_cell
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

pub fn write_code_health_markdown<W: Write>(rows: &[CodeHealthRow], w: &mut W) -> Result<()> {
    header(w, "CodeLore code-health")?;
    writeln!(
        w,
        "| Entity | Cognitive | Score | Structural risk | Percentile | Band | Corpus percentile | Corpus 95% CI |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|---|---|---|---|---|---|").map_err(CodeLoreError::Io)?;
    for row in rows {
        let corpus_cell = match row.corpus_percentile {
            Some(v) => {
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                // v is in [0.0, 1.0] after saturation; *100+round fits u32.
                let pct = (v * 100.0).round() as u32;
                if row.beyond_corpus {
                    format!("{pct}%+")
                } else {
                    format!("{pct}%")
                }
            }
            None => "".to_owned(),
        };
        // Wilson 95% interval on the corpus percentile, as an integer-percent
        // range. Present exactly when `corpus_percentile` is.
        let corpus_ci_cell = match (row.corpus_percentile_ci_low, row.corpus_percentile_ci_high) {
            (Some(lo), Some(hi)) => {
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                // Both bounds are in [0.0, 1.0]; *100+round fits u32.
                let (lo_pct, hi_pct) = ((lo * 100.0).round() as u32, (hi * 100.0).round() as u32);
                format!("{lo_pct}{hi_pct}%")
            }
            _ => "".to_owned(),
        };
        writeln!(
            w,
            "| `{}` | {:.2} | {:.2} | {:.4} | {:.4} | {} | {} | {} |",
            escape_md_cell(&row.path),
            row.cognitive,
            row.score,
            row.structural_risk,
            row.percentile,
            row.band,
            corpus_cell,
            corpus_ci_cell
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

/// `health-trend` markdown emitter — repo health timeline across sampled revs.
pub fn write_health_trend_markdown<W: Write>(
    rows: &[crate::analyses::health_trend::HealthTrendRow],
    w: &mut W,
) -> Result<()> {
    header(w, "CodeLore health trend")?;
    if rows.is_empty() {
        writeln!(w, "_No commit history to sample._").map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(w, "| Date | Rev | Files | Arch | Code | Combined |").map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|---:|---:|---:|---:|").map_err(CodeLoreError::Io)?;
    for row in rows {
        writeln!(
            w,
            "| {} | `{}` | {} | {:.1} ({}) | {:.1} ({}) | {:.1} ({}) |",
            escape_md_cell(&row.date),
            escape_md_cell(&row.rev),
            row.files,
            row.arch_health,
            row.arch_band,
            row.code_health,
            row.code_band,
            row.combined_health,
            row.combined_band,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

pub fn write_effort_exposure_markdown<W: Write>(
    rows: &[crate::analyses::effort_exposure::EffortExposureRow],
    w: &mut W,
) -> Result<()> {
    header(w, "CodeLore effort-exposure")?;
    if rows.is_empty() {
        writeln!(w, "_No code-health data — run with `--min-revs 1` or ensure complexity metrics are available._")
            .map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(
        w,
        "| Band | Files | LOC share % | Commit share % | Churn share % | CI 95% low | CI 95% high | Improving churn % | Degrading churn % |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---:|---:|---:|---:|---:|---:|---:|---:|").map_err(CodeLoreError::Io)?;
    for row in rows {
        // The improving/degrading split is populated only for the red band when
        // the decomposition ran (repo available); elsewhere it reads "—".
        let improving = row
            .churn_share_improving_pct
            .map_or_else(|| "".to_owned(), |v| format!("{v:.1}"));
        let degrading = row
            .churn_share_degrading_pct
            .map_or_else(|| "".to_owned(), |v| format!("{v:.1}"));
        writeln!(
            w,
            "| {} | {} | {:.1} | {:.1} | {:.1} | {:.3} | {:.3} | {} | {} |",
            escape_md_cell(&row.band),
            row.files,
            row.loc_share_pct,
            row.commit_share_pct,
            row.churn_share_pct,
            row.commit_share_ci_low,
            row.commit_share_ci_high,
            improving,
            degrading,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

/// `defect-validation` markdown emitter — flat `(metric, value)` evidence
/// rows from a defect-calibration artifact. Empty (no artifact configured)
/// prints an honest-absence note pointing at `codelore calibrate-defects`.
pub fn write_defect_validation_markdown<W: Write>(
    rows: &[crate::analyses::defect_validation::DefectValidationRow],
    w: &mut W,
) -> Result<()> {
    header(w, "CodeLore defect-validation")?;
    if rows.is_empty() {
        writeln!(
            w,
            "_No defect-calibration artifact configured — run `codelore calibrate-defects` and pass it with `--defect-calibration`._"
        )
        .map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(w, "| Metric | Value |").map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|").map_err(CodeLoreError::Io)?;
    for row in rows {
        writeln!(
            w,
            "| {} | {} |",
            escape_md_cell(&row.metric),
            escape_md_cell(&row.value),
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

/// Markdown table emitter for the `refactoring-targets` analysis.
///
/// # Errors
/// Propagates any write error from `w`.
pub fn write_refactoring_targets_markdown<W: Write>(
    rows: &[crate::analyses::refactoring_targets::RefactoringTargetRow],
    w: &mut W,
) -> Result<()> {
    writeln!(
        w,
        "| Entity | Priority | Combined risk | Structural risk | Hotspot | Revisions | LOC | Type | Band | ManualUp |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|---|---|---|---|---|---|---|---|").map_err(CodeLoreError::Io)?;
    for row in rows {
        writeln!(
            w,
            "| `{}` | {:.6} | {:.6} | {:.4} | {:.4} | {} | {} | {} | {} | {} |",
            escape_md_cell(&row.path),
            row.priority,
            row.combined_risk,
            row.structural_risk,
            row.hotspot_score,
            row.revisions,
            row.loc,
            escape_md_cell(&row.dominant_type),
            row.band,
            row.manual_up_rank,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

pub fn write_function_xray_markdown<W: Write>(
    rows: &[crate::analyses::function_xray::FunctionXrayRow],
    target: &str,
    w: &mut W,
) -> Result<()> {
    header(w, &format!("CodeLore function-xray — {target}"))?;
    if rows.is_empty() {
        writeln!(
            w,
            "_No HEAD-alive functions found in `{target}` or no changes recorded._"
        )
        .map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(
        w,
        "| Function | Change Freq | LOC | Cyclomatic | Cognitive | Last Changed |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---:|---:|---:|---:|---|").map_err(CodeLoreError::Io)?;
    for row in rows {
        let cyc = row
            .cyclomatic
            .map_or_else(|| "".to_string(), |v| v.to_string());
        let cog = row
            .cognitive
            .map_or_else(|| "".to_string(), |v| v.to_string());
        let last = if row.last_changed.is_empty() {
            "".to_string()
        } else {
            row.last_changed.clone()
        };
        writeln!(
            w,
            "| {} | {} | {} | {} | {} | {} |",
            escape_md_cell(&row.function),
            row.change_freq,
            row.loc,
            cyc,
            cog,
            last,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

/// `function-hotspots` markdown emitter — repo-wide function-level hotspot
/// ranking (revs × cognitive, the `hotspots` scoring shape at function
/// granularity).
pub fn write_function_hotspots_markdown<W: Write>(
    rows: &[crate::analyses::function_hotspots::FunctionHotspotRow],
    w: &mut W,
) -> Result<()> {
    header(w, "CodeLore function-hotspots")?;
    if rows.is_empty() {
        writeln!(w, "_No HEAD-alive functions cleared `--min-revs`._")
            .map_err(CodeLoreError::Io)?;
        return Ok(());
    }
    writeln!(
        w,
        "| Path | Function | Revs | Cognitive | Cognitive Health | Score |"
    )
    .map_err(CodeLoreError::Io)?;
    writeln!(w, "|---|---|---:|---:|---:|---:|").map_err(CodeLoreError::Io)?;
    for row in rows {
        writeln!(
            w,
            "| `{}` | {} | {} | {:.2} | {:.2} | {:.4} |",
            escape_md_cell(&row.path),
            escape_md_cell(&row.function),
            row.revs,
            row.cognitive,
            row.cognitive_health,
            row.function_hotspot_score,
        )
        .map_err(CodeLoreError::Io)?;
    }
    Ok(())
}

pub fn write_finding_hotspot_overlap_markdown<W: Write>(
    rows: &[crate::analyses::finding_hotspot_overlap::FindingHotspotOverlapRow],
    w: &mut W,
) -> crate::Result<()> {
    writeln!(
        w,
        "| Path | Findings | Engines | Worst Level | Hotspot Score | Revs Percentile | Health Band | Priority |"
    )
    .map_err(crate::CodeLoreError::Io)?;
    writeln!(w, "|---|---:|---|---|---:|---:|---|---|").map_err(crate::CodeLoreError::Io)?;
    for row in rows {
        writeln!(
            w,
            "| {} | {} | {} | {} | {:.4} | {:.4} | {} | {} |",
            escape_md_cell(&row.path),
            row.findings,
            escape_md_cell(&row.engines),
            escape_md_cell(&row.worst_level),
            row.hotspot_score,
            row.revs_percentile,
            escape_md_cell(&row.health_band),
            escape_md_cell(&row.priority),
        )
        .map_err(crate::CodeLoreError::Io)?;
    }
    Ok(())
}