knowyourbusiness 0.3.4

Git-backed, searchable knowledge base and incident tracker for AI agent fleets
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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
/*
 * KYB (Know Your Business) — git-backed knowledge base and incident tracker for AI agent fleets
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/kyb
 * SPDX-License-Identifier: MIT
 */

use crate::deadline::Deadline;
use crate::model::{Entry, Window, KIND_KNOWLEDGE};
use crate::store::Store;
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use tantivy::collector::{Count, DocSetCollector, TopDocs};
use tantivy::query::{AllQuery, BooleanQuery, Occur, Query, QueryParser, RangeQuery, TermQuery};
use tantivy::schema::{
    Field, IndexRecordOption, Schema, TextFieldIndexing, TextOptions, Value, FAST, INDEXED, STORED,
    STRING,
};
use tantivy::tokenizer::{Language, LowerCaser, SimpleTokenizer, Stemmer, TextAnalyzer};
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::{Arc, Mutex, RwLock};
use tantivy::{Index, IndexReader, IndexWriter, Order, ReloadPolicy, TantivyDocument, Term};

/// Russian stemmer: bodies are mostly Russian; latin identifiers
/// (CreateOrUpdateStream, NATS) pass through unchanged after lowercasing.
const ANALYZER: &str = "ru_stem";

pub struct Fields {
    doc_id: Field,
    key: Field,
    /// Tokenized copy of the key ("nats-streams" -> "nats streams") so a plain
    /// query matches the key itself, not just the prose.
    key_text: Field,
    title: Field,
    body: Field,
    /// Exact tag terms, for filtering.
    tags: Field,
    /// Tokenized copy of the tags, so free-text search finds an entry by its
    /// topic even when the tag word never appears in the body.
    tags_text: Field,
    /// "knowledge" | "incident" — exact term, for the kind filter.
    kind: Field,
    /// Incident metadata as exact terms (filters) …
    service: Field,
    status: Field,
    severity: Field,
    /// Task priority as an exact term — same shape as status/severity, so the
    /// `?priority=` filter is one more clause in the same BooleanQuery.
    priority: Field,
    /// Task ownership as exact terms: "what is agent-a holding" and "what hangs
    /// under this task" are filters, not free-text questions.
    assignee: Field,
    parent_task: Field,
    hosts: Field,
    knowledge: Field,
    /// Stored only: what a blocked task waits on rides on the hit; it is state,
    /// not prose people grep for.
    blocked_reason: Field,
    /// Tokenized + stored: "how did we fix X before" must be searchable.
    resolution: Field,
    /// Tokenized + stored: the "is it still happening?" check often names the
    /// exact tables/metrics people search by.
    detection: Field,
    /// Stored only (JSON): affected windows ride on the hit, nobody greps them.
    affected: Field,
    /// Stored only (JSON): a task's deadline rides on the hit, so the deadline
    /// block of every response is one query over the task heads, not a disk walk.
    deadline: Field,
    started_at: Field,
    detected_at: Field,
    mitigated_at: Field,
    resolved_at: Field,
    /// … and one tokenized copy of service+hosts+knowledge keys, so free text
    /// like "orders api" reaches an incident even when the prose never says it.
    meta_text: Field,
    sha: Field,
    committed_at: Field,
    /// Monotonic insertion order. Git commit times have 1-second granularity,
    /// so a burst of agent writes ties on committed_at and "recent" ordering
    /// becomes a coin flip; seq breaks the tie exactly.
    seq: Field,
    is_head: Field,
    updated_at: Field,
}

/// Retracted knowledge: key -> (committed_at, seq) of every deletion. Not a
/// document - nothing should ever find a tombstone - but the as_of snapshot
/// needs to know that a key had stopped existing by T.
type Tombstones = HashMap<String, Vec<(i64, u64)>>;

/// What a search reads: the documents of one commit and the tombstones that
/// belong to that same commit, published together by commit_and_reload. A
/// search holds one generation for its whole run. The two must never be paired
/// across generations: reindex renumbers every document, so a tombstone's seq
/// only means something next to the documents it was built with.
struct Generation {
    searcher: tantivy::Searcher,
    tombstones: Tombstones,
}

pub struct SearchIndex {
    pub index: Index,
    /// Reloaded only by commit_and_reload, never on its own: a reader that
    /// reloads behind our back would publish documents without their tombstones
    /// (and reindex's intermediate empty commit as a generation of its own).
    pub reader: IndexReader,
    fields: Fields,
    /// Next insertion sequence number; rebuilt by reindex(), advanced by
    /// upsert_head() and retract(). Startup always reindexes, so it is never stale.
    next_seq: AtomicU64,
    /// The tombstones the next commit_and_reload will publish, mutated only by
    /// whoever holds the IndexWriter: rebuilt by reindex(), extended by retract().
    pending_tombstones: Mutex<Tombstones>,
    generation: RwLock<Arc<Generation>>,
}

#[derive(serde::Serialize)]
pub struct Hit {
    pub key: String,
    pub title: String,
    pub kind: String,
    pub body: String,
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub service: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub hosts: Vec<String>,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub severity: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub status: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub priority: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub blocked_reason: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub assignee: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub parent_task: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub knowledge: Vec<String>,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub resolution: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub detection: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub affected: Vec<Window>,
    /// due, hard, remind_days, waits_on, expected - each only when set.
    #[serde(flatten)]
    pub deadline: Deadline,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub started_at: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub detected_at: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub mitigated_at: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub resolved_at: String,
    pub sha: String,
    pub committed_at: String,
    pub is_head: bool,
    pub updated_at: String,
    pub score: f32,
}

#[derive(Default)]
pub struct SearchOpts {
    pub tags: Vec<String>,
    pub history: bool,
    /// Unix seconds: answer as the base stood at that instant. Searches history
    /// and collapses to the newest version of each key committed at or before
    /// it, so a superseded value is returned when - and only when - it was still
    /// the current one. `history` is about *all* versions; this is about *one*
    /// moment, and they are different questions.
    pub as_of: Option<i64>,
    /// Unix seconds, inclusive: which entries moved inside this window. Answers
    /// "what changed while I was away", which is the question an agent taking
    /// over from another actually has - and which neither `history` (all time)
    /// nor `as_of` (one instant) can express.
    pub changed_between: Option<(i64, i64)>,
    pub limit: usize,
    /// Order by commit time instead of relevance ("what changed lately").
    pub recent: bool,
    /// Exact filters; None = no filter.
    pub kind: Option<String>,
    pub status: Option<String>,
    pub service: Option<String>,
    pub priority: Option<String>,
    pub assignee: Option<String>,
    pub parent_task: Option<String>,
}

fn text_opts() -> TextOptions {
    TextOptions::default().set_indexing_options(
        TextFieldIndexing::default()
            .set_tokenizer(ANALYZER)
            .set_index_option(IndexRecordOption::WithFreqsAndPositions),
    )
}

fn build_schema() -> Schema {
    let mut sb = Schema::builder();
    sb.add_text_field("doc_id", STRING | STORED);
    sb.add_text_field("key", STRING | STORED);
    sb.add_text_field("key_text", text_opts());
    sb.add_text_field("title", text_opts().set_stored());
    sb.add_text_field("body", text_opts().set_stored());
    sb.add_text_field("tags", STRING | STORED);
    sb.add_text_field("tags_text", text_opts());
    sb.add_text_field("kind", STRING | STORED);
    sb.add_text_field("service", STRING | STORED);
    sb.add_text_field("status", STRING | STORED);
    sb.add_text_field("severity", STRING | STORED);
    sb.add_text_field("priority", STRING | STORED);
    sb.add_text_field("assignee", STRING | STORED);
    sb.add_text_field("parent_task", STRING | STORED);
    sb.add_text_field("hosts", STRING | STORED);
    sb.add_text_field("knowledge", STRING | STORED);
    sb.add_text_field("blocked_reason", TextOptions::default().set_stored());
    sb.add_text_field("resolution", text_opts().set_stored());
    sb.add_text_field("detection", text_opts().set_stored());
    sb.add_text_field("affected", TextOptions::default().set_stored());
    sb.add_text_field("deadline", TextOptions::default().set_stored());
    sb.add_text_field("started_at", TextOptions::default().set_stored());
    sb.add_text_field("detected_at", TextOptions::default().set_stored());
    sb.add_text_field("mitigated_at", TextOptions::default().set_stored());
    sb.add_text_field("resolved_at", TextOptions::default().set_stored());
    sb.add_text_field("meta_text", text_opts());
    sb.add_text_field("sha", STRING | STORED);
    sb.add_i64_field("committed_at", INDEXED | STORED | FAST);
    sb.add_u64_field("seq", STORED | FAST);
    sb.add_u64_field("is_head", INDEXED | STORED | FAST);
    sb.add_text_field("updated_at", TextOptions::default().set_stored());
    sb.build()
}

fn head_doc_id(key: &str) -> String {
    format!("head/{key}")
}

fn hist_doc_id(sha: &str, key: &str) -> String {
    format!("{sha}/{key}")
}

fn iso(secs: i64) -> String {
    chrono::DateTime::from_timestamp(secs, 0)
        .map(|t| t.to_rfc3339())
        .unwrap_or_default()
}

impl SearchIndex {
    pub fn open_or_create(dir: &Path) -> Result<SearchIndex> {
        std::fs::create_dir_all(dir)?;
        let schema = build_schema();
        let mmap = tantivy::directory::MmapDirectory::open(dir)?;
        let index = match Index::open_or_create(mmap, schema.clone()) {
            Ok(index) => index,
            // Schema changed since this index was written. Git is the truth and
            // startup reindexes anyway, so throwing the index away is safe.
            Err(err) => {
                eprintln!("kyb: index schema mismatch ({err}), rebuilding from git");
                std::fs::remove_dir_all(dir)?;
                std::fs::create_dir_all(dir)?;
                let mmap = tantivy::directory::MmapDirectory::open(dir)?;
                Index::open_or_create(mmap, schema.clone())?
            }
        };
        let analyzer = TextAnalyzer::builder(SimpleTokenizer::default())
            .filter(LowerCaser)
            .filter(Stemmer::new(Language::Russian))
            .build();
        index.tokenizers().register(ANALYZER, analyzer);
        let f = |n: &str| schema.get_field(n).expect("field from our own schema");
        let fields = Fields {
            doc_id: f("doc_id"),
            key: f("key"),
            key_text: f("key_text"),
            title: f("title"),
            body: f("body"),
            tags: f("tags"),
            tags_text: f("tags_text"),
            kind: f("kind"),
            service: f("service"),
            status: f("status"),
            severity: f("severity"),
            priority: f("priority"),
            assignee: f("assignee"),
            parent_task: f("parent_task"),
            hosts: f("hosts"),
            knowledge: f("knowledge"),
            blocked_reason: f("blocked_reason"),
            resolution: f("resolution"),
            detection: f("detection"),
            affected: f("affected"),
            deadline: f("deadline"),
            started_at: f("started_at"),
            detected_at: f("detected_at"),
            mitigated_at: f("mitigated_at"),
            resolved_at: f("resolved_at"),
            meta_text: f("meta_text"),
            sha: f("sha"),
            committed_at: f("committed_at"),
            seq: f("seq"),
            is_head: f("is_head"),
            updated_at: f("updated_at"),
        };
        let reader = index.reader_builder().reload_policy(ReloadPolicy::Manual).try_into()?;
        let generation = Generation { searcher: reader.searcher(), tombstones: HashMap::new() };
        Ok(SearchIndex {
            index,
            reader,
            fields,
            next_seq: AtomicU64::new(1),
            pending_tombstones: Mutex::new(HashMap::new()),
            generation: RwLock::new(Arc::new(generation)),
        })
    }

    pub fn writer(&self) -> Result<IndexWriter> {
        Ok(self.index.writer(50_000_000)?)
    }

    fn make_doc(
        &self,
        e: &Entry,
        sha: &str,
        committed_at: i64,
        is_head: bool,
        seq: u64,
    ) -> TantivyDocument {
        let mut d = TantivyDocument::default();
        let id = if is_head { head_doc_id(&e.key) } else { hist_doc_id(sha, &e.key) };
        d.add_text(self.fields.doc_id, id);
        d.add_text(self.fields.key, &e.key);
        d.add_text(self.fields.key_text, e.key.replace('-', " "));
        d.add_text(self.fields.title, &e.title);
        d.add_text(self.fields.body, &e.body);
        for t in &e.tags {
            d.add_text(self.fields.tags, t.to_lowercase());
        }
        d.add_text(self.fields.tags_text, e.tags.join(" ").replace('-', " "));
        d.add_text(self.fields.kind, &e.kind);
        if !e.service.is_empty() {
            d.add_text(self.fields.service, e.service.to_lowercase());
        }
        if !e.status.is_empty() {
            d.add_text(self.fields.status, &e.status);
        }
        if !e.severity.is_empty() {
            d.add_text(self.fields.severity, &e.severity);
        }
        if !e.priority.is_empty() {
            d.add_text(self.fields.priority, &e.priority);
        }
        if !e.blocked_reason.is_empty() {
            d.add_text(self.fields.blocked_reason, &e.blocked_reason);
        }
        if !e.assignee.is_empty() {
            d.add_text(self.fields.assignee, &e.assignee);
        }
        if !e.parent_task.is_empty() {
            d.add_text(self.fields.parent_task, &e.parent_task);
        }
        for h in &e.hosts {
            d.add_text(self.fields.hosts, h.to_lowercase());
        }
        for k in &e.knowledge {
            d.add_text(self.fields.knowledge, k);
        }
        if !e.resolution.is_empty() {
            d.add_text(self.fields.resolution, &e.resolution);
        }
        if !e.detection.is_empty() {
            d.add_text(self.fields.detection, &e.detection);
        }
        if !e.affected.is_empty() {
            let json = serde_json::to_string(&e.affected).expect("windows always serialize");
            d.add_text(self.fields.affected, json);
        }
        if !e.deadline.is_empty() {
            let json = serde_json::to_string(&e.deadline).expect("a deadline always serializes");
            d.add_text(self.fields.deadline, json);
        }
        for (f, v) in [
            (self.fields.started_at, &e.started_at),
            (self.fields.detected_at, &e.detected_at),
            (self.fields.mitigated_at, &e.mitigated_at),
            (self.fields.resolved_at, &e.resolved_at),
        ] {
            if !v.is_empty() {
                d.add_text(f, v);
            }
        }
        // SimpleTokenizer splits on non-alphanumerics, so orders_api and
        // orders-api-architecture both become searchable words here
        let meta = format!(
            "{} {} {} {}",
            e.service,
            e.hosts.join(" "),
            e.knowledge.join(" "),
            e.deadline.waits_on
        );
        if !meta.trim().is_empty() {
            d.add_text(self.fields.meta_text, meta);
        }
        d.add_text(self.fields.sha, sha);
        d.add_i64(self.fields.committed_at, committed_at);
        d.add_u64(self.fields.seq, seq);
        d.add_u64(self.fields.is_head, is_head as u64);
        d.add_text(self.fields.updated_at, &e.updated_at);
        d
    }

    /// Incremental update after a git commit: replace the head doc,
    /// append a history doc (<sha>/<key>) — history only grows.
    pub fn upsert_head(
        &self,
        w: &mut IndexWriter,
        e: &Entry,
        sha: &str,
        committed_at: i64,
    ) -> Result<()> {
        w.delete_term(Term::from_field_text(self.fields.doc_id, &head_doc_id(&e.key)));
        let seq = self.next_seq.fetch_add(1, AtomicOrdering::SeqCst);
        w.add_document(self.make_doc(e, sha, committed_at, true, seq))?;
        w.add_document(self.make_doc(e, sha, committed_at, false, seq))?;
        Ok(())
    }

    pub fn delete_head(&self, w: &mut IndexWriter, key: &str) {
        w.delete_term(Term::from_field_text(self.fields.doc_id, &head_doc_id(key)));
    }

    /// A knowledge entry was deleted now: from this instant on, an as_of
    /// snapshot no longer has a current version of it.
    pub fn retract(&self, key: &str, committed_at: i64) {
        let seq = self.next_seq.fetch_add(1, AtomicOrdering::SeqCst);
        self.pending_tombstones
            .lock()
            .unwrap()
            .entry(key.to_string())
            .or_default()
            .push((committed_at, seq));
    }

    /// The generation searches read right now.
    fn generation(&self) -> Arc<Generation> {
        self.generation.read().unwrap().clone()
    }

    /// Publish: the committed documents and the pending tombstones become one
    /// generation, swapped in as a unit. A search already holding the previous
    /// generation finishes with the previous documents and the previous tombstones.
    pub fn commit_and_reload(&self, w: &mut IndexWriter) -> Result<()> {
        w.commit()?;
        self.reader.reload()?;
        let generation = Generation {
            searcher: self.reader.searcher(),
            tombstones: self.pending_tombstones.lock().unwrap().clone(),
        };
        *self.generation.write().unwrap() = Arc::new(generation);
        Ok(())
    }

    /// Full rebuild from git: entire history, plus one "live" doc per key —
    /// the version the default search sees. Live is the working tree for keys
    /// that exist there, and the latest historical version for archived
    /// incidents/tasks (closed things stay findable). Deleted knowledge is a
    /// retraction: history-only. Returns (live, history) doc counts.
    pub fn reindex(&self, w: &mut IndexWriter, store: &Store) -> Result<(usize, usize)> {
        w.delete_all_documents()?;
        // Tantivy resets the writer stamper when deleting every segment. Its
        // delete-then-add contract requires a commit boundary before new docs;
        // without it a multi-threaded writer can discard part of this rebuild.
        // Do not reload the reader yet: searches keep seeing the previous
        // complete generation until the replacement generation commits below.
        w.commit()?;
        // walk_history is chronological, so seq = walk order
        let (hist, retractions) = store.walk_history_and_retractions()?;
        let mut seq = 0u64;
        let mut last: HashMap<String, (Entry, String, i64, u64)> = HashMap::new();
        for h in &hist {
            seq += 1;
            w.add_document(self.make_doc(&h.entry, &h.sha, h.committed_at, false, seq))?;
            last.insert(h.entry.key.clone(), (h.entry.clone(), h.sha.clone(), h.committed_at, seq));
        }
        // a retraction after `n` documents outranks seq n and everything before
        // it; published together with these documents by commit_and_reload below
        let mut tombstones: Tombstones = HashMap::new();
        for r in retractions {
            tombstones.entry(r.key).or_default().push((r.committed_at, r.after as u64));
        }
        let heads = store.list_head()?;
        let mut live = 0usize;
        let mut alive: HashSet<&str> = HashSet::new();
        for e in &heads {
            alive.insert(e.key.as_str());
            let (sha, at, sq) = last
                .get(&e.key)
                .map(|(_, s, a, q)| (s.clone(), *a, *q))
                .unwrap_or_default();
            w.add_document(self.make_doc(e, &sha, at, true, sq))?;
            live += 1;
        }
        for (key, (entry, sha, at, sq)) in &last {
            if alive.contains(key.as_str()) || entry.kind == KIND_KNOWLEDGE {
                continue;
            }
            w.add_document(self.make_doc(entry, sha, *at, true, *sq))?;
            live += 1;
        }
        self.next_seq.store(seq + 1, AtomicOrdering::SeqCst);
        *self.pending_tombstones.lock().unwrap() = tombstones;
        self.commit_and_reload(w)?;
        Ok((live, hist.len()))
    }

    /// The live doc of one key (tree version, or the archived latest).
    pub fn get_live(&self, key: &str) -> Result<Option<Hit>> {
        let searcher = self.reader.searcher();
        let q = TermQuery::new(
            Term::from_field_text(self.fields.doc_id, &head_doc_id(key)),
            IndexRecordOption::Basic,
        );
        let top = searcher.search(&q, &TopDocs::with_limit(1))?;
        match top.first() {
            None => Ok(None),
            Some((score, addr)) => Ok(Some(self.to_hit(&searcher, *addr, *score)?)),
        }
    }

    pub fn search(&self, q: &str, opts: &SearchOpts) -> Result<Vec<Hit>> {
        self.search_in(&self.generation(), q, opts)
    }

    fn search_in(&self, generation: &Generation, q: &str, opts: &SearchOpts) -> Result<Vec<Hit>> {
        let searcher = generation.searcher.clone();
        let base: Box<dyn Query> = if q.trim().is_empty() {
            Box::new(AllQuery)
        } else {
            let mut parser = QueryParser::for_index(
                &self.index,
                vec![
                    self.fields.key_text,
                    self.fields.title,
                    self.fields.body,
                    self.fields.tags_text,
                    self.fields.meta_text,
                    self.fields.resolution,
                    self.fields.detection,
                ],
            );
            parser.set_field_boost(self.fields.title, 2.0);
            // a tag match is a strong topical signal, but weaker than the headline
            parser.set_field_boost(self.fields.tags_text, 1.5);
            parser.set_field_boost(self.fields.key_text, 1.5);
            parser.set_field_boost(self.fields.meta_text, 1.5);
            // lenient: broken query syntax from an agent must not fail the request
            let (query, _errs) = parser.parse_query_lenient(q);
            query
        };
        let mut clauses: Vec<(Occur, Box<dyn Query>)> = vec![(Occur::Must, base)];
        // History docs cover ALL versions (current included); head docs are the
        // HEAD slice. Filter strictly by one of the two worlds, otherwise a
        // history search duplicates the current version (head + history doc
        // sharing one sha).
        // as_of is a history question - it asks for a version, not for the head -
        // so it selects the history world the same way --history does.
        let as_of = opts.as_of;
        let window = opts.changed_between;
        // Both read versions rather than the head slice; both collapse to one
        // row per key afterwards.
        let versioned = opts.history || as_of.is_some() || window.is_some();
        let head_val = if versioned { 0 } else { 1 };
        clauses.push((
            Occur::Must,
            Box::new(TermQuery::new(
                Term::from_field_u64(self.fields.is_head, head_val),
                IndexRecordOption::Basic,
            )),
        ));
        if let Some(at) = as_of {
            clauses.push((
                Occur::Must,
                Box::new(RangeQuery::new_i64(
                    "committed_at".to_string(),
                    i64::MIN..at.saturating_add(1),
                )),
            ));
        }
        if let Some((lo, hi)) = window {
            clauses.push((
                Occur::Must,
                Box::new(RangeQuery::new_i64(
                    "committed_at".to_string(),
                    lo..hi.saturating_add(1),
                )),
            ));
        }
        for t in &opts.tags {
            clauses.push((
                Occur::Must,
                Box::new(TermQuery::new(
                    Term::from_field_text(self.fields.tags, &t.to_lowercase()),
                    IndexRecordOption::Basic,
                )),
            ));
        }
        let exact = [
            (self.fields.kind, opts.kind.as_deref(), false),
            (self.fields.status, opts.status.as_deref(), false),
            (self.fields.service, opts.service.as_deref(), true),
            (self.fields.priority, opts.priority.as_deref(), false),
            // an assignee label is stored verbatim, so the filter matches it verbatim
            (self.fields.assignee, opts.assignee.as_deref(), false),
            (self.fields.parent_task, opts.parent_task.as_deref(), false),
        ];
        for (field, value, fold) in exact {
            let Some(v) = value.filter(|v| !v.is_empty()) else { continue };
            let v = if fold { v.to_lowercase() } else { v.to_string() };
            clauses.push((
                Occur::Must,
                Box::new(TermQuery::new(
                    Term::from_field_text(field, &v),
                    IndexRecordOption::Basic,
                )),
            ));
        }
        let query = BooleanQuery::new(clauses);
        let limit = opts.limit.max(1);
        // An as_of or changed_between answer is one document per key, and which
        // one wins is decided after retrieval - so the top-k must be taken from
        // the whole matching set, not from a k-sized window that a single busy
        // key could fill with its own superseded versions. The matching set is
        // counted first, so no budget can truncate it. The corpus is hundreds to
        // thousands of entries by design (see the README), so collecting every
        // match and collapsing in memory is both exact and cheap.
        let collapse = as_of.is_some() || window.is_some();
        let fetch = if collapse { searcher.search(&query, &Count)?.max(limit) } else { limit };
        let top: Vec<(f32, tantivy::DocAddress)> = if opts.recent {
            // seq, not committed_at: git time is 1s-granular and a write burst
            // ties on it, turning "latest first" into segment-order roulette
            searcher
                .search(
                    &query,
                    &TopDocs::with_limit(fetch).order_by_fast_field::<u64>("seq", Order::Desc),
                )?
                .into_iter()
                // ordering by a fast field skips scoring; report 0 rather than a fake score
                .map(|(_seq, addr)| (0.0f32, addr))
                .collect()
        } else {
            searcher.search(&query, &TopDocs::with_limit(fetch))?
        };
        // as_of is a snapshot question: which version of each key was current
        // at T is decided first, and only that version is asked whether it
        // matches the words and the filters. Deciding after filtering would let
        // a superseded version answer for a key whose current version at T no
        // longer says the word, or no longer carries the status.
        let snapshot = match as_of {
            Some(at) => Some(self.current_version_per_key(generation, at, window)?),
            None => None,
        };
        let top = if collapse {
            self.collapse_to_latest_per_key(&searcher, top, limit, snapshot.as_ref())?
        } else {
            top
        };
        let mut hits = vec![];
        for (score, addr) in top {
            hits.push(self.to_hit(&searcher, addr, score)?);
        }
        Ok(hits)
    }

    /// The version of every key that was current at `at`: key -> `seq` of its
    /// newest history document committed at or before that instant (and inside
    /// the window, when one is set). Every history document up to T is visited,
    /// so a key is never lost to a candidate budget; the corpus is hundreds to
    /// thousands of entries by design, so this is a few milliseconds.
    fn current_version_per_key(
        &self,
        generation: &Generation,
        at: i64,
        window: Option<(i64, i64)>,
    ) -> Result<HashMap<String, u64>> {
        let searcher = &generation.searcher;
        let mut clauses: Vec<(Occur, Box<dyn Query>)> = vec![
            (
                Occur::Must,
                Box::new(TermQuery::new(
                    Term::from_field_u64(self.fields.is_head, 0),
                    IndexRecordOption::Basic,
                )),
            ),
            (
                Occur::Must,
                Box::new(RangeQuery::new_i64(
                    "committed_at".to_string(),
                    i64::MIN..at.saturating_add(1),
                )),
            ),
        ];
        if let Some((lo, hi)) = window {
            clauses.push((
                Occur::Must,
                Box::new(RangeQuery::new_i64(
                    "committed_at".to_string(),
                    lo..hi.saturating_add(1),
                )),
            ));
        }
        let addrs = searcher.search(&BooleanQuery::new(clauses), &DocSetCollector)?;
        let mut current: HashMap<String, u64> = HashMap::new();
        for addr in addrs {
            let doc: TantivyDocument = searcher.doc(addr)?;
            let key = doc.get_first(self.fields.key).and_then(|v| v.as_str()).unwrap_or_default();
            let seq = doc.get_first(self.fields.seq).and_then(|v| v.as_u64()).unwrap_or(0);
            match current.get_mut(key) {
                Some(best) => *best = (*best).max(seq),
                None => {
                    current.insert(key.to_string(), seq);
                }
            }
        }
        // a knowledge entry deleted by T, and not written again since, had no
        // current version at T - judged by the tombstones of this very generation
        let tombstones = &generation.tombstones;
        current.retain(|key, seq| {
            !tombstones
                .get(key)
                .is_some_and(|ts| ts.iter().any(|(t_at, t_seq)| *t_at <= at && *t_seq >= *seq))
        });
        Ok(current)
    }

    /// One document per key.
    ///
    /// With a snapshot (as_of), a row survives only if it is the version that
    /// was current at T - a superseded version that still matched the query is
    /// dropped even when nothing newer matched. Without one (changed_between),
    /// the newest matching version inside the window wins.
    ///
    /// Ordering is by `seq`, the chronological walk position assigned when the
    /// index was built, never by `committed_at` - git timestamps are 1s-granular
    /// and a burst of writes ties on them, which would make "newest" depend on
    /// segment order. Relevance order among the survivors is preserved: the
    /// caller asked for the best answers, not the most recent ones.
    fn collapse_to_latest_per_key(
        &self,
        searcher: &tantivy::Searcher,
        top: Vec<(f32, tantivy::DocAddress)>,
        limit: usize,
        snapshot: Option<&HashMap<String, u64>>,
    ) -> Result<Vec<(f32, tantivy::DocAddress)>> {
        let mut best: HashMap<String, (u64, usize)> = HashMap::new();
        let mut rows: Vec<(f32, tantivy::DocAddress)> = Vec::with_capacity(top.len());
        for (score, addr) in top {
            let doc: TantivyDocument = searcher.doc(addr)?;
            let key = doc
                .get_first(self.fields.key)
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string();
            let seq = doc.get_first(self.fields.seq).and_then(|v| v.as_u64()).unwrap_or(0);
            if let Some(current) = snapshot {
                if current.get(&key) == Some(&seq) {
                    rows.push((score, addr));
                    if rows.len() == limit {
                        break;
                    }
                }
                continue;
            }
            let idx = rows.len();
            rows.push((score, addr));
            match best.get(&key) {
                Some((prev_seq, _)) if *prev_seq >= seq => {}
                _ => {
                    best.insert(key, (seq, idx));
                }
            }
        }
        if snapshot.is_some() {
            return Ok(rows);
        }
        let keep: HashSet<usize> = best.values().map(|(_, idx)| *idx).collect();
        Ok(rows
            .into_iter()
            .enumerate()
            .filter(|(idx, _)| keep.contains(idx))
            .map(|(_, row)| row)
            .take(limit)
            .collect())
    }

    fn to_hit(
        &self,
        searcher: &tantivy::Searcher,
        addr: tantivy::DocAddress,
        score: f32,
    ) -> Result<Hit> {
        let doc: TantivyDocument = searcher.doc(addr)?;
        let text =
            |f: Field| doc.get_first(f).and_then(|v| v.as_str()).unwrap_or_default().to_string();
        let multi = |f: Field| -> Vec<String> {
            doc.get_all(f).filter_map(|v| v.as_str()).map(String::from).collect()
        };
        Ok(Hit {
            key: text(self.fields.key),
            title: text(self.fields.title),
            kind: text(self.fields.kind),
            body: text(self.fields.body),
            tags: multi(self.fields.tags),
            service: text(self.fields.service),
            hosts: multi(self.fields.hosts),
            severity: text(self.fields.severity),
            status: text(self.fields.status),
            priority: text(self.fields.priority),
            blocked_reason: text(self.fields.blocked_reason),
            assignee: text(self.fields.assignee),
            parent_task: text(self.fields.parent_task),
            knowledge: multi(self.fields.knowledge),
            resolution: text(self.fields.resolution),
            detection: text(self.fields.detection),
            affected: serde_json::from_str(&text(self.fields.affected)).unwrap_or_default(),
            deadline: serde_json::from_str(&text(self.fields.deadline)).unwrap_or_default(),
            started_at: text(self.fields.started_at),
            detected_at: text(self.fields.detected_at),
            mitigated_at: text(self.fields.mitigated_at),
            resolved_at: text(self.fields.resolved_at),
            sha: text(self.fields.sha),
            committed_at: iso(
                doc.get_first(self.fields.committed_at).and_then(|v| v.as_i64()).unwrap_or(0),
            ),
            is_head: doc.get_first(self.fields.is_head).and_then(|v| v.as_u64()).unwrap_or(0) == 1,
            updated_at: text(self.fields.updated_at),
            score,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Entry;
    use rstest::rstest;

    fn entry(key: &str, title: &str, body: &str) -> Entry {
        Entry {
            key: key.into(),
            title: title.into(),
            tags: vec!["infra".into()],
            body: body.into(),
            ..Default::default()
        }
    }

    /// Mini rig: temp git repo + temp index, everything indexed.
    fn mini(docs: &[(&str, &str, &str)]) -> (SearchIndex, tempfile::TempDir, tempfile::TempDir) {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        for (k, t, b) in docs {
            store.upsert(entry(k, t, b), "2026-07-20").unwrap();
        }
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();
        (index, data, idxd)
    }

    fn o(history: bool) -> SearchOpts {
        SearchOpts { tags: vec![], history, limit: 10, ..Default::default() }
    }

    // --- stemming/tokenization: query form vs body form ---
    // Russian pairs are the test subject here (ru_stem analyzer), data stays Russian.
    #[rstest]
    #[case("стримах", "используем стримы всегда", true)]
    #[case("стрим", "конфиг стримов переехал", true)]
    #[case("стримом", "работаем со стримами", true)]
    #[case("nats", "NATS живее всех живых", true)]
    #[case("NATS", "пишем в nats постоянно", true)]
    #[case("createorupdatestream", "вызываем CreateOrUpdateStream", true)]
    #[case("терраформе", "весь конфиг в терраформ уехал", true)]
    // snowball limitation: "деплоя" stems to "депло" while "деплой" (-й loanword) stays — no match
    #[case("деплоя", "деплой только через пайплайн", false)]
    #[case("реестра", "реестр знаний для агентов", true)]
    #[case("пайплайну", "пайплайн собирает образ", true)]
    #[case("индексы", "пересобираем индекс из гита", true)]
    #[case("докере", "собираем в докер контейнере", true)]
    #[case("знанием", "реестр знаний для агентов", true)]
    #[case("кубернетес", "у нас нет кубера", false)]
    #[case("postgres", "только clickhouse и mongo", false)]
    fn stemming_matrix(#[case] q: &str, #[case] body: &str, #[case] should_match: bool) {
        let (index, _d, _i) = mini(&[("k", "title", body)]);
        let hits = index.search(q, &o(false)).unwrap();
        assert_eq!(!hits.is_empty(), should_match, "q='{q}' vs body='{body}'");
    }

    // --- broken query syntax must never fail the search ---
    #[rstest]
    #[case("")]
    #[case("   ")]
    #[case("\"unclosed")]
    #[case("title:(((")]
    #[case("AND OR NOT")]
    #[case("a:b:c")]
    #[case("()")]
    #[case("[]")]
    #[case("*")]
    #[case("-dash")]
    #[case("+plus")]
    #[case("^boost^^")]
    #[case("word)")]
    #[case("слово)")]
    #[case("~~~")]
    fn garbage_queries_dont_crash(#[case] q: &str) {
        let (index, _d, _i) = mini(&[("k", "title", "an ordinary body")]);
        assert!(index.search(q, &o(false)).is_ok(), "failed on q={q:?}");
        assert!(index.search(q, &o(true)).is_ok(), "failed on history q={q:?}");
    }

    fn make_incident(key: &str, service: &str, status: &str) -> Entry {
        Entry {
            key: key.into(),
            title: format!("{service} incident"),
            kind: "incident".into(),
            service: service.into(),
            hosts: vec!["host-a".into()],
            severity: "high".into(),
            status: status.into(),
            knowledge: vec!["orders-api-architecture".into()],
            body: "The pipeline stalled and metrics stopped flowing.".into(),
            ..Default::default()
        }
    }

    // kind/status/service are exact filters; free text still applies on top
    #[test]
    fn incident_filters() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store.upsert(entry("orders-api-architecture", "orders_api", "The gRPC gateway."), "2026-07-22").unwrap();
        store.upsert(make_incident("inc-2026-07-22-orders-api-oom", "orders_api", "open"), "2026-07-22").unwrap();
        store.upsert(make_incident("inc-2026-07-21-landing-gap", "web_app", "resolved"), "2026-07-22").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let by = |kind: Option<&str>, status: Option<&str>, service: Option<&str>| {
            index
                .search("", &SearchOpts {
                    limit: 10,
                    kind: kind.map(String::from),
                    status: status.map(String::from),
                    service: service.map(String::from),
                    ..Default::default()
                })
                .unwrap()
        };
        assert_eq!(by(None, None, None).len(), 3, "no filter sees everything");
        assert_eq!(by(Some("incident"), None, None).len(), 2);
        assert_eq!(by(Some("knowledge"), None, None).len(), 1);
        assert_eq!(by(Some("incident"), Some("open"), None).len(), 1);
        assert_eq!(by(Some("incident"), None, Some("ORDERS_API")).len(), 1, "service filter is case-insensitive");
        assert_eq!(by(Some("incident"), Some("open"), Some("web_app")).len(), 0);

        // incident fields come back on the hit
        let hits = by(Some("incident"), Some("open"), None);
        let h = &hits[0];
        assert_eq!(h.kind, "incident");
        assert_eq!(h.service, "orders_api");
        assert_eq!(h.status, "open");
        assert_eq!(h.severity, "high");
        assert_eq!(h.hosts, vec!["host-a"]);
        assert_eq!(h.knowledge, vec!["orders-api-architecture"]);

        // free text reaches the incident through service/knowledge meta_text:
        // the body never says "api", the service name does
        let hits = index
            .search("orders api", &SearchOpts { limit: 10, kind: Some("incident".into()), ..Default::default() })
            .unwrap();
        assert_eq!(hits.len(), 2, "both incidents mention orders_api or link its knowledge: {:?}",
            hits.iter().map(|h| &h.key).collect::<Vec<_>>());

        // knowledge hits carry kind too, with empty incident fields
        let hits = by(Some("knowledge"), None, None);
        assert_eq!(hits[0].kind, "knowledge");
        assert!(hits[0].service.is_empty());
        assert!(hits[0].status.is_empty());
    }

    fn make_task(key: &str, status: &str, priority: &str) -> Entry {
        Entry {
            key: key.into(),
            title: format!("{key} task"),
            kind: "task".into(),
            status: status.into(),
            priority: priority.into(),
            body: "Raise the retention window for container logs.".into(),
            ..Default::default()
        }
    }

    // priority is an exact filter alongside kind/status, and both new fields
    // ride back on the hit
    #[test]
    fn task_priority_filter_and_hit_fields() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store.upsert(make_task("task-high-one", "open", "high"), "2026-08-15").unwrap();
        store.upsert(make_task("task-high-two", "in_progress", "high"), "2026-08-15").unwrap();
        store.upsert(make_task("task-low-one", "open", "low"), "2026-08-15").unwrap();
        let mut blocked = make_task("task-blocked", "blocked", "");
        blocked.blocked_reason = "waiting on the host-a disk upgrade".into();
        store.upsert(blocked, "2026-08-15").unwrap();
        store.upsert(entry("plain-note", "A note", "nothing to do with tasks"), "2026-08-15").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let by = |status: Option<&str>, priority: Option<&str>| {
            index
                .search("", &SearchOpts {
                    limit: 10,
                    kind: Some("task".into()),
                    status: status.map(String::from),
                    priority: priority.map(String::from),
                    ..Default::default()
                })
                .unwrap()
        };
        assert_eq!(by(None, None).len(), 4, "all tasks, the note excluded");
        assert_eq!(by(None, Some("high")).len(), 2);
        assert_eq!(by(None, Some("low")).len(), 1);
        assert_eq!(by(None, Some("critical")).len(), 0, "nothing is critical");
        assert_eq!(by(Some("open"), Some("high")).len(), 1, "filters combine");

        let h = &by(None, Some("low"))[0];
        assert_eq!(h.key, "task-low-one");
        assert_eq!(h.priority, "low");
        assert!(h.blocked_reason.is_empty());

        let h = &by(Some("blocked"), None)[0];
        assert_eq!(h.blocked_reason, "waiting on the host-a disk upgrade");
        assert!(h.priority.is_empty(), "unranked stays unranked");
    }

    // assignee and parent_task are exact filters of the same shape, and both
    // ride back on the hit
    #[test]
    fn task_assignee_and_parent_filters() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let mut parent = make_task("task-migrate-logs", "in_progress", "high");
        parent.assignee = "agent-a".into();
        store.upsert(parent, "2026-08-15").unwrap();
        let mut child = make_task("task-migrate-logs-step-one", "in_progress", "");
        child.assignee = "agent-a".into();
        child.parent_task = "task-migrate-logs".into();
        store.upsert(child, "2026-08-15").unwrap();
        let mut other = make_task("task-swap-disk", "open", "");
        other.assignee = "agent-b".into();
        other.parent_task = "task-migrate-logs".into();
        store.upsert(other, "2026-08-15").unwrap();
        store.upsert(make_task("task-unclaimed", "open", ""), "2026-08-15").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let by = |assignee: Option<&str>, parent: Option<&str>| {
            index
                .search("", &SearchOpts {
                    limit: 10,
                    kind: Some("task".into()),
                    assignee: assignee.map(String::from),
                    parent_task: parent.map(String::from),
                    ..Default::default()
                })
                .unwrap()
        };
        assert_eq!(by(None, None).len(), 4, "no filter sees every task");
        assert_eq!(by(Some("agent-a"), None).len(), 2, "what one owner holds");
        assert_eq!(by(Some("agent-b"), None).len(), 1);
        assert_eq!(by(Some("Agent-A"), None).len(), 0, "the label matches verbatim");
        assert_eq!(by(None, Some("task-migrate-logs")).len(), 2, "the children of one parent");
        assert_eq!(by(Some("agent-a"), Some("task-migrate-logs")).len(), 1, "filters combine");
        assert_eq!(by(None, Some("task-nothing-hangs-here")).len(), 0);

        let h = &by(Some("agent-a"), Some("task-migrate-logs"))[0];
        assert_eq!(h.key, "task-migrate-logs-step-one");
        assert_eq!(h.assignee, "agent-a");
        assert_eq!(h.parent_task, "task-migrate-logs");
        // an unclaimed top-level task carries neither
        let all = by(None, None);
        let h = all.iter().find(|h| h.key == "task-unclaimed").unwrap();
        assert!(h.assignee.is_empty());
        assert!(h.parent_task.is_empty());
    }

    // the two deletion semantics: archived closed entries stay in the default
    // search as their latest version; deleted knowledge is a retraction and
    // drops to history-only
    #[test]
    fn archived_entries_live_in_default_search() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store.upsert(entry("gone-note", "Wrong note", "a retracted statement"), "2026-07-20").unwrap();
        store.delete("gone-note").unwrap();
        let mut inc = make_incident("inc-2026-07-20-oom", "svc", "resolved");
        inc.resolution = "raised the memory limit".into();
        store.upsert(inc, "2026-07-20").unwrap();
        store.archive("inc-2026-07-20-oom").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        // the archived incident is a first-class default-search citizen
        let hits = index.search("memory limit", &o(false)).unwrap();
        assert_eq!(hits.len(), 1, "{:?}", hits.iter().map(|h| &h.key).collect::<Vec<_>>());
        assert_eq!(hits[0].key, "inc-2026-07-20-oom");
        assert!(hits[0].is_head);
        assert_eq!(hits[0].status, "resolved");
        assert!(index.get_live("inc-2026-07-20-oom").unwrap().is_some());

        // the retracted note is not; history still holds both
        assert!(index.search("retracted statement", &o(false)).unwrap().is_empty());
        assert_eq!(index.search("retracted statement", &o(true)).unwrap().len(), 1);
        assert!(index.get_live("gone-note").unwrap().is_none());
    }

    #[test]
    fn title_ranks_above_body() {
        let (index, _d, _i) = mini(&[
            ("in-body", "totally different", "terraform is mentioned in the body"),
            ("in-title", "terraform config", "nothing special here"),
        ]);
        let hits = index.search("terraform", &o(false)).unwrap();
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].key, "in-title", "title hit must rank first");
    }

    #[test]
    fn as_of_returns_the_version_that_was_current_then() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();

        store.upsert(entry("svc", "Service", "the port is 8080"), "2026-07-19").unwrap();
        // git timestamps are whole seconds, so two versions written inside one
        // second are genuinely indistinguishable by time - see as_of_is_second_granular.
        std::thread::sleep(std::time::Duration::from_millis(1100));
        let mid = chrono::Utc::now().timestamp();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        store.upsert(entry("svc", "Service", "the port is 9090"), "2026-07-21").unwrap();

        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        // head: today's answer
        let hits = index.search("port", &o(false)).unwrap();
        assert_eq!(hits.len(), 1);
        assert!(hits[0].body.contains("9090"), "head must be current: {}", hits[0].body);

        // as_of before the change: the value that was true then, exactly one doc
        let opts = SearchOpts { as_of: Some(mid), limit: 10, ..Default::default() };
        let hits = index.search("port", &opts).unwrap();
        assert_eq!(hits.len(), 1, "as_of must collapse to one version per key");
        assert!(hits[0].body.contains("8080"), "as_of must be the superseded value: {}", hits[0].body);
        assert!(!hits[0].is_head);

        // as_of after everything: back to the current value, still one doc
        let opts = SearchOpts {
            as_of: Some(chrono::Utc::now().timestamp() + 60),
            limit: 10,
            ..Default::default()
        };
        let hits = index.search("port", &opts).unwrap();
        assert_eq!(hits.len(), 1);
        assert!(hits[0].body.contains("9090"));
    }

    #[test]
    fn as_of_before_an_entry_existed_does_not_find_it() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let before = chrono::Utc::now().timestamp() - 3600;
        store.upsert(entry("svc", "Service", "the port is 8080"), "2026-07-19").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let opts = SearchOpts { as_of: Some(before), limit: 10, ..Default::default() };
        assert!(index.search("port", &opts).unwrap().is_empty(), "an entry cannot predate itself");
    }

    /// A key with a long history must not crowd the result with its own
    /// superseded versions - that is the whole reason the collapse exists.
    #[test]
    fn as_of_collapses_a_busy_key_to_one_row() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        for i in 0..8 {
            store
                .upsert(entry("busy", "Busy", &format!("shared token, revision {i}")), "2026-07-20")
                .unwrap();
        }
        store.upsert(entry("other", "Other", "shared token, elsewhere"), "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let opts = SearchOpts {
            as_of: Some(chrono::Utc::now().timestamp() + 60),
            limit: 10,
            ..Default::default()
        };
        let hits = index.search("shared token", &opts).unwrap();
        let keys: Vec<&str> = hits.iter().map(|h| h.key.as_str()).collect();
        assert_eq!(hits.len(), 2, "one row per key, got {keys:?}");
        assert!(keys.contains(&"busy") && keys.contains(&"other"), "{keys:?}");
        let busy = hits.iter().find(|h| h.key == "busy").unwrap();
        assert!(busy.body.contains("revision 7"), "newest surviving version wins: {}", busy.body);
    }

    /// Honest about the resolution of the thing: git commits carry whole
    /// seconds, so two versions written inside one second cannot be told apart
    /// by as_of, and the later one wins. Benchmarks built on as_of must skip
    /// transitions whose neighbours share a timestamp.
    #[test]
    fn as_of_is_second_granular() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store.upsert(entry("svc", "Service", "value one"), "2026-07-19").unwrap();
        store.upsert(entry("svc", "Service", "value two"), "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let versions = store.history("svc").unwrap();
        let opts = SearchOpts {
            as_of: Some(store.rev_time(&versions[0].sha).unwrap().unwrap()),
            limit: 10,
            ..Default::default()
        };
        let hits = index.search("value", &opts).unwrap();
        assert_eq!(hits.len(), 1, "still exactly one row per key");
        assert!(hits[0].body.contains("value two"), "a tie resolves to the later version");
    }

    /// The snapshot is chosen before it is searched. A version that was already
    /// superseded at T must not answer for its key just because it still says
    /// the word - or still carries the status - that the version current at T
    /// no longer does.
    #[test]
    fn as_of_never_answers_from_a_version_already_superseded_at_that_instant() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();

        store.upsert(entry("svc", "Service", "runs on legacyhost"), "2026-07-19").unwrap();
        let mut inc = entry("inc-1", "Outage", "the api was down");
        inc.kind = "incident".into();
        inc.service = "api".into();
        inc.status = "open".into();
        store.upsert(inc.clone(), "2026-07-19").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        store.upsert(entry("svc", "Service", "runs on newhost"), "2026-07-20").unwrap();
        inc.status = "resolved".into();
        store.upsert(inc, "2026-07-20").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        let after_both = chrono::Utc::now().timestamp();

        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        // the word was removed by the version current at T: no answer, not the old one
        let at = |q: &str, status: Option<&str>| {
            let opts = SearchOpts {
                as_of: Some(after_both),
                status: status.map(String::from),
                limit: 10,
                ..Default::default()
            };
            index.search(q, &opts).unwrap()
        };
        assert!(
            at("legacyhost", None).is_empty(),
            "a superseded version must not answer: {:?}",
            at("legacyhost", None).iter().map(|h| &h.body).collect::<Vec<_>>()
        );
        let hits = at("newhost", None);
        assert_eq!(hits.len(), 1);
        assert!(hits[0].body.contains("newhost"));

        // the same for a filter: the incident was resolved by T, so it is not open at T
        assert!(at("", Some("open")).is_empty(), "status is read from the version current at T");
        let hits = at("", Some("resolved"));
        assert_eq!(hits.iter().map(|h| h.key.as_str()).collect::<Vec<_>>(), vec!["inc-1"]);
    }

    /// Documents and tombstones are read from one generation, even across a
    /// reindex that renumbers everything. The interleaving from the review: live
    /// write A (seq 1), delete A (2), write B (3), delete B (4); a rebuild gives
    /// A=1, B=2 with tombstones 1 and 2. A search that began before the rebuild
    /// must judge B(3) by the old tombstone (4), never by the new one (2), or a
    /// deleted entry comes back.
    #[test]
    fn as_of_pairs_documents_with_the_tombstones_of_their_own_generation() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let mut w = index.writer().unwrap();
        let now = chrono::Utc::now().timestamp();
        let created = |out: crate::store::UpsertOutcome| match out {
            crate::store::UpsertOutcome::Created(c) => c,
            _ => panic!("expected a creation"),
        };
        for key in ["a", "b"] {
            let c = created(store.upsert(entry(key, "Short lived", "a fact that was retracted"), "2026-07-19").unwrap());
            index.upsert_head(&mut w, &c.entry, &c.sha, c.committed_at).unwrap();
            index.commit_and_reload(&mut w).unwrap();
            store.delete(key).unwrap();
            index.delete_head(&mut w, key);
            index.retract(key, now);
            index.commit_and_reload(&mut w).unwrap();
        }
        let c = created(store.upsert(entry("kept", "Kept", "a fact that stays"), "2026-07-19").unwrap());
        index.upsert_head(&mut w, &c.entry, &c.sha, c.committed_at).unwrap();
        index.commit_and_reload(&mut w).unwrap();

        let opts = SearchOpts { as_of: Some(now + 3600), limit: 10, ..Default::default() };
        let keys = |hits: Vec<Hit>| hits.into_iter().map(|h| h.key).collect::<Vec<_>>();
        // a search that began before the rebuild holds the live generation …
        let before = index.generation();
        assert_eq!(keys(index.search_in(&before, "fact", &opts).unwrap()), vec!["kept"]);
        // … the rebuild renumbers every document and tombstone …
        index.reindex(&mut w, &store).unwrap();
        assert_ne!(
            before.tombstones, index.generation().tombstones,
            "the rebuild must have renumbered, or this test proves nothing"
        );
        // … and the old search still finishes against its own pair, as a new one does
        assert_eq!(keys(index.search_in(&before, "fact", &opts).unwrap()), vec!["kept"]);
        assert_eq!(keys(index.search("fact", &opts).unwrap()), vec!["kept"]);
    }

    /// A retracted knowledge entry stops existing at the instant of its deletion:
    /// before it the snapshot has it, after it nothing does - until it is written
    /// again. An archived incident is not a retraction; it stays findable at its
    /// last version, as it does at head.
    #[test]
    fn as_of_forgets_retracted_knowledge_from_the_instant_of_its_deletion() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let pause = || std::thread::sleep(std::time::Duration::from_millis(1100));

        store.upsert(entry("gone", "Gone", "an ephemeral fact"), "2026-07-19").unwrap();
        let mut inc = entry("inc-old", "Old outage", "the queue was stuck");
        inc.kind = "incident".into();
        inc.service = "queue".into();
        inc.status = "resolved".into();
        store.upsert(inc, "2026-07-19").unwrap();
        pause();
        let while_alive = chrono::Utc::now().timestamp();
        pause();
        store.delete("gone").unwrap();
        store.archive("inc-old").unwrap();
        pause();
        let after_deletion = chrono::Utc::now().timestamp();

        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();
        let at = |q: &str, t: i64| {
            let opts = SearchOpts { as_of: Some(t), limit: 10, ..Default::default() };
            index.search(q, &opts).unwrap()
        };
        assert_eq!(at("ephemeral", while_alive).len(), 1, "it existed then");
        assert!(at("ephemeral", after_deletion).is_empty(), "retracted: no current version at T");
        assert_eq!(at("queue", after_deletion).len(), 1, "archived is not retracted");

        // written again with the very same text: a new version, current from then on
        pause();
        store.upsert(entry("gone", "Gone", "an ephemeral fact"), "2026-07-22").unwrap();
        index.reindex(&mut w, &store).unwrap();
        assert!(at("ephemeral", after_deletion).is_empty(), "still gone at the earlier instant");
        assert_eq!(at("ephemeral", chrono::Utc::now().timestamp() + 60).len(), 1, "back since the rewrite");
    }

    #[test]
    fn history_search_no_duplicates() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store.upsert(entry("k", "t", "common word, first version"), "2026-07-19").unwrap();
        store.upsert(entry("k", "t", "common word, second version"), "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        // history=true: exactly the versions (2), no head-world duplicate of current
        let hits = index.search("common", &o(true)).unwrap();
        assert_eq!(hits.len(), 2, "duplicates: {:?}", hits.iter().map(|h| &h.sha).collect::<Vec<_>>());
        assert!(hits.iter().all(|h| !h.is_head));
        let shas: std::collections::HashSet<_> = hits.iter().map(|h| h.sha.clone()).collect();
        assert_eq!(shas.len(), 2);
        // head: exactly one current
        let hits = index.search("common", &o(false)).unwrap();
        assert_eq!(hits.len(), 1);
        assert!(hits[0].is_head);
    }

    // --- tags: AND semantics and case-insensitivity ---
    #[test]
    fn multi_tag_and_semantics() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let mut e = entry("k", "t", "body");
        e.tags = vec!["NATS".into(), "Infra".into()];
        store.upsert(e, "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let search_tags = |tags: &[&str]| {
            index
                .search("", &SearchOpts {
                    tags: tags.iter().map(|s| s.to_string()).collect(),
                    limit: 10,
                    ..Default::default()
                })
                .unwrap()
                .len()
        };
        assert_eq!(search_tags(&["nats"]), 1, "case must not matter");
        assert_eq!(search_tags(&["NATS", "infra"]), 1, "both tags present");
        assert_eq!(search_tags(&["nats", "prod"]), 0, "AND: prod is absent");
        assert_eq!(search_tags(&["prod"]), 0);
    }

    // A tag is a topic label; free-text search must honour it even when the
    // word never appears in the prose — otherwise you can only find a tag you
    // already guessed.
    #[test]
    fn tags_are_searchable_as_text() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let mut e = entry("probe", "Nothing to see", "This body talks about apples and bicycles.");
        e.tags = vec!["kubernetes".into(), "multi-word-tag".into()];
        store.upsert(e, "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        assert_eq!(index.search("kubernetes", &o(false)).unwrap().len(), 1, "tag must be findable");
        assert_eq!(index.search("multi word tag", &o(false)).unwrap().len(), 1, "dashed tag tokenized");
        assert!(index.search("postgres", &o(false)).unwrap().is_empty(), "no false positives");
    }

    // The key itself carries meaning; "nats streams" should reach nats-streams
    // even when the prose never spells it out.
    #[test]
    fn key_is_searchable_tokenized() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        store
            .upsert(entry("orders-api-deploy", "Shipping notes", "Ships through the pipeline."), "2026-07-20")
            .unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        assert_eq!(index.search("orders api", &o(false)).unwrap().len(), 1);
        assert_eq!(index.search("orders-api-deploy", &o(false)).unwrap().len(), 1);
    }

    #[test]
    fn sort_by_recent_overrides_relevance() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        // "shared" appears twice in the older entry, so relevance favours it
        store
            .upsert(entry("older", "Shared shared topic", "shared shared shared word"), "2026-07-19")
            .unwrap();
        store.upsert(entry("newer", "Later note", "shared word once"), "2026-07-20").unwrap();
        let mut w = index.writer().unwrap();
        index.reindex(&mut w, &store).unwrap();

        let by_score = index.search("shared", &o(false)).unwrap();
        assert_eq!(by_score[0].key, "older", "relevance should favour the denser match");

        let by_time = index
            .search("shared", &SearchOpts { tags: vec![], history: false, limit: 10, recent: true, ..Default::default() })
            .unwrap();
        assert_eq!(by_time[0].key, "newer", "recent sort must put the latest commit first");
    }

    // A burst of writes lands within one git-time second (1s granularity), so
    // committed_at ties; recent order must still be exact insertion order —
    // both incrementally and after a full reindex.
    #[test]
    fn recent_sort_stable_within_one_second() {
        let data = tempfile::tempdir().unwrap();
        let idxd = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idxd.path()).unwrap();
        let mut w = index.writer().unwrap();
        for i in 0..6 {
            let out = store.upsert(entry(&format!("burst-{i}"), "t", "same body"), &format!("2026-07-22T00:00:0{i}Z")).unwrap();
            let c = match out {
                crate::store::UpsertOutcome::Created(c) => c,
                _ => panic!(),
            };
            index.upsert_head(&mut w, &c.entry, &c.sha, c.committed_at).unwrap();
        }
        index.commit_and_reload(&mut w).unwrap();
        let opts = SearchOpts { limit: 10, recent: true, ..Default::default() };
        let keys = |index: &SearchIndex| -> Vec<String> {
            index.search("", &opts).unwrap().into_iter().map(|h| h.key).collect()
        };
        let want: Vec<String> = (0..6).rev().map(|i| format!("burst-{i}")).collect();
        assert_eq!(keys(&index), want, "incremental path");
        index.reindex(&mut w, &store).unwrap();
        assert_eq!(keys(&index), want, "after full reindex");
    }

    #[test]
    fn limit_respected() {
        let docs: Vec<(String, String, String)> = (0..7)
            .map(|i| (format!("k-{i}"), format!("title {i}"), "the same body about the service".to_string()))
            .collect();
        let refs: Vec<(&str, &str, &str)> =
            docs.iter().map(|(a, b, c)| (a.as_str(), b.as_str(), c.as_str())).collect();
        let (index, _d, _i) = mini(&refs);
        for limit in [1, 3, 7, 50] {
            let hits = index
                .search("service", &SearchOpts { limit, ..Default::default() })
                .unwrap();
            assert_eq!(hits.len(), limit.min(7), "limit={limit}");
        }
    }

    #[test]
    fn search_head_and_history() {
        let data = tempfile::tempdir().unwrap();
        let idx_dir = tempfile::tempdir().unwrap();
        let store = Store::open(data.path()).unwrap();
        let index = SearchIndex::open_or_create(idx_dir.path()).unwrap();
        let mut w = index.writer().unwrap();

        // v1 body is Russian on purpose — the ru-stem check below needs it
        store
            .upsert(entry("nats-streams", "NATS: CreateOrUpdateStream", "Всегда используем стримы через CreateOrUpdateStream."), "2026-07-19")
            .unwrap();
        store
            .upsert(entry("nats-streams", "NATS: CreateOrUpdateStream", "New rule: config moved to terraform."), "2026-07-20")
            .unwrap();
        let (heads, hist) = index.reindex(&mut w, &store).unwrap();
        assert_eq!(heads, 1);
        assert_eq!(hist, 2);

        let opts = |history| SearchOpts { tags: vec![], history, limit: 10, ..Default::default() };

        // russian stem: "стримах" matches "стримы" from the old version → history only
        let old_only = index.search("стримах", &opts(false)).unwrap();
        assert!(old_only.is_empty(), "old text must not be found in HEAD");
        let old_hist = index.search("стримах", &opts(true)).unwrap();
        assert_eq!(old_hist.len(), 1);
        assert!(!old_hist[0].is_head);

        // current text is found in HEAD, sha is set
        let head = index.search("terraform config", &opts(false)).unwrap();
        assert_eq!(head.len(), 1);
        assert!(head[0].is_head);
        assert_eq!(head[0].sha.len(), 40);

        // tag filter
        let tagged = index
            .search("nats", &SearchOpts { tags: vec!["infra".into()], history: false, limit: 10, recent: false, ..Default::default() })
            .unwrap();
        assert_eq!(tagged.len(), 1);
        let missing = index
            .search("nats", &SearchOpts { tags: vec!["absent".into()], history: false, limit: 10, recent: false, ..Default::default() })
            .unwrap();
        assert!(missing.is_empty());

        // incremental upsert without a full reindex
        let out = store.upsert(entry("orders-api", "orders_api deploys", "Deploys go through the pipeline only."), "2026-07-20").unwrap();
        let c = match out {
            crate::store::UpsertOutcome::Created(c) => c,
            _ => panic!(),
        };
        index.upsert_head(&mut w, &c.entry, &c.sha, c.committed_at).unwrap();
        index.commit_and_reload(&mut w).unwrap();
        let found = index.search("pipeline deploys", &opts(false)).unwrap();
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].key, "orders-api");
    }
}