minutes-core 0.18.7

Core library for minutes — audio capture, transcription, and meeting memory
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
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
use crate::config::Config;
use crate::error::SearchError;
use crate::markdown::{extract_field, split_frontmatter, Frontmatter, IntentKind};
use crate::overlays;
use chrono::Local;
use serde::Serialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// Directories within `output_dir` that should be excluded from search results.
/// These contain archived, processed, or failed files that are not active meetings.
const EXCLUDED_DIRS: &[&str] = &["archive", "processed", "failed", "failed-captures"];

/// Walk `dir` for `.md` files, skipping excluded subdirectories.
fn walk_meeting_files(dir: &Path) -> impl Iterator<Item = walkdir::DirEntry> {
    WalkDir::new(dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| {
            if e.file_type().is_dir() {
                let name = e.file_name().to_string_lossy();
                !EXCLUDED_DIRS.contains(&name.as_ref())
            } else {
                true
            }
        })
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
}

// ──────────────────────────────────────────────────────────────
// Built-in search: walk dir + case-insensitive text match.
// Zero dependencies beyond walkdir. Fast enough for <1000 files.
//
// Config can swap to QMD engine for semantic search:
//   [search]
//   engine = "qmd"
//   qmd_collection = "meetings"
// ──────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct SearchResult {
    pub path: PathBuf,
    pub title: String,
    pub date: String,
    pub content_type: String,
    pub snippet: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matched_via_alias: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IntentResult {
    pub path: PathBuf,
    pub title: String,
    pub date: String,
    pub content_type: String,
    pub kind: IntentKind,
    pub what: String,
    pub who: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub who_original: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub who_provenance: Option<String>,
    pub status: String,
    pub by_date: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ReportEntry {
    pub path: PathBuf,
    pub title: String,
    pub date: String,
    pub what: String,
    pub who: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub who_original: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub who_provenance: Option<String>,
    pub by_date: Option<String>,
    /// Frontmatter v2: optional authority grade ("high" | "medium" | "low").
    /// Propagated from the source decision when present. None for pre-v2
    /// frontmatter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct DecisionConflict {
    pub topic: String,
    pub latest: ReportEntry,
    pub previous: Vec<ReportEntry>,
    /// Frontmatter v2: when the latest decision explicitly `supersedes` an
    /// earlier one, this carries the supersession rationale. Consumers like
    /// `/minutes-lint` should treat resolved conflicts as informational
    /// rather than red flags. None means this is an unresolved contradiction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolution: Option<String>,
}

#[derive(Debug, Clone, Default)]
struct OwnerResolution {
    who: Option<String>,
    who_original: Option<String>,
    who_provenance: Option<String>,
}

#[derive(Debug, Clone)]
struct SpeakerOwner {
    name: String,
    provenance: String,
}

fn speaker_overlay_map(
    frontmatter: &Frontmatter,
    overlay_db_path: &Path,
    meeting_path: &Path,
) -> HashMap<String, SpeakerOwner> {
    let mut speakers = frontmatter
        .speaker_map
        .iter()
        .filter(|attr| attr.confidence == crate::diarize::Confidence::High)
        .map(|attr| {
            (
                attr.speaker_label.clone(),
                SpeakerOwner {
                    name: attr.name.clone(),
                    provenance: "speaker_map".to_string(),
                },
            )
        })
        .collect::<HashMap<_, _>>();

    match overlays::load_speaker_confirmations_for_meeting_at(overlay_db_path, meeting_path) {
        Ok(confirmations) => {
            for confirmation in confirmations {
                speakers.insert(
                    confirmation.speaker_label,
                    SpeakerOwner {
                        name: confirmation.name,
                        provenance: "speaker overlay".to_string(),
                    },
                );
            }
        }
        Err(error) => {
            tracing::warn!(
                path = %meeting_path.display(),
                error = %error,
                "failed to load speaker overlays for reporting"
            );
        }
    }

    speakers
}

fn resolve_owner_with_speaker_overlays(
    who: Option<&str>,
    speaker_overlays: &HashMap<String, SpeakerOwner>,
) -> OwnerResolution {
    let Some(raw) = who.map(str::trim).filter(|value| !value.is_empty()) else {
        return OwnerResolution::default();
    };

    if let Some(speaker) = speaker_overlays.get(raw) {
        return OwnerResolution {
            who: Some(speaker.name.clone()),
            who_original: Some(raw.to_string()),
            who_provenance: Some(speaker.provenance.clone()),
        };
    }

    OwnerResolution {
        who: Some(raw.to_string()),
        who_original: None,
        who_provenance: None,
    }
}

fn owner_matches(resolution: &OwnerResolution, owner_lower: &str) -> bool {
    resolution
        .who
        .as_ref()
        .is_some_and(|who| who.to_lowercase().contains(owner_lower))
        || resolution
            .who_original
            .as_ref()
            .is_some_and(|who| who.to_lowercase().contains(owner_lower))
}

fn explicit_supersedes_resolution(
    latest_supersedes: Option<&str>,
    conflicting_previous: &[ReportEntry],
) -> Option<String> {
    let value = latest_supersedes
        .map(str::trim)
        .filter(|value| !value.is_empty())?;

    // `supersedes` is a free-text pointer. It's reliable for a simple
    // one-new-decision-replaces-one-prior-decision case, but not strong enough
    // to auto-resolve an entire topic arc when multiple contradictory prior
    // decisions remain. Stay conservative so `/minutes-lint` doesn't hide a
    // still-live conflict as "resolved".
    if conflicting_previous.len() != 1 {
        return None;
    }

    if !supersedes_references_previous_decision(value, &conflicting_previous[0]) {
        return None;
    }

    Some(format!("Resolved by explicit supersedes: {}", value))
}

fn supersedes_references_previous_decision(supersedes: &str, previous: &ReportEntry) -> bool {
    let supersedes_norm = normalize_decision_value(supersedes);
    if supersedes_norm.is_empty() {
        return false;
    }

    let previous_date = previous
        .date
        .split('T')
        .next()
        .unwrap_or(previous.date.as_str());
    let previous_date_norm = normalize_decision_value(previous_date);
    if !previous_date_norm.is_empty() && supersedes_norm.contains(&previous_date_norm) {
        return true;
    }

    let previous_title_norm = normalize_decision_value(&previous.title);
    if previous_title_norm.len() >= 4 && supersedes_norm.contains(&previous_title_norm) {
        return true;
    }

    let previous_what_norm = normalize_decision_value(&previous.what);
    if previous_what_norm.is_empty() {
        return false;
    }

    let supersedes_tokens = supersedes_norm
        .split_whitespace()
        .filter(|token| token.len() >= 4)
        .collect::<std::collections::HashSet<_>>();
    let previous_tokens = previous_what_norm
        .split_whitespace()
        .filter(|token| token.len() >= 4)
        .collect::<std::collections::HashSet<_>>();

    supersedes_tokens
        .intersection(&previous_tokens)
        .take(2)
        .count()
        >= 2
}

#[derive(Debug, Clone, Serialize)]
pub struct StaleCommitment {
    pub kind: IntentKind,
    pub entry: ReportEntry,
    pub meetings_since: usize,
    pub age_days: i64,
    pub reasons: Vec<String>,
    pub latest_follow_up: Option<MeetingReference>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ConsistencyReport {
    pub decision_conflicts: Vec<DecisionConflict>,
    pub stale_commitments: Vec<StaleCommitment>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TopicSummary {
    pub topic: String,
    pub count: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct MeetingReference {
    pub path: PathBuf,
    pub title: String,
    pub date: String,
    pub content_type: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct PersonProfile {
    pub name: String,
    pub recent_meetings: Vec<MeetingReference>,
    pub open_intents: Vec<IntentResult>,
    pub recent_decisions: Vec<ReportEntry>,
    pub top_topics: Vec<TopicSummary>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CrossMeetingResearch {
    pub query: String,
    pub related_decisions: Vec<ReportEntry>,
    pub related_open_intents: Vec<IntentResult>,
    pub recent_meetings: Vec<MeetingReference>,
    pub related_topics: Vec<TopicSummary>,
}

#[derive(Default)]
pub struct SearchFilters {
    pub content_type: Option<String>,
    pub since: Option<String>,
    pub attendee: Option<String>,
    pub intent_kind: Option<IntentKind>,
    pub owner: Option<String>,
    pub recorded_by: Option<String>,
}

/// Resolve a meeting file by slug prefix (date-title pattern).
/// Returns the first match found in the output directory.
pub fn resolve_slug(slug: &str, config: &Config) -> Option<PathBuf> {
    if slug.is_empty() {
        return None;
    }

    let dir = &config.output_dir;
    if !dir.exists() {
        return None;
    }

    for entry in walk_meeting_files(dir) {
        let filename = entry
            .path()
            .file_stem()
            .unwrap_or_default()
            .to_string_lossy();
        if filename.to_lowercase().contains(&slug.to_lowercase()) {
            return Some(entry.path().to_path_buf());
        }
    }

    None
}

pub fn cross_meeting_research(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
) -> Result<CrossMeetingResearch, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Err(SearchError::DirNotFound(dir.display().to_string()));
    }

    let query_lower = query.to_lowercase();
    let mut related_decisions = Vec::new();
    let mut related_open_intents = Vec::new();
    let mut recent_meetings = Vec::new();
    let mut topic_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();
    let overlay_db_path = overlays::default_db_path();

    for entry in walk_meeting_files(dir) {
        let path = entry.path();
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping file in cross-meeting research");
                continue;
            }
        };

        let (frontmatter_str, _) = split_frontmatter(&content);
        if frontmatter_str.is_empty() {
            continue;
        }

        let frontmatter: Frontmatter = match serde_yaml::from_str(frontmatter_str) {
            Ok(frontmatter) => frontmatter,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping malformed frontmatter in cross-meeting research");
                continue;
            }
        };

        let content_type = match frontmatter.r#type {
            crate::markdown::ContentType::Meeting => "meeting".to_string(),
            crate::markdown::ContentType::Memo => "memo".to_string(),
            crate::markdown::ContentType::Dictation => "dictation".to_string(),
        };
        let speaker_overlays = speaker_overlay_map(&frontmatter, &overlay_db_path, path);
        if let Some(ref type_filter) = filters.content_type {
            if content_type != *type_filter {
                continue;
            }
        }

        let date = frontmatter.date.to_rfc3339();
        if let Some(ref since) = filters.since {
            if date < *since {
                continue;
            }
        }
        if let Some(ref attendee) = filters.attendee {
            let attendee_lower = attendee.to_lowercase();
            let attendee_match = frontmatter
                .attendees
                .iter()
                .any(|name| name.to_lowercase().contains(&attendee_lower))
                || frontmatter
                    .people
                    .iter()
                    .any(|person| person.to_lowercase().contains(&attendee_lower));
            if !attendee_match {
                continue;
            }
        }

        let meeting_matches = frontmatter.title.to_lowercase().contains(&query_lower)
            || frontmatter
                .context
                .as_ref()
                .map(|context| context.to_lowercase().contains(&query_lower))
                .unwrap_or(false);

        let mut matched_this_meeting = meeting_matches;

        for decision in &frontmatter.decisions {
            let topic = decision
                .topic
                .clone()
                .unwrap_or_else(|| normalize_topic(&decision.text));
            let haystack = format!("{} {}", topic, decision.text).to_lowercase();
            if haystack.contains(&query_lower) {
                matched_this_meeting = true;
                if !topic.is_empty() {
                    *topic_counts.entry(topic).or_insert(0) += 1;
                }
                related_decisions.push(ReportEntry {
                    path: path.to_path_buf(),
                    title: frontmatter.title.clone(),
                    date: date.clone(),
                    what: decision.text.clone(),
                    who: None,
                    who_original: None,
                    who_provenance: None,
                    by_date: None,
                    authority: decision.authority.clone(),
                });
            }
        }

        for intent in &frontmatter.intents {
            let owner_resolution =
                resolve_owner_with_speaker_overlays(intent.who.as_deref(), &speaker_overlays);
            let haystack = format!(
                "{} {} {} {} {}",
                intent.what,
                owner_resolution.who.clone().unwrap_or_default(),
                owner_resolution.who_original.clone().unwrap_or_default(),
                intent.status,
                intent.by_date.clone().unwrap_or_default()
            )
            .to_lowercase();
            if !haystack.contains(&query_lower) {
                continue;
            }

            matched_this_meeting = true;
            let topic = normalize_topic(&intent.what);
            if !topic.is_empty() {
                *topic_counts.entry(topic).or_insert(0) += 1;
            }

            if intent.status == "open" {
                related_open_intents.push(IntentResult {
                    path: path.to_path_buf(),
                    title: frontmatter.title.clone(),
                    date: date.clone(),
                    content_type: content_type.clone(),
                    kind: intent.kind,
                    what: intent.what.clone(),
                    who: owner_resolution.who.clone(),
                    who_original: owner_resolution.who_original.clone(),
                    who_provenance: owner_resolution.who_provenance.clone(),
                    status: intent.status.clone(),
                    by_date: intent.by_date.clone(),
                });
            }
        }

        if matched_this_meeting {
            recent_meetings.push(MeetingReference {
                path: path.to_path_buf(),
                title: frontmatter.title.clone(),
                date,
                content_type,
            });
        }
    }

    related_decisions.sort_by(|a, b| b.date.cmp(&a.date));
    related_open_intents.sort_by(|a, b| b.date.cmp(&a.date));
    recent_meetings.sort_by(|a, b| b.date.cmp(&a.date));

    let mut related_topics: Vec<TopicSummary> = topic_counts
        .into_iter()
        .map(|(topic, count)| TopicSummary { topic, count })
        .collect();
    related_topics.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.topic.cmp(&b.topic)));

    related_decisions.truncate(10);
    related_open_intents.truncate(10);
    recent_meetings.truncate(10);
    related_topics.truncate(5);

    Ok(CrossMeetingResearch {
        query: query.to_string(),
        related_decisions,
        related_open_intents,
        recent_meetings,
        related_topics,
    })
}

/// Search all markdown files in the meetings directory.
pub fn search(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
) -> Result<Vec<SearchResult>, SearchError> {
    search_with_mode(query, config, filters, crate::search_index::SyncMode::Auto)
}

/// Search with explicit sync mode. Lets the CLI expose `--sync` / `--no-sync`
/// flags for piped/scripted use cases without making every other caller think
/// about freshness.
///
/// Logs sync stats (indexed/updated/removed/duration_ms) at INFO level when
/// any work was done. Empty/no-op syncs stay silent. The duration_ms field is
/// the canary for the watcher coalescer decision: if p95 starts approaching
/// the 80ms UI debounce we know the corpus has outgrown the per-file scan.
pub fn search_with_mode(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
    mode: crate::search_index::SyncMode,
) -> Result<Vec<SearchResult>, SearchError> {
    search_with_mode_and_vocabulary(query, config, filters, mode, None)
}

fn search_with_mode_and_vocabulary(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
    mode: crate::search_index::SyncMode,
    vocabulary_override: Option<&crate::vocabulary::VocabularyStore>,
) -> Result<Vec<SearchResult>, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Err(SearchError::DirNotFound(dir.display().to_string()));
    }
    let index = crate::search_index::SearchIndex::open(config)?;
    let stats = index.sync(config, mode)?;
    if stats.indexed + stats.updated + stats.removed + stats.errored > 0 {
        tracing::info!(
            indexed = stats.indexed,
            updated = stats.updated,
            removed = stats.removed,
            errored = stats.errored,
            duration_ms = stats.duration_ms,
            "search index sync"
        );
    }

    let expansions = vocabulary_search_expansions(query, vocabulary_override);
    if expansions.len() <= 1 {
        return Ok(index.search(query, filters, None)?);
    }

    let original_key = search_expansion_key(query);
    let mut merged = Vec::new();
    let mut seen_paths = std::collections::HashSet::new();

    for expansion in expansions {
        let expansion_key = search_expansion_key(&expansion);
        for mut result in index.search(&expansion, filters, None)? {
            if !seen_paths.insert(result.path.clone()) {
                continue;
            }
            if expansion_key != original_key {
                result.matched_via_alias = Some(expansion.clone());
            }
            merged.push(result);
        }
    }

    Ok(merged)
}

fn vocabulary_search_expansions(
    query: &str,
    vocabulary_override: Option<&crate::vocabulary::VocabularyStore>,
) -> Vec<String> {
    if query.trim().is_empty() {
        return Vec::new();
    }

    let mut expansions = vocabulary_override
        .map(|store| store.search_expansions(query))
        .unwrap_or_else(|| {
            crate::vocabulary::load()
                .map(|store| store.search_expansions(query))
                .unwrap_or_else(|error| {
                    tracing::debug!(error = %error, "could not load vocabulary for search expansion");
                    Vec::new()
                })
        });

    if expansions.is_empty() {
        expansions.push(query.trim().to_string());
    } else if !expansions
        .iter()
        .any(|candidate| search_expansion_key(candidate) == search_expansion_key(query))
    {
        expansions.insert(0, query.trim().to_string());
    }

    let mut seen = std::collections::HashSet::new();
    expansions
        .into_iter()
        .filter_map(|candidate| {
            let trimmed = candidate.trim();
            if trimmed.is_empty() {
                return None;
            }
            let key = search_expansion_key(trimmed);
            if seen.insert(key) {
                Some(trimmed.to_string())
            } else {
                None
            }
        })
        .take(8)
        .collect()
}

fn search_expansion_key(value: &str) -> String {
    value
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .trim()
        .to_ascii_lowercase()
}

/// Search structured intents across all markdown files in the meetings directory.
pub fn search_intents(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
) -> Result<Vec<IntentResult>, SearchError> {
    search_intents_at(query, config, filters, &overlays::default_db_path())
}

fn search_intents_at(
    query: &str,
    config: &Config,
    filters: &SearchFilters,
    overlay_db_path: &Path,
) -> Result<Vec<IntentResult>, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Err(SearchError::DirNotFound(dir.display().to_string()));
    }

    let query_lower = query.to_lowercase();
    let mut results = Vec::new();

    for entry in walk_meeting_files(dir) {
        let path = entry.path();
        match process_intent_file(path, &query_lower, filters, overlay_db_path) {
            Ok(mut file_results) => results.append(&mut file_results),
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping file in intent search");
            }
        }
    }

    results.sort_by(|a, b| b.date.cmp(&a.date));
    Ok(results)
}

pub fn consistency_report(
    config: &Config,
    owner: Option<&str>,
    stale_after_days: i64,
) -> Result<ConsistencyReport, SearchError> {
    consistency_report_at(
        config,
        owner,
        stale_after_days,
        &overlays::default_db_path(),
    )
}

fn consistency_report_at(
    config: &Config,
    owner: Option<&str>,
    stale_after_days: i64,
    overlay_db_path: &Path,
) -> Result<ConsistencyReport, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Err(SearchError::DirNotFound(dir.display().to_string()));
    }

    let mut parsed_frontmatters = Vec::new();
    for entry in walk_meeting_files(dir) {
        let path = entry.path();
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping file in consistency report");
                continue;
            }
        };

        let (frontmatter_str, _) = split_frontmatter(&content);
        if frontmatter_str.is_empty() {
            continue;
        }

        match serde_yaml::from_str::<Frontmatter>(frontmatter_str) {
            Ok(frontmatter) => parsed_frontmatters.push((path.to_path_buf(), frontmatter)),
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping malformed frontmatter in consistency report");
            }
        }
    }

    parsed_frontmatters.sort_by_key(|entry| entry.1.date);

    let owner_lower = owner.map(|value| value.to_lowercase());
    let now = Local::now();
    // Each entry carries its source decision's `supersedes` value alongside the
    // ReportEntry so we can detect documented supersessions when the topic
    // group has conflicting decisions.
    let mut decision_groups: std::collections::HashMap<String, Vec<(ReportEntry, Option<String>)>> =
        std::collections::HashMap::new();
    let mut stale_commitments = Vec::new();

    for (path, frontmatter) in &parsed_frontmatters {
        let speaker_overlays = speaker_overlay_map(frontmatter, overlay_db_path, path);

        for decision in &frontmatter.decisions {
            let topic = decision
                .topic
                .as_deref()
                .map(normalize_topic)
                .filter(|topic| !topic.is_empty())
                .unwrap_or_else(|| normalize_topic(&decision.text));
            if topic.is_empty() {
                continue;
            }

            decision_groups.entry(topic).or_default().push((
                ReportEntry {
                    path: path.clone(),
                    title: frontmatter.title.clone(),
                    date: frontmatter.date.to_rfc3339(),
                    what: decision.text.clone(),
                    who: None,
                    who_original: None,
                    who_provenance: None,
                    by_date: None,
                    authority: decision.authority.clone(),
                },
                decision.supersedes.clone(),
            ));
        }

        for intent in &frontmatter.intents {
            if !matches!(intent.kind, IntentKind::Commitment | IntentKind::ActionItem) {
                continue;
            }
            if intent.status != "open" {
                continue;
            }

            let owner_resolution =
                resolve_owner_with_speaker_overlays(intent.who.as_deref(), &speaker_overlays);
            if let Some(ref owner_lower) = owner_lower {
                if !owner_matches(&owner_resolution, owner_lower) {
                    continue;
                }
            }

            let newer_meetings: Vec<_> = parsed_frontmatters
                .iter()
                .filter(|(_, newer)| newer.date > frontmatter.date)
                .collect();
            let meetings_since = newer_meetings.len();
            let age_days = now.signed_duration_since(frontmatter.date).num_days();
            let latest_follow_up =
                newer_meetings
                    .last()
                    .map(|(path, frontmatter)| MeetingReference {
                        path: path.clone(),
                        title: frontmatter.title.clone(),
                        date: frontmatter.date.to_rfc3339(),
                        content_type: match frontmatter.r#type {
                            crate::markdown::ContentType::Meeting => "meeting".to_string(),
                            crate::markdown::ContentType::Memo => "memo".to_string(),
                            crate::markdown::ContentType::Dictation => "dictation".to_string(),
                        },
                    });

            let mut reasons = Vec::new();
            if age_days >= stale_after_days {
                reasons.push(format!("{} days old", age_days));
            }
            if meetings_since >= 3 {
                reasons.push(format!("{} newer meetings since", meetings_since));
            }
            if let Some(by_date) = &intent.by_date {
                if meetings_since >= 1 || age_days >= 1 {
                    reasons.push(format!("still open with due date {}", by_date));
                }
            }
            if intent
                .who
                .as_deref()
                .is_none_or(|who| who.trim().is_empty())
            {
                reasons.push("still open without an owner".to_string());
            }

            if !reasons.is_empty() {
                stale_commitments.push(StaleCommitment {
                    kind: intent.kind,
                    entry: ReportEntry {
                        path: path.clone(),
                        title: frontmatter.title.clone(),
                        date: frontmatter.date.to_rfc3339(),
                        what: intent.what.clone(),
                        who: owner_resolution.who.clone(),
                        who_original: owner_resolution.who_original.clone(),
                        who_provenance: owner_resolution.who_provenance.clone(),
                        by_date: intent.by_date.clone(),
                        authority: None,
                    },
                    meetings_since,
                    age_days,
                    reasons,
                    latest_follow_up,
                });
            }
        }
    }

    let mut decision_conflicts = Vec::new();
    for (topic, mut entries) in decision_groups {
        entries.sort_by(|a, b| a.0.date.cmp(&b.0.date));
        let mut unique_values = std::collections::HashSet::new();
        for (entry, _) in &entries {
            unique_values.insert(normalize_decision_value(&entry.what));
        }

        if unique_values.len() > 1 {
            let (latest_entry, latest_supersedes) = entries.pop().expect("entries not empty");
            let previous_entries: Vec<ReportEntry> =
                entries.into_iter().map(|(entry, _)| entry).collect();
            let resolution =
                explicit_supersedes_resolution(latest_supersedes.as_deref(), &previous_entries);
            decision_conflicts.push(DecisionConflict {
                topic,
                latest: latest_entry,
                previous: previous_entries,
                resolution,
            });
        }
    }

    decision_conflicts.sort_by(|a, b| b.latest.date.cmp(&a.latest.date));
    stale_commitments.sort_by(|a, b| b.entry.date.cmp(&a.entry.date));

    Ok(ConsistencyReport {
        decision_conflicts,
        stale_commitments,
    })
}

pub fn person_profile(config: &Config, person: &str) -> Result<PersonProfile, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Err(SearchError::DirNotFound(dir.display().to_string()));
    }

    let person_lower = person.to_lowercase();
    let mut parsed_frontmatters = Vec::new();
    let overlay_db_path = overlays::default_db_path();
    for entry in walk_meeting_files(dir) {
        let path = entry.path();
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping file in person profile");
                continue;
            }
        };

        let (frontmatter_str, _) = split_frontmatter(&content);
        if frontmatter_str.is_empty() {
            continue;
        }

        match serde_yaml::from_str::<Frontmatter>(frontmatter_str) {
            Ok(frontmatter) => parsed_frontmatters.push((path.to_path_buf(), frontmatter)),
            Err(e) => {
                tracing::warn!(path = %path.display(), error = %e, "skipping malformed frontmatter in person profile");
            }
        }
    }

    parsed_frontmatters.sort_by_key(|entry| std::cmp::Reverse(entry.1.date));

    let mut recent_meetings = Vec::new();
    let mut open_intents = Vec::new();
    let mut recent_decisions = Vec::new();
    let mut topic_counts: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();

    for (path, frontmatter) in parsed_frontmatters {
        let content_type = match frontmatter.r#type {
            crate::markdown::ContentType::Meeting => "meeting".to_string(),
            crate::markdown::ContentType::Memo => "memo".to_string(),
            crate::markdown::ContentType::Dictation => "dictation".to_string(),
        };
        let date = frontmatter.date.to_rfc3339();
        let speaker_overlays = speaker_overlay_map(&frontmatter, &overlay_db_path, &path);

        let attendee_match = frontmatter
            .attendees
            .iter()
            .any(|attendee| attendee.to_lowercase().contains(&person_lower));
        let linked_person_match = frontmatter
            .people
            .iter()
            .any(|person| person.to_lowercase().contains(&person_lower))
            || frontmatter.entities.people.iter().any(|entity| {
                entity.label.to_lowercase().contains(&person_lower)
                    || entity
                        .aliases
                        .iter()
                        .any(|alias| alias.to_lowercase().contains(&person_lower))
            });
        let owned_intent_match = frontmatter.intents.iter().any(|intent| {
            let owner_resolution =
                resolve_owner_with_speaker_overlays(intent.who.as_deref(), &speaker_overlays);
            owner_matches(&owner_resolution, &person_lower)
        });

        if !(attendee_match || linked_person_match || owned_intent_match) {
            continue;
        }

        recent_meetings.push(MeetingReference {
            path: path.clone(),
            title: frontmatter.title.clone(),
            date: date.clone(),
            content_type: content_type.clone(),
        });

        for decision in &frontmatter.decisions {
            recent_decisions.push(ReportEntry {
                path: path.clone(),
                title: frontmatter.title.clone(),
                date: date.clone(),
                what: decision.text.clone(),
                who: None,
                who_original: None,
                who_provenance: None,
                by_date: None,
                authority: decision.authority.clone(),
            });

            let topic = decision
                .topic
                .clone()
                .unwrap_or_else(|| normalize_topic(&decision.text));
            if !topic.is_empty() {
                *topic_counts.entry(topic).or_insert(0) += 1;
            }
        }

        for intent in &frontmatter.intents {
            let owner_resolution =
                resolve_owner_with_speaker_overlays(intent.who.as_deref(), &speaker_overlays);
            let owned_by_person = owner_matches(&owner_resolution, &person_lower);

            if owned_by_person
                && intent.status == "open"
                && matches!(intent.kind, IntentKind::ActionItem | IntentKind::Commitment)
            {
                open_intents.push(IntentResult {
                    path: path.clone(),
                    title: frontmatter.title.clone(),
                    date: date.clone(),
                    content_type: content_type.clone(),
                    kind: intent.kind,
                    what: intent.what.clone(),
                    who: owner_resolution.who.clone(),
                    who_original: owner_resolution.who_original.clone(),
                    who_provenance: owner_resolution.who_provenance.clone(),
                    status: intent.status.clone(),
                    by_date: intent.by_date.clone(),
                });
            }

            if attendee_match || owned_by_person {
                let topic = normalize_topic(&intent.what);
                if !topic.is_empty() {
                    *topic_counts.entry(topic).or_insert(0) += 1;
                }
            }
        }
    }

    recent_meetings.truncate(5);
    recent_decisions.truncate(5);
    open_intents.truncate(10);

    let mut top_topics: Vec<TopicSummary> = topic_counts
        .into_iter()
        .map(|(topic, count)| TopicSummary { topic, count })
        .collect();
    top_topics.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.topic.cmp(&b.topic)));
    top_topics.truncate(5);

    Ok(PersonProfile {
        name: person.to_string(),
        recent_meetings,
        open_intents,
        recent_decisions,
        top_topics,
    })
}

// Legacy walk-and-grep helper. The `search()` public API now delegates to the
// FTS5 index, but `cross_meeting_research`, `person_profile`, and
// `find_open_actions` (deferred to follow-up PRs) still walk files. They'll be
// migrated in their own PRs; meanwhile this stays so the helpers don't need
// to be reinvented later.
#[allow(dead_code)]
fn process_file(
    path: &Path,
    query: &str,
    filters: &SearchFilters,
) -> Result<Option<SearchResult>, SearchError> {
    let content = std::fs::read_to_string(path)?;

    // Parse frontmatter
    let (frontmatter_str, body) = split_frontmatter(&content);
    let title = extract_field(frontmatter_str, "title").unwrap_or_default();
    let date = extract_field(frontmatter_str, "date").unwrap_or_default();
    let content_type = extract_field(frontmatter_str, "type").unwrap_or_else(|| "meeting".into());

    // Apply filters
    if let Some(ref type_filter) = filters.content_type {
        if content_type != *type_filter {
            return Ok(None);
        }
    }
    if let Some(ref since) = filters.since {
        if date < *since {
            return Ok(None);
        }
    }
    if let Some(ref attendee) = filters.attendee {
        let attendees = extract_field(frontmatter_str, "attendees").unwrap_or_default();
        if !attendees.to_lowercase().contains(&attendee.to_lowercase()) {
            return Ok(None);
        }
    }
    if let Some(ref recorded_by) = filters.recorded_by {
        let recorded = extract_field(frontmatter_str, "recorded_by").unwrap_or_default();
        if !recorded
            .to_lowercase()
            .contains(&recorded_by.to_lowercase())
        {
            return Ok(None);
        }
    }

    // Text search (case-insensitive)
    let body_lower = body.to_lowercase();
    let title_lower = title.to_lowercase();

    if body_lower.contains(query) || title_lower.contains(query) {
        let snippet = extract_snippet(body, query);
        Ok(Some(SearchResult {
            path: path.to_path_buf(),
            title,
            date,
            content_type,
            snippet,
            matched_via_alias: None,
        }))
    } else {
        Ok(None)
    }
}

fn process_intent_file(
    path: &Path,
    query: &str,
    filters: &SearchFilters,
    overlay_db_path: &Path,
) -> Result<Vec<IntentResult>, SearchError> {
    let content = std::fs::read_to_string(path)?;
    let (frontmatter_str, _) = split_frontmatter(&content);
    if frontmatter_str.is_empty() {
        return Ok(vec![]);
    }

    let frontmatter: Frontmatter = serde_yaml::from_str(frontmatter_str)
        .map_err(|e| SearchError::Io(std::io::Error::other(e.to_string())))?;

    let date = frontmatter.date.to_rfc3339();
    let content_type = match frontmatter.r#type {
        crate::markdown::ContentType::Meeting => "meeting".to_string(),
        crate::markdown::ContentType::Memo => "memo".to_string(),
        crate::markdown::ContentType::Dictation => "dictation".to_string(),
    };

    if let Some(ref type_filter) = filters.content_type {
        if content_type != *type_filter {
            return Ok(vec![]);
        }
    }
    if let Some(ref since) = filters.since {
        if date < *since {
            return Ok(vec![]);
        }
    }
    if let Some(ref attendee) = filters.attendee {
        let attendee_lower = attendee.to_lowercase();
        let attendee_match = frontmatter
            .attendees
            .iter()
            .any(|name| name.to_lowercase().contains(&attendee_lower));
        if !attendee_match {
            return Ok(vec![]);
        }
    }
    if let Some(ref recorded_by) = filters.recorded_by {
        let matches = frontmatter
            .recorded_by
            .as_ref()
            .is_some_and(|r| r.to_lowercase().contains(&recorded_by.to_lowercase()));
        if !matches {
            return Ok(vec![]);
        }
    }

    let speaker_overlays = speaker_overlay_map(&frontmatter, overlay_db_path, path);
    let mut results = Vec::new();
    for intent in frontmatter.intents {
        if let Some(kind) = filters.intent_kind {
            if intent.kind != kind {
                continue;
            }
        }
        let owner_resolution =
            resolve_owner_with_speaker_overlays(intent.who.as_deref(), &speaker_overlays);
        if let Some(ref owner) = filters.owner {
            let owner_lower = owner.to_lowercase();
            if !owner_matches(&owner_resolution, &owner_lower) {
                continue;
            }
        }

        let haystack = format!(
            "{} {} {} {} {} {}",
            frontmatter.title,
            intent.what,
            owner_resolution.who.clone().unwrap_or_default(),
            owner_resolution.who_original.clone().unwrap_or_default(),
            intent.status,
            intent.by_date.clone().unwrap_or_default()
        )
        .to_lowercase();

        if !query.is_empty() && !haystack.contains(query) {
            continue;
        }

        results.push(IntentResult {
            path: path.to_path_buf(),
            title: frontmatter.title.clone(),
            date: date.clone(),
            content_type: content_type.clone(),
            kind: intent.kind,
            what: intent.what,
            who: owner_resolution.who,
            who_original: owner_resolution.who_original,
            who_provenance: owner_resolution.who_provenance,
            status: intent.status,
            by_date: intent.by_date,
        });
    }

    Ok(results)
}

// split_frontmatter and extract_field are in markdown.rs (shared)

/// Find meetings with open action items, optionally filtered by assignee.
/// Parses YAML frontmatter for the structured action_items field.
pub fn find_open_actions(
    config: &Config,
    assignee: Option<&str>,
) -> Result<Vec<ActionResult>, SearchError> {
    let dir = &config.output_dir;
    if !dir.exists() {
        return Ok(vec![]);
    }

    let mut results = Vec::new();

    for entry in walk_meeting_files(dir) {
        let path = entry.path();
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let (fm_str, _) = split_frontmatter(&content);
        let title = extract_field(fm_str, "title").unwrap_or_default();
        let date = extract_field(fm_str, "date").unwrap_or_default();

        // Parse action_items from frontmatter (YAML list)
        // Look for lines like "  - assignee: mat" within the action_items block
        if !content.contains("action_items:") {
            continue;
        }

        // Simple parse: find action_items section in frontmatter YAML
        // Note: fm_str is already stripped of --- markers by split_frontmatter,
        // so pass it directly — wrapping with --- would create a multi-document
        // YAML that serde_yaml rejects.
        let parsed: Result<serde_yaml::Value, _> = serde_yaml::from_str(fm_str);
        if let Ok(yaml) = parsed {
            if let Some(items) = yaml.get("action_items").and_then(|v| v.as_sequence()) {
                for item in items {
                    let item_assignee = item
                        .get("assignee")
                        .and_then(|v| v.as_str())
                        .unwrap_or("unassigned");
                    let item_status = item
                        .get("status")
                        .and_then(|v| v.as_str())
                        .unwrap_or("open");
                    let item_task = item.get("task").and_then(|v| v.as_str()).unwrap_or("");
                    let item_due = item
                        .get("due")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());

                    if item_status != "open" {
                        continue;
                    }
                    if let Some(filter) = assignee {
                        let a = item_assignee.to_lowercase();
                        let f = filter.to_lowercase();
                        if a != f && !a.contains(&f) {
                            continue;
                        }
                    }

                    results.push(ActionResult {
                        meeting_path: path.to_path_buf(),
                        meeting_title: title.clone(),
                        meeting_date: date.clone(),
                        assignee: item_assignee.to_string(),
                        task: item_task.to_string(),
                        due: item_due,
                    });
                }
            }
        }
    }

    results.sort_by(|a, b| b.meeting_date.cmp(&a.meeting_date));
    Ok(results)
}

/// A structured action item result from cross-meeting search.
#[derive(Debug, Clone, Serialize)]
pub struct ActionResult {
    pub meeting_path: PathBuf,
    pub meeting_title: String,
    pub meeting_date: String,
    pub assignee: String,
    pub task: String,
    pub due: Option<String>,
}

/// Extract a snippet around the first match of the query.
#[allow(dead_code)]
fn extract_snippet(body: &str, query: &str) -> String {
    // Find the query in the body case-insensitively.
    // We search the original body to avoid byte-offset mismatch from to_lowercase().
    let pos = body
        .char_indices()
        .position(|(i, _)| body[i..].to_lowercase().starts_with(query))
        .and_then(|char_idx| body.char_indices().nth(char_idx).map(|(i, _)| i));

    if let Some(pos) = pos {
        let start = body[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
        let end = body[pos..]
            .find('\n')
            .map(|i| pos + i)
            .unwrap_or(body.len());

        let line = body[start..end].trim();
        if line.chars().count() > 200 {
            let truncated: String = line.chars().take(200).collect();
            format!("{}...", truncated)
        } else {
            line.to_string()
        }
    } else {
        String::new()
    }
}

fn normalize_topic(text: &str) -> String {
    let stopwords = [
        "a", "an", "and", "as", "at", "by", "for", "from", "in", "of", "on", "or", "the", "to",
        "with", "we", "should", "will", "be", "is", "are", "use", "using",
    ];

    text.split_whitespace()
        .map(|word| word.trim_matches(|c: char| !c.is_alphanumeric()))
        .filter(|word| !word.is_empty())
        .filter(|word| !stopwords.contains(&word.to_lowercase().as_str()))
        .take(4)
        .map(|word| word.to_lowercase())
        .collect::<Vec<_>>()
        .join(" ")
}

fn normalize_decision_value(text: &str) -> String {
    text.chars()
        .map(|ch| {
            if ch.is_alphanumeric() || ch.is_whitespace() {
                ch.to_ascii_lowercase()
            } else {
                ' '
            }
        })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_file(dir: &Path, name: &str, content: &str) {
        let path = dir.join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }

    #[test]
    fn search_finds_matching_content() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Test Meeting\ndate: 2026-03-17\ntype: meeting\n---\n\n## Transcript\n\nWe discussed pricing strategy in detail.",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };

        let results = search("pricing", &config, &filters).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].snippet.contains("pricing"));
    }

    #[test]
    fn search_returns_empty_for_no_match() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "test.md",
            "---\ntitle: Test\ndate: 2026-03-17\n---\n\nHello world.",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };

        let results = search("nonexistent", &config, &filters).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn search_is_case_insensitive() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "test.md",
            "---\ntitle: Test\ndate: 2026-03-17\n---\n\nPRICING discussion",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };

        let results = search("pricing", &config, &filters).unwrap();
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn search_expands_vocabulary_aliases_with_provenance() {
        let _guard = crate::test_home_env_lock();
        let home = TempDir::new().unwrap();
        unsafe {
            std::env::set_var("HOME", home.path());
            std::env::set_var("USERPROFILE", home.path());
        }

        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "test.md",
            "---\ntitle: Writing Tools\ndate: 2026-05-01\ntype: meeting\n---\n\nWe discussed Automatic and Harper.",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters::default();
        let vocabulary = crate::vocabulary::VocabularyStore {
            entries: vec![crate::vocabulary::VocabularyEntry {
                kind: crate::vocabulary::VocabularyKind::Organization,
                canonical: "Automattic".into(),
                aliases: vec!["Automatic".into()],
                ..crate::vocabulary::VocabularyEntry::default()
            }],
        }
        .normalized()
        .unwrap();

        let results = search_with_mode_and_vocabulary(
            "Automattic",
            &config,
            &filters,
            crate::search_index::SyncMode::Force,
            Some(&vocabulary),
        )
        .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].matched_via_alias.as_deref(), Some("Automatic"));
    }

    #[test]
    fn search_filters_by_recorded_by() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "test.md",
            "---\ntitle: Test\ndate: 2026-03-17\nrecorded_by: Mat Silver\ntype: meeting\n---\n\nPricing discussion",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let matching_filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: Some("mat".into()),
        };
        let non_matching_filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: Some("sarah".into()),
        };

        let matching_results = search("pricing", &config, &matching_filters).unwrap();
        let non_matching_results = search("pricing", &config, &non_matching_filters).unwrap();

        assert_eq!(matching_results.len(), 1);
        assert!(non_matching_results.is_empty());
    }

    #[test]
    fn search_empty_directory() {
        let dir = TempDir::new().unwrap();
        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };

        let results = search("anything", &config, &filters).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn split_frontmatter_works() {
        let content = "---\ntitle: Test\ndate: 2026-03-17\n---\n\nBody text here.";
        let (fm, body) = split_frontmatter(content);
        assert!(fm.contains("title: Test"));
        assert!(body.contains("Body text here"));
    }

    #[test]
    fn extract_field_finds_value() {
        let fm = "title: My Meeting\ndate: 2026-03-17\ntype: meeting";
        assert_eq!(extract_field(fm, "title"), Some("My Meeting".into()));
        assert_eq!(extract_field(fm, "type"), Some("meeting".into()));
        assert_eq!(extract_field(fm, "nonexistent"), None);
    }

    #[test]
    fn search_intents_returns_matching_structured_records() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nintents:\n  - kind: action-item\n    what: Send pricing doc\n    who: mat\n    status: open\n    by_date: Friday\n  - kind: commitment\n    what: Share revised pricing model\n    who: sarah\n    status: open\n    by_date: Tuesday\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );

        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };

        let overlay_db = dir.path().join("overlays.db");
        let results = process_intent_file(
            &dir.path().join("2026-03-17-test.md"),
            "pricing",
            &filters,
            &overlay_db,
        )
        .unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].title, "Pricing Review");
        assert!(results
            .iter()
            .any(|item| item.kind == IntentKind::ActionItem));
        assert!(results
            .iter()
            .any(|item| item.kind == IntentKind::Commitment));
    }

    #[test]
    fn search_intents_filters_by_kind_and_owner() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nintents:\n  - kind: action-item\n    what: Send pricing doc\n    who: mat\n    status: open\n    by_date: Friday\n  - kind: commitment\n    what: Share revised pricing model\n    who: sarah\n    status: open\n    by_date: Tuesday\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );

        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: Some(IntentKind::Commitment),
            owner: Some("sarah".into()),
            recorded_by: None,
        };

        let overlay_db = dir.path().join("overlays.db");
        let results = process_intent_file(
            &dir.path().join("2026-03-17-test.md"),
            "",
            &filters,
            &overlay_db,
        )
        .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].kind, IntentKind::Commitment);
        assert_eq!(results[0].who.as_deref(), Some("sarah"));
    }

    #[test]
    fn search_intents_filters_owner_through_speaker_overlay() {
        let dir = TempDir::new().unwrap();
        let meeting = dir.path().join("2026-03-17-test.md");
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nspeaker_map:\n  - speaker_label: SPEAKER_0\n    name: Unknown Speaker\n    confidence: medium\n    source: llm\nintents:\n  - kind: action-item\n    what: Send pricing doc\n    who: SPEAKER_0\n    status: open\n    by_date: Friday\n---\n\n## Transcript\n\n[SPEAKER_0 0:00] I'll send pricing.\n",
        );

        let overlay_db = dir.path().join("overlays.db");
        crate::overlays::write_speaker_confirmation_at(
            &overlay_db,
            &meeting,
            "SPEAKER_0",
            "Alex Kim",
            Some("Unknown Speaker"),
            Some("test owner resolution"),
        )
        .unwrap();

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: Some(IntentKind::ActionItem),
            owner: Some("alex".into()),
            recorded_by: None,
        };

        let results = search_intents_at("", &config, &filters, &overlay_db).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].who.as_deref(), Some("Alex Kim"));
        assert_eq!(results[0].who_original.as_deref(), Some("SPEAKER_0"));
        assert_eq!(
            results[0].who_provenance.as_deref(),
            Some("speaker overlay")
        );
    }

    #[test]
    fn search_intents_filter_by_recorded_by() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: []\npeople: []\nrecorded_by: Mat Silver\naction_items: []\ndecisions: []\nintents:\n  - kind: action-item\n    what: Send pricing doc\n    who: mat\n    status: open\n    by_date: Friday\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );

        let matching_filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: Some("mat".into()),
        };
        let non_matching_filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: Some("sarah".into()),
        };

        let matching_results = process_intent_file(
            &dir.path().join("2026-03-17-test.md"),
            "",
            &matching_filters,
            &dir.path().join("overlays.db"),
        )
        .unwrap();
        let non_matching_results = process_intent_file(
            &dir.path().join("2026-03-17-test.md"),
            "",
            &non_matching_filters,
            &dir.path().join("overlays.db"),
        )
        .unwrap();

        assert_eq!(matching_results.len(), 1);
        assert!(non_matching_results.is_empty());
    }

    #[test]
    fn consistency_report_flags_conflicts_and_stale_commitments() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-01-a.md",
            "---\ntitle: Pricing Decision\ntype: meeting\ndate: 2026-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch pricing at annual billing per month\n    topic: pricing\nintents:\n  - kind: commitment\n    what: Send pricing doc\n    who: case\n    status: open\n    by_date: March 8\n---\n\n## Transcript\n\nPricing discussion.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-12-b.md",
            "---\ntitle: Pricing Revisit\ntype: meeting\ndate: 2026-03-12T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch pricing at monthly billing per month\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nPricing changed.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-20-c.md",
            "---\ntitle: Follow-up\ntype: meeting\ndate: 2026-03-20T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nintents: []\n---\n\n## Transcript\n\nFollow-up.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-25-d.md",
            "---\ntitle: Another Follow-up\ntype: meeting\ndate: 2026-03-25T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nintents: []\n---\n\n## Transcript\n\nAnother follow-up.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert_eq!(report.decision_conflicts.len(), 1);
        assert_eq!(report.decision_conflicts[0].topic, "pricing");
        assert_eq!(report.decision_conflicts[0].previous.len(), 1);
        assert_eq!(report.stale_commitments.len(), 1);
        assert_eq!(
            report.stale_commitments[0].entry.who.as_deref(),
            Some("case")
        );
        assert!(report.stale_commitments[0].meetings_since >= 3);
        assert!(report.stale_commitments[0]
            .reasons
            .iter()
            .any(|reason| reason.contains("days old")));
        assert!(report.stale_commitments[0]
            .reasons
            .iter()
            .any(|reason| reason.contains("newer meetings since")));
        assert!(report.stale_commitments[0]
            .reasons
            .iter()
            .any(|reason| reason.contains("still open with due date March 8")));
        assert_eq!(
            report.stale_commitments[0]
                .latest_follow_up
                .as_ref()
                .map(|meeting| meeting.title.as_str()),
            Some("Another Follow-up")
        );
    }

    #[test]
    fn consistency_report_resolves_stale_owner_through_speaker_overlay() {
        let dir = TempDir::new().unwrap();
        let meeting = dir.path().join("2020-03-01-a.md");
        create_test_file(
            dir.path(),
            "2020-03-01-a.md",
            "---\ntitle: Follow-up Owner\ntype: meeting\ndate: 2020-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nspeaker_map:\n  - speaker_label: SPEAKER_0\n    name: Unknown Speaker\n    confidence: medium\n    source: llm\nintents:\n  - kind: commitment\n    what: Send the rollout memo\n    who: SPEAKER_0\n    status: open\n    by_date: March 8\n---\n\n## Transcript\n\n[SPEAKER_0 0:00] I'll send it.\n",
        );

        let overlay_db = dir.path().join("overlays.db");
        crate::overlays::write_speaker_confirmation_at(
            &overlay_db,
            &meeting,
            "SPEAKER_0",
            "Alex Kim",
            Some("Unknown Speaker"),
            Some("test consistency owner resolution"),
        )
        .unwrap();

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };
        let report = consistency_report_at(&config, Some("alex"), 7, &overlay_db).unwrap();

        assert_eq!(report.stale_commitments.len(), 1);
        let entry = &report.stale_commitments[0].entry;
        assert_eq!(entry.who.as_deref(), Some("Alex Kim"));
        assert_eq!(entry.who_original.as_deref(), Some("SPEAKER_0"));
        assert_eq!(entry.who_provenance.as_deref(), Some("speaker overlay"));
    }

    #[test]
    fn consistency_report_marks_conflict_resolved_when_supersedes_is_set() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-02-28-a.md",
            "---\ntitle: Pricing Strategy\ntype: meeting\ndate: 2026-02-28T10:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch monthly billing for consultants\n    topic: pricing\n    authority: high\nintents: []\n---\n\n## Transcript\n\nDecision A.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-25-b.md",
            "---\ntitle: Pricing Reversal\ntype: meeting\ndate: 2026-03-25T10:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Revert to annual-only billing across all segments\n    topic: pricing\n    authority: high\n    supersedes: \"2026-02-28 monthly billing decision\"\nintents: []\n---\n\n## Transcript\n\nDecision B reverses A.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert_eq!(report.decision_conflicts.len(), 1);
        let conflict = &report.decision_conflicts[0];
        assert_eq!(conflict.topic, "pricing");
        assert!(conflict.resolution.is_some());
        assert!(conflict.resolution.as_ref().unwrap().contains("2026-02-28"));
        assert_eq!(conflict.latest.authority.as_deref(), Some("high"));
        assert_eq!(conflict.previous[0].authority.as_deref(), Some("high"));
    }

    #[test]
    fn consistency_report_leaves_resolution_none_without_supersedes() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-01-a.md",
            "---\ntitle: A\ntype: meeting\ndate: 2026-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch monthly billing\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nA.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-12-b.md",
            "---\ntitle: B\ntype: meeting\ndate: 2026-03-12T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Stay on annual billing\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nB without supersedes.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert_eq!(report.decision_conflicts.len(), 1);
        assert!(report.decision_conflicts[0].resolution.is_none());
        assert!(report.decision_conflicts[0].latest.authority.is_none());
    }

    #[test]
    fn consistency_report_does_not_mark_resolution_when_other_conflicts_remain() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-01-a.md",
            "---\ntitle: A\ntype: meeting\ndate: 2026-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch monthly billing\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nA.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-12-b.md",
            "---\ntitle: B\ntype: meeting\ndate: 2026-03-12T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Stay annual only\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nB.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-25-c.md",
            "---\ntitle: C\ntype: meeting\ndate: 2026-03-25T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Test monthly billing for consultants only\n    topic: pricing\n    supersedes: \"2026-03-01 monthly billing decision\"\nintents: []\n---\n\n## Transcript\n\nC.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert_eq!(report.decision_conflicts.len(), 1);
        let conflict = &report.decision_conflicts[0];
        assert_eq!(conflict.previous.len(), 2);
        assert!(conflict.resolution.is_none());
    }

    #[test]
    fn consistency_report_requires_supersedes_to_reference_the_prior_decision() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-01-a.md",
            "---\ntitle: A\ntype: meeting\ndate: 2026-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch monthly billing\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nA.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-12-b.md",
            "---\ntitle: B\ntype: meeting\ndate: 2026-03-12T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Stay annual only\n    topic: pricing\n    supersedes: \"some old plan\"\nintents: []\n---\n\n## Transcript\n\nB.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert_eq!(report.decision_conflicts.len(), 1);
        assert!(report.decision_conflicts[0].resolution.is_none());
    }

    #[test]
    fn consistency_report_ignores_near_duplicate_decisions() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-01-a.md",
            "---\ntitle: Pricing Decision\ntype: meeting\ndate: 2026-03-01T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch pricing at 399 per month\n    topic: pricing strategy\nintents: []\n---\n\n## Transcript\n\nPricing discussion.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-12-b.md",
            "---\ntitle: Pricing Follow-up\ntype: meeting\ndate: 2026-03-12T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions:\n  - text: Launch pricing at 399 per month.\n    topic: pricing strategy\nintents: []\n---\n\n## Transcript\n\nPricing repeated.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let report = consistency_report(&config, None, 7).unwrap();
        assert!(report.decision_conflicts.is_empty());
    }

    #[test]
    fn person_profile_aggregates_recent_meetings_topics_and_open_intents() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-a.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: [Alex]\npeople: []\naction_items: []\ndecisions:\n  - text: Launch pricing at monthly billing per month\n    topic: pricing\nintents:\n  - kind: commitment\n    what: Share revised pricing model\n    who: Alex\n    status: open\n    by_date: Tuesday\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-20-b.md",
            "---\ntitle: Onboarding Follow-up\ntype: meeting\ndate: 2026-03-20T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: [Alex]\npeople: []\naction_items: []\ndecisions: []\nintents:\n  - kind: action-item\n    what: Review onboarding copy\n    who: Alex\n    status: open\n    by_date: Friday\n---\n\n## Transcript\n\nWe discussed onboarding.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let profile = person_profile(&config, "alex").unwrap();
        assert_eq!(profile.name, "alex");
        assert_eq!(profile.recent_meetings.len(), 2);
        assert_eq!(profile.open_intents.len(), 2);
        assert_eq!(profile.recent_decisions.len(), 1);
        assert!(profile
            .top_topics
            .iter()
            .any(|topic| topic.topic == "pricing"));
    }

    #[test]
    fn person_profile_matches_linked_people_entities() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-a.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: []\npeople: [Alex Chen]\nentities:\n  people:\n    - slug: sarah-chen\n      label: Alex Chen\n      aliases: [sarah]\n  projects:\n    - slug: pricing-review\n      label: Pricing Review\n      aliases: [pricing]\naction_items: []\ndecisions:\n  - text: Launch pricing at monthly billing per month\n    topic: pricing\nintents: []\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let profile = person_profile(&config, "sarah").unwrap();
        assert_eq!(profile.recent_meetings.len(), 1);
        assert_eq!(profile.recent_meetings[0].title, "Pricing Review");
    }

    #[test]
    fn cross_meeting_research_collects_decisions_intents_and_meetings() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-a.md",
            "---\ntitle: Pricing Review\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 42m\nstatus: complete\ntags: []\nattendees: [Alex]\npeople: [Alex]\nentities:\n  people:\n    - slug: sarah\n      label: Alex\n      aliases: []\n  projects:\n    - slug: pricing\n      label: Pricing\n      aliases: []\ncontext: pricing review\naction_items: []\ndecisions:\n  - text: Launch pricing at monthly billing per month\n    topic: pricing\nintents:\n  - kind: commitment\n    what: Share revised pricing model\n    who: Alex\n    status: open\n    by_date: Tuesday\n---\n\n## Transcript\n\nWe discussed pricing.\n",
        );
        create_test_file(
            dir.path(),
            "2026-03-20-b.md",
            "---\ntitle: Onboarding Follow-up\ntype: meeting\ndate: 2026-03-20T12:00:00-07:00\nduration: 30m\nstatus: complete\ntags: []\nattendees: []\npeople: []\naction_items: []\ndecisions: []\nintents: []\n---\n\n## Transcript\n\nWe discussed onboarding.\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let filters = SearchFilters {
            content_type: None,
            since: None,
            attendee: None,
            intent_kind: None,
            owner: None,
            recorded_by: None,
        };
        let report = cross_meeting_research("pricing", &config, &filters).unwrap();

        assert_eq!(report.related_decisions.len(), 1);
        assert_eq!(report.related_open_intents.len(), 1);
        assert_eq!(report.recent_meetings.len(), 1);
        assert_eq!(report.recent_meetings[0].title, "Pricing Review");
        assert!(report
            .related_topics
            .iter()
            .any(|topic| topic.topic == "pricing"));
    }

    #[test]
    fn find_open_actions_parses_frontmatter() {
        let dir = TempDir::new().unwrap();
        create_test_file(
            dir.path(),
            "2026-03-17-test.md",
            "---\ntitle: Test\ntype: meeting\ndate: 2026-03-17T12:00:00-07:00\nduration: 5m\nstatus: complete\naction_items:\n  - assignee: mat\n    task: Send doc\n    status: open\n  - assignee: alex\n    task: Review PR\n    status: done\ndecisions: []\nintents: []\n---\n\nTranscript\n",
        );

        let config = Config {
            output_dir: dir.path().to_path_buf(),
            ..Config::default()
        };

        let results = find_open_actions(&config, None).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].assignee, "mat");
        assert_eq!(results[0].task, "Send doc");

        // Filter by assignee
        let filtered = find_open_actions(&config, Some("nobody")).unwrap();
        assert!(filtered.is_empty());
    }
}