nomograph-kit 0.10.2

Verified tool registry manager -- manages developer toolchains from git-based registries
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
mod ci;
mod config;
mod lockfile;
mod mise;
mod platform;
mod registry;
mod source;
mod tool;
mod verify;

use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(
    name = "kit",
    version,
    about = "Verified tool registry manager",
    long_about = "kit manages developer toolchains from git-based registries.\n\n\
        Tools are defined in per-tool TOML files within registries. kit resolves versions\n\
        across multiple registries, generates mise configuration, verifies checksums and\n\
        signatures, and automates upstream update tracking.\n\n\
        Supply chain CI (three-pipeline architecture):\n  \
        kit sense                     # Pipeline 1: detect upstream changes\n  \
        kit evaluate + kit apply      # Pipeline 2: LLM assessment + MR\n  \
        kit verify-registry           # Pipeline 3: validate before merge\n\n\
        User commands:\n  \
        kit setup                     # one-time: create config, add registry\n  \
        kit sync                      # pull registries, generate mise config, verify\n  \
        kit status                    # show installed vs registry, drift detection\n  \
        kit verify                    # re-verify all installed binaries\n  \
        kit add gh cli/cli            # add a tool from GitHub\n  \
        kit pin gh 2.73.0             # pin a version locally\n  \
        kit init --ci                 # create a new registry with CI automation"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// One-time setup: create config, optionally add a registry
    Setup {
        /// Registry URL to add (e.g., https://gitlab.com/nomograph/kits.git)
        #[arg(long)]
        registry: Option<String>,
        /// Name for the registry (defaults to inferring from URL)
        #[arg(long)]
        name: Option<String>,
    },

    /// Pull registries, resolve versions, generate mise config, verify
    Sync {
        /// Accept all changes without confirmation
        #[arg(long)]
        yes: bool,
    },

    /// Show installed vs registry, drift detection
    Status,

    /// Re-verify all installed binaries from scratch
    Verify,

    /// Add a tool to a writable registry
    Add {
        /// Tool name
        name: String,
        /// Source (owner/repo for GitHub/GitLab, package name for npm/crates)
        source: Option<String>,
        /// GitLab project (source is the repo path, e.g. nomograph/muxr)
        #[arg(long)]
        gitlab: bool,
        /// npm package
        #[arg(long)]
        npm: bool,
        /// Crates.io package
        #[arg(long)]
        crates: bool,
    },

    /// Push a tool definition to its registry
    Push {
        /// Tool name
        name: String,
    },

    /// Remove a tool from a writable registry
    Remove {
        /// Tool name
        name: String,
    },

    /// Pin a tool's version or registry source locally
    Pin {
        /// Tool name
        name: String,
        /// Version to pin (omit for registry-only pin)
        version: Option<String>,
        /// Pin to specific registry
        #[arg(long, short)]
        registry: Option<String>,
    },

    /// Remove a local pin
    Unpin {
        /// Tool name
        name: String,
    },

    /// Check upstream for newer versions (CI mode)
    Check {
        /// Registry directory to check
        #[arg(long)]
        registry: Option<PathBuf>,
        /// Output file for update candidates
        #[arg(long, default_value = "updates.json")]
        output: PathBuf,
    },

    /// LLM evaluation of edge-case updates (CI mode)
    Evaluate {
        /// Input file from check phase
        #[arg(long, default_value = "updates.json")]
        input: PathBuf,
        /// Output file for evaluation results
        #[arg(long, default_value = "evaluated.json")]
        output: PathBuf,
    },

    /// Apply evaluated updates to registry TOML files (CI mode)
    ///
    /// Writes updated tool definitions and outputs apply-result.json
    /// for CI to consume. Does not create git branches or MRs.
    Apply {
        /// Input file from evaluate phase
        #[arg(long, default_value = "evaluated.json")]
        input: PathBuf,
        /// Output file for apply results (JSON contract for CI)
        #[arg(long, default_value = "apply-result.json")]
        output: PathBuf,
    },

    /// Detect upstream changes (Pipeline 1: Sense)
    ///
    /// Scans all tools in a registry for upstream updates, downloads and verifies
    /// checksums, queries advisory databases, and produces a classified report.
    /// Always succeeds unless infrastructure is broken (network, auth).
    Sense {
        /// Registry directory to scan
        #[arg(long)]
        registry: Option<PathBuf>,
        /// Output file for the sense report
        #[arg(long, default_value = "sense-report.json")]
        output: PathBuf,
    },

    /// Validate all tool definitions in a registry (Pipeline 3: Verify)
    ///
    /// Loads every TOML file in tools/, validates fields and checksums,
    /// and re-verifies checksums against upstream where possible.
    /// Used in MR pipelines as the deterministic gate before merge.
    VerifyRegistry {
        /// Registry directory to validate
        #[arg(long)]
        registry: Option<PathBuf>,
        /// Output file for verification results
        #[arg(long)]
        output: Option<PathBuf>,
    },

    /// Check installed tools for known security advisories
    Audit,

    /// Initialize kit in current directory (project-local) or create a registry
    Init {
        /// Create a tool registry instead of a project config
        #[arg(long)]
        registry: bool,
        /// Include CI automation template (requires --registry)
        #[arg(long, requires = "registry")]
        ci: bool,
        /// Registry name (requires --registry)
        #[arg(long, default_value = "my-registry", requires = "registry")]
        name: String,
        /// Registry URL for kit.toml (project init)
        #[arg(long)]
        url: Option<String>,
    },

    /// Show changes between local lockfile and current registry
    Diff,

    /// Check upstream for updates and apply interactively
    Upgrade {
        /// Apply all available updates without prompting
        #[arg(long)]
        yes: bool,
        /// Only check a specific tool
        tool: Option<String>,
    },

    /// Generate shell completions
    #[command(hide = true)]
    Completions {
        /// Shell to generate for
        shell: clap_complete::Shell,
    },

    /// Generate man page
    #[command(hide = true)]
    ManPage,
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Setup { registry, name } => cmd_setup(registry.as_deref(), name.as_deref()),
        Commands::Sync { yes } => cmd_sync(yes),
        Commands::Status => cmd_status(),
        Commands::Verify => cmd_verify(),
        Commands::Add {
            name,
            source,
            gitlab,
            npm,
            crates,
        } => cmd_add(&name, source.as_deref(), gitlab, npm, crates),

        Commands::Push { name } => cmd_push(&name),
        Commands::Remove { name } => cmd_remove(&name),
        Commands::Pin {
            name,
            version,
            registry,
        } => cmd_pin(&name, version.as_deref(), registry.as_deref()),
        Commands::Unpin { name } => cmd_unpin(&name),
        Commands::Audit => cmd_audit(),
        Commands::Diff => cmd_diff(),
        Commands::Check { registry, output } => cmd_check(registry.as_deref(), &output),
        Commands::Evaluate { input, output } => cmd_evaluate(&input, &output),
        Commands::Apply { input, output } => cmd_apply(&input, &output),
        Commands::Sense { registry, output } => cmd_sense(registry.as_deref(), &output),
        Commands::VerifyRegistry { registry, output } => {
            cmd_verify_registry(registry.as_deref(), output.as_deref())
        }
        Commands::Init { registry, ci, name, url } => {
            if registry {
                cmd_init_registry(ci, &name)
            } else {
                cmd_init_project(url.as_deref())
            }
        }
        Commands::Upgrade { yes, tool } => cmd_upgrade(yes, tool.as_deref()),
        Commands::Completions { shell } => cmd_completions(shell),
        Commands::ManPage => cmd_man_page(),
    }
}

fn cmd_completions(shell: clap_complete::Shell) -> Result<()> {
    let mut cmd = Cli::command();
    clap_complete::generate(shell, &mut cmd, "kit", &mut std::io::stdout());
    Ok(())
}

fn cmd_man_page() -> Result<()> {
    let cmd = Cli::command();
    let man = clap_mangen::Man::new(cmd);
    man.render(&mut std::io::stdout())
        .context("failed to render man page")?;
    Ok(())
}

fn cmd_diff() -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    // Pull registries to get latest definitions
    for reg in &config.registry {
        match registry::ensure_registry(config, reg) {
            Ok(_) => {}
            Err(e) => {
                eprintln!("  warning: could not pull registry {}: {e}", reg.name);
            }
        }
    }

    // Resolve tools from registries
    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;

    // Load lockfile
    let lock = lockfile::Lockfile::load_from(&ctx.lockfile_path()?)?;

    if lock.entries.is_empty() {
        eprintln!("No lockfile found. Run `kit sync` first.");
        return Ok(());
    }

    // Build the new-resolved tuples for lockfile::diff
    let new_resolved: Vec<(String, String, String)> = resolved
        .iter()
        .map(|rt| {
            (
                rt.def.name.clone(),
                rt.def.version.clone(),
                rt.registry.clone(),
            )
        })
        .collect();

    let changes = lockfile::diff(&lock, &new_resolved);

    if changes.is_empty() {
        eprintln!("kit diff: no changes ({} tools unchanged)", resolved.len());
        return Ok(());
    }

    // Print table header
    let mut changed_count = 0;
    eprintln!();
    eprintln!(
        "  {:<20} {:<12} {:<12} CHANGE",
        "TOOL", "LOCKFILE", "REGISTRY"
    );
    for change in &changes {
        match change {
            lockfile::Change::Updated {
                name, from, to, ..
            } => {
                let bump = detect_bump(from, to);
                eprintln!(
                    "  {:<20} {:<12} {:<12} {} bump",
                    name, from, to, bump
                );
                changed_count += 1;
            }
            lockfile::Change::Added { name } => {
                // Find the version from resolved
                let version = resolved
                    .iter()
                    .find(|rt| rt.def.name == *name)
                    .map(|rt| rt.def.version.as_str())
                    .unwrap_or("?");
                eprintln!(
                    "  {:<20} {:<12} {:<12} new",
                    name, "--", version
                );
                changed_count += 1;
            }
            lockfile::Change::Removed { name } => {
                let version = lock
                    .get(name)
                    .map(|e| e.version.as_str())
                    .unwrap_or("?");
                eprintln!(
                    "  {:<20} {:<12} {:<12} removed",
                    name, version, "--"
                );
                changed_count += 1;
            }
            lockfile::Change::RegistryMoved {
                name, from, to, ..
            } => {
                let version = lock
                    .get(name)
                    .map(|e| e.version.as_str())
                    .unwrap_or("?");
                eprintln!(
                    "  {:<20} {:<12} {:<12} registry: {} -> {}",
                    name, version, version, from, to
                );
                changed_count += 1;
            }
        }
    }

    let unchanged = resolved.len().saturating_sub(changed_count);
    if unchanged > 0 {
        eprintln!("  ({} tools unchanged)", unchanged);
    }
    eprintln!();

    Ok(())
}

fn cmd_upgrade(auto_yes: bool, tool_filter: Option<&str>) -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    // Pull registries to ensure we have latest definitions
    for reg in &config.registry {
        match registry::ensure_registry(config, reg) {
            Ok(_) => {}
            Err(e) => {
                eprintln!("  warning: could not pull registry {}: {e}", reg.name);
            }
        }
    }

    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;

    // Filter to the specific tool if requested
    if let Some(name) = tool_filter {
        resolved.retain(|rt| rt.def.name == name);
        if resolved.is_empty() {
            anyhow::bail!("tool '{name}' not found in any registry");
        }
    }

    eprintln!("kit upgrade: checking {} tools for updates\n", resolved.len());

    struct UpgradeCandidate {
        name: String,
        current: String,
        available: String,
        bump: String,
        registry_dir: PathBuf,
    }

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

    for rt in &resolved {
        eprint!("  {:<20} ", rt.def.name);

        // Skip sources we can't auto-check
        match rt.def.source {
            tool::Source::Direct => {
                eprintln!("{:<12} skip (direct source)", rt.def.version);
                continue;
            }
            tool::Source::Rustup => {
                eprintln!("{:<12} skip (rustup)", rt.def.version);
                continue;
            }
            tool::Source::Npm => {
                eprintln!("{:<12} skip (npm)", rt.def.version);
                continue;
            }
            tool::Source::Crates => {
                eprintln!("{:<12} skip (crates)", rt.def.version);
                continue;
            }
            _ => {}
        }

        let upstream = match rt.def.source {
            tool::Source::Github => {
                let repo = match rt.def.repo.as_deref() {
                    Some(r) => r,
                    None => {
                        eprintln!("{:<12} skip (no repo)", rt.def.version);
                        continue;
                    }
                };
                source::query_github(repo)
            }
            tool::Source::Gitlab => {
                let repo = match rt.def.repo.as_deref() {
                    Some(r) => r,
                    None => {
                        eprintln!("{:<12} skip (no repo)", rt.def.version);
                        continue;
                    }
                };
                source::query_gitlab(repo)
            }
            _ => unreachable!(),
        };

        match upstream {
            Ok(info) => {
                if info.version == rt.def.version {
                    eprintln!("{:<12} up to date", rt.def.version);
                } else {
                    let bump = detect_bump(&rt.def.version, &info.version);
                    eprintln!(
                        "{:<12} -> {:<12} ({})",
                        rt.def.version, info.version, bump
                    );
                    let registry_dir = config.registry_dir()?.join(&rt.registry);
                    candidates.push(UpgradeCandidate {
                        name: rt.def.name.clone(),
                        current: rt.def.version.clone(),
                        available: info.version,
                        bump,
                        registry_dir,
                    });
                }
            }
            Err(e) => {
                eprintln!("{:<12} error ({e:#})", rt.def.version);
            }
        }
    }

    if candidates.is_empty() {
        eprintln!("\nAll tools are up to date.");
        return Ok(());
    }

    // Print summary table
    eprintln!();
    eprintln!(
        "  {:<20} {:<12} {:<12} BUMP",
        "TOOL", "CURRENT", "AVAILABLE"
    );
    for c in &candidates {
        eprintln!(
            "  {:<20} {:<12} {:<12} {}",
            c.name, c.current, c.available, c.bump
        );
    }
    eprintln!();

    // Confirm or auto-apply
    let proceed = if auto_yes {
        true
    } else {
        eprint!("Apply {} update(s)? [y/N] ", candidates.len());
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap_or(0);
        matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
    };

    if !proceed {
        eprintln!("Aborted.");
        return Ok(());
    }

    // Apply updates to TOML files
    for c in &candidates {
        let tool_path = c.registry_dir.join("tools").join(format!("{}.toml", c.name));
        if !tool_path.exists() {
            eprintln!("  warning: {}.toml not found, skipping", c.name);
            continue;
        }

        let raw = std::fs::read_to_string(&tool_path)
            .with_context(|| format!("failed to read {}", tool_path.display()))?;

        let mut doc = raw
            .parse::<toml_edit::DocumentMut>()
            .with_context(|| format!("failed to parse {} as TOML", tool_path.display()))?;

        if let Some(tool_table) = doc.get_mut("tool").and_then(|t| t.as_table_mut()) {
            tool_table["version"] = toml_edit::value(c.available.as_str());
            // Remove stale checksums -- they belong to the old version.
            tool_table.remove("checksums");
        } else {
            eprintln!("  warning: no [tool] table in {}.toml, skipping", c.name);
            continue;
        }

        std::fs::write(&tool_path, doc.to_string())
            .with_context(|| format!("failed to write {}", tool_path.display()))?;

        eprintln!("  updated {}: {} -> {}", c.name, c.current, c.available);
    }

    eprintln!("\nRun `kit sync` to install the updates.");
    Ok(())
}

/// Compare semver components to determine the bump type.
/// Returns true if `to` is an older version than `from` by simple numeric comparison.
fn is_version_downgrade(from: &str, to: &str) -> bool {
    let parse = |v: &str| -> (u64, u64, u64) {
        let parts: Vec<&str> = v.split('.').collect();
        let major = parts.first().and_then(|p| p.parse().ok()).unwrap_or(0);
        let minor = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
        let patch = parts
            .get(2)
            .and_then(|p| p.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|p| p.parse().ok())
            .unwrap_or(0);
        (major, minor, patch)
    };
    parse(to) < parse(from)
}

fn detect_bump(current: &str, available: &str) -> String {
    let parse = |v: &str| -> (u64, u64, u64) {
        let parts: Vec<&str> = v.split('.').collect();
        let major = parts.first().and_then(|p| p.parse().ok()).unwrap_or(0);
        let minor = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(0);
        // Strip any pre-release suffix from the patch component (e.g. "0-beta.1" -> 0)
        let patch = parts
            .get(2)
            .and_then(|p| p.split(|c: char| !c.is_ascii_digit()).next())
            .and_then(|p| p.parse().ok())
            .unwrap_or(0);
        (major, minor, patch)
    };

    let (cm, cmi, _cp) = parse(current);
    let (am, ami, _ap) = parse(available);

    if am != cm {
        "major".to_string()
    } else if ami != cmi {
        "minor".to_string()
    } else {
        "patch".to_string()
    }
}

fn cmd_setup(registry_url: Option<&str>, registry_name: Option<&str>) -> Result<()> {
    let config_path = config::Config::path()?;
    if config_path.exists() {
        // If --registry was passed, add it to the existing config rather than erroring.
        if let Some(url) = registry_url {
            let mut config = config::Config::load()?;
            let name = registry_name.unwrap_or_else(|| {
                url.trim_end_matches(".git")
                    .rsplit('/')
                    .next()
                    .unwrap_or("default")
            });
            if config.registry(name).is_some() {
                eprintln!("Registry '{name}' already configured.");
                return Ok(());
            }
            config.registry.push(config::Registry {
                name: name.to_string(),
                url: url.to_string(),
                branch: "main".to_string(),
                readonly: false,
            });
            config.save()?;
            eprintln!("Added registry '{name}' to {}", config_path.display());
            eprintln!("Run `kit sync` to pull tools and generate mise config.");
            return Ok(());
        }
        eprintln!("Config already exists at {}", config_path.display());
        eprintln!("To add a registry: kit setup --registry <url>");
        return Ok(());
    }

    let config = if let Some(url) = registry_url {
        // Infer registry name from URL if not provided
        let name = registry_name.unwrap_or_else(|| {
            url.trim_end_matches(".git")
                .rsplit('/')
                .next()
                .unwrap_or("default")
        });
        config::Config::default_with_registry(name, url)
    } else {
        // No default registry -- user adds their own
        config::Config {
            settings: config::Settings::default(),
            registry: vec![],
            pins: std::collections::HashMap::new(),
        }
    };
    config.save()?;
    eprintln!("Created {}", config_path.display());
    if registry_url.is_some() {
        eprintln!("Run `kit sync` to pull tools and generate mise config.");
    } else {
        eprintln!("No registry configured. Add one to your config:");
        eprintln!("  [[registry]]");
        eprintln!("  name = \"my-registry\"");
        eprintln!("  url = \"https://gitlab.com/your/registry.git\"");
        eprintln!("\nOr run: kit setup --registry https://gitlab.com/your/registry.git");
    }
    eprintln!();
    eprintln!("Tip: enable shell completions:");
    eprintln!("  kit completions zsh > ~/.zfunc/_kit    # zsh");
    eprintln!("  kit completions bash > /etc/bash_completion.d/kit  # bash");
    Ok(())
}

fn cmd_sync(auto_yes: bool) -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;
    let platform = resolve_platform(config)?;

    eprintln!("kit sync ({}) [{}]", platform, ctx.mode_label());

    // 1. Pull all registries
    for reg in &config.registry {
        eprint!("  pulling {}... ", reg.name);
        match registry::ensure_registry(config, reg) {
            Ok(_) => eprintln!("ok"),
            Err(e) => {
                eprintln!("FAILED: {e}");
                eprintln!("  skipping registry {}", reg.name);
            }
        }
    }

    // 2. Resolve tools across registries
    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;
    eprintln!("  resolved {} tools", resolved.len());

    // 3. Resolve expected checksums for ALL tools (inline + checksum files).
    // This must happen before generating mise config so that a tampered
    // checksum is caught before any binaries are downloaded.
    let mut registry_checksums: std::collections::HashMap<String, Option<String>> =
        std::collections::HashMap::new();
    let tools_with_checksums: Vec<&registry::ResolvedTool> = resolved
        .iter()
        .filter(|rt| {
            rt.def.checksums.contains_key(platform.key())
                || rt.def.checksum.is_some()
        })
        .collect();
    if !tools_with_checksums.is_empty() {
        eprintln!("  resolving checksums for {} tools...", tools_with_checksums.len());
    }
    for rt in &tools_with_checksums {
        // Inline checksums are immediate; checksum files require HTTP.
        if let Some(inline) = rt.def.checksums.get(platform.key()) {
            registry_checksums.insert(rt.def.name.clone(), Some(inline.clone()));
        } else {
            // Download the checksum file for this tool+platform.
            match verify::resolve_expected_checksum(&rt.def, platform) {
                Ok(verify::VerifyResult::Verified { sha256, .. }) => {
                    eprintln!("    {} checksum resolved", rt.def.name);
                    registry_checksums.insert(rt.def.name.clone(), Some(sha256));
                }
                Ok(verify::VerifyResult::Failed { reason, .. }) => {
                    eprintln!("    {} checksum FAILED: {}", rt.def.name, reason);
                    registry_checksums.insert(rt.def.name.clone(), None);
                }
                Ok(verify::VerifyResult::Unavailable { reason }) => {
                    eprintln!("    {} checksum unavailable: {}", rt.def.name, reason);
                    registry_checksums.insert(rt.def.name.clone(), None);
                }
                Err(e) => {
                    eprintln!("    {} checksum error: {:#}", rt.def.name, e);
                    registry_checksums.insert(rt.def.name.clone(), None);
                }
            }
        }
    }

    // 4. Load existing lockfile and check integrity
    let lockfile_path = ctx.lockfile_path()?;
    let old_lock = lockfile::Lockfile::load_from(&lockfile_path)?;

    // S-2: ALWAYS check integrity, even when diff shows no version changes.
    // A compromised registry could change only the checksum (same version).
    // This check must run unconditionally -- it is the primary supply chain defense.
    // Uses resolved checksums (inline + downloaded) so ALL tools are covered.
    for rt in &resolved {
        let sha = registry_checksums
            .get(&rt.def.name)
            .and_then(|opt| opt.as_deref());
        let result = old_lock.check_integrity(
            &rt.def.name,
            &rt.def.version,
            sha,
        );
        if result == lockfile::IntegrityResult::ChecksumChanged {
            anyhow::bail!(
                "SUPPLY CHAIN ALERT: {} has same version but different checksum. \
                 This may indicate a compromised upstream release. Aborting.",
                rt.def.name
            );
        }
    }

    // Build the new-resolved tuples for diff
    let new_tuples: Vec<(String, String, String)> = resolved
        .iter()
        .map(|rt| (rt.def.name.clone(), rt.def.version.clone(), rt.registry.clone()))
        .collect();
    let changes = lockfile::diff(&old_lock, &new_tuples);

    if !changes.is_empty() {
        eprintln!("\n  Changes:");
        for change in &changes {
            eprintln!("    {change}");
        }

        // Warn explicitly on version downgrades (registry pins an older version
        // than what the user already has installed).
        let downgrades: Vec<(&str, &str, &str)> = changes
            .iter()
            .filter_map(|c| {
                if let lockfile::Change::Updated { name, from, to } = c {
                    if is_version_downgrade(from, to) {
                        Some((name.as_str(), from.as_str(), to.as_str()))
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .collect();

        if !downgrades.is_empty() {
            eprintln!("\n  WARNING: the following tools would be downgraded:");
            for (name, from, to) in &downgrades {
                eprintln!("    {name}: {from} -> {to}  (downgrade)");
            }
            if !auto_yes {
                eprintln!("  Use --yes to accept version downgrades.");
                anyhow::bail!("version downgrades detected -- review and re-run with --yes");
            }
        }

        // S-9: registry migration requires confirmation
        let has_registry_moves = changes
            .iter()
            .any(|c| matches!(c, lockfile::Change::RegistryMoved { .. }));

        if has_registry_moves && !auto_yes {
            eprintln!("\n  Tools have moved between registries. Use --yes to accept.");
            anyhow::bail!("registry migration detected -- review and re-run with --yes");
        }
    } else {
        eprintln!("  no changes");
    }

    // 5. Generate mise config (S-3: uses toml crate, not string interpolation)
    let mise_path = ctx.mise_config_path()?;
    if let Some(parent) = mise_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    if ctx.is_project() {
        // Project mode: merge into existing .mise.toml with markers
        let existing = if mise_path.exists() {
            Some(std::fs::read_to_string(&mise_path)?)
        } else {
            None
        };
        let registry_label = config
            .registry
            .first()
            .map(|r| r.name.as_str())
            .unwrap_or("kit");
        let merge_result =
            mise::merge_into(&resolved, existing.as_deref(), registry_label)?;

        if !merge_result.conflicts.is_empty() {
            eprintln!("\n  Conflicts (user tool vs kit):");
            for c in &merge_result.conflicts {
                eprintln!("    {}: user={}, kit={}", c.tool, c.user_version, c.kit_version);
            }
            if !auto_yes {
                eprintln!("  Kit tools will be added alongside user tools.");
                eprintln!("  Remove duplicates from your .mise.toml to resolve.");
            }
        }

        std::fs::write(&mise_path, &merge_result.content)?;
    } else {
        // Global mode: write complete config to conf.d (additive)
        let mise_content = mise::generate(&resolved, config)?;
        std::fs::write(&mise_path, &mise_content)?;

        // One-time migration: clean up old "Managed by kit" config.toml
        let old_global = config
            .mise_config_path()
            .unwrap_or_else(|_| std::path::PathBuf::from(""));
        if old_global != mise_path
            && old_global.exists()
            && std::fs::read_to_string(&old_global)
                .map(|c| c.starts_with("# Managed by kit"))
                .unwrap_or(false)
        {
            let _ = std::fs::write(
                &old_global,
                "# Moved to conf.d/kit.toml by kit. Safe to delete this file.\n",
            );
            eprintln!("  migrated {} -> conf.d/", old_global.display());
        }
    }
    eprintln!("  wrote {}", mise_path.display());

    // 6. Run mise install
    eprint!("  running mise install... ");
    let mise_ok = match std::process::Command::new("mise")
        .args(["install", "--yes", "--quiet"])
        .status()
    {
        Ok(s) if s.success() => {
            eprintln!("ok");
            true
        }
        Ok(s) => {
            eprintln!("warning: mise install exited {s}");
            false
        }
        Err(e) => {
            eprintln!("warning: could not run mise: {e}");
            false
        }
    };

    // F12: warn clearly if mise failed -- lockfile will still be updated
    // but the `installed` field will reflect the failure.
    if !mise_ok {
        eprintln!("  warning: lockfile updated but mise install failed -- tools may not be installed");
    }

    // 7. Update lockfile
    // T3-1: store registry checksums and binary checksums separately.
    // Registry checksums (inline + downloaded) are used by S-2 integrity checks.
    // Binary checksums (F6) are computed from installed binaries.
    let mise_installs = dirs::home_dir()
        .unwrap_or_default()
        .join(".local/share/mise/installs");

    let mut new_lock = lockfile::Lockfile {
        entries: std::collections::HashMap::new(),
    };
    for rt in &resolved {
        let url = rt.def.url_for(platform).unwrap_or_default();
        // Registry checksum (inline or downloaded) -- for S-2 comparison
        let registry_sha = registry_checksums
            .get(&rt.def.name)
            .and_then(|opt| opt.as_deref());
        // F6: compute actual binary checksum from installed location
        let binary_sha = if mise_ok {
            resolve_installed_sha(&rt.def, platform, &mise_installs)
        } else {
            None
        };
        let method = verification_method(&rt.def);

        new_lock.set(
            &rt.def.name,
            lockfile::new_entry(
                &rt.def.version,
                &rt.registry,
                if url.is_empty() { None } else { Some(url.as_str()) },
                registry_sha,
                binary_sha.as_deref(),
                method,
            ),
        );
    }
    new_lock.save_to(&lockfile_path)?;

    eprintln!("\n  {} tools synced.", resolved.len());
    Ok(())
}

fn cmd_status() -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;
    let lock = lockfile::Lockfile::load_from(&ctx.lockfile_path()?)?;

    eprintln!("kit status [{}]\n", ctx.mode_label());

    println!(
        "  {:<20} {:<12} {:<10} {:<10} {:<10} {:<12}",
        "TOOL", "VERSION", "STATUS", "SOURCE", "TIER", "VERIFY"
    );

    // Kit-managed tools
    for rt in &resolved {
        let (status, verify_method) = match lock.get(&rt.def.name) {
            Some(entry) => {
                let s = if entry.version == rt.def.version {
                    "current"
                } else {
                    "outdated"
                };
                (s, entry.verification_method.as_str())
            }
            None => ("new", ""),
        };

        let pinned = if config.pins.contains_key(&rt.def.name) {
            " (pinned)"
        } else {
            ""
        };

        println!(
            "  {:<20} {:<12} {:<10} {:<10} {:<10} {verify_method}{pinned}",
            rt.def.name, rt.def.version, status,
            format!("kit({})", rt.registry), rt.def.tier
        );
    }

    // User-managed tools (from .mise.toml outside kit markers)
    if ctx.is_project() {
        let mise_path = ctx.mise_config_path()?;
        if let Ok(user_tools) = mise::user_managed_tools(&mise_path) {
            let kit_names: std::collections::HashSet<&str> =
                resolved.iter().map(|rt| rt.def.name.as_str()).collect();
            for (name, version) in &user_tools {
                if !kit_names.contains(name.as_str()) {
                    println!(
                        "  {:<20} {:<12} {:<10} {:<10} {:<10}",
                        name, version, "", "user", ""
                    );
                }
            }
        }
    }

    Ok(())
}

fn cmd_verify() -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;
    let platform = resolve_platform(config)?;

    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;

    let mut pass = 0u32;
    let mut fail = 0u32;
    let mut skip = 0u32;

    for rt in &resolved {
        eprint!("  {:<20} {:<12} ", rt.def.name, rt.def.version);

        // Tools installed via package managers (npm, crates, rustup) don't have
        // download URLs for checksum verification -- skip them early.
        if matches!(
            rt.def.source,
            tool::Source::Npm | tool::Source::Crates | tool::Source::Rustup
        ) {
            eprintln!("skip  (package-manager install, no binary checksum)");
            skip += 1;
            continue;
        }

        // Resolve the binary path via `mise which`.
        let binary_path = match verify::resolve_binary_path(&rt.def) {
            Some(p) => p,
            None => {
                eprintln!("skip  (binary not found via mise)");
                skip += 1;
                continue;
            }
        };

        match verify::verify_tool(&rt.def, platform, &binary_path) {
            Ok(verify::VerifyResult::Verified { method, .. }) => {
                eprintln!("ok  ({method})");
                pass += 1;
            }
            Ok(verify::VerifyResult::Failed { method, reason }) => {
                eprintln!("FAIL  ({method}: {reason})");
                fail += 1;
            }
            Ok(verify::VerifyResult::Unavailable { reason }) => {
                eprintln!("skip  ({reason})");
                skip += 1;
            }
            Err(e) => {
                eprintln!("error  ({e})");
                skip += 1;
            }
        }
    }

    eprintln!("\n  {pass} verified, {fail} failed, {skip} skipped");
    if fail > 0 {
        anyhow::bail!("{fail} tools failed verification");
    }
    Ok(())
}

fn cmd_add(name: &str, source: Option<&str>, gitlab: bool, npm: bool, crates: bool) -> Result<()> {
    tool::validate_name(name)?;
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    let reg = config
        .registry
        .iter()
        .find(|r| !r.readonly)
        .ok_or_else(|| anyhow::anyhow!("no writable registry configured"))?;

    let registry_dir = config.registry_dir()?.join(&reg.name);
    let tools_dir = registry_dir.join("tools");
    let tool_path = tools_dir.join(format!("{name}.toml"));

    if tool_path.exists() {
        anyhow::bail!("{name} already exists in registry {}", reg.name);
    }

    let (source_type, repo, pkg, crate_name) = if crates {
        (tool::Source::Crates, None, None, source.map(|s| s.to_string()))
    } else if npm {
        (tool::Source::Npm, None, source.map(|s| s.to_string()), None)
    } else if gitlab {
        (tool::Source::Gitlab, source.map(|s| s.to_string()), None, None)
    } else {
        (tool::Source::Github, source.map(|s| s.to_string()), None, None)
    };

    // Query upstream for version, assets, and checksum info.
    let upstream = match source_type {
        tool::Source::Github => {
            let repo_str = source
                .ok_or_else(|| anyhow::anyhow!("GitHub source requires owner/repo argument"))?;
            eprint!("  querying GitHub {repo_str}... ");
            match source::query_github(repo_str) {
                Ok(info) => {
                    eprintln!("ok ({})", info.version);
                    Some(info)
                }
                Err(e) => {
                    eprintln!("failed ({e:#})");
                    eprintln!("  falling back to skeleton definition");
                    None
                }
            }
        }
        tool::Source::Gitlab => {
            let repo_str = source.ok_or_else(|| {
                anyhow::anyhow!("GitLab source requires owner/repo path argument")
            })?;
            eprint!("  querying GitLab {repo_str}... ");
            match source::query_gitlab(repo_str) {
                Ok(info) => {
                    eprintln!(
                        "ok ({}, project_id={})",
                        info.version,
                        info.project_id.unwrap_or(0)
                    );
                    Some(info)
                }
                Err(e) => {
                    eprintln!("failed ({e:#})");
                    eprintln!("  falling back to skeleton definition");
                    None
                }
            }
        }
        tool::Source::Npm => {
            let pkg_name = source.unwrap_or(name);
            eprint!("  querying npm {pkg_name}... ");
            match source::query_npm(pkg_name) {
                Ok(info) => {
                    eprintln!("ok ({})", info.version);
                    Some(info)
                }
                Err(e) => {
                    eprintln!("failed ({e:#})");
                    eprintln!("  falling back to skeleton definition");
                    None
                }
            }
        }
        tool::Source::Crates => {
            let crate_str = source.unwrap_or(name);
            eprint!("  querying crates.io {crate_str}... ");
            match source::query_crates(crate_str) {
                Ok(info) => {
                    eprintln!("ok ({})", info.version);
                    Some(info)
                }
                Err(e) => {
                    eprintln!("failed ({e:#})");
                    eprintln!("  falling back to skeleton definition");
                    None
                }
            }
        }
        _ => None,
    };

    // Detect aqua registry membership for GitHub tools.
    let aqua = if source_type == tool::Source::Github {
        eprint!("  detecting aqua registry... ");
        match source::detect_aqua(name, source) {
            Some(id) => {
                eprintln!("found ({id})");
                Some(id)
            }
            None => {
                eprintln!("not found");
                None
            }
        }
    } else {
        None
    };

    // Determine tier: "own" if the tool's namespace matches the registry namespace.
    let resolved_project_id = upstream.as_ref().and_then(|u| u.project_id);
    let tier = detect_tier(gitlab, source, &reg.url, &registry_dir);

    // Build the tool definition, populated from upstream when available.
    let (version, tag_prefix, assets, checksum) = match &upstream {
        Some(info) => {
            let templated_assets = source::templatize_assets(&info.assets, &info.version);
            let checksum_cfg = info.checksum_file.as_ref().map(|f| tool::ChecksumConfig {
                file: Some(source::templatize_checksum(f, &info.version)),
                format: info
                    .checksum_format
                    .clone()
                    .unwrap_or(tool::ChecksumFormat::Sha256),
            });
            (
                info.version.clone(),
                info.tag_prefix.clone(),
                templated_assets,
                checksum_cfg,
            )
        }
        None => (
            "0.0.0".to_string(),
            "v".to_string(),
            std::collections::HashMap::new(),
            None,
        ),
    };

    // Auto-detect cosign signature config from upstream.
    let signature = upstream
        .as_ref()
        .and_then(|info| info.signature_method.as_ref())
        .map(|method| match method.as_str() {
            "cosign-keyless" if gitlab => {
                let repo_path = source.unwrap_or("");
                tool::SignatureConfig {
                    method: tool::SignatureMethod::CosignKeyless,
                    issuer: Some("https://gitlab.com".to_string()),
                    identity: Some(format!("https://gitlab.com/{repo_path}")),
                }
            }
            "cosign-keyless" => tool::SignatureConfig {
                method: tool::SignatureMethod::CosignKeyless,
                issuer: None,
                identity: None,
            },
            _ => tool::SignatureConfig {
                method: tool::SignatureMethod::None,
                issuer: None,
                identity: None,
            },
        });

    let file = tool::ToolFile {
        tool: tool::ToolDef {
            name: name.to_string(),
            description: None,
            source: source_type,
            version,
            tag_prefix,
            bin: Some(name.to_string()),
            tier,
            repo: repo.clone(),
            project_id: resolved_project_id,
            package: pkg,
            crate_name,
            aqua,
            assets,
            checksum,
            checksums: std::collections::HashMap::new(),
            signature,
        },
    };

    let content = format!(
        "# Tool definition for {name}\n\
         # Review the detected values, then `kit push {name}`\n\n\
         {}",
        toml::to_string_pretty(&file)?
    );

    std::fs::create_dir_all(&tools_dir)?;
    std::fs::write(&tool_path, content)?;

    eprintln!("\nCreated {}", tool_path.display());

    // Print what was detected for user verification.
    if let Some(info) = &upstream {
        eprintln!("\n  Detected from upstream:");
        eprintln!("    version:     {}", info.version);
        eprintln!("    tag_prefix:  {:?}", info.tag_prefix);
        if let Some(pid) = info.project_id {
            eprintln!("    project_id:  {pid}");
        }
        if let Some(a) = info.assets.get("macos-arm64") {
            eprintln!("    macos-arm64: {a}");
        }
        if let Some(a) = info.assets.get("linux-x64") {
            eprintln!("    linux-x64:   {a}");
        }
        if let Some(f) = &info.checksum_file {
            eprintln!("    checksum:    {f}");
        }
        if let Some(m) = &info.signature_method {
            eprintln!("    signature:   {m}");
        }
        let missing: Vec<&str> = ["macos-arm64", "linux-x64"]
            .iter()
            .filter(|p| !info.assets.contains_key(**p))
            .copied()
            .collect();
        if !missing.is_empty() {
            eprintln!(
                "    warning: no assets detected for: {}",
                missing.join(", ")
            );
        }
    }
    eprintln!("    tier:        {tier}");
    if let Some(ref a) = file.tool.aqua {
        eprintln!("    aqua:        {a}");
    }

    eprintln!("\nReview the definition, then run `kit push {name}`");
    Ok(())
}

/// Detect tier based on whether the tool's source namespace matches the registry namespace.
fn detect_tier(
    gitlab: bool,
    source: Option<&str>,
    registry_url: &str,
    registry_dir: &std::path::Path,
) -> tool::Tier {
    // Try to get the namespace from _meta.toml, falling back to URL extraction.
    let registry_ns = tool::load_registry_meta(registry_dir)
        .ok()
        .and_then(|meta| {
            // Use the maintainer field if set, otherwise the registry name.
            meta.registry.maintainer.or(Some(meta.registry.name))
        });

    // Fall back to extracting namespace from the registry URL.
    let url_ns = source::extract_registry_namespace(registry_url);
    let effective_ns = registry_ns.or(url_ns);

    if let (Some(ns), Some(src)) = (effective_ns, source)
        && let Some(src_ns) = src.split('/').next()
        && src_ns == ns
    {
        return if gitlab {
            // GitLab tools from the same org are "own" -- you control the release pipeline.
            tool::Tier::Own
        } else {
            // GitHub tools from the same org are "high" trust.
            tool::Tier::High
        };
    }

    tool::Tier::Low
}

fn cmd_push(name: &str) -> Result<()> {
    tool::validate_name(name)?;
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    let reg = config
        .registry
        .iter()
        .find(|r| !r.readonly)
        .ok_or_else(|| anyhow::anyhow!("no writable registry configured"))?;

    let registry_dir = config.registry_dir()?.join(&reg.name);
    let tool_path = registry_dir.join("tools").join(format!("{name}.toml"));

    if !tool_path.exists() {
        anyhow::bail!("{name}.toml not found in registry {}", reg.name);
    }

    // Validate before pushing
    let _def = tool::ToolDef::load(&tool_path)?;

    // Git add + commit via CLI
    let relative = std::path::Path::new("tools").join(format!("{name}.toml"));
    let add_status = std::process::Command::new("git")
        .args(["add", &relative.to_string_lossy()])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git add")?;
    if !add_status.success() {
        anyhow::bail!("git add failed for {name}.toml");
    }

    let message = format!("kit: add {name}");
    let commit_status = std::process::Command::new("git")
        .args(["commit", "-m", &message])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git commit")?;
    if !commit_status.success() {
        anyhow::bail!("git commit failed for {name}.toml");
    }

    // Push via git CLI (needs system credential helpers)
    let status = std::process::Command::new("git")
        .args(["push", "--quiet", "origin", &reg.branch])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git push")?;

    if !status.success() {
        anyhow::bail!("git push failed for registry {}", reg.name);
    }

    eprintln!("Pushed {name} to {}", reg.name);
    Ok(())
}

fn cmd_remove(name: &str) -> Result<()> {
    tool::validate_name(name)?;
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    let reg = config
        .registry
        .iter()
        .find(|r| !r.readonly)
        .ok_or_else(|| anyhow::anyhow!("no writable registry configured"))?;

    let registry_dir = config.registry_dir()?.join(&reg.name);
    let tool_path = registry_dir.join("tools").join(format!("{name}.toml"));

    if !tool_path.exists() {
        anyhow::bail!("{name}.toml not found in registry {}", reg.name);
    }

    std::fs::remove_file(&tool_path)
        .with_context(|| format!("failed to delete {}", tool_path.display()))?;

    // Git add + commit + push (same pattern as cmd_push)
    let relative = std::path::Path::new("tools").join(format!("{name}.toml"));
    let add_status = std::process::Command::new("git")
        .args(["add", &relative.to_string_lossy()])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git add")?;
    if !add_status.success() {
        anyhow::bail!("git add failed for {name}.toml");
    }

    let message = format!("kit: remove {name}");
    let commit_status = std::process::Command::new("git")
        .args(["commit", "-m", &message])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git commit")?;
    if !commit_status.success() {
        anyhow::bail!("git commit failed for {name}.toml");
    }

    let status = std::process::Command::new("git")
        .args(["push", "--quiet", "origin", &reg.branch])
        .current_dir(&registry_dir)
        .status()
        .context("failed to run git push")?;

    if !status.success() {
        anyhow::bail!("git push failed for registry {}", reg.name);
    }

    eprintln!("Removed {name} from {}", reg.name);
    Ok(())
}

fn cmd_audit() -> Result<()> {
    let ctx = config::ConfigContext::resolve()?;
    let config = &ctx.config;

    let mut resolved = registry::resolve_tools(config)?;
    registry::apply_pins(&mut resolved, &config.pins, config)?;

    eprintln!("kit audit: checking {} tools for security advisories\n", resolved.len());

    let mut findings: Vec<(String, String, ci::Advisory)> = Vec::new();

    for rt in &resolved {
        eprint!("  {:<20} {:<12} ", rt.def.name, rt.def.version);

        let advs = match rt.def.source {
            tool::Source::Github => audit_github(&rt.def),
            tool::Source::Npm => audit_npm(&rt.def),
            _ => {
                eprintln!("skip (no advisory source for {:?})", rt.def.source);
                continue;
            }
        };

        match advs {
            Ok(ref list) if list.is_empty() => {
                eprintln!("ok");
            }
            Ok(list) => {
                eprintln!("{} advisory(ies)", list.len());
                for a in list {
                    findings.push((rt.def.name.clone(), rt.def.version.clone(), a));
                }
            }
            Err(e) => {
                eprintln!("error ({e:#})");
            }
        }
    }

    if findings.is_empty() {
        eprintln!("\nNo advisories found.");
        return Ok(());
    }

    eprintln!("\n{}", "=".repeat(80));
    eprintln!(
        "  {:<20} {:<12} {:<20} {:<12} SUMMARY",
        "TOOL", "VERSION", "CVE", "SEVERITY"
    );
    eprintln!("{}", "-".repeat(80));
    for (tool_name, version, adv) in &findings {
        let summary = &adv.summary;
        eprintln!(
            "  {tool_name:<20} {version:<12} {:<20} {:<12} {summary}",
            adv.id, adv.severity
        );
    }
    eprintln!("{}", "=".repeat(80));
    eprintln!("{} advisory(ies) found.", findings.len());

    let has_critical = findings
        .iter()
        .any(|(_, _, a)| a.severity == "high" || a.severity == "critical");

    if has_critical {
        anyhow::bail!("high or critical advisories found -- action required");
    }

    Ok(())
}

/// Query GitHub Advisory Database for a GitHub-sourced tool.
fn audit_github(def: &tool::ToolDef) -> Result<Vec<ci::Advisory>> {
    let repo = def
        .repo
        .as_deref()
        .context("github source requires 'repo' field")?;

    let escaped_version = def.version.replace('.', "\\\\.");
    let jq_filter = format!(
        r#"[.[] | select(.vulnerabilities[]?.vulnerable_version_range | test("{escaped_version}"))]"#
    );

    let output = std::process::Command::new("gh")
        .args([
            "api",
            &format!("repos/{repo}/security-advisories"),
            "--jq",
            &jq_filter,
        ])
        .output()
        .context("failed to execute gh")?;

    if !output.status.success() {
        // Some repos have no advisories endpoint -- not an error
        return Ok(vec![]);
    }

    let text = String::from_utf8_lossy(&output.stdout);
    let trimmed = text.trim();
    if trimmed.is_empty() || trimmed == "[]" || trimmed == "null" {
        return Ok(vec![]);
    }

    let raw: Vec<serde_json::Value> = serde_json::from_str(trimmed).unwrap_or_default();

    Ok(raw
        .iter()
        .map(|a| ci::Advisory {
            id: a["ghsa_id"].as_str().unwrap_or("?").to_string(),
            severity: a["severity"].as_str().unwrap_or("?").to_string(),
            summary: a["summary"]
                .as_str()
                .unwrap_or("?")
                .chars()
                .take(200)
                .collect(),
        })
        .collect())
}

/// Query GitHub Advisory Database for an npm package.
fn audit_npm(def: &tool::ToolDef) -> Result<Vec<ci::Advisory>> {
    let pkg = def.package.as_deref().unwrap_or(&def.name);
    let version = &def.version;

    let output = std::process::Command::new("gh")
        .args([
            "api",
            &format!(
                "/advisories?ecosystem=npm&package={pkg}&affects={version}"
            ),
        ])
        .output()
        .context("failed to execute gh")?;

    if !output.status.success() {
        return Ok(vec![]);
    }

    let text = String::from_utf8_lossy(&output.stdout);
    let trimmed = text.trim();
    if trimmed.is_empty() || trimmed == "[]" || trimmed == "null" {
        return Ok(vec![]);
    }

    let raw: Vec<serde_json::Value> = serde_json::from_str(trimmed).unwrap_or_default();

    Ok(raw
        .iter()
        .map(|a| ci::Advisory {
            id: a["ghsa_id"]
                .as_str()
                .or_else(|| a["cve_id"].as_str())
                .unwrap_or("?")
                .to_string(),
            severity: a["severity"].as_str().unwrap_or("?").to_string(),
            summary: a["summary"]
                .as_str()
                .unwrap_or("?")
                .chars()
                .take(200)
                .collect(),
        })
        .collect())
}

fn cmd_pin(name: &str, version: Option<&str>, registry: Option<&str>) -> Result<()> {
    if let Some(v) = version {
        tool::validate_version(v)
            .with_context(|| format!("invalid pin version for '{name}'"))?;
    }

    let mut ctx = config::ConfigContext::resolve()?;

    let pin = config::Pin {
        version: version.map(|s| s.to_string()),
        registry: registry.map(|s| s.to_string()),
    };

    ctx.config.pins.insert(name.to_string(), pin);
    ctx.save_config()?;

    match (version, registry) {
        (Some(v), Some(r)) => eprintln!("Pinned {name} to {v} from {r}"),
        (Some(v), None) => eprintln!("Pinned {name} to {v}"),
        (None, Some(r)) => eprintln!("Pinned {name} to registry {r}"),
        (None, None) => eprintln!("Pin created for {name} (no version or registry specified)"),
    }

    eprintln!("Run `kit sync` to apply.");
    Ok(())
}

fn cmd_unpin(name: &str) -> Result<()> {
    let mut ctx = config::ConfigContext::resolve()?;

    if ctx.config.pins.remove(name).is_some() {
        ctx.save_config()?;
        eprintln!("Unpinned {name}. Run `kit sync` to apply.");
    } else {
        eprintln!("{name} is not pinned.");
    }

    Ok(())
}

fn cmd_check(registry: Option<&std::path::Path>, output: &std::path::Path) -> Result<()> {
    let registry_dir = registry
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    ci::check(&registry_dir, output)
}

fn cmd_evaluate(input: &std::path::Path, output: &std::path::Path) -> Result<()> {
    ci::evaluate(input, output)
}

fn cmd_apply(input: &std::path::Path, output: &std::path::Path) -> Result<()> {
    ci::apply(input, output)
}

fn cmd_sense(registry: Option<&std::path::Path>, output: &std::path::Path) -> Result<()> {
    let registry_dir = registry
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    ci::sense(&registry_dir, output)
}

fn cmd_verify_registry(
    registry: Option<&std::path::Path>,
    output: Option<&std::path::Path>,
) -> Result<()> {
    let registry_dir = registry
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    ci::verify_registry(&registry_dir, output)
}

/// Initialize a project-local kit.toml in the current directory.
/// Seeds registry entries from the global config if it exists.
fn cmd_init_project(url: Option<&str>) -> Result<()> {
    let kit_toml = std::path::Path::new("kit.toml");
    if kit_toml.exists() {
        anyhow::bail!("kit.toml already exists in this directory");
    }

    // Try to seed from global config
    let registries = if let Some(url) = url {
        let name = url
            .trim_end_matches(".git")
            .rsplit('/')
            .next()
            .unwrap_or("default");
        format!(
            "[[registry]]\nname = \"{name}\"\nurl = \"{url}\"\nbranch = \"main\"\nreadonly = true\n"
        )
    } else if let Ok(global) = config::Config::load() {
        // Seed from global config
        let mut sections = Vec::new();
        for reg in &global.registry {
            sections.push(format!(
                "[[registry]]\nname = \"{}\"\nurl = \"{}\"\nbranch = \"{}\"\nreadonly = {}\n",
                reg.name, reg.url, reg.branch, reg.readonly
            ));
        }
        if sections.is_empty() {
            "# Add a registry:\n# [[registry]]\n# name = \"my-registry\"\n# url = \"https://gitlab.com/your/registry.git\"\n# branch = \"main\"\n# readonly = true\n".to_string()
        } else {
            sections.join("\n")
        }
    } else {
        "# Add a registry:\n# [[registry]]\n# name = \"my-registry\"\n# url = \"https://gitlab.com/your/registry.git\"\n# branch = \"main\"\n# readonly = true\n".to_string()
    };

    let content = format!(
        "# Kit project configuration\n# https://gitlab.com/nomograph/kit\n\n{registries}\n[pins]\n"
    );
    std::fs::write(kit_toml, &content)?;
    eprintln!("Created kit.toml");
    eprintln!("Run `kit sync` to pull tools and generate .mise.toml");
    Ok(())
}

fn cmd_init_registry(ci: bool, name: &str) -> Result<()> {
    tool::validate_name(name)
        .context("invalid registry name (must be lowercase alphanumeric + hyphens)")?;
    let tools_dir = std::path::Path::new("tools");
    if tools_dir.exists() {
        anyhow::bail!("tools/ directory already exists");
    }

    std::fs::create_dir_all(tools_dir)?;

    let meta = format!(
        "[registry]\nname = \"{name}\"\ndescription = \"\"\nmaintainer = \"\"\n\n\
         [policy]\nauto_merge_tiers = [\"low\"]\n\
         auto_merge_bump = [\"patch\", \"minor\"]\n\
         auto_merge_requires_checksum = true\n"
    );
    std::fs::write(tools_dir.join("_meta.toml"), meta)?;
    eprintln!("Created tools/_meta.toml");

    std::fs::write(
        ".gitignore",
        "updates.json\nupdates.json.sha256\nevaluated.json\nevaluated.json.sha256\nsense-report.json\nsense-report.json.sha256\n__pycache__/\n",
    )?;

    if ci {
        std::fs::write(".gitlab-ci.yml", CI_TEMPLATE)?;
        eprintln!("Created .gitlab-ci.yml");
    }

    eprintln!("Registry initialized. Add tools with `kit add <name> <source>`.");
    Ok(())
}

// -- Helpers --

fn resolve_platform(config: &config::Config) -> Result<platform::Platform> {
    match &config.settings.platform {
        Some(p) => platform::Platform::from_key(p)
            .ok_or_else(|| anyhow::anyhow!("unknown platform: {p}")),
        None => platform::Platform::detect(),
    }
}

fn verification_method(def: &tool::ToolDef) -> &'static str {
    match &def.signature {
        Some(sig) => match sig.method {
            tool::SignatureMethod::CosignKeyless => "cosign",
            tool::SignatureMethod::GithubAttestation => "attestation",
            tool::SignatureMethod::None => has_checksum(def),
        },
        None => has_checksum(def),
    }
}

fn has_checksum(def: &tool::ToolDef) -> &'static str {
    if def.checksum.is_some() || !def.checksums.is_empty() {
        "checksum"
    } else {
        "none"
    }
}

/// F6: compute the actual SHA256 of an installed binary.
/// Returns None if the binary isn't found (not installed or different layout).
fn resolve_installed_sha(
    def: &tool::ToolDef,
    _platform: platform::Platform,
    _mise_installs: &std::path::Path,
) -> Option<String> {
    // Use `mise which` for authoritative binary resolution.
    if let Some(bin_path) = verify::resolve_binary_path(def) {
        return verify::compute_sha256(&bin_path).ok();
    }

    // Binary not found -- return None rather than falling back to registry
    // checksums, which are expected values not actual installed hashes.
    None
}

const CI_TEMPLATE: &str = r#"# kit registry CI -- three-pipeline supply chain architecture
#
# Pipeline 1: Sense   (scheduled) -- detect upstream changes, produce report
# Pipeline 2: Respond (scheduled) -- LLM evaluation, apply updates, open MR
# Pipeline 3: Verify  (MR)        -- independent validation, gate before merge
#
# kit CLI is pure: it writes files and JSON. CI owns all git/MR lifecycle.

stages:
  - sense
  - respond
  - verify

variables:
  CLAUDE_MODEL: "claude-haiku-4-5-20251001"

# ---------------------------------------------------------------------------
# Pipeline 1: Sense (scheduled -- detect upstream changes)
# ---------------------------------------------------------------------------

kit:sense:
  stage: sense
  image: rust:1.93-bookworm
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
    - if: $CI_PIPELINE_SOURCE == "web"
  before_script:
    - cargo install --locked nomograph-kit || true
  script:
    - kit sense --registry . --output sense-report.json
    - sha256sum sense-report.json > sense-report.json.sha256
  artifacts:
    paths: [sense-report.json, sense-report.json.sha256]
    expire_in: 1 day

# ---------------------------------------------------------------------------
# Pipeline 2: Respond (after sense -- evaluate, apply, create MR)
# ---------------------------------------------------------------------------

kit:respond:
  stage: respond
  image: rust:1.93-bookworm
  needs: [kit:sense]
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
    - if: $CI_PIPELINE_SOURCE == "web"
  before_script:
    - cargo install --locked nomograph-kit || true
    - apt-get update -qq && apt-get install -y -qq git jq > /dev/null
    - git config user.email "kit-bot@localhost"
    - git config user.name "kit"
  script:
    # --- kit CLI (pure data transforms) ---
    - sha256sum -c sense-report.json.sha256
    - kit evaluate --input sense-report.json --output evaluated.json
    - kit apply --input evaluated.json --output apply-result.json
    # --- CI orchestration (git/MR lifecycle) ---
    - |
      APPLIED=$(jq '.applied | length' apply-result.json)
      if [ "$APPLIED" -eq 0 ]; then
        echo "No updates to apply"
        exit 0
      fi
    # Close stale kit/* MRs
    - |
      STALE=$(glab mr list --source-branch "kit/" -F json 2>/dev/null \
        | jq -r '.[].iid' || true)
      for iid in $STALE; do
        echo "Closing stale MR !${iid}"
        glab mr close "$iid" || true
      done
    # Branch, commit, push
    - BRANCH=$(jq -r '.branch_hint' apply-result.json)
    - git checkout -b "$BRANCH"
    - git add tools/*.toml
    - jq -r '.commit_message' apply-result.json | git commit -F -
    - git push -u origin "$BRANCH"
    # Create MR
    - |
      MR_TITLE=$(jq -r '.mr_title' apply-result.json)
      MR_BODY=$(jq -r '.mr_body' apply-result.json)
      AUTO=$(jq -r '.auto_merge_eligible' apply-result.json)
      glab mr create --title "$MR_TITLE" --description "$MR_BODY" \
        --source-branch "$BRANCH" --remove-source-branch --yes
      if [ "$AUTO" = "true" ]; then
        MR_IID=$(glab mr list --source-branch "$BRANCH" -F json | jq -r '.[0].iid')
        echo "Enabling auto-merge on MR !${MR_IID}"
        glab mr merge "$MR_IID" --auto --remove-source-branch || \
          echo "warning: auto-merge failed, MR needs manual merge"
      fi

# ---------------------------------------------------------------------------
# Pipeline 3: Verify (triggered by MR -- independent validation)
# ---------------------------------------------------------------------------

kit:verify:
  stage: verify
  image: rust:1.93-bookworm
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  before_script:
    - cargo install --locked nomograph-kit || true
  script:
    - kit verify-registry --registry .
"#;

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

    #[test]
    fn detect_bump_major() {
        assert_eq!(detect_bump("2.5.0", "3.0.6"), "major");
        assert_eq!(detect_bump("1.0.0", "2.0.0"), "major");
    }

    #[test]
    fn detect_bump_minor() {
        assert_eq!(detect_bump("1.85.0", "1.86.0"), "minor");
        assert_eq!(detect_bump("1.56.0", "1.91.0"), "minor");
    }

    #[test]
    fn detect_bump_patch() {
        assert_eq!(detect_bump("2.5.0", "2.5.1"), "patch");
        assert_eq!(detect_bump("1.0.0", "1.0.3"), "patch");
    }

    #[test]
    fn detect_bump_prerelease() {
        assert_eq!(detect_bump("1.0.0-beta.1", "1.0.0"), "patch");
        assert_eq!(detect_bump("1.0.0", "2.0.0-rc.1"), "major");
    }
}