bobbin-ai 0.25.2

Local-first context injection engine for AI coding agents
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
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
use anyhow::{bail, Context, Result};
use chrono::Utc;
use clap::Args;
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use super::OutputConfig;
use crate::config::Config;
use crate::index::git::GitAnalyzer;
use crate::index::Embedder;
use crate::search::context::{BridgeMode, ContentMode, ContextAssembler, ContextConfig};
use crate::storage::{MetadataStore, VectorStore};

// --- CLI Args ---

#[derive(Args)]
pub struct CalibrateArgs {
    /// Number of commits to sample from git history
    #[arg(long, short = 'n', default_value = "20")]
    samples: usize,

    /// Time range to sample from (git --since format)
    #[arg(long, default_value = "6 months ago")]
    since: String,

    /// Max results per probe (search limit). If omitted, sweeps [10, 20, 30, 40].
    #[arg(long)]
    search_limit: Option<usize>,

    /// Budget lines per probe. If omitted, sweeps [150, 300, 500].
    #[arg(long)]
    budget: Option<usize>,

    /// Apply best config to .bobbin/calibration.json
    #[arg(long)]
    apply: bool,

    /// Show detailed per-commit results
    #[arg(long)]
    verbose: bool,

    /// Extended calibration: sweep recency and coupling parameters
    #[arg(long)]
    full: bool,

    /// Resume an interrupted --full sweep from cache
    #[arg(long)]
    resume: bool,

    /// Sweep only bridge_mode + bridge_boost_factor using calibrated core params
    #[arg(long)]
    bridge_sweep: bool,

    /// Repository name to calibrate against (for multi-repo setups).
    /// Samples commits from this repo's git history instead of the workspace root.
    /// Source path is resolved from index metadata or --source.
    #[arg(long)]
    repo: Option<String>,

    /// Source directory containing the git repo to sample commits from.
    /// Overrides automatic source path resolution from index metadata.
    #[arg(long)]
    source: Option<PathBuf>,

    /// Directory to calibrate
    #[arg(default_value = ".")]
    path: PathBuf,
}

// --- Calibration Results ---

/// Persisted calibration state
#[derive(Debug, Serialize, Deserialize)]
pub struct CalibrationResult {
    pub calibrated_at: String,
    pub snapshot: ProjectSnapshot,
    pub best_config: CalibratedConfig,
    pub top_results: Vec<GridResult>,
    pub sample_count: usize,
    pub probe_count: usize,
    pub terse_warning: bool,
}

/// Point-in-time snapshot of project characteristics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectSnapshot {
    pub chunk_count: usize,
    pub file_count: usize,
    pub primary_language: String,
    pub language_distribution: Vec<(String, f32)>,
    pub repo_age_days: u32,
    pub recent_commit_rate: f32,
}

/// The calibrated search config values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CalibratedConfig {
    pub semantic_weight: f32,
    pub doc_demotion: f32,
    pub rrf_k: f32,
    /// Best recency half-life in days (only set by --full)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recency_half_life_days: Option<f32>,
    /// Best recency weight (only set by --full)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recency_weight: Option<f32>,
    /// Best coupling depth (only set by --full)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupling_depth: Option<usize>,
    /// Best budget_lines (context line budget)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget_lines: Option<usize>,
    /// Best search_limit (initial search results)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_limit: Option<usize>,
    /// Best bridge mode (only set by --full)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bridge_mode: Option<BridgeMode>,
    /// Best bridge boost factor (only set by --full)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bridge_boost_factor: Option<f32>,
}

/// Result for a single grid point
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridResult {
    pub semantic_weight: f32,
    pub doc_demotion: f32,
    pub rrf_k: f32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recency_half_life_days: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recency_weight: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupling_depth: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub budget_lines: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search_limit: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bridge_mode: Option<BridgeMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bridge_boost_factor: Option<f32>,
    pub precision: f32,
    pub recall: f32,
    pub f1: f32,
}

// --- Commit Sampling ---

/// A sampled commit for calibration probing
struct SampledCommit {
    hash: String,
    message: String,
    files: Vec<String>,
}

/// Sample commits from git history suitable for calibration.
///
/// Filters: skip merges, reverts, >30 files, <2 files, noise prefixes.
/// Stratified sampling across the time range.
fn sample_commits(
    git: &GitAnalyzer,
    since: &str,
    target_count: usize,
) -> Result<Vec<SampledCommit>> {
    // Fetch a large pool of commits to filter from
    let scan_depth = target_count * 20; // Oversample heavily
    let all_commits = git.get_commit_log(scan_depth, None)?;

    // Parse the since date for filtering
    let since_ts = parse_since_timestamp(git, since)?;

    let mut candidates: Vec<SampledCommit> = Vec::new();

    for commit in &all_commits {
        // Time filter
        if commit.timestamp < since_ts {
            continue;
        }

        // Skip merges (no files or "Merge" prefix)
        if commit.files.is_empty() {
            continue;
        }
        if commit.message.starts_with("Merge ") {
            continue;
        }

        // Skip reverts
        if commit.message.starts_with("Revert ") {
            continue;
        }

        // Skip noise commits
        if is_noise_commit(&commit.message) {
            continue;
        }

        // File count bounds: 2..=30
        let file_count = commit.files.len();
        if file_count < 2 || file_count > 30 {
            continue;
        }

        candidates.push(SampledCommit {
            hash: commit.hash.clone(),
            message: commit.message.clone(),
            files: commit.files.clone(),
        });
    }

    if candidates.is_empty() {
        bail!(
            "No suitable commits found in the last {}. \
             Need commits with 2-30 files, non-merge, non-noise.",
            since
        );
    }

    // Stratified sampling: take evenly spaced commits across the candidate list
    // (candidates are in reverse chronological order from git log)
    let selected = if candidates.len() <= target_count {
        candidates
    } else {
        let step = candidates.len() as f64 / target_count as f64;
        (0..target_count)
            .map(|i| {
                let idx = (i as f64 * step) as usize;
                // Safety: idx < candidates.len() because step = len/count
                let idx = idx.min(candidates.len() - 1);
                SampledCommit {
                    hash: candidates[idx].hash.clone(),
                    message: candidates[idx].message.clone(),
                    files: candidates[idx].files.clone(),
                }
            })
            .collect()
    };

    Ok(selected)
}

/// Check if a commit message indicates a non-code change
fn is_noise_commit(message: &str) -> bool {
    let lower = message.to_lowercase();
    let noise_prefixes = [
        "chore:",
        "chore(",
        "ci:",
        "ci(",
        "docs:",
        "docs(",
        "style:",
        "style(",
        "build:",
        "build(",
        "release:",
        "bump ",
        "auto-merge",
        "update dependency",
    ];
    noise_prefixes.iter().any(|p| lower.starts_with(p))
}

/// Parse a "since" string into a unix timestamp.
///
/// Uses `git log --format="" --since=<since> -1` to leverage git's date
/// parsing, then uses `git log --format=%ct --since=<since> --diff-filter=A -1 --reverse`
/// to find the boundary. We actually just need to compute what timestamp the
/// --since flag resolves to, so we ask git for it via `--date=unix`.
fn parse_since_timestamp(git: &GitAnalyzer, since: &str) -> Result<i64> {
    // Use `git log` with --since to find the effective cutoff date.
    // We ask for the boundary by getting the earliest commit IN the range
    // and subtracting 1 second, so `commit.timestamp < since_ts` correctly
    // excludes commits before the window.
    //
    // Simpler approach: compute relative date ourselves for common patterns.
    let now = chrono::Utc::now().timestamp();

    // Try common patterns first
    let lower = since.to_lowercase();
    if let Some(ts) = parse_relative_date(&lower, now) {
        return Ok(ts);
    }

    // Fallback: ask git for the oldest commit in the range and use its timestamp - 1
    let output = std::process::Command::new("git")
        .args([
            "log",
            "--no-merges",
            "--format=%ct",
            &format!("--since={}", since),
            "--reverse",
        ])
        .current_dir(git.repo_root())
        .output()
        .context("Failed to parse --since timestamp")?;

    let first_line = String::from_utf8_lossy(&output.stdout);
    let ts = first_line
        .lines()
        .next()
        .and_then(|l| l.trim().parse::<i64>().ok())
        .unwrap_or(0);

    // Return ts - 1 so that the boundary commit itself passes the < check
    Ok(if ts > 0 { ts - 1 } else { 0 })
}

/// Parse common relative date strings into timestamps.
fn parse_relative_date(s: &str, now: i64) -> Option<i64> {
    let parts: Vec<&str> = s.split_whitespace().collect();
    if parts.len() < 3 || parts.last() != Some(&"ago") {
        return None;
    }
    let n: i64 = parts[0].parse().ok()?;
    let unit = parts[1].trim_end_matches('s'); // "months" -> "month"
    let seconds_per_unit = match unit {
        "second" => 1,
        "minute" => 60,
        "hour" => 3600,
        "day" => 86400,
        "week" => 7 * 86400,
        "month" => 30 * 86400,
        "year" => 365 * 86400,
        _ => return None,
    };
    Some(now - n * seconds_per_unit)
}

/// Detect terse commit messages in the sample
fn detect_terse_messages(commits: &[SampledCommit]) -> bool {
    if commits.is_empty() {
        return false;
    }
    let terse_count = commits
        .iter()
        .filter(|c| is_terse_message(&c.message))
        .count();
    (terse_count as f32 / commits.len() as f32) > 0.5
}

fn is_terse_message(message: &str) -> bool {
    let msg = message.trim();
    if msg.len() < 20 {
        return true;
    }
    let generic = ["fix", "update", "wip", "temp", "fixup", "squash"];
    let lower = msg.to_lowercase();
    generic.iter().any(|g| lower == *g)
}

// --- Scorer ---

/// Score a single probe: compare context bundle files against ground truth files
fn score_probe(injected_files: &[String], ground_truth_files: &[String]) -> (f32, f32, f32) {
    let injected: HashSet<&str> = injected_files.iter().map(|s| s.as_str()).collect();
    let truth: HashSet<&str> = ground_truth_files.iter().map(|s| s.as_str()).collect();

    let overlap: HashSet<&&str> = injected.intersection(&truth).collect();

    let precision = if injected.is_empty() {
        0.0
    } else {
        overlap.len() as f32 / injected.len() as f32
    };

    let recall = if truth.is_empty() {
        0.0
    } else {
        overlap.len() as f32 / truth.len() as f32
    };

    let f1 = if precision + recall > 0.0 {
        2.0 * precision * recall / (precision + recall)
    } else {
        0.0
    };

    (precision, recall, f1)
}

// --- Grid ---

struct GridPoint {
    semantic_weight: f32,
    doc_demotion: f32,
    rrf_k: f32,
    recency_half_life_days: Option<f32>,
    recency_weight: Option<f32>,
    budget_lines: usize,
    search_limit: usize,
    bridge_mode: BridgeMode,
    bridge_boost_factor: f32,
}

/// Build the core parameter grid (sw × dd × k × sl × b points).
/// Core grid uses Inject mode only. Bridge modes are swept in --full.
fn build_grid(budgets: &[usize], search_limits: &[usize]) -> Vec<GridPoint> {
    build_grid_with_recency(
        &[],
        &[],
        budgets,
        search_limits,
        &[BridgeMode::Inject],
        &[0.3],
    )
}

/// Build grid with optional recency and bridge parameter sweep.
/// Empty recency slices → use config defaults (None in grid point).
fn build_grid_with_recency(
    half_lives: &[f32],
    recency_weights: &[f32],
    budgets: &[usize],
    search_limits: &[usize],
    bridge_modes: &[BridgeMode],
    bridge_boost_factors: &[f32],
) -> Vec<GridPoint> {
    let sws = [0.0, 0.3, 0.5, 0.7, 0.9];
    let dds = [0.1, 0.3, 0.5];
    let ks = [60.0]; // Keep k fixed for v1

    // If no recency values specified, use a single None entry
    let hl_iter: Vec<Option<f32>> = if half_lives.is_empty() {
        vec![None]
    } else {
        half_lives.iter().map(|&v| Some(v)).collect()
    };
    let rw_iter: Vec<Option<f32>> = if recency_weights.is_empty() {
        vec![None]
    } else {
        recency_weights.iter().map(|&v| Some(v)).collect()
    };

    let mut grid = Vec::new();
    for &sw in &sws {
        for &dd in &dds {
            for &k in &ks {
                for &hl in &hl_iter {
                    for &rw in &rw_iter {
                        for &b in budgets {
                            for &sl in search_limits {
                                for &bm in bridge_modes {
                                    // Only sweep boost factors for modes that use them
                                    let factors: &[f32] = match bm {
                                        BridgeMode::Off | BridgeMode::Inject => &[0.0],
                                        BridgeMode::Boost | BridgeMode::BoostInject => {
                                            bridge_boost_factors
                                        }
                                    };
                                    for &bbf in factors {
                                        grid.push(GridPoint {
                                            semantic_weight: sw,
                                            doc_demotion: dd,
                                            rrf_k: k,
                                            recency_half_life_days: hl,
                                            recency_weight: rw,
                                            budget_lines: b,
                                            search_limit: sl,
                                            bridge_mode: bm,
                                            bridge_boost_factor: bbf,
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    grid
}

// --- Project Snapshot ---

async fn capture_snapshot(
    vector_store: &VectorStore,
    git: &GitAnalyzer,
) -> Result<ProjectSnapshot> {
    let chunk_count = vector_store.count().await? as usize;

    // Repo age: time from first commit to now
    let repo_age_days = git_repo_age_days(git).unwrap_or(0);

    // Recent commit rate: commits in last 30 days / 4.3 weeks
    let recent_commits = git
        .get_commit_log(500, None)
        .ok()
        .map(|commits| {
            let thirty_days_ago = Utc::now().timestamp() - (30 * 86400);
            commits
                .iter()
                .filter(|c| c.timestamp > thirty_days_ago)
                .count()
        })
        .unwrap_or(0);
    let recent_commit_rate = recent_commits as f32 / 4.3;

    Ok(ProjectSnapshot {
        chunk_count,
        file_count: 0,                           // TODO: add count_files to VectorStore
        primary_language: "unknown".to_string(), // TODO: add language stats
        language_distribution: vec![],
        repo_age_days,
        recent_commit_rate,
    })
}

fn git_repo_age_days(git: &GitAnalyzer) -> Result<u32> {
    let output = std::process::Command::new("git")
        .args(["log", "--reverse", "--format=%ct", "-1"])
        .current_dir(git.repo_root())
        .output()
        .context("Failed to get repo age")?;
    let first_ts: i64 = String::from_utf8_lossy(&output.stdout)
        .trim()
        .parse()
        .unwrap_or(0);
    if first_ts == 0 {
        return Ok(0);
    }
    let now = Utc::now().timestamp();
    Ok(((now - first_ts) / 86400) as u32)
}

/// Create a lightweight ProjectSnapshot from just a chunk count.
/// Used by index.rs auto-calibrate guard to avoid reopening stores.
pub fn capture_snapshot_from_index(chunk_count: usize) -> ProjectSnapshot {
    ProjectSnapshot {
        chunk_count,
        file_count: 0,
        primary_language: "unknown".to_string(),
        language_distribution: vec![],
        repo_age_days: 0,
        recent_commit_rate: 0.0,
    }
}

// --- Persistence ---

fn calibration_path(repo_root: &std::path::Path) -> PathBuf {
    Config::data_dir(repo_root).join("calibration.json")
}

fn cache_path(repo_root: &std::path::Path) -> PathBuf {
    Config::data_dir(repo_root).join("calibration_cache.json")
}

fn progress_path(repo_root: &std::path::Path) -> PathBuf {
    Config::data_dir(repo_root).join("calibration_progress.jsonl")
}

fn save_calibration(repo_root: &std::path::Path, result: &CalibrationResult) -> Result<()> {
    let path = calibration_path(repo_root);
    let json = serde_json::to_string_pretty(result)?;
    std::fs::write(&path, json).with_context(|| format!("Failed to write {}", path.display()))?;
    Ok(())
}

/// Load calibration results (if they exist)
pub fn load_calibration(repo_root: &std::path::Path) -> Option<CalibrationResult> {
    let path = calibration_path(repo_root);
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

// --- Sweep Cache (for --full resume) ---

/// Cached results from an interrupted --full sweep.
/// Keyed by coupling_depth → list of grid results for that depth.
#[derive(Debug, Serialize, Deserialize)]
struct SweepCache {
    /// Map of coupling_depth → completed grid results
    completed_depths: HashMap<String, Vec<GridResult>>,
    /// Total commits sampled (must match to resume)
    sample_count: usize,
    /// Commit hashes for validation
    sample_hashes: Vec<String>,
}

fn save_cache(repo_root: &std::path::Path, cache: &SweepCache) -> Result<()> {
    let path = cache_path(repo_root);
    let json = serde_json::to_string_pretty(cache)?;
    std::fs::write(&path, json)
        .with_context(|| format!("Failed to write cache {}", path.display()))?;
    Ok(())
}

fn load_cache(repo_root: &std::path::Path) -> Option<SweepCache> {
    let path = cache_path(repo_root);
    let content = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

fn clear_cache(repo_root: &std::path::Path) {
    let path = cache_path(repo_root);
    let _ = std::fs::remove_file(path);
}

// --- Probe Runner ---

/// Run probes for a grid against sampled commits. Returns scored grid results.
/// The coupling_depth tag is attached to each result for --full sweeps.
///
/// Opens VectorStore, MetadataStore, and Embedder once and reuses across all
/// probes. ContextAssembler.set_config() swaps search params between grid points
/// without reopening stores.
async fn run_probes(
    grid: &[GridPoint],
    commits: &[SampledCommit],
    lance_path: &std::path::Path,
    db_path: &std::path::Path,
    config: &Config,
    model_dir: &std::path::Path,
    coupling_depth: Option<usize>,
    repo_root: &std::path::Path,
    pb: Option<&ProgressBar>,
    progress_file: Option<&std::path::Path>,
) -> Result<Vec<GridResult>> {
    // Open stores and embedder once for all probes
    let vs = VectorStore::open(lance_path).await?;
    let ms = MetadataStore::open(db_path)?;
    let embedder = Embedder::from_config(&config.embedding, model_dir)?;

    // Build initial assembler with a placeholder config (overwritten per grid point)
    let initial_config = ContextConfig {
        budget_lines: 300,
        depth: 1,
        max_coupled: 3,
        coupling_threshold: 0.1,
        semantic_weight: 0.5,
        content_mode: ContentMode::None,
        search_limit: 20,
        doc_demotion: 0.3,
        recency_half_life_days: config.search.recency_half_life_days,
        recency_weight: config.search.recency_weight,
        rrf_k: 60.0,
        bridge_mode: BridgeMode::Inject,
        bridge_boost_factor: 0.3,
        extra_filter: None,
        tags_config: None,
        role: None,
        file_type_rules: vec![],
        repo_affinity: None,
        repo_affinity_boost: 2.0,
        max_bridged_files: 3,
        max_bridged_chunks_per_file: 2,
        repo_path_prefix: config.server.repo_path_prefix.clone(),
        ..ContextConfig::default()
    };
    let mut assembler = ContextAssembler::new(embedder, vs, ms, initial_config);

    let mut grid_results: Vec<GridResult> = Vec::new();
    let prefix = repo_root.to_string_lossy();

    for point in grid {
        // Swap config for this grid point
        assembler.set_config(ContextConfig {
            budget_lines: point.budget_lines,
            depth: 1,
            max_coupled: 3,
            coupling_threshold: 0.1,
            semantic_weight: point.semantic_weight,
            content_mode: ContentMode::None,
            search_limit: point.search_limit,
            doc_demotion: point.doc_demotion,
            recency_half_life_days: point
                .recency_half_life_days
                .unwrap_or(config.search.recency_half_life_days),
            recency_weight: point.recency_weight.unwrap_or(config.search.recency_weight),
            rrf_k: point.rrf_k,
            bridge_mode: point.bridge_mode,
            bridge_boost_factor: point.bridge_boost_factor,
            extra_filter: None,
            tags_config: None,
            role: None,
            file_type_rules: vec![],
            repo_affinity: None,
            repo_affinity_boost: 2.0,
            max_bridged_files: 3,
            max_bridged_chunks_per_file: 2,
            repo_path_prefix: config.server.repo_path_prefix.clone(),
            ..ContextConfig::default()
        });

        let mut total_precision = 0.0_f32;
        let mut total_recall = 0.0_f32;
        let mut total_f1 = 0.0_f32;
        let mut valid_probes = 0usize;

        for commit in commits {
            let bundle = assembler.assemble(&commit.message, None).await;

            if let Ok(bundle) = bundle {
                let injected: Vec<String> = bundle
                    .files
                    .iter()
                    .map(|f| {
                        f.path
                            .strip_prefix(prefix.as_ref())
                            .unwrap_or(&f.path)
                            .trim_start_matches('/')
                            .to_string()
                    })
                    .collect();
                let (p, r, f1) = score_probe(&injected, &commit.files);
                total_precision += p;
                total_recall += r;
                total_f1 += f1;
                valid_probes += 1;
            }

            if let Some(pb) = pb {
                pb.inc(1);
            }
        }

        let n = valid_probes.max(1) as f32;
        let result = GridResult {
            semantic_weight: point.semantic_weight,
            doc_demotion: point.doc_demotion,
            rrf_k: point.rrf_k,
            recency_half_life_days: point.recency_half_life_days,
            recency_weight: point.recency_weight,
            coupling_depth,
            budget_lines: Some(point.budget_lines),
            search_limit: Some(point.search_limit),
            bridge_mode: Some(point.bridge_mode),
            bridge_boost_factor: if point.bridge_boost_factor > 0.0 {
                Some(point.bridge_boost_factor)
            } else {
                None
            },
            precision: total_precision / n,
            recall: total_recall / n,
            f1: total_f1 / n,
        };

        if let Some(path) = progress_file {
            use std::io::Write;
            if let Ok(mut f) = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
            {
                let _ = writeln!(f, "{}", serde_json::to_string(&result).unwrap_or_default());
            }
        }

        grid_results.push(result);
    }

    Ok(grid_results)
}

/// Re-index coupling data for a specific depth, replacing existing coupling table.
fn reindex_coupling(
    git: &GitAnalyzer,
    db_path: &std::path::Path,
    depth: usize,
    threshold: u32,
    freq_weight: f32,
    recency_days: f32,
) -> Result<()> {
    let couplings = git.analyze_coupling(depth, threshold, freq_weight, recency_days)?;
    let ms = MetadataStore::open(db_path)?;
    ms.clear_coupling()?;
    ms.begin_transaction()?;
    for c in &couplings {
        ms.upsert_coupling(c)?;
    }
    ms.commit()?;
    Ok(())
}

/// Format a GridResult line for display, adapting columns to --full mode.
fn format_result(r: &GridResult, full: bool, bridge_sweep: bool) -> String {
    let mut s = format!(
        "  sw={:.2} dd={:.2} k={:.0}",
        r.semantic_weight, r.doc_demotion, r.rrf_k
    );
    // Show budget/search_limit when they differ from defaults
    if let Some(b) = r.budget_lines {
        if b != 300 {
            s.push_str(&format!(" b={}", b));
        }
    }
    if let Some(sl) = r.search_limit {
        if sl != 20 {
            s.push_str(&format!(" sl={}", sl));
        }
    }
    // Show bridge_mode (always in bridge_sweep, otherwise only when non-default)
    if let Some(bm) = r.bridge_mode {
        if bridge_sweep || bm != BridgeMode::Inject {
            s.push_str(&format!(" bm={}", bm));
        }
    }
    if let Some(bbf) = r.bridge_boost_factor {
        if bbf > 0.0 {
            s.push_str(&format!(" bbf={:.2}", bbf));
        }
    }
    if full {
        if let Some(hl) = r.recency_half_life_days {
            s.push_str(&format!(" hl={:.0}", hl));
        }
        if let Some(rw) = r.recency_weight {
            s.push_str(&format!(" rw={:.2}", rw));
        }
        if let Some(cd) = r.coupling_depth {
            s.push_str(&format!(" cd={}", cd));
        }
    }
    s.push_str(&format!(
        "  F1={:.3}  P={:.3}  R={:.3}",
        r.f1, r.precision, r.recall
    ));
    s
}

// --- Git Source Resolution ---

/// Resolve the git source directory for commit sampling.
///
/// In multi-repo setups (e.g., `bobbin index --source /path/to/repo --repo name`),
/// the `.bobbin/` directory lives in a workspace root that may not be a git repo.
/// This function resolves the actual git repository path to sample commits from.
///
/// Resolution order:
/// 1. `--source <path>` flag (explicit override)
/// 2. `--repo <name>` → look up `repo_source:<name>` in metadata DB
/// 3. If only one repo indexed, use its stored source path
/// 4. Fall back to repo_root (works for single-repo setups where .bobbin/ is in the repo)
fn resolve_git_source(
    args: &CalibrateArgs,
    repo_root: &std::path::Path,
    db_path: &std::path::Path,
) -> Result<PathBuf> {
    // 1. Explicit --source flag
    if let Some(ref source) = args.source {
        return source
            .canonicalize()
            .with_context(|| format!("Invalid source path: {}", source.display()));
    }

    let ms = MetadataStore::open(db_path).ok();

    // 2. --repo flag → metadata lookup
    if let Some(ref repo_name) = args.repo {
        if let Some(ref ms) = ms {
            let key = format!("repo_source:{}", repo_name);
            if let Ok(Some(path_str)) = ms.get_meta(&key) {
                let path = PathBuf::from(&path_str);
                if path.exists() {
                    return Ok(path);
                }
                eprintln!(
                    "  Warning: stored source path {} no longer exists, falling back to repo root",
                    path_str
                );
            } else {
                bail!(
                    "No source path stored for repo '{}'. Re-run `bobbin index --repo {} --source <path>` to register it.",
                    repo_name, repo_name
                );
            }
        }
    }

    // 3. No --repo specified: if exactly one repo is indexed, use its source path
    if let Some(ref ms) = ms {
        let sources = collect_repo_sources(ms);
        if sources.len() == 1 {
            let (name, path) = &sources[0];
            if path.exists() {
                if !args.repo.is_some() {
                    // Silently use the single repo's source
                    return Ok(path.clone());
                }
            } else {
                eprintln!(
                    "  Warning: stored source for '{}' ({}) no longer exists",
                    name,
                    path.display()
                );
            }
        } else if sources.len() > 1 {
            // Multiple repos but no --repo specified — check if repo_root is a git repo
            let git_check = std::process::Command::new("git")
                .args(["rev-parse", "--git-dir"])
                .current_dir(repo_root)
                .output();
            if git_check.map(|o| o.status.success()).unwrap_or(false) {
                // repo_root is itself a git repo, use it
                return Ok(repo_root.to_path_buf());
            }
            // Not a git repo — list available repos for the user
            let repo_names: Vec<&str> = sources.iter().map(|(n, _)| n.as_str()).collect();
            bail!(
                "Multiple repos indexed ({}) but workspace root is not a git repo.\n\
                 Use --repo <name> to specify which repo to calibrate against.\n\
                 Available repos: {}",
                sources.len(),
                repo_names.join(", ")
            );
        }
    }

    // 4. Fallback: repo_root
    Ok(repo_root.to_path_buf())
}

/// Collect all repo → source path mappings from metadata.
fn collect_repo_sources(ms: &MetadataStore) -> Vec<(String, PathBuf)> {
    ms.get_meta_by_prefix("repo_source:")
        .unwrap_or_default()
        .into_iter()
        .map(|(key, value)| {
            let name = key.strip_prefix("repo_source:").unwrap_or(&key).to_string();
            (name, PathBuf::from(value))
        })
        .collect()
}

// --- Main Entry Point ---

pub async fn run(args: CalibrateArgs, output: OutputConfig) -> Result<()> {
    let repo_root = args
        .path
        .canonicalize()
        .with_context(|| format!("Invalid path: {}", args.path.display()))?;

    let config_path = Config::config_path(&repo_root);
    if !config_path.exists() {
        bail!("{}", super::not_initialized_error(&repo_root));
    }

    let config = Config::load_merged(&repo_root)?;
    let lance_path = Config::lance_path(&repo_root);
    let db_path = Config::db_path(&repo_root);
    let model_dir = Config::model_cache_dir()?;

    let vector_store = VectorStore::open(&lance_path)
        .await
        .context("Failed to open vector store")?;

    let count = vector_store.count().await?;
    if count == 0 {
        bail!("Index is empty. Run `bobbin index` first.");
    }

    // Resolve git source directory for commit sampling.
    // Priority: --source flag > metadata lookup (repo_source:<name>) > repo_root fallback
    let git_source = resolve_git_source(&args, &repo_root, &db_path)?;
    let git = GitAnalyzer::new(&git_source).with_context(|| {
        format!(
            "Not a git repository: {}. Use --source to specify the repo path.",
            git_source.display()
        )
    })?;

    // Phase 1: Sample commits
    if !output.quiet {
        if args.full {
            eprintln!(
                "{}",
                "Extended calibration (includes recency and coupling parameters)...".bold()
            );
        } else {
            eprintln!(
                "{}",
                "Calibrating search parameters against git history...".bold()
            );
        }
        if git_source != repo_root {
            eprintln!("  Sampling commits from: {}", git_source.display());
        }
    }

    let commits = sample_commits(&git, &args.since, args.samples)?;
    let is_terse = detect_terse_messages(&commits);

    if is_terse && !output.quiet {
        eprintln!(
            "{}",
            "⚠ Many commit messages are too short for reliable calibration.\n  \
             Calibration accuracy may be reduced."
                .yellow()
        );
    }

    if !output.quiet {
        eprintln!(
            "  Sampled {} commits across last {}",
            commits.len(),
            args.since
        );
    }

    // Validate embedder can be loaded before starting the sweep
    let _embedder_check = Embedder::from_config(&config.embedding, &model_dir)
        .context("Failed to load embedding model")?;

    // Phase 2: Build grid and run probes
    let grid_results = if args.bridge_sweep {
        run_bridge_sweep(
            &output,
            &config,
            &commits,
            &lance_path,
            &db_path,
            &model_dir,
            &repo_root,
        )
        .await?
    } else if args.full {
        run_full_sweep(
            &args,
            &output,
            &config,
            &commits,
            &git,
            &lance_path,
            &db_path,
            &model_dir,
            &repo_root,
        )
        .await?
    } else {
        run_core_sweep(
            &args,
            &output,
            &config,
            &commits,
            &lance_path,
            &db_path,
            &model_dir,
            &repo_root,
        )
        .await?
    };

    // Phase 3: Sort results and report
    let mut sorted = grid_results;
    sorted.sort_by(|a, b| b.f1.partial_cmp(&a.f1).unwrap());

    let best = sorted
        .first()
        .expect("Grid should have at least one result");

    // Find current config result for comparison
    let current_f1 = sorted
        .iter()
        .find(|r| {
            (r.semantic_weight - config.search.semantic_weight).abs() < 0.01
                && (r.doc_demotion - config.search.doc_demotion).abs() < 0.01
        })
        .map(|r| r.f1)
        .unwrap_or(0.0);

    // Capture snapshot
    let snapshot = capture_snapshot(&vector_store, &git).await?;
    let total_probes = sorted.len() * commits.len();

    let calibration = CalibrationResult {
        calibrated_at: Utc::now().to_rfc3339(),
        snapshot,
        best_config: CalibratedConfig {
            semantic_weight: best.semantic_weight,
            doc_demotion: best.doc_demotion,
            rrf_k: best.rrf_k,
            recency_half_life_days: best.recency_half_life_days,
            recency_weight: best.recency_weight,
            coupling_depth: best.coupling_depth,
            budget_lines: best.budget_lines,
            search_limit: best.search_limit,
            bridge_mode: best.bridge_mode,
            bridge_boost_factor: best.bridge_boost_factor,
        },
        top_results: sorted.iter().take(10).cloned().collect(),
        sample_count: commits.len(),
        probe_count: total_probes,
        terse_warning: is_terse,
    };

    // Output
    if output.json {
        println!("{}", serde_json::to_string_pretty(&calibration)?);
    } else if !output.quiet {
        eprintln!();
        eprintln!("{}", "Calibration results (top 5 by F1):".bold());
        for result in sorted.iter().take(5) {
            eprintln!("{}", format_result(result, args.full, args.bridge_sweep));
        }

        eprintln!();
        eprintln!(
            "  Current config F1: {:.3} (sw={:.2})",
            current_f1, config.search.semantic_weight
        );
        eprintln!(
            "  Best config F1:    {:.3} (sw={:.2})  {}",
            best.f1,
            best.semantic_weight,
            if best.f1 > current_f1 && current_f1 > 0.0 {
                let pct = ((best.f1 - current_f1) / current_f1 * 100.0) as i32;
                format!("[+{}% improvement]", pct).green().to_string()
            } else {
                String::new()
            }
        );
    }

    // Apply
    if args.apply {
        save_calibration(&repo_root, &calibration)?;
        if !output.quiet {
            eprintln!(
                "\n  {} Applied best config to .bobbin/calibration.json",
                "✓".green()
            );
        }
    } else if !output.quiet && !output.json {
        eprintln!("\n  Run with {} to apply best config.", "--apply".bold());
    }

    // Clean up cache on successful completion of --full
    if args.full {
        clear_cache(&repo_root);
    }

    Ok(())
}

/// Core sweep: semantic_weight × doc_demotion × rrf_k × search_limit × budget.
async fn run_core_sweep(
    args: &CalibrateArgs,
    output: &OutputConfig,
    config: &Config,
    commits: &[SampledCommit],
    lance_path: &std::path::Path,
    db_path: &std::path::Path,
    model_dir: &std::path::Path,
    repo_root: &std::path::Path,
) -> Result<Vec<GridResult>> {
    let budgets = match args.budget {
        Some(b) => vec![b],
        None => vec![300],
    };
    let search_limits = match args.search_limit {
        Some(sl) => vec![sl],
        None => vec![20],
    };
    let grid = build_grid(&budgets, &search_limits);
    let total_probes = grid.len() * commits.len();

    if !output.quiet {
        eprintln!(
            "  Grid: {} configs × {} commits = {} probes",
            grid.len(),
            commits.len(),
            total_probes
        );
    }

    let pb = if !output.quiet {
        let pb = ProgressBar::new(total_probes as u64);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("  Running {pos}/{len} probes {bar:30} {eta}")
                .unwrap()
                .progress_chars("█▓░"),
        );
        Some(pb)
    } else {
        None
    };

    let prog = progress_path(repo_root);
    let results = run_probes(
        &grid,
        commits,
        lance_path,
        db_path,
        config,
        model_dir,
        None,
        repo_root,
        pb.as_ref(),
        Some(&prog),
    )
    .await?;

    if let Some(pb) = &pb {
        pb.finish_and_clear();
    }

    Ok(results)
}

/// Bridge sweep: use calibrated core params, only sweep bridge_mode × bridge_boost_factor.
///
/// Grid: 4 bridge_modes × 3 boost_factors = 7 configs (off+inject don't use bbf)
/// Total probes: 7 × 20 commits = 140 (very fast)
///
/// Requires existing calibration.json — run core sweep first.
async fn run_bridge_sweep(
    output: &OutputConfig,
    config: &Config,
    commits: &[SampledCommit],
    lance_path: &std::path::Path,
    db_path: &std::path::Path,
    model_dir: &std::path::Path,
    repo_root: &std::path::Path,
) -> Result<Vec<GridResult>> {
    let cal = load_calibration(repo_root)
        .context("--bridge-sweep requires existing calibration.json (run core sweep first)")?;
    let best = &cal.best_config;

    let budgets = vec![best.budget_lines.unwrap_or(300)];
    let search_limits = vec![best.search_limit.unwrap_or(20)];
    let bridge_modes = [
        BridgeMode::Off,
        BridgeMode::Inject,
        BridgeMode::Boost,
        BridgeMode::BoostInject,
    ];
    let bridge_boost_factors = [0.15, 0.3, 0.5];

    // Build grid with fixed core params, sweep only bridge dimensions
    let grid = build_grid_with_recency(
        &[],
        &[],
        &budgets,
        &search_limits,
        &bridge_modes,
        &bridge_boost_factors,
    );
    // Filter to only the calibrated sw/dd/k values
    let sw = best.semantic_weight;
    let dd = best.doc_demotion;
    let k = best.rrf_k;
    let grid: Vec<GridPoint> = grid
        .into_iter()
        .filter(|p| {
            (p.semantic_weight - sw).abs() < 0.01
                && (p.doc_demotion - dd).abs() < 0.01
                && (p.rrf_k - k).abs() < 0.01
        })
        .collect();

    let total_probes = grid.len() * commits.len();

    if !output.quiet {
        eprintln!(
            "  Bridge sweep: {} configs × {} commits = {} probes (sw={:.2} dd={:.1} b={} sl={})",
            grid.len(),
            commits.len(),
            total_probes,
            sw,
            dd,
            budgets[0],
            search_limits[0],
        );
    }

    let pb = if !output.quiet {
        let pb = ProgressBar::new(total_probes as u64);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("  Running {pos}/{len} probes {bar:30} {eta}")
                .unwrap()
                .progress_chars("█▓░"),
        );
        Some(pb)
    } else {
        None
    };

    let prog = progress_path(repo_root);
    let results = run_probes(
        &grid,
        commits,
        lance_path,
        db_path,
        config,
        model_dir,
        None,
        repo_root,
        pb.as_ref(),
        Some(&prog),
    )
    .await?;

    if let Some(pb) = &pb {
        pb.finish_and_clear();
    }

    Ok(results)
}

/// Full sweep: core grid × recency params, then per coupling_depth.
///
/// Grid, at default args (bobbin-10d — the previous comment stopped at the
/// first five dimensions and reported 240 configs / 19,200 probes, missing the
/// budget, search-limit and bridge dimensions this actually sweeps):
///
///   5 sw × 3 dd × 1 k × 4 hl × 4 rw × 3 budgets × 4 search limits × 8 bridge
///     = 23,040 configs
///
/// The bridge term is 8, not 12: `Off` and `Inject` ignore the boost factor and
/// contribute one point each, while `Boost` and `BoostInject` sweep all three
/// (1 + 1 + 3 + 3). See `build_grid_with_recency`.
///
///   × 4 coupling depths      =    92,160 configs
///   × 20 commits (default)   = 1,843,200 probes
///
/// `--budget` or `--search-limit` pin their dimension to one value, dividing
/// the total by 3 or 4 respectively.
///
/// These figures are a reader's aid and not the authority: the sweep prints the
/// real counts from `grid.len()` before it starts, and
/// `test_full_sweep_grid_geometry` pins the arithmetic above so this comment
/// cannot drift again without a test failing.
///
/// Coupling depth sweep re-indexes coupling data per depth value,
/// so each depth iteration is a separate probe run.
async fn run_full_sweep(
    args: &CalibrateArgs,
    output: &OutputConfig,
    config: &Config,
    commits: &[SampledCommit],
    git: &GitAnalyzer,
    lance_path: &std::path::Path,
    db_path: &std::path::Path,
    model_dir: &std::path::Path,
    repo_root: &std::path::Path,
) -> Result<Vec<GridResult>> {
    let half_lives: Vec<f32> = vec![7.0, 14.0, 30.0, 90.0];
    let recency_weights: Vec<f32> = vec![0.0, 0.15, 0.30, 0.50];
    let coupling_depths: Vec<usize> = vec![500, 2000, 5000, 20000];
    let budgets: Vec<usize> = match args.budget {
        Some(b) => vec![b],
        None => vec![150, 300, 500],
    };
    let search_limits: Vec<usize> = match args.search_limit {
        Some(sl) => vec![sl],
        None => vec![10, 20, 30, 40],
    };

    let bridge_modes = [
        BridgeMode::Off,
        BridgeMode::Inject,
        BridgeMode::Boost,
        BridgeMode::BoostInject,
    ];
    let bridge_boost_factors = [0.15, 0.3, 0.5];
    let grid = build_grid_with_recency(
        &half_lives,
        &recency_weights,
        &budgets,
        &search_limits,
        &bridge_modes,
        &bridge_boost_factors,
    );
    let total_configs = grid.len() * coupling_depths.len();
    let total_probes = total_configs * commits.len();

    if !output.quiet {
        eprintln!(
            "  Grid: {} configs × {} coupling depths = {} total configs",
            grid.len(),
            coupling_depths.len(),
            total_configs,
        );
        eprintln!(
            "  Total: {} configs × {} commits = {} probes",
            total_configs,
            commits.len(),
            total_probes,
        );
    }

    // Load cache for resume
    let mut cache = if args.resume {
        load_cache(repo_root).unwrap_or_else(|| {
            if !output.quiet {
                eprintln!("  No cache found, starting fresh.");
            }
            SweepCache {
                completed_depths: HashMap::new(),
                sample_count: commits.len(),
                sample_hashes: commits.iter().map(|c| c.hash.clone()).collect(),
            }
        })
    } else {
        SweepCache {
            completed_depths: HashMap::new(),
            sample_count: commits.len(),
            sample_hashes: commits.iter().map(|c| c.hash.clone()).collect(),
        }
    };

    // Validate cache matches current sample set
    if args.resume && cache.sample_count != commits.len() {
        if !output.quiet {
            eprintln!(
                "  {} Cache sample count mismatch ({} vs {}), starting fresh.",
                "⚠".yellow(),
                cache.sample_count,
                commits.len()
            );
        }
        cache.completed_depths.clear();
    }

    let mut all_results: Vec<GridResult> = Vec::new();

    // Collect cached results
    for (depth_key, results) in &cache.completed_depths {
        if !output.quiet {
            eprintln!(
                "  Restored {} results from cache (depth={})",
                results.len(),
                depth_key
            );
        }
        all_results.extend(results.iter().cloned());
    }

    // Calculate remaining probes for progress bar
    let remaining_depths: Vec<&usize> = coupling_depths
        .iter()
        .filter(|d| !cache.completed_depths.contains_key(&d.to_string()))
        .collect();
    let remaining_probes = remaining_depths.len() * grid.len() * commits.len();

    let pb = if !output.quiet && remaining_probes > 0 {
        let pb = ProgressBar::new(remaining_probes as u64);
        pb.set_style(
            ProgressStyle::default_bar()
                .template("  [{msg}] {pos}/{len} probes {bar:30} {eta}")
                .unwrap()
                .progress_chars("█▓░"),
        );
        Some(pb)
    } else {
        None
    };

    // Save original coupling data to restore after sweep
    let original_coupling_depth = config.git.coupling_depth;

    for &depth in &coupling_depths {
        let depth_key = depth.to_string();
        if cache.completed_depths.contains_key(&depth_key) {
            continue;
        }

        if let Some(pb) = &pb {
            pb.set_message(format!("cd={}", depth));
        }

        // Re-index coupling data for this depth
        if !output.quiet {
            if let Some(pb) = &pb {
                pb.suspend(|| {
                    eprintln!("  Re-indexing coupling data (depth={})...", depth);
                });
            }
        }
        reindex_coupling(
            git,
            db_path,
            depth,
            config.git.coupling_threshold,
            config.git.coupling_freq_weight,
            config.git.coupling_recency_days,
        )?;

        // Run probes with this coupling depth
        let prog = progress_path(repo_root);
        let depth_results = run_probes(
            &grid,
            commits,
            lance_path,
            db_path,
            config,
            model_dir,
            Some(depth),
            repo_root,
            pb.as_ref(),
            Some(&prog),
        )
        .await?;

        all_results.extend(depth_results.iter().cloned());
        cache.completed_depths.insert(depth_key, depth_results);

        // Save cache after each depth completes
        save_cache(repo_root, &cache)?;
    }

    if let Some(pb) = &pb {
        pb.finish_and_clear();
    }

    // Restore original coupling data
    if !output.quiet {
        eprintln!(
            "  Restoring coupling data (depth={})...",
            original_coupling_depth
        );
    }
    reindex_coupling(
        git,
        db_path,
        original_coupling_depth,
        config.git.coupling_threshold,
        config.git.coupling_freq_weight,
        config.git.coupling_recency_days,
    )?;

    Ok(all_results)
}

// --- CalibrationGuard ---

/// Determines whether a project needs (re)calibration.
pub trait CalibrationGuard {
    fn should_recalibrate(
        &self,
        current: &ProjectSnapshot,
        previous: Option<&CalibrationResult>,
    ) -> bool;
}

/// Default guard: recalibrate on first run, >20% chunk change,
/// primary language change, or >30 days since last calibration.
pub struct DefaultCalibrationGuard;

impl CalibrationGuard for DefaultCalibrationGuard {
    fn should_recalibrate(
        &self,
        current: &ProjectSnapshot,
        previous: Option<&CalibrationResult>,
    ) -> bool {
        let Some(prev) = previous else {
            return true;
        };

        // Chunk count changed >20%
        let prev_chunks = prev.snapshot.chunk_count;
        if prev_chunks > 0 {
            let delta =
                (current.chunk_count as f64 - prev_chunks as f64).abs() / prev_chunks as f64;
            if delta > 0.2 {
                return true;
            }
        }

        // Primary language changed
        if current.primary_language != prev.snapshot.primary_language
            && current.primary_language != "unknown"
            && prev.snapshot.primary_language != "unknown"
        {
            return true;
        }

        // Last calibration >30 days ago
        if let Ok(cal_time) = chrono::DateTime::parse_from_rfc3339(&prev.calibrated_at) {
            let age = Utc::now() - cal_time.with_timezone(&Utc);
            if age.num_days() > 30 {
                return true;
            }
        }

        false
    }
}

impl CalibrateArgs {
    /// Construct args suitable for auto-calibration after indexing.
    ///
    /// `path` must be the bobbin HOME (repo_root) — where `.bobbin/config.toml` and
    /// `calibration.json` live — NOT the indexed source tree. `source`/`repo` carry the
    /// git tree to sample commits from. Passing the source tree as `path` (the bobbin-ewtu2
    /// bug) makes calibrate's `config_path(path)` check miss `.bobbin/config.toml` and bail
    /// "Bobbin not initialized", which fired on every incremental run.
    pub fn default_for_auto(path: PathBuf, repo: Option<String>, source: Option<PathBuf>) -> Self {
        Self {
            samples: 20,
            since: "6 months ago".to_string(),
            search_limit: Some(20),
            budget: Some(300),
            apply: true,
            verbose: false,
            full: false,
            resume: false,
            bridge_sweep: false,
            repo,
            source,
            path,
        }
    }
}

// --- Tests ---

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

    #[test]
    fn test_score_probe_perfect() {
        let injected = vec!["a.rs".into(), "b.rs".into()];
        let truth = vec!["a.rs".into(), "b.rs".into()];
        let (p, r, f1) = score_probe(&injected, &truth);
        assert!((p - 1.0).abs() < 0.001);
        assert!((r - 1.0).abs() < 0.001);
        assert!((f1 - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_score_probe_no_overlap() {
        let injected = vec!["a.rs".into(), "b.rs".into()];
        let truth = vec!["c.rs".into(), "d.rs".into()];
        let (p, r, f1) = score_probe(&injected, &truth);
        assert!((p - 0.0).abs() < 0.001);
        assert!((r - 0.0).abs() < 0.001);
        assert!((f1 - 0.0).abs() < 0.001);
    }

    #[test]
    fn test_score_probe_partial() {
        let injected = vec!["a.rs".into(), "b.rs".into(), "c.rs".into()];
        let truth = vec!["a.rs".into(), "d.rs".into()];
        let (p, r, _f1) = score_probe(&injected, &truth);
        // precision: 1/3 = 0.333
        assert!((p - 0.333).abs() < 0.01);
        // recall: 1/2 = 0.5
        assert!((r - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_score_probe_empty_injected() {
        let injected: Vec<String> = vec![];
        let truth = vec!["a.rs".into()];
        let (p, r, f1) = score_probe(&injected, &truth);
        assert!((p - 0.0).abs() < 0.001);
        assert!((r - 0.0).abs() < 0.001);
        assert!((f1 - 0.0).abs() < 0.001);
    }

    #[test]
    fn test_is_noise_commit() {
        assert!(is_noise_commit("chore: update deps"));
        assert!(is_noise_commit("ci: fix pipeline"));
        assert!(is_noise_commit("docs: update readme"));
        assert!(is_noise_commit("Bump version to 1.2.3"));
        assert!(!is_noise_commit("Fix parser to handle nested types"));
        assert!(!is_noise_commit(
            "Add webhook support for real-time indexing"
        ));
    }

    #[test]
    fn test_is_terse_message() {
        assert!(is_terse_message("fix"));
        assert!(is_terse_message("update"));
        assert!(is_terse_message("wip"));
        assert!(is_terse_message("short msg"));
        assert!(!is_terse_message(
            "Fix parser to handle nested generic types correctly"
        ));
    }

    #[test]
    fn test_detect_terse_majority() {
        let commits = vec![
            SampledCommit {
                hash: "a".into(),
                message: "fix".into(),
                files: vec![],
            },
            SampledCommit {
                hash: "b".into(),
                message: "wip".into(),
                files: vec![],
            },
            SampledCommit {
                hash: "c".into(),
                message: "This is a proper commit message about fixing auth".into(),
                files: vec![],
            },
        ];
        // 2/3 terse > 50%
        assert!(detect_terse_messages(&commits));
    }

    #[test]
    fn test_detect_terse_minority() {
        let commits = vec![
            SampledCommit {
                hash: "a".into(),
                message: "fix".into(),
                files: vec![],
            },
            SampledCommit {
                hash: "b".into(),
                message: "Fix parser to handle nested types".into(),
                files: vec![],
            },
            SampledCommit {
                hash: "c".into(),
                message: "Add webhook support for real-time reindexing".into(),
                files: vec![],
            },
        ];
        // 1/3 terse < 50%
        assert!(!detect_terse_messages(&commits));
    }

    #[test]
    fn test_build_grid_size() {
        let grid = build_grid(&[300], &[20]);
        // 15 configs × 20 default samples = a bounded 300-probe core run.
        assert_eq!(grid.len() * 20, 300);
        // Core grid points should have no recency overrides
        assert!(grid[0].recency_half_life_days.is_none());
        assert!(grid[0].recency_weight.is_none());
        assert_eq!(grid[0].budget_lines, 300);
        assert_eq!(grid[0].search_limit, 20);
    }

    #[test]
    fn test_build_grid_sweep_budget_search_limit() {
        let grid = build_grid(&[150, 300, 500], &[10, 20, 30, 40]);
        // 5 sw × 3 dd × 1 k × 3 b × 4 sl = 180 (core uses single bridge mode)
        assert_eq!(grid.len(), 180);
    }

    #[test]
    fn test_build_grid_with_recency() {
        let half_lives = [7.0, 14.0, 30.0, 90.0];
        let recency_weights = [0.0, 0.15, 0.30, 0.50];
        let grid = build_grid_with_recency(
            &half_lives,
            &recency_weights,
            &[300],
            &[20],
            &[BridgeMode::Inject],
            &[0.3],
        );
        // 5 sw × 3 dd × 1 k × 4 hl × 4 rw × 1 b × 1 sl × 1 bm = 240
        assert_eq!(grid.len(), 240);
        // All extended grid points should have recency overrides
        assert!(grid[0].recency_half_life_days.is_some());
        assert!(grid[0].recency_weight.is_some());
    }

    #[test]
    fn test_build_grid_recency_empty_fallback() {
        // Empty arrays should fall back to None (same as core grid)
        let grid = build_grid_with_recency(&[], &[], &[300], &[20], &[BridgeMode::Inject], &[0.3]);
        assert_eq!(grid.len(), 15);
        assert!(grid[0].recency_half_life_days.is_none());
    }

    #[test]
    fn test_build_grid_bridge_mode_sweep() {
        // Sweep all 4 bridge modes with 2 boost factors
        let bridge_modes = [
            BridgeMode::Off,
            BridgeMode::Inject,
            BridgeMode::Boost,
            BridgeMode::BoostInject,
        ];
        let grid = build_grid_with_recency(&[], &[], &[300], &[20], &bridge_modes, &[0.15, 0.3]);
        // 5 sw × 3 dd × 1 k × 1 hl × 1 rw × 1 b × 1 sl × (2 off + 2 inject + 2×2 boost + 2×2 boost_inject) = 15 × 8 = 120
        // Off: factor[0.0] only = 1, Inject: factor[0.0] only = 1, Boost: 2 factors, BoostInject: 2 factors
        // Total per inner = 1 + 1 + 2 + 2 = 6
        assert_eq!(grid.len(), 15 * 6);
    }

    #[test]
    fn test_format_result_core() {
        let r = GridResult {
            semantic_weight: 0.3,
            doc_demotion: 0.3,
            rrf_k: 60.0,
            recency_half_life_days: None,
            recency_weight: None,
            coupling_depth: None,
            budget_lines: Some(300),
            search_limit: Some(20),
            bridge_mode: None,
            bridge_boost_factor: None,
            precision: 0.4,
            recall: 0.5,
            f1: 0.444,
        };
        let s = format_result(&r, false, false);
        assert!(s.contains("sw=0.30"));
        assert!(!s.contains("hl="));
        // Default values should not appear in output
        assert!(!s.contains("b="));
        assert!(!s.contains("sl="));
    }

    #[test]
    fn test_format_result_non_default_budget_search_limit() {
        let r = GridResult {
            semantic_weight: 0.3,
            doc_demotion: 0.3,
            rrf_k: 60.0,
            recency_half_life_days: None,
            recency_weight: None,
            coupling_depth: None,
            budget_lines: Some(500),
            search_limit: Some(40),
            bridge_mode: None,
            bridge_boost_factor: None,
            precision: 0.4,
            recall: 0.5,
            f1: 0.444,
        };
        let s = format_result(&r, false, false);
        assert!(s.contains("b=500"));
        assert!(s.contains("sl=40"));
    }

    #[test]
    fn test_format_result_full() {
        let r = GridResult {
            semantic_weight: 0.3,
            doc_demotion: 0.3,
            rrf_k: 60.0,
            recency_half_life_days: Some(14.0),
            recency_weight: Some(0.15),
            coupling_depth: Some(5000),
            budget_lines: Some(300),
            search_limit: Some(20),
            bridge_mode: None,
            bridge_boost_factor: None,
            precision: 0.4,
            recall: 0.5,
            f1: 0.444,
        };
        let s = format_result(&r, true, false);
        assert!(s.contains("hl=14"));
        assert!(s.contains("rw=0.15"));
        assert!(s.contains("cd=5000"));
    }

    #[test]
    fn test_sweep_cache_roundtrip() {
        let mut cache = SweepCache {
            completed_depths: HashMap::new(),
            sample_count: 20,
            sample_hashes: vec!["abc123".into()],
        };
        cache.completed_depths.insert(
            "5000".into(),
            vec![GridResult {
                semantic_weight: 0.3,
                doc_demotion: 0.3,
                rrf_k: 60.0,
                recency_half_life_days: Some(30.0),
                recency_weight: Some(0.3),
                coupling_depth: Some(5000),
                budget_lines: Some(300),
                search_limit: Some(20),
                bridge_mode: None,
                bridge_boost_factor: None,
                precision: 0.4,
                recall: 0.5,
                f1: 0.444,
            }],
        );
        let json = serde_json::to_string(&cache).unwrap();
        let loaded: SweepCache = serde_json::from_str(&json).unwrap();
        assert_eq!(loaded.sample_count, 20);
        assert_eq!(loaded.completed_depths.len(), 1);
        assert_eq!(loaded.completed_depths["5000"][0].f1, 0.444);
    }

    // --- CalibrationGuard tests ---

    fn make_snapshot(chunks: usize, lang: &str) -> ProjectSnapshot {
        ProjectSnapshot {
            chunk_count: chunks,
            file_count: 0,
            primary_language: lang.to_string(),
            language_distribution: vec![],
            repo_age_days: 100,
            recent_commit_rate: 5.0,
        }
    }

    fn make_calibration(chunks: usize, lang: &str, days_ago: i64) -> CalibrationResult {
        let cal_time = Utc::now() - chrono::Duration::days(days_ago);
        CalibrationResult {
            calibrated_at: cal_time.to_rfc3339(),
            snapshot: make_snapshot(chunks, lang),
            best_config: CalibratedConfig {
                semantic_weight: 0.7,
                doc_demotion: 0.3,
                rrf_k: 60.0,
                recency_half_life_days: None,
                recency_weight: None,
                coupling_depth: None,
                budget_lines: None,
                search_limit: None,
                bridge_mode: None,
                bridge_boost_factor: None,
            },
            top_results: vec![],
            sample_count: 20,
            probe_count: 300,
            terse_warning: false,
        }
    }

    #[test]
    fn test_guard_first_run_always_calibrates() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "rust");
        assert!(guard.should_recalibrate(&current, None));
    }

    #[test]
    fn test_guard_chunk_delta_over_20_pct() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1300, "rust"); // 30% increase from 1000
        let prev = make_calibration(1000, "rust", 5);
        assert!(guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_chunk_delta_under_20_pct() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1100, "rust"); // 10% increase from 1000
        let prev = make_calibration(1000, "rust", 5);
        assert!(!guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_language_change() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "python");
        let prev = make_calibration(1000, "rust", 5);
        assert!(guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_language_unknown_ignored() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "unknown");
        let prev = make_calibration(1000, "rust", 5);
        assert!(!guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_age_over_30_days() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "rust");
        let prev = make_calibration(1000, "rust", 35);
        assert!(guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_age_under_30_days() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "rust");
        let prev = make_calibration(1000, "rust", 10);
        assert!(!guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_guard_no_change() {
        let guard = DefaultCalibrationGuard;
        let current = make_snapshot(1000, "rust");
        let prev = make_calibration(1000, "rust", 5);
        assert!(!guard.should_recalibrate(&current, Some(&prev)));
    }

    #[test]
    fn test_default_for_auto() {
        let home = PathBuf::from("/var/lib/bobbin");
        let source = PathBuf::from("/var/lib/bobbin/repos/demo");
        let args = CalibrateArgs::default_for_auto(
            home.clone(),
            Some("demo".to_string()),
            Some(source.clone()),
        );
        assert!(args.apply);
        assert!(!args.verbose);
        assert_eq!(args.samples, 20);
        assert_eq!(args.search_limit, Some(20));
        assert_eq!(args.budget, Some(300));
        // bobbin-ewtu2 regression guard: path MUST be the bobbin home (where
        // .bobbin/config.toml lives) so the init check passes — NOT the source tree.
        // repo/source must carry the git tree to sample. Reverting any of these
        // reintroduces the "Bobbin not initialized" failure on every incremental run.
        assert_eq!(args.path, home);
        assert_eq!(args.repo, Some("demo".to_string()));
        assert_eq!(args.source, Some(source));
    }

    #[test]
    fn test_capture_snapshot_from_index() {
        let snap = capture_snapshot_from_index(500);
        assert_eq!(snap.chunk_count, 500);
        assert_eq!(snap.primary_language, "unknown");
    }

    /// bobbin-10d: the doc comment on `run_full_sweep` claimed 240 configs and
    /// 19,200 probes for a grid that is actually 23,040 and 1.84M — off by 96x,
    /// because it stopped counting at the first five dimensions. A comment is
    /// the wrong place to keep arithmetic nobody re-derives, so this pins it.
    ///
    /// If a dimension is added, this test fails and BOTH it and the comment
    /// must be updated. That is the point: the failure is the reminder.
    #[test]
    fn test_full_sweep_grid_geometry() {
        let half_lives = [7.0f32, 14.0, 30.0, 90.0];
        let recency_weights = [0.0f32, 0.15, 0.30, 0.50];
        let budgets = [150usize, 300, 500];
        let search_limits = [10usize, 20, 30, 40];
        let bridge_modes = [
            BridgeMode::Off,
            BridgeMode::Inject,
            BridgeMode::Boost,
            BridgeMode::BoostInject,
        ];
        let bridge_boost_factors = [0.15f32, 0.3, 0.5];

        let grid = build_grid_with_recency(
            &half_lives,
            &recency_weights,
            &budgets,
            &search_limits,
            &bridge_modes,
            &bridge_boost_factors,
        );

        // 5 sw × 3 dd × 1 k × 4 hl × 4 rw × 3 budgets × 4 limits × 8 bridge
        assert_eq!(grid.len(), 23_040, "default full-sweep grid size");

        // The bridge term is 8 rather than 4 × 3 = 12: Off and Inject ignore
        // the boost factor. Asserted separately because it is the part of the
        // arithmetic that is easy to get wrong by inspection.
        let off_or_inject = grid
            .iter()
            .filter(|p| matches!(p.bridge_mode, BridgeMode::Off | BridgeMode::Inject))
            .count();
        assert_eq!(
            off_or_inject,
            23_040 / 8 * 2,
            "Off and Inject contribute one point each"
        );

        // What the sweep then multiplies by, spelled out so the doc comment's
        // headline figures are covered and not just the grid.
        let coupling_depths = 4;
        let default_commits = 20;
        assert_eq!(grid.len() * coupling_depths, 92_160);
        assert_eq!(grid.len() * coupling_depths * default_commits, 1_843_200);
    }

    /// bobbin-10d: pinning a dimension via CLI args divides the total, and the
    /// comment says so. Cheap to state, and it is the path `--budget 300
    /// --search-limit 20` actually takes on every incremental run.
    #[test]
    fn test_pinned_dimensions_shrink_the_grid() {
        let half_lives = [7.0f32, 14.0, 30.0, 90.0];
        let recency_weights = [0.0f32, 0.15, 0.30, 0.50];
        let bridge_modes = [
            BridgeMode::Off,
            BridgeMode::Inject,
            BridgeMode::Boost,
            BridgeMode::BoostInject,
        ];
        let bridge_boost_factors = [0.15f32, 0.3, 0.5];

        let pinned = build_grid_with_recency(
            &half_lives,
            &recency_weights,
            &[300],
            &[20],
            &bridge_modes,
            &bridge_boost_factors,
        );

        assert_eq!(pinned.len(), 23_040 / 3 / 4);
    }
}