semlith 0.44.0

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
//! `semlith setup`: the far half of the install one-liner.
//!
//! The script's job ends when a binary is on disk. Everything between that and
//! a working semlith — a `PATH` that finds it, weights already fetched so the
//! first `index` is not a silent four-minute wait, and an agent that knows the
//! MCP server exists — is here.
//!
//! Every step is idempotent and reports "already done" rather than doing it
//! again, which is what makes this the repair command as well as the install
//! one. [`status`] computes the same per-step answers without changing
//! anything; the portal's `/api/setup` route is that function and nothing else,
//! so the page and the terminal cannot disagree about what is set up.
//!
//! Nothing here writes outside the semlith home, the shell's rc file and the
//! model cache, and nothing here uses `sudo`.

use anyhow::{Context, Result, bail};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::{chunk, clients, embed, home, model_cache_dir};

/// The fences around the block this command owns in a shell rc file. They are
/// what make a second run an update instead of an append: the block between
/// them is replaced, and anything outside them is never touched.
const BEGIN: &str = "# >>> semlith >>>";
const END: &str = "# <<< semlith <<<";

/// What one step found or did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum State {
    /// The step ran and changed something.
    Done,
    /// The step had nothing to do.
    AlreadyDone,
    /// The step was deliberately not run — `--airgap`, or a client the user
    /// did not pick.
    Skipped,
    /// The step could not finish. Never fatal on its own: a client's CLI
    /// refusing is not a reason to abandon an otherwise good install.
    Failed,
}

/// One line of the report, in the terminal and in the portal alike.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Step {
    pub name: &'static str,
    pub state: State,
    /// One line a human can act on: a path, a version, a reason.
    pub detail: String,
}

/// Everything `semlith setup` knows, computed without touching anything.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Status {
    pub bin_dir: String,
    pub binary_installed: bool,
    pub on_path: bool,
    pub rc_file: Option<String>,
    pub rc_block_present: bool,
    pub model_cache: String,
    pub model_cached: bool,
    /// Whether the cross-encoder the rescoring stage needs is in the cache.
    /// Absent means searches rank by fusion alone, which is a different
    /// product from the one the release measured.
    pub rerank_cached: bool,
    /// The clients whose own configuration file names semlith, read from disk
    /// rather than by asking each client's CLI.
    pub registered_clients: Vec<String>,
    pub version: &'static str,
    /// The install one-liners, so the portal shows the text the README
    /// documents rather than a second copy that can drift.
    pub install_sh: &'static str,
    pub install_ps1: &'static str,
    pub steps: Vec<Step>,
}

/// The macOS and Linux one-liner. The URL resolves at run time, which is what
/// lets a fix to the script reach people without a release.
/// Set to `1` to skip installing the daemon as a login service.
///
/// Read by `semlith setup` itself as well as by the two install scripts, so it
/// works whichever of them a provisioning script reaches for.
pub const NO_SERVICE_ENV: &str = "SEMLITH_NO_SERVICE";

pub const INSTALL_SH: &str = "curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/semlith/semlith/main/install.sh | sh";

/// The Windows one-liner.
pub const INSTALL_PS1: &str =
    "irm https://raw.githubusercontent.com/semlith/semlith/main/install.ps1 | iex";

/// Read-only. Every field is a question the portal asks and `run` answers.
pub fn status() -> Status {
    // The one place in this file that cannot return an error: the portal asks
    // for a status and gets one. An unresolvable home makes every step report
    // what it could not find, rather than reporting a path semlith made up.
    let bin = home::bin_dir();
    let bin_path = bin.as_deref().unwrap_or(Path::new(""));
    let rc = rc_file();
    let block = rc
        .as_deref()
        .and_then(|p| std::fs::read_to_string(p).ok())
        .map(|text| text.contains(BEGIN))
        .unwrap_or(false);
    // A cache that cannot be resolved is a cache with nothing in it, which is
    // what the model step already reports.
    let cache = model_cache_dir().unwrap_or_default();

    // Read from each client's own configuration file rather than by asking
    // each client's CLI. This used to run `claude mcp list` and wait for it,
    // which on a slow machine turned the portal's Agents page into a
    // twenty-second hang — and that was for one client. A process per client
    // would be that many times over, on a route the page calls on every load.
    let registered = crate::clientfile::registered_clients();
    let installed = bin.is_ok() && bin_path.join(exe_name()).exists();
    let path_has_bin = bin.is_ok() && on_path(bin_path);
    let model_cached = embed::is_cached(&cache);
    let rerank_cached = crate::rerank::cached(&cache);

    let steps = vec![
        Step {
            name: "binary",
            state: if installed {
                State::AlreadyDone
            } else {
                State::Skipped
            },
            detail: match &bin {
                Ok(dir) => dir.join(exe_name()).display().to_string(),
                Err(e) => e.to_string(),
            },
        },
        Step {
            name: "path",
            // The rc file counts. A daemon started from a shell that predates
            // the edit has the old `PATH` for as long as it runs, so asking
            // only `on_path` reported "not done" immediately after the portal
            // had just written the block — and the button looked broken.
            state: if path_has_bin || block {
                State::AlreadyDone
            } else {
                State::Skipped
            },
            detail: match (&rc, path_has_bin, block) {
                (Some(p), false, true) => {
                    format!("{} — a new shell picks it up", p.display())
                }
                (Some(p), _, _) => p.display().to_string(),
                (None, _, _) => "no shell rc file found".into(),
            },
        },
        Step {
            name: "model",
            state: if model_cached {
                State::AlreadyDone
            } else {
                State::Skipped
            },
            // Both models, because one of them being absent is the difference
            // between the answers this machine gives and the answers the
            // release measured.
            detail: format!(
                "{} — rescoring model {}",
                cache.display(),
                if rerank_cached { "present" } else { "absent" }
            ),
        },
        Step {
            name: "agents",
            state: if registered.is_empty() {
                State::Skipped
            } else {
                State::AlreadyDone
            },
            detail: if registered.is_empty() {
                "no client on this machine has the semlith server".into()
            } else {
                format!("{} has the semlith server", registered.join(", "))
            },
        },
    ];

    Status {
        bin_dir: bin_path.display().to_string(),
        binary_installed: installed,
        on_path: path_has_bin,
        rc_file: rc.map(|p| p.display().to_string()),
        rc_block_present: block,
        model_cache: cache.display().to_string(),
        model_cached,
        rerank_cached,
        registered_clients: registered,
        version: env!("CARGO_PKG_VERSION"),
        install_sh: INSTALL_SH,
        install_ps1: INSTALL_PS1,
        steps,
    }
}

/// The guided flow. `yes` takes the default at every prompt — add to `PATH`,
/// download the model — so a script or an agent can install semlith with
/// nothing attached to stdin.
///
/// Registration is not one of those prompts from 0.18.0. It runs either way,
/// because an install that leaves the agent unable to see the store is not an
/// install anybody wanted, and because every registration is now the stdio
/// form: no key lands in a file, and nothing outside the client's own registry
/// is touched. `register_all` is the one part that does ask, and it asks with
/// the list of files in front of the user.
#[allow(clippy::too_many_arguments)]
pub fn run(
    yes: bool,
    airgap: bool,
    register_all: bool,
    service: bool,
    hooks: bool,
    mode: crate::hook::Mode,
    agents: bool,
    file_managers: Option<bool>,
) -> Result<()> {
    let _ = cliclack::intro(format!(" semlith {} setup ", env!("CARGO_PKG_VERSION")));

    // Reported as they run rather than replayed at the end, so the line about
    // a step is next to whatever that step printed.
    let report = [
        announce(step_binary(yes)?),
        announce(step_path(yes)?),
        announce(step_model(yes, airgap)?),
        announce(step_neural_engine(yes, airgap)?),
        announce(step_agents(register_all, yes)?),
        announce(step_leftovers()),
        announce(step_always_load()?),
        announce(step_skill()?),
        announce(step_explorer(agents)?),
        announce(step_file_managers(file_managers, yes)?),
        announce(step_hooks(hooks, mode)?),
        announce(step_rules(register_all)?),
        announce(step_service(service)?),
        announce(step_verify()?),
    ];

    if report.iter().all(|s| s.state != State::Done) {
        let _ = cliclack::log::success("Everything was already set up. Nothing changed.");
    }

    let _ = cliclack::outro(format!(
        "Next: `semlith index .` to index this directory, then `semlith start` \
         for the portal on http://127.0.0.1:7365\n  Open a new shell first if \
         {} was only just added to PATH.",
        home::bin_dir()
            .map(|d| d.display().to_string())
            .unwrap_or_else(|e| e.to_string())
    ));
    Ok(())
}

/// One line per step, in the order the steps ran.
fn announce(step: Step) -> Step {
    let line = format!("{}: {}", step.name, step.detail);
    let _ = match step.state {
        State::Done => cliclack::log::success(line),
        State::AlreadyDone => cliclack::log::info(format!("{line} (already done)")),
        State::Skipped => cliclack::log::info(format!("{line} (skipped)")),
        State::Failed => cliclack::log::warning(line),
    };
    step
}

/// Where a shell looks for the binary this release installs.
pub(crate) fn exe_name() -> &'static str {
    if cfg!(windows) {
        "semlith.exe"
    } else {
        "semlith"
    }
}

fn on_path(bin: &Path) -> bool {
    std::env::var_os("PATH")
        .map(|paths| std::env::split_paths(&paths).any(|p| p == bin))
        .unwrap_or(false)
}

/// Step 1. The scripts put the binary here themselves; this covers the person
/// who downloaded an archive by hand and then ran `semlith setup` out of it.
fn step_binary(yes: bool) -> Result<Step> {
    let bin = home::bin_dir()?;
    let target = bin.join(exe_name());
    let running = std::env::current_exe().context("locating the running binary")?;

    if running == target || target.exists() {
        return Ok(Step {
            name: "binary",
            state: State::AlreadyDone,
            detail: target.display().to_string(),
        });
    }

    let copy = yes
        || cliclack::confirm(format!("Copy this binary into {}?", bin.display()))
            .initial_value(true)
            .interact()
            .unwrap_or(false);
    if !copy {
        return Ok(Step {
            name: "binary",
            state: State::Skipped,
            detail: format!("left at {}", running.display()),
        });
    }

    home::secure_dir(&bin).with_context(|| format!("creating {}", bin.display()))?;
    std::fs::copy(&running, &target)
        .with_context(|| format!("copying {} to {}", running.display(), target.display()))?;
    Ok(Step {
        name: "binary",
        state: State::Done,
        detail: target.display().to_string(),
    })
}

/// The rc file of `$SHELL`. `.profile` is the fallback rather than nothing,
/// because a login shell reads it and an unknown shell is still a shell.
///
/// `SHELL` unset is the case that matters: a container, a CI runner and a cron
/// job all have a HOME and no `SHELL`, and returning `None` there left the
/// binary off `PATH` after an otherwise perfect install. Only a missing HOME
/// means there is genuinely nowhere to write.
fn rc_file() -> Option<PathBuf> {
    let base = home::user_home().ok()?;
    let shell = std::env::var("SHELL").unwrap_or_default();
    let name = Path::new(&shell)
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
    Some(match name.as_str() {
        "zsh" => base.join(".zshrc"),
        "fish" => base.join(".config").join("fish").join("config.fish"),
        "bash" => {
            let rc = base.join(".bashrc");
            if rc.exists() {
                rc
            } else {
                base.join(".bash_profile")
            }
        }
        _ => base.join(".profile"),
    })
}

/// Step 2. The block is appended at the end and *prepends* the bin directory,
/// so the binary this install put there wins over an older one somebody
/// dropped in `/usr/local/bin` and forgot.
/// Run the PATH step on its own, non-interactively.
///
/// The portal's setup panel reports this step as not done and then tells the
/// reader to go and run a command; a panel that can see the problem can fix it.
/// `yes` is forced, because a button press is the confirmation.
pub fn run_path_step() -> Result<Step> {
    step_path(true)
}

fn step_path(yes: bool) -> Result<Step> {
    let bin = home::bin_dir()?;
    if on_path(&bin) {
        return Ok(Step {
            name: "path",
            state: State::AlreadyDone,
            detail: bin.display().to_string(),
        });
    }

    if cfg!(windows) {
        return step_path_windows(&bin, yes);
    }

    let Some(rc) = rc_file() else {
        return Ok(Step {
            name: "path",
            state: State::Failed,
            detail: format!(
                "no HOME, so no rc file to edit — add {} to PATH by hand",
                bin.display()
            ),
        });
    };

    let existing = std::fs::read_to_string(&rc).unwrap_or_default();

    // A block that is already there is replaced when it is not the block this
    // version writes, rather than left because something with the right fences
    // exists. Until 0.18.0 this returned here on sight of `BEGIN`, so a user
    // upgrading kept whatever an older version had written for ever — and what
    // 0.17.3 wrote was an export of `SEMLITH_AGENT_KEY`, a credential placed in
    // the environment of every process they start, which nothing reads any more.
    //
    // Found by the clean-container check between the tag and the publish, on a
    // release whose whole subject is that no file semlith writes carries the key.
    if existing.contains(BEGIN) {
        let wanted = path_line(&bin)?;
        let current = block_body(&existing);
        if current.as_deref() == Some(wanted.as_str()) {
            return Ok(Step {
                name: "path",
                state: State::AlreadyDone,
                detail: format!("{} already has the semlith block", rc.display()),
            });
        }
        let dropped_key = current
            .as_deref()
            .is_some_and(|body| body.contains(KEY_ENV));
        replace_block(&rc, &existing, &wanted)?;
        return Ok(Step {
            name: "path",
            state: State::Done,
            detail: if dropped_key {
                format!(
                    "{} — replaced the block an older version wrote, which exported {KEY_ENV}. \
                     Nothing reads it now: a registered client launches `semlith mcp`, which reads \
                     the key from the file itself. Open a new shell to be rid of it.",
                    rc.display()
                )
            } else {
                format!(
                    "{} — replaced the block an older version wrote",
                    rc.display()
                )
            },
        });
    }

    let add = yes
        || cliclack::confirm(format!(
            "Add {} to PATH in {}?",
            bin.display(),
            rc.display()
        ))
        .initial_value(true)
        .interact()
        .unwrap_or(false);
    if !add {
        return Ok(Step {
            name: "path",
            state: State::Skipped,
            detail: format!("add {} to PATH by hand", bin.display()),
        });
    }

    // Built before the file is touched, so a home that cannot be written into a
    // shell file leaves the rc exactly as it was rather than half-edited.
    let line = path_line(&bin)?;

    if let Some(parent) = rc.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&rc)
        .with_context(|| format!("opening {}", rc.display()))?;
    let sep = if existing.is_empty() || existing.ends_with('\n') {
        ""
    } else {
        "\n"
    };
    write!(file, "{sep}\n{}\n{}\n{END}\n", BEGIN, line)
        .with_context(|| format!("writing {}", rc.display()))?;

    Ok(Step {
        name: "path",
        state: State::Done,
        detail: rc.display().to_string(),
    })
}

/// fish is not POSIX and `export` is a syntax error in it.
/// What sits between the fences, or `None` when the file has no closing one.
///
/// Trimmed of the newlines the fences are written with, so it compares equal to
/// what [`path_line`] returns.
fn block_body(text: &str) -> Option<String> {
    let start = text.find(BEGIN)? + BEGIN.len();
    let end = text[start..].find(END)? + start;
    Some(text[start..end].trim_matches('\n').to_string())
}

/// Replace what is between the fences, leaving every byte outside them alone.
///
/// Through a neighbouring temporary file and a rename: a half-written rc file
/// is a shell that will not start, and this is somebody's login shell.
fn replace_block(rc: &Path, existing: &str, line: &str) -> Result<()> {
    let start = existing
        .find(BEGIN)
        .context("the block's opening fence went missing between reading and writing")?;
    let end = existing[start..]
        .find(END)
        .map(|at| start + at + END.len())
        .context("the semlith block has an opening fence and no closing one; fix it by hand")?;
    let next = format!(
        "{}{BEGIN}\n{line}\n{END}{}",
        &existing[..start],
        &existing[end..]
    );

    crate::clientfile::rewrite(rc, &next)
}

fn path_line(bin: &Path) -> Result<String> {
    let path = bin.display().to_string();
    // A newline would end the line and start another one, which is a second
    // command in a file the shell runs at every start. There is no quoting that
    // survives it, so a store home containing one is refused rather than
    // written. A NUL cannot reach a shell at all.
    if path.contains('\n') || path.contains('\r') || path.contains('\0') {
        bail!(
            "{} contains a newline, so it cannot be written into a shell startup \
             file. Point {} at a directory whose name is one line and run \
             `semlith setup` again.",
            path.escape_debug(),
            home::HOME_ENV
        );
    }

    let is_fish = std::env::var("SHELL")
        .map(|s| s.ends_with("fish"))
        .unwrap_or(false);

    // One line: the bin directory on `PATH`.
    //
    // There used to be a second, exporting `SEMLITH_AGENT_KEY` by reading the
    // key file at every shell start, because every client stanza named the
    // variable. From 0.18.0 none of them does — a registration semlith writes
    // launches `semlith mcp`, which reads the key out of the file itself — so
    // the export is a credential placed in the environment of every process the
    // user starts, in exchange for nothing. A user who pastes one of the HTTP
    // stanzas by hand can export it themselves, and `docs/clients.md` says so.
    //
    // A block written by an earlier version still holds the export. `step_path`
    // replaces the whole block between its fences on every run, so running
    // `semlith setup` once removes it.
    Ok(if is_fish {
        format!("set -gx PATH {} $PATH", fish_quote(&path))
    } else {
        format!("export PATH={}:$PATH", posix_quote(&path))
    })
}

/// A POSIX shell word that is exactly this string.
///
/// Single quotes, because inside them every character is itself — no variable
/// expansion, no command substitution, no backslash escapes. The one character
/// that cannot appear inside them is a single quote, which is closed, escaped
/// and reopened in the usual way. It was double quotes before 0.14.0, which
/// expand `$(…)`, backticks and `$VAR`, so a directory name could run a command
/// on every shell start.
pub(crate) fn posix_quote(raw: &str) -> String {
    format!("'{}'", raw.replace('\'', r"'\''"))
}

/// The same for fish, which has no `'\''` idiom: inside single quotes it
/// recognises `\'` and `\\` and nothing else.
fn fish_quote(raw: &str) -> String {
    format!("'{}'", raw.replace('\\', r"\\").replace('\'', r"\'"))
}

/// A PowerShell single-quoted string. Inside them the only special characters
/// are the quotes, each written twice — and PowerShell takes the typographic
/// single quotes U+2018-U+201B as quotes too, so a name holding one ended the
/// string early (audit S17).
pub(crate) fn powershell_quote(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len() + 2);
    out.push('\'');
    for c in raw.chars() {
        if matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}') {
            out.push(c);
        }
        out.push(c);
    }
    out.push('\'');
    out
}

/// Windows has no rc file; the user `PATH` is a registry value, and PowerShell
/// is the supported way to set one. `-NoProfile` keeps a user's own profile
/// from changing what this does, and `Bypass` covers the default
/// execution policy refusing to run anything at all.
fn step_path_windows(bin: &Path, yes: bool) -> Result<Step> {
    let add = yes
        || cliclack::confirm(format!("Add {} to your user PATH?", bin.display()))
            .initial_value(true)
            .interact()
            .unwrap_or(false);
    if !add {
        return Ok(Step {
            name: "path",
            state: State::Skipped,
            detail: format!("add {} to PATH by hand", bin.display()),
        });
    }

    let script = format!(
        "$dir = {}; \
         $cur = [Environment]::GetEnvironmentVariable('Path','User'); \
         if ($cur -notlike \"*$dir*\") {{ \
           [Environment]::SetEnvironmentVariable('Path', \"$dir;$cur\", 'User') }}",
        powershell_quote(&bin.display().to_string())
    );
    let out = Command::new("powershell")
        .args(["-ExecutionPolicy", "Bypass", "-NoProfile", "-Command"])
        .arg(&script)
        .output();

    match out {
        Ok(o) if o.status.success() => Ok(Step {
            name: "path",
            state: State::Done,
            detail: "user PATH".into(),
        }),
        _ => Ok(Step {
            name: "path",
            state: State::Failed,
            detail: format!(
                "could not set the user PATH — add {} through System Properties > \
                 Environment Variables",
                bin.display()
            ),
        }),
    }
}

/// Step 3. The weights are ~52 MB and the first `index` otherwise spends
/// minutes on them with nothing on screen. hf-hub draws the byte progress
/// itself when it is not told to be quiet, so this reuses the loader every
/// other command uses rather than plumbing a second progress path.
fn step_model(yes: bool, airgap: bool) -> Result<Step> {
    let cache = model_cache_dir()?;
    if embed::is_cached(&cache) {
        return Ok(Step {
            name: "model",
            state: State::AlreadyDone,
            detail: cache.display().to_string(),
        });
    }
    if airgap || embed::airgap() {
        return Ok(Step {
            name: "model",
            state: State::Skipped,
            detail: format!("--airgap; pre-seed {}", cache.display()),
        });
    }

    let fetch = yes
        || cliclack::confirm("Download the default embedding model now (~52 MB)?")
            .initial_value(true)
            .interact()
            .unwrap_or(false);
    if !fetch {
        return Ok(Step {
            name: "model",
            state: State::Skipped,
            detail: "the first `semlith index` will fetch it".into(),
        });
    }

    let _ = cliclack::log::step(format!("model: downloading into {}", cache.display()));
    // The model cache is weights, and weights are what every vector in every
    // store is computed by. A cache another account can write to is a model
    // another account chooses.
    home::secure_dir(&cache).with_context(|| format!("creating {}", cache.display()))?;
    match embed::Model::default().load(cache.clone(), chunk::MAX_CHARS / 2, false) {
        Ok(_) => {
            // The rescoring model, in the same step and the same cache.
            //
            // It is fetched here so that it is never fetched inside a query:
            // a search that paused to download 38 MB the first time somebody
            // asked a question would be a worse surprise than a search that
            // ranks by fusion alone, which is what happens when this is
            // absent. A failure here leaves the stage off and says so; it
            // does not fail the step, because the embedding model — the one
            // semlith cannot work without — is already in the cache.
            let _ = cliclack::log::step(format!(
                "model: downloading the rescoring model ({}, ~38 MB)",
                crate::rerank::RERANK_NAME
            ));
            if let Err(e) = crate::rerank::load(&cache, false) {
                let _ = cliclack::log::warning(format!(
                    "the rescoring model did not download: {e}. Searches rank by fusion \
                     alone until `semlith setup` is run again."
                ));
            }
            Ok(Step {
                name: "model",
                state: State::Done,
                detail: cache.display().to_string(),
            })
        }
        Err(e) => Ok(Step {
            name: "model",
            state: State::Failed,
            detail: format!("{e} — `semlith setup` again when the network is back"),
        }),
    }
}

/// Step 3b. On Apple silicon, the Neural Engine's models: granite as Core ML,
/// pinned by digest, fetched here so the lane is ready before the first index
/// rather than a run's worth later. The lane compiles them for this Mac the
/// first time it starts — minutes, once — and a run with no other lane on
/// waits for it; the daemon starts that compilation when it starts.
fn step_neural_engine(yes: bool, airgap: bool) -> Result<Step> {
    let name = "neural engine";
    if let Some(why) = crate::accel::unavailable_here("ane") {
        return Ok(Step {
            name,
            state: State::Skipped,
            detail: why,
        });
    }
    if !crate::accel::enabled().ane {
        return Ok(Step {
            name,
            state: State::Skipped,
            detail: "switched off — `semlith accel on ane` turns it on".into(),
        });
    }
    let cache = model_cache_dir()?;
    let pack = crate::packs::coreml();
    if let Some(dir) = crate::packs::installed(&cache, &pack) {
        return Ok(Step {
            name,
            state: State::AlreadyDone,
            detail: dir.display().to_string(),
        });
    }
    if airgap || embed::airgap() {
        return Ok(Step {
            name,
            state: State::Skipped,
            detail: format!("--airgap; pre-seed {}", pack.dir(&cache).display()),
        });
    }
    let size = crate::human_bytes(pack.bytes() as i64);
    let fetch = yes
        || cliclack::confirm(format!(
            "Download the Neural Engine models ({size})? Indexing on this Mac is several times faster with them."
        ))
        .initial_value(true)
        .interact()
        .unwrap_or(false);
    if !fetch {
        return Ok(Step {
            name,
            state: State::Skipped,
            detail: "`semlith accel on ane` fetches them later".into(),
        });
    }
    let _ = cliclack::log::step(format!("neural engine: downloading {size}"));
    let mut said = 0u8;
    match crate::packs::fetch(&cache, &pack, &mut |percent| {
        if percent >= said.saturating_add(25) {
            said = percent;
            let _ = cliclack::log::step(format!("neural engine: {percent} %"));
        }
    }) {
        Ok(dir) => Ok(Step {
            name,
            state: State::Done,
            detail: format!(
                "{} — the first run compiles them for this Mac, a few minutes once",
                dir.display()
            ),
        }),
        Err(e) => Ok(Step {
            name,
            state: State::Failed,
            detail: format!("{e:#} — `semlith accel on ane` tries again"),
        }),
    }
}

/// Step 4. Every client with a global registration CLI, registered by running
/// it.
///
/// Until 0.18.0 this step registered one client of twenty-seven and printed the
/// other twenty-six as stanzas to paste. Two things were wrong with that and
/// neither announced itself. Of the sixteen stanzas that are a command, exactly
/// one named a scope, so a user pasting any of the other fifteen while sitting
/// in a project registered semlith for that project alone and found it gone
/// from the next one. And every HTTP stanza named `${SEMLITH_AGENT_KEY}`, which
/// only expands if something exported it — so on a machine whose shell startup
/// file did not, or for a client launched from a desktop icon that reads no
/// startup file, the client registered, connected, and failed to authenticate
/// with nothing anywhere saying why.
///
/// Both are gone. Every registration is the stdio form, so there is no header
/// to expand and no key in any file; and every command carries the scope its
/// client spells "every project". A client semlith cannot register globally is
/// named as such rather than registered wrongly and counted as a success.
fn step_agents(register_all: bool, yes: bool) -> Result<Step> {
    let all = clients::clients();
    if all.is_empty() {
        return Ok(Step {
            name: "agents",
            state: State::Skipped,
            detail: "no documented clients".into(),
        });
    }

    let mut wired: Vec<&str> = Vec::new();
    let mut replaced: Vec<String> = Vec::new();
    let mut failed: Vec<(&str, String)> = Vec::new();
    let mut absent = 0usize;
    let mut by_file: Vec<&clients::Client> = Vec::new();
    let mut nowhere: Vec<&str> = Vec::new();

    for client in all {
        match register(client) {
            Registration::Registered { replaced: was } => {
                wired.push(&client.name);
                replaced.extend(was);
            }
            // No CLI, but the client is here and documents its file: VS Code
            // with `code` not on `PATH` (the macOS default), the ChatGPT
            // desktop app with no Codex CLI. The file is the way in.
            Registration::Absent
                if client.config_files().any(|stanza| {
                    crate::clientfile::resolve(stanza)
                        .is_some_and(|path| crate::clientfile::client_present(&path))
                }) =>
            {
                by_file.push(client)
            }
            Registration::Absent => absent += 1,
            Registration::Failed { reason } => failed.push((&client.name, reason)),
            Registration::ProjectScoped => by_file.push(client),
            Registration::Unregisterable => nowhere.push(&client.name),
        }
    }
    // A client with no CLI at all: its file is the only way in, so it joins the
    // `--register-all` set rather than being reported as missing.
    let extra: Vec<&clients::Client> = all
        .iter()
        .filter(|client| client.needs_a_file_written())
        .filter(|client| !by_file.iter().any(|seen| seen.name == client.name))
        .collect();
    by_file.extend(extra);

    let written = if register_all {
        write_client_files(&by_file, yes)?
    } else {
        for client in &by_file {
            print_stanza(client);
        }
        Vec::new()
    };

    for (name, reason) in &failed {
        let client = all.iter().find(|c| &c.name == name);
        let _ = cliclack::log::warning(format!("{name} would not register: {reason}"));
        if let Some(client) = client {
            print_stanza(client);
        }
    }
    for name in &nowhere {
        let _ = cliclack::log::info(format!(
            "{name}: semlith cannot register this one — it documents no file outside a project. \
             Paste the stanza below."
        ));
        if let Some(client) = all.iter().find(|c| &c.name == name) {
            print_stanza(client);
        }
    }
    for was in &replaced {
        let _ = cliclack::log::info(format!("replaced an existing entry: {was}"));
    }

    let mut detail = Vec::new();
    if !wired.is_empty() {
        detail.push(format!("registered {}", wired.join(", ")));
    }
    if !written.is_empty() {
        detail.push(format!(
            "wrote {}",
            written
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }
    if absent > 0 {
        detail.push(format!("{absent} client CLIs are not on this machine"));
    }
    if !by_file.is_empty() && !register_all {
        detail.push(format!(
            "{} need `semlith setup --register-all` or the printed stanza",
            by_file.len()
        ));
    }

    Ok(Step {
        name: "agents",
        state: if wired.is_empty() && written.is_empty() {
            State::Skipped
        } else {
            State::Done
        },
        detail: if detail.is_empty() {
            "no client CLI on this machine; stanzas printed".into()
        } else {
            detail.join("; ")
        },
    })
}

/// Take semlith's own entries back out of clients it no longer supports, once.
///
/// Unconditional and unprompted, because each removal is only what an earlier
/// `semlith setup` put there, each edited file is backed up beside itself, and
/// every removal is listed. A second run finds nothing and says nothing.
fn step_leftovers() -> Step {
    let removed = crate::leftovers::clean();
    for line in &removed {
        let _ = match line.left {
            None => cliclack::log::info(line.to_string()),
            Some(_) => cliclack::log::warning(line.to_string()),
        };
    }
    let done = removed.iter().filter(|r| r.left.is_none()).count();
    Step {
        name: "leftovers",
        state: if done > 0 {
            State::Done
        } else {
            State::AlreadyDone
        },
        detail: if removed.is_empty() {
            "nothing left in unsupported clients".into()
        } else {
            format!(
                "removed {done} semlith entr{} from clients semlith no longer supports; \
                 each file is backed up beside itself as .semlith-backup",
                if done == 1 { "y" } else { "ies" }
            )
        },
    }
}

/// Write the user-level configuration file for every client semlith cannot ask
/// to register itself.
///
/// The paths are listed and confirmed before anything is written, because this
/// is the one place semlith writes a file it does not own. A user who says no
/// gets the stanzas printed, which is what they would have had anyway.
fn write_client_files(clients: &[&clients::Client], yes: bool) -> Result<Vec<PathBuf>> {
    let plans = crate::clientfile::plan(clients);
    if plans.is_empty() {
        return Ok(Vec::new());
    }
    let listing = plans
        .iter()
        .map(|plan| plan.to_string())
        .collect::<Vec<_>>()
        .join("\n");
    let _ = cliclack::note("Files semlith would write", listing);

    // `--yes --register-all` writes without asking. The flag is the asking:
    // a user who typed `--register-all` has already said the one thing this
    // prompt exists to get, and a script with nothing on stdin would otherwise
    // take the default and silently write nothing.
    let go = yes
        || cliclack::confirm("Write these files? Each is backed up beside itself first.")
            .initial_value(false)
            .interact()
            .unwrap_or(false);
    if !go {
        for client in clients {
            print_stanza(client);
        }
        return Ok(Vec::new());
    }

    let stanzas: Vec<(&str, &clients::Stanza)> = clients
        .iter()
        .flat_map(|client| {
            client
                .config_files()
                .map(move |stanza| (client.name.as_str(), stanza))
        })
        .collect();
    let written = crate::clientfile::apply(&plans, &stanzas)?;

    // A refusal is not a failure of the run: the other files are written and
    // the one that could not be is named, with its stanza, so the user can
    // finish it by hand.
    for plan in &plans {
        if let crate::clientfile::Action::Refuse { reason } = &plan.action {
            let _ = cliclack::log::warning(format!(
                "{}: {} was left alone — {reason}",
                plan.client,
                plan.path.display()
            ));
            if let Some(client) = clients.iter().find(|c| c.name == plan.client) {
                print_stanza(client);
            }
        }
    }
    Ok(written)
}

/// Print one client's stanzas for a user to paste.
///
/// The stdio form first, because it is what semlith would have registered and
/// it needs no key. The HTTP form follows for a daemon on another machine,
/// naming `${SEMLITH_AGENT_KEY}` as `docs/clients.md` promises. Until 0.33.0 it
/// carried the live key, which an installer run printed twenty-six times into
/// terminal scrollback and whatever the run was piped into; `semlith key show`
/// is the one command that prints it.
fn print_stanza(client: &clients::Client) {
    let mut body = client
        .stanzas
        .iter()
        .filter(|stanza| !stanza.unregister)
        .map(|stanza| stanza.text.as_str())
        .collect::<Vec<_>>()
        .join("\n\n");
    body.push_str(&http_suffix());
    let _ = cliclack::note(format!("{} — {}", client.name, client.note), body);
}

/// The HTTP stanzas as `print_stanza` appends them, with the placeholder in
/// place of the key.
fn http_suffix() -> String {
    let http = crate::clients::http_stanzas(crate::clients::KEY_PLACEHOLDER);
    if http.is_empty() {
        return String::new();
    }
    format!(
        "\n\nOr over HTTP, against a running `semlith start` (export {KEY_ENV} from \
         `semlith key show` first):\n\n{}",
        http.iter()
            .map(|s| s.text.as_str())
            .collect::<Vec<_>>()
            .join("\n")
    )
}

/// What happened when semlith tried to register one client.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "outcome", rename_all = "kebab-case")]
pub enum Registration {
    /// Registered, naming whatever was replaced to get there.
    Registered { replaced: Vec<String> },
    /// The client's CLI is not on this machine. Not a failure: most people have
    /// two or three of the twelve.
    Absent,
    /// The CLI is here and did not accept the registration. The stanza is
    /// printed instead and the install continues.
    Failed { reason: String },
    /// The CLI registers the directory it is run in, so semlith does not run
    /// it. `--register-all` writes this client's user-level file instead.
    ProjectScoped,
    /// No registration CLI and no documented user-level file. No supported
    /// client is in this state; the arm stays so a documentation change that
    /// puts one here is reported rather than miscounted.
    Unregisterable,
}

/// Register one client by running its own CLI.
///
/// The exit status decides and no output is parsed. That contract was written
/// for `claude mcp add`, whose flags have changed between Claude Code versions,
/// and it holds harder across seven CLIs than it did across one: semlith
/// controls none of them, and a message it matched on today is a message
/// somebody rewords next release.
///
/// Any `unregister` command the client documents runs first, and its status is
/// ignored. That is how an existing entry is replaced rather than added beside:
/// `claude mcp add` refuses a name that is already registered, so an install
/// repairing a stale HTTP registration would otherwise fail on the machine that
/// most needs repairing. A client may document more than one — Claude Code has
/// three, one per scope — because the entry being replaced is often not at the
/// scope the new one goes to. That is the whole of the bug this release exists
/// to fix: an entry under `projects."…".mcpServers` that made semlith invisible
/// from every other directory.
pub fn register(client: &clients::Client) -> Registration {
    if !client.registers_globally() {
        return if client.config_files().next().is_some() {
            Registration::ProjectScoped
        } else {
            Registration::Unregisterable
        };
    }
    let Some(command) = client.register_command() else {
        return Registration::Unregisterable;
    };
    let Some((program, args)) = argv(&command) else {
        return Registration::Failed {
            reason: format!("{command:?} is not a command semlith could read"),
        };
    };

    // Absence is checked by trying, rather than by walking `PATH`: the answer
    // wanted is "can this process run it", and a `PATH` walk gets that wrong
    // for a shell function, an alias and a binary the user cannot execute.
    let mut replaced = Vec::new();
    for undo in client.unregister_commands() {
        let Some((program, args)) = argv(&undo) else {
            continue;
        };
        match Command::new(crate::doctor::program_path(&program))
            .args(&args)
            .output()
        {
            // An exit of zero means there was something there to remove, which
            // is what the user is told. A non-zero exit is the ordinary case of
            // nothing being registered, and says nothing.
            Ok(out) if out.status.success() => replaced.push(undo),
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Registration::Absent;
            }
            Err(_) => {}
        }
    }

    match Command::new(crate::doctor::program_path(&program))
        .args(&args)
        .output()
    {
        Ok(out) if out.status.success() => Registration::Registered { replaced },
        Ok(out) => Registration::Failed {
            reason: first_line(&out.stderr, &out.stdout)
                .unwrap_or_else(|| format!("{program} exited {}", out.status)),
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Registration::Absent,
        Err(e) => Registration::Failed {
            reason: e.to_string(),
        },
    }
}

/// Split a documented command into a program and its arguments, without a
/// shell.
///
/// `sh -c` would be four characters shorter and would hand every one of these
/// strings to a shell that expands `$`, `` ` `` and `~`. The commands come from
/// a document compiled into the binary rather than from a user, so that is not
/// an injection today — but a registration path that evaluates shell
/// metacharacters is one edit away from being one, and one of these commands is
/// a JSON object in single quotes, which a shell would be free to mangle.
///
/// Quotes group; a backslash escapes the character after it outside quotes.
/// `None` for an empty command or an unterminated quote, which is a
/// documentation error rather than something to guess at.
pub fn argv(command: &str) -> Option<(String, Vec<String>)> {
    let mut words: Vec<String> = Vec::new();
    let mut word = String::new();
    let mut started = false;
    let mut quote: Option<char> = None;
    let mut chars = command.chars();
    while let Some(c) = chars.next() {
        match (quote, c) {
            (Some(q), c) if c == q => quote = None,
            (Some(_), c) => word.push(c),
            (None, '\'' | '"') => {
                quote = Some(c);
                started = true;
            }
            (None, '\\') => word.push(chars.next()?),
            (None, c) if c.is_whitespace() => {
                if started || !word.is_empty() {
                    words.push(std::mem::take(&mut word));
                    started = false;
                }
            }
            (None, c) => word.push(c),
        }
    }
    if quote.is_some() {
        return None;
    }
    if started || !word.is_empty() {
        words.push(word);
    }
    let mut words = words.into_iter();
    let program = words.next()?;
    Some((program, words.collect()))
}

/// The first non-empty line a failing CLI printed, for the one-line report.
///
/// Not parsed for meaning — only shown, so the user reads what the client said
/// rather than what semlith guessed it meant.
fn first_line(stderr: &[u8], stdout: &[u8]) -> Option<String> {
    [stderr, stdout]
        .into_iter()
        .flat_map(|bytes| {
            String::from_utf8_lossy(bytes)
                .lines()
                .map(str::trim)
                .filter(|line| !line.is_empty())
                .map(str::to_string)
                .collect::<Vec<_>>()
        })
        .next()
        .map(|line| line.chars().take(200).collect())
}

/// The variable a client's configuration names instead of the key itself.
///
/// Nothing semlith registers names it from 0.18.0 — a registration is the stdio
/// form and `semlith mcp` reads the key out of `~/.semlith/agent.key` itself.
/// It stays because the HTTP stanzas stay: a daemon on another machine, or a
/// client that can only speak HTTP, still needs a header, and a user who pastes
/// one of those exports this themselves.
pub const KEY_ENV: &str = "SEMLITH_AGENT_KEY";

/// Step 5. Install the daemon as a login service.
///
/// On by default, and on even when nothing can answer a prompt. The argument
/// for asking is that a background process is a thing a user should consent to;
/// the argument against is the whole of this release. A client that starts
/// before any daemon finds nothing and says nothing, and the user who meets
/// that is precisely the one who ran a piped installer and never read a
/// question. `--no-service` opts out, `semlith start --no-service` undoes it,
/// and the step prints what it installed and how to remove it.
///
/// Points at the binary `step_binary` installed rather than the one running
/// this code, which during an install is the downloaded installer.
/// Install the Agent Skill and link it wherever a client reads user skills.
///
/// Unconditional, because it is a file under the store home and a link into a
/// directory that client already reads: nothing is rewritten, nothing is merged
/// into a file semlith does not own, and a client with no such directory is
/// simply not linked.
fn step_skill() -> Result<Step> {
    let linked = crate::agentfiles::install_skill()?;
    if linked.is_empty() {
        let held = crate::agentfiles::skill_state()
            .into_iter()
            .filter(|(_, state)| *state == crate::agentfiles::State::Present)
            .count();
        return Ok(Step {
            name: "skill",
            state: if held > 0 {
                State::AlreadyDone
            } else {
                State::Skipped
            },
            detail: if held > 0 {
                format!("linked in {held} skill directories")
            } else {
                "no client on this machine reads a user-level skill directory".into()
            },
        });
    }
    Ok(Step {
        name: "skill",
        state: State::Done,
        detail: format!(
            "linked into {}",
            linked
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ),
    })
}

/// Claude Code's `alwaysLoad` on the entry `claude mcp add` just wrote (4.1).
///
/// Without it the tools sit behind ToolSearch and an agent's first turn does
/// not see them: on 2026-09-25 it moved the first lookup from 33 % to 79 %.
fn step_always_load() -> Result<Step> {
    Ok(match crate::agentfiles::set_always_load()? {
        Some((path, true)) => Step {
            name: "always load",
            state: State::Done,
            detail: format!(
                "the semlith tools load on the first turn ({})",
                path.display()
            ),
        },
        Some((_, false)) => Step {
            name: "always load",
            state: State::AlreadyDone,
            detail: "Claude Code loads the semlith tools on the first turn".into(),
        },
        None => Step {
            name: "always load",
            state: State::Skipped,
            detail: "no user-scope Claude Code entry to upgrade".into(),
        },
    })
}

/// Write, or with `--no-agents` remove, the semlith-explorer subagent (4.8).
fn step_explorer(wanted: bool) -> Result<Step> {
    if !wanted {
        let removed = crate::agentfiles::remove_explorer()?;
        return Ok(Step {
            name: "research agent",
            state: if removed.is_some() {
                State::Done
            } else {
                State::AlreadyDone
            },
            detail: match removed {
                Some(path) => format!("removed {}", path.display()),
                None => "no semlith-explorer agent was installed".into(),
            },
        });
    }
    Ok(match crate::agentfiles::install_explorer()? {
        Some(path) => Step {
            name: "research agent",
            state: State::Done,
            detail: format!("semlith-explorer for Claude Code at {}", path.display()),
        },
        None if crate::agentfiles::explorer_installed() => Step {
            name: "research agent",
            state: State::AlreadyDone,
            detail: "semlith-explorer is installed for Claude Code".into(),
        },
        None => Step {
            name: "research agent",
            state: State::Skipped,
            detail: "Claude Code is not on this machine".into(),
        },
    })
}

/// The "Index with semlith" entries in the file manager (`crate::helpers`).
///
/// Opt-in, unlike every step around it: these write into Finder's services,
/// Explorer's menus and Thunar's own file, which an agent install has no
/// reason to touch. `Some(true)` is `--file-managers`, `Some(false)`
/// `--no-file-managers` (which removes them), and `None` asks — default no —
/// or, under `--yes`, leaves them as they are.
fn step_file_managers(choice: Option<bool>, yes: bool) -> Result<Step> {
    const NAME: &str = "file managers";
    let env = crate::helpers::Env::current()?;
    let before = crate::helpers::status(&env);
    let all = !before.is_empty() && before.iter().all(|h| h.installed);
    let any = before.iter().any(|h| h.installed);
    let labels = |list: &[crate::helpers::Helper]| {
        list.iter().map(|h| h.label).collect::<Vec<_>>().join(", ")
    };

    let wanted = match choice {
        Some(wanted) => wanted,
        None if all => {
            return Ok(Step {
                name: NAME,
                state: State::AlreadyDone,
                detail: format!("{} — `--no-file-managers` removes them", labels(&before)),
            });
        }
        None if yes => false,
        None => cliclack::confirm(format!(
            "Add \"Index with semlith\" to your file manager ({})?",
            labels(&before)
        ))
        .initial_value(false)
        .interact()
        .unwrap_or(false),
    };

    if !wanted {
        if choice != Some(false) {
            return Ok(Step {
                name: NAME,
                state: State::Skipped,
                detail: "opt-in: `semlith setup --file-managers` adds \"Index with semlith\""
                    .into(),
            });
        }
        crate::helpers::remove(&env)?;
        return Ok(Step {
            name: NAME,
            state: if any { State::Done } else { State::AlreadyDone },
            detail: if any {
                format!("removed {}", labels(&before))
            } else {
                "no file-manager helper was installed".into()
            },
        });
    }
    let after = crate::helpers::install(&env)?;
    Ok(Step {
        name: NAME,
        state: if all { State::AlreadyDone } else { State::Done },
        detail: format!(
            "\"Index with semlith\" in {}",
            after
                .iter()
                .map(|h| h.path.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ),
    })
}

/// Write, or remove, the `PreToolUse` hook.
///
/// On by default. The file it edits belongs to the client, so it is backed up
/// beside itself before the first write and `--no-hooks` takes the entry out
/// again, leaving every other hook in place.
fn step_hooks(wanted: bool, mode: crate::hook::Mode) -> Result<Step> {
    if !wanted {
        let removed = crate::agentfiles::remove_hooks()?;
        return Ok(Step {
            name: "hook",
            state: if removed.is_empty() {
                State::AlreadyDone
            } else {
                State::Done
            },
            detail: if removed.is_empty() {
                "no steering hook was installed".into()
            } else {
                format!(
                    "removed from {}",
                    removed
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            },
        });
    }

    let written = crate::agentfiles::install_hooks(mode)?;
    if written.is_empty() {
        return Ok(Step {
            name: "hook",
            state: State::AlreadyDone,
            detail: "already installed, or no client here documents one".into(),
        });
    }
    Ok(Step {
        name: "hook",
        state: State::Done,
        detail: format!(
            "{} in {}{}",
            mode.as_str(),
            written
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join(", "),
            gate_hint(mode)
        ),
    })
}

/// What `--hook-mode gate` buys, said where the choice is made (#189). On
/// code an agent with Grep reaches for it first and no wording moves it; the
/// gate does, measured on 50 held-out code questions with Opus 5.5.
fn gate_hint(mode: crate::hook::Mode) -> &'static str {
    if matches!(mode, crate::hook::Mode::Soft) {
        "; `semlith setup --hook-mode gate` makes agents call semlith before grep on code \
         (44 of 50 sessions against 0, two more correct answers, about 31 % more cost a session)"
    } else {
        ""
    }
}

/// Append the rule block to the rules files of the clients that have one.
///
/// Only under `--register-all`, because a rules file is prose somebody wrote
/// and appending to it unasked is a different act from merging a server into a
/// server list. `doctor` prints the block for every other client.
fn step_rules(register_all: bool) -> Result<Step> {
    if !register_all {
        return Ok(Step {
            name: "rules",
            state: State::Skipped,
            detail: "`semlith setup --register-all` writes them; `semlith doctor` prints them"
                .into(),
        });
    }
    let written = crate::agentfiles::install_rules()?;
    Ok(Step {
        name: "rules",
        state: if written.is_empty() {
            State::AlreadyDone
        } else {
            State::Done
        },
        detail: if written.is_empty() {
            "already written, or no client here documents a rules file".into()
        } else {
            format!(
                "wrote {}",
                written
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        },
    })
}

fn step_service(wanted: bool) -> Result<Step> {
    if !wanted {
        return Ok(Step {
            name: "service",
            state: State::Skipped,
            detail: "--no-service: start the daemon yourself with `semlith start`".to_string(),
        });
    }
    let target = home::bin_dir()?.join(exe_name());
    let binary = target.exists().then_some(target);

    // `setup` promises to be a no-op once it has run, and says so in its own
    // last line. Re-bootstrapping a service that is already installed and
    // already names this binary breaks that promise and restarts a daemon
    // somebody may be using. The definition is read rather than trusted:
    // a service still pointing at a binary an upgrade moved is one that has to
    // be rewritten, which is the case this check must not swallow.
    let installed = crate::service::status();
    // A definition from before 0.28.0 names the right binary and still has to
    // be rewritten: it asks for background priority, which the daemon cannot
    // lift itself out of.
    if installed.installed
        && names_the_binary(&installed, binary.as_deref())
        && crate::service::stale_definition().is_none()
    {
        // The definition being current says nothing about the process: an
        // upgrade replaces the binary under a daemon that keeps serving the
        // old one until it is restarted (F1, 0.33.0).
        return Ok(match crate::service::restart_if_stale() {
            Ok(Some(previous)) => Step {
                name: "service",
                state: State::Done,
                detail: format!(
                    "restarted the daemon, which was serving {previous}, onto {} ({})",
                    env!("CARGO_PKG_VERSION"),
                    installed.mechanism,
                ),
            },
            Ok(None) => Step {
                name: "service",
                state: State::AlreadyDone,
                detail: format!(
                    "running from every login ({}) — remove with `semlith start --no-service`",
                    installed.mechanism,
                ),
            },
            Err(e) => Step {
                name: "service",
                state: State::Failed,
                detail: format!("{e:#}"),
            },
        });
    }

    let installed = crate::service::install(binary.as_deref(), None);
    // A reinstall while a daemon answers registers for the next login and
    // leaves that daemon running; if it is an older one, it goes now.
    let restarted = match &installed {
        Ok(status) if status.installed && !status.started_now => crate::service::restart_if_stale(),
        _ => Ok(None),
    };
    if let Err(e) = &restarted {
        return Ok(Step {
            name: "service",
            state: State::Failed,
            detail: format!("{e:#}"),
        });
    }
    if let (Ok(status), Ok(Some(previous))) = (&installed, &restarted) {
        return Ok(Step {
            name: "service",
            state: State::Done,
            detail: format!(
                "restarted the daemon, which was serving {previous}, onto {} ({})",
                env!("CARGO_PKG_VERSION"),
                status.mechanism,
            ),
        });
    }

    match installed {
        Ok(status) if status.installed => Ok(Step {
            name: "service",
            state: State::Done,
            detail: if status.started_now {
                format!(
                    "running now and from every login ({}) — remove with `semlith start --no-service`",
                    status.mechanism,
                )
            } else {
                format!(
                    "a daemon is already listening, so this one starts at the next login ({}) — remove with `semlith start --no-service`",
                    status.mechanism,
                )
            },
        }),
        // Not fatal, and not silent. A machine with no systemd user session, or
        // a binary somewhere macOS will not run a background job from, still
        // gets a working semlith — it just has to be started by hand, and this
        // is the line that says so.
        Ok(status) => Ok(Step {
            name: "service",
            state: State::Failed,
            detail: format!(
                "{} did not report the service as installed — start the daemon with `semlith start`",
                status.mechanism,
            ),
        }),
        Err(e) => Ok(Step {
            name: "service",
            state: State::Failed,
            detail: format!("{e} — start the daemon with `semlith start`"),
        }),
    }
}

/// Whether an installed service already points at the binary setup would name.
///
/// `false` when there is no definition file to read — Windows registers a task
/// rather than writing one semlith can inspect — so that platform reinstalls,
/// which its `/F` makes safe and which is the only way a moved binary gets
/// picked up there.
fn names_the_binary(status: &crate::service::Status, binary: Option<&std::path::Path>) -> bool {
    let Some(definition) = status.definition.as_deref() else {
        return false;
    };
    let Ok(text) = std::fs::read_to_string(definition) else {
        return false;
    };
    let wanted = match binary {
        Some(path) => path.to_path_buf(),
        None => match crate::service::exe() {
            Ok(exe) => exe,
            Err(_) => return false,
        },
    };
    text.contains(&wanted.to_string_lossy().into_owned())
}

/// Step 6. Runs the binary that was just installed, not this process, because
/// the question is whether the installed one works.
fn step_verify() -> Result<Step> {
    let target = home::bin_dir()?.join(exe_name());
    let which = if target.exists() {
        target
    } else {
        std::env::current_exe().context("locating the running binary")?
    };
    match Command::new(&which).arg("--version").output() {
        Ok(o) if o.status.success() => {
            let line = String::from_utf8_lossy(&o.stdout).trim().to_string();
            Ok(Step {
                name: "verify",
                state: State::AlreadyDone,
                detail: line,
            })
        }
        _ => Ok(Step {
            name: "verify",
            state: State::Failed,
            detail: format!("{} would not run", which.display()),
        }),
    }
}

// ---------------------------------------------------------------- rotation

/// Carry a rotated agent key into the client configuration files that already
/// hold the old one.
///
/// Rotation used to leave every configured client authenticating with a key
/// the daemon had stopped accepting, and the only repair was to open each file
/// and paste. This edits the files that already carry the old key — nothing
/// else. A file is rewritten only when the exact 68-character key appears in
/// it, so a path that happens to exist but names a different server is left
/// alone, and no file is ever created.
///
/// Returns the files that changed, in the order they were tried.
pub fn recarry_key(previous: &str, fresh: &str) -> Vec<PathBuf> {
    let mut done = Vec::new();
    if previous == fresh || !home::is_agent_key(previous) || !home::is_agent_key(fresh) {
        return done;
    }
    for path in client_configs() {
        let Ok(text) = std::fs::read_to_string(&path) else {
            continue;
        };
        if !text.contains(previous) {
            continue;
        }
        // A rotation is meant to narrow what a credential is exposed to, so
        // the file keeps its mode and its link (see `clientfile::rewrite`).
        if crate::clientfile::rewrite(&path, &text.replace(previous, fresh)).is_ok() {
            done.push(path);
        }
    }
    done
}

/// Where the clients `docs/clients.md` documents keep their configuration.
///
/// The user-level file for each, plus the project-level ones relative to
/// wherever the daemon was started. It mirrors the paths in that document; a path that is absent is simply skipped, so listing one
/// costs nothing and missing one costs a manual edit after a rotation.
fn client_configs() -> Vec<PathBuf> {
    let mut out = Vec::new();
    if let Ok(home_dir) = home::user_home() {
        for rest in [
            // Claude Code writes the user scope here, and `claude mcp add`
            // does too.
            ".claude.json",
            ".codex/config.toml",
            ".config/opencode/opencode.json",
            ".copilot/mcp-config.json",
            ".gemini/settings.json",
            ".cursor/mcp.json",
            ".config/zed/settings.json",
            ".cline/data/settings/cline_mcp_settings.json",
            // The editors that keep their MCP file inside a per-platform
            // application-support directory.
            "Library/Application Support/Claude/claude_desktop_config.json",
            "Library/Application Support/Code/User/mcp.json",
            ".config/Code/User/mcp.json",
        ] {
            out.push(home_dir.join(rest));
        }
    }
    if let Some(appdata) = std::env::var_os("APPDATA").map(PathBuf::from) {
        out.push(appdata.join("Claude/claude_desktop_config.json"));
        out.push(appdata.join("Code/User/mcp.json"));
    }
    // The project-scoped files, against wherever this process was started.
    if let Ok(here) = std::env::current_dir() {
        for rest in [
            ".mcp.json",
            ".vscode/mcp.json",
            ".cursor/mcp.json",
            "opencode.json",
            "io.local.toml",
        ] {
            out.push(here.join(rest));
        }
    }
    out
}

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

    /// Windows: an npm-installed client CLI is a `.cmd` shim, and it is
    /// invoked — remove, then add — rather than read as not installed.
    #[cfg(windows)]
    #[test]
    fn a_client_cli_that_is_a_cmd_shim_is_registered() {
        let dir = tempfile::tempdir().unwrap();
        let log = dir.path().join("calls.txt");
        std::fs::write(
            dir.path().join("gemini.cmd"),
            format!(
                "@echo off\r\necho %*>> \"{}\"\r\nexit /b 0\r\n",
                log.display()
            ),
        )
        .unwrap();
        let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
        let path = std::ffi::OsString::from(format!("{};{system}\\System32", dir.path().display()));
        let gemini = crate::clients::clients()
            .iter()
            .find(|c| c.name == "Gemini CLI")
            .expect("documented");
        let outcome = home::with_env_var("PATH", &path, || register(gemini));
        assert!(
            matches!(outcome, Registration::Registered { .. }),
            "{outcome:?}"
        );
        let calls = std::fs::read_to_string(&log).unwrap();
        assert!(
            calls.contains("mcp add") && calls.contains("semlith"),
            "{calls}"
        );
    }

    /// F2: a printed stanza names the variable, never the key.
    #[test]
    fn a_printed_stanza_carries_the_placeholder_and_no_key() {
        let text = http_suffix();
        assert!(text.contains("${SEMLITH_AGENT_KEY}"), "{text}");
        assert!(!text.contains("sml_"), "{text}");
    }

    /// The whole point: a file that carries the old key is rewritten, and a
    /// file that does not is not touched at all.
    #[test]
    fn only_the_files_holding_the_old_key_are_rewritten() {
        let dir = tempfile::tempdir().unwrap();
        let home_dir = dir.path().join("home");
        std::fs::create_dir_all(home_dir.join(".gemini")).unwrap();
        std::fs::create_dir_all(home_dir.join(".cursor")).unwrap();

        let previous = format!("sml_{}", "a".repeat(64));
        let fresh = format!("sml_{}", "b".repeat(64));

        let carries = home_dir.join(".gemini/settings.json");
        std::fs::write(
            &carries,
            format!("{{\"mcpServers\":{{\"semlith\":{{\"headers\":{{\"Authorization\":\"Bearer {previous}\"}}}}}}}}"),
        )
        .unwrap();
        let untouched = home_dir.join(".cursor/mcp.json");
        std::fs::write(&untouched, "{\"mcpServers\":{\"other\":{}}}").unwrap();
        let before = std::fs::read_to_string(&untouched).unwrap();

        // `HOME` is process-wide. Living in its own module serialises nothing —
        // `cargo test` runs the whole crate on one thread pool — so this takes
        // the lock every other test that reads a home directory takes.
        let changed = home::with_env_var(home::HOME_VAR, home_dir.as_os_str(), || {
            recarry_key(&previous, &fresh)
        });

        assert_eq!(changed, vec![carries.clone()], "{changed:?}");
        let text = std::fs::read_to_string(&carries).unwrap();
        assert!(
            text.contains(&fresh),
            "the new key is not in the file: {text}"
        );
        assert!(!text.contains(&previous), "the old key survived: {text}");
        assert_eq!(std::fs::read_to_string(&untouched).unwrap(), before);
        assert!(
            !carries.with_extension("json.semlith-tmp").exists(),
            "the temporary file was left behind"
        );
    }

    /// Rotating to the same key, or passing something that is not a key, does
    /// nothing rather than rewriting every file with a placeholder.
    #[test]
    fn a_non_rotation_changes_nothing() {
        let key = format!("sml_{}", "c".repeat(64));
        assert!(recarry_key(&key, &key).is_empty());
        assert!(recarry_key("sml_YOURKEY", &key).is_empty());
        assert!(recarry_key(&key, "").is_empty());
    }
}

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

    /// Single quotes are the only POSIX construct in which every character is
    /// itself. What it has to survive is a directory name, which can hold any
    /// byte but a slash and a NUL.
    #[test]
    fn a_posix_word_is_exactly_the_path() {
        assert_eq!(
            posix_quote("/home/me/.semlith/bin"),
            "'/home/me/.semlith/bin'"
        );
        assert_eq!(posix_quote("with space"), "'with space'");
        assert_eq!(posix_quote("$(touch x)"), "'$(touch x)'");
        assert_eq!(posix_quote("`touch x`"), "'`touch x`'");
        assert_eq!(posix_quote("${HOME}"), "'${HOME}'");
        assert_eq!(posix_quote(r#"a"b"#), r#"'a"b'"#);
        assert_eq!(posix_quote(r"back\slash"), r"'back\slash'");
        // The one character that cannot appear inside single quotes.
        assert_eq!(posix_quote("it's"), r"'it'\''s'");
    }

    /// fish has no `'\''` idiom: inside single quotes it recognises a
    /// backslash escape, so the backslash itself has to be escaped first.
    #[test]
    fn a_fish_word_escapes_what_fish_reads() {
        assert_eq!(fish_quote("/home/me/bin"), "'/home/me/bin'");
        assert_eq!(fish_quote("it's"), r"'it\'s'");
        assert_eq!(fish_quote(r"back\slash"), r"'back\\slash'");
        // Order matters: escaping the quote first would then escape its own
        // backslash and end the string early.
        assert_eq!(fish_quote(r"\'"), r"'\\\''");
    }

    /// PowerShell doubles the quote and treats nothing else as special inside
    /// single quotes — `$dir` in the script is why this matters at all.
    #[test]
    fn a_powershell_word_doubles_its_quotes() {
        assert_eq!(powershell_quote(r"C:\Users\me\bin"), r"'C:\Users\me\bin'");
        assert_eq!(powershell_quote("it's"), "'it''s'");
        assert_eq!(powershell_quote("$(pwd)"), "'$(pwd)'");
    }
}