khive-runtime 0.2.8

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
//! Integration tests for khive-runtime.
//!
//! Tests cover entity CRUD, graph operations, note memory, GQL query,
//! and namespace isolation using an in-memory runtime.

use khive_runtime::{KhiveRuntime, Namespace, RuntimeConfig};
use khive_storage::types::{Direction, TraversalOptions, TraversalRequest};
use khive_storage::{EdgeRelation, Event};
use khive_types::{EventKind, SubstrateKind};
use uuid::Uuid;

fn rt() -> KhiveRuntime {
    KhiveRuntime::memory().expect("in-memory runtime")
}

// =============================================================================
// Entity operations
// =============================================================================

#[tokio::test]
async fn entity_create_and_get_roundtrip() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let entity = rt
        .create_entity(
            &tok,
            "concept",
            None,
            "LoRA",
            Some("Low-Rank Adaptation"),
            None,
            vec![],
        )
        .await
        .unwrap();

    let fetched = rt.get_entity(&tok, entity.id).await.unwrap();
    assert_eq!(fetched.id, entity.id);
    assert_eq!(fetched.name, "LoRA");
    assert_eq!(fetched.kind, "concept");
    assert_eq!(fetched.description.as_deref(), Some("Low-Rank Adaptation"));
}

#[tokio::test]
async fn entity_create_with_properties_and_tags() {
    let rt = rt();
    let research_tok = rt.authorize(Namespace::parse("research").unwrap()).unwrap();

    let props = serde_json::json!({"domain": "fine-tuning", "type": "technique"});
    let entity = rt
        .create_entity(
            &research_tok,
            "concept",
            None,
            "QLoRA",
            Some("Quantized LoRA"),
            Some(props.clone()),
            vec!["fine-tuning".to_string(), "quantization".to_string()],
        )
        .await
        .unwrap();

    let fetched = rt.get_entity(&research_tok, entity.id).await.unwrap();
    assert_eq!(fetched.properties, Some(props));
    assert_eq!(fetched.tags, vec!["fine-tuning", "quantization"]);
}

#[tokio::test]
async fn entity_list_by_kind() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    rt.create_entity(&tok, "concept", None, "FlashAttention", None, None, vec![])
        .await
        .unwrap();
    rt.create_entity(&tok, "concept", None, "GQA", None, None, vec![])
        .await
        .unwrap();
    rt.create_entity(
        &tok,
        "document",
        None,
        "Attention Is All You Need",
        None,
        None,
        vec![],
    )
    .await
    .unwrap();

    let concepts = rt
        .list_entities(&tok, Some("concept"), None, 50, 0)
        .await
        .unwrap();
    assert_eq!(concepts.len(), 2);
    assert!(concepts.iter().any(|e| e.name == "FlashAttention"));
    assert!(concepts.iter().any(|e| e.name == "GQA"));

    let docs = rt
        .list_entities(&tok, Some("document"), None, 50, 0)
        .await
        .unwrap();
    assert_eq!(docs.len(), 1);
    assert_eq!(docs[0].name, "Attention Is All You Need");

    let all = rt.list_entities(&tok, None, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 3);
}

#[tokio::test]
async fn entity_delete_soft() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let entity = rt
        .create_entity(&tok, "concept", None, "to-delete", None, None, vec![])
        .await
        .unwrap();

    let deleted = rt.delete_entity(&tok, entity.id, false).await.unwrap();
    assert!(deleted);

    // Soft-deleted entity is not found via get_entity
    let fetched = rt.get_entity(&tok, entity.id).await;
    assert!(fetched.is_err());
}

#[tokio::test]
async fn entity_count_by_kind() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    for _ in 0..3 {
        rt.create_entity(&tok, "concept", None, "concept-X", None, None, vec![])
            .await
            .unwrap();
    }
    for _ in 0..2 {
        rt.create_entity(&tok, "document", None, "doc-Y", None, None, vec![])
            .await
            .unwrap();
    }

    let concept_count = rt.count_entities(&tok, Some("concept")).await.unwrap();
    let doc_count = rt.count_entities(&tok, Some("document")).await.unwrap();
    let total = rt.count_entities(&tok, None).await.unwrap();

    assert_eq!(concept_count, 3);
    assert_eq!(doc_count, 2);
    assert_eq!(total, 5);
}

// =============================================================================
// Graph operations
// =============================================================================

#[tokio::test]
async fn link_and_neighbors() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let lora = rt
        .create_entity(&tok, "concept", None, "LoRA", None, None, vec![])
        .await
        .unwrap();
    let qlora = rt
        .create_entity(&tok, "concept", None, "QLoRA", None, None, vec![])
        .await
        .unwrap();

    rt.link(&tok, qlora.id, lora.id, EdgeRelation::VariantOf, 1.0, None)
        .await
        .unwrap();

    let hits = rt
        .neighbors(&tok, qlora.id, Direction::Out, None, None)
        .await
        .unwrap();
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].node_id, lora.id);
    assert_eq!(hits[0].relation, EdgeRelation::VariantOf);
}

#[tokio::test]
async fn traverse_multi_hop() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity(&tok, "concept", None, "A", None, None, vec![])
        .await
        .unwrap();
    let b = rt
        .create_entity(&tok, "concept", None, "B", None, None, vec![])
        .await
        .unwrap();
    let c = rt
        .create_entity(&tok, "concept", None, "C", None, None, vec![])
        .await
        .unwrap();

    rt.link(&tok, a.id, b.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();
    rt.link(&tok, b.id, c.id, EdgeRelation::Extends, 1.0, None)
        .await
        .unwrap();

    let request = TraversalRequest {
        roots: vec![a.id],
        options: TraversalOptions {
            max_depth: 2,
            direction: Direction::Out,
            relations: Some(vec![EdgeRelation::Extends]),
            ..Default::default()
        },
        include_roots: false,
    };

    let paths = rt.traverse(&tok, request).await.unwrap();
    assert!(!paths.is_empty());

    // All traversed nodes should be reachable from a
    let reachable_ids: Vec<Uuid> = paths
        .iter()
        .flat_map(|p| p.nodes.iter().map(|n| n.node_id))
        .collect();
    assert!(reachable_ids.contains(&b.id));
    assert!(reachable_ids.contains(&c.id));
}

// =============================================================================
// Note (memory) operations
// =============================================================================

#[tokio::test]
async fn create_note_and_list_notes() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    rt.create_note(
        &tok,
        "observation",
        None,
        "LoRA is a fine-tuning technique",
        Some(0.9),
        None,
        vec![],
    )
    .await
    .unwrap();
    rt.create_note(
        &tok,
        "observation",
        None,
        "QLoRA uses quantization",
        Some(0.8),
        None,
        vec![],
    )
    .await
    .unwrap();
    rt.create_note(
        &tok,
        "question",
        None,
        "Review LoRA paper",
        Some(0.7),
        None,
        vec![],
    )
    .await
    .unwrap();

    let observations = rt
        .list_notes(&tok, Some("observation"), 50, 0)
        .await
        .unwrap();
    assert_eq!(observations.len(), 2);

    let questions = rt.list_notes(&tok, Some("question"), 50, 0).await.unwrap();
    assert_eq!(questions.len(), 1);
    assert_eq!(questions[0].content, "Review LoRA paper");

    let all = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 3);
}

#[tokio::test]
async fn create_all_note_kinds() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    for kind in [
        "observation",
        "insight",
        "question",
        "decision",
        "reference",
    ] {
        rt.create_note(&tok, kind, None, "content", Some(0.5), None, vec![])
            .await
            .unwrap();
    }
    let all = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert_eq!(all.len(), 5);
}

// =============================================================================
// GQL query
// =============================================================================

#[tokio::test]
async fn query_via_gql() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    // Set up entities and edges
    let lora = rt
        .create_entity(&tok, "concept", None, "LoRA", None, None, vec![])
        .await
        .unwrap();
    let qlora = rt
        .create_entity(&tok, "concept", None, "QLoRA", None, None, vec![])
        .await
        .unwrap();
    rt.link(&tok, qlora.id, lora.id, EdgeRelation::VariantOf, 1.0, None)
        .await
        .unwrap();

    // Run a GQL traversal query
    let rows = rt
        .query(
            &tok,
            "MATCH (a:concept)-[e:variant_of]->(b:concept) RETURN a, e, b LIMIT 10",
        )
        .await
        .unwrap();

    assert_eq!(rows.len(), 1);
    // Verify row contains the expected column names
    let first_row = &rows[0];
    assert!(first_row.get("a_name").is_some() || first_row.get("a_kind").is_some());
}

// =============================================================================
// Namespace isolation
// =============================================================================

#[tokio::test]
async fn namespace_isolation() {
    let rt = rt();
    let ns_a_tok = rt.authorize(Namespace::parse("ns-a").unwrap()).unwrap();
    let ns_b_tok = rt.authorize(Namespace::parse("ns-b").unwrap()).unwrap();

    rt.create_entity(&ns_a_tok, "concept", None, "EntityA", None, None, vec![])
        .await
        .unwrap();
    rt.create_entity(&ns_b_tok, "concept", None, "EntityB", None, None, vec![])
        .await
        .unwrap();

    let a_entities = rt
        .list_entities(&ns_a_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(a_entities.len(), 1);
    assert_eq!(a_entities[0].name, "EntityA");

    let b_entities = rt
        .list_entities(&ns_b_tok, None, None, 50, 0)
        .await
        .unwrap();
    assert_eq!(b_entities.len(), 1);
    assert_eq!(b_entities[0].name, "EntityB");
}

// =============================================================================
// Hybrid search indexing
// =============================================================================

#[tokio::test]
async fn create_entity_indexes_into_text_search() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity(
            &tok,
            "concept",
            None,
            "FlashAttention",
            Some("efficient attention mechanism"),
            None,
            vec![],
        )
        .await
        .unwrap();
    let hits = rt
        .hybrid_search(&tok, "FlashAttention", None, 10, None, None)
        .await
        .unwrap();
    assert!(
        hits.iter().any(|h| h.entity_id == entity.id),
        "newly created entity should be findable via hybrid_search (text path)"
    );
}

#[tokio::test]
async fn create_entity_no_embedding_model_does_not_propagate_vector_error() {
    // KhiveRuntime::memory() has embedding_model: None — vector indexing is silently skipped.
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let result = rt
        .create_entity(
            &tok,
            "concept",
            None,
            "SilentVectorSkip",
            None,
            None,
            vec![],
        )
        .await;
    assert!(
        result.is_ok(),
        "create_entity must not propagate Unconfigured from vector store"
    );
}

// =============================================================================
// Soft-delete visibility
// =============================================================================

/// Soft-deleted entities must not appear in hybrid_search results.
#[tokio::test]
async fn hybrid_search_excludes_soft_deleted_entities() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity(
            &tok,
            "concept",
            None,
            "SoftDeleteMe",
            Some("entity that will be soft-deleted"),
            None,
            vec![],
        )
        .await
        .unwrap();

    // Confirm the entity is visible before deletion.
    let hits_before = rt
        .hybrid_search(&tok, "SoftDeleteMe", None, 10, None, None)
        .await
        .unwrap();
    assert!(
        hits_before.iter().any(|h| h.entity_id == entity.id),
        "entity should appear in hybrid_search before soft-delete"
    );

    rt.delete_entity(&tok, entity.id, false).await.unwrap(); // soft delete

    let hits_after = rt
        .hybrid_search(&tok, "SoftDeleteMe", None, 10, None, None)
        .await
        .unwrap();
    assert!(
        !hits_after.iter().any(|h| h.entity_id == entity.id),
        "soft-deleted entity must not appear in hybrid_search"
    );
}

/// Hard-deleted entities are gone from storage entirely and never appear in hybrid_search.
#[tokio::test]
async fn hybrid_search_excludes_hard_deleted_entities() {
    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let entity = rt
        .create_entity(
            &tok,
            "concept",
            None,
            "HardDeleteMe",
            Some("entity that will be hard-deleted"),
            None,
            vec![],
        )
        .await
        .unwrap();

    let hits_before = rt
        .hybrid_search(&tok, "HardDeleteMe", None, 10, None, None)
        .await
        .unwrap();
    assert!(
        hits_before.iter().any(|h| h.entity_id == entity.id),
        "entity should appear in hybrid_search before hard-delete"
    );

    rt.delete_entity(&tok, entity.id, true).await.unwrap(); // hard delete

    // Hard-deleted rows are gone from the entity store; the FTS/vector indexes may still
    // have stale entries. The soft-delete filter sees no alive entity and drops the hit.
    let hits_after = rt
        .hybrid_search(&tok, "HardDeleteMe", None, 10, None, None)
        .await
        .unwrap();
    assert!(
        !hits_after.iter().any(|h| h.entity_id == entity.id),
        "hard-deleted entity must not appear in hybrid_search"
    );
}

/// Soft-deleted notes must not appear in list_notes results.
#[tokio::test]
async fn list_notes_excludes_soft_deleted() {
    use khive_storage::types::DeleteMode;

    let rt = KhiveRuntime::memory().expect("in-memory runtime");
    let tok = rt.authorize(Namespace::local()).unwrap();
    let note = rt
        .create_note(
            &tok,
            "observation",
            None,
            "soft-delete-test",
            Some(0.9),
            None,
            vec![],
        )
        .await
        .unwrap();

    let notes_before = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert!(
        notes_before.iter().any(|n| n.id == note.id),
        "note should appear before soft-delete"
    );

    rt.notes(&tok)
        .unwrap()
        .delete_note(note.id, DeleteMode::Soft)
        .await
        .unwrap();

    let notes_after = rt.list_notes(&tok, None, 50, 0).await.unwrap();
    assert!(
        !notes_after.iter().any(|n| n.id == note.id),
        "soft-deleted note must not appear in list"
    );
}

// =============================================================================
// File-backed runtime
// =============================================================================

#[tokio::test]
async fn file_backed_runtime_persists() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("persist.db");

    {
        let config = RuntimeConfig {
            db_path: Some(path.clone()),
            default_namespace: Namespace::local(),
            embedding_model: None,
            gate: std::sync::Arc::new(khive_runtime::AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            additional_embedding_models: vec![],
        };
        let rt = KhiveRuntime::new(config).unwrap();
        let tok = rt.authorize(Namespace::local()).unwrap();
        rt.create_entity(&tok, "concept", None, "Persistent", None, None, vec![])
            .await
            .unwrap();
    }

    // Re-open the same file
    {
        let config = RuntimeConfig {
            db_path: Some(path.clone()),
            default_namespace: Namespace::local(),
            embedding_model: None,
            gate: std::sync::Arc::new(khive_runtime::AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            additional_embedding_models: vec![],
        };
        let rt = KhiveRuntime::new(config).unwrap();
        let tok = rt.authorize(Namespace::local()).unwrap();
        let entities = rt.list_entities(&tok, None, None, 50, 0).await.unwrap();
        assert_eq!(entities.len(), 1);
        assert_eq!(entities[0].name, "Persistent");
    }
}

// =============================================================================
// F218 integration: synthetic observed_as_* edge end-to-end (CRIT-1 regression)
// =============================================================================

/// This test is the ONLY test that would have caught CRIT-1 (wrong JOIN target).
///
/// It seeds a real event + event_observations row and executes the canonical
/// ADR-041 §11 synthetic-edge GQL query end-to-end against an in-memory SQLite
/// database.  The old code joined `event_observations.event_id = entities.id`,
/// which can never match because the two ID spaces are disjoint.
#[tokio::test]
async fn synthetic_edge_observed_as_selected_returns_memory_note() {
    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();
    let ns = "local";

    // Step 1: create a memory note (the observed entity).
    let memory_note = rt
        .create_note(
            &tok,
            "memory",
            None,
            "recalled memory content",
            Some(0.9),
            None,
            vec![],
        )
        .await
        .unwrap();
    let memory_id = memory_note.id;

    // Step 2: create an event of kind RerankExecuted with a payload that
    // includes `selected: [memory_id]`.  The storage layer's `append_event`
    // implementation calls `decode_rank_observations`, which reads
    // `payload["selected"]` and inserts a row into `event_observations` with
    // role="selected" and entity_id=memory_id.
    let event_store = rt.events(&tok).unwrap();
    let mut event = Event::new(
        ns,
        "rerank",
        EventKind::RerankExecuted,
        SubstrateKind::Note,
        "agent:test",
    );
    event.payload = serde_json::json!({
        "candidates": [],
        "selected": [memory_id.to_string()]
    });
    event_store.append_event(event).await.unwrap();

    // Step 3: execute the canonical ADR-041 §11 GQL query.
    // Before CRIT-1 fix: `FROM entities n0 JOIN event_observations e0 ON e0.event_id = n0.id`
    //   — IDs are disjoint, so zero rows returned.
    // After fix: `FROM events n0 JOIN event_observations e0 ON e0.event_id = n0.id`
    //   — correct join; the memory note is returned.
    let rows = rt
        .query(
            &tok,
            "MATCH (ev)-[:observed_as_selected]->(m:memory) RETURN m",
        )
        .await
        .unwrap();

    assert!(
        !rows.is_empty(),
        "CRIT-1: synthetic edge query must return at least one row (memory note was seeded); \
         got 0 rows — event_observations join is broken"
    );

    // Verify the returned row contains our memory note's UUID.
    let memory_id_str = memory_id.to_string();
    let found = rows.iter().any(|row| {
        row.columns.iter().any(|col| {
            if let khive_storage::types::SqlValue::Text(s) = &col.value {
                s.contains(&memory_id_str)
            } else {
                false
            }
        })
    });
    assert!(
        found,
        "CRIT-1: returned rows must include the seeded memory note id {}; columns: {:?}",
        memory_id,
        rows.iter()
            .map(|r| r
                .columns
                .iter()
                .map(|c| (&c.name, &c.value))
                .collect::<Vec<_>>())
            .collect::<Vec<_>>()
    );
}

// =============================================================================
// update_edge conflict handling regression tests (codex round-3 H1)
// =============================================================================

/// Regression for Bug 1: when update_edge absorbs a conflict (the requested edge
/// is deleted and the existing canonical row is refreshed), the returned edge must
/// carry the SURVIVING canonical row's id — not the id of the deleted edge.
///
/// Setup: pre-create canonical A→B competes_with (E1), create A→B extends (E2).
/// Update E2's relation to competes_with. The returned id must be E1, not E2.
/// A subsequent get(returned_id) must succeed.
#[tokio::test]
async fn update_edge_returns_surviving_canonical_id_on_conflict() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity(&tok, "concept", None, "SurvA", None, None, vec![])
        .await
        .unwrap();
    let b = rt
        .create_entity(&tok, "concept", None, "SurvB", None, None, vec![])
        .await
        .unwrap();

    // E1: canonical competes_with between A and B (runtime canonicalises order).
    let e1 = rt
        .link(&tok, a.id, b.id, EdgeRelation::CompetesWith, 1.0, None)
        .await
        .unwrap();

    // E2: non-symmetric extends edge, using the higher-uuid as source so that
    // updating to competes_with will trigger a flip (endpoints_flipped=true path).
    let (src, tgt) = if a.id > b.id {
        (a.id, b.id)
    } else {
        (b.id, a.id)
    };
    let e2 = rt
        .link(&tok, src, tgt, EdgeRelation::Extends, 0.5, None)
        .await
        .unwrap();

    // E1 and E2 must be different edges.
    assert_ne!(
        e1.id, e2.id,
        "pre-condition: E1 and E2 must be distinct edges"
    );

    // Update E2 to competes_with → conflict with E1 must be absorbed.
    let returned = rt
        .update_edge(
            &tok,
            e2.id.into(),
            EdgePatch {
                relation: Some(EdgeRelation::CompetesWith),
                weight: Some(0.9),
                ..Default::default()
            },
        )
        .await
        .expect("update_edge must succeed even when conflict is absorbed");

    // Bug 1 assertion: returned id must be E1 (surviving canonical row), not E2 (deleted).
    assert_eq!(
        returned.id, e1.id,
        "Bug 1: update_edge must return the SURVIVING canonical row id (E1={:?}), \
         got E2={:?}",
        e1.id, returned.id
    );

    // get(returned.id) must succeed — it must not 404.
    let fetched = rt
        .get_edge(&tok, returned.id.into())
        .await
        .expect("get_edge on returned id must not error")
        .expect("get_edge on returned id must find a row (not 404)");
    assert_eq!(
        fetched.id, e1.id,
        "fetched row id must match E1 (surviving canonical)"
    );

    // E2 must no longer exist.
    let e2_lookup = rt
        .get_edge(&tok, e2.id.into())
        .await
        .expect("get_edge on deleted id must not error");
    assert!(
        e2_lookup.is_none(),
        "Bug 1: deleted edge E2 must not be findable after conflict absorption"
    );
}

/// Regression for Bug 2: when an edge's relation is updated to a symmetric relation
/// and the endpoints are ALREADY in canonical order (endpoints_flipped=false),
/// a pre-existing canonical row with the same natural key must still be detected and
/// absorbed — no UNIQUE-constraint error, no duplicate row.
///
/// Setup: ensure A < B (canonical order). Pre-create canonical A→B competes_with (E1).
/// Create A→B extends (E2, already canonical since A < B and extends is non-symmetric).
/// Update E2's relation to competes_with (endpoints_flipped=false because A < B).
/// Assert: exactly one live competes_with edge remains between A and B.
#[tokio::test]
async fn update_edge_canonical_orientation_conflict() {
    use khive_runtime::EdgePatch;

    let rt = rt();
    let tok = rt.authorize(Namespace::local()).unwrap();

    let a = rt
        .create_entity(&tok, "concept", None, "CanOrA", None, None, vec![])
        .await
        .unwrap();
    let b = rt
        .create_entity(&tok, "concept", None, "CanOrB", None, None, vec![])
        .await
        .unwrap();

    // Determine canonical order: canon_lo < canon_hi.
    let (canon_lo, canon_hi) = if a.id < b.id {
        (a.id, b.id)
    } else {
        (b.id, a.id)
    };

    // E1: canonical competes_with (lower → higher, which is canonical).
    let e1 = rt
        .link(
            &tok,
            canon_lo,
            canon_hi,
            EdgeRelation::CompetesWith,
            1.0,
            None,
        )
        .await
        .unwrap();

    // E2: extends in the same canonical direction (lower → higher).
    // endpoints_flipped will be false when we update to competes_with.
    let e2 = rt
        .link(&tok, canon_lo, canon_hi, EdgeRelation::Extends, 0.5, None)
        .await
        .unwrap();

    assert_ne!(
        e1.id, e2.id,
        "pre-condition: E1 and E2 must be distinct edges"
    );

    // Update E2's relation to competes_with — must not produce UNIQUE-constraint error.
    // Bug 2: the non-flipped path used to call upsert_edge which only checked ON CONFLICT(id),
    // missing the natural-key duplicate with a different id.
    rt.update_edge(
        &tok,
        e2.id.into(),
        EdgePatch {
            relation: Some(EdgeRelation::CompetesWith),
            ..Default::default()
        },
    )
    .await
    .expect("Bug 2: update_edge on canonical-orientation conflict must not error");

    // Verify exactly one live competes_with edge exists between canon_lo and canon_hi.
    let edges = rt
        .list_edges(
            &tok,
            khive_runtime::EdgeListFilter {
                source_id: Some(canon_lo),
                target_id: Some(canon_hi),
                relations: vec![EdgeRelation::CompetesWith],
                ..Default::default()
            },
            100,
        )
        .await
        .expect("list_edges must succeed");

    assert_eq!(
        edges.len(),
        1,
        "Bug 2: exactly one competes_with edge must exist after non-flipped conflict absorption; \
         found {} edges: {edges:?}",
        edges.len()
    );
}

// =============================================================================
// EmbedderRegistry integration tests (#397)
// =============================================================================

mod embedder_registry_tests {
    use async_trait::async_trait;
    use khive_gate::AllowAllGate;
    use khive_runtime::{EmbedderProvider, KhiveRuntime, RuntimeConfig, RuntimeError};
    use khive_types::Namespace;
    use lattice_embed::{EmbeddingModel, EmbeddingService};
    use std::sync::Arc;

    // ── MockEmbedderProvider ─────────────────────────────────────────────────

    /// A synthetic embedding provider that returns a fixed vector of `42.0` values.
    ///
    /// Used to verify that custom providers are reachable via
    /// `KhiveRuntime::embedder` after registration.
    struct MockEmbedderProvider {
        name: String,
        dims: usize,
    }

    impl MockEmbedderProvider {
        fn new(name: &str, dims: usize) -> Self {
            Self {
                name: name.to_owned(),
                dims,
            }
        }
    }

    struct MockEmbeddingService {
        dims: usize,
    }

    #[async_trait]
    impl EmbeddingService for MockEmbeddingService {
        async fn embed(
            &self,
            texts: &[String],
            _model: EmbeddingModel,
        ) -> Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
            Ok(texts.iter().map(|_| vec![42.0_f32; self.dims]).collect())
        }

        fn supports_model(&self, _model: EmbeddingModel) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            "mock-embedding-service"
        }
    }

    #[async_trait]
    impl EmbedderProvider for MockEmbedderProvider {
        fn name(&self) -> &str {
            &self.name
        }

        fn dimensions(&self) -> usize {
            self.dims
        }

        async fn build(&self) -> Result<Arc<dyn EmbeddingService>, RuntimeError> {
            Ok(Arc::new(MockEmbeddingService { dims: self.dims }))
        }
    }

    fn memory_rt_no_model() -> KhiveRuntime {
        KhiveRuntime::new(RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: None,
            additional_embedding_models: vec![],
            gate: Arc::new(AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
        })
        .expect("in-memory runtime")
    }

    // ── Test: register + embedder round-trip ─────────────────────────────────

    #[tokio::test]
    async fn register_embedder_and_retrieve_via_embedder_method() {
        let rt = memory_rt_no_model();
        rt.register_embedder(MockEmbedderProvider::new("mock", 384));

        let service = rt
            .embedder("mock")
            .await
            .expect("embedder lookup must succeed after registration");

        let texts = vec!["hello world".to_string()];
        let vecs = service
            .embed(&texts, EmbeddingModel::AllMiniLmL6V2)
            .await
            .expect("mock service must embed successfully");

        assert_eq!(vecs.len(), 1);
        assert_eq!(vecs[0].len(), 384);
        assert!(
            vecs[0].iter().all(|&v| (v - 42.0_f32).abs() < 1e-6),
            "mock service must return constant 42.0 vector"
        );
    }

    // ── Test: registered names include custom provider ────────────────────────

    #[tokio::test]
    async fn registered_names_includes_custom_provider() {
        let rt = memory_rt_no_model();
        rt.register_embedder(MockEmbedderProvider::new("my-encoder", 128));

        let names = rt.registered_embedding_model_names();
        assert!(
            names.contains(&"my-encoder".to_string()),
            "registered_embedding_model_names must include custom provider 'my-encoder'; got {names:?}"
        );
    }

    // ── Test: dual-embedding regression — both MiniLM and paraphrase reachable ─

    #[tokio::test]
    async fn dual_embedding_regression_both_models_registered() {
        use khive_runtime::RuntimeConfig;
        let rt = KhiveRuntime::new(RuntimeConfig {
            db_path: None,
            default_namespace: Namespace::local(),
            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2],
            gate: Arc::new(AllowAllGate),
            packs: vec!["kg".to_string()],
            backend_id: khive_runtime::BackendId::main(),
        })
        .expect("runtime with two models");

        let names = rt.registered_embedding_model_names();

        assert!(
            names.contains(&"all-minilm-l6-v2".to_string()),
            "MiniLM must be registered; names: {names:?}"
        );
        assert!(
            names.contains(&"paraphrase-multilingual-minilm-l12-v2".to_string()),
            "paraphrase must be registered; names: {names:?}"
        );

        // Verify resolve_embedding_model works for both.
        rt.resolve_embedding_model(Some("all-minilm-l6-v2"))
            .expect("MiniLM must resolve");
        rt.resolve_embedding_model(Some("paraphrase"))
            .expect("paraphrase alias must resolve");
    }

    // ── Test: unknown embedder returns UnknownModel ───────────────────────────

    #[tokio::test]
    async fn embedder_unknown_name_returns_error() {
        let rt = memory_rt_no_model();
        let err = rt
            .embedder("no-such-model")
            .await
            .err()
            .expect("expected Err for unknown embedder name, got Ok");
        assert!(
            matches!(err, RuntimeError::UnknownModel(ref n) if n == "no-such-model"),
            "expected UnknownModel for unregistered name; got {err:?}"
        );
    }

    // ── Test: custom provider registered via pack hook is reachable end-to-end ─
    //
    // This is the integration counterpart to the unit tests in
    // `embedder_registry.rs`. It verifies the full stack: a pack overrides
    // `register_embedders`, the transport calls `VerbRegistry::call_register_embedders`,
    // and the custom provider can be resolved and used via `rt.embedder(name)`.

    #[tokio::test]
    async fn pack_register_embedders_hook_makes_provider_reachable() {
        use async_trait::async_trait;
        use khive_runtime::pack::HandlerDef;
        use khive_runtime::NamespaceToken;
        use khive_runtime::{PackRuntime, VerbRegistry, VerbRegistryBuilder};
        use khive_types::Pack;
        use serde_json::Value;

        struct EmbedderPack;

        impl Pack for EmbedderPack {
            const NAME: &'static str = "embedder-test-pack";
            const NOTE_KINDS: &'static [&'static str] = &[];
            const ENTITY_KINDS: &'static [&'static str] = &[];
            const HANDLERS: &'static [HandlerDef] = &[];
        }

        #[async_trait]
        impl PackRuntime for EmbedderPack {
            fn name(&self) -> &str {
                Self::NAME
            }
            fn note_kinds(&self) -> &'static [&'static str] {
                Self::NOTE_KINDS
            }
            fn entity_kinds(&self) -> &'static [&'static str] {
                Self::ENTITY_KINDS
            }
            fn handlers(&self) -> &'static [HandlerDef] {
                Self::HANDLERS
            }
            fn register_embedders(&self, runtime: &KhiveRuntime) {
                runtime.register_embedder(MockEmbedderProvider::new("pack-custom-encoder", 256));
            }
            async fn dispatch(
                &self,
                _verb: &str,
                _params: Value,
                _registry: &VerbRegistry,
                _token: &NamespaceToken,
            ) -> Result<Value, khive_runtime::RuntimeError> {
                Ok(Value::Null)
            }
        }

        let rt = memory_rt_no_model();
        // Simulate what the transport does: build the registry, then call the hook.
        let mut builder = VerbRegistryBuilder::new();
        builder.register(EmbedderPack);
        let registry = builder.build().expect("registry builds");
        registry.call_register_embedders(&rt);

        // After the hook fires, the custom provider must be reachable.
        let service = rt
            .embedder("pack-custom-encoder")
            .await
            .expect("pack-contributed provider must be reachable after call_register_embedders");

        let texts = vec!["test sentence".to_string()];
        let vecs = service
            .embed(&texts, EmbeddingModel::AllMiniLmL6V2)
            .await
            .expect("custom service must embed without error");
        assert_eq!(vecs.len(), 1);
        assert_eq!(
            vecs[0].len(),
            256,
            "dims must match provider declaration (256)"
        );
    }

    // ── Test: failing provider build() returns Err instead of panicking ───────

    #[tokio::test]
    async fn failing_provider_build_returns_err_not_panic() {
        struct FailingProvider;

        #[async_trait]
        impl EmbedderProvider for FailingProvider {
            fn name(&self) -> &str {
                "failing-provider"
            }
            fn dimensions(&self) -> usize {
                128
            }
            async fn build(&self) -> Result<Arc<dyn EmbeddingService>, RuntimeError> {
                Err(RuntimeError::Internal(
                    "simulated provider construction failure".into(),
                ))
            }
        }

        let rt = memory_rt_no_model();
        rt.register_embedder(FailingProvider);

        let result = rt.embedder("failing-provider").await;
        assert!(
            result.is_err(),
            "embedder() must return Err when build() fails, not panic; got Ok"
        );
        let err = result.err().expect("checked above");
        let msg = err.to_string();
        assert!(
            msg.contains("simulated provider construction failure")
                || msg.contains("build() failed")
                || msg.contains("Internal"),
            "error must carry build failure context; got: {msg}"
        );
    }
}