velesdb-memory 0.8.0

VelesDB-memory: local-first MCP memory server for AI agents (remember/recall/relate/forget/why + deterministic context compiler).
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
//! BDD integration tests for the context compiler's memory bridge
//! (US-002 of EPIC-P-070): memory-backed fragment selection, source
//! round-trips, working contexts, and compilation events.
//!
//! Categories: Nominal (≥60%), Edge (~20%), Negative (≥20%).

#![cfg(all(feature = "context", feature = "persistence"))]

mod common;

use common::service;
use velesdb_memory::context::{
    CompilePolicy, CompileRequest, ContextCompiler, ContextFragment, DeterministicReranker,
    MemoryScope, WorkingContext,
};
use velesdb_memory::{ErrorCategory, FusionOptions, HashEmbedder, MemoryService};

fn fragment(content: &str) -> ContextFragment {
    ContextFragment {
        id: None,
        content: content.to_owned(),
        kind: None,
        priority: None,
        metadata: None,
    }
}

fn request(query: &str, fragments: Vec<ContextFragment>, budget: u64) -> CompileRequest {
    CompileRequest {
        query: query.to_owned(),
        fragments,
        project: None,
        target_model: None,
        token_budget: budget,
        memory_scope: None,
        policy: None,
    }
}

// --- Nominal -----------------------------------------------------------------

#[test]
fn test_compile_context_memory_scope_pulls_relevant_memory_with_provenance() {
    // Given a remembered fact relevant to the query
    let (_dir, svc) = service();
    let memory_id = svc
        .remember("the deploy pipeline runs clippy before tests", &[], None)
        .expect("remember");

    // When compiling with a memory scope
    let mut req = request(
        "deploy pipeline checks",
        vec![fragment("Session note: user asked about CI.")],
        10_000,
    );
    req.memory_scope = Some(MemoryScope {
        k: Some(3),
        ..MemoryScope::default()
    });
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // Then the memory is pulled in with full provenance
    assert!(
        out.content.contains("runs clippy before tests"),
        "the relevant memory must be compiled in, got:\n{}",
        out.content
    );
    let memory_decision = out
        .decisions
        .iter()
        .find(|d| d.memory_id == Some(memory_id))
        .expect("the pulled memory must carry its memory_id in provenance");
    assert!(
        (0.0..=1.0).contains(&memory_decision.relevance),
        "memory relevance must be normalised into [0, 1]"
    );
}

#[test]
fn test_compile_context_without_scope_matches_memoryless_compile() {
    // Given a request with no memory scope
    let (_dir, svc) = service();
    svc.remember("an unrelated remembered fact", &[], None)
        .expect("remember");
    let req = request("deploy", vec![fragment("Only caller content.")], 10_000);
    let compiler = ContextCompiler::new(CompilePolicy::default());

    // When compiling through the bridge and through the bare compiler
    let bridged = svc.compile_context(&compiler, &req).expect("bridged");
    let bare = compiler.compile(&req).expect("bare");

    // Then the compiled content is identical (the bridge only adds memories
    // when a scope asks for them)
    assert_eq!(bridged.content, bare.content);
    assert_eq!(bridged.decisions.len(), bare.decisions.len());
}

#[test]
fn test_retrieve_context_source_round_trips_original() {
    // Given a compiled request whose sources were stored
    let (_dir, svc) = service();
    let original = "Never restart the primary node during a rebalance.";
    let req = request("rebalance", vec![fragment(original)], 10_000);
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // When retrieving the source behind its handle
    let handle = &out.sources[0].handle;
    let retrieved = svc.retrieve_context_source(handle).expect("retrieve");

    // Then the exact original bytes come back
    assert_eq!(retrieved, original);
}

#[test]
fn test_working_context_round_trips_across_reopen() {
    // Given a saved working context
    let dir = tempfile::TempDir::new().expect("tempdir");
    let wc = WorkingContext {
        goal: Some("ship US-002".to_owned()),
        pending_actions: vec!["open PR2".to_owned()],
        ..WorkingContext::default()
    };
    {
        let svc = MemoryService::open(dir.path(), HashEmbedder::new(common::DIM)).expect("open");
        svc.save_working_context("veles", "session-1", &wc)
            .expect("save");
    }

    // When reopening the store in a new service (a later session)
    let svc = MemoryService::open(dir.path(), HashEmbedder::new(common::DIM)).expect("reopen");
    let loaded = svc
        .load_working_context("veles", "session-1")
        .expect("load")
        .expect("the working context must survive the reopen");

    // Then the working state is intact
    assert_eq!(loaded.goal.as_deref(), Some("ship US-002"));
    assert_eq!(loaded.pending_actions, vec!["open PR2".to_owned()]);
}

#[test]
fn test_compile_context_records_aggregatable_events() {
    // Given two compilations under one project and one under another
    let (_dir, svc) = service();
    let compiler = ContextCompiler::new(CompilePolicy::default());
    for _ in 0..2 {
        let mut req = request("deploy", vec![fragment("a"), fragment("a")], 10_000);
        req.project = Some("veles".to_owned());
        svc.compile_context(&compiler, &req).expect("compile");
    }
    let mut other = request("deploy", vec![fragment("b")], 10_000);
    other.project = Some("other".to_owned());
    svc.compile_context(&compiler, &other).expect("compile");

    // When aggregating savings per project
    let veles = svc.context_savings(Some("veles")).expect("savings");
    let other_project = svc.context_savings(Some("other")).expect("savings");
    let all = svc.context_savings(None).expect("savings");

    // Then events aggregate by project and across projects
    assert_eq!(veles.events, 2);
    assert_eq!(other_project.events, 1);
    assert_eq!(all.events, 3);
    assert!(veles.tokens_saved > 0, "the duplicate drop saved tokens");
    assert!(!all.truncated);
}

#[test]
fn test_recall_fused_reranked_with_deterministic_reranker_orders_by_overlap() {
    // Given facts of varying lexical overlap with the query
    let (_dir, svc) = service();
    svc.remember("the cat sat on the mat", &[], None)
        .expect("remember");
    svc.remember("deploy pipeline runs clippy", &[], None)
        .expect("remember");
    svc.remember(
        "clippy pedantic gates the deploy pipeline strictly",
        &[],
        None,
    )
    .expect("remember");

    // When recalling with the first shipped deterministic reranker
    let hits = svc
        .recall_fused_reranked(
            "deploy pipeline clippy",
            3,
            None,
            FusionOptions::default(),
            &DeterministicReranker,
        )
        .expect("recall");

    // Then the most lexically overlapping fact leads and nothing is dropped
    assert_eq!(hits.len(), 3);
    assert!(
        hits[0].content.contains("clippy"),
        "the top hit must overlap the query, got: {}",
        hits[0].content
    );
    assert!(
        !hits[0].content.contains("cat sat"),
        "the unrelated fact must not lead"
    );
}

// --- Edge --------------------------------------------------------------------

#[test]
fn test_compile_context_system_facts_never_pollute_recall() {
    // Given a compilation that stored sources and an event
    let (_dir, svc) = service();
    let sensitive = "internal incident postmortem draft for the veles cluster";
    let req = request("incident", vec![fragment(sensitive)], 10_000);
    let compiler = ContextCompiler::new(CompilePolicy::default());
    svc.compile_context(&compiler, &req).expect("compile");

    // When recalling normally for that content
    let hits = svc.recall(sensitive, 10, None).expect("recall");

    // Then neither the stored source nor the event surfaces as a memory
    assert!(
        hits.is_empty(),
        "compiler system facts must stay out of normal recall, got {hits:?}"
    );
}

#[test]
fn test_working_context_load_missing_returns_none() {
    let (_dir, svc) = service();
    let loaded = svc
        .load_working_context("veles", "no-such-session")
        .expect("load");
    assert!(loaded.is_none());
}

// --- Negative ----------------------------------------------------------------

#[test]
fn test_compile_context_event_and_sources_opt_out() {
    // Given a policy that opts out of events and source storage
    let (_dir, svc) = service();
    let policy = CompilePolicy {
        record_events: false,
        store_sources: false,
        ..CompilePolicy::default()
    };
    let mut req = request("deploy", vec![fragment("caller content")], 10_000);
    req.project = Some("veles".to_owned());
    req.policy = Some(policy);
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // When aggregating and retrieving afterwards
    let savings = svc.context_savings(Some("veles")).expect("savings");
    let retrieved = svc.retrieve_context_source(&out.sources[0].handle);

    // Then nothing was recorded and the source is not retrievable
    assert_eq!(savings.events, 0, "opt-out must record no event");
    let err = retrieved.expect_err("opt-out must not store sources");
    assert_eq!(err.category(), ErrorCategory::NotFound);
}

#[test]
fn test_retrieve_context_source_unknown_handle_is_not_found() {
    let (_dir, svc) = service();
    let err = svc
        .retrieve_context_source("ctx://source/1234567890")
        .expect_err("nothing was stored under this handle");
    assert_eq!(err.category(), ErrorCategory::NotFound);
}

#[test]
fn test_retrieve_context_source_malformed_handle_is_not_found() {
    let (_dir, svc) = service();
    for bad in ["not-a-handle", "ctx://source/", "ctx://source/xyz", ""] {
        let err = svc
            .retrieve_context_source(bad)
            .expect_err("malformed handles must fail");
        assert_eq!(err.category(), ErrorCategory::NotFound, "handle: {bad}");
    }
}

// --- Review findings (2026-07-17): system-fact isolation & robustness -------

#[test]
fn test_system_facts_never_pollute_filtered_recall_or_memory_scope() {
    // Given a compilation that recorded an event and a saved working context,
    // both under a project facet
    let (_dir, svc) = service();
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let mut req = request(
        "incident",
        vec![fragment("caller note about the incident")],
        10_000,
    );
    req.project = Some("acme".to_owned());
    svc.compile_context(&compiler, &req).expect("compile");
    svc.save_working_context("acme", "s1", &WorkingContext::default())
        .expect("save");

    // When recalling with a caller-style project filter
    let mut filter = serde_json::Map::new();
    filter.insert(
        "project".to_owned(),
        serde_json::Value::String("acme".to_owned()),
    );
    let hits = svc
        .recall("compilation event working context", 10, Some(&filter))
        .expect("recall");

    // Then no system fact surfaces (events/working state carry no caller keys)
    assert!(
        hits.is_empty(),
        "system facts must be invisible to filtered recall, got {hits:?}"
    );

    // And a project-scoped memory pull can never compile them into a prompt
    let mut scoped = request("compilation event", vec![fragment("note")], 10_000);
    scoped.memory_scope = Some(MemoryScope {
        project: Some("acme".to_owned()),
        k: Some(10),
        ..MemoryScope::default()
    });
    let out = svc.compile_context(&compiler, &scoped).expect("compile");
    assert!(
        !out.content.contains("veles context compilation event")
            && !out.content.contains("active_constraints"),
        "system facts must never be pulled as memories, got:\n{}",
        out.content
    );
}

#[test]
fn test_context_savings_ignores_forged_caller_events_and_never_overflows() {
    // Given ordinary caller facts that try to pose as compilation events
    let (_dir, svc) = service();
    let mut forged = serde_json::Map::new();
    forged.insert("ctx_event".to_owned(), serde_json::Value::Bool(true));
    forged.insert(
        "project".to_owned(),
        serde_json::Value::String("x".to_owned()),
    );
    forged.insert(
        "tokens_saved".to_owned(),
        serde_json::Value::Number(serde_json::Number::from(u64::MAX)),
    );
    forged.insert(
        "cost_saved_micros".to_owned(),
        serde_json::Value::Number(serde_json::Number::from(u64::MAX)),
    );
    forged.insert(
        "currency".to_owned(),
        serde_json::Value::String("USD".to_owned()),
    );
    svc.remember("a perfectly ordinary fact", &[], Some(&forged))
        .expect("remember");
    svc.remember("another ordinary fact", &[], Some(&forged))
        .expect("remember");

    // When aggregating savings
    let savings = svc
        .context_savings(Some("x"))
        .expect("savings must not panic");

    // Then forged facts count for nothing
    assert_eq!(savings.events, 0, "caller facts must never count as events");
    assert_eq!(savings.tokens_saved, 0);
    assert!(savings.cost_saved_micros_by_currency.is_empty());
}

#[test]
fn test_compile_context_memory_scope_respects_the_fragment_cap() {
    // Given a request already at the fragment cap and a scope asking for more
    let (_dir, svc) = service();
    svc.remember("the deploy pipeline runs clippy", &[], None)
        .expect("remember");
    let fragments: Vec<ContextFragment> = (0..velesdb_memory::limits::MAX_FRAGMENTS)
        .map(|i| fragment(&format!("note {i}")))
        .collect();
    let mut req = request("deploy pipeline", fragments, 100_000);
    req.memory_scope = Some(MemoryScope {
        k: Some(5),
        ..MemoryScope::default()
    });
    let compiler = ContextCompiler::new(CompilePolicy::default());

    // When compiling — the bridge must not push the request over the cap
    let out = svc
        .compile_context(&compiler, &req)
        .expect("a valid request must stay valid with a memory scope");

    // Then exactly the caller's fragments were compiled (no room for pulls)
    assert_eq!(out.decisions.len(), velesdb_memory::limits::MAX_FRAGMENTS);
}

#[test]
fn test_retrieve_context_source_refuses_a_squatting_caller_fact() {
    // Given a compiled source and a caller fact remembered at the literal
    // salt-preimage of another handle's storage slot
    let (_dir, svc) = service();
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc
        .compile_context(
            &compiler,
            &request("q", vec![fragment("legit source")], 10_000),
        )
        .expect("compile");
    let legit_handle = out.sources[0].handle.clone();

    let squatted_hash: u64 = 424_242;
    svc.remember(&format!("veles-ctx-source:{squatted_hash}"), &[], None)
        .expect("remember");

    // When retrieving both handles
    let legit = svc.retrieve_context_source(&legit_handle).expect("legit");
    let squatted = svc.retrieve_context_source(&format!("ctx://source/{squatted_hash}"));

    // Then the real source round-trips and the squatter is never served back
    assert_eq!(legit, "legit source");
    let err = squatted.expect_err("a caller fact must never masquerade as a stored source");
    assert_eq!(err.category(), ErrorCategory::NotFound);
}

#[test]
fn test_source_ttl_zero_stores_permanently_like_remember() {
    // Given the crate-wide TTL convention: Some(0) means "no expiry"
    let (_dir, svc) = service();
    let policy = CompilePolicy {
        source_ttl_seconds: Some(0),
        ..CompilePolicy::default()
    };
    let mut req = request("q", vec![fragment("must stay retrievable")], 10_000);
    req.policy = Some(policy);
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // When retrieving right away (an expired-at-once fact would already fail)
    let retrieved = svc
        .retrieve_context_source(&out.sources[0].handle)
        .expect("Some(0) must mean permanent, exactly like remember_with_ttl");

    // Then the source is there
    assert_eq!(retrieved, "must stay retrievable");
}

// --- Coverage round (2026-07-17): pricing trail, writer guard, provenance ----

#[test]
fn test_context_savings_aggregates_cost_by_currency_when_pricing_injected() {
    // Given a service compiling twice with a pricing table and a project
    let (_dir, svc) = service();
    let mut models = std::collections::BTreeMap::new();
    models.insert(
        "claude-sonnet-5".to_owned(),
        velesdb_memory::context::ModelPricing {
            input_micros_per_million_tokens: 3_000_000,
        },
    );
    let pricing = velesdb_memory::context::PricingTable {
        version: "2026-07".to_owned(),
        currency: "EUR".to_owned(),
        models,
    };
    let compiler = ContextCompiler::new(CompilePolicy::default()).with_pricing(pricing);
    let dup = "The rebalance pauses ingestion on the affected shard.";
    let mut expected_micros = 0_u64;
    for _ in 0..2 {
        let mut req = request("rebalance", vec![fragment(dup), fragment(dup)], 10_000);
        req.project = Some("acme".to_owned());
        req.target_model = Some("claude-sonnet-5".to_owned());
        let out = svc.compile_context(&compiler, &req).expect("compile");
        expected_micros += out
            .insights
            .estimated_cost_saved_micros
            .expect("priced model must yield a cost figure");
    }

    // When aggregating the project's savings
    let savings = svc.context_savings(Some("acme")).expect("savings");

    // Then the cost trail sums per currency, exactly
    assert_eq!(savings.events, 2);
    assert!(expected_micros > 0);
    assert_eq!(
        savings.cost_saved_micros_by_currency.get("EUR").copied(),
        Some(expected_micros),
        "the recorded events must carry and aggregate the cost figures"
    );
}

#[test]
fn test_store_context_sources_never_clobbers_a_caller_fact_squatting_the_slot() {
    // Given a caller fact remembered at the literal salt-preimage of the
    // slot where a future compile would store its source
    let (_dir, svc) = service();
    let content = "a fragment whose source slot is already squatted";
    let hash = velesdb_memory::context::fragment_id(content);
    let squat = format!("veles-ctx-source:{hash}");
    let squat_id = svc.remember(&squat, &[], None).expect("remember");

    // When compiling that content (store_sources defaults to true)
    let compiler = ContextCompiler::new(CompilePolicy::default());
    svc.compile_context(&compiler, &request("q", vec![fragment(content)], 10_000))
        .expect("compile");

    // Then the caller's fact is intact (never overwritten by the writer) ...
    let hits = svc.recall(&squat, 3, None).expect("recall");
    assert!(
        hits.iter().any(|h| h.id == squat_id && h.content == squat),
        "the squatting caller fact must survive a compile of the colliding content"
    );
    // ... and the handle stays unresolvable rather than serving wrong bytes
    let err = svc
        .retrieve_context_source(&format!("ctx://source/{hash}"))
        .expect_err("a squatted slot must not resolve");
    assert_eq!(err.category(), ErrorCategory::NotFound);
}

#[test]
fn test_pulled_memory_source_reference_carries_its_memory_id() {
    // Given a remembered fact pulled into a compilation via memory scope
    let (_dir, svc) = service();
    let memory_id = svc
        .remember("the canary stage rolls to five percent first", &[], None)
        .expect("remember");
    let mut req = request("canary rollout", vec![fragment("Session note.")], 10_000);
    req.memory_scope = Some(MemoryScope {
        k: Some(3),
        ..MemoryScope::default()
    });
    let compiler = ContextCompiler::new(CompilePolicy::default());

    // When compiling
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // Then the pulled memory's source reference links back to the memory id
    let hash = velesdb_memory::context::fragment_id("the canary stage rolls to five percent first");
    let source = out
        .sources
        .iter()
        .find(|s| s.handle.ends_with(&hash.to_string()))
        .expect("the pulled memory must have a source reference");
    assert_eq!(
        source.memory_id,
        Some(memory_id),
        "provenance must link the source back to the memory it came from"
    );
}

#[test]
fn test_memory_scope_graph_boost_pulls_evidence_sharing_no_words_with_the_query() {
    // Given a cause-chain in memory: a symptom fact (lexically close to the
    // query) linked to a fix fact that shares NO vocabulary with the query,
    // plus a distractor that out-scores the fix in the lexical vector space
    let (_dir, svc) = service();
    let symptom = svc
        .remember(
            "the payments checkout flow returns five hundred and two errors under peak load",
            &[],
            None,
        )
        .expect("remember");
    let fix = svc
        .remember(
            "raising the pool acquisition timeout to forty-five seconds stopped the cascade",
            &[],
            None,
        )
        .expect("remember");
    svc.relate(symptom, fix, "fixed_by").expect("relate");
    svc.remember(
        "the release notifications are posted to the payments channel under the weekly load report",
        &[],
        None,
    )
    .expect("remember distractor");

    // When compiling with a memory scope that raises the graph boost —
    // built from the exact wire JSON an MCP/Node caller sends
    let raw = r#"{
        "query": "why does the payments checkout flow fail under peak load",
        "token_budget": 4000,
        "fragments": [{"content": "Session note."}],
        "memory_scope": {"k": 2, "graph_boost": 0.8}
    }"#;
    let req: CompileRequest = serde_json::from_str(raw).expect("wire shape");
    let compiler = ContextCompiler::new(CompilePolicy::default());
    let out = svc.compile_context(&compiler, &req).expect("compile");

    // Then the graph-reached fix — invisible to lexical/vector matching —
    // is compiled into the context with memory provenance
    assert!(
        out.content
            .contains("forty-five seconds stopped the cascade"),
        "the boosted graph walk must pull the zero-overlap evidence, got:\n{}",
        out.content
    );
    let fix_decision = out
        .decisions
        .iter()
        .find(|d| d.memory_id == Some(fix))
        .expect("the fix must carry its memory id in provenance");
    assert!(fix_decision.relevance > 0.0);
}

// --- Reranker seam (2026-07-17): the last engine capability wired in -------

/// A stand-in for a caller's cross-encoder: promotes the memory containing
/// its marker to the front, keeps every other candidate in place.
struct MarkerReranker(&'static str);

impl velesdb_memory::Reranker for MarkerReranker {
    fn rerank(
        &self,
        _query: &str,
        mut candidates: Vec<velesdb_memory::Recollection>,
    ) -> Result<Vec<velesdb_memory::Recollection>, velesdb_memory::RerankError> {
        candidates.sort_by_key(|c| usize::from(!c.content.contains(self.0)));
        Ok(candidates)
    }
}

#[test]
fn test_compile_context_reranked_lets_a_cross_encoder_drive_memory_selection() {
    // Given two memories where the fused (lexical-vector) ranking prefers
    // the wordy near-miss, while a semantic reranker knows the terse one is
    // the real answer
    let (_dir, svc) = service();
    svc.remember(
        "the deploy pipeline deploy checks deploy the canary deploy stage",
        &[],
        None,
    )
    .expect("remember wordy near-miss");
    let answer = svc
        .remember("promotion is gated on checksum verification", &[], None)
        .expect("remember terse answer");

    let mut req = request(
        "deploy pipeline checks",
        vec![fragment("Session note.")],
        10_000,
    );
    req.memory_scope = Some(MemoryScope {
        k: Some(1),
        ..MemoryScope::default()
    });
    let compiler = ContextCompiler::new(CompilePolicy::default());

    // When compiling once with the fused default and once with the reranker
    let fused_only = svc.compile_context(&compiler, &req).expect("compile");
    let reranked = svc
        .compile_context_reranked(&compiler, &req, &MarkerReranker("checksum"))
        .expect("compile reranked");

    // Then the reranker changed which memory was selected (k=1), and the
    // selected memory carries its provenance
    assert!(
        !fused_only.content.contains("checksum verification"),
        "precondition: the fused default must prefer the wordy near-miss"
    );
    assert!(
        reranked
            .content
            .contains("promotion is gated on checksum verification"),
        "the reranker must drive selection, got:\n{}",
        reranked.content
    );
    let picked = reranked
        .decisions
        .iter()
        .find(|d| d.memory_id == Some(answer))
        .expect("the reranked pull must carry its memory id");
    assert!(picked.relevance > 0.0);
}

#[test]
fn test_compile_context_reranked_with_a_lexical_reranker_demotes_graph_rescues() {
    // Given a symptom -> fix chain whose fix shares no vocabulary with the
    // query (the tri-engine rescue case)
    let (_dir, svc) = service();
    let symptom = svc
        .remember("checkout requests fail under peak load", &[], None)
        .expect("remember");
    let fix = svc
        .remember(
            "raising the acquisition timeout stopped the cascade",
            &[],
            None,
        )
        .expect("remember");
    svc.relate(symptom, fix, "fixed_by").expect("relate");

    let raw = r#"{
        "query": "why do checkout requests fail under peak load",
        "token_budget": 4000,
        "fragments": [{"content": "Session note."}],
        "memory_scope": {"k": 2, "graph_boost": 0.8}
    }"#;
    let req: CompileRequest = serde_json::from_str(raw).expect("wire shape");
    let compiler = ContextCompiler::new(CompilePolicy::default());

    // When selecting with the boosted fusion vs re-ranking that same pool
    // with the shipped LEXICAL reranker
    let fused = svc.compile_context(&compiler, &req).expect("compile");
    let lexical = velesdb_memory::context::DeterministicReranker;
    let reranked = svc
        .compile_context_reranked(&compiler, &req, &lexical)
        .expect("compile reranked");

    // Then fusion surfaces the zero-overlap fix — and the lexical reranker
    // (scoring by word overlap alone) demotes it out of k=2's front, which
    // is exactly why no reranker runs by default: a lexical second stage
    // would undo the graph rescue. The seam exists for SEMANTIC rerankers.
    assert!(
        fused.content.contains("stopped the cascade"),
        "precondition: the boosted fusion must rescue the fix"
    );
    assert!(
        reranked.decisions.iter().any(|d| d.memory_id == Some(fix)),
        "rerank reorders but never drops: the fix stays in the pulled set"
    );
}