ripr 0.10.0

Find static mutation-exposure gaps before expensive mutation testing
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
use serde::Serialize;

use crate::app::CheckOutput;

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffChangedFile {
    pub(crate) path: String,
    pub(crate) added_lines: Vec<usize>,
    pub(crate) removed_lines: Vec<usize>,
    pub(crate) added_count: usize,
    pub(crate) removed_count: usize,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffChangedSeam {
    pub(crate) seam_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) canonical_gap_id: Option<String>,
    pub(crate) file: String,
    pub(crate) line: usize,
    pub(crate) classification: String,
    pub(crate) evidence: Vec<String>,
    pub(crate) missing_discriminators: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) recommended_next_step: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffPhaseStatus {
    pub(crate) state: String,
    pub(crate) phase: String,
    pub(crate) changed_files: usize,
    pub(crate) changed_seams: usize,
    pub(crate) downstream_consumable: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct FullRepoContextStatus {
    pub(crate) state: String,
    pub(crate) phase: String,
    pub(crate) limitation_category: String,
    pub(crate) downstream_consumable: bool,
    pub(crate) repair_route: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffRuntimeStatus {
    pub(crate) state: String,
    pub(crate) diff: DiffPhaseStatus,
    pub(crate) full_repo_context: FullRepoContextStatus,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffReceiptStatus {
    pub(crate) state: String,
    pub(crate) path: String,
    pub(crate) outcome_hint: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffSummary {
    pub(crate) changed_files: usize,
    pub(crate) changed_seams: usize,
    pub(crate) probes: usize,
    pub(crate) exposed: usize,
    pub(crate) weakly_exposed: usize,
    pub(crate) reachable_unrevealed: usize,
    pub(crate) no_static_path: usize,
    pub(crate) unknown: usize,
}

/// Advisory disclosure for one preview-language adapter that processed files
/// in the diff scope. Serialized into the JSON diff report when present.
///
/// An empty `preview_languages` array means only stable (Rust) files were in
/// scope. A non-empty array means at least one preview-language file was
/// present — an empty `changed_seams` together with a non-empty
/// `preview_languages` is NOT a clean Rust-grade result.
///
/// See RIPR-SPEC-0082.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffPreviewLanguageAdvisory {
    /// Stable language wire string (e.g. `"typescript"`, `"python"`).
    pub(crate) language: String,
    /// Number of files routed to this preview adapter.
    pub(crate) file_count: usize,
    /// Up to three sample file paths (normalized, forward-slash).
    pub(crate) sample_paths: Vec<String>,
    /// Whether the preview adapter was enabled (ran) for this analysis.
    pub(crate) enabled: bool,
    /// Whether the files were analyzed (mirrors `enabled`).
    pub(crate) analyzed: bool,
    /// Advisory category tag.
    pub(crate) category: &'static str,
    /// Human-readable advisory note.
    pub(crate) why: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct DiffReport {
    pub(crate) schema_version: String,
    pub(crate) kind: String,
    pub(crate) tool: String,
    pub(crate) run_status: String,
    pub(crate) root: String,
    pub(crate) base: String,
    pub(crate) head: String,
    pub(crate) mode: String,
    pub(crate) runtime_status: DiffRuntimeStatus,
    pub(crate) receipt: DiffReceiptStatus,
    pub(crate) summary: DiffSummary,
    pub(crate) changed_files: Vec<DiffChangedFile>,
    pub(crate) changed_seams: Vec<DiffChangedSeam>,
    /// Advisory disclosures for preview-language files in the analyzed scope.
    ///
    /// Empty when only Rust (stable) files were in scope. Non-empty entries
    /// mean the diff contained preview-language files and empty changed_seams
    /// is NOT a clean Rust-grade result. See RIPR-SPEC-0082.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub(crate) preview_languages: Vec<DiffPreviewLanguageAdvisory>,
}

pub(crate) fn build_diff_report(
    output: &CheckOutput,
    base: &str,
    head: &str,
    changed_files: Vec<DiffChangedFile>,
    receipt_path: String,
) -> DiffReport {
    let changed_seams = output
        .findings
        .iter()
        .map(|finding| DiffChangedSeam {
            seam_id: finding.id.clone(),
            canonical_gap_id: finding
                .canonical_gap
                .as_ref()
                .map(|canonical| canonical.id.clone()),
            file: finding.probe.location.file.display().to_string(),
            line: finding.probe.location.line,
            classification: finding.class.as_str().to_string(),
            evidence: finding.evidence.clone(),
            missing_discriminators: finding.missing.clone(),
            recommended_next_step: finding.recommended_next_step.clone(),
        })
        .collect::<Vec<_>>();
    let changed_file_count = changed_files.len();
    let changed_seam_count = changed_seams.len();
    let unknown = output.summary.static_unknown
        + output.summary.infection_unknown
        + output.summary.propagation_unknown;

    DiffReport {
        schema_version: "0.1".to_string(),
        kind: "ripr_diff".to_string(),
        tool: output.tool.clone(),
        run_status: "diff_complete_full_repo_limited".to_string(),
        root: output.root.display().to_string(),
        base: base.to_string(),
        head: head.to_string(),
        mode: output.mode.as_str().to_string(),
        runtime_status: DiffRuntimeStatus {
            state: "diff_complete_full_repo_limited".to_string(),
            diff: DiffPhaseStatus {
                state: "diff_complete".to_string(),
                phase: "changed_surface_diff".to_string(),
                changed_files: changed_file_count,
                changed_seams: changed_seam_count,
                downstream_consumable: true,
            },
            full_repo_context: FullRepoContextStatus {
                state: "full_repo_limited".to_string(),
                phase: "full_repo_context".to_string(),
                limitation_category: "full_repo_context_not_run".to_string(),
                downstream_consumable: false,
                repair_route: "ripr check --format repo-exposure-summary-json".to_string(),
            },
        },
        receipt: DiffReceiptStatus {
            state: "not_written".to_string(),
            path: receipt_path,
            outcome_hint: "diff_complete/full_repo_limited".to_string(),
        },
        summary: DiffSummary {
            changed_files: changed_file_count,
            changed_seams: changed_seam_count,
            probes: output.summary.probes,
            exposed: output.summary.exposed,
            weakly_exposed: output.summary.weakly_exposed,
            reachable_unrevealed: output.summary.reachable_unrevealed,
            no_static_path: output.summary.no_static_path,
            unknown,
        },
        changed_files,
        changed_seams,
        preview_languages: output
            .preview_language_advisories
            .iter()
            .map(|advisory| DiffPreviewLanguageAdvisory {
                language: advisory.language.clone(),
                file_count: advisory.file_count,
                sample_paths: advisory.sample_paths.clone(),
                enabled: advisory.enabled,
                analyzed: advisory.enabled,
                category: "preview_language_advisory",
                why: if advisory.enabled {
                    "preview adapter; advisory; may be incomplete; empty result is not Rust-grade clean".to_string()
                } else {
                    format!(
                        "preview adapter not enabled; files detected but not analyzed; empty result is not Rust-grade clean; to enable add to ripr.toml: [languages] enabled = [\"rust\", \"{}\"]",
                        advisory.language
                    )
                },
            })
            .collect(),
    }
}

pub(crate) fn render_diff_report_json(report: &DiffReport) -> Result<String, String> {
    super::json::render_pretty_with_newline(report, "ripr diff report")
}

pub(crate) fn render_diff_report_human(report: &DiffReport) -> String {
    let mut out = String::new();
    out.push_str("RIPR diff status: ");
    out.push_str(&report.run_status);
    out.push('\n');
    out.push_str(&format!("root: {}\n", report.root));
    out.push_str(&format!("range: {}...{}\n", report.base, report.head));
    out.push_str(&format!("mode: {}\n", report.mode));
    out.push_str(&format!(
        "changed files: {}\nchanged seams: {}\n",
        report.summary.changed_files, report.summary.changed_seams
    ));
    out.push_str(&format!(
        "full repo context: {} ({})\n",
        report.runtime_status.full_repo_context.state,
        report.runtime_status.full_repo_context.limitation_category
    ));
    out.push_str(&format!("receipt path: {}\n\n", report.receipt.path));

    out.push_str("Changed files\n");
    if report.changed_files.is_empty() {
        out.push_str("  none\n");
    } else {
        for file in &report.changed_files {
            out.push_str(&format!(
                "  - {} (+{} -{})\n",
                file.path, file.added_count, file.removed_count
            ));
        }
    }

    out.push_str("\nChanged seams\n");
    if report.changed_seams.is_empty() {
        out.push_str("  none\n");
    } else {
        for seam in &report.changed_seams {
            out.push_str(&format!(
                "  - {} {}:{} {}\n",
                seam.seam_id, seam.file, seam.line, seam.classification
            ));
            if let Some(canonical_gap_id) = &seam.canonical_gap_id {
                out.push_str(&format!("    canonical_gap_id: {canonical_gap_id}\n"));
            }
            if let Some(next_step) = &seam.recommended_next_step {
                out.push_str(&format!("    next action: {next_step}\n"));
            }
            if let Some(evidence) = seam.evidence.first() {
                out.push_str(&format!("    evidence: {evidence}\n"));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::{CheckOutput, Mode};
    use crate::domain::{
        ActivationEvidence, Confidence, DeltaKind, ExposureClass, Probe, ProbeFamily, ProbeId,
        RevealEvidence, RiprEvidence, SourceLocation, StageEvidence, StageState, Summary, SymbolId,
    };
    use std::path::PathBuf;

    #[test]
    fn diff_report_preserves_diff_complete_full_repo_limited_status() -> Result<(), String> {
        let report = build_diff_report(
            &CheckOutput {
                schema_version: "0.1".to_string(),
                tool: "ripr".to_string(),
                mode: Mode::Draft,
                root: PathBuf::from("repo"),
                base: None,
                summary: Summary {
                    probes: 1,
                    weakly_exposed: 1,
                    ..Summary::default()
                },
                findings: vec![sample_finding()],
                preview_language_advisories: Vec::new(),
                no_scope_provided: false,
            },
            "origin/main",
            "HEAD",
            vec![DiffChangedFile {
                path: "src/lib.rs".to_string(),
                added_lines: vec![2],
                removed_lines: vec![2],
                added_count: 1,
                removed_count: 1,
            }],
            "target/ripr/receipts/diff-first-origin-main-HEAD.json".to_string(),
        );

        let json = render_diff_report_json(&report)?;
        assert!(json.contains(r#""run_status": "diff_complete_full_repo_limited""#));
        assert!(json.contains(r#""state": "diff_complete""#));
        assert!(json.contains(r#""state": "full_repo_limited""#));
        assert!(json.contains(r#""downstream_consumable": true"#));
        assert!(json.contains(r#""outcome_hint": "diff_complete/full_repo_limited""#));

        let human = render_diff_report_human(&report);
        assert!(human.contains("RIPR diff status: diff_complete_full_repo_limited"));
        assert!(human.contains("full repo context: full_repo_limited"));
        assert!(human.contains("receipt path: target/ripr/receipts/"));
        Ok(())
    }

    fn sample_finding() -> crate::domain::Finding {
        crate::domain::Finding {
            id: "probe:src_lib_rs:2:predicate".to_string(),
            canonical_gap: Some(crate::domain::FindingCanonicalGap {
                id: "gap:src-lib-rs:predicate".to_string(),
                language: "rust".to_string(),
                file: "src/lib.rs".to_string(),
                owner: "over_threshold".to_string(),
                behavior_kind: "predicate_boundary".to_string(),
                probe_kind: "predicate".to_string(),
                normalized_discriminator: "amount == threshold".to_string(),
            }),
            probe: Probe {
                id: ProbeId("probe:src_lib_rs:2:predicate".to_string()),
                location: SourceLocation::new("src/lib.rs", 2, 5),
                owner: Some(SymbolId("src::over_threshold".to_string())),
                family: ProbeFamily::Predicate,
                delta: DeltaKind::Control,
                before: Some("amount >= threshold".to_string()),
                after: Some("amount > threshold".to_string()),
                expression: "amount >= threshold".to_string(),
                expected_sinks: vec!["return_value".to_string()],
                required_oracles: vec!["equality_boundary".to_string()],
            },
            class: ExposureClass::WeaklyExposed,
            ripr: RiprEvidence {
                reach: StageEvidence::new(
                    StageState::Yes,
                    Confidence::Medium,
                    "related test reaches owner",
                ),
                infect: StageEvidence::new(
                    StageState::Weak,
                    Confidence::Medium,
                    "changed value is not exact",
                ),
                propagate: StageEvidence::new(
                    StageState::Yes,
                    Confidence::Medium,
                    "return value is visible",
                ),
                reveal: RevealEvidence {
                    observe: StageEvidence::new(
                        StageState::Weak,
                        Confidence::Medium,
                        "broad assertion observes value",
                    ),
                    discriminate: StageEvidence::new(
                        StageState::No,
                        Confidence::Medium,
                        "missing equality boundary",
                    ),
                },
            },
            confidence: 0.70,
            evidence: vec!["related test reaches owner".to_string()],
            missing: vec!["missing discriminator amount == threshold".to_string()],
            flow_sinks: Vec::new(),
            activation: ActivationEvidence::default(),
            stop_reasons: Vec::new(),
            related_tests: Vec::new(),
            recommended_next_step: Some("Add equality-boundary assertion.".to_string()),
            language: None,
            language_status: None,
            owner_kind: None,
            static_limit_kind: None,
            changed_sink: None,
            observed_sink: None,
            oracle_alignment: None,
            alignment_reason: None,
        }
    }

    // RIPR-SPEC-0082 tests: preview-language JSON disclosure
    #[test]
    fn diff_report_includes_preview_languages_when_ts_files_in_scope() -> Result<(), String> {
        use crate::analysis::PreviewLanguageAdvisory;
        let report = build_diff_report(
            &CheckOutput {
                schema_version: "0.1".to_string(),
                tool: "ripr".to_string(),
                mode: Mode::Draft,
                root: PathBuf::from("repo"),
                base: None,
                summary: Summary::default(),
                findings: vec![],
                preview_language_advisories: vec![PreviewLanguageAdvisory {
                    language: "typescript".to_string(),
                    file_count: 2,
                    sample_paths: vec!["src/discount.ts".to_string()],
                    enabled: true,
                }],
                no_scope_provided: false,
            },
            "origin/main",
            "HEAD",
            vec![],
            "target/ripr/receipts/test.json".to_string(),
        );

        let json = render_diff_report_json(&report)?;
        assert!(
            json.contains(r#""preview_languages""#),
            "expected preview_languages in JSON; got:\n{json}"
        );
        assert!(
            json.contains(r#""language": "typescript""#),
            "expected language=typescript; got:\n{json}"
        );
        assert!(
            json.contains(r#""file_count": 2"#),
            "expected file_count=2; got:\n{json}"
        );
        assert!(
            json.contains(r#""category": "preview_language_advisory""#),
            "expected category; got:\n{json}"
        );
        assert!(
            json.contains("preview adapter; advisory"),
            "expected why note; got:\n{json}"
        );
        Ok(())
    }

    #[test]
    fn diff_report_omits_preview_languages_for_pure_rust_scope() -> Result<(), String> {
        let report = build_diff_report(
            &CheckOutput {
                schema_version: "0.1".to_string(),
                tool: "ripr".to_string(),
                mode: Mode::Draft,
                root: PathBuf::from("repo"),
                base: None,
                summary: Summary::default(),
                findings: vec![],
                preview_language_advisories: Vec::new(),
                no_scope_provided: false,
            },
            "origin/main",
            "HEAD",
            vec![],
            "target/ripr/receipts/test.json".to_string(),
        );

        let json = render_diff_report_json(&report)?;
        assert!(
            !json.contains("preview_languages"),
            "pure-Rust scope must not emit preview_languages in JSON; got:\n{json}"
        );
        Ok(())
    }
}