kimetsu-brain 1.5.1

Project + user-scope memory, hybrid retrieval (lexical + cosine), ambient context, secret redaction at ingest for kimetsu.
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
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
//! v0.5.2: conflict detection at ingest.
//!
//! Two memories that say opposite things ("use thiserror" /
//! "use anyhow") confuse the model when both surface in the same
//! broker bundle. v0.5.0 + v0.5.1 made the brain learn from
//! outcomes; v0.5.2 prevents the brain from accumulating
//! contradictions in the first place.
//!
//! The detector runs at `add_memory` / `add_user_memory` time:
//!   1. Embed the incoming text via the active embedder.
//!   2. Scan all active memories in the same scope, score cosine
//!      against the new vector.
//!   3. Pairs that exceed `DEFAULT_CONFLICT_THRESHOLD` (0.8) AND
//!      whose `normalized_text` differs from the new text get
//!      flagged as a conflict.
//!   4. The match is recorded in `memory_conflicts` (idempotent on
//!      (new_memory_id, existing_memory_id)) and a one-line
//!      warning is printed by the caller.
//!
//! Embedder gating:
//!   * NoopEmbedder → empty result, no DB writes. Lean builds keep
//!     v0.4.x behavior.
//!   * Cross-model rows (embedding_model != active model_id) are
//!     skipped — cosine across models is meaningless. A subsequent
//!     `kimetsu brain reindex` would rehydrate them under the
//!     active model and let the next ingest catch the conflict.
//!
//! Resolution policy:
//!   v0.5.2 surfaces conflicts but does NOT block the write. The
//!   new memory is accepted; the operator reviews open conflicts
//!   via `kimetsu brain memory conflicts` and decides which to
//!   invalidate. Surfacing > blocking: a blocked write loses the
//!   user's intent; a logged write loses nothing because the
//!   operator can always invalidate after the fact.

use kimetsu_core::KimetsuResult;
use kimetsu_core::ids::new_id;
use kimetsu_core::memory::{MemoryScope, normalize_memory_text};
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::embeddings::{Embedder, cosine_similarity, decode_embedding};

/// v1.0: config-aware conflict-detection gate.
///
/// Resolution precedence (mirrors `user_brain_enabled_with`):
///   1. `KIMETSU_DETECT_CONFLICTS` env is set → its value wins.
///      Disable values (`0` / `false` / `off` / `no`) → false.
///      Any other non-empty value → true.
///   2. Env unset → `config_value` governs.
///   3. Default (when no config and no env) → true.
///
/// Call sites in `add_memory` and `propose_or_merge_memory` check this
/// before invoking `detect_and_record` / `find_potential_conflicts`.
pub fn conflict_detection_enabled(config_value: bool) -> bool {
    match std::env::var("KIMETSU_DETECT_CONFLICTS") {
        Ok(raw) => {
            let v = raw.trim().to_ascii_lowercase();
            if v.is_empty() {
                // Empty string — treat as unset, fall through to config.
                config_value
            } else {
                // Any explicit disable value turns it off; everything else on.
                !matches!(v.as_str(), "0" | "false" | "off" | "no")
            }
        }
        // Env unset → config governs.
        Err(_) => config_value,
    }
}

/// Default cosine-similarity threshold above which two memories
/// (with differing normalized text) are flagged as a potential
/// conflict. 0.8 is BGE-small-en-v1.5's empirical "same concept"
/// floor — tighter than 0.7 (which catches loosely related ideas)
/// and looser than 0.9 (which only fires on near-paraphrases).
pub const DEFAULT_CONFLICT_THRESHOLD: f32 = 0.8;

/// Default number of nearest existing memories to evaluate per
/// ingest. We don't need many — if more than 3 capsules
/// simultaneously cross the threshold, the deeper bug is duplicate
/// concepts in the corpus, not a conflict with this one new write.
pub const DEFAULT_TOP_K: u32 = 3;

/// A single conflict-detection hit. Returned by
/// [`find_potential_conflicts`]; persisted by [`record_conflict`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConflictHit {
    pub existing_memory_id: String,
    pub existing_kind: String,
    pub existing_text: String,
    pub similarity: f32,
}

/// A persisted conflict row joined with both memories' text for
/// CLI / MCP display. Used by [`list_unresolved_conflicts`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConflictReport {
    pub conflict_id: String,
    pub new_memory_id: String,
    pub new_text: String,
    pub existing_memory_id: String,
    pub existing_text: String,
    pub scope: String,
    pub kind: String,
    pub similarity: f32,
    pub detected_at: String,
    pub resolved_at: Option<String>,
    pub resolution: Option<String>,
}

/// Fix 4c: ANN-based conflict detection.
///
/// Accepts the **precomputed query vector** (already embedded by the add path)
/// instead of re-embedding — halves embedding cost per add. Uses the usearch
/// ANN index to fetch a small candidate pool (≤ max(top_k * 8, 64) rows), then
/// scores only that pool with exact cosine, never full-scanning the corpus.
///
/// On non-embeddings builds (lean mode, or ANN query failure) we fall back to
/// the scope-filtered SQL scan so the function stays correct on lean builds.
///
/// `exclude_id`: the memory_id of the newly-added memory, excluded from the
/// conflict scan (a memory must not conflict with itself).
///
/// Pre-existing memories (upgraded brains) enter the usearch index on the next
/// retrieval's reconcile (see `crate::ann`), so conflict detection is
/// best-effort until then — acceptable per the v0.5.2 policy of "surface >
/// block".
pub fn find_potential_conflicts(
    conn: &Connection,
    scope: &MemoryScope,
    new_text: &str,
    embedder: &dyn Embedder,
    top_k: u32,
    threshold: f32,
) -> KimetsuResult<Vec<ConflictHit>> {
    find_potential_conflicts_with_vec(
        conn, scope, new_text, None, embedder, None, top_k, threshold,
    )
}

/// Internal: full signature used by `detect_and_record` when a precomputed
/// embedding is available (avoids re-embedding at conflict-scan time).
///
/// - `precomputed_vec`: the embedding produced by `embed_and_persist` for the
///   new memory.  When `None`, we embed `new_text` here (original behavior).
/// - `exclude_id`: the new memory's own id, excluded so a memory is never
///   flagged as conflicting with itself.
#[allow(clippy::too_many_arguments)]
pub(crate) fn find_potential_conflicts_with_vec(
    conn: &Connection,
    scope: &MemoryScope,
    new_text: &str,
    precomputed_vec: Option<&[f32]>,
    embedder: &dyn Embedder,
    exclude_id: Option<&str>,
    top_k: u32,
    threshold: f32,
) -> KimetsuResult<Vec<ConflictHit>> {
    if embedder.is_noop() {
        return Ok(Vec::new());
    }

    // Use the precomputed vector when available, else embed now.
    let new_vec: Vec<f32>;
    let query_vec: &[f32] = if let Some(v) = precomputed_vec {
        v
    } else {
        new_vec = embedder
            .embed(new_text)
            .map_err(|e| format!("embedder failed during conflict scan: {e}"))?;
        if new_vec.len() != embedder.dim() {
            return Err(format!(
                "embedder {} returned {} dims, expected {}",
                embedder.model_id(),
                new_vec.len(),
                embedder.dim()
            )
            .into());
        }
        &new_vec
    };

    let new_normalized = normalize_memory_text(new_text);
    let scope_label = scope.to_string();
    let active_model = embedder.model_id();
    // Pool size for ANN candidate fetch: at least 64, at least top_k * 8.
    // Only used on embeddings builds; suppress the lint on lean builds.
    #[cfg_attr(not(feature = "embeddings"), allow(unused_variables))]
    let pool_size = (top_k * 8).max(64) as i64;

    // Fix 4c: ANN path — query the usearch index for a small candidate pool.
    // Only available on embeddings builds (the ANN index is lean-build absent).
    #[cfg(feature = "embeddings")]
    {
        let handle = crate::ann::handle_for_query(conn, query_vec.len(), active_model)?;
        let ann_rowids: Vec<i64> = handle
            .read()
            .unwrap_or_else(|p| p.into_inner())
            .search(query_vec, pool_size as usize)?
            .into_iter()
            .map(|(rowid, _)| rowid)
            .collect();

        if !ann_rowids.is_empty() {
            // Fetch full rows for the ANN pool.
            let placeholders: String = ann_rowids
                .iter()
                .enumerate()
                .map(|(i, _)| format!("?{}", i + 1))
                .collect::<Vec<_>>()
                .join(", ");
            let sql = format!(
                "SELECT memory_id, kind, text, normalized_text, embedding, embedding_model
                 FROM   memories
                 WHERE  invalidated_at IS NULL
                   AND  scope = '{scope_label}'
                   AND  embedding_model = '{active_model}'
                   AND  rowid IN ({placeholders})"
            );
            let mut stmt = conn.prepare(&sql)?;
            let params_vec: Vec<&dyn rusqlite::ToSql> = ann_rowids
                .iter()
                .map(|n| n as &dyn rusqlite::ToSql)
                .collect();
            let rows_iter = stmt.query_map(params_vec.as_slice(), |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, Vec<u8>>(4)?,
                ))
            })?;

            let mut hits: Vec<ConflictHit> = Vec::new();
            for row in rows_iter {
                let (existing_id, kind, text, normalized, bytes) = row?;
                // Skip: same normalized text (dedup, not conflict).
                if normalized == new_normalized {
                    continue;
                }
                // Skip: the new memory itself.
                if let Some(excl) = exclude_id {
                    if existing_id == excl {
                        continue;
                    }
                }
                let Ok(existing_vec) = decode_embedding(&bytes, Some(query_vec.len())) else {
                    continue;
                };
                let sim = cosine_similarity(query_vec, &existing_vec);
                if sim >= threshold {
                    hits.push(ConflictHit {
                        existing_memory_id: existing_id,
                        existing_kind: kind,
                        existing_text: text,
                        similarity: sim,
                    });
                }
            }

            hits.sort_by(|a, b| {
                b.similarity
                    .partial_cmp(&a.similarity)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            hits.truncate(top_k as usize);
            return Ok(hits);
        }
    }

    // Lean / fallback: full scope-filtered SQL scan (original O(N) path).
    // Used on lean builds and when the ANN index is unavailable or its pool is
    // empty (e.g. a fresh upgraded brain not yet reconciled).
    find_potential_conflicts_sql(
        conn,
        &scope_label,
        &new_normalized,
        query_vec,
        active_model,
        exclude_id,
        top_k,
        threshold,
    )
}

/// Scope-filtered SQL scan — O(N) fallback used on lean builds and when the
/// ANN index is unavailable. This is the original `find_potential_conflicts`
/// body.
#[allow(clippy::too_many_arguments)]
fn find_potential_conflicts_sql(
    conn: &Connection,
    scope_label: &str,
    new_normalized: &str,
    query_vec: &[f32],
    active_model: &str,
    exclude_id: Option<&str>,
    top_k: u32,
    threshold: f32,
) -> KimetsuResult<Vec<ConflictHit>> {
    let mut stmt = conn.prepare(
        "
        SELECT memory_id, kind, text, normalized_text, embedding
        FROM memories
        WHERE scope = ?1
          AND invalidated_at IS NULL
          AND embedding IS NOT NULL
          AND embedding_model = ?2
        ",
    )?;
    let rows = stmt.query_map(params![scope_label, active_model], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, Vec<u8>>(4)?,
        ))
    })?;

    let mut hits: Vec<ConflictHit> = Vec::new();
    for row in rows {
        let (existing_id, kind, text, normalized, bytes) = row?;
        if normalized == new_normalized {
            continue;
        }
        if let Some(excl) = exclude_id {
            if existing_id == excl {
                continue;
            }
        }
        let Ok(existing_vec) = decode_embedding(&bytes, Some(query_vec.len())) else {
            continue;
        };
        let sim = cosine_similarity(query_vec, &existing_vec);
        if sim >= threshold {
            hits.push(ConflictHit {
                existing_memory_id: existing_id,
                existing_kind: kind,
                existing_text: text,
                similarity: sim,
            });
        }
    }

    hits.sort_by(|a, b| {
        b.similarity
            .partial_cmp(&a.similarity)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    hits.truncate(top_k as usize);
    Ok(hits)
}

/// Persist a single conflict pair. Idempotent on
/// (new_memory_id, existing_memory_id) via UNIQUE — a re-scan of
/// the same ingest won't double-write rows. Returns the
/// conflict_id (freshly minted or existing) so the caller can
/// chain follow-ups.
pub fn record_conflict(
    conn: &Connection,
    new_memory_id: &str,
    scope: &MemoryScope,
    kind: &str,
    hit: &ConflictHit,
) -> KimetsuResult<String> {
    // If a row for this pair already exists, return its id.
    let existing: Option<String> = conn
        .query_row(
            "
            SELECT conflict_id
            FROM memory_conflicts
            WHERE new_memory_id = ?1 AND existing_memory_id = ?2
            ",
            params![new_memory_id, hit.existing_memory_id],
            |row| row.get::<_, String>(0),
        )
        .optional()?;
    if let Some(id) = existing {
        return Ok(id);
    }
    let conflict_id = new_id().to_string();
    let detected_at = OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .map_err(|e| format!("timestamp format: {e}"))?;
    conn.execute(
        "
        INSERT INTO memory_conflicts (
            conflict_id, new_memory_id, existing_memory_id,
            scope, kind, similarity, detected_at
        )
        VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
        ",
        params![
            conflict_id,
            new_memory_id,
            hit.existing_memory_id,
            scope.to_string(),
            kind,
            hit.similarity as f64,
            detected_at,
        ],
    )?;
    Ok(conflict_id)
}

/// Convenience wrapper used by `add_memory` / `add_user_memory`:
/// run detection, persist each hit, return the number of recorded
/// conflicts so the caller can decide whether to surface a
/// warning to stderr.
///
/// `precomputed_vec`: when the caller already embedded `text` (e.g.
/// `embed_and_persist` just ran), pass that vector here to skip re-embedding.
/// Pass `None` to let the scan embed on demand (original behavior).
///
/// Best-effort: an error inside the scan is downgraded to "no
/// conflicts detected this round" + a stderr line, because we
/// never want conflict detection to fail an otherwise-valid memory
/// write.
pub fn detect_and_record(
    conn: &Connection,
    new_memory_id: &str,
    scope: &MemoryScope,
    kind: &str,
    text: &str,
    embedder: &dyn Embedder,
) -> usize {
    detect_and_record_with_vec(conn, new_memory_id, scope, kind, text, None, embedder)
}

/// Internal: full variant used by paths that have a precomputed embedding.
pub(crate) fn detect_and_record_with_vec(
    conn: &Connection,
    new_memory_id: &str,
    scope: &MemoryScope,
    kind: &str,
    text: &str,
    precomputed_vec: Option<&[f32]>,
    embedder: &dyn Embedder,
) -> usize {
    let hits = match find_potential_conflicts_with_vec(
        conn,
        scope,
        text,
        precomputed_vec,
        embedder,
        Some(new_memory_id),
        DEFAULT_TOP_K,
        DEFAULT_CONFLICT_THRESHOLD,
    ) {
        Ok(h) => h,
        Err(e) => {
            eprintln!("kimetsu-brain: conflict scan skipped: {e}");
            return 0;
        }
    };
    let mut recorded = 0usize;
    for hit in &hits {
        match record_conflict(conn, new_memory_id, scope, kind, hit) {
            Ok(_) => recorded += 1,
            Err(e) => {
                eprintln!(
                    "kimetsu-brain: failed to record conflict {} <-> {}: {e}",
                    new_memory_id, hit.existing_memory_id
                );
            }
        }
    }
    recorded
}

/// List open (unresolved) conflicts ordered by most recent first,
/// joined with both memories' text so the CLI can render rich
/// rows without a second query round-trip. `limit` is applied
/// after sorting; pass a generous default at the call site
/// (e.g. 50) since conflicts are sparse by construction.
pub fn list_unresolved_conflicts(
    conn: &Connection,
    limit: u32,
) -> KimetsuResult<Vec<ConflictReport>> {
    let mut stmt = conn.prepare(
        "
        SELECT c.conflict_id, c.new_memory_id, mn.text, c.existing_memory_id,
               me.text, c.scope, c.kind, c.similarity, c.detected_at,
               c.resolved_at, c.resolution
        FROM memory_conflicts c
        LEFT JOIN memories mn ON mn.memory_id = c.new_memory_id
        LEFT JOIN memories me ON me.memory_id = c.existing_memory_id
        WHERE c.resolved_at IS NULL
        ORDER BY c.detected_at DESC
        LIMIT ?1
        ",
    )?;
    let rows = stmt.query_map(params![limit], |row| {
        Ok(ConflictReport {
            conflict_id: row.get(0)?,
            new_memory_id: row.get(1)?,
            new_text: row.get::<_, Option<String>>(2)?.unwrap_or_default(),
            existing_memory_id: row.get(3)?,
            existing_text: row.get::<_, Option<String>>(4)?.unwrap_or_default(),
            scope: row.get(5)?,
            kind: row.get(6)?,
            similarity: row.get::<_, f64>(7)? as f32,
            detected_at: row.get(8)?,
            resolved_at: row.get(9)?,
            resolution: row.get(10)?,
        })
    })?;
    let mut out = Vec::new();
    for row in rows {
        out.push(row?);
    }
    Ok(out)
}

/// Mark a conflict as resolved with one of `'kept_new'`,
/// `'kept_existing'`, or `'kept_both'`. Returns true if a row was
/// updated (i.e. the id exists and was previously unresolved).
///
/// Side effect: when `resolution = 'kept_new'` the existing
/// memory is invalidated (resolution "I chose the new write");
/// `'kept_existing'` invalidates the new memory; `'kept_both'`
/// invalidates neither. Either invalidation is idempotent —
/// re-applying the same resolution is a no-op on the memory rows.
pub fn resolve_conflict(
    conn: &Connection,
    conflict_id: &str,
    resolution: &str,
) -> KimetsuResult<bool> {
    let resolution = resolution.trim();
    if !matches!(resolution, "kept_new" | "kept_existing" | "kept_both") {
        return Err(format!(
            "invalid conflict resolution {resolution:?}; expected kept_new | kept_existing | kept_both"
        )
        .into());
    }
    // Pull the pair so we know which (if any) memory to invalidate.
    let pair: Option<(String, String)> = conn
        .query_row(
            "
            SELECT new_memory_id, existing_memory_id
            FROM memory_conflicts
            WHERE conflict_id = ?1 AND resolved_at IS NULL
            ",
            params![conflict_id],
            |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
        )
        .optional()?;
    let Some((new_memory_id, existing_memory_id)) = pair else {
        return Ok(false);
    };

    let now = OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .map_err(|e| format!("timestamp format: {e}"))?;

    // Invalidate the losing side, if any. We do this BEFORE marking
    // the conflict resolved so a crash mid-resolve leaves the row
    // still actionable for the operator.
    let invalidation_reason = format!("v0.5.2 conflict {conflict_id} resolved as {resolution}");
    if resolution == "kept_new" {
        conn.execute(
            "
            UPDATE memories
            SET invalidated_at = COALESCE(invalidated_at, ?2),
                invalidated_reason = COALESCE(invalidated_reason, ?3)
            WHERE memory_id = ?1
            ",
            params![existing_memory_id, now, invalidation_reason],
        )?;
        #[cfg(feature = "embeddings")]
        crate::ann::on_invalidate(conn, &existing_memory_id);
    } else if resolution == "kept_existing" {
        conn.execute(
            "
            UPDATE memories
            SET invalidated_at = COALESCE(invalidated_at, ?2),
                invalidated_reason = COALESCE(invalidated_reason, ?3)
            WHERE memory_id = ?1
            ",
            params![new_memory_id, now, invalidation_reason],
        )?;
        #[cfg(feature = "embeddings")]
        crate::ann::on_invalidate(conn, &new_memory_id);
    }

    let updated = conn.execute(
        "
        UPDATE memory_conflicts
        SET resolved_at = ?2, resolution = ?3
        WHERE conflict_id = ?1 AND resolved_at IS NULL
        ",
        params![conflict_id, now, resolution],
    )?;
    Ok(updated > 0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embeddings::{NoopEmbedder, StubEmbedder, encode_embedding};
    use kimetsu_core::memory::normalize_memory_text;
    use rusqlite::Connection;

    fn open_test_brain() -> Connection {
        let conn = Connection::open_in_memory().expect("open in-memory");
        crate::schema::initialize(&conn).expect("init schema");
        conn
    }

    fn insert_memory(
        conn: &Connection,
        memory_id: &str,
        scope: &str,
        kind: &str,
        text: &str,
        embedder: &dyn Embedder,
    ) {
        let normalized = normalize_memory_text(text);
        let vec = embedder.embed(text).expect("embed test row");
        let blob = encode_embedding(&vec);
        conn.execute(
            "
            INSERT INTO memories (
                memory_id, scope, kind, text, normalized_text, confidence,
                source_event_id, provenance_snapshot_json, created_at,
                use_count, usefulness_score, embedding, embedding_model
            )
            VALUES (?1, ?2, ?3, ?4, ?5, 1.0, NULL, '{}',
                    '2026-01-01T00:00:00Z', 0, 0.0, ?6, ?7)
            ",
            params![
                memory_id,
                scope,
                kind,
                text,
                normalized,
                blob,
                embedder.model_id(),
            ],
        )
        .expect("insert");
        conn.execute(
            "INSERT INTO memories_fts (memory_id, text, kind, scope)
             VALUES (?1, ?2, ?3, ?4)",
            params![memory_id, text, kind, scope],
        )
        .expect("fts");
    }

    /// v0.5.2: NoopEmbedder MUST short-circuit to zero hits. Lean
    /// builds without --features embeddings keep v0.4.x behavior.
    #[test]
    fn noop_embedder_returns_no_conflicts() {
        let conn = open_test_brain();
        // Insert via stub so the row has an embedding; then scan with Noop.
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_existing",
            "global_user",
            "fact",
            "use thiserror for libraries",
            &stub,
        );
        let hits = find_potential_conflicts(
            &conn,
            &MemoryScope::GlobalUser,
            "use anyhow for libraries",
            &NoopEmbedder,
            DEFAULT_TOP_K,
            DEFAULT_CONFLICT_THRESHOLD,
        )
        .expect("scan");
        assert!(hits.is_empty(), "noop embedder should produce no hits");
    }

    /// v0.5.2: cross-model rows are skipped (cosine across models is
    /// meaningless). Critical for safety mid-reindex when some rows
    /// carry the old model id.
    #[test]
    fn cross_model_rows_are_skipped() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_xmodel",
            "global_user",
            "fact",
            "use thiserror",
            &stub,
        );
        // Stomp the model id to simulate a pre-reindex row.
        conn.execute(
            "UPDATE memories SET embedding_model = 'bge-small-en-v1.5' WHERE memory_id = 'm_xmodel'",
            [],
        )
        .expect("force mismatch");
        let hits = find_potential_conflicts(
            &conn,
            &MemoryScope::GlobalUser,
            "use thiserror everywhere", // very similar text
            &stub,
            DEFAULT_TOP_K,
            // Threshold low enough that the StubEmbedder would normally hit it.
            0.0,
        )
        .expect("scan");
        assert!(
            hits.is_empty(),
            "cross-model rows must be skipped from conflict scan"
        );
    }

    /// v0.5.2: identical normalized text is dedup territory, not a
    /// conflict. The scanner must filter exact matches out so a
    /// re-add doesn't generate a self-conflict.
    #[test]
    fn exact_match_is_not_flagged_as_conflict() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_exact",
            "global_user",
            "fact",
            "Use ripgrep",
            &stub,
        );
        let hits = find_potential_conflicts(
            &conn,
            &MemoryScope::GlobalUser,
            // Same after normalization.
            "use ripgrep",
            &stub,
            DEFAULT_TOP_K,
            0.0, // even at zero threshold, exact-text should be filtered
        )
        .expect("scan");
        assert!(
            hits.is_empty(),
            "exact normalized-text match should be dedup, not conflict"
        );
    }

    /// v0.5.2: a memory with text similar (high cosine) but
    /// different (post-normalization) gets flagged. Uses
    /// StubEmbedder where identical-token-bag inputs cosine to 1.0
    /// — we exploit that to construct a "shared concept, different
    /// wording" pair.
    #[test]
    fn similar_but_different_text_is_flagged() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        // StubEmbedder cosine is driven by tokenized hash buckets.
        // Two strings sharing 3 distinctive tokens out of 4 will
        // score very high cosine while normalizing differently.
        insert_memory(
            &conn,
            "m_existing",
            "global_user",
            "fact",
            "alpha beta gamma delta",
            &stub,
        );
        let hits = find_potential_conflicts(
            &conn,
            &MemoryScope::GlobalUser,
            "alpha beta gamma omega", // 3/4 shared tokens → high cosine
            &stub,
            DEFAULT_TOP_K,
            // Use a permissive threshold; the StubEmbedder cosine is
            // architecture-dependent so we want the test to fire on
            // the substantive overlap, not the exact 0.8.
            0.4,
        )
        .expect("scan");
        assert!(
            !hits.is_empty(),
            "high-cosine + different-normalized text should flag a conflict"
        );
        assert_eq!(hits[0].existing_memory_id, "m_existing");
        assert!(
            hits[0].similarity >= 0.4,
            "similarity should be >= threshold; got {}",
            hits[0].similarity
        );
    }

    /// v0.5.2: record_conflict is idempotent on
    /// (new_memory_id, existing_memory_id) — re-recording the same
    /// pair returns the original conflict_id instead of duplicating.
    #[test]
    fn record_conflict_is_idempotent() {
        let conn = open_test_brain();
        // Seed two memories so the FK-style assumption (memory rows
        // exist) holds for any downstream join.
        let stub = StubEmbedder::new();
        insert_memory(&conn, "m_new", "global_user", "fact", "alpha", &stub);
        insert_memory(&conn, "m_old", "global_user", "fact", "beta", &stub);
        let hit = ConflictHit {
            existing_memory_id: "m_old".to_string(),
            existing_kind: "fact".to_string(),
            existing_text: "beta".to_string(),
            similarity: 0.85,
        };
        let id1 = record_conflict(&conn, "m_new", &MemoryScope::GlobalUser, "fact", &hit)
            .expect("record 1");
        let id2 = record_conflict(&conn, "m_new", &MemoryScope::GlobalUser, "fact", &hit)
            .expect("record 2");
        assert_eq!(id1, id2, "re-recording the same pair must return same id");
        // Confirm only one row landed.
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_conflicts", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(count, 1);
    }

    /// v0.5.2: list_unresolved_conflicts joins memory text and
    /// returns rows ordered by detected_at DESC. Resolved rows are
    /// excluded.
    #[test]
    fn list_unresolved_excludes_resolved_rows() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_new1",
            "global_user",
            "fact",
            "use thiserror",
            &stub,
        );
        insert_memory(&conn, "m_old1", "global_user", "fact", "use anyhow", &stub);
        insert_memory(
            &conn,
            "m_new2",
            "global_user",
            "fact",
            "tabs over spaces",
            &stub,
        );
        insert_memory(
            &conn,
            "m_old2",
            "global_user",
            "fact",
            "spaces over tabs",
            &stub,
        );

        let hit1 = ConflictHit {
            existing_memory_id: "m_old1".to_string(),
            existing_kind: "fact".to_string(),
            existing_text: "use anyhow".to_string(),
            similarity: 0.9,
        };
        let hit2 = ConflictHit {
            existing_memory_id: "m_old2".to_string(),
            existing_kind: "fact".to_string(),
            existing_text: "spaces over tabs".to_string(),
            similarity: 0.85,
        };
        let cid1 =
            record_conflict(&conn, "m_new1", &MemoryScope::GlobalUser, "fact", &hit1).unwrap();
        let _cid2 =
            record_conflict(&conn, "m_new2", &MemoryScope::GlobalUser, "fact", &hit2).unwrap();

        // Resolve the first conflict (kept_both — neither
        // invalidated); both should still be visible only via the
        // second listing.
        assert!(resolve_conflict(&conn, &cid1, "kept_both").unwrap());

        let open = list_unresolved_conflicts(&conn, 50).unwrap();
        assert_eq!(open.len(), 1, "only the unresolved conflict should list");
        assert_eq!(open[0].new_memory_id, "m_new2");
        assert_eq!(open[0].existing_memory_id, "m_old2");
        assert_eq!(open[0].new_text, "tabs over spaces");
        assert_eq!(open[0].existing_text, "spaces over tabs");
    }

    /// v0.5.2: resolve_conflict with `kept_new` invalidates the
    /// existing memory; `kept_existing` invalidates the new one;
    /// `kept_both` leaves both active.
    #[test]
    fn resolve_conflict_invalidates_loser_side() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        for (mid, text) in [
            ("m_keep_new", "alpha"),
            ("m_old_loses", "beta"),
            ("m_new_loses", "gamma"),
            ("m_keep_existing", "delta"),
            ("m_both_a", "epsilon"),
            ("m_both_b", "zeta"),
        ] {
            insert_memory(&conn, mid, "global_user", "fact", text, &stub);
        }
        let mk_hit = |old: &str| ConflictHit {
            existing_memory_id: old.to_string(),
            existing_kind: "fact".to_string(),
            existing_text: "x".to_string(),
            similarity: 0.9,
        };

        let c_kept_new = record_conflict(
            &conn,
            "m_keep_new",
            &MemoryScope::GlobalUser,
            "fact",
            &mk_hit("m_old_loses"),
        )
        .unwrap();
        let c_kept_existing = record_conflict(
            &conn,
            "m_new_loses",
            &MemoryScope::GlobalUser,
            "fact",
            &mk_hit("m_keep_existing"),
        )
        .unwrap();
        let c_both = record_conflict(
            &conn,
            "m_both_a",
            &MemoryScope::GlobalUser,
            "fact",
            &mk_hit("m_both_b"),
        )
        .unwrap();

        assert!(resolve_conflict(&conn, &c_kept_new, "kept_new").unwrap());
        assert!(resolve_conflict(&conn, &c_kept_existing, "kept_existing").unwrap());
        assert!(resolve_conflict(&conn, &c_both, "kept_both").unwrap());

        let invalidated_at: Vec<(String, Option<String>)> = {
            let mut stmt = conn
                .prepare("SELECT memory_id, invalidated_at FROM memories ORDER BY memory_id")
                .unwrap();
            stmt.query_map([], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, Option<String>>(1)?))
            })
            .unwrap()
            .map(|r| r.unwrap())
            .collect()
        };

        let map: std::collections::HashMap<_, _> = invalidated_at.into_iter().collect();
        // kept_new → existing invalidated
        assert!(map["m_keep_new"].is_none(), "winner should stay active");
        assert!(
            map["m_old_loses"].is_some(),
            "kept_new must invalidate the existing memory"
        );
        // kept_existing → new invalidated
        assert!(
            map["m_keep_existing"].is_none(),
            "winner (existing) should stay active"
        );
        assert!(
            map["m_new_loses"].is_some(),
            "kept_existing must invalidate the new memory"
        );
        // kept_both → neither invalidated
        assert!(
            map["m_both_a"].is_none() && map["m_both_b"].is_none(),
            "kept_both should leave both memories active"
        );
    }

    /// v0.5.2: re-resolving the same conflict is a no-op (returns
    /// false on the second call) and does NOT re-stamp
    /// `invalidated_at`. Critical so an operator can't accidentally
    /// rewrite history by re-running `resolve`.
    #[test]
    fn resolve_conflict_is_idempotent() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(&conn, "m_new", "global_user", "fact", "x", &stub);
        insert_memory(&conn, "m_old", "global_user", "fact", "y", &stub);
        let hit = ConflictHit {
            existing_memory_id: "m_old".to_string(),
            existing_kind: "fact".to_string(),
            existing_text: "y".to_string(),
            similarity: 0.95,
        };
        let cid = record_conflict(&conn, "m_new", &MemoryScope::GlobalUser, "fact", &hit).unwrap();
        assert!(resolve_conflict(&conn, &cid, "kept_new").unwrap());
        assert!(
            !resolve_conflict(&conn, &cid, "kept_existing").unwrap(),
            "second resolve must return false (already resolved)"
        );
    }

    /// v0.5.2: detect_and_record returns 0 + writes nothing under
    /// NoopEmbedder. End-to-end version of the noop-skip rule.
    #[test]
    fn detect_and_record_noop_writes_nothing() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_existing",
            "global_user",
            "fact",
            "alpha beta",
            &stub,
        );
        insert_memory(&conn, "m_new", "global_user", "fact", "alpha gamma", &stub);
        let recorded = detect_and_record(
            &conn,
            "m_new",
            &MemoryScope::GlobalUser,
            "fact",
            "alpha gamma",
            &NoopEmbedder,
        );
        assert_eq!(recorded, 0);
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_conflicts", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(count, 0);
    }

    /// v0.5.2: invalid resolution strings are rejected before any
    /// DB write happens. Belt-and-suspenders so a typo from the CLI
    /// doesn't silently mark a conflict as "resolved" with garbage.
    #[test]
    fn resolve_conflict_rejects_invalid_resolution_strings() {
        let conn = open_test_brain();
        let err = resolve_conflict(&conn, "ignored", "delete_them_all").unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("invalid conflict resolution"), "got: {msg}");
    }

    // ------------------------------------------------------------------
    // Fix 2: conflict_detection_enabled off-switch
    // ------------------------------------------------------------------

    /// Fix 2: conflict_detection_enabled returns false when env is set to a
    /// disable value. Tests the env > config precedence.
    #[test]
    fn conflict_detection_enabled_env_disable_overrides_config_true() {
        let lock = crate::user_brain::test_env_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        let prev = std::env::var("KIMETSU_DETECT_CONFLICTS").ok();
        for v in ["0", "false", "off", "no"] {
            unsafe {
                std::env::set_var("KIMETSU_DETECT_CONFLICTS", v);
            }
            assert!(
                !conflict_detection_enabled(true),
                "env={v:?} must disable even when config=true"
            );
        }
        // Restore.
        unsafe {
            match prev {
                Some(v) => std::env::set_var("KIMETSU_DETECT_CONFLICTS", v),
                None => std::env::remove_var("KIMETSU_DETECT_CONFLICTS"),
            }
        }
        drop(lock);
    }

    /// Fix 2: conflict_detection_enabled respects config=false when env is unset.
    #[test]
    fn conflict_detection_enabled_config_false_when_env_unset() {
        let lock = crate::user_brain::test_env_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        let prev = std::env::var("KIMETSU_DETECT_CONFLICTS").ok();
        unsafe {
            std::env::remove_var("KIMETSU_DETECT_CONFLICTS");
        }
        assert!(
            !conflict_detection_enabled(false),
            "config=false + env unset must be disabled"
        );
        assert!(
            conflict_detection_enabled(true),
            "config=true + env unset must be enabled"
        );
        unsafe {
            match prev {
                Some(v) => std::env::set_var("KIMETSU_DETECT_CONFLICTS", v),
                None => std::env::remove_var("KIMETSU_DETECT_CONFLICTS"),
            }
        }
        drop(lock);
    }

    /// Fix 2: with detect_conflicts=false (via env), add_memory of a near-
    /// duplicate records NO conflict in memory_conflicts.
    /// Uses find_potential_conflicts directly with config_value=false to test
    /// the gate — the actual add_memory path goes through project which requires
    /// disk, so we test the detection layer.
    #[test]
    fn off_switch_prevents_conflict_detection() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        // Insert a seed memory.
        insert_memory(
            &conn,
            "m_seed",
            "global_user",
            "fact",
            "alpha beta gamma delta",
            &stub,
        );

        // With detection disabled (config_value=false, env unset):
        let lock = crate::user_brain::test_env_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner());
        let prev = std::env::var("KIMETSU_DETECT_CONFLICTS").ok();
        unsafe {
            std::env::remove_var("KIMETSU_DETECT_CONFLICTS");
        }

        // Simulate what add_memory does when detect_conflicts=false.
        if conflict_detection_enabled(false) {
            // Should not reach here.
            panic!("detect_conflicts=false must disable the gate");
        }
        // No conflicts written.
        let count: i64 = conn
            .query_row("SELECT COUNT(*) FROM memory_conflicts", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(count, 0, "off-switch must prevent any conflict writes");

        // With detection enabled (default=true), the near-dup IS flagged.
        let hits = find_potential_conflicts(
            &conn,
            &MemoryScope::GlobalUser,
            "alpha beta gamma omega",
            &stub,
            DEFAULT_TOP_K,
            0.4,
        )
        .expect("scan");
        // Should fire (near-dup detected) to prove the test setup is valid.
        assert!(
            !hits.is_empty(),
            "when enabled, near-dup must be detected (test sanity check)"
        );

        unsafe {
            match prev {
                Some(v) => std::env::set_var("KIMETSU_DETECT_CONFLICTS", v),
                None => std::env::remove_var("KIMETSU_DETECT_CONFLICTS"),
            }
        }
        drop(lock);
    }

    // ------------------------------------------------------------------
    // Fix 4c: exclude_id — new memory must not conflict with itself
    // ------------------------------------------------------------------

    /// Fix 4c: the exclude_id mechanism prevents a memory from being flagged
    /// as conflicting with itself. This tests the SQL fallback path
    /// (which is always active on lean builds and serves as the correctness
    /// reference).
    #[test]
    fn exclude_id_prevents_self_conflict() {
        let conn = open_test_brain();
        let stub = StubEmbedder::new();
        insert_memory(
            &conn,
            "m_self",
            "global_user",
            "fact",
            "alpha beta gamma delta",
            &stub,
        );
        // Scan for conflicts of the same text, excluding m_self.
        let hits = find_potential_conflicts_with_vec(
            &conn,
            &MemoryScope::GlobalUser,
            "alpha beta gamma delta",
            None,
            &stub,
            Some("m_self"),
            DEFAULT_TOP_K,
            0.0, // zero threshold so anything would fire
        )
        .expect("scan");
        assert!(
            hits.is_empty(),
            "excluded memory must not appear as a conflict hit"
        );
    }
}