repon-core 0.30.1

Rendering-agnostic core for Repon: computes git state, knows nothing about terminals
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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! The row summary fold and the Snapshot a consumer reads.
//!
//! See `docs/spec/core-api.md`'s "The row summary" and "The snapshot" sections, and
//! [ADR 0015](https://github.com/paulchiu/repon/blob/main/docs/adr/0015-the-core-owns-the-table.md)
//! for why this is a clone read rather than a channel of cell updates: the terminal
//! interface's event loop is a blocking receive on one channel already, so a second
//! channel would not wake it, and a full-table clone measures in microseconds
//! against a 16.7 millisecond frame.

use crate::cell::{Cell, Generation, Settled, Timestamp};
use crate::entity::{ActionReceipt, Diagnostics, EntityState};

/// The one state a row's Cells fold into, for the gutter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowSummary {
    Fresh,
    Stale,
    Unknown,
    Failed,
    InFlight,
}

/// Where one Cell sits on the settledness scale `summary` folds over.
/// `NotApplicable` cells never reach this: they are excluded before folding.
/// Declared worst-last, so `Ord` gives the least settled cell as the maximum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Settledness {
    Fresh,
    Stale,
    Unknown,
    Failed,
}

/// Reads a [`Cell<T>`]'s contribution to the fold, uniformly across every payload
/// type `EntityState` carries, without a shared payload trait.
trait FoldableCell {
    fn settledness(&self) -> Option<Settledness>;
    /// Whether this Cell has ever settled to a genuine value: `Known`, `Unknown`
    /// or `Failed`. Never-probed and `NotApplicable` both read `false`, since
    /// neither is a value the row's first-probe spinner rule should treat as
    /// already shown.
    fn holds_a_value(&self) -> bool;
}

impl<T> FoldableCell for Cell<T> {
    fn settledness(&self) -> Option<Settledness> {
        match self.settled() {
            Some(Settled::NotApplicable) => None,
            Some(Settled::Known {
                stale: false,
                value: _,
                at: _,
            }) => Some(Settledness::Fresh),
            Some(Settled::Known {
                stale: true,
                value: _,
                at: _,
            }) => Some(Settledness::Stale),
            Some(Settled::Unknown(_)) => Some(Settledness::Unknown),
            Some(Settled::Failed(_)) => Some(Settledness::Failed),
            // Nothing has settled this Cell yet, whether a probe is currently
            // running against it or none has been dispatched at all: it carries
            // no settled fact for the fold to weigh, the same exclusion
            // `NotApplicable` gets, rather than the `Unknown` this used to read
            // as. `docs/spec/refresh.md`'s "What the gutter and the cells show"
            // is what this excludes for: once the row holds another value, an
            // outstanding Cell shows its own loading mark rather than dragging
            // the row's gutter to `?`.
            None => None,
        }
    }

    fn holds_a_value(&self) -> bool {
        matches!(
            self.settled(),
            Some(Settled::Known {
                value: _,
                at: _,
                stale: _
            }) | Some(Settled::Unknown(_))
                | Some(Settled::Failed(_))
        )
    }
}

/// Folds one Entity's Cells into the state its row's gutter shows.
///
/// In-flight outranks the least-settled summary while the row holds no values
/// at all, its first probe, regardless of whether a probe happens to be
/// dispatched against it yet: `docs/spec/core-api.md`'s `Cell` carries the same
/// "nothing has looked at this yet" fact either way, and
/// `docs/spec/refresh.md`'s "Startup is Generation 1 with an empty prior state"
/// is what makes that fact Loading rather than Unknown. Once any Cell has
/// settled to something, the gutter falls back to the row's least-settled
/// *settled* state instead, and a Cell nothing has settled yet is excluded from
/// that fold exactly like `NotApplicable`: its own loading mark, drawn by the
/// consumer, is what says a value is still coming (`docs/spec/refresh.md`'s
/// "What the gutter and the cells show", amended by ADR 0013). A `NotApplicable`
/// Cell is excluded from the fold entirely too, which is what lets a Repo row
/// (Worktree state Not applicable by kind) or a Worktree row on its own default
/// branch (`base` Not applicable) read Fresh, or still show the first-probe
/// spinner, on cells that simply do not apply. A Submodule row's `state` and
/// `base` are `Unknown` rather than `NotApplicable`, per
/// [ADR 0017](https://github.com/paulchiu/repon/blob/main/docs/adr/0017-discovery-stops-at-the-repo-boundary.md)
/// as amended, so they do fold in, and with the periodic fetch off (the
/// default) that is what puts `?` in a Submodule row's gutter rather than a
/// space. Otherwise the row shows its least settled Cell, widened by two
/// entity-level derivations that are not Cells at all: an unparseable
/// `.gitmodules` and a failed last Action both drive the row to `Failed` even
/// when every Cell reads fine. Before any of that, though, `last_action.running` being
/// `Some` also reads `InFlight`, outranking a `Failed` Cell and the same receipt's own
/// past failures: `Core::run_action` writes it once per step while a run is on this row
/// right now (`docs/spec/actions.md`'s "The run on screen"), so a row being retried is
/// in-flight rather than still reporting the failure it is retrying. The default branch's
/// rung and its disagreement stay out, being metadata about how a value was obtained
/// rather than a value that can itself fail.
pub fn summary(entity: &EntityState) -> RowSummary {
    // Exhaustive: a Cell or derivation source added to EntityState or Diagnostics
    // later must be named here or the pattern fails to compile, so it cannot be
    // silently left out of the fold below. This is also the only compile-time stop
    // for the exit-code predicate behind `repon status`, which folds the same Cells
    // by hand because the terminal crate forbids naming the in-progress-operation
    // field outside its detail pane; a Cell added here belongs in that fold too.
    let EntityState {
        key: _,
        name: _,
        common_dir: _,
        kind: _,
        branch,
        sync,
        base,
        dirty,
        state,
        default_branch,
        diagnostics,
        last_action,
        presence: _,
        excluded: _,
        in_progress_operation: _,
        recent_commits: _,
    } = entity;
    let Diagnostics {
        default_branch_rung: _,
        default_branch_rung_disagreement: _,
        default_branch_rung_two_stale: _,
        default_branch_stopped: _,
        gitmodules_failed,
    } = diagnostics;

    let cells: [&dyn FoldableCell; 6] = [branch, sync, base, dirty, state, default_branch];

    // No dependence on `is_in_flight` here, deliberately: "nothing has looked at
    // this Cell yet" and "a probe is running against it right now" are the same
    // "no prior state" fact from a reader's point of view, and both must read
    // Loading rather than Unknown (criterion 3). A row a Generation has not
    // reached yet and a row whose first probe is already running therefore fold
    // identically.
    let holds_no_values = cells.iter().all(|cell| !cell.holds_a_value());
    // A running Action step outranks everything below it, a failed Cell and the same
    // receipt's own past failures included: a row being retried right now is in-flight, and
    // reporting the old failure while the retry runs is the wrong answer.
    let action_running = last_action
        .as_ref()
        .is_some_and(|receipt| receipt.running.is_some());
    if holds_no_values || action_running {
        return RowSummary::InFlight;
    }

    let derivation_failed =
        gitmodules_failed.is_some() || last_action.as_ref().is_some_and(ActionReceipt::failed);

    let worst = cells
        .iter()
        .filter_map(|cell| cell.settledness())
        .chain(derivation_failed.then_some(Settledness::Failed))
        .max();

    match worst {
        None => RowSummary::Fresh,
        Some(Settledness::Fresh) => RowSummary::Fresh,
        Some(Settledness::Stale) => RowSummary::Stale,
        Some(Settledness::Unknown) => RowSummary::Unknown,
        Some(Settledness::Failed) => RowSummary::Failed,
    }
}

/// The whole table, as a consumer reads it. `Core::snapshot` clones this every
/// frame, so every field here, and everything reachable from it, is `Clone`, and
/// every text-bearing value on an [`EntityState`] is an `Arc<str>` rather than a
/// `String` precisely because of that per-frame clone.
///
/// There is no notification channel, update stream or callback anywhere on this
/// crate's public surface: a consumer reads a `Snapshot` when it decides to, it
/// never gets pushed one.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Snapshot {
    pub generation: Generation,
    pub discovered_at: Timestamp,
    pub entities: Vec<EntityState>,
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::sync::Arc;

    use super::*;
    use crate::cell::Unknown;
    use crate::entity::{
        AheadBehind, DefaultBranch, DirtyCounts, EntityKey, Head, Kind, OwnWork, StepOutcome,
        StepResult, SyncState, WorktreeState,
    };

    /// One receipt, one step per outcome given, in order: enough for the fold's own tests,
    /// which only ever ask whether *some* step failed, never which one or what it printed.
    fn receipt_with_steps(outcomes: Vec<StepOutcome>) -> ActionReceipt {
        let steps = outcomes
            .into_iter()
            .enumerate()
            .map(|(index, outcome)| StepResult {
                label: Arc::from(format!("step {index}")),
                outcome,
                output: Arc::from(&b""[..]),
                elapsed: std::time::Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            })
            .collect::<Vec<_>>();
        ActionReceipt {
            label: Arc::from("action"),
            steps: Arc::from(steps),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        }
    }

    fn fresh_entity(name: &str) -> EntityState {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new(name))),
            Arc::from(name),
            Arc::from(Path::new(name)),
            Kind::Repo,
        );
        let generation = Generation::new(1);
        entity.branch.settle(
            generation,
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("main"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.sync.settle(
            generation,
            Settled::Known {
                value: SyncState::Tracking(AheadBehind {
                    ahead: 0,
                    behind: 0,
                }),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.base.settle(
            generation,
            Settled::Known {
                value: 0,
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.dirty.settle(
            generation,
            Settled::Known {
                value: DirtyCounts::default(),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.state.settle(
            generation,
            Settled::Known {
                value: WorktreeState::Active,
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.default_branch.settle(
            generation,
            Settled::Known {
                value: DefaultBranch::new(Arc::from("main")),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity
    }

    #[test]
    fn an_entity_with_every_cell_fresh_summarises_fresh() {
        let entity = fresh_entity("repo");

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    /// ADR 0019: an in-progress git operation is not a state and not a gutter mark, read by
    /// the detail pane alone. A row stopped mid-rebase and the same row idle summarise
    /// identically here, which is what "not a gutter mark" actually means: not merely that no
    /// existing branch of `summary` happens to read the field, but that setting it never
    /// changes the fold's answer at all.
    #[test]
    fn an_in_progress_git_operation_never_changes_the_row_summary() {
        let idle = fresh_entity("repo-idle");
        let mut rebasing = fresh_entity("repo-rebasing");
        rebasing.in_progress_operation = Some(crate::git::InProgressOperation::Rebase);

        assert_eq!(summary(&idle), summary(&rebasing));
        assert_eq!(summary(&rebasing), RowSummary::Fresh);
    }

    #[test]
    fn a_not_applicable_cell_is_excluded_rather_than_dragging_the_row_down() {
        // A freshly constructed Repo has `state` Not-applicable by kind
        // (`EntityState::new`); `base` is settled Not-applicable by hand below,
        // simulating a Repo with no remote, so both of `NotApplicable`'s named
        // producers are exercised in one row. If Not-applicable were not
        // excluded, the row would still read Unknown here too, so this only
        // distinguishes a correct fold from a naive one once the other four
        // cells are made Fresh.
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("/repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("/repo/.git")),
            Kind::Repo,
        );
        let generation = Generation::new(1);
        entity.base.settle(generation, Settled::NotApplicable);
        entity.branch.settle(
            generation,
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("main"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.sync.settle(
            generation,
            Settled::Known {
                value: SyncState::Tracking(AheadBehind {
                    ahead: 0,
                    behind: 0,
                }),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.dirty.settle(
            generation,
            Settled::Known {
                value: DirtyCounts::default(),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.default_branch.settle(
            generation,
            Settled::Known {
                value: DefaultBranch::new(Arc::from("main")),
                at: Timestamp::now(),
                stale: false,
            },
        );

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    /// A freshly constructed Repo's `state` cell is `NotApplicable` rather than
    /// merely never probed, so it is excluded from the fold rather than dragging
    /// the row to Unknown. Every other cell is made Fresh here so this only tells
    /// a correct fold from a naive one once nothing else is outstanding: a
    /// genuinely never-settled Cell (as opposed to `NotApplicable`) would also
    /// be excluded now, per `a_cell_nothing_has_ever_settled_is_excluded_from_the_fold_once_the_row_holds_other_values`
    /// below, but this test is about the `NotApplicable` producer specifically.
    #[test]
    fn a_repo_rows_worktree_state_is_excluded_so_the_gutter_never_shows_a_question_mark() {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("/repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("/repo/.git")),
            Kind::Repo,
        );
        let generation = Generation::new(1);
        entity.branch.settle(
            generation,
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("main"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.sync.settle(
            generation,
            Settled::Known {
                value: SyncState::Tracking(AheadBehind {
                    ahead: 0,
                    behind: 0,
                }),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.base.settle(
            generation,
            Settled::Known {
                value: 0,
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.dirty.settle(
            generation,
            Settled::Known {
                value: DirtyCounts::default(),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.default_branch.settle(
            generation,
            Settled::Known {
                value: DefaultBranch::new(Arc::from("main")),
                at: Timestamp::now(),
                stale: false,
            },
        );
        // `state` is left exactly as construction set it: never settled again here.

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    #[test]
    fn one_failed_cell_outranks_every_other_fresh_cell() {
        let mut entity = fresh_entity("repo");
        entity.dirty.settle(
            Generation::new(2),
            Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
        );

        assert_eq!(summary(&entity), RowSummary::Failed);
    }

    #[test]
    fn once_a_row_holds_values_a_failed_cell_outranks_an_in_flight_one() {
        let mut entity = fresh_entity("repo");
        entity.dirty.settle(
            Generation::new(2),
            Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
        );
        entity.branch.begin_probe();

        assert_eq!(summary(&entity), RowSummary::Failed);
    }

    #[test]
    fn a_freshly_discovered_row_shows_in_flight_while_it_holds_no_values_at_all() {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("repo")),
            Kind::Repo,
        );

        entity.branch.begin_probe();

        assert_eq!(summary(&entity), RowSummary::InFlight);
    }

    /// A Submodule is constructed with `state` and `base` already `Unknown`
    /// (see `EntityState::new`), and `Unknown` is a genuine settled fact rather
    /// than "nothing has looked at this yet", so [`FoldableCell::holds_a_value`]
    /// correctly counts it: the row reads `?` from the moment it is discovered,
    /// before `branch`, `sync`, `dirty` or `default_branch` have been probed at
    /// all, rather than showing the first-probe spinner in the meantime. Those
    /// four cells still show their own per-cell loading mark while they settle,
    /// the same fallback an ordinary partially-probed row already gets.
    #[test]
    fn a_freshly_discovered_submodule_reads_unknown_before_any_other_cell_is_probed() {
        let entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("/repo/vendor/lib"))),
            Arc::from("lib"),
            Arc::from(Path::new("/repo/.git")),
            Kind::Submodule,
        );
        assert!(matches!(
            entity.state.settled(),
            Some(Settled::Unknown(Unknown::NoDefaultBranch))
        ));
        assert!(matches!(
            entity.base.settled(),
            Some(Settled::Unknown(Unknown::NoDefaultBranch))
        ));

        assert_eq!(summary(&entity), RowSummary::Unknown);
    }

    /// Criterion 3's "no prior state" case, constructed so the two readings this ticket
    /// exists to tell apart would actually differ: nothing has ever settled this row *and*
    /// no probe has even been dispatched yet (no `begin_probe` call anywhere), which is
    /// exactly the state `docs/spec/core-api.md`'s `Cell` doc says "only happens before the
    /// first Generation covers it". A fold that required `is_in_flight` to read InFlight
    /// would read Unknown here instead, since nothing is in flight; `docs/spec/refresh.md`'s
    /// "Startup is Generation 1 with an empty prior state" is why that would be wrong.
    #[test]
    fn a_row_with_no_prior_state_at_all_reads_in_flight_even_before_any_probe_is_dispatched() {
        let entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("repo")),
            Kind::Repo,
        );
        assert!(
            !entity.branch.is_in_flight(),
            "sanity check: nothing must be in flight yet"
        );

        assert_eq!(summary(&entity), RowSummary::InFlight);
    }

    /// Criterion 2's outstanding-cell case: a Cell nothing has ever settled must not drag an
    /// otherwise-settled row down to Unknown once another Cell already holds a value, or
    /// every row would read `?` forever behind any column a probe has not reached (today,
    /// `sync`, `base` and `dirty`), rather than showing that column's own loading mark and
    /// leaving the gutter to read the row's least-settled *settled* state instead
    /// (`docs/spec/refresh.md`'s "What the gutter and the cells show"). A version of this
    /// fold that only excluded `NotApplicable` and still read a bare `None` as Unknown would
    /// fail exactly this case.
    #[test]
    fn a_cell_nothing_has_ever_settled_is_excluded_from_the_fold_once_the_row_holds_other_values() {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("repo")),
            Kind::Repo,
        );
        entity.branch.settle(
            Generation::new(1),
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("main"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );
        // `sync`, `base` and `dirty` are left exactly as construction left them: never
        // settled, and no probe dispatched against them either.

        assert_eq!(
            summary(&entity),
            RowSummary::Fresh,
            "a Cell nothing has ever settled must not drag an otherwise-settled row to Unknown"
        );
    }

    /// The "truly fully populated" counterpart to the render layer's own predecessor-defect
    /// test (`crates/repon/src/components/list.rs`'s
    /// `a_row_that_already_shows_its_cheap_columns_still_animates_its_outstanding_cell_on_refresh`),
    /// exercised here because only this crate can settle every one of the six Cells
    /// `docs/spec/core-api.md`'s `EntityState` carries: `Cell::begin_probe` and `Cell::settle`
    /// are `pub(crate)`. A row where every Cell already holds a Known value, reprobed on every
    /// Cell at once, must keep exactly the same fold: `docs/spec/refresh.md`'s "re-probing
    /// keeps the previous value" means a Cell that already answered shows that answer, not a
    /// spinner, until a *new* answer lands, so the gutter must not move either. This is the
    /// mirror of the other tests above: there, an in-flight Cell that already held a value was
    /// shown not to elevate the row past a Failed one; here, refreshing *every* Cell of an
    /// all-Fresh row is shown not to move it at all.
    #[test]
    fn reprobing_every_cell_of_an_already_fully_settled_row_never_changes_its_summary() {
        let entity = fresh_entity("repo");
        let before = summary(&entity);
        assert_eq!(
            before,
            RowSummary::Fresh,
            "sanity check: fresh_entity settles every Cell"
        );

        let mut reprobing = entity.clone();
        reprobing.branch.begin_probe();
        reprobing.sync.begin_probe();
        reprobing.base.begin_probe();
        reprobing.dirty.begin_probe();
        reprobing.default_branch.begin_probe();
        // `state` is excluded from a Repo row's fold (`NotApplicable`), so `begin_probe`
        // is deliberately not called on it here: nothing would ever `settle` it back.
        assert!(reprobing.branch.is_in_flight());

        assert_eq!(
            summary(&reprobing),
            before,
            "reprobing every already-settled Cell must not move the row's summary until a \
             new answer actually lands"
        );
    }

    #[test]
    fn stale_outranks_fresh_but_not_unknown() {
        let mut entity = fresh_entity("repo");
        entity.dirty.settle(
            Generation::new(2),
            Settled::Known {
                value: DirtyCounts {
                    modified: 3,
                    untracked: 0,
                    deleted: 0,
                },
                at: Timestamp::now(),
                stale: true,
            },
        );

        assert_eq!(summary(&entity), RowSummary::Stale);

        entity.base.settle(
            Generation::new(2),
            Settled::Unknown(crate::cell::Unknown::TimedOut),
        );

        assert_eq!(summary(&entity), RowSummary::Unknown);
    }

    /// Every unordered pair of settledness cases, applied to two different Cells
    /// on one otherwise-fresh entity, so the fold sees both at once. No other test
    /// puts, say, an Unknown cell and a Failed cell on the same row, so an
    /// accidental reorder of `Settledness`'s declaration (its `Ord` is derived
    /// from that order) would still pass every test that only ever compares one
    /// settledness against a Fresh baseline.
    #[test]
    fn every_pair_of_cell_settlednesses_folds_to_the_worse_of_the_two() {
        #[derive(Clone, Copy)]
        enum Case {
            Fresh,
            Stale,
            Unknown,
            Failed,
        }

        fn settle<T: Default>(cell: &mut Cell<T>, generation: Generation, case: Case) {
            let settled = match case {
                Case::Fresh => Settled::Known {
                    value: T::default(),
                    at: Timestamp::now(),
                    stale: false,
                },
                Case::Stale => Settled::Known {
                    value: T::default(),
                    at: Timestamp::now(),
                    stale: true,
                },
                Case::Unknown => Settled::Unknown(crate::cell::Unknown::TimedOut),
                Case::Failed => Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
            };
            cell.settle(generation, settled);
        }

        fn rank(summary: RowSummary) -> u8 {
            match summary {
                RowSummary::Fresh => 0,
                RowSummary::Stale => 1,
                RowSummary::Unknown => 2,
                RowSummary::Failed => 3,
                RowSummary::InFlight => 4,
            }
        }

        let cases = [
            ("fresh", Case::Fresh, RowSummary::Fresh),
            ("stale", Case::Stale, RowSummary::Stale),
            ("unknown", Case::Unknown, RowSummary::Unknown),
            ("failed", Case::Failed, RowSummary::Failed),
        ];
        let generation = Generation::new(2);

        for &(label_a, case_a, rank_a) in &cases {
            for &(label_b, case_b, rank_b) in &cases {
                let mut entity = fresh_entity("repo");
                settle(&mut entity.dirty, generation, case_a);
                settle(&mut entity.base, generation, case_b);

                let expected = if rank(rank_a) >= rank(rank_b) {
                    rank_a
                } else {
                    rank_b
                };

                assert_eq!(
                    summary(&entity),
                    expected,
                    "case: dirty={label_a}, base={label_b}"
                );
            }
        }
    }

    #[test]
    fn an_unparseable_gitmodules_drives_the_row_to_failed_even_though_every_cell_is_fine() {
        let mut entity = fresh_entity("repo");
        entity.diagnostics.gitmodules_failed = Some(Arc::from("unexpected EOF"));

        assert_eq!(summary(&entity), RowSummary::Failed);
    }

    /// Criterion 8's whole point, not merely that the fold reacts to `failed`: every Cell
    /// here is fine (`fresh_entity` settles all six), and the mark comes from the receipt
    /// alone. A worthless version of this test would also fail a Cell, which would pass even
    /// if the receipt were never read.
    #[test]
    fn a_failed_last_action_drives_the_row_to_failed_even_though_every_cell_is_fine() {
        let mut entity = fresh_entity("repo");
        assert_eq!(
            summary(&entity),
            RowSummary::Fresh,
            "sanity check: every cell must already read fine before the receipt is added"
        );
        entity.last_action = Some(receipt_with_steps(vec![
            StepOutcome::Ok,
            StepOutcome::Failed(1),
        ]));

        assert_eq!(summary(&entity), RowSummary::Failed);
    }

    /// The first-probe spinner outranks a failed receipt, which is why a consumer waiting
    /// for a row to read Failed cannot stop at "the fan-out finished".
    ///
    /// A row on which nothing has settled yet reads InFlight whatever else is true of it,
    /// so an Action that has already failed on such a row is invisible until the Generation
    /// covering it lands. `repon`'s `run_failing_action_on` fixture waits on the row reading
    /// Failed for exactly this reason, rather than on the fan-out being over; this is the
    /// fold that makes the two different.
    #[test]
    fn a_failed_last_action_is_outranked_while_the_row_still_holds_no_values() {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("repo"))),
            Arc::from("repo"),
            Arc::from(Path::new("repo")),
            Kind::Repo,
        );
        entity.last_action = Some(receipt_with_steps(vec![StepOutcome::Failed(1)]));

        assert_eq!(
            summary(&entity),
            RowSummary::InFlight,
            "a row holding no values yet must still read InFlight, receipt or no receipt"
        );

        // The same entity once one Generation has settled a single Cell: the receipt is
        // read from that point on, so the assertion above is about the ordering of the two
        // rather than about the receipt being ignored outright.
        entity.branch.settle(
            Generation::new(1),
            Settled::Known {
                value: Head::Branch {
                    name: Arc::from("main"),
                    commit: gix::hash::Kind::Sha1.null(),
                },
                at: Timestamp::now(),
                stale: false,
            },
        );

        assert_eq!(summary(&entity), RowSummary::Failed);
    }

    /// The defect this ticket fixes: `EntityState::last_action.running` is what
    /// `Core::run_action` writes once per step while a run is on this row right now
    /// (`docs/spec/actions.md`'s "The run on screen"), and the fold must widen to
    /// `InFlight` for it, not merely name it to skip it.
    #[test]
    fn a_row_with_a_running_action_step_reads_in_flight() {
        let mut entity = fresh_entity("repo");
        entity.last_action = Some(ActionReceipt {
            label: Arc::from("action"),
            steps: Arc::from(Vec::new()),
            skip: None,
            finished_at: Timestamp::now(),
            running: Some(crate::entity::RunningStep {
                label: Arc::from("pnpm install"),
                shell: false,
                interactive: false,
                started_at: Timestamp::now(),
            }),
        });

        assert_eq!(summary(&entity), RowSummary::InFlight);
    }

    /// Settles the issue's own open question: a running Action outranks a failed one, because a
    /// row retrying a previously failed step is in-flight right now, and reporting the old
    /// failure while the retry runs is the wrong answer.
    #[test]
    fn a_running_action_step_outranks_the_same_receipts_own_failed_steps() {
        let mut entity = fresh_entity("repo");
        entity.last_action = Some(ActionReceipt {
            label: Arc::from("action"),
            steps: Arc::from(vec![StepResult {
                label: Arc::from("step 0"),
                outcome: StepOutcome::Failed(1),
                output: Arc::from(&b""[..]),
                elapsed: std::time::Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: Some(crate::entity::RunningStep {
                shell: false,
                interactive: false,
                label: Arc::from("step 1"),
                started_at: Timestamp::now(),
            }),
        });

        assert_eq!(summary(&entity), RowSummary::InFlight);
    }

    /// A running Action outranks a genuinely failed Cell too, not only its own receipt's past
    /// steps: while a row is being retried right now, that is the fact worth showing over a
    /// probe failure from before the retry started.
    #[test]
    fn a_running_action_step_outranks_a_failed_cell() {
        let mut entity = fresh_entity("repo");
        entity.dirty.settle(
            Generation::new(2),
            Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
        );
        entity.last_action = Some(ActionReceipt {
            label: Arc::from("action"),
            steps: Arc::from(Vec::new()),
            skip: None,
            finished_at: Timestamp::now(),
            running: Some(crate::entity::RunningStep {
                shell: false,
                interactive: false,
                label: Arc::from("step 0"),
                started_at: Timestamp::now(),
            }),
        });

        assert_eq!(summary(&entity), RowSummary::InFlight);
    }

    #[test]
    fn a_successful_last_action_does_not_drag_an_otherwise_fresh_row_down() {
        let mut entity = fresh_entity("repo");
        entity.last_action = Some(receipt_with_steps(vec![StepOutcome::Ok, StepOutcome::Ok]));

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    /// `Cancelled` is not a failure ([`docs/spec/actions.md`]'s "Step outcomes"), and that
    /// classification has to hold inside the fold too, not just on `StepOutcome::is_failure`
    /// in isolation: a cancelled run must never turn an otherwise-fine row `!`.
    #[test]
    fn a_cancelled_last_action_does_not_drive_the_row_to_failed() {
        let mut entity = fresh_entity("repo");
        entity.last_action = Some(receipt_with_steps(vec![
            StepOutcome::Ok,
            StepOutcome::Cancelled,
        ]));

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    /// The same classification for a step Repon performed itself: a Management operation that
    /// refused is not a failure and must leave the gutter alone, or a Repo that reads
    /// perfectly well takes `!` for having been declined
    /// (`docs/spec/actions.md`'s "Why the set grew from four to five").
    #[test]
    fn own_work_repon_refused_leaves_the_row_fresh_and_work_it_could_not_finish_does_not() {
        let mut refused = fresh_entity("repo-refused");
        refused.last_action = Some(receipt_with_steps(vec![StepOutcome::OwnWork(
            OwnWork::Refused(Arc::from("refused, already ignored")),
        )]));

        let mut could_not = fresh_entity("repo-could-not");
        could_not.last_action = Some(receipt_with_steps(vec![StepOutcome::OwnWork(
            OwnWork::CouldNotAct(Arc::from("failed, permission denied")),
        )]));

        let mut did = fresh_entity("repo-did");
        did.last_action = Some(receipt_with_steps(vec![StepOutcome::OwnWork(
            OwnWork::Did(Arc::from("ignored")),
        )]));

        assert_eq!(summary(&refused), RowSummary::Fresh);
        assert_eq!(summary(&did), RowSummary::Fresh);
        assert_eq!(summary(&could_not), RowSummary::Failed);
    }

    /// Reinforces criterion 1's exclusion from the Cell machinery: `FoldableCell` is a
    /// per-cell mechanism, private to this module and implemented exactly once, generically,
    /// for `Cell<T>` alone; `EntityState::last_action` is a plain `Option<ActionReceipt>`,
    /// never a `Cell<ActionReceipt>`, so it cannot become `&dyn FoldableCell` and cannot join
    /// `summary`'s six-element `cells` array. What that guarantee predicts, and what this
    /// test actually drives: the fold's verdict on a failed receipt reads only
    /// `ActionReceipt::failed`'s single bool, never the receipt's own step count or shape.
    #[test]
    fn the_folds_verdict_on_a_failed_receipt_does_not_depend_on_how_many_steps_it_has() {
        let mut one_step = fresh_entity("repo-one");
        one_step.last_action = Some(receipt_with_steps(vec![StepOutcome::Failed(1)]));

        let mut many_steps = fresh_entity("repo-many");
        let mut outcomes = vec![StepOutcome::Ok; 20];
        outcomes.push(StepOutcome::Failed(1));
        many_steps.last_action = Some(receipt_with_steps(outcomes));

        assert_eq!(summary(&one_step), RowSummary::Failed);
        assert_eq!(summary(&one_step), summary(&many_steps));
    }

    #[test]
    fn the_default_branchs_rung_and_its_disagreement_never_enter_the_fold() {
        let mut entity = fresh_entity("repo");
        entity.diagnostics.default_branch_rung = Some(2);
        entity.diagnostics.default_branch_rung_disagreement = true;
        entity.diagnostics.default_branch_rung_two_stale = true;
        entity.diagnostics.default_branch_stopped =
            Some(crate::entity::DefaultBranchStopped::NameListExhausted);

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    #[test]
    fn a_repo_row_whose_state_cell_is_not_applicable_folds_to_fresh_rather_than_unknown() {
        let mut entity = fresh_entity("repo");
        assert_eq!(entity.kind, Kind::Repo);
        entity
            .state
            .settle(Generation::new(2), Settled::NotApplicable);

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    #[test]
    fn a_detached_row_whose_state_cell_is_not_applicable_folds_to_fresh_rather_than_unknown() {
        let mut entity = EntityState::new(
            EntityKey::new(Arc::from(Path::new("/repo-pr-1"))),
            Arc::from("repo-pr-1"),
            Arc::from(Path::new("/repo/.git")),
            Kind::Worktree,
        );
        let generation = Generation::new(1);
        entity.branch.settle(
            generation,
            Settled::Known {
                value: Head::Detached(gix::hash::Kind::Sha1.null()),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.sync.settle(
            generation,
            Settled::Unknown(crate::cell::Unknown::NoDefaultBranch),
        );
        entity.dirty.settle(
            generation,
            Settled::Known {
                value: DirtyCounts::default(),
                at: Timestamp::now(),
                stale: false,
            },
        );
        entity.default_branch.settle(
            generation,
            Settled::Known {
                value: DefaultBranch::new(Arc::from("main")),
                at: Timestamp::now(),
                stale: false,
            },
        );
        // The Merged proof found neither ancestry nor patch equivalence against the
        // default branch, so `state` is Not applicable rather than a fifth exclusive
        // state (ADR 0019).
        entity.state.settle(generation, Settled::NotApplicable);
        entity.base.settle(
            generation,
            Settled::Known {
                value: 46,
                at: Timestamp::now(),
                stale: false,
            },
        );

        assert_eq!(
            summary(&entity),
            RowSummary::Unknown,
            "sanity check: an Unknown sync cell should still win over the excluded \
             Not-applicable state cell"
        );

        entity.sync.settle(
            generation,
            Settled::Known {
                value: SyncState::Tracking(AheadBehind {
                    ahead: 0,
                    behind: 0,
                }),
                at: Timestamp::now(),
                stale: false,
            },
        );

        assert_eq!(summary(&entity), RowSummary::Fresh);
    }

    /// One ordering case: a label, a mutation applied to an otherwise-fresh entity,
    /// and the expected fold.
    type OrderingCase = (&'static str, fn(&mut EntityState, Generation), RowSummary);

    #[test]
    fn row_summary_follows_the_documented_ordering_over_every_settledness() {
        let generation = Generation::new(2);
        let cases: [OrderingCase; 6] = [
            (
                "every cell fresh",
                |_entity, _generation| {},
                RowSummary::Fresh,
            ),
            (
                "one cell stale",
                |entity, generation| {
                    entity.dirty.settle(
                        generation,
                        Settled::Known {
                            value: DirtyCounts {
                                modified: 3,
                                untracked: 0,
                                deleted: 0,
                            },
                            at: Timestamp::now(),
                            stale: true,
                        },
                    );
                },
                RowSummary::Stale,
            ),
            (
                "one cell unknown",
                |entity, generation| {
                    entity
                        .dirty
                        .settle(generation, Settled::Unknown(crate::cell::Unknown::TimedOut));
                },
                RowSummary::Unknown,
            ),
            (
                "one cell failed",
                |entity, generation| {
                    entity.dirty.settle(
                        generation,
                        Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
                    );
                },
                RowSummary::Failed,
            ),
            (
                "a failed cell outranks an in-flight one once the row already holds values",
                |entity, generation| {
                    entity.dirty.settle(
                        generation,
                        Settled::Failed(crate::git::ProbeError::Read(Arc::from("boom"))),
                    );
                    entity.branch.begin_probe();
                },
                RowSummary::Failed,
            ),
            (
                "a Not-applicable cell would have been the worst cell had it been \
                 counted, but is excluded, so the row is fresh",
                |entity, generation| {
                    entity.state.settle(generation, Settled::NotApplicable);
                },
                RowSummary::Fresh,
            ),
        ];

        for (label, mutate, expected) in cases {
            let mut entity = fresh_entity("repo");
            mutate(&mut entity, generation);
            assert_eq!(summary(&entity), expected, "case: {label}");
        }
    }

    #[test]
    fn cloning_a_snapshot_of_five_hundred_entities_stays_far_inside_a_frame_budget() {
        let entities: Vec<EntityState> = (0..500)
            .map(|index| fresh_entity(&format!("repo-{index}")))
            .collect();
        let snapshot = Snapshot {
            generation: Generation::new(1),
            discovered_at: Timestamp::now(),
            entities,
        };

        let iterations = 200;
        let start = std::time::Instant::now();
        for _ in 0..iterations {
            std::hint::black_box(snapshot.clone());
        }
        let per_clone = start.elapsed() / iterations;

        // 16.7ms is one frame at 60fps; a clone this cheap (Arc bumps and a Vec
        // copy) should sit at a small fraction of it, not merely under it.
        let frame_budget = std::time::Duration::from_micros(16_700);
        assert!(
            per_clone < frame_budget / 4,
            "one snapshot clone of 500 entities averaged {per_clone:?} across {iterations} runs, expected well under a quarter of the {frame_budget:?} frame budget"
        );
    }
}