claudectl 0.49.3

Mission control for Claude Code — supervise, orchestrate, and connect coding agents with a local LLM brain and hive mind
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
// Convert DistilledPreferences and Insights into KnowledgeUnits for sharing.

use std::collections::HashMap;

use crate::brain::decisions::{DecisionRecord, read_all_decisions};
use crate::brain::outcomes::{ResolvedOutcome, load_resolved_map};
use crate::brain::preferences::{
    DistilledPreferences, PreferencePattern, TemporalPattern, ToolAccuracy,
};

use super::{KnowledgeContent, KnowledgeScope, KnowledgeUnit, epoch_secs, gen_ku_id, semantic_key};

// ────────────────────────────────────────────────────────────────────────────
// Export thresholds
// ────────────────────────────────────────────────────────────────────────────

/// Configurable thresholds for what gets exported as shareable knowledge.
pub struct ExportThresholds {
    /// Minimum decisions backing a pattern before sharing.
    pub min_pattern_evidence: u32,
    /// Minimum total decisions for a tool before sharing accuracy.
    pub min_tool_decisions: u32,
    /// Minimum temporal pattern strength.
    pub min_temporal_strength: f64,
    /// Minimum outcomes attributed to an approach before sharing baseline (#220).
    pub min_outcome_samples: u32,
    /// Minimum samples on each variant before promoting a divergent group
    /// into an `ApproachCluster` (#221).
    pub min_cluster_variant_evidence: u32,
}

impl Default for ExportThresholds {
    fn default() -> Self {
        Self {
            min_pattern_evidence: 5,
            min_tool_decisions: 10,
            min_temporal_strength: 0.7,
            min_outcome_samples: 5,
            min_cluster_variant_evidence: 3,
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Main distillation entry point
// ────────────────────────────────────────────────────────────────────────────

/// Convert distilled preferences into knowledge units for sharing.
/// Returns only units that meet the export thresholds.
pub fn distill_to_knowledge(
    prefs: &DistilledPreferences,
    source_peer: &str,
    project: Option<&str>,
    thresholds: &ExportThresholds,
) -> Vec<KnowledgeUnit> {
    let now = epoch_secs();
    let scope = match project {
        Some(p) => KnowledgeScope::Project(p.to_string()),
        None => KnowledgeScope::Universal,
    };
    let mut units = Vec::new();

    // Convert preference patterns
    for pattern in &prefs.patterns {
        if let Some(unit) = pattern_to_unit(pattern, source_peer, &scope, now, thresholds) {
            units.push(unit);
        }
    }

    // Convert tool accuracy stats
    for acc in &prefs.tool_accuracy {
        if let Some(unit) = accuracy_to_unit(acc, source_peer, now, thresholds) {
            units.push(unit);
        }
    }

    // Convert temporal patterns
    for tp in &prefs.temporal {
        if let Some(unit) = temporal_to_unit(tp, source_peer, &scope, now, thresholds) {
            units.push(unit);
        }
    }

    // #220 baselining: reap any pending PostToolUse outcomes first so the
    // freshest data lands in this pass.
    let _ = crate::brain::outcomes::reap();
    let decisions = read_all_decisions();
    let resolved = load_resolved_map();
    units.extend(distill_outcomes(
        &decisions,
        &resolved,
        source_peer,
        &scope,
        project,
        now,
        thresholds,
    ));

    // #221 conflict-aware: detect competing approaches and emit clusters.
    units.extend(detect_clusters(prefs, source_peer, &scope, now, thresholds));

    units
}

/// Convert distilled preferences into knowledge units, using an existing store
/// to assign stable IDs (update existing units rather than creating new ones).
pub fn distill_to_knowledge_stable(
    prefs: &DistilledPreferences,
    source_peer: &str,
    project: Option<&str>,
    thresholds: &ExportThresholds,
    existing: &super::store::HiveStore,
) -> Vec<KnowledgeUnit> {
    let mut units = distill_to_knowledge(prefs, source_peer, project, thresholds);

    // For each unit, check if a semantically equivalent one already exists.
    // If so, reuse the ID and bump the version. Otherwise mark it as Canary
    // (#223) so its rollout is gated by outcome stats before going wider.
    for unit in &mut units {
        let sk = semantic_key(unit);
        if let Some(existing_unit) = existing.find_by_semantic_key(&sk) {
            if existing_unit.source_peer == unit.source_peer {
                unit.id = existing_unit.id.clone();
                unit.version = existing_unit.version + 1;
                unit.originated_at = existing_unit.originated_at;
                unit.propagation_count = existing_unit.propagation_count;
                // Preserve rollout state and stats — the unit's history is
                // what tells us whether it's earned promotion.
                unit.injection_state = existing_unit.injection_state;
                unit.injection_stats = existing_unit.injection_stats.clone();
            }
        } else {
            // Truly new: start in Canary so we collect outcome signal before
            // exposing it to every prompt.
            unit.injection_state = super::InjectionState::Canary;
        }
    }

    units
}

// ────────────────────────────────────────────────────────────────────────────
// #220 baselining: outcome aggregation
// ────────────────────────────────────────────────────────────────────────────

/// Build the canonical approach reference for a decision. Mirrors the shape
/// used by `Pattern`'s semantic_key so cluster/outcome views can join on it.
fn approach_ref_for(decision: &DecisionRecord) -> Option<String> {
    let tool = decision.tool.as_deref()?;
    let cmd = decision
        .command
        .as_deref()
        .map(|s| s.split_whitespace().collect::<Vec<_>>().join(" "))
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "*".to_string());
    Some(format!("pattern:{tool}:{cmd}"))
}

#[derive(Default)]
struct OutcomeBucket {
    samples: u32,
    successes: u32,
    costs: Vec<f64>,
    durations_ms: Vec<u64>,
    project_hits: HashMap<String, u32>,
}

fn median_f64(mut v: Vec<f64>) -> Option<f64> {
    if v.is_empty() {
        return None;
    }
    v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let mid = v.len() / 2;
    Some(if v.len() % 2 == 0 {
        (v[mid - 1] + v[mid]) / 2.0
    } else {
        v[mid]
    })
}

fn median_u64(mut v: Vec<u64>) -> Option<u64> {
    if v.is_empty() {
        return None;
    }
    v.sort();
    let mid = v.len() / 2;
    Some(if v.len() % 2 == 0 {
        (v[mid - 1] + v[mid]) / 2
    } else {
        v[mid]
    })
}

/// Aggregate decisions + their resolved outcomes into per-approach buckets,
/// then emit ApproachOutcome KnowledgeUnits that meet `min_outcome_samples`.
pub fn distill_outcomes(
    decisions: &[DecisionRecord],
    resolved: &HashMap<String, ResolvedOutcome>,
    source_peer: &str,
    scope: &KnowledgeScope,
    project_filter: Option<&str>,
    now: u64,
    thresholds: &ExportThresholds,
) -> Vec<KnowledgeUnit> {
    let mut buckets: HashMap<String, OutcomeBucket> = HashMap::new();
    for d in decisions {
        // Optional per-project view
        if let Some(p) = project_filter {
            if !d.project.eq_ignore_ascii_case(p) {
                continue;
            }
        }
        let Some(decision_id) = d.decision_id.as_deref() else {
            continue;
        };
        let Some(outcome) = resolved.get(decision_id) else {
            continue;
        };
        let Some(key) = approach_ref_for(d) else {
            continue;
        };
        let entry = buckets.entry(key).or_default();
        entry.samples += 1;
        if outcome.exit_code.unwrap_or(-1) == 0 {
            entry.successes += 1;
        }
        if let Some(ctx) = &d.context {
            if ctx.cost_usd > 0.0 {
                entry.costs.push(ctx.cost_usd);
            }
        }
        if let Some(ms) = outcome.duration_ms {
            entry.durations_ms.push(ms);
        }
        *entry.project_hits.entry(d.project.clone()).or_insert(0) += 1;
    }

    let mut out = Vec::new();
    for (approach_ref, bucket) in buckets {
        if bucket.samples < thresholds.min_outcome_samples {
            continue;
        }
        let success_rate = bucket.successes as f64 / bucket.samples as f64;
        let median_cost_usd = median_f64(bucket.costs);
        let median_duration_ms = median_u64(bucket.durations_ms);

        // Conditions: list each project that contributed >= 2 samples,
        // gives the cluster work later something to filter on.
        let mut conditions: Vec<String> = bucket
            .project_hits
            .into_iter()
            .filter(|(_, n)| *n >= 2)
            .map(|(p, n)| format!("project:{p} (n={n})"))
            .collect();
        conditions.sort();

        out.push(KnowledgeUnit {
            id: gen_ku_id(),
            scope: scope.clone(),
            category: super::KnowledgeCategory::BestPractice,
            content: KnowledgeContent::ApproachOutcome {
                approach_ref,
                success_rate,
                sample_count: bucket.samples,
                median_cost_usd,
                median_duration_ms,
                conditions,
            },
            evidence_count: bucket.samples,
            confidence: success_rate,
            source_peer: source_peer.to_string(),
            originated_at: now,
            last_validated_at: now,
            propagation_count: 0,
            version: 1,
            revalidation_interval_secs: 0,
            injection_state: crate::hive::InjectionState::Live,
            injection_stats: crate::hive::InjectionStats {
                injected_count: 0,
                accepted_count: 0,
                overridden_count: 0,
                last_injected_at: 0,
                last_outcome_at: 0,
            },
            sharing_consent: None,
        });
    }
    out
}

// ────────────────────────────────────────────────────────────────────────────
// #221 conflict-aware: cluster detection
// ────────────────────────────────────────────────────────────────────────────

/// Build the canonical problem key for a preference pattern.
/// Patterns sharing this key but differing on `preferred_action` are
/// candidates for an `ApproachCluster`.
fn problem_key_for(pattern: &PreferencePattern) -> String {
    let cmd = pattern.command_pattern.as_deref().unwrap_or("*");
    let normalized = cmd.split_whitespace().collect::<Vec<_>>().join(" ");
    format!("{}:{normalized}", pattern.tool)
}

/// Render a pattern's conditions as human-readable strings for the cluster
/// variant payload (so peers can reason about *when* a variant tends to win).
fn condition_labels(pattern: &PreferencePattern) -> Vec<String> {
    pattern.conditions.iter().map(|c| c.label()).collect()
}

/// Detect divergent preference patterns and emit `ApproachCluster` units.
/// A group qualifies when:
///   - 2+ patterns share the same `problem_key`
///   - they disagree on `preferred_action`
///   - each variant has `>= min_cluster_variant_evidence` samples
pub fn detect_clusters(
    prefs: &DistilledPreferences,
    source_peer: &str,
    scope: &KnowledgeScope,
    now: u64,
    thresholds: &ExportThresholds,
) -> Vec<KnowledgeUnit> {
    let mut groups: HashMap<String, Vec<&PreferencePattern>> = HashMap::new();
    for p in &prefs.patterns {
        groups.entry(problem_key_for(p)).or_default().push(p);
    }

    let mut units = Vec::new();
    for (problem_key, patterns) in groups {
        if patterns.len() < 2 {
            continue;
        }
        // Drop patterns below the per-variant evidence floor before checking
        // for divergence — a single weak counter-pattern shouldn't promote
        // an otherwise stable preference into a cluster.
        let qualifying: Vec<&PreferencePattern> = patterns
            .into_iter()
            .filter(|p| p.sample_count >= thresholds.min_cluster_variant_evidence)
            .collect();
        if qualifying.len() < 2 {
            continue;
        }
        let mut actions: Vec<&str> = qualifying
            .iter()
            .map(|p| p.preferred_action.as_str())
            .collect();
        actions.sort();
        actions.dedup();
        if actions.len() < 2 {
            continue; // all variants agree — not really a conflict
        }

        let outcome_ref = format!("pattern:{problem_key}");
        let variants: Vec<super::ApproachVariant> = qualifying
            .iter()
            .map(|p| super::ApproachVariant {
                approach_summary: format!(
                    "{} ({:.0}% accept over {})",
                    p.preferred_action,
                    p.accept_rate * 100.0,
                    p.sample_count
                ),
                conditions: condition_labels(p),
                evidence: p.sample_count,
                contributing_peers: vec![source_peer.to_string()],
                outcome_ref: Some(outcome_ref.clone()),
            })
            .collect();

        let total_evidence: u32 = variants.iter().map(|v| v.evidence).sum();
        let mean_confidence =
            qualifying.iter().map(|p| p.confidence).sum::<f64>() / qualifying.len() as f64;

        units.push(KnowledgeUnit {
            id: gen_ku_id(),
            scope: scope.clone(),
            category: super::KnowledgeCategory::Technique,
            content: KnowledgeContent::ApproachCluster {
                problem_key,
                variants,
            },
            evidence_count: total_evidence,
            confidence: mean_confidence,
            source_peer: source_peer.to_string(),
            originated_at: now,
            last_validated_at: now,
            propagation_count: 0,
            version: 1,
            revalidation_interval_secs: 0,
            injection_state: crate::hive::InjectionState::Live,
            injection_stats: crate::hive::InjectionStats {
                injected_count: 0,
                accepted_count: 0,
                overridden_count: 0,
                last_injected_at: 0,
                last_outcome_at: 0,
            },
            sharing_consent: None,
        });
    }
    units
}

// ────────────────────────────────────────────────────────────────────────────
// Individual converters
// ────────────────────────────────────────────────────────────────────────────

/// Classify a preference pattern into a knowledge category.
fn classify_pattern(pattern: &PreferencePattern) -> super::KnowledgeCategory {
    use super::KnowledgeCategory;
    use crate::brain::preferences::PreferenceCondition;

    // Patterns conditioned on cost or time-of-day are personal
    for cond in &pattern.conditions {
        match cond {
            PreferenceCondition::CostAbove(_) | PreferenceCondition::CostBelow(_) => {
                return KnowledgeCategory::Personal;
            }
            PreferenceCondition::HourRange(_, _) => {
                return KnowledgeCategory::Personal;
            }
            _ => {}
        }
    }

    // Tool approval/denial patterns are best practices
    KnowledgeCategory::BestPractice
}

fn pattern_to_unit(
    pattern: &PreferencePattern,
    source_peer: &str,
    scope: &KnowledgeScope,
    now: u64,
    thresholds: &ExportThresholds,
) -> Option<KnowledgeUnit> {
    if pattern.sample_count < thresholds.min_pattern_evidence {
        return None;
    }

    let category = classify_pattern(pattern);
    let conditions: Vec<String> = pattern.conditions.iter().map(|c| c.label()).collect();

    Some(KnowledgeUnit {
        id: gen_ku_id(),
        scope: scope.clone(),
        category,
        content: KnowledgeContent::Pattern {
            tool: pattern.tool.clone(),
            command_pattern: pattern.command_pattern.clone(),
            preferred_action: pattern.preferred_action.clone(),
            accept_rate: pattern.accept_rate,
            sample_count: pattern.sample_count,
            conditions,
        },
        evidence_count: pattern.sample_count,
        confidence: pattern.accept_rate,
        source_peer: source_peer.to_string(),
        originated_at: now,
        last_validated_at: now,
        propagation_count: 0,
        version: 1,
        revalidation_interval_secs: 0,
        injection_state: crate::hive::InjectionState::Live,
        injection_stats: crate::hive::InjectionStats {
            injected_count: 0,
            accepted_count: 0,
            overridden_count: 0,
            last_injected_at: 0,
            last_outcome_at: 0,
        },
        sharing_consent: None,
    })
}

fn accuracy_to_unit(
    acc: &ToolAccuracy,
    source_peer: &str,
    now: u64,
    thresholds: &ExportThresholds,
) -> Option<KnowledgeUnit> {
    if acc.total < thresholds.min_tool_decisions {
        return None;
    }

    Some(KnowledgeUnit {
        id: gen_ku_id(),
        scope: KnowledgeScope::Universal,
        category: super::KnowledgeCategory::BestPractice,
        content: KnowledgeContent::ToolAccuracy {
            tool: acc.tool.clone(),
            total: acc.total,
            correct: acc.correct,
            confidence_threshold: acc.confidence_threshold,
        },
        evidence_count: acc.total,
        confidence: if acc.total > 0 {
            acc.correct as f64 / acc.total as f64
        } else {
            0.0
        },
        source_peer: source_peer.to_string(),
        originated_at: now,
        last_validated_at: now,
        propagation_count: 0,
        version: 1,
        revalidation_interval_secs: 0,
        injection_state: crate::hive::InjectionState::Live,
        injection_stats: crate::hive::InjectionStats {
            injected_count: 0,
            accepted_count: 0,
            overridden_count: 0,
            last_injected_at: 0,
            last_outcome_at: 0,
        },
        sharing_consent: None,
    })
}

/// Classify a temporal pattern by its description.
fn classify_temporal(tp: &TemporalPattern) -> super::KnowledgeCategory {
    use super::KnowledgeCategory;
    let desc = tp.description.to_lowercase();

    // Time-of-day, approval speed, and cost patterns are personal
    if desc.contains("hour")
        || desc.contains("time of day")
        || desc.contains("morning")
        || desc.contains("evening")
        || desc.contains("approval")
    {
        return KnowledgeCategory::Personal;
    }
    if desc.contains("cost") || desc.contains("spend") || desc.contains("budget") {
        return KnowledgeCategory::Personal;
    }

    // Error streaks, context patterns are shareable techniques
    if desc.contains("error") || desc.contains("context") || desc.contains("retry") {
        return KnowledgeCategory::Technique;
    }

    KnowledgeCategory::BestPractice
}

fn temporal_to_unit(
    tp: &TemporalPattern,
    source_peer: &str,
    scope: &KnowledgeScope,
    now: u64,
    thresholds: &ExportThresholds,
) -> Option<KnowledgeUnit> {
    if tp.strength < thresholds.min_temporal_strength {
        return None;
    }

    let category = classify_temporal(tp);

    Some(KnowledgeUnit {
        id: gen_ku_id(),
        scope: scope.clone(),
        category,
        content: KnowledgeContent::Temporal {
            description: tp.description.clone(),
            strength: tp.strength,
        },
        evidence_count: tp.sample_count,
        confidence: tp.strength,
        source_peer: source_peer.to_string(),
        originated_at: now,
        last_validated_at: now,
        propagation_count: 0,
        version: 1,
        revalidation_interval_secs: 0,
        injection_state: crate::hive::InjectionState::Live,
        injection_stats: crate::hive::InjectionStats {
            injected_count: 0,
            accepted_count: 0,
            overridden_count: 0,
            last_injected_at: 0,
            last_outcome_at: 0,
        },
        sharing_consent: None,
    })
}

// ────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────

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

    fn make_prefs() -> DistilledPreferences {
        DistilledPreferences {
            patterns: vec![
                PreferencePattern {
                    tool: "Bash".into(),
                    command_pattern: Some("cargo test".into()),
                    preferred_action: "approve".into(),
                    sample_count: 20,
                    accept_rate: 0.95,
                    conditions: vec![],
                    confidence: 0.95,
                },
                PreferencePattern {
                    tool: "Bash".into(),
                    command_pattern: Some("rm -rf".into()),
                    preferred_action: "deny".into(),
                    sample_count: 3, // below threshold
                    accept_rate: 0.0,
                    conditions: vec![],
                    confidence: 0.0,
                },
            ],
            tool_accuracy: vec![
                ToolAccuracy {
                    tool: "Bash".into(),
                    total: 50,
                    correct: 42,
                    confidence_threshold: 0.7,
                },
                ToolAccuracy {
                    tool: "Read".into(),
                    total: 5, // below threshold
                    correct: 5,
                    confidence_threshold: 0.5,
                },
            ],
            temporal: vec![
                TemporalPattern {
                    description: "Error streak detected".into(),
                    sample_count: 8,
                    strength: 0.85,
                },
                TemporalPattern {
                    description: "Weak pattern".into(),
                    sample_count: 3,
                    strength: 0.3, // below threshold
                },
            ],
            total_decisions: 100,
            overall_accuracy: 84.0,
        }
    }

    #[test]
    fn distill_filters_by_thresholds() {
        let prefs = make_prefs();
        let units = distill_to_knowledge(&prefs, "test-peer", None, &ExportThresholds::default());

        // Should have: 1 pattern (20 >= 5, 3 < 5), 1 accuracy (50 >= 10, 5 < 10), 1 temporal (0.85 >= 0.7, 0.3 < 0.7)
        assert_eq!(units.len(), 3);
    }

    #[test]
    fn pattern_below_threshold_excluded() {
        let prefs = make_prefs();
        let units = distill_to_knowledge(&prefs, "test-peer", None, &ExportThresholds::default());

        // The rm -rf pattern (3 samples) should not be included
        let pattern_tools: Vec<&str> = units
            .iter()
            .filter_map(|u| match &u.content {
                KnowledgeContent::Pattern { tool, .. } => Some(tool.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(pattern_tools, vec!["Bash"]);
    }

    #[test]
    fn accuracy_below_threshold_excluded() {
        let prefs = make_prefs();
        let units = distill_to_knowledge(&prefs, "test-peer", None, &ExportThresholds::default());

        let accuracy_tools: Vec<&str> = units
            .iter()
            .filter_map(|u| match &u.content {
                KnowledgeContent::ToolAccuracy { tool, .. } => Some(tool.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(accuracy_tools, vec!["Bash"]);
    }

    #[test]
    fn temporal_below_threshold_excluded() {
        let prefs = make_prefs();
        let units = distill_to_knowledge(&prefs, "test-peer", None, &ExportThresholds::default());

        let temporal_descs: Vec<&str> = units
            .iter()
            .filter_map(|u| match &u.content {
                KnowledgeContent::Temporal { description, .. } => Some(description.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(temporal_descs, vec!["Error streak detected"]);
    }

    #[test]
    fn project_scope_applied() {
        let prefs = make_prefs();
        let units = distill_to_knowledge(
            &prefs,
            "test-peer",
            Some("claudectl"),
            &ExportThresholds::default(),
        );

        // Patterns and temporals get project scope; accuracy is always universal
        for unit in &units {
            match &unit.content {
                KnowledgeContent::ToolAccuracy { .. } => {
                    assert_eq!(unit.scope, KnowledgeScope::Universal);
                }
                _ => {
                    assert_eq!(unit.scope, KnowledgeScope::Project("claudectl".into()));
                }
            }
        }
    }

    #[test]
    fn stable_distill_reuses_ids() {
        let prefs = make_prefs();
        let first = distill_to_knowledge(&prefs, "test-peer", None, &ExportThresholds::default());

        let mut store =
            super::super::store::HiveStore::load_from(std::path::Path::new("/nonexistent"));
        for unit in &first {
            store.insert(unit.clone());
        }

        let second = distill_to_knowledge_stable(
            &prefs,
            "test-peer",
            None,
            &ExportThresholds::default(),
            &store,
        );

        // Second run should reuse IDs and bump versions
        for unit in &second {
            let sk = semantic_key(unit);
            if let Some(original) = store.find_by_semantic_key(&sk) {
                assert_eq!(unit.id, original.id);
                assert_eq!(unit.version, original.version + 1);
            }
        }
    }

    fn make_decision_with_id(id: &str, tool: &str, command: &str, project: &str) -> DecisionRecord {
        use crate::brain::decisions::DecisionType;
        DecisionRecord {
            timestamp: "0".into(),
            pid: 1,
            project: project.into(),
            tool: Some(tool.into()),
            command: Some(command.into()),
            brain_action: "approve".into(),
            brain_confidence: 0.9,
            brain_reasoning: "test".into(),
            user_action: "accept".into(),
            context: None,
            outcome: None,
            decision_type: DecisionType::Session,
            suggested_at: None,
            resolved_at: None,
            override_reason: None,
            decision_id: Some(id.into()),
        }
    }

    fn make_resolved(
        id: &str,
        tool: &str,
        project: &str,
        exit: Option<i32>,
        dur: Option<u64>,
    ) -> ResolvedOutcome {
        ResolvedOutcome {
            decision_id: id.into(),
            tool: tool.into(),
            command: Some("cargo test".into()),
            project: project.into(),
            exit_code: exit,
            duration_ms: dur,
            stderr_tail: None,
            ts: 0,
        }
    }

    #[test]
    fn distill_outcomes_aggregates_per_approach() {
        let decisions = vec![
            make_decision_with_id("d1", "Bash", "cargo test", "p"),
            make_decision_with_id("d2", "Bash", "cargo test", "p"),
            make_decision_with_id("d3", "Bash", "cargo test", "p"),
        ];
        let mut resolved = HashMap::new();
        resolved.insert(
            "d1".into(),
            make_resolved("d1", "Bash", "p", Some(0), Some(100)),
        );
        resolved.insert(
            "d2".into(),
            make_resolved("d2", "Bash", "p", Some(0), Some(200)),
        );
        resolved.insert(
            "d3".into(),
            make_resolved("d3", "Bash", "p", Some(1), Some(300)),
        );

        let units = distill_outcomes(
            &decisions,
            &resolved,
            "peer",
            &KnowledgeScope::Universal,
            None,
            0,
            &ExportThresholds {
                min_outcome_samples: 1,
                ..Default::default()
            },
        );

        assert_eq!(units.len(), 1, "all three share the same approach_ref");
        match &units[0].content {
            KnowledgeContent::ApproachOutcome {
                approach_ref,
                success_rate,
                sample_count,
                median_duration_ms,
                ..
            } => {
                assert_eq!(approach_ref, "pattern:Bash:cargo test");
                assert_eq!(*sample_count, 3);
                assert!((success_rate - 2.0 / 3.0).abs() < 1e-9);
                assert_eq!(*median_duration_ms, Some(200));
            }
            other => panic!("unexpected content {other:?}"),
        }
    }

    #[test]
    fn distill_outcomes_threshold_filters() {
        let decisions = vec![make_decision_with_id("d1", "Bash", "ls", "p")];
        let mut resolved = HashMap::new();
        resolved.insert("d1".into(), make_resolved("d1", "Bash", "p", Some(0), None));

        let units = distill_outcomes(
            &decisions,
            &resolved,
            "peer",
            &KnowledgeScope::Universal,
            None,
            0,
            &ExportThresholds {
                min_outcome_samples: 5,
                ..Default::default()
            },
        );
        assert!(units.is_empty(), "1 sample below threshold of 5");
    }

    #[test]
    fn distill_outcomes_skips_decisions_without_id() {
        // Old records lack decision_id and can't be joined to outcomes.
        let mut d = make_decision_with_id("d1", "Bash", "cargo test", "p");
        d.decision_id = None;
        let resolved = HashMap::new();
        let units = distill_outcomes(
            &[d],
            &resolved,
            "peer",
            &KnowledgeScope::Universal,
            None,
            0,
            &ExportThresholds {
                min_outcome_samples: 1,
                ..Default::default()
            },
        );
        assert!(units.is_empty());
    }

    #[test]
    fn distill_outcomes_project_filter() {
        let decisions = vec![
            make_decision_with_id("d1", "Bash", "cargo test", "alpha"),
            make_decision_with_id("d2", "Bash", "cargo test", "beta"),
        ];
        let mut resolved = HashMap::new();
        resolved.insert(
            "d1".into(),
            make_resolved("d1", "Bash", "alpha", Some(0), None),
        );
        resolved.insert(
            "d2".into(),
            make_resolved("d2", "Bash", "beta", Some(0), None),
        );

        let units = distill_outcomes(
            &decisions,
            &resolved,
            "peer",
            &KnowledgeScope::Project("alpha".into()),
            Some("alpha"),
            0,
            &ExportThresholds {
                min_outcome_samples: 1,
                ..Default::default()
            },
        );

        assert_eq!(units.len(), 1);
        if let KnowledgeContent::ApproachOutcome { sample_count, .. } = &units[0].content {
            assert_eq!(*sample_count, 1, "beta decision should be filtered out");
        } else {
            panic!("wrong content variant");
        }
    }

    fn make_pattern(
        tool: &str,
        cmd: &str,
        action: &str,
        n: u32,
        accept: f64,
        conds: Vec<crate::brain::preferences::PreferenceCondition>,
    ) -> PreferencePattern {
        PreferencePattern {
            tool: tool.into(),
            command_pattern: Some(cmd.into()),
            preferred_action: action.into(),
            sample_count: n,
            accept_rate: accept,
            conditions: conds,
            confidence: accept,
        }
    }

    #[test]
    fn detect_clusters_on_divergent_actions() {
        use crate::brain::preferences::PreferenceCondition;
        let prefs = DistilledPreferences {
            patterns: vec![
                make_pattern(
                    "Bash",
                    "git push",
                    "approve",
                    8,
                    0.9,
                    vec![PreferenceCondition::CostBelow(1.0)],
                ),
                make_pattern(
                    "Bash",
                    "git push",
                    "deny",
                    5,
                    0.1,
                    vec![PreferenceCondition::CostAbove(1.0)],
                ),
            ],
            tool_accuracy: vec![],
            temporal: vec![],
            total_decisions: 13,
            overall_accuracy: 0.0,
        };
        let units = detect_clusters(
            &prefs,
            "peer-a",
            &KnowledgeScope::Universal,
            0,
            &ExportThresholds::default(),
        );
        assert_eq!(
            units.len(),
            1,
            "should produce one cluster for the divergent group"
        );
        if let KnowledgeContent::ApproachCluster {
            problem_key,
            variants,
        } = &units[0].content
        {
            assert_eq!(problem_key, "Bash:git push");
            assert_eq!(variants.len(), 2);
            // Must capture both actions
            let summaries: Vec<&str> = variants
                .iter()
                .map(|v| v.approach_summary.as_str())
                .collect();
            assert!(summaries.iter().any(|s| s.starts_with("approve")));
            assert!(summaries.iter().any(|s| s.starts_with("deny")));
        } else {
            panic!("wrong content variant");
        }
    }

    #[test]
    fn detect_clusters_skips_when_actions_agree() {
        let prefs = DistilledPreferences {
            patterns: vec![
                make_pattern("Bash", "ls", "approve", 8, 0.9, vec![]),
                make_pattern("Bash", "ls", "approve", 5, 0.95, vec![]),
            ],
            tool_accuracy: vec![],
            temporal: vec![],
            total_decisions: 13,
            overall_accuracy: 0.0,
        };
        let units = detect_clusters(
            &prefs,
            "peer-a",
            &KnowledgeScope::Universal,
            0,
            &ExportThresholds::default(),
        );
        assert!(units.is_empty(), "no divergence → no cluster");
    }

    #[test]
    fn detect_clusters_skips_below_per_variant_threshold() {
        let prefs = DistilledPreferences {
            patterns: vec![
                make_pattern("Bash", "rm -rf", "deny", 8, 0.0, vec![]),
                // Counter-pattern is too weak to count as a real variant
                make_pattern("Bash", "rm -rf", "approve", 1, 1.0, vec![]),
            ],
            tool_accuracy: vec![],
            temporal: vec![],
            total_decisions: 9,
            overall_accuracy: 0.0,
        };
        let units = detect_clusters(
            &prefs,
            "peer-a",
            &KnowledgeScope::Universal,
            0,
            &ExportThresholds::default(),
        );
        assert!(
            units.is_empty(),
            "weak counter-pattern should not promote a cluster"
        );
    }

    #[test]
    fn approach_outcome_semantic_key_stable_across_peers() {
        // Two units from different peers describing the same approach must
        // produce the same semantic_key so the merger can dedup them.
        let unit_a = KnowledgeUnit {
            id: gen_ku_id(),
            scope: KnowledgeScope::Universal,
            category: super::super::KnowledgeCategory::BestPractice,
            content: KnowledgeContent::ApproachOutcome {
                approach_ref: "pattern:Bash:cargo test".into(),
                success_rate: 0.9,
                sample_count: 10,
                median_cost_usd: None,
                median_duration_ms: None,
                conditions: vec![],
            },
            evidence_count: 10,
            confidence: 0.9,
            source_peer: "peer-a".into(),
            originated_at: 0,
            last_validated_at: 0,
            propagation_count: 0,
            version: 1,
            revalidation_interval_secs: 0,
            injection_state: crate::hive::InjectionState::Live,
            injection_stats: crate::hive::InjectionStats {
                injected_count: 0,
                accepted_count: 0,
                overridden_count: 0,
                last_injected_at: 0,
                last_outcome_at: 0,
            },
            sharing_consent: None,
        };
        let mut unit_b = unit_a.clone();
        unit_b.source_peer = "peer-b".into();
        unit_b.id = gen_ku_id();
        assert_eq!(semantic_key(&unit_a), semantic_key(&unit_b));
    }

    #[test]
    fn custom_thresholds() {
        let prefs = make_prefs();
        let strict = ExportThresholds {
            min_pattern_evidence: 50,
            min_tool_decisions: 100,
            min_temporal_strength: 0.99,
            min_outcome_samples: u32::MAX,
            min_cluster_variant_evidence: u32::MAX,
        };
        let units = distill_to_knowledge(&prefs, "test-peer", None, &strict);
        assert_eq!(units.len(), 0); // nothing meets strict thresholds
    }
}