eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! Aggregation helper for degraded-code arrays in agent-facing
//! responses (bd-bife.27).
//!
//! When `ee context` exercises PPR + Pack DNA + Voronoi + Louvain +
//! Ego at once and any structural snapshot is stale, every algorithm
//! emits its own `snapshot_stale` [`DegradationReport`]. The raw
//! concatenation puts N copies of the same code in `degraded[]`;
//! agents read N copies, learn nothing more from the redundancy, and
//! waste tokens. This module collapses same-code entries into one
//! aggregate, escalates severity to the worst observed across
//! emitters, picks the highest-severity emitter's repair hint as the
//! canonical one, and caps the final array length so a single dirty
//! snapshot can't drown the response.
//!
//! The helper is intentionally output-shape-agnostic: it returns
//! [`AggregatedDegradation`] values that any renderer can lower into
//! its own JSON / Markdown / TOON format. Wiring into individual
//! response renderers is tracked separately so this module can land
//! clean and small.

use std::collections::BTreeMap;

use serde::Serialize;

use crate::core::status::DegradationReport;
use crate::models::DegradationSeverity;

/// Maximum number of aggregated entries returned in any single
/// response. Excess entries are folded into a synthetic truncation
/// trailer so agents can detect that the visible array dropped some
/// rows.
pub const DEGRADED_AGGREGATION_MAX_ENTRIES: usize = 20;

/// Synthetic code emitted by the truncation trailer. Agents can
/// match this constant to know that one or more aggregate entries
/// were dropped from the visible array.
pub const DEGRADED_AGGREGATION_TRUNCATED_CODE: &str = "degraded_array_truncated";

/// One entry in the aggregated `degraded[]` array.
///
/// `sources` lists the algorithms or surfaces that emitted the
/// underlying code (for example `"ppr"`, `"louvain"`, `"pack_dna"`).
/// When the input had only one source for a code, `sources` is a
/// one-element vector.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AggregatedDegradation {
    pub code: String,
    pub severity: String,
    pub message: String,
    pub repair: String,
    pub sources: Vec<String>,
}

/// Owned input row for degraded aggregation.
///
/// Most status/graph surfaces use static [`DegradationReport`] rows,
/// but renderers such as `ee context` carry owned strings. This type
/// lets those renderers reuse the same aggregation algorithm without
/// leaking strings or duplicating the rules.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DegradationAggregationInput {
    pub source: String,
    pub code: String,
    pub severity: String,
    pub message: String,
    pub repair: String,
}

impl DegradationAggregationInput {
    #[must_use]
    pub fn new(
        source: impl Into<String>,
        code: impl Into<String>,
        severity: impl Into<String>,
        message: impl Into<String>,
        repair: impl Into<String>,
    ) -> Self {
        Self {
            source: source.into(),
            code: code.into(),
            severity: severity.into(),
            message: message.into(),
            repair: repair.into(),
        }
    }
}

struct AggregatedAccumulator {
    code: String,
    severity: String,
    severity_rank: i16,
    canonical_source: String,
    message: String,
    repair: String,
    sources: Vec<String>,
}

/// Aggregate `(source, DegradationReport)` pairs into a deterministic
/// vector of [`AggregatedDegradation`].
///
/// Aggregation rules (per the bd-bife.27 acceptance contract):
///
/// 1. **Same code, multiple sources** — merged into one entry with
///    `sources` populated by the emitting algorithm names.
/// 2. **Severity escalation** — aggregate severity is the maximum
///    observed across emitters of the same code, ranked by the
///    6-tier `info < low < warning < medium < high < critical`
///    vocabulary. The retired `advisory` value is normalized to `low`;
///    unknown values emit as `info` but retain an internal rank below genuine
///    `info`, so output stays canonical without allowing typos to win.
/// 3. **Repair-hint deduplication** — the canonical repair hint is
///    the one emitted by the highest-severity source. When two
///    emitters tie on severity, the lexicographically smallest
///    `(source, message, repair)` tuple wins so output stays
///    independent of input iterator order.
/// 4. **Truncation** — at most
///    [`DEGRADED_AGGREGATION_MAX_ENTRIES`] aggregates are returned.
///    When the input would produce more, the visible array is
///    truncated to `MAX - 1` and a synthetic trailer entry with
///    code [`DEGRADED_AGGREGATION_TRUNCATED_CODE`] reports the
///    dropped count and the dropped codes (sorted, deduplicated).
///
/// Output is sorted by **descending** severity, then by code, so the
/// most urgent aggregates surface first and the order is
/// byte-stable across runs (J7 determinism contract).
#[must_use]
pub fn aggregate_degraded<I>(entries: I) -> Vec<AggregatedDegradation>
where
    I: IntoIterator<Item = (&'static str, DegradationReport)>,
{
    aggregate_degraded_entries(entries.into_iter().map(|(source, report)| {
        DegradationAggregationInput::new(
            source,
            report.code,
            report.severity,
            report.message,
            report.repair,
        )
    }))
}

/// Aggregate owned degraded entries into a deterministic vector of
/// [`AggregatedDegradation`].
#[must_use]
pub fn aggregate_degraded_entries<I>(entries: I) -> Vec<AggregatedDegradation>
where
    I: IntoIterator<Item = DegradationAggregationInput>,
{
    let mut by_code: BTreeMap<String, AggregatedAccumulator> = BTreeMap::new();
    for report in entries {
        let (normalized_severity, normalized_severity_rank) =
            normalize_severity_for_aggregation(&report.severity);
        let normalized_severity_name = normalized_severity.as_str().to_owned();
        let acc = by_code
            .entry(report.code.clone())
            .or_insert_with(|| AggregatedAccumulator {
                code: report.code.clone(),
                severity: normalized_severity_name.clone(),
                severity_rank: normalized_severity_rank,
                canonical_source: report.source.clone(),
                message: report.message.clone(),
                repair: report.repair.clone(),
                sources: Vec::new(),
            });
        let report_rank = normalized_severity_rank;
        if report_rank > acc.severity_rank
            || report_rank == acc.severity_rank
                && (
                    report.source.as_str(),
                    report.message.as_str(),
                    report.repair.as_str(),
                ) < (
                    acc.canonical_source.as_str(),
                    acc.message.as_str(),
                    acc.repair.as_str(),
                )
        {
            acc.severity = normalized_severity_name;
            acc.severity_rank = report_rank;
            acc.canonical_source = report.source.clone();
            // Use the message and repair from the highest-severity emitter.
            // Ties choose a stable canonical source/message/repair tuple so
            // aggregation is independent of input iterator order.
            acc.message = report.message.clone();
            acc.repair = report.repair.clone();
        }
        if !acc.sources.contains(&report.source) {
            acc.sources.push(report.source.clone());
        }
    }

    let mut ranked_aggregates: Vec<(AggregatedDegradation, i16)> = by_code
        .into_values()
        .map(|acc| {
            let mut sources = acc.sources;
            sources.sort_unstable();
            sources.dedup();
            (
                AggregatedDegradation {
                    code: acc.code,
                    severity: acc.severity,
                    message: acc.message,
                    repair: acc.repair,
                    sources,
                },
                acc.severity_rank,
            )
        })
        .collect();
    ranked_aggregates
        .sort_by(|(a, a_rank), (b, b_rank)| b_rank.cmp(a_rank).then_with(|| a.code.cmp(&b.code)));
    let mut aggregates: Vec<AggregatedDegradation> = ranked_aggregates
        .into_iter()
        .map(|(degradation, _rank)| degradation)
        .collect();

    if aggregates.len() <= DEGRADED_AGGREGATION_MAX_ENTRIES {
        return aggregates;
    }

    // Truncate to MAX - 1 visible entries plus a synthetic trailer
    // so the caller can detect that the array was dropped from. The
    // trailer carries the dropped count in its message and the
    // dropped codes in `sources` so an operator can still see what
    // got hidden without rerunning.
    let kept = DEGRADED_AGGREGATION_MAX_ENTRIES - 1;
    let mut dropped: Vec<String> = aggregates[kept..]
        .iter()
        .map(|entry| entry.code.clone())
        .collect();
    dropped.sort_unstable();
    dropped.dedup();
    let dropped_count = dropped.len();
    aggregates.truncate(kept);
    aggregates.push(AggregatedDegradation {
        code: DEGRADED_AGGREGATION_TRUNCATED_CODE.to_owned(),
        severity: "info".to_owned(),
        message: format!(
            "{dropped_count} additional aggregated degraded entries were truncated; \
             rerun with `--fields full` or check `ee doctor --json` for the full set"
        ),
        repair: "ee doctor --json".to_owned(),
        sources: dropped,
    });
    aggregates
}

fn normalize_severity_for_aggregation(severity: &str) -> (DegradationSeverity, i16) {
    if let Some(canonical) = DegradationSeverity::parse(severity) {
        return (canonical, i16::from(canonical.rank()));
    }
    if severity.trim().eq_ignore_ascii_case("advisory") {
        return (
            DegradationSeverity::Low,
            i16::from(DegradationSeverity::Low.rank()),
        );
    }
    (DegradationSeverity::Info, -1)
}

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

    fn report(
        code: &'static str,
        severity: &'static str,
        message: &'static str,
        repair: &'static str,
    ) -> DegradationReport {
        DegradationReport {
            code,
            severity,
            message,
            repair,
        }
    }

    /// Rule 1: same code from multiple sources collapses into one
    /// aggregate with sources[] populated.
    #[test]
    fn same_code_from_multiple_sources_aggregates_into_one_entry() {
        let entries = vec![
            (
                "ppr",
                report("snapshot_stale", "medium", "stale", "rebuild"),
            ),
            (
                "louvain",
                report("snapshot_stale", "medium", "stale", "rebuild"),
            ),
            (
                "pack_dna",
                report("snapshot_stale", "medium", "stale", "rebuild"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(
            aggregates.len(),
            1,
            "three same-code emitters → 1 aggregate"
        );
        assert_eq!(aggregates[0].code, "snapshot_stale");
        assert_eq!(aggregates[0].sources, vec!["louvain", "pack_dna", "ppr"]);
    }

    /// Rule 2: severity escalates to the maximum observed across
    /// emitters; the load-bearing repair hint travels with it.
    #[test]
    fn severity_escalates_to_max_and_uses_top_severity_repair() {
        let entries = vec![
            (
                "ppr",
                report("snapshot_stale", "low", "low msg", "low repair"),
            ),
            (
                "pack_dna",
                report("snapshot_stale", "high", "high msg", "high repair"),
            ),
            (
                "louvain",
                report("snapshot_stale", "medium", "medium msg", "medium repair"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 1);
        assert_eq!(aggregates[0].severity, "high");
        assert_eq!(aggregates[0].message, "high msg");
        assert_eq!(
            aggregates[0].repair, "high repair",
            "highest-severity repair hint must win"
        );
    }

    #[test]
    fn same_severity_ties_choose_stable_canonical_hint() {
        let order_a = vec![
            (
                "zeta",
                report("snapshot_stale", "medium", "zeta msg", "zeta repair"),
            ),
            (
                "alpha",
                report("snapshot_stale", "medium", "alpha msg", "alpha repair"),
            ),
        ];
        let mut order_b = order_a.clone();
        order_b.reverse();

        let agg_a = aggregate_degraded(order_a);
        let agg_b = aggregate_degraded(order_b);

        assert_eq!(agg_a, agg_b);
        assert_eq!(agg_a[0].message, "alpha msg");
        assert_eq!(agg_a[0].repair, "alpha repair");
        assert_eq!(agg_a[0].sources, vec!["alpha", "zeta"]);
    }

    /// Rule 3: identical repair hints across emitters of the same
    /// code appear once. (Implicit in the aggregation contract: one
    /// entry → one repair string, regardless of how many sources
    /// emitted that hint.)
    #[test]
    fn duplicate_repair_hints_collapse_with_their_aggregate() {
        let entries = vec![
            (
                "ppr",
                report("idx_cold", "warning", "cold", "ee index warm"),
            ),
            (
                "voronoi",
                report("idx_cold", "warning", "cold", "ee index warm"),
            ),
            (
                "ego",
                report("idx_cold", "warning", "cold", "ee index warm"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 1);
        assert_eq!(aggregates[0].repair, "ee index warm");
        assert_eq!(aggregates[0].sources, vec!["ego", "ppr", "voronoi"]);
    }

    /// Rule 4: the visible array is capped at
    /// DEGRADED_AGGREGATION_MAX_ENTRIES; excess produces a
    /// synthetic trailer carrying the dropped codes.
    #[test]
    fn excess_entries_produce_truncation_trailer_with_dropped_codes() {
        // Build 25 distinct codes, all "low" severity so none
        // outrank each other.
        let codes: Vec<&'static str> = vec![
            "code_aa", "code_ab", "code_ac", "code_ad", "code_ae", "code_af", "code_ag", "code_ah",
            "code_ai", "code_aj", "code_ak", "code_al", "code_am", "code_an", "code_ao", "code_ap",
            "code_aq", "code_ar", "code_as", "code_at", "code_au", "code_av", "code_aw", "code_ax",
            "code_ay",
        ];
        let entries: Vec<(&'static str, DegradationReport)> = codes
            .iter()
            .map(|code| ("emitter_x", report(code, "low", "msg", "repair")))
            .collect();

        let aggregates = aggregate_degraded(entries);

        assert_eq!(
            aggregates.len(),
            DEGRADED_AGGREGATION_MAX_ENTRIES,
            "truncated array length must equal the cap"
        );
        let trailer = aggregates.last().expect("trailer present");
        assert_eq!(trailer.code, DEGRADED_AGGREGATION_TRUNCATED_CODE);
        assert!(
            trailer.message.contains(&format!(
                "{} additional",
                codes.len() - (DEGRADED_AGGREGATION_MAX_ENTRIES - 1)
            )),
            "trailer message must report the dropped count, got: {}",
            trailer.message
        );
        assert!(
            !trailer.sources.is_empty(),
            "trailer must carry the dropped codes in sources"
        );
        // Each dropped code must appear exactly once in the trailer.
        for source in &trailer.sources {
            assert!(codes.contains(&source.as_str()));
        }
    }

    #[test]
    fn truncation_trailer_dropped_codes_are_sorted_by_code() {
        let mut entries = Vec::new();
        for index in 0..(DEGRADED_AGGREGATION_MAX_ENTRIES - 1) {
            let code = format!("kept_{index:02}");
            entries.push(DegradationAggregationInput::new(
                "search",
                code,
                "critical",
                "kept msg",
                "kept repair",
            ));
        }
        entries.extend([
            DegradationAggregationInput::new(
                "pack",
                "z_drop_high",
                "high",
                "high msg",
                "high repair",
            ),
            DegradationAggregationInput::new(
                "status",
                "a_drop_medium",
                "medium",
                "medium msg",
                "medium repair",
            ),
            DegradationAggregationInput::new(
                "insights",
                "m_drop_low",
                "low",
                "low msg",
                "low repair",
            ),
        ]);

        let aggregates = aggregate_degraded_entries(entries);
        let trailer = aggregates.last().expect("trailer present");

        assert_eq!(trailer.code, DEGRADED_AGGREGATION_TRUNCATED_CODE);
        assert_eq!(
            trailer.sources,
            vec!["a_drop_medium", "m_drop_low", "z_drop_high"],
            "trailer sources carry dropped codes sorted lexically, not severity-first"
        );
    }

    /// Worst-case integration: 8 distinct degradation streams (PPR +
    /// Pack DNA + Voronoi + Louvain + Ego + four others) all
    /// emitting the same `snapshot_stale` code at varying severities
    /// must collapse to one aggregate with the right severity, the
    /// right repair hint, and all 8 sources listed.
    #[test]
    fn worst_case_eight_emitters_one_aggregate_one_clean_entry() {
        let entries = vec![
            ("ppr", report("snapshot_stale", "low", "lo", "lo-repair")),
            (
                "pack_dna",
                report("snapshot_stale", "medium", "med", "med-repair"),
            ),
            (
                "voronoi",
                report("snapshot_stale", "warning", "wn", "wn-repair"),
            ),
            (
                "louvain",
                report("snapshot_stale", "high", "hi", "hi-repair"),
            ),
            ("ego", report("snapshot_stale", "low", "lo2", "lo2-repair")),
            (
                "hits",
                report("snapshot_stale", "medium", "med2", "med2-repair"),
            ),
            (
                "betweenness",
                report("snapshot_stale", "info", "in", "in-repair"),
            ),
            (
                "kcore",
                report("snapshot_stale", "low", "lo3", "lo3-repair"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 1, "one code → one aggregate");
        let entry = &aggregates[0];
        assert_eq!(entry.severity, "high");
        assert_eq!(entry.repair, "hi-repair");
        assert_eq!(entry.sources.len(), 8);
        assert_eq!(
            entry.sources,
            vec![
                "betweenness",
                "ego",
                "hits",
                "kcore",
                "louvain",
                "pack_dna",
                "ppr",
                "voronoi",
            ],
        );
    }

    /// Determinism: the same input set in different orders must
    /// produce byte-identical JSON.
    #[test]
    fn aggregation_output_is_byte_stable_across_input_orders() {
        let mut order_a = vec![
            ("emit_a", report("code_x", "medium", "x", "fix-x")),
            ("emit_b", report("code_y", "high", "y", "fix-y")),
            ("emit_c", report("code_x", "low", "x", "fix-x")),
            ("emit_d", report("code_z", "warning", "z", "fix-z")),
        ];
        let mut order_b = order_a.clone();
        order_b.reverse();

        let agg_a = aggregate_degraded(order_a.drain(..));
        let agg_b = aggregate_degraded(order_b.drain(..));

        let json_a = serde_json::to_string(&agg_a).expect("agg A serializes");
        let json_b = serde_json::to_string(&agg_b).expect("agg B serializes");
        assert_eq!(
            json_a, json_b,
            "aggregate output must be insertion-order-invariant"
        );
        // Spot-check ordering: highest severity (code_y, high) first.
        assert_eq!(agg_a[0].code, "code_y");
        assert_eq!(agg_a[0].severity, "high");
    }

    #[test]
    fn legacy_and_unknown_severities_are_normalized_before_emission() {
        let entries = vec![
            (
                "legacy",
                report("legacy_code", "advisory", "legacy-msg", "legacy-fix"),
            ),
            (
                "typo",
                report("typo_code", "criticla", "typo-msg", "typo-fix"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 2);
        assert_eq!(aggregates[0].code, "legacy_code");
        assert_eq!(aggregates[0].severity, "low");
        assert_eq!(aggregates[1].code, "typo_code");
        assert_eq!(aggregates[1].severity, "info");
        assert!(aggregates.iter().all(|entry| {
            DegradationSeverity::parse(&entry.severity).is_some()
                && entry.severity != "advisory"
                && entry.severity != "criticla"
        }));
    }

    #[test]
    fn unknown_severity_ranks_below_genuine_info_after_normalization() {
        let entries = vec![
            (
                "real",
                report("zzz_real_code", "info", "info-msg", "info-fix"),
            ),
            (
                "typo",
                report("aaa_typo_code", "criticla", "typo-msg", "typo-fix"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 2);
        assert_eq!(aggregates[0].code, "zzz_real_code");
        assert_eq!(aggregates[0].severity, "info");
        assert_eq!(aggregates[1].code, "aaa_typo_code");
        assert_eq!(aggregates[1].severity, "info");
    }

    #[test]
    fn genuine_info_hint_beats_unknown_hint_for_the_same_code() {
        let entries = vec![
            (
                "aaa_typo",
                report("same_code", "criticla", "typo-msg", "typo-fix"),
            ),
            (
                "zzz_real",
                report("same_code", "info", "info-msg", "info-fix"),
            ),
        ];

        let aggregates = aggregate_degraded(entries);

        assert_eq!(aggregates.len(), 1);
        assert_eq!(aggregates[0].severity, "info");
        assert_eq!(aggregates[0].message, "info-msg");
        assert_eq!(aggregates[0].repair, "info-fix");
    }

    #[test]
    fn all_six_severities_sort_in_descending_canonical_order() {
        let entries = DegradationSeverity::ALL.map(|severity| {
            DegradationAggregationInput::new(
                severity.as_str(),
                format!("code_{}", severity.as_str()),
                severity.as_str(),
                "message",
                "repair",
            )
        });

        let aggregates = aggregate_degraded_entries(entries);
        let actual: Vec<&str> = aggregates
            .iter()
            .map(|entry| entry.severity.as_str())
            .collect();
        assert_eq!(
            actual,
            vec!["critical", "high", "medium", "warning", "low", "info"]
        );
    }

    /// Empty input must produce empty output, not a trailer.
    #[test]
    fn empty_input_produces_empty_aggregate_array() {
        let aggregates = aggregate_degraded(std::iter::empty());
        assert!(aggregates.is_empty());
    }
}