context-forge 0.8.0

Local-first persistent memory for LLM applications - turso + Tantivy BM25 retrieval, recency decay, token-budget context assembly, secret scrubbing, and optional local-LLM distillation.
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
use std::collections::{HashMap, HashSet};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

use crate::analysis::lexicon::Lexicons;

/// Classification configuration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClassificationConfig {
    /// Word proximity window for corrective detection (default: 5).
    pub corrective_proximity: usize,
    /// Minimum sessions for reinforcing classification (default: 3).
    pub reinforcing_min_sessions: usize,
    /// Minimum bigram overlap ratio over passage text for reinforcing
    /// classification (default: 0.6).
    pub reinforcing_overlap_threshold: f64,
}

impl Default for ClassificationConfig {
    fn default() -> Self {
        Self {
            corrective_proximity: 5,
            reinforcing_min_sessions: 3,
            reinforcing_overlap_threshold: 0.6,
        }
    }
}

/// Context about a passage needed for classification.
/// Keeps classification decoupled from core types.
#[derive(Debug, Clone)]
pub struct PassageContext {
    /// The passage text.
    pub passage_text: String,
    /// High-recurrence terms that triggered extraction of this passage.
    pub triggering_terms: Vec<String>,
    /// Session ID this passage belongs to.
    pub session_id: String,
    /// Source entry timestamp (Unix seconds).
    pub timestamp: i64,
}

/// A category of importance assigned to a passage during classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ImportanceCategory {
    /// The passage corrects or contradicts earlier information.
    Corrective,
    /// The passage records a state change (entity is now value).
    Stateful,
    /// The passage records a decision and its rationale.
    Decisive,
    /// The passage repeats or reinforces a recurring topic.
    Reinforcing,
}

/// A passage that has been classified into zero or more
/// [`ImportanceCategory`] values, with extracted entities/values where
/// applicable.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClassifiedPassage {
    /// The passage text.
    pub text: String,
    /// Categories assigned to this passage.
    pub categories: Vec<ImportanceCategory>,
    /// High-recurrence terms that triggered extraction of this passage.
    pub triggering_terms: Vec<String>,
    /// Session ID this passage belongs to.
    pub session_id: String,
    /// Source entry timestamp (Unix seconds).
    pub timestamp: i64,
    /// Extracted entity for stateful/decisive categories.
    pub entity: Option<String>,
    /// Extracted value for stateful category.
    pub value: Option<String>,
    /// Second entity for decisive category (entity pair).
    pub entity_pair: Option<(String, String)>,
    /// Whether this passage has been superseded by a newer one.
    ///
    /// Supersession is evaluated per-category (stateful or decisive),
    /// but this flag represents "superseded in at least one category."
    /// A multi-category passage marked superseded may still be the
    /// latest representative of another category it belongs to.
    /// Consumers should check category-specific supersession if needed.
    pub superseded: bool,
}

/// Classify passages into importance categories and apply supersession.
#[must_use]
#[allow(
    clippy::cast_precision_loss,
    reason = "Overlap ratio uses f64 by design for threshold comparisons"
)]
pub fn classify_passages(
    passages: &[PassageContext],
    lexicons: &Lexicons,
    config: &ClassificationConfig,
) -> Vec<ClassifiedPassage> {
    if passages.is_empty() {
        return Vec::new();
    }

    let classify_one = |passage: &PassageContext| {
        let mut categories: Vec<ImportanceCategory> = Vec::new();

        if is_corrective(passage, lexicons, config) {
            categories.push(ImportanceCategory::Corrective);
        }

        let state_match = detect_stateful(passage, lexicons);
        let (entity, value) = if let Some((state_entity, state_value)) = state_match {
            categories.push(ImportanceCategory::Stateful);
            (Some(state_entity), Some(state_value))
        } else {
            (None, None)
        };

        let entity_pair = if is_decisive(passage, lexicons) {
            categories.push(ImportanceCategory::Decisive);
            extract_entity_pair(passage)
        } else {
            None
        };

        ClassifiedPassage {
            text: passage.passage_text.clone(),
            categories,
            triggering_terms: passage.triggering_terms.clone(),
            session_id: passage.session_id.clone(),
            timestamp: passage.timestamp,
            entity,
            value,
            entity_pair,
            superseded: false,
        }
    };

    #[cfg(feature = "parallel")]
    let mut classified: Vec<ClassifiedPassage> = passages.par_iter().map(classify_one).collect();
    #[cfg(not(feature = "parallel"))]
    let mut classified: Vec<ClassifiedPassage> = passages.iter().map(classify_one).collect();

    apply_reinforcing(&mut classified, lexicons, config);
    apply_supersession(&mut classified);
    classified
}

fn is_corrective(
    passage: &PassageContext,
    lexicons: &Lexicons,
    config: &ClassificationConfig,
) -> bool {
    if passage
        .passage_text
        .trim_end()
        .trim_end_matches(['"', '\'', ')', ']', '}'])
        .ends_with('?')
    {
        return false;
    }

    let words = tokenize_words(&passage.passage_text.to_lowercase());
    if words.is_empty() {
        return false;
    }

    let negation_positions: Vec<usize> = lexicons
        .negation_markers
        .iter()
        .flat_map(|marker| find_marker_positions(&words, &marker.to_lowercase()))
        .collect();

    if negation_positions.is_empty() {
        return false;
    }

    let triggering_positions: Vec<usize> = passage
        .triggering_terms
        .iter()
        .flat_map(|term| find_term_positions(&words, &term.to_lowercase()))
        .collect();

    if triggering_positions.is_empty() {
        return false;
    }

    for negation_pos in &negation_positions {
        for term_pos in &triggering_positions {
            if usize::abs_diff(*negation_pos, *term_pos) <= config.corrective_proximity {
                return true;
            }
        }
    }

    false
}

fn detect_stateful(passage: &PassageContext, lexicons: &Lexicons) -> Option<(String, String)> {
    let passage_lower = passage.passage_text.to_lowercase();
    let mut matches: Vec<(usize, usize, String)> = Vec::new();
    for operator in &lexicons.state_operators {
        let operator_lower = operator.to_lowercase();
        for (start_index, _) in passage_lower.match_indices(&operator_lower) {
            let end_index = start_index + operator_lower.len();
            let operator_starts_with_alnum = operator_lower.as_bytes()[0].is_ascii_alphanumeric();
            let operator_ends_with_alnum =
                operator_lower.as_bytes()[operator_lower.len() - 1].is_ascii_alphanumeric();

            let has_start_boundary = !operator_starts_with_alnum
                || start_index == 0
                || !passage_lower.as_bytes()[start_index - 1].is_ascii_alphanumeric();
            let has_end_boundary = !operator_ends_with_alnum
                || end_index >= passage_lower.len()
                || !passage_lower.as_bytes()[end_index].is_ascii_alphanumeric();

            if has_start_boundary && has_end_boundary {
                matches.push((start_index, operator_lower.len(), operator_lower.clone()));
            }
        }
    }

    matches.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| right.1.cmp(&left.1)));

    for (start_index, operator_len, _) in matches {
        let before = &passage_lower[..start_index];
        let after = &passage_lower[start_index + operator_len..];

        let entity_words = tokenize_words(before);
        let value_words = tokenize_words(after);

        if entity_words.is_empty() || value_words.is_empty() {
            continue;
        }

        let entity_start = entity_words.len().saturating_sub(4);
        let entity = entity_words[entity_start..].join(" ");
        if !contains_ascii_alpha(&entity) {
            continue;
        }

        let value = value_words
            .into_iter()
            .take(6)
            .collect::<Vec<String>>()
            .join(" ");
        if value.is_empty() {
            continue;
        }

        return Some((entity, value));
    }

    None
}

fn is_decisive(passage: &PassageContext, lexicons: &Lexicons) -> bool {
    let passage_lower = passage.passage_text.to_lowercase();
    let has_comparison = has_marker_in_passage(&passage_lower, &lexicons.comparison_markers);
    let has_causal = has_marker_in_passage(&passage_lower, &lexicons.causal_connectors);

    has_comparison && has_causal
}

fn has_marker_in_passage(passage_lower: &str, markers: &[String]) -> bool {
    let words: Vec<String> = passage_lower
        .split_whitespace()
        .map(clean_for_comparison)
        .filter(|word| !word.is_empty())
        .collect();

    for marker in markers {
        let marker_lower = marker.to_lowercase();
        if marker_lower.contains(' ') {
            if passage_lower.contains(&marker_lower) {
                return true;
            }
        } else if words.iter().any(|word| word == &marker_lower) {
            return true;
        }
    }

    false
}

fn extract_entity_pair(passage: &PassageContext) -> Option<(String, String)> {
    let mut capitalized: Vec<String> = Vec::new();
    let mut at_sentence_start = true;

    for raw_word in passage.passage_text.split_whitespace() {
        let cleaned = clean_token(raw_word);
        if cleaned.is_empty() {
            at_sentence_start = raw_word_ends_sentence(raw_word);
            continue;
        }

        if !at_sentence_start
            && cleaned
                .chars()
                .next()
                .is_some_and(|character| character.is_ascii_uppercase())
            && !capitalized.contains(&cleaned)
        {
            capitalized.push(cleaned.clone());
        }

        at_sentence_start = raw_word_ends_sentence(raw_word);
    }

    if capitalized.len() >= 2 {
        return Some((capitalized[0].clone(), capitalized[1].clone()));
    }

    let mut proxies: Vec<String> = Vec::new();
    for term in &passage.triggering_terms {
        let trimmed = term.trim();
        if trimmed.is_empty() {
            continue;
        }
        if !proxies.contains(&trimmed.to_string()) {
            proxies.push(trimmed.to_string());
        }
    }

    if proxies.len() >= 2 {
        return Some((proxies[0].clone(), proxies[1].clone()));
    }

    None
}

#[allow(
    clippy::cast_precision_loss,
    clippy::implicit_hasher,
    reason = "Threshold math uses f64 and HashMap defaults are acceptable for local grouping"
)]
fn apply_reinforcing(
    passages: &mut [ClassifiedPassage],
    lexicons: &Lexicons,
    config: &ClassificationConfig,
) {
    let confirmation_sets: Vec<HashSet<String>> = passages
        .iter()
        .map(|passage| confirmation_tokens_in_passage(&passage.text, lexicons))
        .collect();

    let candidate_indices: Vec<usize> = confirmation_sets
        .iter()
        .enumerate()
        .filter_map(|(index, tokens)| if tokens.is_empty() { None } else { Some(index) })
        .collect();

    if candidate_indices.len() < config.reinforcing_min_sessions {
        return;
    }

    let mut graph: HashMap<usize, Vec<usize>> = HashMap::new();
    for index in &candidate_indices {
        graph.insert(*index, Vec::new());
    }

    for left_index in 0..candidate_indices.len() {
        for right_index in (left_index + 1)..candidate_indices.len() {
            let left = candidate_indices[left_index];
            let right = candidate_indices[right_index];

            if !shares_confirmation_token(&confirmation_sets[left], &confirmation_sets[right]) {
                continue;
            }

            let overlap = bigram_overlap_ratio(&passages[left].text, &passages[right].text);
            if overlap > config.reinforcing_overlap_threshold {
                if let Some(neighbors) = graph.get_mut(&left) {
                    neighbors.push(right);
                }
                if let Some(neighbors) = graph.get_mut(&right) {
                    neighbors.push(left);
                }
            }
        }
    }

    let mut visited: HashSet<usize> = HashSet::new();
    for index in candidate_indices {
        if visited.contains(&index) {
            continue;
        }

        let mut stack: Vec<usize> = vec![index];
        let mut component: Vec<usize> = Vec::new();

        while let Some(current) = stack.pop() {
            if !visited.insert(current) {
                continue;
            }

            component.push(current);
            if let Some(neighbors) = graph.get(&current) {
                for neighbor in neighbors {
                    if !visited.contains(neighbor) {
                        stack.push(*neighbor);
                    }
                }
            }
        }

        let distinct_sessions: HashSet<&str> = component
            .iter()
            .map(|component_index| passages[*component_index].session_id.as_str())
            .collect();

        if distinct_sessions.len() >= config.reinforcing_min_sessions {
            for component_index in component {
                if !passages[component_index]
                    .categories
                    .contains(&ImportanceCategory::Reinforcing)
                {
                    passages[component_index]
                        .categories
                        .push(ImportanceCategory::Reinforcing);
                }
            }
        }
    }
}

fn apply_supersession(passages: &mut [ClassifiedPassage]) {
    let mut stateful_groups: HashMap<String, Vec<usize>> = HashMap::new();
    for (index, passage) in passages.iter().enumerate() {
        if passage.categories.contains(&ImportanceCategory::Stateful) {
            if let Some(entity) = &passage.entity {
                let key = entity.trim().to_lowercase();
                if !key.is_empty() {
                    stateful_groups.entry(key).or_default().push(index);
                }
            }
        }
    }

    mark_group_superseded(passages, stateful_groups.values());

    let mut decisive_groups: HashMap<(String, String), Vec<usize>> = HashMap::new();
    for (index, passage) in passages.iter().enumerate() {
        if passage.categories.contains(&ImportanceCategory::Decisive) {
            if let Some((left, right)) = &passage.entity_pair {
                let mut pair = [left.trim().to_lowercase(), right.trim().to_lowercase()];
                pair.sort();
                decisive_groups
                    .entry((pair[0].clone(), pair[1].clone()))
                    .or_default()
                    .push(index);
            }
        }
    }

    mark_group_superseded(passages, decisive_groups.values());
}

fn mark_group_superseded<'a>(
    passages: &mut [ClassifiedPassage],
    groups: impl Iterator<Item = &'a Vec<usize>>,
) {
    for indices in groups {
        if indices.len() <= 1 {
            continue;
        }

        let latest = indices.iter().copied().max_by(|left, right| {
            passages[*left]
                .timestamp
                .cmp(&passages[*right].timestamp)
                // Tie-broken by input order: later index wins.
                .then_with(|| left.cmp(right))
        });

        if let Some(latest_index) = latest {
            for index in indices {
                if *index != latest_index {
                    passages[*index].superseded = true;
                }
            }
        }
    }
}

fn confirmation_tokens_in_passage(text: &str, lexicons: &Lexicons) -> HashSet<String> {
    let words = tokenize_words(&text.to_lowercase());
    let mut matched: HashSet<String> = HashSet::new();

    for token in &lexicons.confirmation_tokens {
        let token_lower = token.to_lowercase();
        if words.iter().any(|word| word == &token_lower) {
            matched.insert(token_lower);
        }
    }

    matched
}

fn shares_confirmation_token(left: &HashSet<String>, right: &HashSet<String>) -> bool {
    left.iter().any(|token| right.contains(token))
}

#[allow(
    clippy::cast_precision_loss,
    reason = "Overlap ratio uses f64 thresholding by configuration contract"
)]
fn bigram_overlap_ratio(text_a: &str, text_b: &str) -> f64 {
    let bigrams_a = text_bigrams(text_a);
    let bigrams_b = text_bigrams(text_b);

    let min_count = bigrams_a.len().min(bigrams_b.len());
    if min_count == 0 {
        return 0.0;
    }

    let intersection_count = bigrams_a.intersection(&bigrams_b).count();
    intersection_count as f64 / min_count as f64
}

fn text_bigrams(text: &str) -> HashSet<(String, String)> {
    let words: Vec<String> = text
        .split_whitespace()
        .map(|word| {
            word.to_lowercase()
                .chars()
                .filter(char::is_ascii_alphanumeric)
                .collect::<String>()
        })
        .filter(|word| !word.is_empty())
        .collect();

    let mut bigrams: HashSet<(String, String)> = HashSet::new();
    for pair in words.windows(2) {
        bigrams.insert((pair[0].clone(), pair[1].clone()));
    }

    bigrams
}

fn find_marker_positions(words: &[String], marker: &str) -> Vec<usize> {
    let marker_words: Vec<&str> = marker.split_whitespace().collect();
    if marker_words.is_empty() {
        return Vec::new();
    }

    if marker_words.len() == 1 {
        return words
            .iter()
            .enumerate()
            .filter_map(|(index, word)| {
                if *word == marker_words[0] {
                    Some(index)
                } else {
                    None
                }
            })
            .collect();
    }

    find_phrase_positions(words, &marker_words)
}

fn find_term_positions(words: &[String], term: &str) -> Vec<usize> {
    let term_words: Vec<&str> = term.split_whitespace().collect();
    if term_words.is_empty() {
        return Vec::new();
    }

    if term_words.len() == 1 {
        return words
            .iter()
            .enumerate()
            .filter_map(|(index, word)| {
                if *word == term_words[0] {
                    Some(index)
                } else {
                    None
                }
            })
            .collect();
    }

    find_phrase_positions(words, &term_words)
}

fn find_phrase_positions(words: &[String], phrase_words: &[&str]) -> Vec<usize> {
    if words.len() < phrase_words.len() {
        return Vec::new();
    }

    let mut positions: Vec<usize> = Vec::new();
    for index in 0..=(words.len() - phrase_words.len()) {
        let mut matches = true;
        for (offset, phrase_word) in phrase_words.iter().enumerate() {
            if words[index + offset] != *phrase_word {
                matches = false;
                break;
            }
        }
        if matches {
            positions.push(index);
        }
    }

    positions
}

fn tokenize_words(text: &str) -> Vec<String> {
    text.split_whitespace()
        .map(clean_token)
        .filter(|token| !token.is_empty())
        .collect()
}

fn clean_token(token: &str) -> String {
    token
        .trim_matches(|character: char| {
            !character.is_ascii_alphanumeric() && !matches!(character, '\'' | '-' | '_' | ':' | '=')
        })
        .trim_matches([':', '='])
        .to_string()
}

fn clean_for_comparison(token: &str) -> String {
    clean_token(token).to_lowercase()
}

fn contains_ascii_alpha(text: &str) -> bool {
    text.chars()
        .any(|character| character.is_ascii_alphabetic())
}

fn raw_word_ends_sentence(raw_word: &str) -> bool {
    raw_word
        .trim_end_matches(['"', '\'', ')', ']'])
        .ends_with(['.', '!', '?'])
}

#[cfg(test)]
mod tests {
    use super::{classify_passages, ClassificationConfig, ImportanceCategory, PassageContext};
    use crate::analysis::lexicon::Lexicons;

    fn passage(text: &str, terms: &[&str], session_id: &str, timestamp: i64) -> PassageContext {
        PassageContext {
            passage_text: text.to_string(),
            triggering_terms: terms.iter().map(|term| (*term).to_string()).collect(),
            session_id: session_id.to_string(),
            timestamp,
        }
    }

    fn default_config() -> ClassificationConfig {
        ClassificationConfig::default()
    }

    fn has_category(passage: &super::ClassifiedPassage, category: ImportanceCategory) -> bool {
        passage.categories.contains(&category)
    }

    #[test]
    fn empty_passages_returns_empty_vec() {
        let lexicons = Lexicons::default();
        let config = default_config();

        let result = classify_passages(&[], &lexicons, &config);
        assert!(result.is_empty());
    }

    #[test]
    fn no_category_match_has_empty_categories() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "General context discussion about implementation details.",
            &["context"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert_eq!(result.len(), 1);
        assert!(result[0].categories.is_empty());
        assert!(!result[0].superseded);
    }

    #[test]
    fn corrective_detection_matches_negation_near_trigger_term() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "We should not enable cache in production.",
            &["cache"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Corrective));
    }

    #[test]
    fn corrective_detection_skips_questions() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "Should we not use cache?",
            &["cache"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(!has_category(&result[0], ImportanceCategory::Corrective));
    }

    #[test]
    fn corrective_detection_proximity_boundary() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig {
            corrective_proximity: 3,
            ..ClassificationConfig::default()
        };

        let within = passage("not alpha beta cache", &["cache"], "session-a", 10);
        let beyond = passage("not alpha beta gamma cache", &["cache"], "session-b", 20);

        let result = classify_passages(&[within, beyond], &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Corrective));
        assert!(!has_category(&result[1], ImportanceCategory::Corrective));
    }

    #[test]
    fn stateful_detection_matches_explicit_operators() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![
            passage("Cache mode set to writeback", &["cache"], "session-a", 10),
            passage("Timeout changed to 30", &["timeout"], "session-a", 11),
            passage("PORT = 8080", &["port"], "session-a", 12),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Stateful));
        assert!(has_category(&result[1], ImportanceCategory::Stateful));
        assert!(has_category(&result[2], ImportanceCategory::Stateful));
    }

    #[test]
    fn stateful_rejects_bare_is() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "Context is important for robust agents.",
            &["context"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(!has_category(&result[0], ImportanceCategory::Stateful));
    }

    #[test]
    fn stateful_entity_requires_alphabetic_characters() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage("1234 = 5678", &["1234"], "session-a", 10)];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(!has_category(&result[0], ImportanceCategory::Stateful));
    }

    #[test]
    fn stateful_supersession_marks_older_passage() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![
            passage("Cache mode set to writeback", &["cache"], "session-a", 100),
            passage(
                "Cache mode set to writethrough",
                &["cache"],
                "session-b",
                200,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Stateful));
        assert!(has_category(&result[1], ImportanceCategory::Stateful));
        assert!(result[0].superseded);
        assert!(!result[1].superseded);
    }

    #[test]
    fn stateful_supersession_equal_timestamps() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig::default();
        let passages = vec![
            PassageContext {
                passage_text: "Server IP: changed to 10.0.0.1".to_string(),
                triggering_terms: vec!["server".to_string()],
                session_id: "s1".to_string(),
                timestamp: 100,
            },
            PassageContext {
                passage_text: "Server IP: changed to 10.0.0.2".to_string(),
                triggering_terms: vec!["server".to_string()],
                session_id: "s2".to_string(),
                timestamp: 100,
            },
        ];
        let result = classify_passages(&passages, &lexicons, &config);
        let stateful: Vec<_> = result
            .iter()
            .filter(|passage| passage.categories.contains(&ImportanceCategory::Stateful))
            .collect();
        assert_eq!(stateful.len(), 2);
        let superseded_count = result.iter().filter(|passage| passage.superseded).count();
        assert_eq!(superseded_count, 1);
    }

    #[test]
    fn decisive_detection_requires_comparison_and_causal() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "We switched from Redis to Memcached because latency dropped.",
            &["redis", "memcached"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Decisive));
    }

    #[test]
    fn decisive_requires_both_signals() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let comparison_only = passage(
            "We switched from Redis to Memcached yesterday.",
            &["redis", "memcached"],
            "session-a",
            10,
        );
        let causal_only = passage(
            "Latency dropped because pipeline tuning improved.",
            &["latency", "pipeline"],
            "session-b",
            11,
        );

        let result = classify_passages(&[comparison_only, causal_only], &lexicons, &config);
        assert!(!has_category(&result[0], ImportanceCategory::Decisive));
        assert!(!has_category(&result[1], ImportanceCategory::Decisive));
    }

    #[test]
    fn decisive_supersession_marks_older_entity_pair() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![
            passage(
                "We switched from Redis to Memcached because latency improved.",
                &["redis", "memcached"],
                "session-a",
                10,
            ),
            passage(
                "We switched from Memcached to Redis because cache misses rose.",
                &["memcached", "redis"],
                "session-b",
                20,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Decisive));
        assert!(has_category(&result[1], ImportanceCategory::Decisive));
        assert!(result[0].superseded);
        assert!(!result[1].superseded);
    }

    #[test]
    fn reinforcing_detection_with_three_sessions() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig {
            reinforcing_min_sessions: 3,
            reinforcing_overlap_threshold: 0.6,
            ..ClassificationConfig::default()
        };
        let inputs = vec![
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s1",
                1,
            ),
            passage(
                "Yes always run cargo test before committing code",
                &["cargo", "test"],
                "s2",
                2,
            ),
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s3",
                3,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(result
            .iter()
            .all(|passage| has_category(passage, ImportanceCategory::Reinforcing)));
    }

    #[test]
    fn reinforcing_below_threshold_with_two_sessions() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig {
            reinforcing_min_sessions: 3,
            reinforcing_overlap_threshold: 0.6,
            ..ClassificationConfig::default()
        };
        let inputs = vec![
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s1",
                1,
            ),
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s2",
                2,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(result
            .iter()
            .all(|passage| !has_category(passage, ImportanceCategory::Reinforcing)));
    }

    #[test]
    fn reinforcing_different_text_same_terms_rejected() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig {
            reinforcing_min_sessions: 3,
            reinforcing_overlap_threshold: 0.6,
            ..ClassificationConfig::default()
        };
        let inputs = vec![
            passage(
                "Yes start the docker container on boot",
                &["docker"],
                "s1",
                1,
            ),
            passage(
                "Confirmed docker causes memory leak issues",
                &["docker"],
                "s2",
                2,
            ),
            passage(
                "Good the docker container starts on boot",
                &["docker"],
                "s3",
                3,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(result
            .iter()
            .all(|passage| !has_category(passage, ImportanceCategory::Reinforcing)));
    }

    #[test]
    fn reinforcing_high_bigram_overlap_triggers() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig {
            reinforcing_min_sessions: 3,
            reinforcing_overlap_threshold: 0.6,
            ..ClassificationConfig::default()
        };
        let inputs = vec![
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s1",
                1,
            ),
            passage(
                "Yes run cargo test before committing code",
                &["cargo", "test"],
                "s2",
                2,
            ),
            passage(
                "Yes always run cargo test before committing",
                &["cargo", "test"],
                "s3",
                3,
            ),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(result
            .iter()
            .all(|passage| has_category(passage, ImportanceCategory::Reinforcing)));
    }

    #[test]
    fn multi_category_passage_can_be_corrective_and_decisive() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "We should not use Redis and switched to Memcached because costs dropped.",
            &["redis", "memcached"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Corrective));
        assert!(has_category(&result[0], ImportanceCategory::Decisive));
    }

    #[test]
    fn stateful_is_now_operator_matches() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![passage(
            "Primary database is now PostgreSQL 16",
            &["database"],
            "session-a",
            10,
        )];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(has_category(&result[0], ImportanceCategory::Stateful));
    }

    #[test]
    fn state_operators_are_phrases_set_alone_does_not_match() {
        let lexicons = Lexicons::default();
        let config = default_config();
        let inputs = vec![
            passage("We set cache flags manually", &["cache"], "session-a", 10),
            passage("Cache is set to strict mode", &["cache"], "session-b", 11),
        ];

        let result = classify_passages(&inputs, &lexicons, &config);
        assert!(!has_category(&result[0], ImportanceCategory::Stateful));
        assert!(has_category(&result[1], ImportanceCategory::Stateful));
    }

    #[test]
    fn stateful_reset_does_not_match_set_to_operator() {
        let lexicons = Lexicons::default();
        let config = ClassificationConfig::default();
        let passages = vec![PassageContext {
            passage_text: "Reset to factory defaults immediately".to_string(),
            triggering_terms: vec!["factory".to_string()],
            session_id: "s1".to_string(),
            timestamp: 10,
        }];
        let result = classify_passages(&passages, &lexicons, &config);
        assert!(!result[0].categories.contains(&ImportanceCategory::Stateful));
    }
}