khive-pack-brain 0.5.0

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
//! Brain event interpretation — maps raw `Event` records to typed `BrainSignal` values.

use std::collections::HashMap;

use khive_storage::event::Event;
use khive_types::EventOutcome;

pub use khive_brain_core::BrainSignal;
use khive_brain_core::{FeedbackEventKind, FeedbackSignal, SectionType};

/// Extract a brain signal from a raw storage Event.
///
/// `brain.emit` is no longer handled here — it was renamed to `brain.feedback`
/// (`brain.feedback` is the `FeedbackExplicit` event emitter).
/// Any `brain.emit` event that predates this rename is treated as Irrelevant so
/// that old event log entries do not cause spurious feedback updates.
///
/// The runtime dispatch hook (`khive-runtime`) emits the namespaced verb
/// (e.g. `"memory.recall"`) as the verb it actually dispatched. `"recall"` is
/// retained as a legacy alias for event-log rows predating namespacing.
///
/// To add a new signal source: add one match arm to this function.
pub fn interpret(event: &Event) -> BrainSignal {
    match event.verb.as_str() {
        "memory.recall" | "recall" => match event.outcome {
            EventOutcome::Success => match event.target_id {
                Some(tid) => BrainSignal::RecallHit {
                    target_id: tid,
                    latency_us: event.duration_us,
                },
                None => BrainSignal::RecallMiss,
            },
            _ => BrainSignal::RecallMiss,
        },
        "search" => BrainSignal::SearchCompleted {
            latency_us: event.duration_us,
        },
        // brain.feedback is the verb for FeedbackExplicit events.
        // (brain.emit predates this rename; treated as Irrelevant for old replays.)
        "brain.feedback" => {
            let target = match event.target_id {
                Some(t) => t,
                None => return BrainSignal::Irrelevant,
            };
            let signal_str = event
                .payload
                .get("signal")
                .and_then(|s| s.as_str())
                .unwrap_or("");
            let served_by = event
                .payload
                .get("served_by_profile_id")
                .and_then(|v| v.as_str())
                .map(|s| s.to_owned());
            // Parse section_signals through the shared validator so that semantically
            // poisoned entries (empty map, unknown section, out-of-contract signal value)
            // produce None — identical treatment during both live handler and replay.
            let section_signals = event.payload.get("section_signals").and_then(|v| {
                // Reject anything the shared validator would have rejected up front.
                // This is the replay path: invalid entries yield None (→ Irrelevant for
                // the section fold), and the caller (persist.rs) quarantines the whole
                // event before calling apply_signal.
                if crate::validate_section_signals(v).is_err() {
                    return None;
                }
                serde_json::from_value::<HashMap<SectionType, FeedbackSignal>>(v.clone()).ok()
            });

            // Issue #268: try semantic event kind names first, then fall back to
            // legacy FeedbackSignal (useful / not_useful / wrong).
            if let Some(event_kind) = FeedbackEventKind::from_signal_str(signal_str) {
                // ADR-081 §2: the fold gate (handlers::handle_feedback) computes the
                // actually-applied weight once, at emit time, and stamps it onto the
                // event payload under "gate.effective_weight" before persisting. Replay
                // reads the same stamp so the posterior update is reproduced exactly,
                // rather than re-evaluating the gate against present-day mass state.
                // Events without the stamp (pre-ADR-081 history, or non-gated signals)
                // fall back to the nominal weight.
                let effective_weight = event
                    .payload
                    .get("gate")
                    .and_then(|g| g.get("effective_weight"))
                    .and_then(|v| v.as_f64())
                    .unwrap_or_else(|| event_kind.update_weight());
                BrainSignal::SemanticFeedback {
                    target_id: target,
                    event_kind,
                    served_by_profile_id: served_by,
                    effective_weight,
                }
            } else {
                let signal = serde_json::from_value::<FeedbackSignal>(serde_json::Value::String(
                    signal_str.to_owned(),
                ))
                .ok();
                match signal {
                    Some(s) => BrainSignal::Feedback {
                        target_id: target,
                        signal: s,
                        served_by_profile_id: served_by,
                        section_signals,
                    },
                    None => BrainSignal::Irrelevant,
                }
            }
        }
        "get" | "remember" => match event.target_id {
            Some(tid) => BrainSignal::NoteAccessed { target_id: tid },
            None => BrainSignal::Irrelevant,
        },
        _ => BrainSignal::Irrelevant,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use khive_brain_core::{entity_signal, is_recall_positive};
    use khive_types::{EventKind, SubstrateKind};
    use uuid::Uuid;

    fn make_event(verb: &str, outcome: EventOutcome, target: Option<Uuid>) -> Event {
        let mut e = Event::new("test", verb, EventKind::Audit, SubstrateKind::Note, "brain");
        e.outcome = outcome;
        e.target_id = target;
        e
    }

    #[test]
    fn recall_success_with_target_is_hit() {
        let id = Uuid::new_v4();
        let e = make_event("recall", EventOutcome::Success, Some(id));
        match interpret(&e) {
            BrainSignal::RecallHit { target_id, .. } => assert_eq!(target_id, id),
            other => panic!("expected RecallHit, got {other:?}"),
        }
    }

    #[test]
    fn memory_recall_success_with_target_is_hit() {
        // Namespaced verb, as actually dispatched by the runtime's VerbRegistry
        // for `memory.recall` — see khive-runtime/src/pack.rs's dispatch hook.
        let id = Uuid::new_v4();
        let e = make_event("memory.recall", EventOutcome::Success, Some(id));
        match interpret(&e) {
            BrainSignal::RecallHit { target_id, .. } => assert_eq!(target_id, id),
            other => panic!("expected RecallHit, got {other:?}"),
        }
    }

    #[test]
    fn recall_success_without_target_is_miss() {
        let e = make_event("recall", EventOutcome::Success, None);
        assert!(matches!(interpret(&e), BrainSignal::RecallMiss));
    }

    #[test]
    fn recall_error_is_miss() {
        let e = make_event("recall", EventOutcome::Error, Some(Uuid::new_v4()));
        assert!(matches!(interpret(&e), BrainSignal::RecallMiss));
    }

    #[test]
    fn search_is_completed() {
        let e = make_event("search", EventOutcome::Success, None);
        assert!(matches!(interpret(&e), BrainSignal::SearchCompleted { .. }));
    }

    #[test]
    fn brain_feedback_with_useful_signal() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "useful"});
        match interpret(&e) {
            BrainSignal::Feedback {
                target_id,
                signal,
                served_by_profile_id,
                ..
            } => {
                assert_eq!(target_id, id);
                assert_eq!(signal, FeedbackSignal::Useful);
                assert!(served_by_profile_id.is_none());
            }
            other => panic!("expected Feedback, got {other:?}"),
        }
    }

    #[test]
    fn brain_feedback_with_served_by_profile_id() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({
            "signal": "not_useful",
            "served_by_profile_id": "balanced-recall-v1"
        });
        match interpret(&e) {
            BrainSignal::Feedback {
                target_id,
                signal,
                served_by_profile_id,
                ..
            } => {
                assert_eq!(target_id, id);
                assert_eq!(signal, FeedbackSignal::NotUseful);
                assert_eq!(served_by_profile_id.as_deref(), Some("balanced-recall-v1"));
            }
            other => panic!("expected Feedback, got {other:?}"),
        }
    }

    #[test]
    fn brain_feedback_with_resolution_marker_decodes_served_by() {
        // #1016: handle_feedback now always stamps the resolved profile plus a
        // `profile_resolution` marker. The marker is payload-only metadata —
        // the decoder must surface served_by_profile_id and ignore the marker.
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({
            "signal": "useful",
            "served_by_profile_id": "balanced-recall-v1",
            "profile_resolution": "default"
        });
        match interpret(&e) {
            BrainSignal::Feedback {
                target_id,
                served_by_profile_id,
                ..
            } => {
                assert_eq!(target_id, id);
                assert_eq!(served_by_profile_id.as_deref(), Some("balanced-recall-v1"));
            }
            other => panic!("expected Feedback, got {other:?}"),
        }
    }

    #[test]
    fn brain_feedback_without_target_is_irrelevant() {
        let e = make_event("brain.feedback", EventOutcome::Success, None);
        assert!(matches!(interpret(&e), BrainSignal::Irrelevant));
    }

    #[test]
    fn brain_emit_legacy_is_irrelevant() {
        // brain.emit predates brain.feedback; old log entries must not trigger feedback.
        let id = Uuid::new_v4();
        let mut e = make_event("brain.emit", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "useful"});
        assert!(matches!(interpret(&e), BrainSignal::Irrelevant));
    }

    #[test]
    fn unknown_verb_is_irrelevant() {
        let e = make_event("link", EventOutcome::Success, Some(Uuid::new_v4()));
        assert!(matches!(interpret(&e), BrainSignal::Irrelevant));
    }

    #[test]
    fn entity_signal_for_hit() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::RecallHit {
            target_id: id,
            latency_us: 100,
        };
        assert_eq!(entity_signal(&sig), Some((id, true)));
    }

    #[test]
    fn entity_signal_for_miss() {
        assert_eq!(entity_signal(&BrainSignal::RecallMiss), None);
    }

    #[test]
    fn recall_positive_classification() {
        let hit = BrainSignal::RecallHit {
            target_id: Uuid::new_v4(),
            latency_us: 0,
        };
        assert_eq!(is_recall_positive(&hit), Some(true));
        assert_eq!(is_recall_positive(&BrainSignal::RecallMiss), Some(false));
        assert_eq!(
            is_recall_positive(&BrainSignal::SearchCompleted { latency_us: 0 }),
            None
        );
    }

    #[test]
    fn feedback_not_useful_is_negative_entity_signal() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::Feedback {
            target_id: id,
            signal: FeedbackSignal::NotUseful,
            served_by_profile_id: None,
            section_signals: None,
        };
        assert_eq!(entity_signal(&sig), Some((id, false)));
    }

    #[test]
    fn feedback_wrong_is_negative_entity_signal() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::Feedback {
            target_id: id,
            signal: FeedbackSignal::Wrong,
            served_by_profile_id: None,
            section_signals: None,
        };
        assert_eq!(entity_signal(&sig), Some((id, false)));
    }

    #[test]
    fn brain_feedback_invalid_signal_data_is_irrelevant() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "bad_value"});
        assert!(matches!(interpret(&e), BrainSignal::Irrelevant));
    }

    #[test]
    fn note_accessed_via_get_verb_is_positive_entity_signal() {
        let id = Uuid::new_v4();
        let e = make_event("get", EventOutcome::Success, Some(id));
        match interpret(&e) {
            BrainSignal::NoteAccessed { target_id } => {
                assert_eq!(target_id, id);
                assert_eq!(
                    entity_signal(&BrainSignal::NoteAccessed { target_id }),
                    Some((id, true))
                );
            }
            other => panic!("expected NoteAccessed, got {other:?}"),
        }
    }

    #[test]
    fn note_accessed_via_remember_verb_is_positive_entity_signal() {
        let id = Uuid::new_v4();
        let e = make_event("remember", EventOutcome::Success, Some(id));
        match interpret(&e) {
            BrainSignal::NoteAccessed { target_id } => {
                assert_eq!(target_id, id);
            }
            other => panic!("expected NoteAccessed, got {other:?}"),
        }
    }

    #[test]
    fn feedback_with_section_signals() {
        use khive_brain_core::SectionType;
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({
            "signal": "useful",
            "section_signals": {
                "overview": "useful",
                "formalism": "not_useful",
                "examples": "wrong"
            }
        });
        match interpret(&e) {
            BrainSignal::Feedback {
                section_signals, ..
            } => {
                let ss = section_signals.expect("section_signals should be parsed");
                assert_eq!(ss.len(), 3);
                assert_eq!(ss[&SectionType::Overview], FeedbackSignal::Useful);
                assert_eq!(ss[&SectionType::Formalism], FeedbackSignal::NotUseful);
                assert_eq!(ss[&SectionType::Examples], FeedbackSignal::Wrong);
            }
            other => panic!("expected Feedback, got {other:?}"),
        }
    }

    // ── FeedbackEventKind unit tests (MAJ-001 coverage) ──────────────────────

    #[test]
    fn feedback_event_kind_from_signal_str_all_variants() {
        assert_eq!(
            FeedbackEventKind::from_signal_str("explicit_positive"),
            Some(FeedbackEventKind::ExplicitPositive)
        );
        assert_eq!(
            FeedbackEventKind::from_signal_str("explicit_negative"),
            Some(FeedbackEventKind::ExplicitNegative)
        );
        assert_eq!(
            FeedbackEventKind::from_signal_str("implicit_positive"),
            Some(FeedbackEventKind::ImplicitPositive)
        );
        assert_eq!(
            FeedbackEventKind::from_signal_str("implicit_negative"),
            Some(FeedbackEventKind::ImplicitNegative)
        );
        assert_eq!(
            FeedbackEventKind::from_signal_str("correction"),
            Some(FeedbackEventKind::Correction)
        );
    }

    #[test]
    fn feedback_event_kind_from_signal_str_unknown_returns_none() {
        assert_eq!(FeedbackEventKind::from_signal_str("useful"), None);
        assert_eq!(FeedbackEventKind::from_signal_str("not_useful"), None);
        assert_eq!(FeedbackEventKind::from_signal_str(""), None);
        assert_eq!(FeedbackEventKind::from_signal_str("ExplicitPositive"), None);
    }

    #[test]
    fn feedback_event_kind_update_weight_values() {
        assert!((FeedbackEventKind::Correction.update_weight() - 2.0).abs() < 1e-12);
        assert!((FeedbackEventKind::ExplicitPositive.update_weight() - 1.5).abs() < 1e-12);
        assert!((FeedbackEventKind::ExplicitNegative.update_weight() - 1.5).abs() < 1e-12);
        assert!((FeedbackEventKind::ImplicitPositive.update_weight() - 0.1).abs() < 1e-12);
        assert!((FeedbackEventKind::ImplicitNegative.update_weight() - 0.1).abs() < 1e-12);
    }

    #[test]
    fn feedback_event_kind_is_positive_classification() {
        assert!(FeedbackEventKind::ExplicitPositive.is_positive());
        assert!(FeedbackEventKind::ImplicitPositive.is_positive());
        assert!(!FeedbackEventKind::ExplicitNegative.is_positive());
        assert!(!FeedbackEventKind::ImplicitNegative.is_positive());
        assert!(!FeedbackEventKind::Correction.is_positive());
    }

    #[test]
    fn brain_feedback_semantic_explicit_positive_produces_semantic_signal() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "explicit_positive"});
        match interpret(&e) {
            BrainSignal::SemanticFeedback {
                target_id,
                event_kind,
                served_by_profile_id,
                effective_weight,
            } => {
                assert_eq!(target_id, id);
                assert_eq!(event_kind, FeedbackEventKind::ExplicitPositive);
                assert!(served_by_profile_id.is_none());
                assert!((effective_weight - 1.5).abs() < 1e-12);
            }
            other => panic!("expected SemanticFeedback, got {other:?}"),
        }
    }

    #[test]
    fn feedback_without_section_signals_is_none() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "useful"});
        match interpret(&e) {
            BrainSignal::Feedback {
                section_signals, ..
            } => {
                assert!(section_signals.is_none());
            }
            other => panic!("expected Feedback, got {other:?}"),
        }
    }

    #[test]
    fn brain_feedback_semantic_correction_produces_semantic_signal() {
        let id = Uuid::new_v4();
        let mut e = make_event("brain.feedback", EventOutcome::Success, Some(id));
        e.payload = serde_json::json!({"signal": "correction"});
        match interpret(&e) {
            BrainSignal::SemanticFeedback {
                target_id,
                event_kind,
                ..
            } => {
                assert_eq!(target_id, id);
                assert_eq!(event_kind, FeedbackEventKind::Correction);
            }
            other => panic!("expected SemanticFeedback, got {other:?}"),
        }
    }

    #[test]
    fn semantic_feedback_entity_signal_positive_for_explicit_positive() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::SemanticFeedback {
            target_id: id,
            event_kind: FeedbackEventKind::ExplicitPositive,
            served_by_profile_id: None,
            effective_weight: FeedbackEventKind::ExplicitPositive.update_weight(),
        };
        assert_eq!(entity_signal(&sig), Some((id, true)));
    }

    #[test]
    fn semantic_feedback_entity_signal_negative_for_implicit_negative() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::SemanticFeedback {
            target_id: id,
            event_kind: FeedbackEventKind::ImplicitNegative,
            served_by_profile_id: None,
            effective_weight: FeedbackEventKind::ImplicitNegative.update_weight(),
        };
        assert_eq!(entity_signal(&sig), Some((id, false)));
    }

    #[test]
    fn semantic_feedback_entity_signal_negative_for_correction() {
        let id = Uuid::new_v4();
        let sig = BrainSignal::SemanticFeedback {
            target_id: id,
            event_kind: FeedbackEventKind::Correction,
            served_by_profile_id: None,
            effective_weight: FeedbackEventKind::Correction.update_weight(),
        };
        assert_eq!(entity_signal(&sig), Some((id, false)));
    }
}