cortex-memory 0.3.1

Self-organizing graph memory for AI agents. Single binary, zero dependencies.
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
use cortex_core::*;
use std::collections::HashMap;
use std::sync::{Arc, RwLock as StdRwLock};
use tempfile::tempdir;

fn make_source(agent: &str) -> Source {
    Source {
        agent: agent.to_string(),
        session: None,
        channel: None,
    }
}

fn make_manual(created_by: &str) -> EdgeProvenance {
    EdgeProvenance::Manual {
        created_by: created_by.to_string(),
    }
}

// ── Storage Persistence ──────────────────────────────────────────────────────

#[test]
fn test_storage_persistence() {
    let dir = tempdir().unwrap();
    let db_path = dir.path().join("test.redb");

    let node_id = {
        let storage = RedbStorage::open(&db_path).unwrap();
        let node = Node::new(
            NodeKind::new("fact").unwrap(),
            "Persistence Test".to_string(),
            "Testing persistence across reopens".to_string(),
            make_source("test"),
            0.5,
        );
        let id = node.id;
        storage.put_node(&node).unwrap();
        id
    };

    // Reopen storage and verify data survived
    let storage = RedbStorage::open(&db_path).unwrap();
    let node = storage
        .get_node(node_id)
        .unwrap()
        .expect("Node should survive reopen");
    assert_eq!(node.data.title, "Persistence Test");
}

// ── Graph Traversal ──────────────────────────────────────────────────────────

#[test]
fn test_graph_bfs_traversal() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    // Create chain: A -> B -> C
    let node_a = Node::new(
        NodeKind::new("fact").unwrap(),
        "A".to_string(),
        "First".to_string(),
        make_source("test"),
        0.5,
    );
    let node_b = Node::new(
        NodeKind::new("fact").unwrap(),
        "B".to_string(),
        "Second".to_string(),
        make_source("test"),
        0.5,
    );
    let node_c = Node::new(
        NodeKind::new("fact").unwrap(),
        "C".to_string(),
        "Third".to_string(),
        make_source("test"),
        0.5,
    );

    storage.put_node(&node_a).unwrap();
    storage.put_node(&node_b).unwrap();
    storage.put_node(&node_c).unwrap();

    storage
        .put_edge(&Edge::new(
            node_a.id,
            node_b.id,
            Relation::new("informed_by").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();
    storage
        .put_edge(&Edge::new(
            node_b.id,
            node_c.id,
            Relation::new("informed_by").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();

    let request = TraversalRequest {
        start: vec![node_a.id],
        max_depth: Some(5),
        direction: TraversalDirection::Outgoing,
        strategy: TraversalStrategy::Bfs,
        ..Default::default()
    };

    let subgraph = graph_engine.traverse(request).unwrap();

    assert!(
        subgraph.nodes.contains_key(&node_b.id),
        "B should be reachable from A"
    );
    assert!(
        subgraph.nodes.contains_key(&node_c.id),
        "C should be reachable from A"
    );
    assert_eq!(subgraph.depths[&node_b.id], 1);
    assert_eq!(subgraph.depths[&node_c.id], 2);
}

#[test]
fn test_graph_depth_limit() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let a = Node::new(
        NodeKind::new("fact").unwrap(),
        "A".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let b = Node::new(
        NodeKind::new("fact").unwrap(),
        "B".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let c = Node::new(
        NodeKind::new("fact").unwrap(),
        "C".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );

    storage.put_node(&a).unwrap();
    storage.put_node(&b).unwrap();
    storage.put_node(&c).unwrap();

    storage
        .put_edge(&Edge::new(
            a.id,
            b.id,
            Relation::new("led_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();
    storage
        .put_edge(&Edge::new(
            b.id,
            c.id,
            Relation::new("led_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();

    // Depth 1 should reach B but not C
    let request = TraversalRequest {
        start: vec![a.id],
        max_depth: Some(1),
        direction: TraversalDirection::Outgoing,
        strategy: TraversalStrategy::Bfs,
        ..Default::default()
    };

    let subgraph = graph_engine.traverse(request).unwrap();
    assert!(subgraph.nodes.contains_key(&b.id));
    assert!(
        !subgraph.nodes.contains_key(&c.id),
        "C should be beyond depth limit"
    );
}

#[test]
fn test_find_paths() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let a = Node::new(
        NodeKind::new("fact").unwrap(),
        "A".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let b = Node::new(
        NodeKind::new("fact").unwrap(),
        "B".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let c = Node::new(
        NodeKind::new("fact").unwrap(),
        "C".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );

    storage.put_node(&a).unwrap();
    storage.put_node(&b).unwrap();
    storage.put_node(&c).unwrap();

    // A -> B -> C
    storage
        .put_edge(&Edge::new(
            a.id,
            b.id,
            Relation::new("led_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();
    storage
        .put_edge(&Edge::new(
            b.id,
            c.id,
            Relation::new("led_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();

    let path_req = PathRequest {
        from: a.id,
        to: c.id,
        max_paths: 1,
        max_length: Some(10),
        ..Default::default()
    };
    let result = graph_engine.find_paths(path_req).unwrap();

    assert!(!result.paths.is_empty(), "Should find path from A to C");
    assert_eq!(result.paths[0].nodes.len(), 3, "Path A->B->C has 3 nodes");
    assert_eq!(result.paths[0].nodes[0], a.id);
    assert_eq!(result.paths[0].nodes[2], c.id);
}

#[test]
fn test_graph_neighborhood() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let center = Node::new(
        NodeKind::new("agent").unwrap(),
        "Center".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let n1 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N1".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let n2 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N2".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let far = Node::new(
        NodeKind::new("fact").unwrap(),
        "Far".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );

    storage.put_node(&center).unwrap();
    storage.put_node(&n1).unwrap();
    storage.put_node(&n2).unwrap();
    storage.put_node(&far).unwrap();

    storage
        .put_edge(&Edge::new(
            center.id,
            n1.id,
            Relation::new("related_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();
    storage
        .put_edge(&Edge::new(
            center.id,
            n2.id,
            Relation::new("related_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();
    storage
        .put_edge(&Edge::new(
            n1.id,
            far.id,
            Relation::new("related_to").unwrap(),
            1.0,
            make_manual("test"),
        ))
        .unwrap();

    // neighborhood always traverses Both directions at the given depth
    let subgraph = graph_engine.neighborhood(center.id, 1).unwrap();

    assert!(subgraph.nodes.contains_key(&n1.id));
    assert!(subgraph.nodes.contains_key(&n2.id));
    assert!(
        !subgraph.nodes.contains_key(&far.id),
        "Far should be beyond depth 1"
    );
    assert_eq!(subgraph.edges.len(), 2);
}

// ── Vector Index ─────────────────────────────────────────────────────────────

#[test]
fn test_vector_index_rebuild() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let embedding_service = Arc::new(FastEmbedService::new().unwrap());
    let vector_index = Arc::new(StdRwLock::new(HnswIndex::new(
        embedding_service.dimension(),
    )));

    for i in 0..5 {
        let mut node = Node::new(
            NodeKind::new("fact").unwrap(),
            format!("Test Node {}", i),
            format!("Body {}", i),
            make_source("test"),
            0.5,
        );
        let text = embedding_input(&node);
        let embedding = embedding_service.embed(&text).unwrap();
        node.embedding = Some(embedding.clone());
        storage.put_node(&node).unwrap();
        vector_index
            .write()
            .unwrap()
            .insert(node.id, &embedding)
            .unwrap();
    }

    // Rebuild should not lose data
    vector_index.write().unwrap().rebuild().unwrap();

    let query = embedding_service.embed("test query").unwrap();
    let results = vector_index
        .read()
        .unwrap()
        .search(&query, 5, None)
        .unwrap();
    assert!(!results.is_empty(), "Should find results after rebuild");
    assert!(results.len() <= 5);
}

#[test]
fn test_similarity_search_returns_relevant_results() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let embedding_service = Arc::new(FastEmbedService::new().unwrap());
    let vector_index = Arc::new(StdRwLock::new(HnswIndex::new(
        embedding_service.dimension(),
    )));

    // Add a semantically distinct set of nodes
    let topics = vec![
        (
            "Rust programming",
            "Rust is a systems programming language focused on safety",
        ),
        (
            "Python scripting",
            "Python is great for scripting and data science",
        ),
        (
            "Machine learning",
            "ML models learn patterns from training data",
        ),
    ];

    for (title, body) in topics {
        let mut node = Node::new(
            NodeKind::new("fact").unwrap(),
            title.to_string(),
            body.to_string(),
            make_source("test"),
            0.5,
        );
        let text = embedding_input(&node);
        let emb = embedding_service.embed(&text).unwrap();
        node.embedding = Some(emb.clone());
        storage.put_node(&node).unwrap();
        vector_index.write().unwrap().insert(node.id, &emb).unwrap();
    }

    vector_index.write().unwrap().rebuild().unwrap();

    // Query for Rust — the Rust node should score highest
    let query_emb = embedding_service
        .embed("Rust systems programming safety")
        .unwrap();
    let results = vector_index
        .read()
        .unwrap()
        .search(&query_emb, 3, None)
        .unwrap();

    assert!(!results.is_empty());
    let top_node = storage.get_node(results[0].node_id).unwrap().unwrap();
    assert!(
        top_node.data.title.to_lowercase().contains("rust"),
        "Top result should be the Rust node, got: {}",
        top_node.data.title
    );
}

// ── Auto-Linker ──────────────────────────────────────────────────────────────

#[test]
fn test_auto_linker_creates_similarity_link() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let embedding_service = Arc::new(FastEmbedService::new().unwrap());
    let vector_index = Arc::new(StdRwLock::new(HnswIndex::new(
        embedding_service.dimension(),
    )));
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let config = AutoLinkerConfig::default();
    let mut auto_linker = AutoLinker::new(
        storage.clone(),
        graph_engine,
        vector_index.clone(),
        embedding_service.clone(),
        config,
    )
    .unwrap();

    // Two highly similar nodes about Rust memory safety
    let mut node1 = Node::new(
        NodeKind::new("fact").unwrap(),
        "Rust is memory-safe".to_string(),
        "Rust provides memory safety without garbage collection".to_string(),
        make_source("test"),
        0.8,
    );
    let mut node2 = Node::new(
        NodeKind::new("fact").unwrap(),
        "Rust ensures memory safety".to_string(),
        "Memory safety is guaranteed by Rust's ownership system".to_string(),
        make_source("test"),
        0.8,
    );

    let emb1 = embedding_service.embed(&embedding_input(&node1)).unwrap();
    let emb2 = embedding_service.embed(&embedding_input(&node2)).unwrap();
    node1.embedding = Some(emb1.clone());
    node2.embedding = Some(emb2.clone());

    storage.put_node(&node1).unwrap();
    storage.put_node(&node2).unwrap();
    {
        let mut idx = vector_index.write().unwrap();
        idx.insert(node1.id, &emb1).unwrap();
        idx.insert(node2.id, &emb2).unwrap();
    }

    auto_linker.run_cycle().unwrap();

    let edges_from = storage.edges_from(node1.id).unwrap();
    let edges_to = storage.edges_to(node1.id).unwrap();
    assert!(
        edges_from.len() + edges_to.len() > 0,
        "Auto-linker should create a similarity edge between similar nodes"
    );
}

#[test]
fn test_auto_linker_metrics_update_after_cycle() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let embedding_service = Arc::new(FastEmbedService::new().unwrap());
    let vector_index = Arc::new(StdRwLock::new(HnswIndex::new(
        embedding_service.dimension(),
    )));
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let mut auto_linker = AutoLinker::new(
        storage.clone(),
        graph_engine,
        vector_index,
        embedding_service,
        AutoLinkerConfig::default(),
    )
    .unwrap();

    assert_eq!(auto_linker.metrics().cycles, 0);
    auto_linker.run_cycle().unwrap();
    assert_eq!(
        auto_linker.metrics().cycles,
        1,
        "Cycle count should increment"
    );
}

// ── Edge Decay ───────────────────────────────────────────────────────────────

#[test]
fn test_edge_decay_preserves_recent_auto_edges() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let decay_engine = DecayEngine::new(storage.clone(), DecayConfig::default());

    let node1 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N1".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let node2 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N2".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    storage.put_node(&node1).unwrap();
    storage.put_node(&node2).unwrap();

    // Auto-similarity edge (subject to decay)
    let edge = Edge::new(
        node1.id,
        node2.id,
        Relation::new("related_to").unwrap(),
        1.0,
        EdgeProvenance::AutoSimilarity { score: 0.9 },
    );
    storage.put_edge(&edge).unwrap();

    // Just-created edges should survive decay
    let (pruned, deleted) = decay_engine.apply_decay(chrono::Utc::now()).unwrap();
    assert_eq!(
        pruned, 0,
        "Recently created auto-edges should not be pruned immediately"
    );
    assert_eq!(
        deleted, 0,
        "Recently created auto-edges should not be deleted immediately"
    );

    // Edge should still exist
    let retrieved = storage.get_edge(edge.id).unwrap();
    assert!(
        retrieved.is_some(),
        "Edge should still exist after decay pass"
    );
}

#[test]
fn test_edge_decay_exempts_manual_edges() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let decay_engine = DecayEngine::new(storage.clone(), DecayConfig::default());

    let n1 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N1".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    let n2 = Node::new(
        NodeKind::new("fact").unwrap(),
        "N2".to_string(),
        "".to_string(),
        make_source("test"),
        0.5,
    );
    storage.put_node(&n1).unwrap();
    storage.put_node(&n2).unwrap();

    let manual_edge = Edge::new(
        n1.id,
        n2.id,
        Relation::new("related_to").unwrap(),
        0.01,
        make_manual("test"),
    );
    storage.put_edge(&manual_edge).unwrap();

    // Even with weight below thresholds, manual edges are exempt
    let (_, deleted) = decay_engine.apply_decay(chrono::Utc::now()).unwrap();
    assert_eq!(
        deleted, 0,
        "Manual edges should be exempt from decay deletion"
    );

    let still_exists = storage.get_edge(manual_edge.id).unwrap();
    assert!(still_exists.is_some(), "Manual edge should survive decay");
}

// ── Hybrid Search ────────────────────────────────────────────────────────────

#[test]
fn test_hybrid_search_finds_relevant_nodes() {
    let dir = tempdir().unwrap();
    let storage = Arc::new(RedbStorage::open(dir.path().join("test.redb")).unwrap());
    let embedding_service = Arc::new(FastEmbedService::new().unwrap());
    let vector_index = Arc::new(StdRwLock::new(HnswIndex::new(
        embedding_service.dimension(),
    )));
    let graph_engine = Arc::new(GraphEngineImpl::new(storage.clone()));

    let mut node = Node::new(
        NodeKind::new("fact").unwrap(),
        "Machine learning algorithms".to_string(),
        "Various algorithms used in machine learning include neural networks".to_string(),
        make_source("test"),
        0.8,
    );
    let emb = embedding_service.embed(&embedding_input(&node)).unwrap();
    node.embedding = Some(emb.clone());
    storage.put_node(&node).unwrap();
    vector_index.write().unwrap().insert(node.id, &emb).unwrap();

    // Arc<E> and Arc<G> implement EmbeddingService/GraphEngine via blanket impls.
    // RwLockVectorIndex wraps Arc<RwLock<V>> to implement VectorIndex.
    let hybrid = HybridSearch::new(
        storage.clone(),
        embedding_service.clone(),
        RwLockVectorIndex(vector_index.clone()),
        graph_engine.clone(),
    );

    let query = HybridQuery::new("machine learning".to_string()).with_limit(10);
    let results = hybrid.search(query).unwrap();

    assert!(!results.is_empty(), "Should find results for ML query");
    assert!(
        results[0].vector_score > 0.0,
        "Top result should have a positive vector score"
    );
}

// ── Config ───────────────────────────────────────────────────────────────────

#[test]
fn test_auto_linker_config_defaults_are_sane() {
    let config = AutoLinkerConfig::default();
    assert_eq!(config.interval.as_secs(), 60);
    assert_eq!(config.max_nodes_per_cycle, 500);
    assert_eq!(config.max_edges_per_cycle, 2000);
    assert!(config.run_on_startup);
    assert!(config.validate().is_ok());
}

#[test]
fn test_decay_config_defaults_are_sane() {
    let config = DecayConfig::default();
    assert!(config.daily_decay_rate > 0.0 && config.daily_decay_rate <= 1.0);
    assert!(config.prune_threshold > config.delete_threshold);
    assert!(config.exempt_manual);
    assert!(config.validate().is_ok());
}

// ── Write Gate Schema Validation ────────────────────────────────────────────

#[test]
fn test_write_gate_schema_rejection() {
    // Build a SchemaValidator that requires "rationale" (type: string) for
    // decision nodes.
    let mut fields = HashMap::new();
    fields.insert(
        "rationale".to_string(),
        FieldSchema {
            field_type: Some(FieldType::String),
            ..Default::default()
        },
    );
    let mut schemas = HashMap::new();
    schemas.insert(
        "decision".to_string(),
        KindSchema {
            required_fields: vec!["rationale".to_string()],
            fields,
        },
    );
    let validator = SchemaValidator::new(schemas);

    // Create a decision node with empty metadata (missing the required
    // "rationale" field).
    let node = Node::new(
        NodeKind::new("decision").unwrap(),
        "Choose the storage backend".to_string(),
        "We decided to use redb for embedded ACID storage".to_string(),
        make_source("test"),
        0.5,
    );

    let result = WriteGate::check_schema(&node, &validator);
    match result {
        GateResult::Reject(rejection) => {
            assert_eq!(
                rejection.check,
                GateCheck::Schema,
                "Rejection should be a Schema gate check"
            );
            assert!(
                rejection.reason.contains("rationale"),
                "Rejection reason should mention the missing field: {}",
                rejection.reason
            );
        }
        GateResult::Pass => {
            panic!("Expected schema rejection for a decision node missing 'rationale'");
        }
    }
}

#[test]
fn test_http_schema_422() {
    // Full HTTP 422 testing requires a running server.  Instead we verify
    // the same validation pipeline that the HTTP handler delegates to:
    // SchemaValidator rejects a node whose metadata violates field-type
    // constraints, and WriteGate::check_schema surfaces the rejection with
    // a Schema GateCheck variant.

    // Schema: decision nodes need "rationale" (string) and "priority" (number
    // between 1 and 5).
    let mut fields = HashMap::new();
    fields.insert(
        "rationale".to_string(),
        FieldSchema {
            field_type: Some(FieldType::String),
            ..Default::default()
        },
    );
    fields.insert(
        "priority".to_string(),
        FieldSchema {
            field_type: Some(FieldType::Number),
            min: Some(1.0),
            max: Some(5.0),
            ..Default::default()
        },
    );
    let mut schemas = HashMap::new();
    schemas.insert(
        "decision".to_string(),
        KindSchema {
            required_fields: vec!["rationale".to_string()],
            fields,
        },
    );
    let validator = SchemaValidator::new(schemas);

    // Create a decision node whose metadata violates the type constraint:
    // "priority" is a string ("high") instead of a number.
    let mut node = Node::new(
        NodeKind::new("decision").unwrap(),
        "Choose the storage backend".to_string(),
        "We decided to use redb for embedded ACID storage".to_string(),
        make_source("test"),
        0.5,
    );
    node.data.metadata.insert(
        "rationale".to_string(),
        serde_json::json!("Performance requirements"),
    );
    node.data
        .metadata
        .insert("priority".to_string(), serde_json::json!("high"));

    let result = WriteGate::check_schema(&node, &validator);
    match result {
        GateResult::Reject(rejection) => {
            assert_eq!(
                rejection.check,
                GateCheck::Schema,
                "Rejection should be a Schema gate check"
            );
            assert!(
                rejection.reason.contains("priority"),
                "Rejection reason should mention the violating field: {}",
                rejection.reason
            );
            assert!(
                rejection.reason.contains("expected type"),
                "Rejection reason should explain the type mismatch: {}",
                rejection.reason
            );
        }
        GateResult::Pass => {
            panic!("Expected schema rejection for a 'priority' field with wrong type");
        }
    }
}