haps 0.1.12

Hashtree Package System: signed packages, content-addressed distribution, social discovery
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
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
use anyhow::{Context, Result, ensure};
use clap::{Args, Parser, Subcommand};
use haps::comments::{self, Comments, Scope};
use haps::{
    discovery::{Announcement, Discovery},
    install::{Installation, ensure_public_key, load_keys},
    model::*,
    repository::{Repository, Snapshot},
    trust::{Trust, attest, attest_at, attestation_time_ms, parse_attestation, warn, warn_at},
};
use nostr::{Event, EventBuilder, EventId, Keys, Kind, Tag, Timestamp};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
    process::ExitCode,
    sync::Arc,
};

#[derive(Parser)]
#[command(version, about = "Haps — Hashtree Package System")]
struct Cli {
    #[arg(long, global = true, env = "HAPS_HOME")]
    home: Option<PathBuf>,
    /// Start a fresh configuration without discovery presets or a trust seed.
    #[arg(long, global = true, env = "HAPS_NO_DEFAULTS")]
    no_defaults: bool,
    /// Never prompt; require publisher/name when several publishers match.
    #[arg(long, global = true, env = "HAPS_NON_INTERACTIVE")]
    non_interactive: bool,
    #[command(subcommand)]
    command: Command,
}

#[derive(Args)]
struct ClaimArgs {
    /// Release event ID, or publisher/package with --version.
    release: String,
    /// Required with a package name. Uses this machine's platform by default.
    #[arg(long)]
    version: Option<semver::Version>,
    /// Select another platform when using a package name and --version.
    #[arg(long, requires = "version")]
    target: Option<String>,
    #[arg(long)]
    note: String,
    /// Withdraw your previous claim without endorsing or warning.
    #[arg(long)]
    revoke: bool,
    #[arg(long)]
    out: Option<PathBuf>,
    /// Emit the signed event as JSON and never prompt.
    #[arg(long)]
    json: bool,
}

#[derive(Subcommand)]
enum Command {
    /// Show, replace, or disable the local social-graph starting point.
    StartingPoint {
        public_key: Option<String>,
        #[arg(long, conflicts_with = "public_key")]
        clear: bool,
    },
    /// Create or use a Nostr publishing identity. No account registration.
    Identity {
        #[command(subcommand)]
        action: IdentityAction,
    },
    /// Give a publisher a local name, such as alice/package.
    Alias {
        #[command(subcommand)]
        action: AliasAction,
    },
    /// Show this machine's package target.
    Target,
    /// Create a package manifest for a staged binary or macOS app.
    Init(haps::init::InitArgs),
    /// Add a staged package or another publisher's package to your event catalog.
    Add {
        package: String,
        /// With a manifest path, sign a release from this staged directory.
        #[arg(long)]
        payload: Option<PathBuf>,
        #[arg(long, default_value = "default")]
        catalog: String,
    },
    /// Maintain and discover searchable catalogs of signed package events.
    Catalog {
        #[command(subcommand)]
        action: CatalogAction,
    },
    /// Sign staged files and prepare your package for publication.
    Pack {
        manifest: PathBuf,
        #[arg(long)]
        payload: PathBuf,
        #[arg(long)]
        out: PathBuf,
        #[arg(long)]
        key_file: Option<PathBuf>,
    },
    /// Prepare or publish packages from a verified Hashtree/Iris Git release directory.
    ImportRelease(haps::release::ReleaseArgs),
    /// Share signed packages through Hashtree and announce them on Nostr.
    Publish {
        #[arg(value_name = "DIRECTORY")]
        catalog: PathBuf,
        /// Hashtree name to create or update under your hosting identity.
        #[arg(long)]
        name: String,
        /// Catalog publisher's signing key (defaults to the local Haps identity).
        #[arg(long)]
        key_file: Option<PathBuf>,
    },
    /// Retry queued announcements and refresh the private discovery cache.
    Sync,
    /// Configure shared signed indexes or build one from the local event cache.
    #[command(hide = true)]
    Index {
        #[command(subcommand)]
        action: IndexAction,
    },
    /// Inspect or explicitly execute a build recipe from a pinned Git checkout.
    Build {
        repository: String,
        #[arg(long)]
        rev: String,
        #[arg(long, default_value = "haps-build.toml")]
        recipe: String,
        /// Run the recipe with your user permissions. Builds are not sandboxed.
        #[arg(long)]
        execute: bool,
        /// Install the locally signed build after it succeeds.
        #[arg(long, requires = "execute")]
        install: bool,
        /// Share the passing source scan after a successful build and installation.
        #[arg(long, requires = "install")]
        attest_scan: bool,
    },
    /// Advanced compatibility controls for package sources.
    #[command(hide = true)]
    Source {
        #[command(subcommand)]
        action: SourceAction,
    },
    /// Search packages authored or vouched for by your social graph.
    Search {
        query: String,
        /// Emit one JSON array and never prompt.
        #[arg(long)]
        json: bool,
    },
    /// Inspect the publisher, exact release ID, and social evidence.
    Info {
        package: String,
        #[arg(long)]
        version: Option<semver::Version>,
        /// Emit JSON and never prompt.
        #[arg(long)]
        json: bool,
    },
    /// Install a package. An explicit publisher/name can bypass the social filter.
    Install {
        package: String,
        #[arg(long)]
        version: Option<semver::Version>,
        #[arg(long)]
        allow_untrusted: bool,
        /// Override trusted release warnings for this operation only.
        #[arg(long)]
        allow_warnings: bool,
        #[arg(long, default_value_t = 0)]
        require_attestations: usize,
        /// Emit JSON and never prompt.
        #[arg(long)]
        json: bool,
    },
    /// Update an installed package while retaining its publisher and attestation policy.
    Update {
        package: String,
        #[arg(long)]
        allow_untrusted: bool,
        /// Override trusted release warnings for this operation only.
        #[arg(long)]
        allow_warnings: bool,
        /// Emit JSON and never prompt.
        #[arg(long)]
        json: bool,
    },
    /// Link installed commands into a directory; links follow updates and rollback.
    Link {
        package: String,
        #[arg(long)]
        bin_dir: Option<PathBuf>,
    },
    /// Configure automatic local scans before executing source builds.
    Security {
        /// Enable scans using a local Semgrep rules file; its contents are pinned.
        #[arg(long, conflicts_with = "disable")]
        rules: Option<PathBuf>,
        /// Semgrep executable (defaults to semgrep on PATH).
        #[arg(long, requires = "rules")]
        scanner: Option<PathBuf>,
        /// Disable the scan requirement, retaining private reports.
        #[arg(long)]
        disable: bool,
    },
    /// Run an installed command without changing your system PATH.
    Run {
        package: String,
        #[arg(long)]
        command: Option<String>,
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// Show an installed directory (including native app bundles).
    Path { package: String },
    /// Add a small Haps submenu to Omarchy v4 (requires Python 3 and fzf).
    #[cfg(target_os = "linux")]
    Omarchy {
        /// Remove only the menu entries installed by Haps.
        #[arg(long)]
        remove: bool,
    },
    List {
        #[arg(long)]
        json: bool,
    },
    /// Activate the previous installed version.
    Rollback { package: String },
    /// Remove from the installed set. Retain cached files for recovery.
    Remove { package: String },
    /// Follow a publisher locally; optionally export the signed Nostr follow event.
    Follow {
        public_key: String,
        #[arg(long)]
        export: Option<PathBuf>,
    },
    /// Import verified Nostr follows, mutes, and release attestations.
    Import { events: PathBuf },
    /// Publish a signed endorsement of an exact release.
    Attest(ClaimArgs),
    /// Publish a signed warning about an exact release.
    Warn(ClaimArgs),
    /// Publish a signed package comment, release comment, or reply.
    Comment {
        package: String,
        text: String,
        /// Target an exact release event ID instead of the whole package.
        #[arg(long)]
        release: Option<String>,
        #[arg(long)]
        reply_to: Option<String>,
        /// Also export the signed comment to a file.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Find comments, with social context and local mutes applied.
    Comments {
        package: String,
        #[arg(long)]
        release: Option<String>,
    },
}

impl Command {
    fn json(&self) -> bool {
        match self {
            Self::Init(args) => args.json,
            Self::Search { json, .. }
            | Self::Info { json, .. }
            | Self::Install { json, .. }
            | Self::Update { json, .. }
            | Self::List { json } => *json,
            Self::Attest(args) | Self::Warn(args) => args.json,
            _ => false,
        }
    }
}

#[derive(Subcommand)]
enum IdentityAction {
    Init,
    /// Use a public key for discovery without storing its secret key.
    Use {
        public_key: String,
    },
    Show,
}

#[derive(Subcommand)]
enum CatalogAction {
    /// List your catalogs and the indexes searched by Haps.
    List,
    /// Show the original signed events in one of your catalogs.
    Show {
        #[arg(default_value = "default")]
        name: String,
    },
    /// Remove a package from your catalog; installed packages are unaffected.
    Remove {
        package: String,
        #[arg(long, default_value = "default")]
        catalog: String,
    },
    /// Include a published event index in searches.
    Add {
        name: String,
        location: String,
        #[arg(long)]
        author: String,
    },
    /// Find event catalogs published by people in your social graph.
    Discover,
    /// Upload your catalog and announce its immutable index on Nostr.
    Publish {
        #[arg(default_value = "default")]
        name: String,
    },
}

#[derive(Subcommand)]
enum SourceAction {
    Add {
        name: String,
        location: String,
        #[arg(long)]
        author: String,
    },
    List,
    Remove {
        name: String,
    },
}

#[derive(Subcommand)]
enum IndexAction {
    Add {
        name: String,
        location: String,
        #[arg(long)]
        author: String,
    },
    List,
    Remove {
        name: String,
    },
    /// Collect signed announcements and export a shareable Hashtree index.
    Build {
        #[arg(long)]
        out: PathBuf,
        #[arg(long)]
        key_file: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum AliasAction {
    Add { name: String, public_key: String },
    List,
    Remove { name: String },
}

#[derive(Default, Serialize, Deserialize)]
struct Config {
    identity: Option<String>,
    sources: BTreeMap<String, Source>,
    #[serde(default)]
    indexes: BTreeMap<String, Source>,
    #[serde(skip)]
    aliases: BTreeMap<String, String>,
    #[serde(default)]
    starting_point: Option<String>,
    #[serde(default)]
    discovery_defaults_version: u32,
}

const DISCOVERY_DEFAULTS_VERSION: u32 = 2;
const LEGACY_INDEX_LOCATION: &str =
    "htree://npub1q6g6t3yk0m2ppp5mrqsze4xg6uqhw5p29kjutet5m3uk637xjfaqac3p2a/package-index";
const LEGACY_INDEX_AUTHOR: &str =
    "731fd6f74667cac0e86b7b4f7cd2c828996db866c3044368a2f26d87cb571ad0";

fn discovery_presets(config: &mut Config) -> Result<()> {
    // A signed immutable bootstrap makes a cold install independent of mutable
    // root availability. Social root announcements can add newer indexes later.
    let event: Event = serde_json::from_str(include_str!("../packages/catalog-root.json"))?;
    let announcement = haps::event_catalog::IndexAnnouncement::verify(event)?;
    config
        .indexes
        .entry("haps".into())
        .or_insert_with(|| Source {
            location: announcement.location,
            author: announcement.event.pubkey.to_hex(),
            sequence: 0,
            event_id: announcement.event.id.to_hex(),
        });
    Ok(())
}

fn fresh_config(no_defaults: bool) -> Result<Config> {
    let mut config = Config {
        discovery_defaults_version: DISCOVERY_DEFAULTS_VERSION,
        ..Default::default()
    };
    if !no_defaults {
        discovery_presets(&mut config)?;
        let npub = hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB;
        let key = ensure_public_key(npub)?;
        config.starting_point = Some(key.clone());
    }
    Ok(config)
}

fn resolve_key(config: &Config, key: &str) -> Result<String> {
    ensure_public_key(config.aliases.get(key).map(String::as_str).unwrap_or(key))
}

fn resolve_package(config: &Config, package: &str) -> Result<String> {
    if let Some((key, name)) = package.split_once('/') {
        safe_name(name)?;
        return Ok(format!("{}/{}", resolve_key(config, key)?, name));
    }
    Ok(package.into())
}

fn publisher_label(aliases: &BTreeMap<String, String>, author: &str) -> String {
    use nostr::nips::nip19::ToBech32;
    aliases
        .iter()
        .find(|(_, key)| key.as_str() == author)
        .map(|(alias, _)| alias.clone())
        .unwrap_or_else(|| {
            nostr::PublicKey::parse(author)
                .map(|p| p.to_bech32().unwrap())
                .unwrap_or_else(|_| author.into())
        })
}

#[derive(Serialize, Deserialize)]
struct Source {
    location: String,
    author: String,
    sequence: u64,
    event_id: String,
}

struct Candidate {
    repository: Arc<Repository>,
    package_card: Option<String>,
    release: Release,
}

fn save_config(home: &Path, config: &Config) -> Result<()> {
    atomic_write(
        &home.join("config.json"),
        &serde_json::to_vec_pretty(config)?,
    )
}

fn load_trust(home: &Path, config: &Config) -> Result<Trust> {
    // An unset identity has no author relationships; explicit installs can still
    // proceed with --allow-untrusted after inspection.
    let mut trust = Trust::new(
        config
            .identity
            .clone()
            .unwrap_or_else(|| "unconfigured".into()),
    );
    let file = home.join("social.json");
    if file.exists() {
        let events: Vec<Event> = read_json(&file)?;
        ensure!(events.len() <= 10_000, "social event limit exceeded");
        for event in events {
            trust.ingest(event)?;
        }
    }
    trust.set_starting_point(config.starting_point.clone())?;
    Ok(trust)
}

fn save_trust(home: &Path, trust: &Trust) -> Result<()> {
    atomic_write(
        &home.join("social.json"),
        &serde_json::to_vec_pretty(&trust.events())?,
    )
}

fn load_comments(home: &Path) -> Result<Comments> {
    let mut comments = Comments::default();
    let path = home.join("comments.json");
    if path.exists() {
        for event in read_json::<Vec<Event>>(&path)? {
            comments.ingest(event)?;
        }
    }
    Ok(comments)
}

fn save_comments(home: &Path, comments: &Comments) -> Result<()> {
    let bytes = serde_json::to_vec_pretty(&comments.events())?;
    ensure!(
        bytes.len() <= MAX_METADATA,
        "local comments exceed metadata limit"
    );
    atomic_write(&home.join("comments.json"), &bytes)
}

fn select_discussion(
    candidates: Vec<Candidate>,
    package: &str,
    release: Option<&str>,
) -> Result<Candidate> {
    if let Some(id) = release {
        let id = EventId::from_hex(id)?;
        let filtered: Vec<_> = candidates
            .into_iter()
            .filter(|c| c.release.event.id == id)
            .collect();
        let normalized = if let Some((key, name)) = package.split_once('/') {
            format!("{}/{}", ensure_public_key(key)?, name)
        } else {
            package.into()
        };
        let candidate = filtered
            .into_iter()
            .find(|c| {
                c.release.identity() == normalized || c.release.data.package.name == normalized
            })
            .context("release does not belong to this package or is unavailable")?;
        return Ok(candidate);
    }
    // Package discussion is shared across operating systems and versions.
    let normalized = if let Some((key, name)) = package.split_once('/') {
        format!("{}/{}", ensure_public_key(key)?, name)
    } else {
        package.into()
    };
    let mut filtered: Vec<_> = candidates
        .into_iter()
        .filter(|c| c.release.identity() == normalized || c.release.data.package.name == normalized)
        .collect();
    let authors: BTreeSet<_> = filtered.iter().map(|c| c.release.author()).collect();
    ensure!(
        authors.len() == 1,
        "package missing or ambiguous; use publisher/name"
    );
    filtered.sort_by(|a, b| {
        b.release
            .data
            .package
            .version
            .cmp(&a.release.data.package.version)
    });
    Ok(filtered.remove(0))
}

fn own_keys(home: &Path, config: &Config) -> Result<Keys> {
    let keys = load_keys(&home.join("identity.key"))?;
    ensure!(
        config.identity.as_deref() == Some(keys.public_key().to_hex().as_str()),
        "active identity does not match local signing key"
    );
    Ok(keys)
}

fn publishing_keys(home: &Path, config: &mut Config) -> Result<Keys> {
    if config.identity.is_none() && !home.join("identity.key").exists() {
        use std::io::Write;
        let keys = Keys::generate();
        let mut options = fs::OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            options.mode(0o600);
        }
        let mut file = options.open(home.join("identity.key"))?;
        file.write_all(keys.secret_key().to_secret_hex().as_bytes())?;
        file.sync_all()?;
        config.identity = Some(keys.public_key().to_hex());
        save_config(home, config)?;
    }
    own_keys(home, config)
}

fn check_checkpoint(source: &mut Source, snapshot: &Snapshot) -> Result<()> {
    ensure!(
        snapshot.head.sequence >= source.sequence,
        "catalog rollback detected"
    );
    ensure!(
        source.event_id.is_empty()
            || snapshot.head.sequence != source.sequence
            || snapshot.event.id.to_hex() == source.event_id,
        "catalog changed at the same sequence"
    );
    source.sequence = snapshot.head.sequence;
    source.event_id = snapshot.event.id.to_hex();
    Ok(())
}

async fn direct_candidates(
    home: &Path,
    query: Option<&str>,
    package: Option<&str>,
) -> Result<Vec<Candidate>> {
    let discovery = Discovery::open(home)?;
    let announcements = discovery.announcements(None).await?;
    let cached: BTreeMap<_, _> = discovery
        .events(vec![nostr::Filter::new().kind(APP_KIND)])
        .await?
        .into_iter()
        .map(|event| (event.id.to_hex(), event))
        .collect();
    drop(discovery);
    let mut found = Vec::new();
    for announcement in announcements {
        let Some(ref head) = announcement.head else {
            continue;
        };
        let author = announcement.author();
        let identity = format!("{author}/{}", announcement.name);
        if package.is_some_and(|p| p != identity && p != announcement.name) {
            continue;
        }
        if let Some(query) = query {
            let text = format!("{} {}", announcement.name, head.description).to_lowercase();
            if !query
                .split_whitespace()
                .all(|term| text.contains(&term.to_lowercase()))
            {
                continue;
            }
        }
        let result: Result<Vec<Candidate>> = async {
            let repo = Arc::new(Repository::open(&head.payload, &home.join("cache"))?);
            let mut releases = Vec::new();
            for pointer in &head.releases {
                let event: Event = match cached.get(&pointer.id) {
                    Some(event) => event.clone(),
                    None => repo.json(&pointer.cid).await?,
                };
                let release = head.verify_release(pointer, event, &author, &announcement.name)?;
                releases.push(Candidate {
                    repository: repo.clone(),
                    package_card: Some(head.card.clone()),
                    release,
                });
            }
            Ok(releases)
        }
        .await;
        match result {
            Ok(releases) => found.extend(releases),
            Err(error) => eprintln!(
                "Package {identity} unavailable or invalid; results may be incomplete: {error:#}"
            ),
        }
    }
    Ok(found)
}

async fn candidates(
    home: &Path,
    config: &mut Config,
    query: Option<&str>,
    package: Option<&str>,
) -> Result<Vec<Candidate>> {
    let mut found = direct_candidates(home, query, package).await?;
    let mut available = usize::from(!found.is_empty());
    let mut seen: BTreeMap<_, _> = found
        .iter()
        .map(|c| (c.release.coordinate(), c.release.event.id))
        .collect();
    let direct_authors: BTreeSet<_> = found.iter().map(|c| c.release.author()).collect();
    for (name, source) in &mut config.sources {
        if package.is_some() && direct_authors.contains(&source.author) {
            continue;
        }
        let repo = match Repository::open(&source.location, &home.join("cache")) {
            Ok(repo) => Arc::new(repo),
            Err(error) => {
                eprintln!(
                    "Package source {name} unavailable; results may be incomplete: {error:#}"
                );
                continue;
            }
        };
        let snapshot = match repo.catalog(&source.author).await {
            Ok(snapshot) => Arc::new(snapshot),
            Err(error) => {
                eprintln!("Package source {name} unavailable or invalid: {error:#}");
                continue;
            }
        };
        check_checkpoint(source, &snapshot)?;
        available += 1;
        let releases = if let Some(query) = query {
            repo.search(&snapshot, query).await?
        } else {
            repo.releases(&snapshot).await?
        };
        for release in releases {
            if let Some(id) = seen.insert(release.coordinate(), release.event.id) {
                ensure!(
                    id == release.event.id,
                    "conflicting signed releases at {}",
                    release.coordinate()
                );
                continue;
            }
            found.push(Candidate {
                repository: repo.clone(),
                package_card: snapshot.catalog.packages.get(&release.identity()).cloned(),
                release,
            });
        }
    }
    save_config(home, config)?;
    ensure!(
        available > 0,
        "package discovery is unavailable or incomplete. Check your connection and try haps sync"
    );
    Ok(found)
}

struct Selection {
    non_interactive: bool,
    include_untrusted: bool,
}

fn select(
    mut candidates: Vec<Candidate>,
    package: &str,
    version: Option<&semver::Version>,
    aliases: &BTreeMap<String, String>,
    trust: &Trust,
    target_filter: &str,
    selection: Selection,
) -> Result<Candidate> {
    let package = if let Some((key, name)) = package.split_once('/') {
        format!("{}/{}", ensure_public_key(key)?, name)
    } else {
        package.to_string()
    };
    candidates.retain(|c| {
        (c.release.identity() == package || c.release.data.package.name == package)
            && c.release.data.package.target == target_filter
            && version.is_none_or(|v| &c.release.data.package.version == v)
            && (version.is_some() || c.release.data.package.version.pre.is_empty())
    });
    // Choose the newest matching version before trust filtering. An endorsement
    // of an older release must never silently pin or downgrade a bare install.
    let mut latest = BTreeMap::new();
    for candidate in &candidates {
        let version = &candidate.release.data.package.version;
        let current = latest.entry(candidate.release.author()).or_insert(version);
        *current = (*current).max(version);
    }
    let latest: BTreeMap<_, _> = latest.into_iter().map(|(k, v)| (k, v.clone())).collect();
    candidates.retain(|c| latest[&c.release.author()] == c.release.data.package.version);
    if !selection.include_untrusted && !package.contains('/') {
        candidates.retain(|c| trust.socially_trusted(&c.release));
    }
    let authors: BTreeSet<_> = candidates.iter().map(|c| c.release.author()).collect();
    ensure!(
        !candidates.is_empty(),
        "no matching release for {} in the selected scope; packages outside your social graph require an explicit npub/package",
        target_filter
    );
    if authors.len() > 1 {
        use std::io::IsTerminal;
        let mut choices: Vec<_> = authors.into_iter().collect();
        let approvals = |author: &str| {
            candidates
                .iter()
                .filter(|c| c.release.author() == author)
                .max_by(|a, b| {
                    a.release
                        .data
                        .package
                        .version
                        .cmp(&b.release.data.package.version)
                })
                .map_or(0, |c| trust.attesters(&c.release).len())
        };
        choices.sort_by_key(|author| {
            (
                trust.muted(author),
                trust.distance(author).unwrap_or(u32::MAX),
                std::cmp::Reverse(approvals(author)),
                publisher_label(aliases, author),
            )
        });
        let releases: Vec<_> = choices
            .iter()
            .map(|author| {
                &candidates
                    .iter()
                    .filter(|c| c.release.author() == *author)
                    .max_by_key(|c| &c.release.data.package.version)
                    .unwrap()
                    .release
            })
            .collect();
        let options: Vec<_> = releases
            .iter()
            .map(|release| {
                let author = release.author();
                format!(
                    "{} {} · {}{}\n    {}",
                    release_label(release, aliases),
                    release.data.package.version,
                    relationship(trust, &author, aliases),
                    if trust.muted(&author) {
                        " · muted"
                    } else {
                        ""
                    },
                    attestation_summary(release, trust, aliases),
                )
            })
            .collect();
        if selection.non_interactive
            || !std::io::stdin().is_terminal()
            || !std::io::stdout().is_terminal()
            || !std::io::stderr().is_terminal()
            || std::env::var("TERM").is_ok_and(|term| term == "dumb")
        {
            return Err(AmbiguousPublishers {
                candidates: releases
                    .iter()
                    .map(|r| release_json(r, trust, aliases))
                    .collect(),
            }
            .into());
        }
        eprintln!("Several publishers match. Choose one:");
        eprintln!("↑/↓ move · Enter select · Esc cancel");
        let theme = dialoguer::theme::ColorfulTheme {
            active_item_style: dialoguer::console::Style::new().for_stderr().green(),
            ..Default::default()
        };
        let index = dialoguer::Select::with_theme(&theme)
            .items(&options)
            .default(0)
            .max_length(5)
            .interact_opt()?
            .context("cancelled; no publisher selected")?;
        candidates.retain(|c| c.release.author() == choices[index]);
    }
    candidates.sort_by(|a, b| {
        b.release
            .data
            .package
            .version
            .cmp(&a.release.data.package.version)
    });
    Ok(candidates.remove(0))
}

// Terminal text must not execute control sequences from shared aliases or signed notes.
fn terminal_text(value: &str) -> String {
    value
        .chars()
        .flat_map(|c| {
            if c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') {
                c.escape_default().collect::<Vec<_>>()
            } else {
                vec![c]
            }
        })
        .collect()
}

fn release_label(release: &Release, aliases: &BTreeMap<String, String>) -> String {
    format!(
        "{}/{}",
        terminal_text(&publisher_label(aliases, &release.author())),
        release.data.package.name
    )
}

fn relationship(trust: &Trust, author: &str, aliases: &BTreeMap<String, String>) -> String {
    if trust.distance(author) == Some(0) {
        return "You".into();
    }
    let mut names: Vec<_> = trust
        .followed_by_friends(author)
        .iter()
        .map(|key| terminal_text(&publisher_label(aliases, key)))
        .collect();
    names.sort();
    if !names.is_empty() {
        let remaining = names.len().saturating_sub(3);
        names.truncate(3);
        let suffix = match remaining {
            0 => String::new(),
            1 => " and 1 other you follow".into(),
            n => format!(" and {n} others you follow"),
        };
        return format!("Followed by {}{suffix}", names.join(", "));
    }
    match trust.distance(author) {
        Some(1) => "Followed by you".into(),
        Some(_) => "In your extended graph".into(),
        None => "outside your graph".into(),
    }
}

fn attestation_summary(
    release: &Release,
    trust: &Trust,
    aliases: &BTreeMap<String, String>,
) -> String {
    let mut names: Vec<_> = trust
        .attesters(release)
        .iter()
        .map(|key| terminal_text(&publisher_label(aliases, key)))
        .collect();
    names.sort();
    let mut summary = if names.is_empty() {
        "No trusted attestations".into()
    } else {
        format!("Attested by {}", names.join(", "))
    };
    let mut warning_names: Vec<_> = trust
        .warnings(release)
        .iter()
        .map(|event| terminal_text(&publisher_label(aliases, &event.pubkey.to_hex())))
        .collect();
    warning_names.sort();
    if !warning_names.is_empty() {
        summary.push_str(&format!("; Warning from {}", warning_names.join(", ")));
    }
    summary
}

fn release_json(
    release: &Release,
    trust: &Trust,
    aliases: &BTreeMap<String, String>,
) -> serde_json::Value {
    let attestations: Vec<_> = trust
        .attestations(release)
        .iter()
        .map(|event| {
            serde_json::json!({"signer": event.pubkey.to_hex(),
            "label": publisher_label(aliases, &event.pubkey.to_hex()), "event": event})
        })
        .collect();
    let warnings: Vec<_> = trust
        .warnings(release)
        .iter()
        .map(|event| {
            serde_json::json!({"signer": event.pubkey.to_hex(),
            "label": publisher_label(aliases, &event.pubkey.to_hex()), "event": event})
        })
        .collect();
    serde_json::json!({
        "identity": release.identity(),
        "label": release_label(release, aliases),
        "package": release.data.package, "publisher": release.author(),
        "release_id": release.event.id.to_hex(), "manifest": release.data.manifest,
        "follow_distance": trust.distance(&release.author()), "muted": trust.muted(&release.author()),
        "overmuted": trust.overmuted(&release.author()), "socially_trusted": trust.socially_trusted(release),
        "followed_by": trust.followed_by_friends(&release.author()).iter().map(|key| serde_json::json!({"pubkey": key, "label": publisher_label(aliases, key)})).collect::<Vec<_>>(),
        "attesters": trust.attesters(release), "attestations": attestations,
        "warnings": warnings,
    })
}

#[derive(Debug)]
struct AmbiguousPublishers {
    candidates: Vec<serde_json::Value>,
}

impl std::fmt::Display for AmbiguousPublishers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "multiple publishers use this name; choose an explicit publisher/name:"
        )?;
        for candidate in &self.candidates {
            writeln!(
                f,
                "  {} ({})",
                candidate["label"].as_str().unwrap(),
                candidate["identity"].as_str().unwrap()
            )?;
        }
        Ok(())
    }
}
impl std::error::Error for AmbiguousPublishers {}

fn print_release(
    release: &Release,
    trust: &Trust,
    aliases: &BTreeMap<String, String>,
) -> Result<()> {
    println!(
        "{}",
        serde_json::to_string_pretty(&release_json(release, trust, aliases))?
    );
    Ok(())
}

fn print_install_start(release: &Release, trust: &Trust, aliases: &BTreeMap<String, String>) {
    eprintln!(
        "Installing {} {}",
        release_label(release, aliases),
        release.data.package.version
    );
    eprintln!("  Signature verified");
    eprintln!("  {}", attestation_summary(release, trust, aliases));
    for event in trust
        .attestations(release)
        .into_iter()
        .chain(trust.warnings(release))
    {
        if let Ok(claim) = parse_attestation(event) {
            eprintln!(
                "    {}: {}",
                terminal_text(&publisher_label(aliases, &event.pubkey.to_hex())),
                terminal_text(&claim.note)
            );
        }
    }
}

fn print_installed(
    release: &Release,
    trust: &Trust,
    aliases: &BTreeMap<String, String>,
    json: bool,
) -> Result<()> {
    if json {
        println!(
            "{}",
            serde_json::json!({"status": "installed", "release": release_json(release, trust, aliases)})
        );
    } else {
        println!(
            "Installed {} {}",
            release_label(release, aliases),
            release.data.package.version
        );
        if release.data.package.app.is_some() || !release.data.package.commands.is_empty() {
            println!("Run with: haps run {}", release_label(release, aliases));
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    let json = cli.command.json();
    match execute(cli).await {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            if json {
                let mut value = serde_json::json!({"code": "operation_failed", "message": format!("{error:#}")});
                if let Some(ambiguous) = error.downcast_ref::<AmbiguousPublishers>() {
                    value["code"] = "ambiguous_package".into();
                    value["candidates"] = serde_json::json!(ambiguous.candidates);
                }
                println!("{}", serde_json::json!({"error": value}));
            } else {
                eprintln!("haps: {error:#}");
            }
            ExitCode::FAILURE
        }
    }
}

async fn execute(mut cli: Cli) -> Result<u8> {
    let non_interactive = cli.non_interactive || cli.command.json();
    let (progress, _reporter) = haps::progress::Progress::stderr(
        !cli.command.json()
            && matches!(
                cli.command,
                Command::Install { .. } | Command::Update { .. }
            ),
    )?;
    match &cli.command {
        Command::Install { package, .. } => {
            progress.stage(format!("Preparing to install {}", terminal_text(package)));
        }
        Command::Update { package, .. } => {
            progress.stage(format!(
                "Checking for updates to {}",
                terminal_text(package)
            ));
        }
        _ => {}
    }
    if let Command::Init(args) = &cli.command {
        let spec = haps::init::create(args)?;
        if args.json {
            println!(
                "{}",
                serde_json::to_string(
                    &serde_json::json!({"status": "created", "manifest": args.out, "package": spec})
                )?
            );
        } else {
            println!("Created {}", args.out.display());
            println!(
                "Check the metadata, then pack it with `haps pack <manifest> --payload <directory> --out <catalog>`."
            );
        }
        return Ok(0);
    }
    if matches!(cli.command, Command::Target) {
        println!("{}", target());
        return Ok(0);
    }
    let home = cli
        .home
        .or_else(|| dirs::data_local_dir().map(|p| p.join("haps")))
        .context("set HAPS_HOME or --home")?;
    fs::create_dir_all(&home)?;
    let home = home.canonicalize()?;
    let guard = lock_with_wait(&home.join(".cli.lock"), || {
        progress.stage("Waiting for another Haps command");
    })?;
    progress.stage("Loading saved social graph");
    let config_file = home.join("config.json");
    let mut config: Config = if config_file.exists() {
        read_json(&config_file)?
    } else {
        fresh_config(cli.no_defaults)?
    };
    if config.discovery_defaults_version < DISCOVERY_DEFAULTS_VERSION {
        let legacy_index = config.indexes.get("haps").is_some_and(|source| {
            source.location == LEGACY_INDEX_LOCATION && source.author == LEGACY_INDEX_AUTHOR
        });
        let original_defaults = config.discovery_defaults_version == 0
            && (config.starting_point.is_some() || config.sources.contains_key("iris"));
        if !cli.no_defaults && (legacy_index || original_defaults) {
            if legacy_index {
                config.indexes.remove("haps");
            }
            discovery_presets(&mut config)?;
            let npub = hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB;
            let author = ensure_public_key(npub)?;
            // Replace only the exact old automatic source, retaining custom
            // source locations, publisher pins, and explicitly removed presets.
            if config.sources.get("iris").is_some_and(|source| {
                source.location == format!("htree://{npub}/haps-packages")
                    && source.author == author
            }) {
                config.sources.remove("iris");
            }
        }
        config.discovery_defaults_version = DISCOVERY_DEFAULTS_VERSION;
        save_config(&home, &config)?;
    }
    config.aliases = haps::aliases::read()?;
    if !config_file.exists() {
        if config.starting_point.is_some() {
            let name = hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_ALIAS;
            if !config.aliases.contains_key(name) {
                haps::aliases::add(name, hashtree_config::DEFAULT_SOCIALGRAPH_ENTRYPOINT_NPUB)?;
                config.aliases = haps::aliases::read()?;
            }
            eprintln!(
                "Starting point: Sirius Business Ltd (maintainer). Use `haps starting-point` to inspect or change it; `haps starting-point --clear` disables it."
            );
        }
        save_config(&home, &config)?;
    }
    let mut trust = load_trust(&home, &config)?;
    match &mut cli.command {
        Command::Install { package, .. }
        | Command::Info { package, .. }
        | Command::Update { package, .. }
        | Command::Run { package, .. }
        | Command::Path { package }
        | Command::Rollback { package }
        | Command::Remove { package }
        | Command::Comment { package, .. }
        | Command::Comments { package, .. } => {
            *package = resolve_package(&config, package)?;
        }
        _ => {}
    }
    match &cli.command {
        Command::Install { package, .. }
        | Command::Info { package, .. }
        | Command::Update { package, .. }
        | Command::Comment { package, .. }
        | Command::Comments { package, .. } => {
            let publisher = package
                .split_once('/')
                .map(|(key, _)| nostr::PublicKey::parse(key))
                .transpose()?;
            progress.stage("Looking up packages and social trust");
            refresh_discovery(
                &home,
                &mut config,
                &mut trust,
                publisher,
                Some(package.rsplit('/').next().unwrap()),
                None,
            )
            .await?;
        }
        _ => {}
    }
    let installation = Installation::new(home.clone())?.with_progress(progress.clone());
    let is_warning = matches!(&cli.command, Command::Warn(_));
    match cli.command {
        Command::Target | Command::Init(_) => unreachable!(),
        Command::Add {
            package,
            payload,
            catalog,
        } => {
            let directory = haps::event_catalog::directory(&home, &catalog)?;
            if let Some(payload) = payload {
                let spec: PackageSpec = toml::from_str(&fs::read_to_string(&package)?)?;
                let keys = publishing_keys(&home, &mut config)?;
                let repo = Repository::local(directory.join("packages"))?;
                let release = repo.publish(&keys, spec, &payload).await?;
                Discovery::open(&directory)?.ingest([release.event]).await?;
            } else {
                let package = resolve_package(&config, &package)?;
                let publisher = package
                    .split_once('/')
                    .map(|(key, _)| nostr::PublicKey::parse(key))
                    .transpose()?;
                refresh_discovery(
                    &home,
                    &mut config,
                    &mut trust,
                    publisher,
                    Some(package.rsplit('/').next().unwrap()),
                    None,
                )
                .await?;
                haps::event_catalog::add_package(&home, &catalog, &package).await?;
            }
            println!("Added to catalog {catalog}. Publish with: haps catalog publish {catalog}");
        }
        Command::Catalog { action } => {
            use haps::event_catalog::{IndexAnnouncement, directory};
            match action {
                CatalogAction::Discover => {
                    refresh_discovery(&home, &mut config, &mut trust, None, None, None).await?;
                    println!("{}", serde_json::to_string_pretty(&config.indexes)?);
                }
                CatalogAction::List => {
                    let path = home.join("catalogs");
                    let mut own = Vec::new();
                    if path.exists() {
                        for entry in fs::read_dir(path)? {
                            let entry = entry?;
                            if entry.file_type()?.is_dir() {
                                own.push(entry.file_name().to_string_lossy().into_owned());
                            }
                        }
                    }
                    own.sort();
                    println!(
                        "{}",
                        serde_json::json!({"own": own, "indexes": config.indexes})
                    );
                }
                CatalogAction::Show { name } => {
                    let path = directory(&home, &name)?;
                    ensure!(path.exists(), "catalog does not exist");
                    println!(
                        "{}",
                        serde_json::to_string_pretty(
                            &Discovery::open(&path)?
                                .events(vec![nostr::Filter::new()])
                                .await?
                        )?
                    );
                }
                CatalogAction::Remove { package, catalog } => {
                    let package = resolve_package(&config, &package)?;
                    let path = directory(&home, &catalog)?;
                    ensure!(path.exists(), "catalog does not exist");
                    let selected = Discovery::open(&path)?;
                    let events = selected.events(vec![nostr::Filter::new()]).await?;
                    let identity = |event: &Event| -> Option<String> {
                        if let Ok(a) = Announcement::verify(event.clone()) {
                            Some(format!("{}/{}", a.author(), a.name))
                        } else {
                            Release::verify(event.clone()).ok().map(|r| r.identity())
                        }
                    };
                    let matches: BTreeSet<_> = events
                        .iter()
                        .filter_map(identity)
                        .filter(|id| {
                            *id == package || id.rsplit('/').next() == Some(package.as_str())
                        })
                        .collect();
                    ensure!(
                        matches.len() == 1,
                        "package is missing or ambiguous; use publisher/name"
                    );
                    selected
                        .replace_events(events.into_iter().filter(|event| {
                            !identity(event).is_some_and(|id| matches.contains(&id))
                        }))
                        .await?;
                    println!("Removed from catalog {catalog}");
                }
                CatalogAction::Add {
                    name,
                    location,
                    author,
                } => {
                    safe_name(&name)?;
                    ensure!(!config.indexes.contains_key(&name), "index already exists");
                    let author = resolve_key(&config, &author)?;
                    Discovery::open(&home)?
                        .import_index(&location, &author)
                        .await?;
                    config.indexes.insert(
                        name,
                        Source {
                            location,
                            author,
                            sequence: 0,
                            event_id: String::new(),
                        },
                    );
                    save_config(&home, &config)?;
                }
                CatalogAction::Publish { name } => {
                    let path = directory(&home, &name)?;
                    ensure!(path.exists(), "catalog does not exist; add a package first");
                    let keys = publishing_keys(&home, &mut config)?;
                    let selected = Discovery::open(&path)?;
                    // Local package records are built once; public indexes retain
                    // original signatures for packages curated from elsewhere.
                    let selected_events = selected.events(vec![nostr::Filter::new()]).await?;
                    let selected_ids: BTreeSet<_> = selected_events
                        .iter()
                        .filter_map(|e| Release::verify(e.clone()).ok().map(|r| r.identity()))
                        .collect();
                    let mut package_events = Vec::new();
                    if path.join("packages/catalog.json").exists() {
                        package_events = haps::event_catalog::package_events(
                            &home,
                            &path.join("packages"),
                            &keys,
                            None,
                        )
                        .await?;
                        package_events.retain(|event| {
                            if let Ok(a) = Announcement::verify(event.clone()) {
                                selected_ids.contains(&format!("{}/{}", a.author(), a.name))
                            } else {
                                Release::verify(event.clone())
                                    .is_ok_and(|r| selected_ids.contains(&r.identity()))
                            }
                        });
                        selected.ingest(package_events.clone()).await?;
                    }
                    let location = haps::event_catalog::upload_index(
                        &selected.events(vec![nostr::Filter::new()]).await?,
                    )?;
                    drop(selected);
                    let discovery = Discovery::open(&home)?;
                    let previous = discovery.events(vec![nostr::Filter::new()]).await?;
                    let announcement = haps::event_catalog::advance(
                        &keys,
                        IndexAnnouncement::sign(&keys, &name, &location)?,
                        &previous,
                    )?;
                    package_events.push(announcement);
                    discovery.queue(&package_events)?;
                    discovery.ingest(package_events).await?;
                    flush_discovery(&home, &discovery).await;
                    println!("Published catalog {name}: {location}");
                }
            }
        }
        Command::StartingPoint { public_key, clear } => {
            if clear {
                config.starting_point = None;
                save_config(&home, &config)?;
                println!("Starting point disabled");
            } else if let Some(key) = public_key {
                config.starting_point = Some(resolve_key(&config, &key)?);
                save_config(&home, &config)?;
            }
            println!("{}", config.starting_point.as_deref().unwrap_or("none"));
        }
        Command::Alias { action } => match action {
            AliasAction::Add { name, public_key } => {
                let key = ensure_public_key(&public_key)?;
                haps::aliases::add(&name, &key)?;
                println!("{name}: {key}");
            }
            AliasAction::List => println!("{}", serde_json::to_string_pretty(&config.aliases)?),
            AliasAction::Remove { name } => {
                haps::aliases::remove(&name)?;
            }
        },
        Command::Identity { action } => match action {
            IdentityAction::Init => {
                let path = home.join("identity.key");
                ensure!(
                    !path.exists(),
                    "identity already exists; use `haps identity show`"
                );
                let keys = Keys::generate();
                use std::io::Write;
                let mut options = fs::OpenOptions::new();
                options.write(true).create_new(true);
                #[cfg(unix)]
                {
                    use std::os::unix::fs::OpenOptionsExt;
                    options.mode(0o600);
                }
                let mut file = options.open(path)?;
                file.write_all(keys.secret_key().to_secret_hex().as_bytes())?;
                file.sync_all()?;
                config.identity = Some(keys.public_key().to_hex());
                save_config(&home, &config)?;
                println!("{}", keys.public_key().to_hex());
            }
            IdentityAction::Use { public_key } => {
                config.identity = Some(ensure_public_key(&public_key)?);
                save_config(&home, &config)?;
                println!("{}", config.identity.unwrap());
            }
            IdentityAction::Show => {
                println!("{}", config.identity.context("no identity configured")?)
            }
        },
        Command::Pack {
            manifest,
            payload,
            out,
            key_file,
        } => {
            let spec: PackageSpec = toml::from_str(&fs::read_to_string(manifest)?)?;
            let keys = load_keys(&key_file.unwrap_or_else(|| home.join("identity.key")))?;
            let repo = Repository::local(out)?;
            let release = repo.publish(&keys, spec, &payload).await?;
            println!("{}", serde_json::to_string_pretty(&release.event)?);
        }
        Command::Link { package, bin_dir } => {
            let package = resolve_package(&config, &package)?;
            let directory = installation.link(&package, bin_dir.as_deref())?;
            println!(
                "Linked commands in {}. Add this directory to PATH before other installations.",
                directory.display()
            );
        }
        Command::Security {
            rules,
            scanner,
            disable,
        } => {
            haps::security::configure(&home, rules.as_deref(), scanner.as_deref(), disable)?;
        }
        Command::ImportRelease(args) => {
            if let Some((path, name, keys)) = haps::release::prepare(&args, &home).await? {
                if args.publish {
                    let mut events =
                        haps::event_catalog::package_events(&home, &path, &keys, None).await?;
                    let location = haps::event_catalog::upload_index(&events)?;
                    let discovery = Discovery::open(&home)?;
                    let previous = discovery.events(vec![nostr::Filter::new()]).await?;
                    events.push(haps::event_catalog::advance(
                        &keys,
                        haps::event_catalog::IndexAnnouncement::sign(&keys, &name, &location)?,
                        &previous,
                    )?);
                    discovery.queue(&events)?;
                    discovery.ingest(events).await?;
                    let bus = haps::discovery::relay_bus(&home).await?;
                    ensure!(
                        discovery.flush(&bus).await? == 0,
                        "release announcements remain queued; run haps sync before considering publication complete"
                    );
                    println!("Release announcements acknowledged by a relay");
                } else {
                    println!("Prepared catalog {name}; publish with haps catalog publish {name}");
                }
            }
        }
        Command::Publish {
            catalog,
            name,
            key_file,
        } => {
            let path = catalog
                .canonicalize()
                .context("catalog directory is missing")?;
            let keys = load_keys(&key_file.unwrap_or_else(|| home.join("identity.key")))?;
            let events =
                haps::event_catalog::package_events(&home, &path, &keys, Some(&name)).await?;
            let discovery = Discovery::open(&home)?;
            discovery.queue(&events)?;
            discovery.ingest(events).await?;
            flush_discovery(&home, &discovery).await;
        }
        Command::Sync => {
            let discovery = Discovery::open(&home)?;
            flush_discovery(&home, &discovery).await;
            drop(discovery);
            refresh_discovery(&home, &mut config, &mut trust, None, None, None).await?;
        }
        Command::Index { action } => match action {
            IndexAction::Add {
                name,
                location,
                author,
            } => {
                safe_name(&name)?;
                let author = resolve_key(&config, &author)?;
                Discovery::open(&home)?
                    .import_index(&location, &author)
                    .await?;
                config.indexes.insert(
                    name,
                    Source {
                        location,
                        author,
                        sequence: 0,
                        event_id: String::new(),
                    },
                );
                save_config(&home, &config)?;
            }
            IndexAction::Remove { name } => {
                ensure!(config.indexes.remove(&name).is_some(), "index not found");
                save_config(&home, &config)?;
            }
            IndexAction::List => println!("{}", serde_json::to_string_pretty(&config.indexes)?),
            IndexAction::Build { out, key_file } => {
                refresh_discovery(&home, &mut config, &mut trust, None, None, None).await?;
                let keys = load_keys(&key_file.unwrap_or_else(|| home.join("identity.key")))?;
                Discovery::open(&home)?.export_index(&out, &keys).await?;
                println!(
                    "Built signed index in {}. Publish with htree add <directory> --publish <name>.",
                    out.display()
                );
            }
        },
        Command::Build {
            repository,
            rev,
            recipe,
            execute,
            install,
            attest_scan,
        } => {
            let checkout = haps::build::Checkout::fetch(
                SourceInfo {
                    git: repository,
                    rev,
                },
                &recipe,
                &home.join("builds"),
            )?;
            println!("{}", serde_json::to_string_pretty(&checkout.recipe)?);
            if execute {
                let keys = own_keys(&home, &config)?;
                let scan = if haps::security::enabled(&home) {
                    Some(haps::security::scan_source(
                        &home,
                        checkout
                            .recipe
                            .package
                            .source
                            .as_ref()
                            .context("source is missing")?,
                        &checkout.root(),
                    )?)
                } else {
                    ensure!(
                        !attest_scan,
                        "enable source scans with haps security --rules FILE first"
                    );
                    None
                };
                let payload = checkout.execute()?;
                let repo = Repository::local(home.join("built-packages"))?;
                let release = repo
                    .publish(&keys, checkout.recipe.package.clone(), &payload)
                    .await?;
                if install {
                    installation.install(&repo, &release).await?;
                }
                if let Some(report) = scan {
                    let report = haps::security::bind_report(&home, &release, report)?;
                    if attest_scan {
                        publish_scan(
                            &home,
                            &config,
                            haps::security::attestation(&keys, &release, &report)?,
                        )
                        .await?;
                    }
                }
                println!("Built {} {}", release.identity(), release.event.id);
            } else {
                println!(
                    "Preview only. Add --execute to run these commands with your user permissions; add --install to activate the result. Build recipes are not sandboxed."
                );
            }
        }
        Command::Source { action } => match action {
            SourceAction::Add {
                name,
                location,
                author,
            } => {
                safe_name(&name)?;
                ensure!(
                    !config.sources.contains_key(&name),
                    "source already exists; remove it explicitly before replacing its publisher pin"
                );
                let author = resolve_key(&config, &author)?;
                let location = if location.starts_with("https://")
                    || location.starts_with("http://")
                    || location.starts_with("htree://")
                {
                    location
                } else {
                    Path::new(&location)
                        .canonicalize()?
                        .to_str()
                        .context("non-UTF8 source path")?
                        .to_string()
                };
                let repo = Repository::open(&location, &home.join("cache"))?;
                let snapshot = repo.catalog(&author).await?;
                config.sources.insert(
                    name.clone(),
                    Source {
                        location,
                        author,
                        sequence: snapshot.head.sequence,
                        event_id: snapshot.event.id.to_hex(),
                    },
                );
                save_config(&home, &config)?;
                println!("Added {name}");
            }
            SourceAction::List => println!("{}", serde_json::to_string_pretty(&config.sources)?),
            SourceAction::Remove { name } => {
                ensure!(config.sources.remove(&name).is_some(), "source not found");
                save_config(&home, &config)?;
            }
        },
        Command::Search { query, json } => {
            refresh_discovery(&home, &mut config, &mut trust, None, None, Some(&query)).await?;
            let mut results = candidates(&home, &mut config, Some(&query), None).await?;
            let releases: Vec<_> = results.iter().map(|c| c.release.clone()).collect();
            refresh_feedback(&home, &config, &mut trust, &releases).await?;
            results.retain(|c| trust.socially_trusted(&c.release));
            // Known authors sort before publishers vouched for by the graph; fewer hops first.
            results.sort_by_key(|c| {
                (
                    trust.distance(&c.release.author()).unwrap_or(u32::MAX),
                    std::cmp::Reverse(trust.attesters(&c.release).len()),
                )
            });
            if json {
                let releases: Vec<_> = results
                    .iter()
                    .map(|c| release_json(&c.release, &trust, &config.aliases))
                    .collect();
                println!("{}", serde_json::to_string(&releases)?);
            } else {
                for candidate in results {
                    print_release(&candidate.release, &trust, &config.aliases)?;
                }
            }
        }
        Command::Info {
            package, version, ..
        } => {
            let choices = candidates(&home, &mut config, None, Some(&package)).await?;
            let releases: Vec<_> = choices.iter().map(|c| c.release.clone()).collect();
            refresh_feedback(&home, &config, &mut trust, &releases).await?;
            let candidate = select(
                choices,
                &package,
                version.as_ref(),
                &config.aliases,
                &trust,
                target(),
                Selection {
                    non_interactive,
                    include_untrusted: false,
                },
            )?;
            print_release(&candidate.release, &trust, &config.aliases)?;
        }
        Command::Install {
            package,
            version,
            allow_untrusted,
            allow_warnings,
            require_attestations,
            json,
        } => {
            progress.stage("Reading package catalogs");
            let choices = candidates(&home, &mut config, None, Some(&package)).await?;
            let releases: Vec<_> = choices.iter().map(|c| c.release.clone()).collect();
            progress.stage("Checking release attestations and warnings");
            refresh_feedback(&home, &config, &mut trust, &releases).await?;
            progress.clear();
            let candidate = select(
                choices,
                &package,
                version.as_ref(),
                &config.aliases,
                &trust,
                target(),
                Selection {
                    non_interactive,
                    include_untrusted: allow_untrusted,
                },
            )?;
            let require_attestations = require_attestations.max(
                installation
                    .receipts()?
                    .get(&candidate.release.identity())
                    .map_or(0, |r| r.minimum_attestations),
            );
            trust.authorize_with_policy(
                &candidate.release,
                allow_untrusted || package.contains('/'),
                require_attestations,
                allow_warnings,
            )?;
            if !trust.socially_trusted(&candidate.release) {
                eprintln!(
                    "Warning: {} is not authored or vouched for by your social graph (or its author/vouchers are overmuted); proceeding with your explicit choice.",
                    release_label(&candidate.release, &config.aliases)
                );
            }
            if !json {
                print_install_start(&candidate.release, &trust, &config.aliases);
            }
            installation
                .install_with_policy(
                    &candidate.repository,
                    &candidate.release,
                    require_attestations,
                )
                .await?;
            progress.clear();
            print_installed(&candidate.release, &trust, &config.aliases, json)?;
        }
        Command::Update {
            package,
            allow_untrusted,
            allow_warnings,
            json,
        } => {
            let receipt = installation.receipt(&package)?;
            let current = Release::verify(receipt.current)?;
            progress.stage("Reading package catalogs");
            let choices = candidates(&home, &mut config, None, Some(&current.identity())).await?;
            let releases: Vec<_> = choices.iter().map(|c| c.release.clone()).collect();
            progress.stage("Checking release attestations and warnings");
            refresh_feedback(&home, &config, &mut trust, &releases).await?;
            progress.clear();
            let candidate = select(
                choices,
                &current.identity(),
                None,
                &config.aliases,
                &trust,
                target(),
                Selection {
                    non_interactive,
                    include_untrusted: true,
                },
            )?;
            trust.authorize_with_policy(
                &candidate.release,
                allow_untrusted || package.contains('/'),
                receipt.minimum_attestations,
                allow_warnings,
            )?;
            if !trust.socially_trusted(&candidate.release) {
                eprintln!(
                    "Warning: {} is not authored or vouched for by your social graph (or its author/vouchers are overmuted); proceeding with your explicit choice.",
                    release_label(&candidate.release, &config.aliases)
                );
            }
            if !json {
                print_install_start(&candidate.release, &trust, &config.aliases);
            }
            installation
                .install_with_policy(
                    &candidate.repository,
                    &candidate.release,
                    receipt.minimum_attestations,
                )
                .await?;
            progress.clear();
            print_installed(&candidate.release, &trust, &config.aliases, json)?;
        }
        Command::Run {
            package,
            command,
            args,
        } => {
            #[cfg(target_os = "macos")]
            if command.is_none() {
                let release = Release::verify(installation.receipt(&package)?.current)?;
                if let Some(app) = release.data.package.app {
                    let path = installation.path(&package)?.join(safe_path(&app)?);
                    drop(guard);
                    let status = std::process::Command::new("open")
                        .arg("-a")
                        .arg(path)
                        .arg("--args")
                        .args(args)
                        .status()?;
                    return Ok(if status.success() { 0 } else { 1 });
                }
            }
            let executable = installation.command(&package, command.as_deref())?;
            let mut process = std::process::Command::new(executable);
            #[cfg(target_os = "linux")]
            process.env(
                "XDG_DATA_DIRS",
                haps::launch::linux_data_dirs(
                    &installation.path(&package)?,
                    std::env::var_os("XDG_DATA_DIRS").as_deref(),
                )?,
            );
            drop(guard);
            let status = process.args(args).status()?;
            return Ok(status
                .code()
                .and_then(|c| u8::try_from(c).ok())
                .unwrap_or(1));
        }
        Command::Path { package } => println!("{}", installation.path(&package)?.display()),
        #[cfg(target_os = "linux")]
        Command::Omarchy { remove } => {
            let mut process = std::process::Command::new("python3");
            process
                .arg("-c")
                .arg(include_str!("integrations/omarchy.py"))
                .arg(std::env::current_exe()?)
                .arg(&home);
            if remove {
                process.arg("--remove");
            }
            ensure!(
                process.status()?.success(),
                "Omarchy menu integration failed"
            );
        }
        Command::List { json } => {
            let mut releases = Vec::new();
            for (id, receipt) in installation.receipts()? {
                let release = Release::verify(receipt.current)?;
                if json {
                    releases.push(release_json(&release, &trust, &config.aliases));
                } else {
                    println!(
                        "{id}\t{}\t{}",
                        release.data.package.version, release.event.id
                    );
                }
            }
            if json {
                println!("{}", serde_json::to_string(&releases)?);
            }
        }
        Command::Rollback { package } => {
            installation.rollback(&package)?;
            println!("Rolled back {package}");
        }
        Command::Remove { package } => {
            installation.remove(&package)?;
            println!("Removed {package}");
        }
        Command::Follow { public_key, export } => {
            let keys = own_keys(&home, &config)?;
            let public_key = nostr::PublicKey::parse(&resolve_key(&config, &public_key)?)?;
            let old = trust
                .events()
                .into_iter()
                .find(|e| e.kind == Kind::ContactList && e.pubkey == keys.public_key());
            let mut tags: Vec<Tag> = old
                .as_ref()
                .map(|e| e.tags.iter().cloned().collect())
                .unwrap_or_default();
            if !tags.iter().any(|t| {
                t.as_slice().first().is_some_and(|v| v == "p")
                    && t.as_slice().get(1) == Some(&public_key.to_hex())
            }) {
                tags.push(Tag::public_key(public_key));
            }
            let timestamp = Timestamp::from(
                Timestamp::now().as_secs().max(
                    old.as_ref()
                        .map(|e| e.created_at.as_secs() + 1)
                        .unwrap_or(0),
                ),
            );
            let event = EventBuilder::new(
                Kind::ContactList,
                old.as_ref().map(|e| e.content.as_str()).unwrap_or(""),
            )
            .tags(tags)
            .custom_created_at(timestamp)
            .sign_with_keys(&keys)?;
            trust.ingest(event.clone())?;
            save_trust(&home, &trust)?;
            if let Some(path) = export {
                atomic_write(&path, &serde_json::to_vec_pretty(&event)?)?;
            }
            println!("Following {} locally", public_key.to_hex());
        }
        Command::Import { events } => {
            let value: serde_json::Value = read_json(&events)?;
            let events: Vec<Event> = if value.is_array() {
                serde_json::from_value(value)?
            } else {
                vec![serde_json::from_value(value)?]
            };
            ensure!(events.len() <= 10_000, "too many events");
            let count = events.len();
            let mut comments = load_comments(&home)?;
            for event in events {
                if event.kind == Kind::Comment {
                    comments.ingest(event)?;
                } else {
                    trust.ingest(event)?;
                }
            }
            save_trust(&home, &trust)?;
            save_comments(&home, &comments)?;
            println!("Imported {count} signed events");
        }
        Command::Attest(args) | Command::Warn(args) => {
            let ClaimArgs {
                release,
                version,
                target: requested_target,
                note,
                revoke,
                out,
                json,
            } = args;
            let keys = own_keys(&home, &config)?;
            ensure!(
                !note.trim().is_empty(),
                "describe your finding or checked work with --note"
            );
            let release_id = if let Ok(id) = EventId::from_hex(&release) {
                ensure!(
                    version.is_none(),
                    "--version is only used with a package name"
                );
                id
            } else {
                let version = version.context(
                    "use publisher/package --version VERSION, or an exact release event ID",
                )?;
                let package = resolve_package(&config, &release)?;
                let candidate = select(
                    candidates(&home, &mut config, None, Some(&package)).await?,
                    &package,
                    Some(&version),
                    &config.aliases,
                    &trust,
                    requested_target.as_deref().unwrap_or(target()),
                    Selection {
                        non_interactive,
                        include_untrusted: false,
                    },
                )?;
                if !json {
                    eprintln!(
                        "{} {} {} ({})",
                        if revoke {
                            "Withdrawing claim for"
                        } else if is_warning {
                            "Warning about"
                        } else {
                            "Attesting to"
                        },
                        release_label(&candidate.release, &config.aliases),
                        version,
                        candidate.release.data.package.target
                    );
                    eprintln!("  Release: {}", candidate.release.event.id);
                    eprintln!("  Claim: {}", terminal_text(&note));
                }
                candidate.release.event.id
            };
            let mut event = if is_warning {
                warn(&keys, release_id, !revoke, note)?
            } else {
                attest(&keys, release_id, !revoke, note)?
            };

            let previous = trust
                .events()
                .into_iter()
                .filter(|e| {
                    e.pubkey == keys.public_key()
                        && parse_attestation(e).is_ok_and(|a| a.release == release_id.to_hex())
                })
                .map(|e| attestation_time_ms(&e))
                .collect::<Result<Vec<_>>>()?
                .into_iter()
                .max();
            if let Some(previous) = previous
                && previous / 1000 >= event.created_at.as_secs()
            {
                // Relays replace addressable events by whole seconds, not our
                // fact snapshot's millisecond field. Rapid edits must advance
                // that timestamp too, or a warning/revocation can be discarded.
                let claim = parse_attestation(&event)?;
                let build = if is_warning { warn_at } else { attest_at };
                event = build(
                    &keys,
                    release_id,
                    if is_warning {
                        claim.warning
                    } else {
                        claim.approved
                    },
                    claim.note,
                    (previous / 1000)
                        .checked_add(1)
                        .and_then(|seconds| seconds.checked_mul(1000))
                        .context("attestation timestamp overflow")?,
                )?;
            }
            trust.ingest(event.clone())?;
            save_trust(&home, &trust)?;
            let out =
                out.unwrap_or_else(|| home.join("attestations").join(format!("{}.json", event.id)));
            atomic_write(&out, &serde_json::to_vec_pretty(&event)?)?;
            publish_feedback(&home, &config, &event).await?;
            if json {
                println!("{}", serde_json::to_string(&event)?);
            } else {
                println!("{}", event.id);
                eprintln!("Saved signed claim: {}", out.display());
            }
        }
        Command::Comment {
            package,
            text,
            release,
            reply_to,
            out,
        } => {
            let candidate = select_discussion(
                candidates(&home, &mut config, None, Some(&package)).await?,
                &package,
                release.as_deref(),
            )?;
            refresh_feedback(
                &home,
                &config,
                &mut trust,
                std::slice::from_ref(&candidate.release),
            )
            .await?;
            let mut comments = load_comments(&home)?;
            let parent = reply_to.as_deref().map(EventId::from_hex).transpose()?;
            let parent = parent
                .map(|id| {
                    comments
                        .get(&id)
                        .context("reply target is unavailable; try haps comments first")
                })
                .transpose()?;
            let root = if release.is_some() {
                candidate.release.event.clone()
            } else {
                let cid = candidate
                    .package_card
                    .as_ref()
                    .context("package card is missing")?;
                let event: Event = candidate.repository.json(cid).await?;
                ensure!(
                    event.pubkey == candidate.release.event.pubkey
                        && tag_value(&event, "d")?
                            == format!("haps/package/{}", candidate.release.data.package.name),
                    "package card publisher/name mismatch"
                );
                event
            };
            let event = comments::create(
                &own_keys(&home, &config)?,
                &root,
                release.is_some(),
                parent,
                text,
            )?;
            comments.ingest(event.clone())?;
            save_comments(&home, &comments)?;
            if let Some(out) = out {
                atomic_write(&out, &serde_json::to_vec_pretty(&event)?)?;
            }
            publish_feedback(&home, &config, &event).await?;
            println!("{}", event.id);
        }
        Command::Comments { package, release } => {
            let candidate = select_discussion(
                candidates(&home, &mut config, None, Some(&package)).await?,
                &package,
                release.as_deref(),
            )?;
            refresh_feedback(
                &home,
                &config,
                &mut trust,
                std::slice::from_ref(&candidate.release),
            )
            .await?;
            let scope = if release.is_some() {
                Scope::release(&candidate.release)
            } else {
                Scope::package(&candidate.release)
            };
            let comments = load_comments(&home)?;
            for event in comments.thread(&scope) {
                if trust.muted(&event.pubkey.to_hex()) {
                    continue;
                }
                println!(
                    "{}",
                    serde_json::to_string_pretty(&serde_json::json!({
                        "event": event, "follow_distance": trust.distance(&event.pubkey.to_hex()),
                    }))?
                );
            }
        }
    }
    Ok(0)
}

fn networking_enabled(config: &Config) -> bool {
    config.starting_point.is_some() || std::env::var_os("NOSTR_RELAYS").is_some()
}

async fn publish_scan(home: &Path, config: &Config, event: Event) -> Result<()> {
    let mut comments = load_comments(home)?;
    comments.ingest(event.clone())?;
    save_comments(home, &comments)?;
    publish_feedback(home, config, &event).await?;
    eprintln!(
        "Signed source scan: {} (evidence only; no release endorsement)",
        event.id
    );
    Ok(())
}

async fn publish_feedback(home: &Path, config: &Config, event: &Event) -> Result<()> {
    let discovery = Discovery::open(home)?;
    discovery.queue(std::slice::from_ref(event))?;
    if networking_enabled(config) {
        let result = async {
            let bus = haps::discovery::relay_bus(home).await?;
            discovery.flush(&bus).await
        }
        .await;
        match result {
            Ok(0) => eprintln!("Signed feedback acknowledged by a relay"),
            Ok(_) => eprintln!("Signed feedback queued; retry with haps sync"),
            Err(error) => eprintln!("Signed feedback queued: {error:#}. Retry with haps sync"),
        }
    }
    Ok(())
}

async fn refresh_feedback(
    home: &Path,
    config: &Config,
    trust: &mut Trust,
    releases: &[Release],
) -> Result<()> {
    if releases.is_empty() {
        return Ok(());
    }
    let result = async {
        let relay = if networking_enabled(config) {
            match haps::discovery::relay_bus(home).await {
                Ok(bus) => Some(Arc::new(bus)),
                Err(error) => {
                    eprintln!("Relay feedback unavailable; using indexes: {error:#}");
                    None
                }
            }
        } else {
            None
        };
        let indexes: Vec<_> = config
            .indexes
            .values()
            .map(|source| (source.location.clone(), source.author.clone()))
            .collect();
        let lookup = Discovery::open(home)?
            .event_lookup(relay, &indexes, std::time::Duration::from_secs(3))
            .await?;
        let mut events = Vec::new();
        for batch in releases.chunks(128) {
            events.extend(haps::feedback::refresh(&lookup, batch).await?);
        }
        Ok::<_, anyhow::Error>(events)
    }
    .await;
    let events = match result {
        Ok(events) => events,
        Err(error) => {
            eprintln!("Feedback refresh unavailable; cached findings may be incomplete: {error:#}");
            return Ok(());
        }
    };
    let mut comments = load_comments(home)?;
    for event in events {
        if event.kind == Kind::Comment {
            comments.ingest(event)?;
        } else {
            trust.ingest(event)?;
        }
    }
    save_trust(home, trust)?;
    save_comments(home, &comments)
}

async fn flush_discovery(home: &Path, discovery: &Discovery) {
    match haps::discovery::relay_bus(home).await {
        Ok(bus) => match discovery.flush(&bus).await {
            Ok(0) => println!("Announcements acknowledged by a relay"),
            Ok(pending) => eprintln!("{pending} announcements queued; retry with haps sync"),
            Err(error) => eprintln!("Announcements remain queued: {error:#}"),
        },
        Err(error) => eprintln!("Announcements remain queued: {error:#}. Retry with haps sync"),
    }
}

async fn discover_social_indexes(
    home: &Path,
    config: &mut Config,
    trust: &mut Trust,
    discovery: &Discovery,
    relay: Option<&Arc<nostr_pubsub_relay::RelayEventBus>>,
) -> Result<()> {
    use haps::event_catalog::{INDEX_KIND, IndexAnnouncement};
    let indexes: Vec<_> = config
        .indexes
        .values()
        .map(|source| (source.location.clone(), source.author.clone()))
        .collect();
    let lookup = discovery
        .event_lookup(relay.cloned(), &indexes, std::time::Duration::from_secs(2))
        .await?;
    let mut queried = BTreeSet::new();
    for _ in 0..2 {
        let authors: Vec<_> = trust
            .discovery_authors(1)
            .into_iter()
            .filter(|key| queried.insert(*key))
            .collect();
        if authors.is_empty() {
            break;
        }
        let events = lookup
            .query(vec![
                nostr::Filter::new()
                    .kinds([Kind::ContactList, Kind::MuteList])
                    .authors(authors)
                    .limit(512),
            ])
            .await?;
        for event in events {
            if let Err(error) = trust.ingest(event) {
                eprintln!("Invalid social event: {error:#}");
            }
        }
        save_trust(home, trust)?;
    }
    let authors = trust.discovery_authors(2);
    if !authors.is_empty() {
        let events = lookup
            .query(vec![
                nostr::Filter::new()
                    .kinds([INDEX_KIND, APP_KIND])
                    .custom_tag(
                        nostr::SingleLetterTag::lowercase(nostr::Alphabet::L),
                        "hashtree",
                    )
                    .authors(authors)
                    .limit(256),
            ])
            .await?;
        discovery.ingest(events).await?;
    }
    config.indexes.retain(|name, source| {
        !name.starts_with("social-")
            || (!trust.overmuted(&source.author)
                && trust.distance(&source.author).is_some_and(|d| d <= 2))
    });
    for event in discovery
        .events(vec![nostr::Filter::new().kinds([INDEX_KIND, APP_KIND])])
        .await?
    {
        let Ok(announcement) = IndexAnnouncement::verify(event) else {
            continue;
        };
        let author = announcement.event.pubkey.to_hex();
        if trust.overmuted(&author) || !trust.distance(&author).is_some_and(|d| d <= 2) {
            continue;
        }
        let name = format!(
            "social-{author}-{}",
            hex::encode(tag_value(&announcement.event, "d")?)
        );
        config.indexes.insert(
            name,
            Source {
                location: announcement.location,
                author,
                sequence: 0,
                event_id: String::new(),
            },
        );
    }
    Ok(())
}

async fn refresh_discovery(
    home: &Path,
    config: &mut Config,
    trust: &mut Trust,
    publisher: Option<nostr::PublicKey>,
    package: Option<&str>,
    query: Option<&str>,
) -> Result<()> {
    let discovery = Discovery::open(home)?;
    let relay = if networking_enabled(config) {
        match haps::discovery::relay_bus(home).await {
            Ok(bus) => Some(Arc::new(bus)),
            Err(error) => {
                eprintln!("Relay discovery unavailable; using indexes: {error:#}");
                None
            }
        }
    } else {
        None
    };
    discover_social_indexes(home, config, trust, &discovery, relay.as_ref()).await?;
    let indexes: Vec<_> = config
        .indexes
        .values()
        .map(|source| (source.location.clone(), source.author.clone()))
        .collect();
    discovery
        .lookup_sources(
            relay,
            &indexes,
            publisher,
            package,
            query,
            std::time::Duration::from_secs(3),
        )
        .await?;
    for announcement in discovery.announcements(publisher).await? {
        if announcement.head.is_some() {
            continue;
        }
        if let Some(query) = query {
            let text =
                format!("{} {}", announcement.name, announcement.event.content).to_lowercase();
            if !query
                .split_whitespace()
                .any(|term| text.contains(&term.to_lowercase()))
            {
                continue;
            }
        }
        let author = announcement.author();
        if config
            .sources
            .values()
            .any(|s| s.author == author && s.location == announcement.location)
        {
            continue;
        }
        let name = format!("discovered-{}-{}", author, announcement.name);
        let source = config.sources.entry(name).or_insert_with(|| Source {
            location: announcement.location.clone(),
            author,
            sequence: 0,
            event_id: String::new(),
        });
        // Keep catalog sequence pinning when a publisher changes hosting.
        source.location = announcement.location;
    }
    save_config(home, config)
}