second-brain-api 0.13.1

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
1135
1136
1137
1138
1139
1140
1141
//! Whether second-brain is worth running: how often sessions recall, how
//! often recall finds something, what agents do with what it found, and
//! what the store costs in disk, memory and sync lag. Kept in memory over a
//! rolling window, so a restart starts every window empty and each check
//! waits for enough events before it judges.

use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::hash::Hash;

use crate::health::{counted, human};
use chrono::{DateTime, Duration, Utc};
use second_brain_core::residency::ComponentResidency;
use serde::Serialize;
use uuid::Uuid;

pub const WINDOW: Duration = Duration::hours(24);
/// Bounds memory when a caller recalls far more often than any agent does.
const MAX_EVENTS: usize = 50_000;

const SESSION_RATE: Band = Band {
    min_samples: 10,
    degrade: 0.25,
    recover: 0.35,
};
/// A real store's typed prompts found nothing to inject 17% of the time
/// (`evals/results/hook_replay.json`).
const EMPTY_OR_LOW: Band = Band {
    min_samples: 50,
    degrade: 0.75,
    recover: 0.65,
};
const CORRECTED: Band = Band {
    min_samples: 20,
    degrade: 0.20,
    recover: 0.15,
};
const RESIDENT_DEGRADE: f64 = 0.85;
const RESIDENT_RECOVER: f64 = 0.75;
/// Free space must reach this multiple of what compaction and an index
/// rebuild rewrite (the database and indexes, never the transcript archive)
/// before a store that outgrew its disk counts as fixed.
const STORE_RECOVER: f64 = 1.1;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecallVerdict {
    /// Something cleared the relevance bar.
    Hit,
    /// Results came back and none cleared the bar.
    LowScore,
    /// Results came back without a bar applied although a reranker exists,
    /// or for a caller that shows only what clears it.
    Unjudged,
    Empty,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PeerOutcome {
    /// Both sides now hold each other's changes.
    Synced,
    /// The peer took this device's changes but its own were not pulled, so
    /// it ends a failure streak without ending the lag.
    Pushed,
    /// What went wrong, as the sync loop logged it.
    Failed(String),
}

#[derive(Debug, Clone, PartialEq)]
pub struct RecallEvent {
    /// The caller's agent session, when it sent one.
    pub session: Option<String>,
    pub verdict: RecallVerdict,
    /// The memories the caller was shown.
    pub memory_ids: Vec<Uuid>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct RecallReport {
    pub window_secs: i64,
    pub recalls: u64,
    pub hits: u64,
    pub low_score: u64,
    pub unjudged: u64,
    pub empty: u64,
    /// Over judged recalls, the pool the threshold judges.
    pub empty_share: Option<f64>,
    /// Over judged recalls, the pool the threshold judges.
    pub low_score_share: Option<f64>,
    pub unjudged_share: Option<f64>,
    pub sessions_with_recall: u64,
    /// None until the first read of the ingest log, or while a backfill
    /// makes the ingest log's recent sessions mostly old ones.
    pub sessions_ingested: Option<u64>,
    /// Ingested sessions that recalled, over ingested sessions.
    pub session_recall_rate: Option<f64>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct RecalledReport {
    pub window_secs: i64,
    pub memories: u64,
    pub corrected: u64,
    /// Fetched by id or cited by id in a note after it was recalled.
    pub used: u64,
    pub corrected_share: Option<f64>,
    pub used_share: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PeerSync {
    pub peer: String,
    pub last_success_at: Option<DateTime<Utc>>,
    pub last_attempt_at: Option<DateTime<Utc>>,
    pub consecutive_failures: u32,
    /// The error of the newest attempt, cleared by a sync or a push.
    pub last_error: Option<String>,
    /// Since the last success, or since startup when none was seen.
    pub lag_secs: i64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct StoreSize {
    pub checked_at: Option<DateTime<Utc>>,
    /// The database with its WAL and shared-memory files.
    pub db_bytes: u64,
    /// The WAL and shared-memory part of `db_bytes`, which a compaction or
    /// rebuild reuses rather than needs anew.
    pub wal_bytes: u64,
    pub index_bytes: u64,
    pub archive_bytes: u64,
    pub raw_index_bytes: u64,
    pub cold_bytes: u64,
    pub total_bytes: u64,
    /// Space left on the store's filesystem; None when it can't be read.
    pub free_bytes: Option<u64>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct ResidentSize {
    pub checked_at: Option<DateTime<Utc>>,
    pub rss_anon_bytes: u64,
    pub components: ComponentResidency,
    pub raw_index_bytes: u64,
    pub unattributed_bytes: i64,
    /// The cgroup's `memory.max`, else the machine's memory; None when
    /// neither can be read.
    pub limit_bytes: Option<u64>,
}

/// Degrades once a share crosses `degrade` and recovers only once it is
/// back past `recover`, so a share hovering at the line alerts once. Below
/// `min_samples` it never degrades, but a degraded share holds until the
/// window empties, so samples aging out do not flip it.
struct Band {
    min_samples: u64,
    degrade: f64,
    recover: f64,
}

/// Which checks are degraded right now; each flips only at its band edge.
#[derive(Debug, Default)]
struct Latches {
    session_rate: bool,
    empty_or_low: bool,
    corrected: bool,
    store: bool,
    resident: bool,
}

#[derive(Debug, Clone, Copy, Default)]
struct Flags {
    corrected: bool,
    used: bool,
}

/// Keys seen within the window with the time each was last seen, oldest
/// first, so pruning is a pop from the front.
#[derive(Debug)]
struct Recent<K, V> {
    entries: HashMap<K, (DateTime<Utc>, V)>,
    order: VecDeque<(DateTime<Utc>, K)>,
}

impl<K, V> Default for Recent<K, V> {
    fn default() -> Self {
        Self {
            entries: HashMap::new(),
            order: VecDeque::new(),
        }
    }
}

impl Band {
    /// For a share where more is worse.
    fn above(&self, latched: bool, count: u64, of: u64) -> bool {
        if of == 0 || (!latched && of < self.min_samples) {
            return false;
        }
        let share = count as f64 / of as f64;
        share > if latched { self.recover } else { self.degrade }
    }

    /// For a share where less is worse.
    fn below(&self, latched: bool, count: u64, of: u64) -> bool {
        if of == 0 || (!latched && of < self.min_samples) {
            return false;
        }
        let share = count as f64 / of as f64;
        share < if latched { self.recover } else { self.degrade }
    }
}

impl<K: Hash + Eq + Clone, V: Default> Recent<K, V> {
    fn touch(&mut self, key: K, at: DateTime<Utc>) {
        match self.entries.get_mut(&key) {
            Some(entry) => entry.0 = at,
            None => {
                self.entries.insert(key.clone(), (at, V::default()));
            }
        }
        self.order.push_back((at, key));
        if self.order.len() > 4 * MAX_EVENTS {
            let entries = &self.entries;
            self.order
                .retain(|(at, key)| entries.get(key).is_some_and(|e| e.0 == *at));
        }
    }

    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        self.entries.get_mut(key).map(|e| &mut e.1)
    }

    /// Calls `evicted` for each entry dropped.
    fn prune(&mut self, cutoff: DateTime<Utc>, mut evicted: impl FnMut(&V)) {
        while let Some((at, key)) = self.order.front() {
            let live = self.entries.get(key).is_some_and(|e| e.0 == *at);
            if live && *at >= cutoff && self.entries.len() <= MAX_EVENTS {
                break;
            }
            if let Some((_, key)) = self.order.pop_front()
                && live
                && let Some((_, value)) = self.entries.remove(&key)
            {
                evicted(&value);
            }
        }
    }

    fn len(&self) -> usize {
        self.entries.len()
    }

    fn count_since(&self, cutoff: DateTime<Utc>) -> usize {
        self.entries
            .values()
            .filter(|(at, _)| *at >= cutoff)
            .count()
    }

    fn contains(&self, key: &K) -> bool {
        self.entries.contains_key(key)
    }
}

#[derive(Debug, Default)]
pub struct ValueFacts {
    recalls: VecDeque<(DateTime<Utc>, RecallVerdict)>,
    hits: u64,
    low_score: u64,
    unjudged: u64,
    empty: u64,
    recall_sessions: Recent<String, ()>,
    recalled: Recent<Uuid, Flags>,
    corrected: u64,
    used: u64,
    ingested_sessions: Option<HashSet<String>>,
    /// The session check's problem while it is degraded, kept through
    /// passes where the ingested sessions are unknown.
    session_problem: Option<String>,
    peers: BTreeMap<String, PeerState>,
    store: Option<StoreSize>,
    resident: Option<ResidentSize>,
    latches: Latches,
}

#[derive(Debug, Clone, Default)]
struct PeerState {
    listed_at: Option<DateTime<Utc>>,
    last_success_at: Option<DateTime<Utc>>,
    last_attempt_at: Option<DateTime<Utc>>,
    consecutive_failures: u32,
    last_error: Option<String>,
}

/// What `refresh` concluded: problems that degrade the daemon, with the
/// per-peer ones apart so a check that already says no sync succeeded at
/// all can leave them out.
#[derive(Debug, Default, PartialEq)]
pub struct ValueProblems {
    pub peers: Vec<String>,
    pub other: Vec<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ValueReport {
    pub recall: RecallReport,
    pub recalled: RecalledReport,
    pub sync_peers: Vec<PeerSync>,
    pub store: Option<StoreSize>,
    pub resident: Option<ResidentSize>,
}

/// The session a transcript or caller belongs to: a subagent's
/// `<session>/<agent>` key counts as its parent session.
pub fn session_of(key: &str) -> &str {
    key.split_once('/').map_or(key, |(session, _)| session)
}

impl ValueFacts {
    pub fn recalled(&mut self, event: RecallEvent, now: DateTime<Utc>) {
        self.recalls.push_back((now, event.verdict));
        *self.count_of(event.verdict) += 1;
        if let Some(session) = &event.session {
            self.recall_sessions
                .touch(session_of(session).to_string(), now);
        }
        for id in event.memory_ids {
            self.recalled.touch(id, now);
        }
    }

    fn count_of(&mut self, verdict: RecallVerdict) -> &mut u64 {
        match verdict {
            RecallVerdict::Hit => &mut self.hits,
            RecallVerdict::LowScore => &mut self.low_score,
            RecallVerdict::Unjudged => &mut self.unjudged,
            RecallVerdict::Empty => &mut self.empty,
        }
    }

    /// Counts only memories recalled within the window, and each once.
    pub fn corrected(&mut self, id: Uuid) {
        if let Some(flags) = self.recalled.get_mut(&id)
            && !flags.corrected
        {
            flags.corrected = true;
            self.corrected += 1;
        }
    }

    pub fn used(&mut self, ids: &[Uuid]) {
        for id in ids {
            if let Some(flags) = self.recalled.get_mut(id)
                && !flags.used
            {
                flags.used = true;
                self.used += 1;
            }
        }
    }

    /// The sessions the ingest log shows captured within the window; None
    /// while that count would mislead.
    pub fn sessions_ingested(&mut self, keys: Option<Vec<String>>) {
        self.ingested_sessions =
            keys.map(|keys| keys.iter().map(|key| session_of(key).to_string()).collect());
    }

    /// Forgets peers no longer listed and starts tracking new ones; results
    /// count only for listed peers, so a sync that ends after its peer was
    /// removed does not bring it back.
    pub fn peers_listed(&mut self, peers: &[String], now: DateTime<Utc>) {
        self.peers.retain(|peer, _| peers.contains(peer));
        for peer in peers {
            self.peers.entry(peer.clone()).or_insert_with(|| PeerState {
                listed_at: Some(now),
                ..PeerState::default()
            });
        }
    }

    pub fn sync_attempted(&mut self, peer: &str, outcome: PeerOutcome, now: DateTime<Utc>) {
        let Some(state) = self.peers.get_mut(peer) else {
            return;
        };
        match outcome {
            PeerOutcome::Synced => {
                state.last_attempt_at = Some(now);
                state.last_success_at = Some(now);
                state.consecutive_failures = 0;
                state.last_error = None;
            }
            PeerOutcome::Pushed => {
                state.last_attempt_at = Some(now);
                state.consecutive_failures = 0;
                state.last_error = None;
            }
            PeerOutcome::Failed(error) => {
                state.last_attempt_at = Some(now);
                state.consecutive_failures += 1;
                state.last_error = Some(error);
            }
        }
    }

    /// None when the measurement failed, which drops the old reading.
    pub fn store_measured(&mut self, size: Option<StoreSize>) {
        self.store = size;
    }

    /// None when the measurement failed, which drops the old reading.
    pub fn resident_measured(&mut self, size: Option<ResidentSize>) {
        self.resident = size;
    }

    /// Prunes the windows, moves each check across its band and reports.
    /// `started` bounds a peer's lag before its first success; `sync_overdue`
    /// is the alert config's window, None when sync checks are off.
    pub fn refresh(
        &mut self,
        now: DateTime<Utc>,
        started: DateTime<Utc>,
        sync_overdue: Option<Duration>,
    ) -> (ValueReport, ValueProblems) {
        self.prune(now - WINDOW);
        let mut problems = ValueProblems::default();
        let recall = self.recall_report(now - WINDOW, &mut problems);
        let recalled = self.recalled_report(&mut problems);
        let sync_peers = self.peer_report(now, started, sync_overdue, &mut problems);
        self.check_store(&mut problems);
        self.check_resident(&mut problems);
        let report = ValueReport {
            recall,
            recalled,
            sync_peers,
            store: self.store.clone(),
            resident: self.resident.clone(),
        };
        (report, problems)
    }

    fn prune(&mut self, cutoff: DateTime<Utc>) {
        while let Some(&(at, verdict)) = self.recalls.front() {
            if at >= cutoff && self.recalls.len() <= MAX_EVENTS {
                break;
            }
            self.recalls.pop_front();
            *self.count_of(verdict) -= 1;
        }
        self.recall_sessions.prune(cutoff - session_grace(), |_| {});
        let (corrected, used) = (&mut self.corrected, &mut self.used);
        self.recalled.prune(cutoff, |flags| {
            *corrected -= u64::from(flags.corrected);
            *used -= u64::from(flags.used);
        });
    }

    fn recall_report(
        &mut self,
        cutoff: DateTime<Utc>,
        problems: &mut ValueProblems,
    ) -> RecallReport {
        let recalls = self.recalls.len() as u64;
        let ingested = self.ingested_sessions.as_ref();
        let joined = ingested.map(|keys| {
            keys.iter()
                .filter(|key| self.recall_sessions.contains(*key))
                .count() as u64
        });
        let sessions_ingested = ingested.map(|keys| keys.len() as u64);

        let judged = recalls - self.unjudged;
        let bad = self.empty + self.low_score;
        self.latches.empty_or_low = EMPTY_OR_LOW.above(self.latches.empty_or_low, bad, judged);
        if self.latches.empty_or_low {
            problems.other.push(format!(
                "{} of {judged} judged recalls in the last 24h found nothing that cleared the \
                 relevance bar ({} empty, {} below it)",
                percent(bad, judged),
                self.empty,
                self.low_score
            ));
        }
        if let (Some(joined), Some(of)) = (joined, sessions_ingested) {
            self.latches.session_rate = SESSION_RATE.below(self.latches.session_rate, joined, of);
            self.session_problem = self.latches.session_rate.then(|| {
                format!(
                    "only {joined} of {of} sessions in the last 24h recalled from second-brain; \
                     check its hooks and MCP server with `sb doctor`"
                )
            });
        }
        if let Some(problem) = &self.session_problem {
            problems.other.push(problem.clone());
        }

        RecallReport {
            window_secs: WINDOW.num_seconds(),
            recalls,
            hits: self.hits,
            low_score: self.low_score,
            unjudged: self.unjudged,
            empty: self.empty,
            empty_share: share(self.empty, judged),
            low_score_share: share(self.low_score, judged),
            unjudged_share: share(self.unjudged, recalls),
            sessions_with_recall: self.recall_sessions.count_since(cutoff) as u64,
            sessions_ingested,
            session_recall_rate: joined
                .zip(sessions_ingested)
                .and_then(|(j, of)| share(j, of)),
        }
    }

    fn recalled_report(&mut self, problems: &mut ValueProblems) -> RecalledReport {
        let memories = self.recalled.len() as u64;
        self.latches.corrected = CORRECTED.above(self.latches.corrected, self.corrected, memories);
        if self.latches.corrected {
            problems.other.push(format!(
                "{} of {memories} memories recalled in the last 24h were corrected",
                self.corrected
            ));
        }
        RecalledReport {
            window_secs: WINDOW.num_seconds(),
            memories,
            corrected: self.corrected,
            used: self.used,
            corrected_share: share(self.corrected, memories),
            used_share: share(self.used, memories),
        }
    }

    fn peer_report(
        &self,
        now: DateTime<Utc>,
        started: DateTime<Utc>,
        sync_overdue: Option<Duration>,
        problems: &mut ValueProblems,
    ) -> Vec<PeerSync> {
        self.peers
            .iter()
            .map(|(peer, state)| {
                let since = state.last_success_at.or(state.listed_at).unwrap_or(started);
                let lag = (now - since).max(Duration::zero());
                if sync_overdue.is_some_and(|window| lag >= window) {
                    let failures = match (state.consecutive_failures, &state.last_error) {
                        (0, _) => String::new(),
                        (n, error) => format!(
                            " ({} in a row{})",
                            counted(u64::from(n), "failure", "failures"),
                            error
                                .as_deref()
                                .and_then(|e| e.lines().next())
                                .map(|line| format!("; the last: {line}"))
                                .unwrap_or_default()
                        ),
                    };
                    problems.peers.push(format!(
                        "no sync with {peer} has succeeded in {}{failures}",
                        human(lag)
                    ));
                }
                PeerSync {
                    peer: peer.clone(),
                    last_success_at: state.last_success_at,
                    last_attempt_at: state.last_attempt_at,
                    consecutive_failures: state.consecutive_failures,
                    last_error: state.last_error.clone(),
                    lag_secs: lag.num_seconds(),
                }
            })
            .collect()
    }

    fn check_store(&mut self, problems: &mut ValueProblems) {
        let Some((rewritten, free)) = self.store.as_ref().and_then(|s| {
            let rewritten =
                s.db_bytes.saturating_sub(s.wal_bytes) + s.index_bytes + s.raw_index_bytes;
            s.free_bytes.map(|free| (rewritten, free))
        }) else {
            self.latches.store = false;
            return;
        };
        let needed = if self.latches.store {
            rewritten as f64 * STORE_RECOVER
        } else {
            rewritten as f64
        };
        self.latches.store = (free as f64) < needed;
        if self.latches.store {
            problems.other.push(format!(
                "compacting or rebuilding the store needs {} MB and its disk has {} MB free",
                rewritten / 1_000_000,
                free / 1_000_000
            ));
        }
    }

    fn check_resident(&mut self, problems: &mut ValueProblems) {
        let Some((rss, limit)) = self.resident.as_ref().and_then(|r| {
            r.limit_bytes
                .filter(|&l| l > 0)
                .map(|l| (r.rss_anon_bytes, l))
        }) else {
            self.latches.resident = false;
            return;
        };
        let ratio = rss as f64 / limit as f64;
        let line = if self.latches.resident {
            RESIDENT_RECOVER
        } else {
            RESIDENT_DEGRADE
        };
        self.latches.resident = ratio >= line;
        if self.latches.resident {
            problems.other.push(format!(
                "the daemon holds {} MB resident, {} of its {} MB limit",
                rss / 1_000_000,
                percent(rss, limit),
                limit / 1_000_000
            ));
        }
    }
}

/// The ingested sessions are read every `progress::INTERVAL`, so a recall
/// stays joined that long past the window to meet a session the last read
/// still lists.
fn session_grace() -> Duration {
    Duration::from_std(crate::progress::INTERVAL).unwrap_or(Duration::zero())
}

fn share(count: u64, of: u64) -> Option<f64> {
    (of > 0).then(|| count as f64 / of as f64)
}

fn percent(count: u64, of: u64) -> String {
    format!("{:.0}%", count as f64 * 100.0 / of as f64)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn t0() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-10-31T12:00:00Z")
            .unwrap()
            .with_timezone(&Utc)
    }

    fn mins(m: i64) -> DateTime<Utc> {
        t0() + Duration::minutes(m)
    }

    fn id(n: u128) -> Uuid {
        Uuid::from_u128(n)
    }

    fn recall(session: &str, verdict: RecallVerdict, ids: &[u128]) -> RecallEvent {
        RecallEvent {
            session: Some(session.to_string()),
            verdict,
            memory_ids: ids.iter().map(|&n| id(n)).collect(),
        }
    }

    fn refresh(v: &mut ValueFacts, now: DateTime<Utc>) -> (ValueReport, ValueProblems) {
        v.refresh(now, t0(), Some(Duration::hours(24)))
    }

    #[test]
    fn subagent_keys_count_as_their_parent_session() {
        assert_eq!(session_of("abc"), "abc");
        assert_eq!(session_of("abc/agent-1"), "abc");
    }

    #[test]
    fn recall_shares_count_empty_and_low_score_recalls() {
        let mut v = ValueFacts::default();
        v.recalled(recall("s1", RecallVerdict::Hit, &[1]), mins(0));
        v.recalled(recall("s1", RecallVerdict::Empty, &[]), mins(1));
        v.recalled(recall("s2", RecallVerdict::LowScore, &[2]), mins(2));
        v.recalled(recall("s2", RecallVerdict::Empty, &[]), mins(3));
        v.recalled(recall("s2", RecallVerdict::Unjudged, &[]), mins(3));
        let (report, problems) = refresh(&mut v, mins(4));
        let r = report.recall;
        assert_eq!(r.window_secs, WINDOW.num_seconds());
        assert_eq!((r.recalls, r.hits, r.low_score, r.empty), (5, 1, 1, 2));
        assert_eq!(r.empty_share, Some(0.5), "over judged recalls");
        assert_eq!(r.low_score_share, Some(0.25), "over judged recalls");
        assert_eq!(r.unjudged_share, Some(0.2), "over all recalls");
        assert_eq!(r.sessions_with_recall, 2);
        assert_eq!(problems, ValueProblems::default());
    }

    #[test]
    fn mostly_empty_recalls_degrade_once_and_recover_past_the_band() {
        let mut v = ValueFacts::default();
        for m in 0..49 {
            v.recalled(recall("s", RecallVerdict::Empty, &[]), mins(m));
        }
        assert!(refresh(&mut v, mins(49)).1.other.is_empty(), "too few");
        v.recalled(recall("s", RecallVerdict::LowScore, &[1]), mins(49));
        let (_, problems) = refresh(&mut v, mins(50));
        assert_eq!(problems.other.len(), 1, "{problems:?}");
        assert!(
            problems.other[0].contains("of 50 judged recalls in the last 24h"),
            "{problems:?}"
        );
        for m in 50..71 {
            v.recalled(recall("s", RecallVerdict::Hit, &[1]), mins(m));
        }
        let (report, problems) = refresh(&mut v, mins(71));
        assert_eq!(
            report.recall.recalls, 71,
            "50 of 71 is 70%, inside the band"
        );
        assert_eq!(problems.other.len(), 1);
        for m in 71..77 {
            v.recalled(recall("s", RecallVerdict::Hit, &[1]), mins(m));
        }
        assert!(
            refresh(&mut v, mins(77)).1.other.is_empty(),
            "50 of 77 is 65%"
        );
    }

    #[test]
    fn a_latched_share_holds_below_the_minimum_until_the_window_empties() {
        let mut v = ValueFacts::default();
        for m in 0..50 {
            v.recalled(recall("s", RecallVerdict::Empty, &[]), mins(m));
        }
        assert_eq!(refresh(&mut v, mins(50)).1.other.len(), 1);
        let first_gone = mins(0) + WINDOW + Duration::seconds(30);
        let (report, problems) = refresh(&mut v, first_gone);
        assert_eq!(report.recall.recalls, 49);
        assert_eq!(problems.other.len(), 1, "below the minimum, still latched");
        let all_gone = mins(50) + WINDOW;
        assert!(refresh(&mut v, all_gone).1.other.is_empty());
    }

    #[test]
    fn unjudged_recalls_are_left_out_of_the_empty_or_low_share() {
        let mut v = ValueFacts::default();
        for m in 0..50 {
            v.recalled(recall("s", RecallVerdict::Unjudged, &[]), mins(m));
        }
        let (report, problems) = refresh(&mut v, mins(50));
        assert_eq!(report.recall.unjudged, 50);
        assert_eq!(report.recall.unjudged_share, Some(1.0));
        assert!(problems.other.is_empty(), "{problems:?}");
        for m in 50..99 {
            v.recalled(recall("s", RecallVerdict::Empty, &[]), mins(m));
        }
        assert!(refresh(&mut v, mins(99)).1.other.is_empty(), "49 judged");
        v.recalled(recall("s", RecallVerdict::LowScore, &[]), mins(99));
        let (_, problems) = refresh(&mut v, mins(100));
        assert_eq!(problems.other.len(), 1);
        assert!(
            problems.other[0].contains("100% of 50 judged recalls in the last 24h"),
            "{problems:?}"
        );
        assert!(
            problems.other[0].contains("(49 empty, 1 below it)"),
            "{problems:?}"
        );
    }

    #[test]
    fn a_session_recalled_just_before_the_window_edge_counts_until_the_next_ingest_read() {
        let mut v = ValueFacts::default();
        v.recalled(recall("a", RecallVerdict::Hit, &[]), mins(0));
        v.sessions_ingested(Some(vec!["a".to_string()]));
        let edge = mins(0) + WINDOW + Duration::minutes(4);
        let recall = refresh(&mut v, edge).0.recall;
        assert_eq!(recall.session_recall_rate, Some(1.0));
        assert_eq!(
            recall.sessions_with_recall, 0,
            "outside the reported window"
        );
        let later = mins(0) + WINDOW + Duration::minutes(6);
        assert_eq!(
            refresh(&mut v, later).0.recall.session_recall_rate,
            Some(0.0)
        );
    }

    #[test]
    fn recalls_older_than_the_window_drop_out() {
        let mut v = ValueFacts::default();
        v.recalled(recall("s1", RecallVerdict::Empty, &[1]), mins(0));
        v.recalled(recall("s2", RecallVerdict::Hit, &[2]), mins(60));
        let (report, _) = refresh(&mut v, mins(0) + WINDOW + Duration::minutes(10));
        assert_eq!(report.recall.recalls, 1);
        assert_eq!(report.recall.empty, 0);
        assert_eq!(report.recall.sessions_with_recall, 1);
        assert_eq!(report.recalled.memories, 1);
    }

    #[test]
    fn the_event_window_is_bounded() {
        let mut v = ValueFacts::default();
        for n in 0..(MAX_EVENTS as u128 + 10) {
            v.recalled(recall(&format!("s{n}"), RecallVerdict::Hit, &[n]), mins(0));
        }
        let (report, _) = refresh(&mut v, mins(1));
        assert_eq!(report.recall.recalls, MAX_EVENTS as u64);
        assert_eq!(report.recall.sessions_with_recall, MAX_EVENTS as u64);
        assert_eq!(report.recalled.memories, MAX_EVENTS as u64);
    }

    #[test]
    fn session_recall_rate_joins_recalling_sessions_with_ingested_ones() {
        let mut v = ValueFacts::default();
        let (report, _) = refresh(&mut v, mins(0));
        assert_eq!(report.recall.sessions_ingested, None);
        assert_eq!(report.recall.session_recall_rate, None);

        v.recalled(recall("a", RecallVerdict::Hit, &[]), mins(0));
        v.recalled(recall("b/agent-1", RecallVerdict::Hit, &[]), mins(0));
        v.recalled(recall("not-ingested", RecallVerdict::Hit, &[]), mins(0));
        let keys = ["a", "a/agent-2", "b", "c", "d"].map(String::from).to_vec();
        v.sessions_ingested(Some(keys));
        let (report, problems) = refresh(&mut v, mins(1));
        assert_eq!(report.recall.sessions_ingested, Some(4));
        assert_eq!(report.recall.session_recall_rate, Some(0.5));
        assert!(problems.other.is_empty(), "under the minimum sample");
    }

    #[test]
    fn sessions_that_never_recall_degrade_once_until_they_recover_past_the_band() {
        let mut v = ValueFacts::default();
        let keys: Vec<String> = (0..10).map(|n| format!("s{n}")).collect();
        v.recalled(recall("s0", RecallVerdict::Hit, &[]), mins(0));
        v.recalled(recall("s1", RecallVerdict::Hit, &[]), mins(0));
        v.sessions_ingested(Some(keys.clone()));
        let (_, problems) = refresh(&mut v, mins(1));
        assert_eq!(problems.other.len(), 1);
        assert!(
            problems.other[0].contains("2 of 10 sessions in the last 24h recalled"),
            "{problems:?}"
        );
        v.recalled(recall("s2", RecallVerdict::Hit, &[]), mins(2));
        assert_eq!(refresh(&mut v, mins(3)).1.other.len(), 1, "inside band");
        v.recalled(recall("s3", RecallVerdict::Hit, &[]), mins(4));
        assert!(refresh(&mut v, mins(5)).1.other.is_empty());

        v.sessions_ingested(None);
        let (report, _) = refresh(&mut v, mins(8));
        assert_eq!(report.recall.session_recall_rate, None);
    }

    #[test]
    fn an_unknown_ingest_count_keeps_the_session_alert_until_a_count_clears_it() {
        let mut v = ValueFacts::default();
        let keys: Vec<String> = (0..10).map(|n| format!("s{n}")).collect();
        v.recalled(recall("s0", RecallVerdict::Hit, &[]), mins(0));
        v.sessions_ingested(Some(keys.clone()));
        assert_eq!(refresh(&mut v, mins(1)).1.other.len(), 1);
        v.sessions_ingested(None);
        let (report, problems) = refresh(&mut v, mins(2));
        assert_eq!(report.recall.session_recall_rate, None);
        assert_eq!(problems.other.len(), 1, "{problems:?}");
        for n in 1..4 {
            v.recalled(recall(&format!("s{n}"), RecallVerdict::Hit, &[]), mins(3));
        }
        v.sessions_ingested(Some(keys));
        assert!(refresh(&mut v, mins(4)).1.other.is_empty());
    }

    #[test]
    fn corrections_and_uses_count_only_recalled_memories_once_each() {
        let mut v = ValueFacts::default();
        v.recalled(recall("s", RecallVerdict::Hit, &[1, 2, 3, 4]), mins(0));
        v.corrected(id(1));
        v.corrected(id(1));
        v.corrected(id(99));
        v.used(&[id(2), id(3), id(2), id(98)]);
        let (report, _) = refresh(&mut v, mins(1));
        let r = report.recalled;
        assert_eq!((r.memories, r.corrected, r.used), (4, 1, 2));
        assert_eq!(r.corrected_share, Some(0.25));
        assert_eq!(r.used_share, Some(0.5));

        let later = mins(0) + WINDOW + Duration::minutes(1);
        let (report, _) = refresh(&mut v, later);
        assert_eq!(
            report.recalled,
            RecalledReport {
                window_secs: WINDOW.num_seconds(),
                ..RecalledReport::default()
            }
        );
    }

    #[test]
    fn a_memory_corrected_before_it_was_recalled_is_not_counted() {
        let mut v = ValueFacts::default();
        v.corrected(id(1));
        v.recalled(recall("s", RecallVerdict::Hit, &[1]), mins(0));
        let (report, _) = refresh(&mut v, mins(1));
        assert_eq!(report.recalled.corrected, 0);
    }

    #[test]
    fn many_corrected_recalls_degrade_once_and_recover_past_the_band() {
        let mut v = ValueFacts::default();
        let ids: Vec<u128> = (0..20).collect();
        v.recalled(recall("s", RecallVerdict::Hit, &ids), mins(0));
        for n in 0..4 {
            v.corrected(id(n));
        }
        assert!(
            refresh(&mut v, mins(1)).1.other.is_empty(),
            "20% is the line"
        );
        v.corrected(id(4));
        let (_, problems) = refresh(&mut v, mins(2));
        assert_eq!(problems.other.len(), 1);
        assert!(
            problems.other[0].contains("5 of 20 memories recalled in the last 24h were corrected"),
            "{problems:?}"
        );
        let more: Vec<u128> = (100..110).collect();
        v.recalled(recall("s", RecallVerdict::Hit, &more), mins(3));
        assert_eq!(refresh(&mut v, mins(4)).1.other.len(), 1, "inside band");
        let more: Vec<u128> = (110..120).collect();
        v.recalled(recall("s", RecallVerdict::Hit, &more), mins(5));
        assert!(refresh(&mut v, mins(6)).1.other.is_empty());
    }

    #[test]
    fn a_peer_lagging_past_the_window_degrades_until_it_syncs() {
        let mut v = ValueFacts::default();
        v.peers_listed(&["u@pi".to_string(), "u@mac".to_string()], mins(0));
        v.sync_attempted("u@pi", PeerOutcome::Synced, mins(0));
        v.sync_attempted("u@mac", PeerOutcome::Failed("refused".into()), mins(0));
        v.sync_attempted(
            "u@mac",
            PeerOutcome::Failed("u@mac refused the sync: pair it with `sb pair`".into()),
            mins(5),
        );
        let (report, problems) = refresh(&mut v, mins(10));
        assert_eq!(report.sync_peers.len(), 2);
        let mac = &report.sync_peers[0];
        assert_eq!(mac.peer, "u@mac");
        assert_eq!(mac.last_success_at, None);
        assert_eq!(mac.last_attempt_at, Some(mins(5)));
        assert_eq!(mac.consecutive_failures, 2);
        assert_eq!(mac.lag_secs, 600, "from startup");
        assert_eq!(
            mac.last_error.as_deref(),
            Some("u@mac refused the sync: pair it with `sb pair`")
        );
        assert_eq!(report.sync_peers[1].lag_secs, 600);
        assert_eq!(report.sync_peers[1].last_error, None);
        assert!(problems.peers.is_empty());

        let late = t0() + Duration::hours(24);
        v.sync_attempted("u@pi", PeerOutcome::Synced, late);
        let (_, problems) = refresh(&mut v, late);
        assert_eq!(problems.peers.len(), 1);
        assert!(
            problems.peers[0].contains("no sync with u@mac has succeeded in 24h 0m"),
            "{problems:?}"
        );
        assert!(
            problems.peers[0].contains("2 failures in a row"),
            "{problems:?}"
        );
        assert!(
            problems.peers[0].contains("the last: u@mac refused the sync: pair it with `sb pair`"),
            "{problems:?}"
        );

        v.sync_attempted("u@mac", PeerOutcome::Synced, late);
        let (report, problems) = refresh(&mut v, late);
        assert!(problems.peers.is_empty());
        assert_eq!(report.sync_peers[0].last_error, None);

        v.peers_listed(&["u@pi".to_string()], late);
        assert_eq!(refresh(&mut v, late).0.sync_peers.len(), 1);
        assert!(
            v.refresh(late + Duration::hours(30), t0(), None)
                .1
                .peers
                .is_empty(),
            "sync checks off"
        );
    }

    #[test]
    fn a_push_ends_a_failure_streak_but_not_the_lag() {
        let mut v = ValueFacts::default();
        v.peers_listed(&["u@pi".to_string()], mins(0));
        v.sync_attempted("u@pi", PeerOutcome::Failed("timed out".into()), mins(1));
        v.sync_attempted("u@pi", PeerOutcome::Pushed, mins(2));
        let (report, _) = refresh(&mut v, mins(3));
        let pi = &report.sync_peers[0];
        assert_eq!(pi.consecutive_failures, 0);
        assert_eq!(pi.last_attempt_at, Some(mins(2)));
        assert_eq!(pi.last_success_at, None);
        assert_eq!(pi.last_error, None);
        assert_eq!(pi.lag_secs, 180);
    }

    #[test]
    fn a_peer_listed_late_lags_from_when_it_was_listed() {
        let mut v = ValueFacts::default();
        let late = t0() + Duration::hours(30);
        v.peers_listed(&["u@mac".to_string()], late);
        let (report, problems) = refresh(&mut v, late + Duration::minutes(5));
        assert_eq!(report.sync_peers[0].lag_secs, 300);
        assert!(problems.peers.is_empty());
        v.peers_listed(&["u@mac".to_string()], late + Duration::hours(1));
        let (report, _) = refresh(&mut v, late + Duration::hours(2));
        assert_eq!(
            report.sync_peers[0].lag_secs, 7_200,
            "listing again keeps the start"
        );
    }

    #[test]
    fn a_result_for_a_peer_no_longer_listed_is_ignored() {
        let mut v = ValueFacts::default();
        v.peers_listed(&["u@pi".to_string()], mins(0));
        v.peers_listed(&[], mins(0));
        v.sync_attempted("u@pi", PeerOutcome::Failed("timed out".into()), mins(1));
        assert!(refresh(&mut v, mins(2)).0.sync_peers.is_empty());
    }

    fn store(total: u64, free: Option<u64>) -> StoreSize {
        StoreSize {
            checked_at: Some(mins(0)),
            db_bytes: total,
            total_bytes: total,
            free_bytes: free,
            ..StoreSize::default()
        }
    }

    #[test]
    fn a_store_larger_than_its_free_space_degrades_until_space_clears_the_band() {
        let mut v = ValueFacts::default();
        let (report, _) = refresh(&mut v, mins(0));
        assert_eq!(report.store, None);
        v.store_measured(Some(store(1_000, Some(1_000))));
        assert!(refresh(&mut v, mins(0)).1.other.is_empty());
        v.store_measured(Some(store(1_000, Some(999))));
        let (report, problems) = refresh(&mut v, mins(1));
        assert_eq!(report.store, Some(store(1_000, Some(999))));
        assert_eq!(problems.other.len(), 1);
        assert!(
            problems.other[0].contains("compacting or rebuilding the store needs 0 MB"),
            "{problems:?}"
        );
        v.store_measured(Some(store(1_000, Some(1_050))));
        assert_eq!(refresh(&mut v, mins(2)).1.other.len(), 1, "inside band");
        v.store_measured(Some(store(1_000, Some(1_100))));
        assert!(refresh(&mut v, mins(3)).1.other.is_empty());
        v.store_measured(Some(store(1_000, Some(999))));
        assert_eq!(refresh(&mut v, mins(4)).1.other.len(), 1);
        v.store_measured(None);
        let (report, problems) = refresh(&mut v, mins(5));
        assert_eq!(report.store, None);
        assert!(problems.other.is_empty());
        v.store_measured(Some(store(1_000, None)));
        assert!(refresh(&mut v, mins(6)).1.other.is_empty());
    }

    #[test]
    fn the_store_check_leaves_out_the_archive_that_compaction_never_rewrites() {
        let mut v = ValueFacts::default();
        v.store_measured(Some(StoreSize {
            checked_at: Some(mins(0)),
            db_bytes: 100,
            wal_bytes: 0,
            index_bytes: 100,
            archive_bytes: 10_000,
            raw_index_bytes: 100,
            cold_bytes: 0,
            total_bytes: 10_300,
            free_bytes: Some(301),
        }));
        assert!(refresh(&mut v, mins(1)).1.other.is_empty());
        v.store_measured(Some(StoreSize {
            free_bytes: Some(299),
            ..v.store.clone().unwrap()
        }));
        assert_eq!(refresh(&mut v, mins(2)).1.other.len(), 1);
    }

    #[test]
    fn a_large_wal_is_not_counted_as_space_a_rewrite_needs() {
        let mut v = ValueFacts::default();
        v.store_measured(Some(StoreSize {
            checked_at: Some(mins(0)),
            db_bytes: 1_000,
            wal_bytes: 600,
            index_bytes: 50,
            total_bytes: 1_050,
            free_bytes: Some(500),
            ..StoreSize::default()
        }));
        assert!(refresh(&mut v, mins(1)).1.other.is_empty(), "needs 450");
    }

    fn resident(rss: u64, limit: Option<u64>) -> ResidentSize {
        ResidentSize {
            checked_at: Some(mins(0)),
            rss_anon_bytes: rss,
            limit_bytes: limit,
            ..ResidentSize::default()
        }
    }

    #[test]
    fn resident_size_near_the_limit_degrades_until_it_falls_past_the_band() {
        let mut v = ValueFacts::default();
        v.resident_measured(Some(resident(840, Some(1_000))));
        assert!(refresh(&mut v, mins(0)).1.other.is_empty());
        v.resident_measured(Some(resident(850, Some(1_000))));
        let (report, problems) = refresh(&mut v, mins(1));
        assert_eq!(report.resident, Some(resident(850, Some(1_000))));
        assert_eq!(problems.other.len(), 1);
        assert!(problems.other[0].contains("85% of its"), "{problems:?}");
        v.resident_measured(Some(resident(760, Some(1_000))));
        assert_eq!(refresh(&mut v, mins(2)).1.other.len(), 1, "inside band");
        v.resident_measured(Some(resident(740, Some(1_000))));
        assert!(refresh(&mut v, mins(3)).1.other.is_empty());
        v.resident_measured(Some(resident(5_000, None)));
        assert!(refresh(&mut v, mins(4)).1.other.is_empty());
        v.resident_measured(Some(resident(900, Some(1_000))));
        assert_eq!(refresh(&mut v, mins(5)).1.other.len(), 1);
        v.resident_measured(None);
        let (report, problems) = refresh(&mut v, mins(6));
        assert_eq!(report.resident, None);
        assert!(problems.other.is_empty());
    }
}