ripr 0.5.0

Find Rust test-oracle gaps before mutation testing with static RIPR evidence
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! Render the first-run pilot packet summary.
//!
//! `ripr pilot` joins existing repo-exposure and agent packet artifacts with
//! one small operator summary. It does not change classification semantics or
//! run additional analysis.

use crate::agent::loop_commands::{self, display_path};
use crate::analysis::ClassifiedSeam;
use crate::analysis::seams::SeamGripClass;
use crate::app::Mode;
use crate::output::agent_seam_packets::{
    suggested_assertion_for_classified_seam, targeted_test_brief_for_classified_seam,
    targeted_test_brief_outline_for_classified_seam,
};
use crate::output::json::escape as json_escape;
use std::cmp::Ordering;
use std::path::{Path, PathBuf};

pub(crate) const PILOT_SUMMARY_SCHEMA_VERSION: &str = "0.2";

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PilotArtifacts {
    pub(crate) repo_exposure_json: PathBuf,
    pub(crate) repo_exposure_md: PathBuf,
    pub(crate) agent_seam_packets_json: PathBuf,
    pub(crate) pilot_summary_json: PathBuf,
    pub(crate) pilot_summary_md: PathBuf,
}

#[derive(Clone, Copy)]
pub(crate) struct PilotSummaryContext<'a> {
    pub(crate) root: &'a Path,
    pub(crate) mode: &'a Mode,
    pub(crate) config_path: Option<&'a Path>,
    pub(crate) max_seams: usize,
    pub(crate) timeout_ms: u64,
    pub(crate) artifacts: &'a PilotArtifacts,
}

pub(crate) fn render_pilot_summary_json(
    classified: &[ClassifiedSeam],
    context: PilotSummaryContext<'_>,
) -> String {
    let actionable_total = actionable_total(classified);
    let top = top_actionable_seams(classified, context.max_seams);
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("{\n");
    out.push_str(&format!(
        "  \"schema_version\": \"{}\",\n",
        PILOT_SUMMARY_SCHEMA_VERSION
    ));
    out.push_str("  \"tool\": \"ripr\",\n");
    out.push_str("  \"scope\": \"repo\",\n");
    out.push_str("  \"status\": \"complete\",\n");
    out.push_str(&format!(
        "  \"root\": \"{}\",\n",
        json_escape(&display_path(context.root))
    ));
    out.push_str(&format!("  \"mode\": \"{}\",\n", context.mode.as_str()));
    out.push_str("  \"config\": {");
    match context.config_path {
        Some(path) => out.push_str(&format!(
            "\"state\": \"loaded\", \"path\": \"{}\"",
            json_escape(&display_path(path))
        )),
        None => out.push_str("\"state\": \"missing\", \"path\": null"),
    }
    out.push_str("},\n");

    out.push_str("  \"outputs\": {\n");
    push_path_field(
        &mut out,
        "repo_exposure_json",
        &context.artifacts.repo_exposure_json,
        true,
    );
    push_path_field(
        &mut out,
        "repo_exposure_md",
        &context.artifacts.repo_exposure_md,
        true,
    );
    push_path_field(
        &mut out,
        "agent_seam_packets_json",
        &context.artifacts.agent_seam_packets_json,
        true,
    );
    push_path_field(
        &mut out,
        "pilot_summary_json",
        &context.artifacts.pilot_summary_json,
        true,
    );
    push_path_field(
        &mut out,
        "pilot_summary_md",
        &context.artifacts.pilot_summary_md,
        false,
    );
    out.push_str("  },\n");

    out.push_str(&format!("  \"max_seams\": {},\n", context.max_seams));
    out.push_str(&format!("  \"timeout_ms\": {},\n", context.timeout_ms));
    out.push_str("  \"outputs_written\": [\n");
    out.push_str("    \"repo_exposure_json\",\n");
    out.push_str("    \"repo_exposure_md\",\n");
    out.push_str("    \"agent_seam_packets_json\",\n");
    out.push_str("    \"pilot_summary_json\",\n");
    out.push_str("    \"pilot_summary_md\"\n");
    out.push_str("  ],\n");
    out.push_str(&format!(
        "  \"actionable_seams_total\": {},\n",
        actionable_total
    ));
    out.push_str("  \"top_actionable_seams\": [");
    for (idx, entry) in top.iter().enumerate() {
        if idx == 0 {
            out.push('\n');
        }
        push_top_seam_json(&mut out, entry);
        if idx + 1 != top.len() {
            out.push_str(",\n");
        } else {
            out.push('\n');
        }
    }
    if !top.is_empty() {
        out.push_str("  ");
    }
    out.push_str("],\n");
    out.push_str("  \"next\": {\n");
    out.push_str(&format!(
        "    \"inspect_packet\": \"{}\",\n",
        json_escape(&display_path(&context.artifacts.agent_seam_packets_json))
    ));
    out.push_str(&format!(
        "    \"after_snapshot_command\": \"{}\",\n",
        json_escape(&commands.after_snapshot)
    ));
    out.push_str(&format!(
        "    \"outcome_command\": \"{}\"\n",
        json_escape(&commands.outcome)
    ));
    out.push_str("  }\n");
    out.push_str("}\n");
    out
}

pub(crate) fn render_pilot_summary_md(
    classified: &[ClassifiedSeam],
    context: PilotSummaryContext<'_>,
) -> String {
    let actionable_total = actionable_total(classified);
    let top = top_actionable_seams(classified, context.max_seams);
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("# RIPR Pilot Summary\n\n");
    out.push_str("## What Was Inspected\n\n");
    out.push_str("- Status: `complete`\n");
    out.push_str(&format!("- Root: `{}`\n", display_path(context.root)));
    out.push_str(&format!("- Mode: `{}`\n", context.mode.as_str()));
    out.push_str(&format!("- Timeout: {} ms\n", context.timeout_ms));
    match context.config_path {
        Some(path) => out.push_str(&format!("- Config: loaded `{}`\n", display_path(path))),
        None => out.push_str("- Config: missing; using built-in defaults\n"),
    }
    out.push_str(&format!(
        "- Actionable seams: {} total, showing up to {}\n\n",
        actionable_total, context.max_seams
    ));

    if top.is_empty() {
        out.push_str("## Top Recommendation\n\n");
        out.push_str("No actionable seam was ranked by the default pilot policy.\n\n");
    } else {
        out.push_str("## Top Recommendation\n\n");
        push_markdown_recommendation(&mut out, top[0]);
        out.push('\n');

        out.push_str("## Ranked Actionable Seams\n\n");
        for (idx, entry) in top.iter().enumerate() {
            out.push_str(&format!(
                "{}. `{}` `{}` {}:{} `{}`\n",
                idx + 1,
                entry.seam.id().as_str(),
                entry.class.as_str(),
                display_path(entry.seam.file()),
                entry.seam.display_line(),
                entry.seam.kind().as_str()
            ));
            out.push_str(&format!("   - Owner: `{}`\n", entry.seam.owner()));
            out.push_str(&format!("   - Why: {}\n", why_line(entry)));
            out.push_str(&format!(
                "   - Related test present: {}\n",
                yes_no(!entry.evidence.related_tests.is_empty())
            ));
            out.push_str(&format!(
                "   - Suggested assertion present: {}\n",
                yes_no(suggested_assertion_for_classified_seam(entry).is_some())
            ));
            out.push('\n');
        }
    }

    out.push_str("## Outputs\n\n");
    out.push_str(&format!(
        "- Repo exposure JSON: `{}`\n",
        display_path(&context.artifacts.repo_exposure_json)
    ));
    out.push_str(&format!(
        "- Repo exposure Markdown: `{}`\n",
        display_path(&context.artifacts.repo_exposure_md)
    ));
    out.push_str(&format!(
        "- Agent seam packets: `{}`\n",
        display_path(&context.artifacts.agent_seam_packets_json)
    ));
    out.push_str(&format!(
        "- Pilot summary JSON: `{}`\n\n",
        display_path(&context.artifacts.pilot_summary_json)
    ));

    out.push_str("## Next Commands\n\n");
    out.push_str(
        "After adding one focused test, rerun repo exposure and compare the snapshots:\n\n",
    );
    out.push_str("```bash\n");
    out.push_str(&commands.after_snapshot);
    out.push('\n');
    out.push_str(&commands.outcome);
    out.push_str("\n```\n");
    out
}

pub(crate) fn render_pilot_terminal(
    classified: &[ClassifiedSeam],
    context: PilotSummaryContext<'_>,
) -> String {
    let top = top_actionable_seams(classified, 1);
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("RIPR pilot complete.\n\n");
    out.push_str("Inspected:\n");
    out.push_str(&format!("  root: {}\n", display_path(context.root)));
    out.push_str(&format!("  mode: {}\n", context.mode.as_str()));
    match context.config_path {
        Some(path) => out.push_str(&format!("  config: loaded {}\n", display_path(path))),
        None => out.push_str("  config: missing, using built-in defaults\n"),
    }
    out.push_str(&format!("  timeout: {} ms\n", context.timeout_ms));
    out.push('\n');

    if let Some(entry) = top.first() {
        let outline = targeted_test_brief_outline_for_classified_seam(entry);
        out.push_str("Top recommendation:\n");
        out.push_str(&format!(
            "  inspected seam: {}:{} {} in {} ({})\n",
            display_path(entry.seam.file()),
            entry.seam.display_line(),
            entry.seam.kind().as_str(),
            entry.seam.owner(),
            entry.class.as_str()
        ));
        out.push_str(&format!("  why it matters: {}\n", why_line(entry)));
        out.push_str(&format!(
            "  focused test: add {} in {}\n",
            outline.suggested_name,
            display_path_text(&outline.suggested_file)
        ));
        if let Some(value) = outline.candidate_value.as_ref() {
            out.push_str(&format!("  candidate value: {value}\n"));
        }
        out.push_str(&format!("  assertion: {}\n\n", outline.assertion_shape));
    } else {
        out.push_str("Top recommendation:\n");
        out.push_str("  none ranked by the default pilot policy\n\n");
    }

    out.push_str("Detailed brief:\n");
    out.push_str(&format!(
        "  {}\n",
        display_path(&context.artifacts.pilot_summary_md)
    ));
    out.push_str("Structured packet:\n");
    out.push_str(&format!(
        "  {}\n\n",
        display_path(&context.artifacts.agent_seam_packets_json)
    ));
    out.push_str("Run after adding the focused test:\n");
    out.push_str(&format!("  {}\n", commands.after_snapshot));
    out.push_str(&format!("  {}\n", commands.outcome));
    out
}

pub(crate) fn render_pilot_timeout_summary_json(context: PilotSummaryContext<'_>) -> String {
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("{\n");
    out.push_str(&format!(
        "  \"schema_version\": \"{}\",\n",
        PILOT_SUMMARY_SCHEMA_VERSION
    ));
    out.push_str("  \"tool\": \"ripr\",\n");
    out.push_str("  \"scope\": \"repo\",\n");
    out.push_str("  \"status\": \"partial\",\n");
    out.push_str("  \"reason\": \"timeout\",\n");
    out.push_str(&format!("  \"timeout_ms\": {},\n", context.timeout_ms));
    out.push_str("  \"completed_phases\": [],\n");
    out.push_str(&format!(
        "  \"root\": \"{}\",\n",
        json_escape(&display_path(context.root))
    ));
    out.push_str(&format!("  \"mode\": \"{}\",\n", context.mode.as_str()));
    out.push_str("  \"config\": {");
    match context.config_path {
        Some(path) => out.push_str(&format!(
            "\"state\": \"loaded\", \"path\": \"{}\"",
            json_escape(&display_path(path))
        )),
        None => out.push_str("\"state\": \"missing\", \"path\": null"),
    }
    out.push_str("},\n");

    out.push_str("  \"outputs\": {\n");
    push_path_field(
        &mut out,
        "repo_exposure_json",
        &context.artifacts.repo_exposure_json,
        true,
    );
    push_path_field(
        &mut out,
        "repo_exposure_md",
        &context.artifacts.repo_exposure_md,
        true,
    );
    push_path_field(
        &mut out,
        "agent_seam_packets_json",
        &context.artifacts.agent_seam_packets_json,
        true,
    );
    push_path_field(
        &mut out,
        "pilot_summary_json",
        &context.artifacts.pilot_summary_json,
        true,
    );
    push_path_field(
        &mut out,
        "pilot_summary_md",
        &context.artifacts.pilot_summary_md,
        false,
    );
    out.push_str("  },\n");

    out.push_str("  \"outputs_written\": [\n");
    out.push_str("    \"pilot_summary_json\",\n");
    out.push_str("    \"pilot_summary_md\"\n");
    out.push_str("  ],\n");
    out.push_str(&format!("  \"max_seams\": {},\n", context.max_seams));
    out.push_str("  \"actionable_seams_total\": null,\n");
    out.push_str("  \"top_actionable_seams\": [],\n");
    out.push_str("  \"next\": {\n");
    out.push_str(&format!(
        "    \"retry_command\": \"{}\"\n",
        json_escape(&commands.retry)
    ));
    out.push_str("  }\n");
    out.push_str("}\n");
    out
}

pub(crate) fn render_pilot_timeout_summary_md(context: PilotSummaryContext<'_>) -> String {
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("# RIPR Pilot Summary\n\n");
    out.push_str("## Scope\n\n");
    out.push_str("- Status: `partial`\n");
    out.push_str(&format!(
        "- Reason: analysis timed out after {} ms\n",
        context.timeout_ms
    ));
    out.push_str(&format!("- Root: `{}`\n", display_path(context.root)));
    out.push_str(&format!("- Mode: `{}`\n", context.mode.as_str()));
    match context.config_path {
        Some(path) => out.push_str(&format!("- Config: loaded `{}`\n\n", display_path(path))),
        None => out.push_str("- Config: missing; using built-in defaults\n\n"),
    }

    out.push_str("## Outputs\n\n");
    out.push_str("Analysis did not finish within the pilot budget, so repo exposure and agent seam packet files were not written.\n\n");
    out.push_str(&format!(
        "- Pilot summary JSON: `{}`\n",
        display_path(&context.artifacts.pilot_summary_json)
    ));
    out.push_str(&format!(
        "- Pilot summary Markdown: `{}`\n\n",
        display_path(&context.artifacts.pilot_summary_md)
    ));

    out.push_str("## Next Command\n\n");
    out.push_str("Rerun with a larger explicit budget:\n\n");
    out.push_str("```bash\n");
    out.push_str(&commands.retry);
    out.push_str("\n```\n");
    out
}

pub(crate) fn render_pilot_timeout_terminal(context: PilotSummaryContext<'_>) -> String {
    let commands = PilotCommands::new(context);

    let mut out = String::new();
    out.push_str("RIPR pilot partial.\n\n");
    out.push_str("Reason:\n");
    out.push_str(&format!(
        "  analysis timed out after {} ms\n\n",
        context.timeout_ms
    ));
    out.push_str("Config:\n");
    match context.config_path {
        Some(path) => out.push_str(&format!("  loaded: {}\n", display_path(path))),
        None => out.push_str("  missing: using built-in defaults\n"),
    }
    out.push('\n');
    out.push_str("Written:\n");
    out.push_str(&format!(
        "  {}\n",
        display_path(&context.artifacts.pilot_summary_json)
    ));
    out.push_str(&format!(
        "  {}\n\n",
        display_path(&context.artifacts.pilot_summary_md)
    ));
    out.push_str("Next:\n");
    out.push_str(&format!("  {}\n", commands.retry));
    out
}

pub(crate) fn top_actionable_seams(
    classified: &[ClassifiedSeam],
    max_seams: usize,
) -> Vec<&ClassifiedSeam> {
    let mut actionable = classified
        .iter()
        .filter(|entry| class_rank(entry.class).is_some())
        .collect::<Vec<_>>();
    actionable.sort_by(|left, right| compare_ranked_seams(left, right));
    actionable.truncate(max_seams);
    actionable
}

fn actionable_total(classified: &[ClassifiedSeam]) -> usize {
    classified
        .iter()
        .filter(|entry| class_rank(entry.class).is_some())
        .count()
}

fn compare_ranked_seams(left: &ClassifiedSeam, right: &ClassifiedSeam) -> Ordering {
    class_rank(left.class)
        .cmp(&class_rank(right.class))
        .then(
            bool_rank(!left.evidence.missing_discriminators.is_empty()).cmp(&bool_rank(
                !right.evidence.missing_discriminators.is_empty(),
            )),
        )
        .then(
            bool_rank(!left.evidence.related_tests.is_empty())
                .cmp(&bool_rank(!right.evidence.related_tests.is_empty())),
        )
        .then(
            bool_rank(suggested_assertion_for_classified_seam(left).is_some()).cmp(&bool_rank(
                suggested_assertion_for_classified_seam(right).is_some(),
            )),
        )
        .then(display_path(left.seam.file()).cmp(&display_path(right.seam.file())))
        .then(left.seam.display_line().cmp(&right.seam.display_line()))
        .then(left.seam.kind().as_str().cmp(right.seam.kind().as_str()))
        .then(left.seam.id().as_str().cmp(right.seam.id().as_str()))
}

fn class_rank(class: SeamGripClass) -> Option<u8> {
    Some(match class {
        SeamGripClass::WeaklyGripped => 0,
        SeamGripClass::Ungripped => 1,
        SeamGripClass::ReachableUnrevealed => 2,
        SeamGripClass::ActivationUnknown
        | SeamGripClass::PropagationUnknown
        | SeamGripClass::ObservationUnknown
        | SeamGripClass::DiscriminationUnknown => 3,
        SeamGripClass::Opaque => 4,
        SeamGripClass::StronglyGripped | SeamGripClass::Intentional | SeamGripClass::Suppressed => {
            return None;
        }
    })
}

fn bool_rank(value: bool) -> u8 {
    if value { 0 } else { 1 }
}

fn push_top_seam_json(out: &mut String, entry: &ClassifiedSeam) {
    out.push_str("    {\n");
    out.push_str(&format!(
        "      \"seam_id\": \"{}\",\n",
        json_escape(entry.seam.id().as_str())
    ));
    out.push_str(&format!(
        "      \"file\": \"{}\",\n",
        json_escape(&display_path(entry.seam.file()))
    ));
    out.push_str(&format!("      \"line\": {},\n", entry.seam.display_line()));
    out.push_str(&format!(
        "      \"kind\": \"{}\",\n",
        entry.seam.kind().as_str()
    ));
    out.push_str(&format!(
        "      \"owner\": \"{}\",\n",
        json_escape(entry.seam.owner())
    ));
    out.push_str(&format!(
        "      \"grip_class\": \"{}\",\n",
        entry.class.as_str()
    ));
    out.push_str(&format!(
        "      \"why\": \"{}\",\n",
        json_escape(&why_line(entry))
    ));
    out.push_str("      \"missing_discriminator\": ");
    if let Some(missing) = entry.evidence.missing_discriminators.first() {
        out.push_str(&format!(
            "{{\"value\": \"{}\", \"reason\": \"{}\"}}",
            json_escape(&missing.value),
            json_escape(&missing.reason)
        ));
    } else {
        out.push_str("null");
    }
    out.push_str(",\n");
    out.push_str(&format!(
        "      \"related_test_present\": {},\n",
        !entry.evidence.related_tests.is_empty()
    ));
    out.push_str(&format!(
        "      \"suggested_assertion_present\": {},\n",
        suggested_assertion_for_classified_seam(entry).is_some()
    ));
    out.push_str(&format!(
        "      \"targeted_test_brief\": \"{}\"\n",
        json_escape(&targeted_test_brief_for_classified_seam(entry))
    ));
    out.push_str("    }");
}

fn push_markdown_recommendation(out: &mut String, entry: &ClassifiedSeam) {
    let outline = targeted_test_brief_outline_for_classified_seam(entry);
    out.push_str(&format!(
        "- Inspected seam: `{}` {}:{} `{}` in `{}` (`{}`)\n",
        entry.seam.id().as_str(),
        display_path(entry.seam.file()),
        entry.seam.display_line(),
        entry.seam.kind().as_str(),
        entry.seam.owner(),
        entry.class.as_str()
    ));
    out.push_str(&format!("- Why it matters: {}\n", why_line(entry)));
    out.push_str(&format!(
        "- Focused test: add `{}` in `{}`\n",
        outline.suggested_name,
        display_path_text(&outline.suggested_file)
    ));
    if let Some(value) = outline.candidate_value.as_ref() {
        out.push_str(&format!("- Candidate value: `{value}`\n"));
    }
    out.push_str(&format!(
        "- Assertion shape: `{}`\n",
        outline.assertion_shape
    ));
    out.push_str("- Detailed work order:\n\n");
    out.push_str("```text\n");
    out.push_str(&targeted_test_brief_for_classified_seam(entry));
    out.push_str("```\n");
}

fn push_path_field(out: &mut String, name: &str, path: &Path, trailing: bool) {
    out.push_str(&format!(
        "    \"{}\": \"{}\"{}\n",
        name,
        json_escape(&display_path(path)),
        if trailing { "," } else { "" }
    ));
}

fn why_line(entry: &ClassifiedSeam) -> String {
    if let Some(missing) = entry.evidence.missing_discriminators.first() {
        return format!(
            "missing discriminator: {} ({})",
            missing.value, missing.reason
        );
    }
    let summary = entry.evidence.discriminate.summary.trim();
    if !summary.is_empty() {
        return format!("static discriminator summary: {summary}");
    }
    format!("{} static seam evidence", entry.class.as_str())
}

fn yes_no(value: bool) -> &'static str {
    if value { "yes" } else { "no" }
}

struct PilotCommands {
    after_snapshot: String,
    outcome: String,
    retry: String,
}

impl PilotCommands {
    fn new(context: PilotSummaryContext<'_>) -> Self {
        let out_dir = context
            .artifacts
            .pilot_summary_json
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        let after_path = context
            .artifacts
            .pilot_summary_json
            .parent()
            .map(|dir| dir.join("after.repo-exposure.json"))
            .unwrap_or_else(|| PathBuf::from("after.repo-exposure.json"));
        let after_snapshot = loop_commands::check_repo_exposure_command(
            &display_path(context.root),
            context.mode.as_str(),
            &loop_commands::shell_path(&after_path),
        );
        let outcome = loop_commands::outcome_command(
            &loop_commands::shell_path(&context.artifacts.repo_exposure_json),
            &loop_commands::shell_path(&after_path),
            None,
        );
        let retry_timeout_ms = context.timeout_ms.saturating_mul(4).max(120_000);
        let retry = format!(
            "ripr pilot --root {} --out {} --mode {} --max-seams {} --timeout-ms {}",
            loop_commands::shell_path(context.root),
            loop_commands::shell_path(&out_dir),
            context.mode.as_str(),
            context.max_seams,
            retry_timeout_ms
        );
        Self {
            after_snapshot,
            outcome,
            retry,
        }
    }
}

fn display_path_text(path: &str) -> String {
    path.replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::seams::{ExpectedSink, RepoSeam, RequiredDiscriminator, SeamKind};
    use crate::analysis::test_grip_evidence::{
        RelatedTestGrip, RelationConfidence, RelationReason, TestGripEvidence,
    };
    use crate::domain::{
        Confidence, MissingDiscriminatorFact, OracleKind, OracleStrength, StageEvidence,
        StageState, ValueFact,
    };

    fn seam(file: &str, line: usize, expression: &str) -> RepoSeam {
        RepoSeam::new(
            file,
            "pricing::discounted_total",
            SeamKind::PredicateBoundary,
            line * 10,
            line,
            expression,
            RequiredDiscriminator::BoundaryValue {
                description: expression.to_string(),
            },
            ExpectedSink::ReturnValue,
        )
    }

    fn stage(state: StageState) -> StageEvidence {
        StageEvidence::new(state, Confidence::Medium, "stage summary")
    }

    fn missing() -> MissingDiscriminatorFact {
        MissingDiscriminatorFact {
            value: "discount_threshold equality boundary".to_string(),
            reason: "observed values do not include the equality-boundary case".to_string(),
            flow_sink: None,
        }
    }

    fn related_test() -> RelatedTestGrip {
        RelatedTestGrip {
            test_name: "below_threshold_has_no_discount".to_string(),
            file: PathBuf::from("tests/pricing.rs"),
            line: 12,
            oracle_kind: OracleKind::ExactValue,
            oracle_strength: OracleStrength::Strong,
            evidence_summary: "exact value assertion".to_string(),
            relation_reason: RelationReason::DirectOwnerCall,
            relation_confidence: RelationConfidence::High,
        }
    }

    fn pilot_artifacts() -> PilotArtifacts {
        PilotArtifacts {
            repo_exposure_json: PathBuf::from("target/ripr/pilot/repo-exposure.json"),
            repo_exposure_md: PathBuf::from("target/ripr/pilot/repo-exposure.md"),
            agent_seam_packets_json: PathBuf::from("target/ripr/pilot/agent-seam-packets.json"),
            pilot_summary_json: PathBuf::from("target/ripr/pilot/pilot-summary.json"),
            pilot_summary_md: PathBuf::from("target/ripr/pilot/pilot-summary.md"),
        }
    }

    fn pilot_context(artifacts: &PilotArtifacts) -> PilotSummaryContext<'_> {
        PilotSummaryContext {
            root: Path::new("."),
            mode: &Mode::Draft,
            config_path: Some(Path::new("ripr.toml")),
            max_seams: 5,
            timeout_ms: 30_000,
            artifacts,
        }
    }

    fn classified_with(
        class: SeamGripClass,
        file: &str,
        line: usize,
        missing_discriminators: Vec<MissingDiscriminatorFact>,
        related_tests: Vec<RelatedTestGrip>,
    ) -> ClassifiedSeam {
        let seam = seam(file, line, "amount >= discount_threshold");
        ClassifiedSeam {
            evidence: TestGripEvidence {
                seam_id: seam.id().clone(),
                related_tests,
                reach: stage(StageState::Yes),
                activate: stage(StageState::Yes),
                propagate: stage(StageState::Yes),
                observe: stage(StageState::Yes),
                discriminate: stage(StageState::Weak),
                observed_values: Vec::<ValueFact>::new(),
                missing_discriminators,
            },
            seam,
            class,
        }
    }

    #[test]
    fn pilot_ranking_prefers_actionable_class_order_before_tie_breakers() {
        let ungripped = classified_with(
            SeamGripClass::Ungripped,
            "src/a.rs",
            10,
            vec![missing()],
            vec![related_test()],
        );
        let weak = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/z.rs",
            99,
            Vec::new(),
            Vec::new(),
        );

        let entries = [ungripped, weak];
        let ranked = top_actionable_seams(&entries, 5);
        assert_eq!(ranked[0].class, SeamGripClass::WeaklyGripped);
        assert_eq!(ranked[1].class, SeamGripClass::Ungripped);
    }

    #[test]
    fn pilot_ranking_uses_evidence_tie_breakers_then_stable_location() {
        let no_missing = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/a.rs",
            10,
            Vec::new(),
            vec![related_test()],
        );
        let with_missing = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/b.rs",
            10,
            vec![missing()],
            Vec::new(),
        );
        let stable_first = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/c.rs",
            10,
            Vec::new(),
            Vec::new(),
        );
        let stable_second = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/d.rs",
            10,
            Vec::new(),
            Vec::new(),
        );

        let entries = [stable_second, stable_first, no_missing, with_missing];
        let ranked = top_actionable_seams(&entries, 5);
        assert_eq!(display_path(ranked[0].seam.file()), "src/b.rs");
        assert_eq!(display_path(ranked[1].seam.file()), "src/a.rs");
        assert_eq!(display_path(ranked[2].seam.file()), "src/c.rs");
        assert_eq!(display_path(ranked[3].seam.file()), "src/d.rs");
    }

    #[test]
    fn pilot_ranking_excludes_solved_governed_classes() {
        let strong = classified_with(
            SeamGripClass::StronglyGripped,
            "src/strong.rs",
            1,
            Vec::new(),
            Vec::new(),
        );
        let intentional = classified_with(
            SeamGripClass::Intentional,
            "src/intentional.rs",
            2,
            Vec::new(),
            Vec::new(),
        );
        let suppressed = classified_with(
            SeamGripClass::Suppressed,
            "src/suppressed.rs",
            3,
            Vec::new(),
            Vec::new(),
        );
        let opaque = classified_with(
            SeamGripClass::Opaque,
            "src/opaque.rs",
            4,
            Vec::new(),
            Vec::new(),
        );

        let entries = [strong, intentional, suppressed, opaque];
        let ranked = top_actionable_seams(&entries, 5);
        assert_eq!(ranked.len(), 1);
        assert_eq!(ranked[0].class, SeamGripClass::Opaque);
    }

    #[test]
    fn pilot_summary_json_contains_config_state_artifacts_and_next_commands() {
        let entry = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/pricing.rs",
            88,
            vec![missing()],
            vec![related_test()],
        );
        let artifacts = PilotArtifacts {
            repo_exposure_json: PathBuf::from("target/ripr/pilot/repo-exposure.json"),
            repo_exposure_md: PathBuf::from("target/ripr/pilot/repo-exposure.md"),
            agent_seam_packets_json: PathBuf::from("target/ripr/pilot/agent-seam-packets.json"),
            pilot_summary_json: PathBuf::from("target/ripr/pilot/pilot-summary.json"),
            pilot_summary_md: PathBuf::from("target/ripr/pilot/pilot-summary.md"),
        };
        let context = PilotSummaryContext {
            root: Path::new("."),
            mode: &Mode::Draft,
            config_path: Some(Path::new("ripr.toml")),
            max_seams: 5,
            timeout_ms: 30_000,
            artifacts: &artifacts,
        };

        let json = render_pilot_summary_json(&[entry], context);
        assert!(json.contains(r#""schema_version": "0.2""#));
        assert!(json.contains(r#""status": "complete""#));
        assert!(json.contains(r#""state": "loaded""#));
        assert!(json.contains(r#""top_actionable_seams""#));
        assert!(json.contains(r#""missing_discriminator""#));
        assert!(json.contains("ripr outcome --before target/ripr/pilot/repo-exposure.json"));
    }

    #[test]
    fn pilot_summary_md_spells_out_first_screen_recommendation() {
        let entry = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/pricing.rs",
            88,
            vec![missing()],
            vec![related_test()],
        );
        let artifacts = pilot_artifacts();
        let md = render_pilot_summary_md(&[entry], pilot_context(&artifacts));

        for needle in [
            "## What Was Inspected",
            "## Top Recommendation",
            "- Inspected seam:",
            "- Why it matters: missing discriminator: discount_threshold equality boundary",
            "- Focused test: add `discounted_total_boundary_discriminator` in `tests/pricing.rs`",
            "- Candidate value: `discount_threshold equality boundary`",
            "Target seam:",
            "Add a targeted test:",
            "## Next Commands",
            "ripr outcome --before target/ripr/pilot/repo-exposure.json",
        ] {
            assert!(md.contains(needle), "missing markdown needle: {needle}");
        }
    }

    #[test]
    fn pilot_terminal_prints_top_test_and_follow_up_commands() {
        let entry = classified_with(
            SeamGripClass::WeaklyGripped,
            "src/pricing.rs",
            88,
            vec![missing()],
            vec![related_test()],
        );
        let artifacts = pilot_artifacts();
        let terminal = render_pilot_terminal(&[entry], pilot_context(&artifacts));

        for needle in [
            "Inspected:",
            "root: .",
            "mode: draft",
            "config: loaded ripr.toml",
            "Top recommendation:",
            "inspected seam: src/pricing.rs:88 predicate_boundary in pricing::discounted_total (weakly_gripped)",
            "why it matters: missing discriminator: discount_threshold equality boundary",
            "focused test: add discounted_total_boundary_discriminator in tests/pricing.rs",
            "candidate value: discount_threshold equality boundary",
            "assertion: assert_eq!(discounted_total(/* discount_threshold equality boundary */), /* expected */)",
            "Detailed brief:",
            "target/ripr/pilot/pilot-summary.md",
            "Structured packet:",
            "target/ripr/pilot/agent-seam-packets.json",
            "Run after adding the focused test:",
            "ripr check --root . --mode draft --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json",
            "ripr outcome --before target/ripr/pilot/repo-exposure.json",
        ] {
            assert!(
                terminal.contains(needle),
                "missing terminal needle: {needle}"
            );
        }
    }

    #[test]
    fn timeout_summary_json_is_partial_and_points_to_retry() {
        let artifacts = PilotArtifacts {
            repo_exposure_json: PathBuf::from("target/ripr/pilot/repo-exposure.json"),
            repo_exposure_md: PathBuf::from("target/ripr/pilot/repo-exposure.md"),
            agent_seam_packets_json: PathBuf::from("target/ripr/pilot/agent-seam-packets.json"),
            pilot_summary_json: PathBuf::from("target/ripr/pilot/pilot-summary.json"),
            pilot_summary_md: PathBuf::from("target/ripr/pilot/pilot-summary.md"),
        };
        let context = PilotSummaryContext {
            root: Path::new("."),
            mode: &Mode::Draft,
            config_path: None,
            max_seams: 5,
            timeout_ms: 1,
            artifacts: &artifacts,
        };

        let json = render_pilot_timeout_summary_json(context);
        assert!(json.contains(r#""schema_version": "0.2""#));
        assert!(json.contains(r#""status": "partial""#));
        assert!(json.contains(r#""reason": "timeout""#));
        assert!(json.contains(r#""actionable_seams_total": null"#));
        assert!(json.contains("ripr pilot --root . --out target/ripr/pilot --mode draft"));
        assert!(json.contains("--timeout-ms 120000"));
    }
}