khive-pack-memory 0.5.0

Memory verb pack — remember/recall semantics with decay-aware ranking
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
//! Handler for `memory.feedback` — explicit recall-domain feedback.

use serde::Deserialize;
use serde_json::{json, Value};
use uuid::Uuid;

use khive_runtime::{NamespaceToken, RuntimeError, VerbRegistry};

use crate::recall_feedback::on_explicit_feedback;
use crate::MemoryPack;

#[derive(Debug, Deserialize)]
struct FeedbackParams {
    target_id: String,
    signal: String,
}

impl MemoryPack {
    /// Route validated feedback through explicit profile, bound profile, then global state.
    /// See `crates/khive-pack-memory/docs/api/memory-lifecycle.md`.
    pub(crate) async fn handle_feedback(
        &self,
        token: &NamespaceToken,
        params: Value,
        registry: &VerbRegistry,
    ) -> Result<Value, RuntimeError> {
        let p: FeedbackParams = serde_json::from_value(params).map_err(|e| {
            RuntimeError::InvalidInput(format!("memory.feedback: invalid params: {e}"))
        })?;
        validate_feedback_signal(&p.signal)?;

        let target_id = p.target_id.parse::<Uuid>().map_err(|_| {
            RuntimeError::InvalidInput(format!(
                "memory.feedback: target_id {:?} is not a valid UUID",
                p.target_id
            ))
        })?;

        // Tiers 1-2: explicit config profile, then namespace-bound profile via
        // brain.resolve(consumer_kind="recall") — shared with memory.recall's
        // serve-time stamp so the two resolution paths cannot drift apart.
        if let Some(profile_id) =
            super::common::resolve_serving_profile(&self.brain_profile, token, registry).await
        {
            return route_to_brain(registry, token, &p.target_id, &p.signal, &profile_id).await;
        }

        // Tier 3: global tuning prior (original behavior).
        if let Ok(mut state) = self.recall_state.lock() {
            on_explicit_feedback(&mut state, target_id, &p.signal);
        }

        Ok(json!({ "ok": true, "target_id": p.target_id, "signal": p.signal }))
    }
}

/// Reject unknown feedback before the low-level tier-three no-op can report success.
fn validate_feedback_signal(signal: &str) -> Result<(), RuntimeError> {
    let semantic = khive_brain_core::FeedbackEventKind::from_signal_str(signal).is_some();
    let legacy = serde_json::from_value::<khive_brain_core::FeedbackSignal>(json!(signal)).is_ok();
    if semantic || legacy {
        Ok(())
    } else {
        Err(RuntimeError::InvalidInput(format!(
            "memory.feedback: invalid signal {signal:?}; valid: useful | not_useful | wrong | \
             explicit_positive | explicit_negative | implicit_positive | implicit_negative | correction"
        )))
    }
}

/// Route feedback to a known profile, returning any brain-pack error unchanged.
async fn route_to_brain(
    registry: &VerbRegistry,
    token: &NamespaceToken,
    target_id: &str,
    signal: &str,
    profile_id: &str,
) -> Result<Value, RuntimeError> {
    // Include `namespace` so the registry mints the correct NamespaceToken for
    // the brain pack — the registry strips it before forwarding to the handler
    // since brain.feedback does not declare `namespace` as a param.
    let brain_params = json!({
        "namespace": token.namespace().as_str(),
        "target_id": target_id,
        "signal": signal,
        "served_by_profile_id": profile_id,
    });
    registry.dispatch("brain.feedback", brain_params).await
}

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

#[cfg(test)]
mod tests {
    use khive_pack_kg::KgPack;
    use khive_runtime::{Namespace, RuntimeConfig, RuntimeError, VerbRegistryBuilder};

    fn build_memory_rt(brain_profile: Option<String>) -> khive_runtime::KhiveRuntime {
        let tmp = tempfile::Builder::new()
            .prefix("khive-mem-feedback-")
            .tempdir_in(std::env::temp_dir())
            .expect("temp dir");
        let db_path = tmp.path().join("khive.db");
        std::mem::forget(tmp);

        khive_runtime::KhiveRuntime::new(RuntimeConfig {
            db_path: Some(db_path),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string(), "memory".to_string()],
            brain_profile,
            ..RuntimeConfig::default()
        })
        .expect("runtime")
    }

    /// Tier-3: when no brain pack is loaded and no profile is configured, feedback
    /// updates the global prior without error.
    #[tokio::test]
    async fn feedback_falls_through_to_global_prior() {
        let rt = build_memory_rt(None);
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "test feedback note",
                Some(0.7),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        let registry = builder.build().expect("registry");

        let result = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "useful",
                }),
            )
            .await;

        assert!(result.is_ok(), "feedback must not error: {:?}", result);
        let v = result.unwrap();
        assert_eq!(v["ok"], true);
        assert_eq!(v["signal"], "useful");
    }

    /// Tier-3: not_useful signal flows through global prior path correctly.
    #[tokio::test]
    async fn feedback_global_prior_not_useful() {
        let rt = build_memory_rt(None);
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "not useful note",
                Some(0.5),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        let registry = builder.build().expect("registry");

        let r = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "not_useful",
                }),
            )
            .await
            .expect("feedback ok");

        assert_eq!(r["ok"], true);
        assert_eq!(r["signal"], "not_useful");
    }

    /// Tier-3: an invalid signal string must be rejected before it reaches
    /// `on_explicit_feedback`, which otherwise silently no-ops and still
    /// returns `ok=true` (AUD-004).
    #[tokio::test]
    async fn feedback_tier3_invalid_signal_is_rejected() {
        let rt = build_memory_rt(None);
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "invalid signal note",
                Some(0.5),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        let memory_pack = crate::MemoryPack::new(rt.clone());

        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(memory_pack);
        let registry = builder.build().expect("registry");

        let result = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "bad_value",
                }),
            )
            .await;

        assert!(
            result.is_err(),
            "invalid signal must be rejected, got {:?}",
            result
        );
        assert!(matches!(result.unwrap_err(), RuntimeError::InvalidInput(_)));
    }

    /// Tier-1: explicit brain_profile config routes to brain.feedback (which errors
    /// if brain pack not loaded — that is the expected contract).
    #[tokio::test]
    async fn feedback_explicit_profile_routes_to_brain() {
        let rt = build_memory_rt(Some("balanced-recall-v1".to_string()));
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "profile routed note",
                Some(0.7),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        // No brain pack loaded → brain.feedback not found → error propagates.
        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        let registry = builder.build().expect("registry");

        let result = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "useful",
                }),
            )
            .await;

        // brain.feedback is not registered → should error (verb not found).
        assert!(
            result.is_err(),
            "explicit profile with no brain pack must error, got {:?}",
            result
        );
    }

    // ── Three-tier integration tests (kg + memory + brain all loaded) ──────────
    //
    // These tests verify that feedback resolution respects the full tier order.
    // Each test builds a registry with ALL THREE packs registered and inspects
    // `brain.profile` (total_events) to confirm which profile received credit.

    fn build_full_rt(brain_profile: Option<String>) -> khive_runtime::KhiveRuntime {
        let tmp = tempfile::Builder::new()
            .prefix("khive-mem-3tier-")
            .tempdir_in(std::env::temp_dir())
            .expect("temp dir");
        let db_path = tmp.path().join("khive.db");
        std::mem::forget(tmp);

        khive_runtime::KhiveRuntime::new(RuntimeConfig {
            db_path: Some(db_path),
            embedding_model: None,
            additional_embedding_models: vec![],
            packs: vec!["kg".to_string(), "memory".to_string(), "brain".to_string()],
            brain_profile,
            ..RuntimeConfig::default()
        })
        .expect("runtime")
    }

    /// Tier-1 wins over tier-2: when an explicit profile is configured AND a
    /// namespace binding exists for consumer_kind="recall", the explicit profile
    /// receives feedback — not the bound profile.
    #[tokio::test]
    async fn feedback_tier1_explicit_wins_over_bound_profile() {
        use khive_pack_brain::BrainPack;

        let rt = build_full_rt(Some("balanced-recall-v1".to_string()));
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "tier-1 wins note",
                Some(0.8),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        let brain = BrainPack::new(rt.clone());
        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        builder.register(brain);
        let registry = builder.build().expect("registry");

        // Create and activate a secondary profile to act as the "bound" tier-2 profile.
        registry
            .dispatch(
                "brain.create_profile",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "name": "alt-recall-v1",
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("create alt profile");

        registry
            .dispatch(
                "brain.activate",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "alt-recall-v1",
                }),
            )
            .await
            .expect("activate alt profile");

        // Bind alt-recall-v1 for consumer_kind="recall" in the local namespace.
        registry
            .dispatch(
                "brain.bind",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "alt-recall-v1",
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("bind alt profile");

        // Send feedback: tier-1 (explicit brain_profile = "balanced-recall-v1") must win.
        // brain.feedback returns {"emitted": true, ...} when routed through the brain pack.
        let r = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "useful",
                }),
            )
            .await
            .expect("feedback ok");
        assert_eq!(
            r["emitted"], true,
            "tier-1 feedback must route to brain pack: {r:?}"
        );

        // balanced-recall-v1 must have total_events == 1 (received the credit).
        let default_prof = registry
            .dispatch(
                "brain.profile",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "balanced-recall-v1",
                }),
            )
            .await
            .expect("brain.profile");
        assert_eq!(
            default_prof["total_events"].as_u64().unwrap_or(0),
            1,
            "tier-1: balanced-recall-v1 must receive the feedback event"
        );

        // alt-recall-v1 must have total_events == 0 (was NOT credited despite binding).
        let alt_prof = registry
            .dispatch(
                "brain.profile",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "alt-recall-v1",
                }),
            )
            .await
            .expect("brain.profile alt");
        assert_eq!(
            alt_prof["total_events"].as_u64().unwrap_or(0),
            0,
            "tier-1 wins: alt-recall-v1 must NOT receive any events when tier-1 is active"
        );
    }

    /// Tier-2 namespace binding: when no explicit profile is configured but a
    /// namespace binding for consumer_kind="recall" exists, that bound profile
    /// receives feedback.
    ///
    /// This test FAILS before the consumer_kind fix ("memory.recall" → "recall")
    /// and PASSES after it.
    #[tokio::test]
    async fn feedback_tier2_namespace_bound_profile_credited() {
        use khive_pack_brain::BrainPack;

        // No explicit brain_profile — tier-2 must kick in.
        let rt = build_full_rt(None);
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "tier-2 binding note",
                Some(0.7),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        let brain = BrainPack::new(rt.clone());
        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        builder.register(brain);
        let registry = builder.build().expect("registry");

        // Create a secondary profile and activate it.
        registry
            .dispatch(
                "brain.create_profile",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "name": "ns-bound-recall",
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("create ns-bound profile");

        registry
            .dispatch(
                "brain.activate",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "ns-bound-recall",
                }),
            )
            .await
            .expect("activate ns-bound profile");

        // Bind ns-bound-recall to the "local" namespace for consumer_kind="recall".
        // resolve_consumer_profile calls brain.resolve(namespace="local", consumer_kind="recall"),
        // which must match this binding when the consumer_kind fix is in place.
        registry
            .dispatch(
                "brain.bind",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "ns-bound-recall",
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("bind ns-bound profile");

        // Verify brain.resolve agrees with the expected binding before calling feedback.
        let resolve_result = registry
            .dispatch(
                "brain.resolve",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("brain.resolve");
        assert_eq!(
            resolve_result["resolved_profile_id"],
            serde_json::json!("ns-bound-recall"),
            "brain.resolve must return the namespace-bound profile for consumer_kind=recall"
        );

        // Send feedback — tier-2 must route to ns-bound-recall.
        // brain.feedback returns {"emitted": true, ...} when routed through the brain pack.
        let r = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "useful",
                }),
            )
            .await
            .expect("feedback ok");
        assert_eq!(
            r["emitted"], true,
            "tier-2 feedback must route to brain pack: {r:?}"
        );

        // ns-bound-recall must have total_events == 1.
        let bound_prof = registry
            .dispatch(
                "brain.profile",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "profile_id": "ns-bound-recall",
                }),
            )
            .await
            .expect("brain.profile ns-bound");
        assert_eq!(
            bound_prof["total_events"].as_u64().unwrap_or(0),
            1,
            "tier-2: namespace-bound profile ns-bound-recall must receive the feedback event"
        );
    }

    /// Tier-3 global fallback: when no explicit profile is configured and no explicit
    /// namespace binding exists, feedback falls through to the pack-local global
    /// tuning prior — even when the brain pack is loaded and balanced-recall-v1 is active.
    ///
    /// Before the matched_binding fix, resolve_consumer_profile treated the system-default
    /// fallback (balanced-recall-v1 active, no binding rows) as a tier-2 hit. This test
    /// verifies that the deactivation workaround is no longer needed: tier-3 fires in
    /// the normal case (brain loaded, no explicit binding).
    #[tokio::test]
    async fn feedback_tier3_global_fallback_with_brain_loaded() {
        use khive_pack_brain::BrainPack;

        // No explicit brain_profile configured.
        let rt = build_full_rt(None);
        let ns = Namespace::parse("local").expect("ns");
        let token = rt.authorize(ns.clone()).expect("token");

        let note_id = rt
            .create_note_with_decay_for_embedding_model(
                &token,
                "memory",
                None,
                "tier-3 global fallback note",
                Some(0.6),
                0.01,
                None,
                vec![],
                None,
            )
            .await
            .expect("create note");

        // Load brain pack but do NOT create any explicit bindings.
        // brain.resolve returns balanced-recall-v1 as system-default (matched_binding=false).
        // With the fix, resolve_consumer_profile returns None for matched_binding=false,
        // so tier-2 is skipped and tier-3 fires WITHOUT needing to deactivate the default profile.
        let brain = BrainPack::new(rt.clone());
        let mut builder = VerbRegistryBuilder::new();
        builder.register(KgPack::new(rt.clone()));
        builder.register(crate::MemoryPack::new(rt.clone()));
        builder.register(brain);
        let registry = builder.build().expect("registry");

        // Confirm brain.resolve returns a system-default (matched_binding=false) — no explicit binding.
        let resolve_result = registry
            .dispatch(
                "brain.resolve",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "consumer_kind": "recall",
                }),
            )
            .await
            .expect("brain.resolve should succeed");
        assert_eq!(
            resolve_result["matched_binding"], false,
            "no explicit binding exists: matched_binding must be false (system default)"
        );

        // Tier-3: feedback must succeed and echo the signal back (ok=true, signal echoed).
        // balanced-recall-v1 is still Active, but tier-2 is skipped due to matched_binding=false.
        let r = registry
            .dispatch(
                "memory.feedback",
                serde_json::json!({
                    "namespace": ns.as_str(),
                    "target_id": note_id.id.to_string(),
                    "signal": "not_useful",
                }),
            )
            .await
            .expect("tier-3 feedback must not error");

        assert_eq!(
            r["ok"], true,
            "tier-3 global path must return ok=true: {r:?}"
        );
        assert_eq!(
            r["signal"], "not_useful",
            "tier-3 path must echo the signal: {r:?}"
        );
        // No brain_profile key in the response (tier-3 does not route to brain).
        assert!(
            r.get("emitted").is_none(),
            "tier-3 path must not produce an emitted key: {r:?}"
        );
    }
}