semlith 0.17.1

A fast local vector store for AI agents — index files once, keep it current as you save, and answer questions across all of it in milliseconds without leaving the machine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
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
use anyhow::{Result, bail};
use clap::{Parser, Subcommand};
use fastembed::TextEmbedding;
use semlith::home;
use semlith::{Semlith, embed, embed::Model, filter::Filter, fleet::Fleet};
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;

/// A local semantic cache for AI agents.
#[derive(Parser)]
#[command(name = "semlith", version, about, long_about = None)]
struct Cli {
    /// Store directory (also settable with SEMLITH_STORE). Repeatable for
    /// `search`, `stats`, `files` and `mcp`, which read every store named;
    /// `index`, `watch` and `forget` write, and take exactly one.
    ///
    /// With no flag, semlith resolves a store itself: a `.semlith` beside the
    /// corpus if there is one, else the registered store covering this
    /// directory, else a new one under the store home.
    #[arg(long, short, global = true)]
    store: Vec<PathBuf>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Index files and directories. Re-running only re-embeds what changed.
    Index {
        /// Paths to index. Defaults to the current directory.
        paths: Vec<PathBuf>,

        /// Embedding model, used only when creating a new store.
        #[arg(long, short)]
        model: Option<String>,

        /// Name the store in the store home, instead of naming it after the
        /// directory being indexed.
        #[arg(long)]
        name: Option<String>,

        /// Suppress per-file output and download progress.
        #[arg(long, short)]
        quiet: bool,

        /// Refuse to download model weights. Exits non-zero naming the cache
        /// path if the model is not already there, so an air-gapped machine can
        /// prove this process never reached the network.
        #[arg(long)]
        airgap: bool,

        /// Index files semlith otherwise refuses: `.env`, private keys,
        /// anything under `~/.ssh` and the rest of the deny-list. Off by
        /// default, because indexing a private key by accident is a mistake and
        /// this flag is how you say you meant it. It has no effect on the MCP
        /// tools or the portal, which are held to the boundary either way.
        #[arg(long)]
        include_secrets: bool,
    },

    /// Run the daemon: hold every registered store's write lock, keep them
    /// current as files are saved, and serve the portal on 127.0.0.1. Runs
    /// until interrupted.
    Start {
        /// Stores to open. Defaults to every registered store.
        paths: Vec<PathBuf>,

        /// Do not record what agents retrieve into each store's ledger.
        ///
        /// Recording is on from 0.15.0. The rows never leave the machine, the
        /// daemon says on every start that it is recording and how to stop,
        /// and deleting every row is one statement. A record an agent cannot
        /// see being written is what makes the savings figure and the audit
        /// trail true rather than optional — and until 0.15.0 the ledger was
        /// opt-in, which in practice meant empty.
        ///
        /// `SEMLITH_LEDGER=0` is the same thing for a machine that should
        /// never record at all. `--ledger` was removed rather than kept as a
        /// flag that does nothing, so a script that passes it fails here and
        /// is corrected once.
        #[arg(long)]
        no_ledger: bool,

        /// Port to listen on (also settable with SEMLITH_PORT). Never falls
        /// back to another port: the URL is meant to be a bookmark.
        #[arg(long)]
        port: Option<u16>,

        /// Quiet period in milliseconds after the last change before
        /// re-embedding, so one editor save costs one re-embed.
        #[arg(long, default_value_t = semlith::watch::DEBOUNCE.as_millis() as u64)]
        debounce: u64,

        /// Refuse to download model weights.
        #[arg(long)]
        airgap: bool,

        /// Do not answer MCP over HTTP. The portal and `semlith mcp` over
        /// stdio are unaffected; only the `/mcp` endpoint is closed.
        #[arg(long)]
        no_mcp_http: bool,
    },

    /// Show or rotate the agent key that authenticates the HTTP MCP endpoint.
    Key {
        #[command(subcommand)]
        what: KeyCommand,
    },

    /// Move an existing store directory into the store home and register it,
    /// so `semlith mcp` and `semlith start` find it with no flags. Nothing is
    /// re-embedded and the store's format does not change.
    Adopt {
        /// The store directory to move — usually `./.semlith`.
        store_dir: PathBuf,

        /// The directory this store indexes. Defaults to the directory the
        /// store sat in. Given on its own with `--name`, re-points a
        /// registered store whose corpus moved.
        #[arg(long)]
        root: Option<PathBuf>,

        /// Name it in the home explicitly.
        #[arg(long)]
        name: Option<String>,
    },

    /// Say that a store directory outside the store home may be opened.
    ///
    /// A `.semlith` directory can arrive inside a repository somebody else
    /// wrote, and a store is what semlith answers from — so one that semlith
    /// did not create is opened only after you have said so, once. Nothing is
    /// moved and nothing is re-embedded; `semlith adopt` is the command that
    /// moves a store into the home.
    Trust {
        /// The store directory to trust — usually `./.semlith`.
        store_dir: Option<PathBuf>,

        /// Print what is trusted and change nothing.
        #[arg(long)]
        list: bool,
    },

    /// Keep the store current: re-embed files as they are saved. Runs until
    /// interrupted, and holds the store's write lock while it does.
    Watch {
        /// Paths to watch. Defaults to the current directory.
        paths: Vec<PathBuf>,

        /// Quiet period in milliseconds after the last change before
        /// re-embedding, so one editor save costs one re-embed.
        #[arg(long, default_value_t = semlith::watch::DEBOUNCE.as_millis() as u64)]
        debounce: u64,

        /// Suppress per-file output and download progress.
        #[arg(long, short)]
        quiet: bool,
    },

    /// Search the store.
    Search {
        query: String,

        /// Number of results.
        #[arg(long, short, default_value_t = 8)]
        k: usize,

        /// Only search files matching this glob. Repeatable; a relative
        /// pattern matches anywhere in the tree.
        #[arg(long, short)]
        path: Vec<String>,

        /// Only search files with this extension. Repeatable.
        #[arg(long, short)]
        ext: Vec<String>,

        /// Only search files of this language. Repeatable; see `semlith languages`.
        #[arg(long, short)]
        lang: Vec<String>,

        /// Lift the implementation (`code`), the prose about it (`docs`), or
        /// neither (`any`, the default). A bias, not a filter.
        #[arg(long, default_value = "any")]
        prefer: String,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// Print one span, or one symbol's definition, and nothing around it.
    ///
    /// The second stage after a search: `semlith read src/store.rs:1041-1080`
    /// or `semlith read record_retrieval`.
    Read {
        /// `path:start-end`, `path:line`, or a symbol name.
        target: String,

        /// Only read files matching this glob. Repeatable.
        #[arg(long, short)]
        path: Vec<String>,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// Run a tree-sitter structural pattern over the indexed files of one
    /// language.
    ///
    /// `semlith pattern --lang rust '(call_expression function: (identifier) @f)'`
    Pattern {
        /// The pattern, in tree-sitter's S-expression query syntax.
        query: String,

        /// The language to parse. Required; see `semlith languages`.
        #[arg(long, short)]
        lang: String,

        /// Only search files matching this glob. Repeatable.
        #[arg(long, short)]
        path: Vec<String>,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// Show what the store contains.
    Stats,

    /// List the files currently indexed.
    Files,

    /// Remove a file from the store.
    Forget { path: PathBuf },

    /// Delete a store: its vectors, chunks, graph and ledger, and the registry
    /// entry naming it. The files it indexed are not touched.
    Drop {
        /// The registered store's name, as `semlith stats` prints it.
        ///
        /// Called `name` rather than `store` because `--store` is a global
        /// argument: two arguments with the same id in one subcommand is a
        /// clap panic at parse time, so every `semlith drop` panicked instead
        /// of deleting anything. The value name keeps the usage line reading
        /// `semlith drop <STORE>`.
        #[arg(value_name = "STORE")]
        name: String,
        /// Skip the confirmation prompt.
        #[arg(long)]
        yes: bool,
    },

    /// Fetch one URL into the store and index it: a web page, a PDF such as an
    /// arXiv paper, or a file on GitHub. One request, for exactly the URL
    /// given — semlith never follows links, re-fetches, or sends a credential.
    Add {
        /// The https URL to fetch. A `github.com/.../blob/...` link is
        /// rewritten to the raw file it displays.
        url: String,

        /// Name the store in the store home, instead of naming it after the
        /// current directory.
        #[arg(long)]
        name: Option<String>,

        /// Refuse to reach the network, which is the whole of this command, so
        /// it exits before opening a socket.
        #[arg(long)]
        airgap: bool,
    },

    /// Run as an MCP server over stdio, for agents to call as a tool.
    Mcp,

    /// Put semlith on PATH, pre-fetch the embedding model and register it
    /// with the agents you use. Every step is idempotent, so this is also the
    /// repair command.
    Setup {
        /// Take the default at every prompt — add to PATH, download the model,
        /// register no agent — so a script or an agent can run it unattended.
        #[arg(long, short)]
        yes: bool,

        /// Refuse to download model weights. The other steps still run.
        #[arg(long)]
        airgap: bool,
    },

    /// Replace this binary with the newest release for this machine. Runs only
    /// when asked: semlith never checks for an update on its own.
    Upgrade {
        /// Say whether a newer release exists and change nothing. Exits 0 when
        /// current and 10 when an upgrade is available.
        #[arg(long)]
        check: bool,

        /// Install this tag instead of the newest release, e.g. `v0.9.0`.
        #[arg(long)]
        version: Option<String>,

        /// Refuse to reach the network. Every path below exits before opening
        /// a connection, which is what an air-gapped machine needs to prove.
        #[arg(long)]
        airgap: bool,
    },

    /// List available embedding models.
    Models,

    /// List the language names `--lang` accepts, and their extensions.
    Languages,

    /// Print what agents retrieved from this store, newest first. Needs no
    /// key: recording and this dump are free on every tier.
    Ledger {
        /// How many retrievals to print.
        #[arg(long, default_value_t = 20)]
        last: usize,

        /// Re-walk the hash chain and exit non-zero if it is broken.
        ///
        /// Prints nothing else. For a cron job or a CI step that wants to know
        /// the record has not been edited, rather than a person reading rows.
        #[arg(long)]
        verify: bool,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// Find where a symbol is defined.
    Symbol {
        /// The symbol's name, matched exactly.
        name: String,

        /// Most definitions to print.
        #[arg(long, short, default_value_t = 20)]
        k: usize,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// List what calls a symbol and what it calls.
    Neighbors {
        /// The symbol's name, matched exactly.
        name: String,

        /// Only follow edges of this kind. Repeatable; one of defines, calls,
        /// imports, references, contains. Every kind by default.
        #[arg(long, short)]
        kind: Vec<String>,

        /// Show every definition behind a collapsed row, and the targets this
        /// store holds no definition for.
        ///
        /// Off by default. A name with four definitions is one row saying so,
        /// because four rows would read as four calls; and a call into a
        /// dependency that was never indexed is left out, because a list of
        /// names the store knows nothing about is noise in an answer about
        /// this codebase.
        #[arg(long)]
        all: bool,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },

    /// Show the shortest chain of edges between two symbols.
    Path {
        /// The symbol the chain starts at.
        from: String,

        /// The symbol the chain ends at.
        to: String,

        /// Most hops to search before giving up.
        #[arg(long, short, default_value_t = 6)]
        depth: u32,

        /// Walk names with several definitions too, and label what that found.
        ///
        /// Off by default. A name like `record` or `index` can be several
        /// unrelated functions, and a chain that crosses one has changed
        /// subject halfway through without saying so. This prints those chains
        /// with the join marked and the sentence that says what they are worth.
        #[arg(long)]
        all_edges: bool,

        /// Refuse to cross a name with several definitions. On by default.
        ///
        /// Here so a script can state the default rather than rely on it. When
        /// both this and --all-edges are given, this one wins.
        #[arg(long)]
        strict: bool,

        /// Emit JSON instead of formatted text.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum KeyCommand {
    /// Print the agent key and the stanza that carries it.
    Show {
        /// Print the key alone, for a script.
        #[arg(long)]
        quiet: bool,
    },

    /// Mint a new agent key. Every client configured with the old one needs
    /// the new stanza.
    Rotate {
        /// Stop accepting the previous key at once, rather than letting a
        /// session that is already open finish.
        #[arg(long)]
        now: bool,
    },
}

fn main() -> Result<()> {
    quiet_on_a_closed_pipe();
    let cli = Cli::parse();
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    match cli.command {
        Command::Setup { yes, airgap } => {
            arm_airgap(airgap);
            semlith::setup::run(yes, airgap)?;
        }

        Command::Upgrade {
            check,
            version,
            airgap,
        } => {
            arm_airgap(airgap);
            if check {
                if let Some(reason) = semlith::upgrade::offline() {
                    bail!("{reason}");
                }
                let found = semlith::upgrade::check()?;
                println!("installed {}", found.installed);
                println!("latest    {}", found.latest.trim_start_matches('v'));
                if let Some(reason) = &found.blocked {
                    println!("note: {reason}");
                }
                if found.available {
                    println!("run `semlith upgrade` to install it");
                    std::process::exit(semlith::upgrade::UPGRADE_AVAILABLE);
                }
                println!("already current");
            } else {
                semlith::upgrade::apply(version)?;
            }
        }

        Command::Models => {
            // The default is listed first and separately: it is not one of
            // fastembed's built-ins, so it never appears in their list.
            println!(
                "{:<44} {:>5} dim  default. IBM Granite R2 small, int8, English",
                embed::GRANITE_NAME,
                384
            );
            for info in TextEmbedding::list_supported_models() {
                println!(
                    "{:<44} {:>5} dim  {}",
                    info.model, info.dim, info.description
                );
            }
        }

        Command::Index {
            paths,
            model,
            name,
            quiet,
            airgap,
            include_secrets,
        } => {
            arm_airgap(airgap);
            let model = model
                .map(|m| m.parse::<Model>().map_err(anyhow::Error::msg))
                .transpose()?;

            let roots = if paths.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                paths
            };

            // Before a store is opened, because opening one creates it. A run
            // whose paths cannot be read used to leave an empty store behind,
            // registered under the typo's own name, and exit 0 (#76).
            let (roots, unreadable) = semlith::check_roots(&roots);
            for (path, why) in &unreadable {
                eprintln!("cannot index {}: {why}", path.display());
            }
            let Some(first) = roots.first().cloned() else {
                bail!(
                    "nothing to index: no path given could be read. Nothing was created \
                     and nothing was registered."
                );
            };

            // The first path is what the store is about, so it is what names
            // the store and what the registry records as its root. `semlith
            // index ~/work/api` from anywhere means the api store, not a store
            // named after wherever the shell happened to be.
            let choice = home::resolve(&cli.store, &first, name.as_deref())?;
            if let Some(hint) = choice.hint() {
                eprintln!("{hint}");
            }
            let dir = choice.one()?;
            let mut store = Semlith::open(&dir, model)?;
            store.quiet = quiet;
            // No confinement on the command line: the person typing it owns the
            // machine. The deny-list still applies, because indexing a private
            // key by accident is a mistake rather than a decision.
            store.boundary = semlith::Boundary {
                roots: None,
                allow_secrets: include_secrets,
            };

            let started = Instant::now();
            // Throttled, not per file: a corpus large enough to need an
            // estimate is one where a line per file is the noise the estimate
            // is trying to cut through.
            let mut spoke = Instant::now();
            let report = store.index_paths(&roots, |path, p| {
                if quiet {
                    return;
                }
                if p.outcome == semlith::FileOutcome::Indexing {
                    eprintln!("  + {}", display(path));
                }
                if p.outcome == semlith::FileOutcome::Refused {
                    eprintln!("  - {}", display(path));
                }
                if spoke.elapsed() >= PROGRESS_INTERVAL {
                    spoke = Instant::now();
                    eprintln!("    {}", predict(p, started.elapsed()));
                }
            })?;

            // Recorded after the run, not before it: a registry entry for a
            // store that failed to index is a store the daemon opens and the
            // portal lists with nothing in it.
            let model_name = store.model().to_string();
            home::record(&choice, &roots, &model_name)?;

            let (files, chunks, bytes) = store.stats()?;
            // Images are counted apart from chunks because they are not
            // chunks: one image is one vector, and folding it into a chunk
            // count would make the number mean two things.
            let images = if report.images > 0 {
                format!(", {} images", report.images)
            } else {
                String::new()
            };
            // Named one per line. A refusal reported as a count is one the
            // person retries with the same arguments.
            for (path, why) in &report.refused {
                eprintln!("refused: {path} — {why}");
            }
            if !report.refused.is_empty() && !include_secrets {
                eprintln!("  `--include-secrets` indexes these anyway, if you meant to.");
            }
            eprintln!(
                "indexed {} files ({} chunks{images}) in {:.1}s — {} already indexed, {} skipped, {} removed",
                report.indexed,
                report.chunks,
                started.elapsed().as_secs_f32(),
                report.unchanged,
                report.skipped,
                report.removed,
            );
            eprintln!(
                "store: {files} files, {chunks} chunks, {} at {}",
                semlith::human_bytes(bytes),
                dir.display()
            );
            // The readable roots are indexed and recorded; the status is what
            // changes, so a script that indexed several roots and tolerated a
            // missing one sees the failure it was told about (#76).
            if !unreadable.is_empty() {
                bail!(
                    "{} of {} paths could not be read, and were not indexed",
                    unreadable.len(),
                    unreadable.len() + roots.len()
                );
            }
        }

        Command::Watch {
            paths,
            debounce,
            quiet,
        } => {
            let roots = if paths.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                paths
            };

            let choice = home::resolve(&cli.store, &roots[0], None)?;
            if let Some(hint) = choice.hint() {
                eprintln!("{hint}");
            }
            let dir = choice.one()?;
            let mut store = Semlith::open(&dir, None)?;
            store.quiet = quiet;
            home::record(&choice, &roots, &store.model().to_string())?;

            // Installed before the first event: Ctrl-C is how this command
            // ends, so it has to leave the store whole.
            semlith::watch::stop_on_signal();

            let shown: Vec<String> = roots.iter().map(|r| display(r)).collect();
            semlith::watch::run(
                &mut store,
                &roots,
                std::time::Duration::from_millis(debounce),
                &semlith::watch::STOP,
                |progress| {
                    use semlith::watch::Progress;
                    match progress {
                        // A watcher that has quietly stopped updating looks
                        // exactly like a corpus nobody edited, so it says what
                        // it is watching and what it did.
                        Progress::Ready {
                            catch_up,
                            files,
                            chunks,
                        } => eprintln!(
                            "watching {} — {files} files, {chunks} chunks \
                             ({} indexed at startup, {} unchanged)",
                            shown.join(", "),
                            catch_up.indexed,
                            catch_up.unchanged,
                        ),
                        Progress::File(path) if !quiet => eprintln!("  ~ {}", display(path)),
                        Progress::Batch(report, elapsed) if !quiet => eprintln!(
                            "  {} re-embedded, {} removed, {} chunks in {:.1}s",
                            report.indexed,
                            report.removed,
                            report.chunks,
                            elapsed.as_secs_f32(),
                        ),
                        Progress::Error(e) => eprintln!("semlith: watch error: {e}"),
                        _ => {}
                    }
                },
            )?;
        }

        Command::Search {
            query,
            k,
            path,
            ext,
            lang,
            prefer,
            json,
        } => {
            // Built before any store is opened, so an unknown language name
            // fails immediately rather than after a model load.
            let filter = Filter::new(&path, &ext, &lang)?;
            // Parsed before the model loads, like the filter, so a typo in the
            // argument costs nothing.
            let prefer = semlith::Prefer::parse(&prefer)?;

            let mut fleet = read_fleet(&cli.store, &cwd, false)?;
            fleet.quiet = json;

            // A glob that selects nothing is a different answer from a corpus
            // that does not discuss the query, and only one of them is the
            // user's typo. Across several stores this is one question about the
            // whole selection: a filter that matches nothing in one store but
            // something in another has not selected nothing.
            let selected = (!filter.is_empty())
                .then(|| fleet.matching_files(&filter))
                .transpose()?;
            if selected == Some(0) {
                if json {
                    println!("[]");
                } else {
                    eprintln!(
                        "no files match the filter (store has {} chunks)",
                        fleet.chunks()
                    );
                }
                return Ok(());
            }

            let started = Instant::now();
            let hits = fleet.search_preferring(None, &query, k, &filter, prefer)?;
            let elapsed = started.elapsed();
            // The command line is a client like any other, and its retrievals
            // count for exactly as much as an agent's. Recorded under `cli`, in
            // the same table, through the same path.
            semlith::ledger::search(&fleet, &CLI_LEDGER, &query, &hits, elapsed);

            if json {
                println!("{}", serde_json::to_string_pretty(&hits)?);
            } else if hits.is_empty() {
                eprintln!("no matches (store has {} chunks)", fleet.chunks());
            } else {
                let mut out = std::io::stdout().lock();
                for (i, h) in hits.iter().enumerate() {
                    // The store is named only when there is more than one to
                    // tell apart, so a single-store search prints what it
                    // always printed.
                    let from = match &h.store {
                        Some(label) => format!("[{label}] "),
                        None => String::new(),
                    };
                    // One letter per list that found it: v vector, f full
                    // text, g graph. A hit the graph alone reached is a
                    // neighbour of a match rather than a match.
                    let via: String = h
                        .lists
                        .iter()
                        .map(|l| match *l {
                            "vector" => 'v',
                            "keyword" => 'f',
                            "image" => 'i',
                            _ => 'g',
                        })
                        .collect();
                    // An image carries its pixel size where a chunk carries a
                    // line range, and has no excerpt to print under it.
                    let where_in = match h.image {
                        Some(px) => format!("{}x{} px", px.width, px.height),
                        None => format!("{}-{}", h.start_line, h.end_line),
                    };
                    writeln!(
                        out,
                        "{}{}. {:.3} {via:<3} {from}{}:{where_in}{}",
                        bold(),
                        i + 1,
                        h.score,
                        display(std::path::Path::new(&h.path)),
                        reset()
                    )?;
                    for line in h.text.lines() {
                        writeln!(out, "   {line}")?;
                    }
                    writeln!(out)?;
                }
                let across = if fleet.len() > 1 {
                    // A store that contributed nothing is worth seeing: it is
                    // otherwise indistinguishable from one that was never
                    // opened.
                    let breakdown: Vec<String> = fleet
                        .labels()
                        .iter()
                        .map(|label| {
                            let n = hits
                                .iter()
                                .filter(|h| h.store.as_deref() == Some(*label))
                                .count();
                            format!("{label} {n}")
                        })
                        .collect();
                    format!(" across {} stores: {}", fleet.len(), breakdown.join(", "))
                } else {
                    String::new()
                };
                match selected {
                    Some(n) => eprintln!(
                        "{} hits in {:?} (filter selected {n} of {} files){across}",
                        hits.len(),
                        elapsed,
                        fleet.files()?,
                    ),
                    None => eprintln!("{} hits in {:?}{across}", hits.len(), elapsed),
                }
                // How the query was read, and what that did. Printed on every
                // answer rather than only when it was surprising: a caller can
                // only correct a misread shape if it can see one happened.
                let shape = semlith::shape_of(&query);
                match prefer {
                    semlith::Prefer::Any => {
                        eprintln!("{} · {}", shape.as_str(), shape.weighting())
                    }
                    chosen => eprintln!(
                        "{} · {} · prefer {}",
                        shape.as_str(),
                        shape.weighting(),
                        chosen.as_str()
                    ),
                }
                // Only when it happened. A store inside its budget never sees
                // this line, and a store past it should not have to guess why
                // its queries got slower.
                let evicted: u64 = fleet.each().map(|(_, s)| s.evictions()).sum();
                if evicted > 0 {
                    eprintln!(
                        "semlith: put down {evicted} shard(s) to stay inside the {} MB index \
                         budget; raise {} to hold more",
                        semlith::index::budget_mb(),
                        semlith::index::INDEX_MEMORY_ENV,
                    );
                }
            }
        }

        Command::Ledger { last, verify, json } => {
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let many = fleet.len() > 1;
            if verify {
                let mut broken = false;
                for (label, store) in fleet.each() {
                    match semlith::store::ledger_break(store.db())? {
                        Some(row) => {
                            broken = true;
                            println!("{label}: the chain does not verify from row {row} onwards");
                        }
                        None => println!("{label}: the chain is intact"),
                    }
                }
                // Non-zero so a script can act on it. A verify that reported a
                // broken chain and exited 0 would be worse than no verify.
                if broken {
                    std::process::exit(1);
                }
                return Ok(());
            }
            let mut any = false;
            for (label, store) in fleet.each() {
                let rows = semlith::store::retrievals(store.db(), last)?;
                if json {
                    println!("{}", serde_json::to_string_pretty(&rows)?);
                    any = any || !rows.is_empty();
                    continue;
                }
                if many {
                    println!("{}{label}{}", bold(), reset());
                }
                if rows.is_empty() {
                    continue;
                }
                any = true;
                let mut out = std::io::stdout().lock();
                for row in &rows {
                    writeln!(
                        out,
                        "{}  {:<14} {:>3} hits  {:>6} ms  {}",
                        human_time(row.at),
                        row.client,
                        row.hits,
                        row.micros / 1000,
                        row.query,
                    )?;
                }
                // A chain that does not verify is the one thing this table can
                // say that a log file cannot, so it is said loudly.
                if let Some(broken) = semlith::store::ledger_break(store.db())? {
                    writeln!(
                        out,
                        "\n  the chain does not verify from row {broken} onwards: \
                         these rows have been edited or removed"
                    )?;
                }
            }
            if !any && !json {
                eprintln!(
                    "nothing recorded yet. The daemon records by default from 0.15.0 and says \
                     so on every start; `--no-ledger` or SEMLITH_LEDGER=0 stops it. Nothing \
                     recorded ever leaves this machine."
                );
            }
        }

        Command::Symbol { name, k, json } => {
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            // One answer rather than three: the definition, who calls it, what
            // it calls, and the ring beyond that. Asking for a definition and
            // then having to ask twice more to know whether it was the right
            // one is what this replaces.
            let found =
                fleet.evidence_in(None, &name, &semlith::graph::dependency_kinds(), k, false)?;
            if json {
                println!("{}", serde_json::to_string_pretty(&found)?);
            } else if found.definitions.is_empty() {
                eprintln!("{}", nothing_known(&fleet, &name));
            } else {
                let mut out = std::io::stdout().lock();
                writeln!(
                    out,
                    "{}",
                    found.render(bold(), reset(), &|p| display(std::path::Path::new(p)))
                )?;
            }
        }

        Command::Read { target, path, json } => {
            let filter = Filter::new(&path, &[], &[])?;
            let target = semlith::Target::parse(&target);
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let started = Instant::now();
            let found = fleet.read_in(None, &target, &filter)?;
            semlith::ledger::graph(
                &fleet,
                &CLI_LEDGER,
                "read",
                match &target {
                    semlith::Target::Span { path, .. } => path,
                    semlith::Target::Symbol(name) => name,
                },
                "",
                found.is_some(),
                started.elapsed(),
            );
            match found {
                None => eprintln!(
                    "nothing indexed at that span or under that name (store has {} chunks)",
                    fleet.chunks()
                ),
                Some(found) if json => println!("{}", serde_json::to_string_pretty(&found)?),
                // Several definitions and nothing to choose between them, so
                // the list is the answer rather than a guess at which one.
                Some(semlith::Read::Choose(rows)) => {
                    let mut out = std::io::stdout().lock();
                    writeln!(out, "{} definitions of this name:", rows.len())?;
                    for row in &rows {
                        writeln!(
                            out,
                            "  {} {}  {}{}:{}-{}",
                            row.name,
                            row.kind,
                            store_prefix(&row.store),
                            display(std::path::Path::new(&row.path)),
                            row.start_line,
                            row.end_line,
                        )?;
                    }
                }
                Some(semlith::Read::One(span)) => {
                    let mut out = std::io::stdout().lock();
                    let named = match (&span.symbol, &span.symbol_kind) {
                        (Some(name), Some(kind)) => format!("  {name} {kind}"),
                        (Some(name), None) => format!("  {name}"),
                        _ => String::new(),
                    };
                    writeln!(
                        out,
                        "{}{}{}:{}-{}{named}{}{}",
                        bold(),
                        store_prefix(&span.store),
                        display(std::path::Path::new(&span.path)),
                        span.start_line,
                        span.end_line,
                        if span.fresh { "" } else { "  · stale" },
                        reset(),
                    )?;
                    for line in span.text.lines() {
                        writeln!(out, "{line}")?;
                    }
                }
            }
        }

        Command::Pattern {
            query,
            lang,
            path,
            json,
        } => {
            let filter = Filter::new(&path, &[], &[])?;
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let started = Instant::now();
            let found = fleet.pattern_in(None, &lang, &query, &filter)?;
            semlith::ledger::graph(
                &fleet,
                &CLI_LEDGER,
                "pattern",
                &query,
                "",
                !found.matches.is_empty(),
                started.elapsed(),
            );
            if json {
                println!("{}", serde_json::to_string_pretty(&found)?);
            } else if found.matches.is_empty() {
                // Two different facts, and only one of them means the caller
                // should change the pattern.
                if found.files == 0 {
                    eprintln!("no indexed file is {}", found.language);
                } else {
                    eprintln!("no match in {} {} files", found.files, found.language);
                }
            } else {
                let mut out = std::io::stdout().lock();
                for found in &found.matches {
                    writeln!(
                        out,
                        "{}{}{}:{}-{}{} @{}  {}",
                        bold(),
                        store_prefix(&found.store),
                        display(std::path::Path::new(&found.path)),
                        found.start_line,
                        found.end_line,
                        reset(),
                        found.capture,
                        found.text,
                    )?;
                }
                eprintln!(
                    "{} match(es) in {} {} files{}",
                    found.matches.len(),
                    found.files,
                    found.language,
                    if found.truncated { " (truncated)" } else { "" },
                );
            }
        }

        Command::Neighbors {
            name,
            kind,
            all,
            json,
        } => {
            for k in &kind {
                if !semlith::graph::KINDS.contains(&k.as_str()) {
                    anyhow::bail!(
                        "unknown edge kind {k:?}; the kinds are {}",
                        semlith::graph::KINDS.join(", ")
                    );
                }
            }
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let started = Instant::now();
            let neighbours = fleet.neighbours_in(None, &name, &kind, all)?;
            let found = !neighbours.callers.is_empty() || !neighbours.callees.is_empty();
            semlith::ledger::graph(
                &fleet,
                &CLI_LEDGER,
                "neighbors",
                &name,
                "",
                found,
                started.elapsed(),
            );
            if json {
                println!("{}", serde_json::to_string_pretty(&neighbours)?);
            } else if neighbours.callers.is_empty()
                && neighbours.callees.is_empty()
                && neighbours.hidden == 0
                && neighbours.unresolved.is_empty()
            {
                eprintln!("{}", nothing_known(&fleet, &name));
            } else {
                let mut out = std::io::stdout().lock();
                print_ends(&mut out, "callers", &neighbours.callers)?;
                print_ends(&mut out, "callees", &neighbours.callees)?;
                if neighbours.hidden > 0 {
                    writeln!(
                        out,
                        "\n{} target{} outside this store, not listed (--all)",
                        neighbours.hidden,
                        if neighbours.hidden == 1 { "" } else { "s" },
                    )?;
                }
                if !neighbours.unresolved.is_empty() {
                    writeln!(out, "\n{}outside this store{}", bold(), reset())?;
                    for end in &neighbours.unresolved {
                        writeln!(out, "  {} via {}", end.name, end.kind)?;
                    }
                }
            }
        }

        Command::Path {
            from,
            to,
            depth,
            all_edges,
            strict,
            json,
        } => {
            let all_edges = all_edges && !strict;
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let started = Instant::now();
            let chain = fleet.path_in(None, &from, &to, depth, all_edges)?;
            semlith::ledger::graph(
                &fleet,
                &CLI_LEDGER,
                "path",
                &from,
                "",
                chain.is_some(),
                started.elapsed(),
            );
            if json {
                println!("{}", serde_json::to_string_pretty(&chain)?);
            } else {
                match chain {
                    // An empty chain is `from == to`, which is a path of no
                    // hops rather than no path.
                    Some(chain) if chain.steps.is_empty() => {
                        println!("{from} is {to}");
                    }
                    Some(chain) => {
                        let mut out = std::io::stdout().lock();
                        write!(
                            out,
                            "{}",
                            chain.render(bold(), reset(), &|p| display(std::path::Path::new(p)))
                        )?;
                    }
                    None => eprintln!(
                        "{}",
                        semlith::graph::not_connected(&from, &to, depth, all_edges)
                    ),
                }
            }
        }

        Command::Languages => {
            for entry in semlith::filter::LANGUAGES {
                // Extensions print with their dot and filenames without one,
                // which is the difference a reader has to see: `.mk` is an
                // extension and `Makefile` is the whole name of the file.
                let what = entry
                    .extensions
                    .iter()
                    .map(|e| format!(".{e}"))
                    .chain(entry.filenames.iter().map(|f| f.to_string()))
                    .collect::<Vec<_>>()
                    .join(" ");
                // The same column the portal's About page and
                // `semlith_languages` show: whether this language carries
                // symbols and edges as well as text.
                let graph = if semlith::graph::has_graph(entry.name) {
                    "graph"
                } else {
                    "     "
                };
                println!("{:<12} {graph}  {what}", entry.name);
            }
        }

        Command::Stats => {
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let many = fleet.len() > 1;
            let mut totals = (0, 0, 0);
            for (label, store) in fleet.each() {
                let (files, chunks, bytes) = store.stats()?;
                totals = (totals.0 + files, totals.1 + chunks, totals.2 + bytes);
                if many {
                    println!("{label}");
                }
                // The store's own directory, not the flag order: a store named
                // twice was opened once.
                println!("store    {}", store.dir().display());
                // Said where somebody will see it. A store directory other
                // accounts on this machine can read holds the text of every
                // file it indexed, and one made before 0.14.0 is loose until
                // this binary opens it.
                if let Some(mode) = home::loose_mode(store.dir()) {
                    println!(
                        "warning  the store directory is mode {mode:o}; other users on this \
                         machine can read what it indexed. Opening it with this semlith \
                         narrows it to 700."
                    );
                }
                println!("model    {} ({} dim)", store.model(), store.dim());
                println!("files    {files}");
                println!("chunks   {chunks}");
                let images = store.image_count()?;
                if images > 0 {
                    println!("images   {images}");
                }
                println!("vectors  {}", store.len());
                if let Some((shards, max)) = store.shards() {
                    // What the store costs to search, before searching it.
                    println!(
                        "shards   {shards}, up to {max} resident ({} MB budget, {})",
                        semlith::index::budget_mb(),
                        semlith::index::INDEX_MEMORY_ENV,
                    );
                }
                println!("indexed  {}", semlith::human_bytes(bytes));
                // One line, and never a number without its denominator. A
                // store that has recorded nothing prints nothing here rather
                // than a zero that reads like a measurement.
                let savings = semlith::store::ledger_savings(store.db())?;
                if savings.total > 0 {
                    println!(
                        "saved    {} tokens not read, over {} of {} retrievals \
                         ({}% coverage, {})",
                        savings.net,
                        savings.credited,
                        savings.total,
                        savings.coverage(),
                        savings.tier(),
                    );
                }
                if many {
                    println!();
                }
            }
            // The per-store blocks are the diagnostic; the total is the answer
            // to "how much is indexed".
            if many {
                println!(
                    "total    {} stores, {} files, {} chunks, {}",
                    fleet.len(),
                    totals.0,
                    totals.1,
                    semlith::human_bytes(totals.2),
                );
            }
        }

        Command::Files => {
            let fleet = read_fleet(&cli.store, &cwd, false)?;
            let many = fleet.len() > 1;
            for (label, store) in fleet.each() {
                if many {
                    println!("{label}");
                }
                for path in semlith::store::all_paths(store.db())? {
                    println!("{}", display(std::path::Path::new(&path)));
                }
                if many {
                    println!();
                }
            }
        }

        Command::Add { url, name, airgap } => {
            arm_airgap(airgap);

            // The current directory is the anchor, the way it is for `index`
            // with no path: "add this to the store I am working in".
            let choice = home::resolve(&cli.store, &cwd, name.as_deref())?;
            let choice = resolve_for_add(choice, &cli.store, name.as_deref())?;
            if let Some(hint) = choice.hint() {
                eprintln!("{hint}");
            }
            let dir = choice.one()?;

            let spinner = cliclack::spinner();
            spinner.start(format!("fetching {url}"));
            let fetched = match semlith::add::fetch(&url, &dir) {
                Ok(fetched) => {
                    spinner.stop(format!(
                        "fetched {}",
                        semlith::human_bytes(fetched.bytes as i64)
                    ));
                    fetched
                }
                Err(e) => {
                    spinner.error("fetch failed");
                    return Err(e);
                }
            };

            let mut store = Semlith::open(&dir, None)?;
            store.quiet = true;
            let report = store.index_paths(std::slice::from_ref(&fetched.path), |_, _| {})?;

            // The root recorded is the downloads directory, not the file: a
            // root is what `semlith start` watches, and watching one file would
            // leave the next thing added to the same store unwatched.
            //
            // Recorded after the fetch and the index both succeeded, so a
            // failed add leaves no registry entry pointing at nothing.
            let model_name = store.model().to_string();
            home::record(&choice, &[semlith::add::downloads_dir(&dir)], &model_name)?;

            eprintln!("{} -> {}", fetched.url, display(&fetched.path));
            eprintln!("indexed {} chunks into {}", report.chunks, dir.display());
        }

        Command::Forget { path } => {
            // Anchored on the file, the way `index` is anchored on the path it
            // is given. Resolving from the working directory asked whichever
            // store covers wherever the user happened to be standing, which for
            // a forget run from anywhere but the corpus is a store that has
            // never held the file: it removed nothing, said so, and exited 0
            // (#77). A caller that believes the exit status believes the file
            // is gone.
            // The directory holding the file, and the working directory for a
            // bare name with no directory in it at all — which is how somebody
            // standing in the corpus types it.
            let anchor = if path.is_dir() {
                path.clone()
            } else {
                match path.parent() {
                    Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
                    _ => cwd.clone(),
                }
            };
            let choice = home::resolve(&cli.store, &anchor, None)?;
            if let Some(hint) = choice.hint() {
                eprintln!("{hint}");
            }
            // `New` is the store that *would* be created for this path. Opening
            // it would create an empty store directory to delete nothing from.
            if matches!(choice, home::Choice::New { .. }) {
                anyhow::bail!(not_indexed(&path));
            }
            let mut store = Semlith::open(&choice.one()?, None)?;
            let (chunks, images) = store.forget(&path)?;
            if chunks == 0 && images == 0 {
                anyhow::bail!(not_indexed(&path));
            }
            // An image has no chunks, so a message counting only chunks would
            // report a successful forget as having done nothing.
            let what = match (chunks, images) {
                (0, images) => format!("{images} image vector(s)"),
                (chunks, 0) => format!("{chunks} chunks"),
                (chunks, images) => format!("{chunks} chunks and {images} image vector(s)"),
            };
            eprintln!("removed {what} for {}", path.display());
        }

        Command::Drop { name: store, yes } => {
            let dir = semlith::home::Registry::dir_of(&store)?;
            if !semlith::home::Registry::load()?.stores.contains_key(&store) {
                anyhow::bail!("no registered store called {store}");
            }
            if !yes {
                let go = cliclack::confirm(format!(
                    "Delete {store}? Its vectors, chunks, graph and ledger go;                      the files it indexed are untouched."
                ))
                .initial_value(false)
                .interact()
                .unwrap_or(false);
                if !go {
                    eprintln!("nothing was deleted");
                    return Ok(());
                }
            }

            // Through the daemon when one is holding it: it owns the lock, and
            // deleting the files under an open writer is how half a store is
            // left behind.
            let dirs = semlith::home::all_dirs(&cli.store, &cwd).unwrap_or_default();
            let through_daemon = match semlith::proxy::find(&dirs) {
                Some(upstream) => upstream.delete_store(&store).is_ok(),
                None => false,
            };
            if !through_daemon {
                semlith::home::delete_store(&store)?;
            }
            eprintln!("deleted {store} ({})", dir.display());
            eprintln!("the files it indexed are untouched");
        }

        Command::Start {
            paths,
            no_ledger,
            port,
            debounce,
            airgap,
            no_mcp_http,
        } => {
            arm_airgap(airgap);
            let dirs = semlith::daemon::stores_to_open(&cli.store, &paths, &cwd)?;
            if dirs.is_empty() {
                // Not an error: the portal's welcome screen exists for exactly
                // this, and telling someone to go index something first is what
                // the screen does better than a bail! does.
                eprintln!("semlith: no store registered yet — the portal will offer to make one");
            }
            semlith::daemon::run(
                &dirs,
                semlith::daemon::port_of(port),
                std::time::Duration::from_millis(debounce),
                semlith::embed::airgap(),
                !no_ledger && semlith::ledger::enabled(),
                !no_mcp_http,
                |line| eprintln!("semlith: {line}"),
            )?;
        }

        Command::Key { what } => match what {
            KeyCommand::Show { quiet } => {
                let key = semlith::home::agent_key()?;
                if quiet {
                    println!("{key}");
                } else {
                    let port = semlith::daemon::port_of(None);
                    println!("{}{key}{}", bold(), reset());
                    println!("{}", semlith::home::agent_key_path()?.display());
                    println!();
                    println!("It authenticates the MCP endpoint and nothing else, and it does not");
                    println!("change when the daemon restarts or the portal's token is rotated.");
                    for stanza in semlith::clients::http_stanzas(&key) {
                        println!();
                        println!("{}{}{}", bold(), stanza.format, reset());
                        print!("{}", stanza.text);
                    }
                    println!();
                    println!("Endpoint: http://127.0.0.1:{port}/mcp");
                }
            }
            KeyCommand::Rotate { now } => {
                // Read before it is replaced: it is what identifies the
                // stanzas to rewrite.
                let previous = semlith::home::agent_key().unwrap_or_default();
                let fresh = semlith::home::rotate_agent_key()?;
                let carried = semlith::setup::recarry_key(&previous, &fresh);
                let port = semlith::daemon::port_of(None);
                let url = format!("http://127.0.0.1:{port}/mcp");

                // A running daemon holds the key in memory, so it is told
                // rather than left serving only the key it started with.
                let dirs = semlith::home::all_dirs(&cli.store, &cwd).unwrap_or_default();
                let reached = match semlith::proxy::find(&dirs) {
                    Some(upstream) => upstream.adopt_key(&fresh, now).is_ok(),
                    None => false,
                };

                println!("{}{fresh}{}", bold(), reset());
                if reached {
                    if now {
                        println!("The running daemon took it up; the previous key is refused now.");
                    } else {
                        println!(
                            "The running daemon took it up. The previous key keeps working until \
                             that daemon exits, so a session already open finishes."
                        );
                    }
                } else {
                    println!(
                        "No daemon is running here; the next `semlith start` reads the new key."
                    );
                }

                // Claude Code is the one client semlith writes a config for,
                // because it has a CLI for it. Everything else is named.
                if semlith::setup::claude_present() {
                    if semlith::setup::register_claude_http(&url) {
                        println!(
                            "Claude Code was re-registered against {url}, naming \
                             ${{{}}} rather than the key itself, so this is the last \
                             rotation that needed it touched.",
                            semlith::setup::KEY_ENV
                        );
                    } else {
                        println!(
                            "Claude Code is installed but `claude mcp add` failed; paste the stanza below."
                        );
                    }
                }
                if carried.is_empty() {
                    println!("No configuration file on this machine carried the old key.");
                } else {
                    println!();
                    println!("Carried the new key into:");
                    for path in &carried {
                        println!("  {}", path.display());
                    }
                }

                println!();
                println!("Any client configured somewhere else needs the stanza below pasted in.");
                for stanza in semlith::clients::http_stanzas(&fresh) {
                    println!();
                    print!("{}", stanza.text);
                }
            }
        },

        Command::Trust { store_dir, list } => {
            let mut registry = home::Registry::load()?;
            if list || store_dir.is_none() {
                if registry.trusted.is_empty() {
                    eprintln!(
                        "no store outside {} is trusted. Every store semlith made is \
                         opened without asking; a `.semlith` that arrived some other \
                         way needs `semlith trust <dir>` once.",
                        home::home_or_error()?.display()
                    );
                } else {
                    for dir in &registry.trusted {
                        let missing = if dir.join("store.db").exists() {
                            ""
                        } else {
                            "  (gone)"
                        };
                        println!("{}{missing}", dir.display());
                    }
                }
                return Ok(());
            }
            let dir = registry.trust(store_dir.as_deref().expect("checked above"))?;
            eprintln!(
                "{} is trusted. semlith will open it from this directory without \
                 --store; `semlith adopt` moves it into {} if you would rather it \
                 lived with the others.",
                dir.display(),
                home::stores_root()?.display()
            );
        }

        Command::Adopt {
            store_dir,
            root,
            name,
        } => {
            // `--root` with a store that is already registered is the
            // re-point: the corpus moved, the store did not.
            let registered = home::Registry::load()?
                .name_of(&store_dir)
                .map(str::to_string)
                .or_else(|| {
                    name.as_deref()
                        .filter(|n| home::Registry::load().is_ok_and(|r| r.stores.contains_key(*n)))
                        .map(str::to_string)
                });
            match (registered, &root) {
                (Some(name), Some(root)) => {
                    home::repoint(&name, root)?;
                    eprintln!("{name} now indexes {}", root.display());
                }
                _ => {
                    let (name, target) = home::adopt(&store_dir, root.as_deref(), name.as_deref())?;
                    let store = Semlith::open_existing(&target)?;
                    let (files, chunks, bytes) = store.stats()?;
                    eprintln!(
                        "adopted {} as {name} — {files} files, {chunks} chunks, {} at {}",
                        store_dir.display(),
                        semlith::human_bytes(bytes),
                        target.display(),
                    );
                }
            }
        }

        Command::Mcp => {
            // Every registered store, so a client stanza is `semlith mcp` and
            // nothing else.
            let dirs = semlith::home::all_dirs(&cli.store, &cwd)?;

            // A daemon is the writer for every store it opened, so an agent
            // that opened the store itself could not index while a portal was
            // open. Forwarding removes that: the daemon answers, and it is the
            // one process allowed to write.
            if let Some(upstream) = semlith::proxy::find(&semlith::proxy::candidates(&dirs)) {
                eprintln!(
                    "semlith {}: forwarding to the daemon on 127.0.0.1:{} (found via {})",
                    env!("CARGO_PKG_VERSION"),
                    upstream.port,
                    upstream.via.display(),
                );
                return semlith::proxy::serve(
                    &upstream,
                    std::io::stdin().lock(),
                    std::io::stdout().lock(),
                );
            }

            let mut fleet = read_fleet(&cli.store, &cwd, true)?;
            // Load each distinct model before the first tool call so an agent
            // does not sit through a cold start mid-conversation.
            fleet.quiet = true;
            fleet.warm()?;
            // stdout is the protocol, so this goes to stderr — which a stdio
            // client captures. A server opened on the wrong store answers
            // every question with nothing, and this is the only place that is
            // visible before a query comes back empty.
            eprintln!(
                "semlith {}: serving {} on {}",
                env!("CARGO_PKG_VERSION"),
                match fleet.len() {
                    1 => "1 store".to_string(),
                    n => format!("{n} stores"),
                },
                fleet.labels().join(", "),
            );
            semlith::mcp::serve(
                &mut fleet,
                std::io::stdin().lock(),
                std::io::stdout().lock(),
            )?;
        }
    }

    Ok(())
}

/// Turn `--airgap` into the environment variable the loader reads.
///
/// One switch rather than a flag threaded through `Semlith`, `Fleet` and the
/// daemon: the check lives at the single place weights are fetched, and this is
/// how the flag reaches it. Called before any thread starts, which is what
/// makes the `set_var` safe.
fn arm_airgap(on: bool) {
    if on {
        unsafe { std::env::set_var(semlith::embed::AIRGAP_ENV, "1") };
    }
}

/// The stores a read-only command opens.
///
/// `all` is what `mcp` asks for: every registered store, because a client
/// stanza cannot know which directory the agent will be started in. Everything
/// else asks about the store covering the working directory.
fn read_fleet(flags: &[PathBuf], cwd: &Path, all: bool) -> Result<Fleet> {
    let dirs = if all {
        home::all_dirs(flags, cwd)?
    } else {
        home::read_dirs(flags, cwd)?
    };
    if dirs.is_empty() {
        bail!(
            "no semlith store covers {} and none is registered — \
             run `semlith index` in a directory to make one, \
             or `semlith adopt ./.semlith` to move an existing one into {}",
            cwd.display(),
            semlith::home::stores_root()?.display(),
        );
    }
    Fleet::open(&dirs)
}

/// Paths are stored absolute; show them relative to the cwd when possible,
/// which is both shorter and directly usable as an editor target.
/// How often an index run says where it has got to.
const PROGRESS_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);

/// Where the run is, how fast it is going, and how much longer it has.
///
/// The estimate is the rate so far applied to the files not yet reached, which
/// is wrong whenever the rest of the corpus does not look like the part already
/// walked — so it is printed as an approximation and never as a countdown. A
/// wrong estimate is still worth far more than a silent hour.
fn predict(p: semlith::IndexProgress, elapsed: std::time::Duration) -> String {
    let secs = elapsed.as_secs_f32().max(0.001);
    let rate = p.chunks as f32 / secs;
    let left = p.total.saturating_sub(p.scanned);
    let per_file = secs / p.scanned.max(1) as f32;
    format!(
        "{}/{} files, {} chunks, {rate:.0} chunks/s, ~{} left",
        p.scanned,
        p.total,
        p.chunks,
        human_duration(left as f32 * per_file),
    )
}

fn human_duration(secs: f32) -> String {
    if secs >= 3600.0 {
        format!("{:.1}h", secs / 3600.0)
    } else if secs >= 60.0 {
        format!("{:.0}m", secs / 60.0)
    } else {
        format!("{secs:.0}s")
    }
}

/// The store `semlith add` writes to, when nothing covers the current
/// directory.
///
/// `index` is free to create a store named after wherever it is run, because
/// that directory is the thing being indexed. `add` is not: the URL is what is
/// being added, and the shell's current directory has nothing to do with it. So
/// a `New` choice here would silently create a store named after a directory
/// the user never mentioned — and, because the root recorded is the store's own
/// downloads folder, the next `add` from the same place would not find it and
/// would create another one beside it. Running `semlith add` twice from `/tmp`
/// produced stores called `tmp` and `tmp-2`, neither of which anyone asked for.
///
/// With exactly one store in the home, that is plainly the one meant. With
/// several, or none, say so rather than guess.
fn resolve_for_add(
    choice: home::Choice,
    flags: &[PathBuf],
    name: Option<&str>,
) -> Result<home::Choice> {
    // An explicit --store or --name is the user saying which, so it stands.
    if !matches!(choice, home::Choice::New { .. }) || !flags.is_empty() || name.is_some() {
        return Ok(choice);
    }

    let registry = home::Registry::load()?;
    let mut names = registry.stores.keys();
    match (names.next(), names.next()) {
        (Some(only), None) => {
            let only = only.clone();
            Ok(home::Choice::Registered {
                dir: home::Registry::dir_of(&only)?,
                name: only,
            })
        }
        (None, _) => bail!(
            "there is no store to add to yet — run `semlith index <path>` first, \
             or give this one a name with `semlith add <url> --name <store>`"
        ),
        _ => bail!(
            "nothing indexes this directory, and there are {} stores to choose from: {}. \
             Name one with `--store <dir>` or `--name <store>`, or run this from a \
             directory one of them covers",
            registry.stores.len(),
            registry
                .stores
                .keys()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

/// What the ledger calls a retrieval made from the command line.
///
/// One session per invocation is the truth of it: the process starts, asks one
/// thing and exits. Pretending otherwise would make a session count that means
/// nothing.
const CLI_LEDGER: semlith::ledger::Who<'static> = semlith::ledger::Who {
    client: "cli",
    session: "cli",
};

/// Exit quietly when whoever was reading our output goes away.
///
/// `semlith files | head` is the most ordinary thing anyone types, and it
/// printed a panic and a non-zero status (#75). Two halves, because the
/// mechanism differs:
///
/// On unix the Rust runtime sets `SIGPIPE` to `SIG_IGN` before `main`, so the
/// write returns `EPIPE` and `println!` panics on it. Restoring the default
/// makes the process end the way `cat` and `grep` do, and a shell reports the
/// pipeline's status, which is the reader's.
///
/// On Windows there is no `SIGPIPE`: the write fails with `BrokenPipe` and
/// reaches the same panic. The hook turns that one panic — and only that one —
/// into a silent exit 0, which is what the reader closing the pipe means.
fn quiet_on_a_closed_pipe() {
    #[cfg(unix)]
    {
        // SAFETY: called once, at the top of `main`, before any thread is
        // spawned and before anything has been printed. `SIG_DFL` is what the
        // process would have had if the Rust runtime had not changed it.
        unsafe {
            libc::signal(libc::SIGPIPE, libc::SIG_DFL);
        }
    }

    let inherited = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let said = info
            .payload()
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| info.payload().downcast_ref::<&str>().copied())
            .unwrap_or_default();
        // The message `std` builds for a failed `print!`, with the OS error
        // spelled differently on each platform — matching the kind rather than
        // the wording is not possible from here, because the error is already
        // formatted into the panic payload.
        let printing = said.starts_with("failed printing to std");
        if printing && (said.contains("Broken pipe") || said.contains("pipe")) {
            std::process::exit(0);
        }
        inherited(info);
    }));
}

/// What a forget of a path no store holds says, on stderr, before exiting 1.
///
/// One sentence rather than a suggestion: the path is either a typo or already
/// gone, and semlith cannot tell which.
fn not_indexed(path: &std::path::Path) -> String {
    format!("nothing to forget: {} is not indexed", path.display())
}

fn display(path: &std::path::Path) -> String {
    // Both sides canonicalised, or neither matches on Windows: the file comes
    // back from `canonicalize` in the verbatim form and the working directory
    // does not, so `strip_prefix` never fired and every hit printed absolute —
    // in a form nothing can open (#74).
    let cwd = semlith::canonical(&std::env::current_dir().unwrap_or_default());
    let real = semlith::canonical(path);
    let shown = real.strip_prefix(&cwd).unwrap_or(&real);
    semlith::plain(&shown.display().to_string())
}

fn bold() -> &'static str {
    if std::io::stdout().is_terminal() {
        "\x1b[1m"
    } else {
        ""
    }
}

fn reset() -> &'static str {
    if std::io::stdout().is_terminal() {
        "\x1b[0m"
    } else {
        ""
    }
}

/// The message for a name the graph has never heard of.
///
/// A store with an empty graph and a store that simply does not contain the
/// symbol are different facts, and only one of them means "run index". Saying
/// "not found" for both is how someone concludes the feature is broken.
/// What to say when the graph has nothing to show for a name.
///
/// Only reached when there is genuinely nothing — no caller, no callee, and
/// nothing hidden. A symbol whose every target lies outside the corpus has
/// something to say and used to be reported here as though it did not exist,
/// which is the confusion between "semlith shows no callees" and "everything
/// this calls is outside the index" that the hidden count exists to end.
fn nothing_known(fleet: &semlith::fleet::Fleet, name: &str) -> String {
    let symbols: i64 = fleet
        .each()
        .map(|(_, store)| {
            semlith::store::graph_stats(store.db())
                .map(|(s, _)| s)
                .unwrap_or(0)
        })
        .sum();
    if symbols == 0 {
        format!(
            "no symbols in this store yet. The graph is built as files are indexed, \
             so run `semlith index` once (or leave `semlith start` running) and \
             {name} will be there if the corpus defines it."
        )
    } else {
        format!("no symbol named {name} in the graph")
    }
}

/// `[store] ` when several stores are open, and nothing when one is.
fn store_prefix(store: &Option<String>) -> String {
    match store {
        Some(label) => format!("[{label}] "),
        None => String::new(),
    }
}

fn print_ends(out: &mut impl Write, heading: &str, ends: &[semlith::store::EdgeEnd]) -> Result<()> {
    writeln!(out, "{}{heading}{} ({})", bold(), reset(), ends.len())?;
    if ends.is_empty() {
        writeln!(out, "  none")?;
        return Ok(());
    }
    for end in ends {
        // A collapsed row stands for every definition of the name, so it says
        // how many rather than pointing at whichever one came back first —
        // which would read as a fact about where the call goes.
        if end.confidence == semlith::graph::AMBIGUOUS {
            writeln!(
                out,
                "  {} via {} ({}) · {} definitions{}",
                end.symbol.name,
                end.kind,
                end.confidence,
                end.definitions,
                semlith::graph::call_site(end, &|p| display(std::path::Path::new(p))),
            )?;
            continue;
        }
        writeln!(
            out,
            "  {} via {} ({})  {}{}:{}{}",
            end.symbol.name,
            end.kind,
            end.confidence,
            store_prefix(&end.symbol.store),
            display(std::path::Path::new(&end.symbol.path)),
            end.symbol.start_line,
            semlith::graph::call_site(end, &|p| display(std::path::Path::new(p))),
        )?;
    }
    Ok(())
}

/// A unix second as a local clock time, for the ledger's rows.
fn human_time(at: i64) -> String {
    let secs = at.max(0) as u64;
    let day = secs / 86_400;
    let rest = secs % 86_400;
    format!(
        "{:02}:{:02}:{:02} d{day}",
        rest / 3600,
        (rest % 3600) / 60,
        rest % 60
    )
}