khive-pack-brain 0.2.1

Brain pack — profile-oriented orchestration via Fold + Objective (ADR-032)
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
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
pub mod event;
pub mod fold;
pub mod state;
pub mod tunable;

use std::sync::Mutex;

use async_trait::async_trait;
use chrono::Utc;
use serde::Deserialize;
use serde_json::{json, Value};

use khive_fold::{Fold, FoldContext};
use khive_runtime::pack::PackRuntime;
use khive_runtime::{
    DispatchHook, EventView, KhiveRuntime, NamespaceToken, RuntimeError, VerbRegistry,
};
use khive_storage::event::{Event, EventFilter};
use khive_storage::types::PageRequest;
use khive_types::{HandlerDef, Pack, VerbCategory, Visibility};

use crate::fold::BalancedRecallFold;
use crate::state::{BrainState, ProfileBinding, ProfileLifecycle, ProfileRecord};

const ENTITY_CACHE_CAPACITY: usize = 10_000;

// ── Handler table ─────────────────────────────────────────────────────────────

/// Brain pack verb surface per ADR-032 §11.
///
/// Visibility::Verb  = exposed on the MCP `request` tool.
/// Visibility::Subhandler = internal / operator-only.
///
/// ADR-025: illocutionary classification applied.
static BRAIN_HANDLERS: &[HandlerDef] = &[
    // ── Assertive (read) verbs ────────────────────────────────────────────
    HandlerDef {
        name: "brain.state",
        description: "Return current BrainState snapshot for inspection",
        visibility: Visibility::Subhandler,
        category: VerbCategory::Assertive,
    },
    HandlerDef {
        name: "brain.config",
        description: "Return projected config for a named pack parameter",
        visibility: Visibility::Subhandler,
        category: VerbCategory::Assertive,
    },
    HandlerDef {
        name: "brain.events",
        description: "List recent brain-relevant events for debugging",
        visibility: Visibility::Subhandler,
        category: VerbCategory::Assertive,
    },
    HandlerDef {
        name: "brain.profiles",
        description: "List profiles, optionally filtered by lifecycle",
        visibility: Visibility::Verb,
        category: VerbCategory::Assertive,
    },
    HandlerDef {
        name: "brain.profile",
        description: "Profile metadata, latest snapshot, current state summary",
        visibility: Visibility::Verb,
        category: VerbCategory::Assertive,
    },
    HandlerDef {
        name: "brain.resolve",
        description: "Show which profile would serve a caller context",
        visibility: Visibility::Verb,
        category: VerbCategory::Assertive,
    },
    // ── Commissive (write state) verbs ────────────────────────────────────
    HandlerDef {
        name: "brain.activate",
        description: "Move a profile to Active (start live update loop)",
        visibility: Visibility::Verb,
        category: VerbCategory::Commissive,
    },
    HandlerDef {
        name: "brain.deactivate",
        description: "Move a profile to Inactive (stop live updates, retain state)",
        visibility: Visibility::Verb,
        category: VerbCategory::Commissive,
    },
    HandlerDef {
        name: "brain.archive",
        description: "Move a profile to Archived (read-only, audit-retained)",
        visibility: Visibility::Verb,
        category: VerbCategory::Declaration,
    },
    HandlerDef {
        name: "brain.reset",
        description: "Reset posteriors to priors (preserves event history)",
        visibility: Visibility::Verb,
        category: VerbCategory::Declaration,
    },
    HandlerDef {
        name: "brain.feedback",
        description: "Emit a FeedbackExplicit event into the shared log",
        visibility: Visibility::Verb,
        category: VerbCategory::Commissive,
    },
    // ── Declaration verbs ─────────────────────────────────────────────────
    HandlerDef {
        name: "brain.bind",
        description: "Write a row in the profile resolution table",
        visibility: Visibility::Verb,
        category: VerbCategory::Declaration,
    },
    HandlerDef {
        name: "brain.unbind",
        description: "Remove rows from the profile resolution table",
        visibility: Visibility::Verb,
        category: VerbCategory::Declaration,
    },
    // ── Legacy / internal ─────────────────────────────────────────────────
    HandlerDef {
        name: "brain.emit",
        description: "Manually emit a feedback event (deprecated; use brain.feedback)",
        visibility: Visibility::Subhandler,
        category: VerbCategory::Commissive,
    },
];

// ── BrainPack ─────────────────────────────────────────────────────────────────

/// Brain pack — profile-oriented auto-tuning (ADR-032).
///
/// `BrainState` holds the profile registry. `BalancedRecallFold` drives the
/// v1 default profile. The old scalar `BrainState` design is superseded; see
/// ADR-032 §1 and the migration notes in `state.rs`.
pub struct BrainPack {
    runtime: KhiveRuntime,
    /// Profile registry + active balanced-recall state.
    state: Mutex<BrainState>,
    /// Fold for the built-in `balanced-recall-v1` profile.
    fold: BalancedRecallFold,
}

impl Pack for BrainPack {
    const NAME: &'static str = "brain";
    const NOTE_KINDS: &'static [&'static str] = &[];
    const ENTITY_KINDS: &'static [&'static str] = &[];
    const HANDLERS: &'static [HandlerDef] = BRAIN_HANDLERS;
    const REQUIRES: &'static [&'static str] = &["kg"];
}

impl BrainPack {
    pub fn new(runtime: KhiveRuntime) -> Self {
        let fold = BalancedRecallFold::new(ENTITY_CACHE_CAPACITY);
        let state = BrainState::new(ENTITY_CACHE_CAPACITY);
        Self {
            runtime,
            state: Mutex::new(state),
            fold,
        }
    }

    /// Public snapshot of the current `BrainState`.
    pub fn snapshot(&self) -> crate::state::BrainStateSnapshot {
        self.state.lock().unwrap().to_snapshot()
    }

    // ── brain.state ───────────────────────────────────────────────────────

    async fn handle_state(&self, _params: Value) -> Result<Value, RuntimeError> {
        let state = self.state.lock().unwrap();
        let snapshot = state.to_snapshot();
        serde_json::to_value(&snapshot).map_err(|e| RuntimeError::InvalidInput(e.to_string()))
    }

    // ── brain.config ──────────────────────────────────────────────────────

    async fn handle_config(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct ConfigParams {
            parameter: Option<String>,
        }
        let p: ConfigParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let state = self.state.lock().unwrap();
        let br = &state.balanced_recall;

        let param_map = [
            ("recall::relevance_weight", &br.relevance),
            ("recall::importance_weight", &br.importance),
            ("recall::temporal_weight", &br.temporal),
        ];

        match p.parameter {
            Some(key) => {
                let posterior = param_map
                    .iter()
                    .find(|(k, _)| *k == key)
                    .map(|(_, p)| *p)
                    .ok_or_else(|| {
                        RuntimeError::NotFound(format!(
                            "parameter {key:?}; valid: {}",
                            param_map
                                .iter()
                                .map(|(k, _)| *k)
                                .collect::<Vec<_>>()
                                .join(", ")
                        ))
                    })?;
                Ok(json!({
                    "parameter": key,
                    "mean": posterior.mean(),
                    "variance": posterior.variance(),
                    "ess": posterior.effective_sample_size(),
                    "alpha": posterior.alpha,
                    "beta": posterior.beta,
                }))
            }
            None => {
                let configs: serde_json::Map<String, Value> = param_map
                    .iter()
                    .map(|(k, p)| {
                        (
                            (*k).to_owned(),
                            json!({
                                "mean": p.mean(),
                                "variance": p.variance(),
                                "ess": p.effective_sample_size(),
                            }),
                        )
                    })
                    .collect();
                Ok(Value::Object(configs))
            }
        }
    }

    // ── brain.events ──────────────────────────────────────────────────────

    async fn handle_events(
        &self,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct EventsParams {
            limit: Option<u32>,
        }
        let p: EventsParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let limit = p.limit.unwrap_or(20).min(100);
        let ns = token.namespace().as_str().to_string();

        let store = self.runtime.events(token)?;
        let filter = EventFilter {
            verbs: vec![
                "recall".into(),
                "search".into(),
                "brain.feedback".into(),
                "brain.emit".into(), // retained for backward-compat queries
                "get".into(),
                "remember".into(),
            ],
            ..EventFilter::default()
        };
        let _ = ns;
        let page = store
            .query_events(filter, PageRequest { offset: 0, limit })
            .await
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let events: Vec<Value> = page
            .items
            .iter()
            .map(|e| {
                json!({
                    "id": e.id.to_string(),
                    "verb": e.verb,
                    "outcome": e.outcome,
                    "target_id": e.target_id.map(|t| t.to_string()),
                    "duration_us": e.duration_us,
                    "created_at": e.created_at,
                    "payload": e.payload,
                })
            })
            .collect();

        Ok(json!({
            "count": events.len(),
            "events": events,
        }))
    }

    // ── brain.profiles ────────────────────────────────────────────────────

    async fn handle_profiles(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct ProfilesParams {
            lifecycle: Option<String>,
        }
        let p: ProfilesParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let state = self.state.lock().unwrap();
        let filter_lc: Option<ProfileLifecycle> = p
            .lifecycle
            .as_deref()
            .map(|s| serde_json::from_value(Value::String(s.to_owned())))
            .transpose()
            .map_err(|e| RuntimeError::InvalidInput(format!("invalid lifecycle: {e}")))?;

        let profiles: Vec<&ProfileRecord> = state
            .profiles
            .values()
            .filter(|r| filter_lc.as_ref().is_none_or(|lc| &r.lifecycle == lc))
            .collect();

        let items: Vec<Value> = profiles
            .iter()
            .map(|r| {
                json!({
                    "id": r.id,
                    "description": r.description,
                    "consumer_kind": r.consumer_kind,
                    "state_class": r.state_class,
                    "lifecycle": r.lifecycle,
                    "total_events": r.total_events,
                    "exploration_epoch": r.exploration_epoch,
                    "created_at": r.created_at,
                })
            })
            .collect();

        Ok(json!({ "count": items.len(), "profiles": items }))
    }

    // ── brain.profile ─────────────────────────────────────────────────────

    async fn handle_profile(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct ProfileParams {
            id: String,
        }
        let p: ProfileParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let state = self.state.lock().unwrap();
        let record = state
            .profiles
            .get(&p.id)
            .ok_or_else(|| RuntimeError::NotFound(format!("profile {:?}", p.id)))?;

        Ok(json!({
            "id": record.id,
            "description": record.description,
            "consumer_kind": record.consumer_kind,
            "state_class": record.state_class,
            "lifecycle": record.lifecycle,
            "total_events": record.total_events,
            "exploration_epoch": record.exploration_epoch,
            "created_at": record.created_at,
            "state_snapshot": record.state_snapshot,
        }))
    }

    // ── brain.resolve ─────────────────────────────────────────────────────

    async fn handle_resolve(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct ResolveParams {
            actor: Option<String>,
            namespace: Option<String>,
            consumer_kind: String,
        }
        let p: ResolveParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let state = self.state.lock().unwrap();
        match state.resolve(p.actor.as_deref(), p.namespace.as_deref(), &p.consumer_kind) {
            Some(record) => Ok(json!({
                "resolved_profile_id": record.id,
                "lifecycle": record.lifecycle,
                "consumer_kind": record.consumer_kind,
            })),
            None => Err(RuntimeError::NotFound(format!(
                "no profile resolved for consumer_kind={:?}",
                p.consumer_kind
            ))),
        }
    }

    // ── brain.activate / deactivate / archive ─────────────────────────────

    async fn handle_activate(&self, params: Value) -> Result<Value, RuntimeError> {
        self.set_lifecycle(params, ProfileLifecycle::Active).await
    }

    async fn handle_deactivate(&self, params: Value) -> Result<Value, RuntimeError> {
        self.set_lifecycle(params, ProfileLifecycle::Inactive).await
    }

    async fn handle_archive(&self, params: Value) -> Result<Value, RuntimeError> {
        self.set_lifecycle(params, ProfileLifecycle::Archived).await
    }

    async fn set_lifecycle(
        &self,
        params: Value,
        lifecycle: ProfileLifecycle,
    ) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct LifecycleParams {
            profile_id: String,
        }
        let p: LifecycleParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let mut state = self.state.lock().unwrap();
        let record = state
            .profiles
            .get_mut(&p.profile_id)
            .ok_or_else(|| RuntimeError::NotFound(format!("profile {:?}", p.profile_id)))?;

        record.lifecycle = lifecycle.clone();
        Ok(json!({
            "profile_id": p.profile_id,
            "lifecycle": lifecycle,
        }))
    }

    // ── brain.reset ───────────────────────────────────────────────────────

    async fn handle_reset(&self, _params: Value) -> Result<Value, RuntimeError> {
        let mut state = self.state.lock().unwrap();
        state.reset_posteriors();
        Ok(json!({
            "reset": true,
            "exploration_epoch": state.balanced_recall.exploration_epoch,
        }))
    }

    // ── brain.feedback ────────────────────────────────────────────────────

    async fn handle_feedback(
        &self,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct FeedbackParams {
            target_id: String,
            signal: String,
            served_by_profile_id: Option<String>,
        }
        let p: FeedbackParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let target: uuid::Uuid = p
            .target_id
            .parse()
            .map_err(|e| RuntimeError::InvalidInput(format!("invalid target_id: {e}")))?;

        let signal = match p.signal.as_str() {
            "useful" => "useful",
            "not_useful" => "not_useful",
            "wrong" => "wrong",
            other => {
                return Err(RuntimeError::InvalidInput(format!(
                    "unknown signal {other:?}; valid: useful | not_useful | wrong"
                )))
            }
        };

        let mut data = json!({"signal": signal});
        if let Some(ref profile_id) = p.served_by_profile_id {
            data["served_by_profile_id"] = json!(profile_id);
        }

        let event = Event::new(
            token.namespace().as_str().to_string(),
            "brain.feedback",
            khive_types::EventKind::FeedbackExplicit,
            khive_types::SubstrateKind::Event,
            "brain",
        )
        .with_target(target)
        .with_payload(data);

        let store = self.runtime.events(token)?;
        store
            .append_event(event.clone())
            .await
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        // Update balanced-recall profile state from this event
        let ctx = FoldContext::new();
        let mut state = self.state.lock().unwrap();
        let current_recall = std::mem::replace(
            &mut state.balanced_recall,
            crate::state::BalancedRecallState::new(0),
        );
        let updated = self.fold.reduce(current_recall, &event, &ctx);
        state.balanced_recall = updated;

        // Sync profile record metadata — collect values first to avoid borrow conflict.
        let total_ev = state.balanced_recall.total_events;
        let snap_val = serde_json::to_value(state.balanced_recall.to_snapshot()).ok();
        if let Some(record) = state.profiles.get_mut("balanced-recall-v1") {
            record.total_events = total_ev;
            record.state_snapshot = snap_val;
        }

        Ok(json!({
            "emitted": true,
            "event_id": event.id.to_string(),
            "verb": "brain.feedback",
            "signal": signal,
            "target_id": target.to_string(),
        }))
    }

    // ── brain.emit (deprecated) ───────────────────────────────────────────

    /// Deprecated: use `brain.feedback`. Kept for backward-compat; routes to
    /// `handle_feedback` with the same parameters.
    async fn handle_emit(
        &self,
        token: &NamespaceToken,
        params: Value,
    ) -> Result<Value, RuntimeError> {
        self.handle_feedback(token, params).await
    }

    // ── brain.bind ────────────────────────────────────────────────────────

    async fn handle_bind(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct BindParams {
            profile_id: String,
            actor: Option<String>,
            namespace: Option<String>,
            consumer_kind: Option<String>,
            priority: Option<i32>,
        }
        let p: BindParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let mut state = self.state.lock().unwrap();

        // Verify the profile exists
        if !state.profiles.contains_key(&p.profile_id) {
            return Err(RuntimeError::NotFound(format!(
                "profile {:?}",
                p.profile_id
            )));
        }

        let actor = p.actor.unwrap_or_else(|| "*".into());
        let namespace = p.namespace.unwrap_or_else(|| "*".into());
        let consumer_kind = p.consumer_kind.unwrap_or_else(|| "*".into());

        // Validate that '*' is not used as a real value (ADR-032 §10 wildcard sentinel)
        for (field, val) in [
            ("actor", &actor),
            ("namespace", &namespace),
            ("consumer_kind", &consumer_kind),
        ] {
            if val.as_str() != "*" && val.contains('*') {
                return Err(RuntimeError::InvalidInput(format!(
                    "{field}: '*' is reserved as the wildcard sentinel and cannot appear inside a real value"
                )));
            }
        }

        // Remove any existing binding for the same (actor, namespace, consumer_kind)
        state.bindings.retain(|b| {
            !(b.actor == actor && b.namespace == namespace && b.consumer_kind == consumer_kind)
        });

        state.bindings.push(ProfileBinding {
            actor: actor.clone(),
            namespace: namespace.clone(),
            consumer_kind: consumer_kind.clone(),
            profile_id: p.profile_id.clone(),
            priority: p.priority.unwrap_or(0),
            created_at: Utc::now(),
        });

        Ok(json!({
            "bound": true,
            "profile_id": p.profile_id,
            "actor": actor,
            "namespace": namespace,
            "consumer_kind": consumer_kind,
        }))
    }

    // ── brain.unbind ──────────────────────────────────────────────────────

    async fn handle_unbind(&self, params: Value) -> Result<Value, RuntimeError> {
        #[derive(Deserialize)]
        struct UnbindParams {
            profile_id: Option<String>,
            actor: Option<String>,
            namespace: Option<String>,
            consumer_kind: Option<String>,
        }
        let p: UnbindParams = serde_json::from_value(params)
            .map_err(|e| RuntimeError::InvalidInput(e.to_string()))?;

        let mut state = self.state.lock().unwrap();
        let before = state.bindings.len();

        state.bindings.retain(|b| {
            let pid_match = p.profile_id.as_ref().is_none_or(|id| &b.profile_id == id);
            let actor_match = p.actor.as_ref().is_none_or(|a| &b.actor == a);
            let ns_match = p.namespace.as_ref().is_none_or(|n| &b.namespace == n);
            let kind_match = p
                .consumer_kind
                .as_ref()
                .is_none_or(|k| &b.consumer_kind == k);
            // Retain if this binding does NOT match ALL of the provided filters.
            // A filter that is absent (None) matches everything — only bindings
            // satisfying every supplied criterion are removed.
            !(pid_match && actor_match && ns_match && kind_match)
        });

        let removed = before - state.bindings.len();
        Ok(json!({ "unbound": removed }))
    }
}

// ── Inventory self-registration ───────────────────────────────────────────────

struct BrainPackFactory;

impl khive_runtime::PackFactory for BrainPackFactory {
    fn name(&self) -> &'static str {
        "brain"
    }

    fn requires(&self) -> &'static [&'static str] {
        &["kg"]
    }

    fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
        Box::new(BrainPack::new(runtime))
    }
}

inventory::submit! { khive_runtime::PackRegistration(&BrainPackFactory) }

// ── PackRuntime impl ──────────────────────────────────────────────────────────

#[async_trait]
impl PackRuntime for BrainPack {
    fn name(&self) -> &str {
        <BrainPack as Pack>::NAME
    }

    fn note_kinds(&self) -> &'static [&'static str] {
        <BrainPack as Pack>::NOTE_KINDS
    }

    fn entity_kinds(&self) -> &'static [&'static str] {
        <BrainPack as Pack>::ENTITY_KINDS
    }

    fn handlers(&self) -> &'static [HandlerDef] {
        BRAIN_HANDLERS
    }

    fn requires(&self) -> &'static [&'static str] {
        <BrainPack as Pack>::REQUIRES
    }

    async fn dispatch(
        &self,
        verb: &str,
        params: Value,
        _registry: &VerbRegistry,
        token: &NamespaceToken,
    ) -> Result<Value, RuntimeError> {
        match verb {
            // Assertive
            "brain.state" => self.handle_state(params).await,
            "brain.config" => self.handle_config(params).await,
            "brain.events" => self.handle_events(token, params).await,
            "brain.profiles" => self.handle_profiles(params).await,
            "brain.profile" => self.handle_profile(params).await,
            "brain.resolve" => self.handle_resolve(params).await,
            // Commissive
            "brain.activate" => self.handle_activate(params).await,
            "brain.deactivate" => self.handle_deactivate(params).await,
            "brain.archive" => self.handle_archive(params).await,
            "brain.reset" => self.handle_reset(params).await,
            "brain.feedback" => self.handle_feedback(token, params).await,
            // Declaration
            "brain.bind" => self.handle_bind(params).await,
            "brain.unbind" => self.handle_unbind(params).await,
            // Legacy
            "brain.emit" => self.handle_emit(token, params).await,
            _ => Err(RuntimeError::InvalidInput(format!(
                "brain pack does not handle verb {verb:?}"
            ))),
        }
    }
}

// ── DispatchHook impl ─────────────────────────────────────────────────────────

/// `BrainPack` as a post-dispatch hook.
///
/// When registered via `VerbRegistryBuilder::with_dispatch_hook`, every
/// successful verb dispatch calls `on_dispatch` with a synthesized `Event`.
/// The event is fed into `BalancedRecallFold::reduce`, updating the brain's
/// posteriors in real time — no polling required.
#[async_trait]
impl DispatchHook for BrainPack {
    async fn on_dispatch(&self, view: &EventView) {
        let ctx = FoldContext::new();
        let mut state = self.state.lock().unwrap();
        let current = std::mem::replace(
            &mut state.balanced_recall,
            crate::state::BalancedRecallState::new(0),
        );
        let updated = self.fold.reduce(current, &view.event, &ctx);
        state.balanced_recall = updated;
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use khive_runtime::{Namespace, VerbRegistryBuilder};
    use serde_json::json;

    fn make_pack() -> (BrainPack, KhiveRuntime) {
        let rt = KhiveRuntime::memory().expect("in-memory runtime");
        let pack = BrainPack::new(rt.clone());
        (pack, rt)
    }

    fn empty_registry() -> VerbRegistry {
        VerbRegistryBuilder::new()
            .build()
            .expect("empty registry builds successfully")
    }

    #[tokio::test]
    async fn dispatch_unknown_verb_returns_invalid_input() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let err = pack
            .dispatch(
                "brain.unknown",
                json!({}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap_err();
        if let RuntimeError::InvalidInput(msg) = &err {
            assert!(
                msg.contains("brain.unknown"),
                "expected verb name in error: {msg}"
            );
        } else {
            panic!("expected InvalidInput, got {err:?}");
        }
    }

    #[tokio::test]
    async fn dispatch_reset_returns_true_and_increments_epoch() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.reset",
                json!({}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert_eq!(result["reset"], json!(true));
        assert_eq!(result["exploration_epoch"], json!(1u64));
    }

    #[tokio::test]
    async fn dispatch_feedback_invalid_signal_returns_invalid_input() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let target = "00000000-0000-0000-0000-000000000001";
        let err = pack
            .dispatch(
                "brain.feedback",
                json!({"target_id": target, "signal": "bad_signal"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap_err();
        if let RuntimeError::InvalidInput(msg) = &err {
            assert!(
                msg.contains("bad_signal"),
                "expected signal name in error: {msg}"
            );
            assert!(
                msg.contains("valid"),
                "expected hint about valid values: {msg}"
            );
        } else {
            panic!("expected InvalidInput, got {err:?}");
        }
    }

    #[tokio::test]
    async fn dispatch_state_returns_snapshot_fields() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.state",
                json!({}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert!(result.get("profiles").is_some(), "missing profiles");
        assert!(
            result.get("balanced_recall").is_some(),
            "missing balanced_recall"
        );
        assert!(result.get("bindings").is_some(), "missing bindings");
    }

    #[tokio::test]
    async fn dispatch_profiles_returns_default_profile() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.profiles",
                json!({}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        let profiles = result["profiles"].as_array().unwrap();
        assert!(!profiles.is_empty(), "expected at least one profile");
        assert_eq!(profiles[0]["id"], json!("balanced-recall-v1"));
    }

    #[tokio::test]
    async fn dispatch_profiles_filtered_by_lifecycle() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.profiles",
                json!({"lifecycle": "active"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        let profiles = result["profiles"].as_array().unwrap();
        for p in profiles {
            assert_eq!(p["lifecycle"], json!("active"));
        }
    }

    #[tokio::test]
    async fn dispatch_profile_returns_profile_details() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.profile",
                json!({"id": "balanced-recall-v1"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert_eq!(result["id"], json!("balanced-recall-v1"));
        assert_eq!(result["state_class"], json!("Bayesian"));
        assert_eq!(result["consumer_kind"], json!("recall"));
    }

    #[tokio::test]
    async fn dispatch_profile_not_found_returns_not_found() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let err = pack
            .dispatch(
                "brain.profile",
                json!({"id": "nonexistent"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[tokio::test]
    async fn dispatch_resolve_returns_default_profile_for_recall() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.resolve",
                json!({"consumer_kind": "recall"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert_eq!(result["resolved_profile_id"], json!("balanced-recall-v1"));
    }

    #[tokio::test]
    async fn dispatch_activate_and_deactivate_profile() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let token = rt.authorize(Namespace::local());

        // Deactivate the default profile
        let result = pack
            .dispatch(
                "brain.deactivate",
                json!({"profile_id": "balanced-recall-v1"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(result["lifecycle"], json!("inactive"));

        // Verify via brain.profile
        let state = pack
            .dispatch(
                "brain.profile",
                json!({"id": "balanced-recall-v1"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(state["lifecycle"], json!("inactive"));

        // Reactivate
        let result = pack
            .dispatch(
                "brain.activate",
                json!({"profile_id": "balanced-recall-v1"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(result["lifecycle"], json!("active"));
    }

    #[tokio::test]
    async fn dispatch_archive_profile() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.archive",
                json!({"profile_id": "balanced-recall-v1"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert_eq!(result["lifecycle"], json!("archived"));
    }

    #[tokio::test]
    async fn dispatch_activate_nonexistent_profile_returns_not_found() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let err = pack
            .dispatch(
                "brain.activate",
                json!({"profile_id": "ghost-profile"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[tokio::test]
    async fn dispatch_bind_and_resolve_explicit_binding() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let token = rt.authorize(Namespace::local());

        // Bind balanced-recall-v1 for actor "agent-x"
        let result = pack
            .dispatch(
                "brain.bind",
                json!({
                    "profile_id": "balanced-recall-v1",
                    "actor": "agent-x",
                    "consumer_kind": "recall"
                }),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(result["bound"], json!(true));
        assert_eq!(result["actor"], json!("agent-x"));

        // Resolve — should return the explicitly bound profile
        let resolved = pack
            .dispatch(
                "brain.resolve",
                json!({"actor": "agent-x", "consumer_kind": "recall"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(resolved["resolved_profile_id"], json!("balanced-recall-v1"));
    }

    #[tokio::test]
    async fn dispatch_bind_nonexistent_profile_returns_not_found() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let err = pack
            .dispatch(
                "brain.bind",
                json!({"profile_id": "ghost", "consumer_kind": "recall"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap_err();
        assert!(matches!(err, RuntimeError::NotFound(_)));
    }

    #[tokio::test]
    async fn dispatch_unbind_removes_binding() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let token = rt.authorize(Namespace::local());

        // Add a binding
        pack.dispatch(
            "brain.bind",
            json!({"profile_id": "balanced-recall-v1", "actor": "agent-y", "consumer_kind": "recall"}),
            &registry,
            &token,
        )
        .await
        .unwrap();

        // Remove it
        let result = pack
            .dispatch(
                "brain.unbind",
                json!({"actor": "agent-y"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(result["unbound"], json!(1u64));
    }

    // Regression test for MAJ-002: unbind with multiple filters must use AND semantics,
    // removing only the binding that satisfies ALL supplied criteria.
    #[tokio::test]
    async fn dispatch_unbind_uses_and_not_or() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let token = rt.authorize(Namespace::local());

        // binding 1: ns=A, profile=P1 (the one we want to remove)
        pack.dispatch(
            "brain.bind",
            json!({"profile_id": "balanced-recall-v1", "namespace": "ns-a", "consumer_kind": "recall"}),
            &registry,
            &token,
        )
        .await
        .unwrap();

        // binding 2: ns=B, profile=P1 (must survive)
        pack.dispatch(
            "brain.bind",
            json!({"profile_id": "balanced-recall-v1", "namespace": "ns-b", "consumer_kind": "recall"}),
            &registry,
            &token,
        )
        .await
        .unwrap();

        // Unbind using both filters: only binding-1 should be removed
        let result = pack
            .dispatch(
                "brain.unbind",
                json!({"namespace": "ns-a", "profile_id": "balanced-recall-v1"}),
                &registry,
                &token,
            )
            .await
            .unwrap();
        assert_eq!(
            result["unbound"],
            json!(1u64),
            "should remove exactly one binding"
        );

        // binding-2 (ns-b) must still exist
        let state = pack.state.lock().unwrap();
        let remaining: Vec<_> = state
            .bindings
            .iter()
            .filter(|b| b.namespace == "ns-b")
            .collect();
        assert_eq!(remaining.len(), 1, "ns-b binding must survive the unbind");
    }

    #[tokio::test]
    async fn dispatch_config_all_parameters() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.config",
                json!({}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        let obj = result.as_object().unwrap();
        assert!(obj.contains_key("recall::relevance_weight"));
        assert!(obj.contains_key("recall::importance_weight"));
        assert!(obj.contains_key("recall::temporal_weight"));
    }

    #[tokio::test]
    async fn dispatch_config_single_parameter() {
        let (pack, rt) = make_pack();
        let registry = empty_registry();
        let result = pack
            .dispatch(
                "brain.config",
                json!({"parameter": "recall::relevance_weight"}),
                &registry,
                &rt.authorize(Namespace::local()),
            )
            .await
            .unwrap();
        assert_eq!(result["parameter"], json!("recall::relevance_weight"));
        // Prior is Beta(7,3): mean = 0.7
        let mean = result["mean"].as_f64().unwrap();
        assert!((mean - 0.7).abs() < 1e-6);
    }
}