hf2q 0.1.10

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
//! CLI argument parsing and validation via clap derive API.
//!
//! All environment variable resolution happens here at startup.
//! No global state — CLI args produce a `ConvertConfig` that flows through the pipeline.

use std::path::PathBuf;

use clap::{Parser, Subcommand};
use clap_complete::Shell;

pub(crate) mod complete;
pub(crate) mod completion_install;
pub(crate) mod completion_receipt;
pub(crate) mod completion_startup;

/// hf2q — Pure Rust CLI for converting HuggingFace models to hardware-optimized formats.
#[derive(Parser, Debug)]
#[command(name = "hf2q", version, about, long_about = None)]
pub struct Cli {
    /// Increase logging verbosity (-v, -vv, -vvv)
    #[arg(short, long, action = clap::ArgAction::Count, global = true)]
    pub verbose: u8,

    /// Log output format. `text` (default) emits human-readable colored
    /// output on stderr; `json` emits one JSON object per line (structured
    /// ingest for Loki / Datadog / etc.). ADR-005 Decision #11.
    #[arg(long, value_enum, global = true, default_value = "text")]
    pub log_format: LogFormat,

    /// Explicit log level override. When unset, verbosity (`-v`) controls
    /// the level. When set, this wins and `-v` is ignored. ADR-005
    /// Decision #11.
    #[arg(long, value_enum, global = true)]
    pub log_level: Option<LogLevel>,

    /// Absolute hf2q state root containing config.toml. Defaults to
    /// `$HOME/.hf2q`. Setup writes this file; convert and serve read it.
    #[arg(
        long,
        value_name = "ABSOLUTE_PATH",
        value_hint = clap::ValueHint::DirPath,
        global = true
    )]
    pub state_root: Option<PathBuf>,

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

/// Log output format (Decision #11).
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum LogFormat {
    /// Human-readable colored stderr (ANSI only when stderr is a TTY).
    Text,
    /// One JSON object per log event (structured ingest).
    Json,
}

/// Log level override (Decision #11). When `None`, `-v` flag controls it.
#[derive(Debug, Clone, Copy, clap::ValueEnum, PartialEq, Eq)]
pub enum LogLevel {
    Debug,
    Info,
    Warn,
    Error,
}

impl LogLevel {
    pub fn as_str(self) -> &'static str {
        match self {
            LogLevel::Debug => "debug",
            LogLevel::Info => "info",
            LogLevel::Warn => "warn",
            LogLevel::Error => "error",
        }
    }
}

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Internal bootstrap used only by the reviewed standalone installer.
    #[command(name = "__standalone-install", hide = true)]
    StandaloneInstall(StandaloneInstallArgs),

    /// Internal request-cancellable boundary for one authenticated hosted
    /// GGUF transfer selected by the diagnostic control plane.
    #[command(name = "__fetch-hub-gguf", hide = true)]
    FetchHubGguf(FetchHubGgufArgs),

    /// Internal cancellable metadata boundary for diagnostic artifact choice.
    #[command(name = "__catalog-hub-gguf", hide = true)]
    CatalogHubGguf(CatalogHubGgufArgs),

    /// Internal cancellable verifier for one server-owned local GGUF.
    #[command(name = "__verify-local-gguf", hide = true)]
    VerifyLocalGguf(VerifyLocalGgufArgs),

    /// Update hf2q through its detected installation channel.
    Update(UpdateArgs),

    /// Remove hf2q through its detected installation channel.
    Uninstall(UninstallArgs),

    /// Learn this Mac and record defaults used by convert and serve.
    Setup(SetupArgs),

    /// Patch an existing GGUF file's metadata without changing tensor bytes
    GgufPatch(GgufPatchArgs),

    /// Inspect model metadata before converting
    Info(InfoArgs),

    /// Run the pinned Qwen3.8 source-teacher evidence canary.
    ///
    /// This command is intentionally hidden while the official 27B Apple
    /// artifact gate is being established. Without `--execute` it performs
    /// source/corpus/work/destination/capacity preflight only.
    #[command(name = "source-teacher", hide = true)]
    SourceTeacher(SourceTeacherArgs),

    /// Compare the pinned source-teacher target to an external reference.
    #[command(name = "source-teacher-reference", hide = true)]
    SourceTeacherReference(SourceTeacherReferenceArgs),

    /// Verify the closed AcceptanceHoldout evidence against the exact source.
    #[command(name = "source-teacher-acceptance-verify", hide = true)]
    SourceTeacherAcceptanceVerify(SourceTeacherAcceptanceVerifyArgs),

    /// Diagnose RuVector, hardware detection, and disk space
    Doctor,

    /// Generate shell completions
    Completions(CompletionsArgs),

    /// Run text generation from a GGUF model
    Generate(GenerateArgs),

    /// Chat with a served model using a diagnostic scrollback interface
    Chat(ChatArgs),

    /// Serve a GGUF model via OpenAI-compatible HTTP API
    Serve(ServeArgs),

    /// ADR-009 parity validation against locked references
    Parity(ParityArgs),

    /// ADR-012 Decision 16 — end-gate smoke test for a registered arch
    Smoke(SmokeArgs),

    /// Manage the local model cache (`~/.cache/hf2q/`).
    ///
    /// `hf2q cache list` enumerates cached models. `hf2q cache size`
    /// totals on-disk bytes. `hf2q cache clear` invalidates entries
    /// (single quant, all quants for one model, or the entire cache).
    /// All clear operations atomically rewrite the cache manifest;
    /// concurrent serves observe coherent before/after state.
    Cache(CacheArgs),

    /// ADR-033 — convert a HuggingFace model directory to GGUF via
    /// the unified policy/quantizer/writer pipeline (the only convert
    /// path post-P6). Per [[feedback-no-backwards-compat-2026-05-18]]:
    /// no migration shims; no alias for legacy `--quant` values; no
    /// `convert-v2` alias (the historical name retired 2026-05-19 via
    /// B4 rename).
    Convert(ConvertCliArgs),

    /// Operate on bundled `tokenizer.json` files (ADR-038 G4-CFA-5e).
    ///
    /// Currently provides `fix-bos`, which patches a `tokenizer.json`'s
    /// `post_processor.single` template + `special_tokens` map so that
    /// `tokenizer.encode(text, add_special_tokens=true)` prepends BOS —
    /// matching how most modern Gemma / Qwen tokenizers ship by default.
    ///
    /// The runtime adapter (`core::tokenizer_adapter::tokenize_with_bos_eos_from_gguf`)
    /// is the load-bearing fix for hf2q's own dispatch paths; this CLI
    /// surface is a belt-and-suspenders option for operators who feed
    /// hf2q's bundled `tokenizer.json` files to other tools.
    Tokenizer(TokenizerArgs),
}

#[derive(clap::Args, Debug)]
pub struct FetchHubGgufArgs {
    #[arg(long)]
    pub repository: String,
    #[arg(long)]
    pub revision: String,
    #[arg(long)]
    pub artifact: String,
    #[arg(long)]
    pub bytes: u64,
    #[arg(long)]
    pub sha256: String,
    #[arg(long)]
    pub quant: String,
}

#[derive(clap::Args, Debug)]
pub struct CatalogHubGgufArgs {
    #[arg(long)]
    pub repository: String,
}

#[derive(clap::Args, Debug)]
pub struct VerifyLocalGgufArgs {
    #[arg(long)]
    pub root: PathBuf,
    #[arg(long)]
    pub artifact: PathBuf,
    #[arg(long)]
    pub bytes: u64,
    #[arg(long)]
    pub sha256: String,
    #[arg(long)]
    pub quant: String,
}

#[derive(clap::Args, Debug, Clone)]
pub struct StandaloneInstallArgs {
    /// Existing canonical user-owned directory that will contain hf2q.
    #[arg(long, value_name = "ABSOLUTE_PATH")]
    pub install_dir: PathBuf,

    /// Downloaded candidate executable already accepted by release policy.
    #[arg(long, value_name = "ABSOLUTE_PATH")]
    pub candidate: PathBuf,

    /// Exact candidate byte length from the immutable release record.
    #[arg(long)]
    pub size: u64,

    /// Exact lowercase SHA-256 from the immutable release record.
    #[arg(long, value_name = "LOWERCASE_HEX")]
    pub sha256: String,
}

#[derive(clap::Args, Debug, Clone)]
pub struct UninstallArgs {
    /// Confirm the exact channel-owned release removal shown by the preview.
    #[arg(long)]
    pub yes: bool,

    /// Also remove only setup-owned config files from the selected state root.
    #[arg(long)]
    pub purge_config: bool,

    /// Also purge the validated hf2q model-cache manifest and models tree.
    #[arg(long)]
    pub purge_cache: bool,
}

#[derive(clap::Args, Debug, Clone)]
pub struct UpdateArgs {
    /// Check the channel or print its exact non-mutating next action.
    #[arg(long, conflicts_with = "rollback")]
    pub check: bool,

    /// Atomically restore the retained previous standalone executable.
    #[arg(long, conflicts_with = "check")]
    pub rollback: bool,
}

#[derive(clap::Args, Debug, Clone)]
pub struct SetupArgs {
    /// Default quant selector used by `hf2q convert` when `--quant` is omitted.
    #[arg(
        long,
        value_name = "QUANT",
        value_hint = clap::ValueHint::Other,
        add = clap_complete::ArgValueCompleter::new(complete::quant_names)
    )]
    pub default_quant: Option<String>,

    /// Default serve bind host. Setup accepts only 127.0.0.1 or 0.0.0.0.
    #[arg(long, value_name = "HOST")]
    pub serve_host: Option<String>,

    /// Default serve port.
    #[arg(long, value_name = "PORT")]
    pub serve_port: Option<u16>,

    /// Default serve scheduler.
    #[arg(long, value_enum, value_name = "POLICY")]
    pub serve_scheduler: Option<SchedulerArg>,

    /// Default active-request slots for inflight-batched serving.
    #[arg(long, value_name = "N")]
    pub serve_max_slots: Option<u32>,

    /// Accept the displayed values without prompting. A fresh config uses the
    /// canonical Qwen3.8 guide defaults; a rerun retains current values.
    /// Explicit setup flags override individual values.
    #[arg(long, default_value_t = false)]
    pub accept_defaults: bool,
}

#[derive(clap::Args, Debug, Clone)]
pub struct SourceTeacherArgs {
    /// Exact local Qwen3.8-27B snapshot selected by the source manifest.
    #[arg(long, value_name = "DIRECTORY")]
    pub model_dir: PathBuf,

    /// Fresh target artifact destination. Existing entries are never replaced.
    #[arg(long, value_name = "FILE")]
    pub output: PathBuf,

    /// Characterization split to execute. AcceptanceHoldout is unavailable on
    /// this ordinary route.
    #[arg(long, value_enum, value_name = "SPLIT")]
    pub evaluation_split: SourceTeacherEvaluationSplitArg,

    /// Perform the ~54 GB Metal upload and completed one-shot teacher run.
    /// Omit this flag for a model-weight/Metal-allocation-free preflight.
    #[arg(long, default_value_t = false)]
    pub execute: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SourceTeacherEvaluationSplitArg {
    Calibration,
    PolicyValidation,
}

#[derive(clap::Args, Debug, Clone)]
pub struct SourceTeacherAcceptanceVerifyArgs {
    /// Exact local Qwen3.8-27B snapshot selected by the source manifest.
    #[arg(long, value_name = "DIRECTORY")]
    pub model_dir: PathBuf,
}

#[derive(clap::Args, Debug, Clone)]
pub struct SourceTeacherReferenceArgs {
    /// Exact local Qwen3.8-27B snapshot selected by the source manifest.
    #[arg(long, value_name = "DIRECTORY")]
    pub model_dir: PathBuf,

    /// JSON stdout captured from the completed native source-teacher run.
    #[arg(long, value_name = "FILE")]
    pub native_summary: PathBuf,

    /// Published native full-vocabulary target artifact.
    #[arg(long, value_name = "FILE")]
    pub native_target: PathBuf,

    /// Metadata emitted by the pinned external reference harness.
    #[arg(long, value_name = "FILE")]
    pub external_evidence: PathBuf,

    /// Full-vocabulary target artifact emitted by the external reference.
    #[arg(long, value_name = "FILE")]
    pub external_target: PathBuf,
}

#[derive(clap::Args, Debug)]
pub struct TokenizerArgs {
    #[command(subcommand)]
    pub action: TokenizerAction,
}

#[derive(Subcommand, Debug)]
pub enum TokenizerAction {
    /// Patch `<path>` in place so its `post_processor.single` template
    /// prepends BOS. Idempotent: re-runs are no-ops. Reads BOS metadata
    /// (token id + text) from a sibling GGUF when `--gguf <path>` is
    /// given; otherwise the operator must supply `--bos-id` + `--bos-text`.
    FixBos {
        /// Path to the `tokenizer.json` file to patch.
        #[arg(value_name = "TOKENIZER_JSON")]
        path: PathBuf,

        /// Optional sibling GGUF — when supplied, reads
        /// `tokenizer.ggml.bos_token_id` and resolves the token text
        /// via the same logic as the runtime adapter.
        #[arg(long, value_name = "GGUF")]
        gguf: Option<PathBuf>,

        /// Override the BOS token id (when no `--gguf` is given).
        /// Default `2` matches Gemma family.
        #[arg(long, default_value_t = 2)]
        bos_id: u32,

        /// Override the BOS token text. Default `<bos>`.
        #[arg(long, default_value = "<bos>")]
        bos_text: String,
    },
}

/// `hf2q convert <hf-dir> --quant <name> -o <out.gguf>` clap args.
///
/// Resolved to [`crate::convert::ConvertArgs`] in `main.rs::cmd_convert`.
#[derive(clap::Args, Debug, Clone)]
pub struct ConvertCliArgs {
    /// Local Hugging Face model directory or public model reference.
    /// Existing paths and explicit `./`, `../`, or absolute paths remain
    /// local. A non-path repository ID or canonical huggingface.co model,
    /// tree, blob, or resolve URL is downloaded natively after its revision
    /// is resolved to an immutable commit. Mutually exclusive with `--repo`.
    #[arg(conflicts_with = "repo")]
    pub hf_dir: Option<PathBuf>,

    /// Compatibility spelling for a Hugging Face model reference. Downloads
    /// use hf2q's in-process `hf-hub` client and standard Hub cache/token
    /// discovery; no Python or external Hub CLI is required.
    #[arg(long, conflicts_with = "hf_dir")]
    pub repo: Option<String>,

    /// Optional branch, tag, or full commit for a remote positional reference
    /// or `--repo`. It must match any URL-embedded revision and is resolved to
    /// a full immutable commit before transfer. Invalid for local paths.
    #[arg(long, value_name = "REVISION")]
    pub revision: Option<String>,

    /// Provenance repo for an already-downloaded positional `<hf_dir>`.
    /// This does not download anything; hf2q verifies the local bytes against
    /// the exact Hugging Face revision before conversion and writes the same
    /// immutable receipt produced by `--repo` conversions.
    #[arg(
        long,
        requires = "hf_dir",
        conflicts_with = "repo",
        value_name = "HF_REPO"
    )]
    pub source_repo: Option<String>,

    /// Exact 40-hex Hugging Face commit for `--source-repo`.
    #[arg(
        long,
        requires = "source_repo",
        conflicts_with = "repo",
        value_name = "REVISION"
    )]
    pub source_revision: Option<String>,

    /// File-type to quantize to. Accepts:
    ///   - Standard GGUF ftypes: `f32`, `f16`, `bf16`, `q4_0`,
    ///     `q4_1`, `q5_0`, `q5_1`, `q8_0`, `q2_k`, `q3_k_s/m/l`,
    ///     `q4_k_s/m`, `q5_k_s/m`, `q6_k`, `iq4_nl`.
    ///   - Apex algorithmic tiers (MoE arches only): `apex-quality`,
    ///     `apex-i-quality`, `apex-balanced`, `apex-i-balanced`,
    ///     `apex-compact`, `apex-i-compact`, `apex-mini`.
    ///   - DeepSeek-V4 agent profile: `deepseek4-agentic-q2` (Q2_K
    ///     expert gate/up, Q3_K expert down, Q8_0 context path).
    ///
    /// Reserved / out-of-scope names (per ADR §P7 AC#1 + Decision §6).
    /// Each surfaces a typed `QuantSelectorError` variant with an
    /// operator-actionable hint pointing at the supported alternative:
    ///   - `dwq` → `DwqReserved` (reserved until ADR-046's native
    ///     affine artifact, trainer, quality, and runtime gates land).
    ///   - `tq1_0`, `tq2_0` → `TqOutOfV1Scope` (recognized ftypes
    ///     without a Quantizer impl in v1).
    ///   - bare `apex` → `ApexUnqualified` (must pick an explicit
    ///     tier; no implicit default).
    ///   - `apex-custom` → `ApexCustomRequiresTensorTypeFile`
    ///     (requires `--tensor-type-file <path>`).
    ///   - `apex-nano`, `apex-i-nano`, `apex-micro`, `apex-i-micro` →
    ///     `ApexTierOutOfScope` (mudler experimental tiers dropped
    ///     from v1; reach via `apex-custom`).
    ///   - any other `apex-<x>` → `UnknownApexTier` (lists the
    ///     supported tier set in the message).
    ///
    /// Parsed via `QuantSelector::from_name`; unrecognized values
    /// surface as input errors. When omitted, the value recorded by
    /// `hf2q setup` is used; without either source, conversion fails and
    /// asks the operator to choose. Per
    /// [[feedback-no-backwards-compat-2026-05-18]]: no legacy aliases.
    #[arg(
        long,
        value_hint = clap::ValueHint::Other,
        add = clap_complete::ArgValueCompleter::new(complete::quant_names)
    )]
    pub quant: Option<String>,

    /// Destination GGUF file. Existing files are overwritten.
    #[arg(short, long)]
    pub output: PathBuf,

    /// Build and report the exact tensor/type/byte plan without creating the
    /// output GGUF. Source download or provenance hashing may still read the
    /// complete input; no tensor payload is materialized by the converter.
    #[arg(
        long,
        default_value_t = false,
        conflicts_with_all = ["imatrix_corpus", "imatrix_out"]
    )]
    pub dry_run: bool,

    /// Pre-computed imatrix file (`.imatrix.gguf`). Required for I-tier
    /// APEX variants (`apex-i-quality`, `apex-i-balanced`, `apex-i-compact`)
    /// per ADR-033 §Pi. Mutually exclusive with `--imatrix-corpus`.
    ///
    /// For supported architectures, `--imatrix-corpus cdv3` is the
    /// recommended alternative. It drives hf2q's own forward-pass-based
    /// generator (ADR-033 §Pi Phase B). A pre-computed file remains useful
    /// for architectures that are not yet wired for in-tree generation.
    #[arg(long, conflicts_with = "imatrix_corpus")]
    pub imatrix: Option<PathBuf>,

    /// Auto-generate an imatrix in-memory during convert by running the
    /// hf2q decoder over the named calibration corpus. ADR-033 §Pi
    /// "Phase B" — SHIPPED 2026-05-19 (Stage 3c). The driver converts
    /// the source `<hf_dir>` to a temporary F16 GGUF, loads it via the
    /// per-arch inference path, tokenizes the corpus, and runs
    /// `forward_prefill` over `--imatrix-n-ctx`-sized chunks (default
    /// 512 while intercepting per-tensor activations.
    ///
    /// **Supported arches: Gemma 4 plus dense and MoE Qwen3.5-family
    /// decoders.** Other arches (MiniMax-M2, BERT, etc.) surface
    /// `ImatrixError::UnsupportedArchForDriver`. For those, use the
    /// `--imatrix <file>` flag with a pre-computed `.imatrix.gguf`.
    ///
    /// Accepted values: `cdv3` (bartowski's default, baked at compile
    /// time), `mudler` (selector parses but the corpus itself is
    /// not yet bundled — typed CorpusRead error), or
    /// `user-file:<path>` for an operator-supplied `.txt` corpus.
    ///
    /// Wall time: roughly seconds per chunk × ~100 chunks on a 26B-A4B
    /// Gemma 4 — operator-coffee-time, not CI-time.
    #[arg(long, conflicts_with = "imatrix")]
    pub imatrix_corpus: Option<String>,

    /// Optional side-effect: write the imatrix used by this convert
    /// run to the given path. Useful both for caching in-tree-computed
    /// imatrices (`--imatrix-corpus`) and for round-tripping
    /// pre-computed ones (`--imatrix <file>`). The on-disk format
    /// matches stock `llama-imatrix --output-format gguf`.
    #[arg(long)]
    pub imatrix_out: Option<PathBuf>,

    /// Context length for in-tree imatrix collection (ADR-033 §Pi
    /// Stage 3c). Only consulted when `--imatrix-corpus` is set;
    /// ignored on the `--imatrix <file>` load path (the loaded file's
    /// `imatrix.chunk_size` KV is authoritative there). Defaults to
    /// 512 to match stock `llama-imatrix -c 512`. Must be > 0; the
    /// corpus must tokenize to at least this many tokens or the
    /// driver surfaces `ImatrixError::CorpusTooShort`.
    ///
    /// Larger `n_ctx` means fewer, longer chunks per forward-pass
    /// loop — useful for matching imatrices produced by stock
    /// llama-imatrix with non-default `-c` values, but at the cost
    /// of more memory per forward pass.
    #[arg(long)]
    pub imatrix_n_ctx: Option<u32>,

    /// Export only the multimodal projector (mmproj) sidecar instead of
    /// the text decoder. This expert mode is retained for repairing or
    /// replacing a projector independently. By default, a supported
    /// multimodal source produces both the text GGUF and its F16 projector.
    ///
    /// When set, hf2q routes the input model through its family-specific
    /// projector emitter. The output GGUF carries the vision tower (`v.*`)
    /// plus projector (`mm.*`) tensors and the `clip.*` metadata schema;
    /// text-decoder tensors are intentionally excluded.
    /// Conventional output filename: `<basename>-mmproj.gguf` —
    /// operator picks via `--output`.
    ///
    /// Currently supported arches include Gemma 4 multimodal and the
    /// Qwen3.5/Qwen3-VL conditional-generation families.
    #[arg(long, default_value_t = false, conflicts_with = "text_only")]
    pub mmproj: bool,

    /// Convert only the text decoder even when the source contains a
    /// supported vision tower. This is the explicit opt-out from hf2q's
    /// default paired text + projector conversion contract.
    #[arg(long, default_value_t = false, conflicts_with = "mmproj")]
    pub text_only: bool,

    /// Override the projector path for an automatic paired conversion.
    /// Without this flag, `<output-stem>-mmproj.gguf` is used beside the
    /// text GGUF. Paired outputs must share one directory. Invalid for
    /// `--text-only` and projector-only `--mmproj`.
    #[arg(
        long,
        value_name = "GGUF",
        conflicts_with_all = ["mmproj", "text_only"]
    )]
    pub mmproj_output: Option<PathBuf>,
}

#[derive(clap::Args, Debug)]
pub struct GgufPatchArgs {
    /// Input GGUF file
    pub input: PathBuf,

    /// Output GGUF path. Required unless --in-place or --dry-run is set.
    #[arg(long, conflicts_with = "in_place")]
    pub output: Option<PathBuf>,

    /// Rewrite the input file atomically in place
    #[arg(long, conflicts_with = "output", default_value_t = false)]
    pub in_place: bool,

    /// Add tokenizer.chat_template from the architecture default.
    ///
    /// This is currently the default and only patch operation; the flag is
    /// accepted for explicit operator intent and forward-compatible scripts.
    #[arg(long, default_value_t = false)]
    pub add_chat_template_from_arch: bool,

    /// Report the planned action without writing
    #[arg(long, default_value_t = false)]
    pub dry_run: bool,
}

/// Top-level args for `hf2q cache`. The actual surface is split into
/// `CacheAction` subcommands (clap convention shared with `parity`).
#[derive(clap::Args, Debug)]
pub struct CacheArgs {
    #[command(subcommand)]
    pub action: CacheAction,
}

/// `hf2q cache` subcommands. ADR-005 Phase 3 iter-205 (AC line 5351).
///
/// ADR-017 §R-F6 extension: the `--kv-namespace` flag (orthogonal to
/// the weights-side surface) flips the action's target from the
/// model-weights cache to the on-disk persistent KV-cache subtree
/// (`<kv-persist>/models/<fp_short>/`). Path discovery order when
/// `--kv-namespace` is set:
///
/// 1. `--kv-path PATH` (explicit; first to win).
/// 2. `HF2Q_KV_PERSIST_PATH` env var.
///
/// We do NOT silently fall back to the weights-cache root or any
/// implicit default — see `docs/operating-kv-cache.md` §3 / ADR-017
/// §R-F1: the kv-persist path is operator-supplied at `cmd_serve`
/// startup with no default, and guessing here could clear an
/// unintended directory.
#[derive(Subcommand, Debug)]
pub enum CacheAction {
    /// List cached models with their quantizations and on-disk sizes.
    ///
    /// With `--kv-namespace`: enumerates per-model directories under
    /// `<kv-persist>/models/<fp_short>/` (one row per `<fp_short>`)
    /// with bytes-on-disk + block count under that subtree. Closes
    /// `docs/operating-kv-cache.md` §11 #4 (ADR-017 §R-F6).
    List {
        /// Switch this action to the persistent KV-cache subtree
        /// instead of the model-weights cache. ADR-017 §R-F6.
        #[arg(long, default_value_t = false)]
        kv_namespace: bool,

        /// KV-persist root override. Required (or via
        /// `HF2Q_KV_PERSIST_PATH`) when `--kv-namespace` is set.
        #[arg(long, value_name = "PATH", requires = "kv_namespace")]
        kv_path: Option<PathBuf>,
    },

    /// Print the total on-disk size of the cache.
    ///
    /// With `--kv-namespace`: total bytes-on-disk under
    /// `<kv-persist>/models/`.
    Size {
        /// Switch this action to the persistent KV-cache subtree.
        /// ADR-017 §R-F6.
        #[arg(long, default_value_t = false)]
        kv_namespace: bool,

        /// KV-persist root override. Required (or via
        /// `HF2Q_KV_PERSIST_PATH`) when `--kv-namespace` is set.
        #[arg(long, value_name = "PATH", requires = "kv_namespace")]
        kv_path: Option<PathBuf>,
    },

    /// Clear cache entries — single (model, quant), all quants for
    /// one model, or the entire cache (`--all --yes`).
    ///
    /// With `--kv-namespace --model <repo>`: removes the per-`(repo,
    /// quant)` directory at `<kv-persist>/models/<fp_short>/kv/`.
    /// `--model` is REQUIRED for kv-namespace clear (no `--all`
    /// shortcut — operator runbook §11 #4 specifically calls for
    /// per-repo scope; whole-cache wipe stays as `rm -rf
    /// <kv-persist>` on a stopped serve). Does NOT touch
    /// `<kv-persist>/locks/` (those are session-scoped) or other
    /// repos' subtrees.
    Clear {
        /// HF repo-id of the model whose cache entry to clear
        /// (e.g. `google/gemma-4-27b-it`). Required unless `--all`
        /// (weights-side) or always-required for `--kv-namespace`.
        #[arg(long)]
        model: Option<String>,

        /// Limit removal to a single quantization (`Q8_0`, `Q6_K`,
        /// `Q4_K_M`, `Q3_K_M`). When omitted with `--model`, every
        /// quant cached for that model is removed (plus the model dir
        /// `source/` and `repo_meta.json`).
        ///
        /// For `--kv-namespace` the per-`(repo, quant)` fingerprint
        /// only varies by `(repo, quant)` at this commit (see
        /// `docs/operating-kv-cache.md` §3); omitting `--quant`
        /// removes every quant variant cached for the repo.
        #[arg(long)]
        quant: Option<String>,

        /// Clear every cached model. Refuses without `--yes` to
        /// prevent accidental wipes (the entire on-disk cache is
        /// removed; manifest is reset to empty). Refused under
        /// `--kv-namespace` — see variant docstring.
        #[arg(long, default_value_t = false)]
        all: bool,

        /// Confirm a destructive operation. Required by `--all`.
        #[arg(long, default_value_t = false)]
        yes: bool,

        /// Switch this action to the persistent KV-cache subtree.
        /// ADR-017 §R-F6.
        #[arg(long, default_value_t = false)]
        kv_namespace: bool,

        /// KV-persist root override. Required (or via
        /// `HF2Q_KV_PERSIST_PATH`) when `--kv-namespace` is set.
        #[arg(long, value_name = "PATH", requires = "kv_namespace")]
        kv_path: Option<PathBuf>,

        /// Override the active-serve sentinel-flock guard. Use only
        /// when you know no `hf2q serve --kv-persist=SAME_PATH` is
        /// running against this cache root (a stopped serve can
        /// leave a stale sentinel under abnormal exit; this flag
        /// re-enables clear in that case).
        #[arg(long, default_value_t = false)]
        force: bool,
    },
}

#[derive(clap::Args, Debug, Clone)]
pub struct SmokeArgs {
    /// Arch key as registered in `src/arch/` (qwen35, qwen35moe)
    #[arg(
        long,
        value_hint = clap::ValueHint::Other,
        add = clap_complete::ArgValueCompleter::new(complete::architecture_names)
    )]
    pub arch: String,

    /// Quant method to smoke-test
    #[arg(
        long,
        default_value = "q4_0",
        value_hint = clap::ValueHint::Other,
        add = clap_complete::ArgValueCompleter::new(complete::quant_names)
    )]
    pub quant: String,

    /// Also exercise the --emit-vision-tower path (dense variants with vision_config)
    #[arg(long, default_value_t = false)]
    pub with_vision: bool,

    /// Skip the convert step and reuse an existing GGUF on disk
    #[arg(long, default_value_t = false)]
    pub skip_convert: bool,

    /// Run preflight + dispatch, skip convert/inference, emit transcript path
    #[arg(long, default_value_t = false)]
    pub dry_run: bool,

    /// Fixtures root (defaults to `tests/fixtures/`)
    #[arg(long)]
    pub fixtures_root: Option<PathBuf>,

    /// Use a local safetensors directory instead of downloading from HF.
    /// When set, preflight skips HF_TOKEN + repo-resolution checks.
    /// Enables CI testing of the Q4_0 end-to-end path on synthetic models.
    #[arg(long)]
    pub local_dir: Option<PathBuf>,

    /// Keep converted GGUF(s) in this directory. Defaults to a temp dir
    /// so repeat smoke runs don't accumulate disk.
    #[arg(long)]
    pub convert_output_dir: Option<PathBuf>,

    /// Override path for llama-cli. When set, preflight skips the default
    /// llama-cli search (/opt/llama.cpp/build/bin/ + PATH) and the smoke
    /// runner uses this path directly. Enables CI tests to inject a
    /// mock stub emitting a deterministic transcript.
    #[arg(long)]
    pub llama_cli_override: Option<PathBuf>,
}

#[derive(clap::Args, Debug)]
pub struct InfoArgs {
    /// Local safetensors directory
    #[arg(long, conflicts_with = "repo")]
    pub input: Option<PathBuf>,

    /// HuggingFace repo ID
    #[arg(long, conflicts_with = "input")]
    pub repo: Option<String>,
}

#[derive(clap::Args, Debug)]
pub struct CompletionsArgs {
    /// Shell to generate completions for
    #[arg(long, value_enum)]
    pub shell: Shell,
}

#[derive(clap::Args, Debug)]
pub struct GenerateArgs {
    /// Path to GGUF model file
    #[arg(long)]
    pub model: PathBuf,

    /// Path to tokenizer.json (if not alongside GGUF)
    #[arg(long)]
    pub tokenizer: Option<PathBuf>,

    /// Path to config.json (if not alongside GGUF)
    #[arg(long)]
    pub config: Option<PathBuf>,

    /// Prompt text (required unless --prompt-file is given)
    #[arg(long, required_unless_present = "prompt_file")]
    pub prompt: Option<String>,

    /// Path to file containing prompt text
    #[arg(long, conflicts_with = "prompt")]
    pub prompt_file: Option<PathBuf>,

    /// Run benchmark mode: 5 consecutive runs, report median and p95 tok/s
    #[arg(long)]
    pub benchmark: bool,

    /// Maximum tokens to generate
    #[arg(long, default_value = "256")]
    pub max_tokens: usize,

    /// Ignore end-of-sequence token; generate the full max_tokens regardless of EOS.
    /// Used for benchmarks that need a fixed-length generation (e.g., true tg5000 vs peer).
    #[arg(long)]
    pub ignore_eos: bool,

    /// Path to a multimodal projector GGUF (mmproj). When supplied,
    /// `hf2q generate` validates the GGUF + parses `MmprojConfig` +
    /// loads the projector weights onto the Metal device, and surfaces
    /// the file in the load banner (`vision = <path> (sha256 ...)`).
    /// Mirror of `serve --mmproj`.
    #[arg(long)]
    pub mmproj: Option<PathBuf>,

    /// Path to an input image (PNG / JPEG / WebP). Requires `--mmproj`.
    /// When supplied, `hf2q generate` runs the ViT GPU forward, splices
    /// the vision embeddings into the prompt at the chat template's
    /// image markers, and decodes against the augmented sequence.
    #[arg(long)]
    pub image: Option<PathBuf>,

    /// Sampling temperature (0.0 = greedy, deterministic).
    ///
    /// Default `0.0` mirrors `--temp 0` in llama-cli's deterministic mode and
    /// gives the user predictable, complete, byte-reproducible output on every
    /// run.  Pass any positive value (e.g. `--temperature 0.8`) to opt into
    /// stochastic sampling — useful for creative-writing prompts where output
    /// diversity matters more than reproducibility, but the cost is occasional
    /// early-`<|im_end|>` stops on prompts where the model's distribution
    /// has non-trivial mass on EOS at any step.
    #[arg(long, default_value = "0.0")]
    pub temperature: f64,

    /// Top-p nucleus sampling
    #[arg(long, default_value = "0.95")]
    pub top_p: f64,

    /// Top-k sampling (0 = disabled)
    #[arg(long, default_value = "40")]
    pub top_k: usize,

    /// Min-p sampling (0.0 = disabled)
    #[arg(long, default_value = "0.05")]
    pub min_p: f64,

    /// Repetition penalty (1.0 = disabled)
    #[arg(long, default_value = "1.0")]
    pub repetition_penalty: f64,

    /// Enable Qwen3.5 MTP speculative decoding when MTP weights are present.
    /// Also enabled by HF2Q_SPEC_DECODE=1; Qwen3.5 GGUFs with MTP default on.
    #[arg(long)]
    pub speculative: bool,

    /// TurboQuant KV cache bit-width (ADR-007 Path C F-6.1).
    ///
    /// Selects the Lloyd-Max codebook used to compress the KV cache:
    ///   - **8** (default): production-grade 8-bit Lloyd-Max HB SDPA. 256
    ///     centroids, ±5.0652659 range. Gate A cosine 0.9998, Gate C
    ///     1.24% PPL delta (intrinsic distortion floor — see ADR §F-2).
    ///   - **6**: opt-in research mode. 64 centroids. Wider cosine spread.
    ///   - **5**: opt-in research mode. 32 centroids. Wider PPL gap.
    ///   - **4**: legacy 4-bit nibble-packed `flash_attn_vec_tq` path
    ///     (close-section §1117 — 127-byte sourdough ceiling, 5.3% argmax
    ///     divergence, 1.55% PPL — NOT shippable as default).
    ///
    /// 16-bit TQ is intentionally **NOT supported** — at 2 bytes/element
    /// it is structurally redundant with F16 dense (`HF2Q_USE_DENSE=1`)
    /// and adds no compression benefit. See ADR §F-2 finding.
    ///
    /// When unset, falls back to `HF2Q_TQ_CODEBOOK_BITS` env var (default 8).
    /// When set, this flag wins and pre-populates the env var before the
    /// engine initializes.
    #[arg(long, value_parser = clap::builder::PossibleValuesParser::new(["4", "5", "6", "8"]))]
    pub kv_bits: Option<String>,

    /// Override chat template with a Jinja2 string
    ///
    /// Priority order (per ADR-005 Phase 1): this flag > --chat-template-file >
    /// GGUF `tokenizer.chat_template` metadata > hardcoded fallback.
    #[arg(long)]
    pub chat_template: Option<String>,

    /// Override chat template by reading from a file containing a Jinja2 template
    #[arg(long, conflicts_with = "chat_template")]
    pub chat_template_file: Option<PathBuf>,

    /// Force thinking-mode rendering on: pass `enable_thinking=true` to the
    /// chat template's Jinja context. For Qwen3-thinking / QwQ / GPT-OSS-
    /// reasoning checkpoints, this opens an unfilled `<think>\n` block at
    /// the end of the rendered prompt — the model emits reasoning content
    /// + `</think>` + the answer (the "both" outcome).
    ///
    /// **Default behavior (NEITHER flag set) is auto-detect via the
    /// canonical render-and-diff signal**: hf2q renders the resolved chat
    /// template TWICE — once with `enable_thinking=true`, once with
    /// `=false` — and checks if the bytes differ. If they do, the
    /// template branches on the variable → the model class supports
    /// thinking-mode → default-on (model produces BOTH reasoning trace
    /// AND answer). If the bytes are identical (or no template can be
    /// resolved), default is `false` (safe fallback).
    ///
    /// Mirrors the peer's `--reasoning auto` decision logic (its
    /// render-and-diff `compare_thinking_enabled` probe and the
    /// server-side decision it feeds).
    ///
    /// Pass `--enable-thinking` to override auto-detect ON (e.g. a custom
    /// template that doesn't probe as thinking-capable but you know the
    /// model supports it). Pass `--no-thinking` to override auto-detect
    /// OFF (e.g. a template that probes as thinking-capable but the
    /// model's actual checkpoint doesn't know how to close `</think>`,
    /// improvising `<|end|>` instead). Mutually exclusive.
    ///
    /// 2026-05-02: added (commit `8c110f5`, plumb-only) → re-defaulted to
    /// false (regression-fix iter 2) → name-substring heuristic (REJECTED
    /// by user) → render-and-diff canonical signal (peer audit:
    /// `/tmp/cfa-thinking-detect/peer-detection-report.md`). H2 audit:
    /// `docs/research/decode-test-gap-2026-05-02.md`.
    #[arg(long)]
    pub enable_thinking: bool,

    /// Force thinking-mode rendering off. See `--enable-thinking` for the
    /// full rationale (auto-detect default + override semantics). Use this
    /// when a model whose name LOOKS thinking-capable (e.g. `qwen-thinking-
    /// distill`) actually breaks with the open-`<think>` prompt cue.
    /// Mutually exclusive with `--enable-thinking`.
    #[arg(long, conflicts_with = "enable_thinking")]
    pub no_thinking: bool,
    // ADR-008: candle-era kernel mode flags removed.
    // The mlx-native backend handles all dispatch internally.
}

#[derive(clap::Args, Debug, Clone)]
pub struct ChatArgs {
    /// OpenAI-compatible server base URL. Without this flag, the automatic
    /// local discovery integration selects a registered hf2q server.
    #[arg(long, value_name = "URL")]
    pub url: Option<String>,

    /// Model id to request. If omitted, chat selects from the endpoint's
    /// advertised models.
    #[arg(long, value_name = "MODEL")]
    pub model: Option<String>,

    /// Select one hosted GGUF quant from a mixed Hugging Face repository.
    /// Requires an hf2q endpoint and --model; ambiguous matches fail closed.
    #[arg(
        long,
        value_name = "TYPE",
        value_enum,
        ignore_case = true,
        requires = "model",
        conflicts_with = "artifact"
    )]
    pub quant: Option<DiagnosticQuantArg>,

    /// Select one exact hosted GGUF filename from a Hugging Face repository.
    /// Requires an hf2q endpoint and --model; no source-conversion fallback.
    #[arg(
        long,
        value_name = "FILE",
        requires = "model",
        conflicts_with = "quant"
    )]
    pub artifact: Option<String>,

    /// System message kept for this TUI session only.
    #[arg(long)]
    pub system: Option<String>,

    /// Sampling temperature. Omitted from requests unless explicitly set.
    #[arg(long)]
    pub temperature: Option<f32>,

    /// Nucleus-sampling probability. Omitted unless explicitly set.
    #[arg(long)]
    pub top_p: Option<f32>,

    /// Maximum completion tokens. Omitted unless explicitly set.
    #[arg(long)]
    pub max_tokens: Option<usize>,

    /// Sampling seed. Omitted unless explicitly set.
    #[arg(long)]
    pub seed: Option<u64>,

    /// Reasoning effort for endpoints that support it.
    #[arg(long, value_parser = ["low", "high", "max"])]
    pub reasoning_effort: Option<String>,

    /// Leave a server started by this chat session running on exit.
    #[arg(long, default_value_t = false)]
    pub keep_serving: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum DiagnosticQuantArg {
    #[value(name = "Q8_0")]
    Q8Zero,
    #[value(name = "Q6_K")]
    Q6K,
    #[value(name = "Q4_K_M")]
    Q4KM,
    #[value(name = "Q3_K_M")]
    Q3KM,
}

impl DiagnosticQuantArg {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Q8Zero => "Q8_0",
            Self::Q6K => "Q6_K",
            Self::Q4KM => "Q4_K_M",
            Self::Q3KM => "Q3_K_M",
        }
    }
}

#[derive(clap::Args, Debug)]
pub struct ServeArgs {
    /// Path to GGUF model file. Optional in the iter-2 backbone which only
    /// exposes /health, /readyz, /v1/models; required once /v1/chat and
    /// /v1/embeddings route. Fail-fast on bad weights is preserved: if
    /// --model is supplied, the GGUF header is validated at startup.
    #[arg(long)]
    pub model: Option<PathBuf>,

    /// Additional server-local directory to search for schema-v3 hf2q
    /// conversion receipts. Repeatable; roots are bounded and never exposed.
    #[arg(long = "model-dir", value_name = "DIR")]
    pub model_dirs: Vec<PathBuf>,

    /// Internal inherited descriptor for a server owned by `hf2q chat`.
    /// The server accepts it only while leading an isolated process group;
    /// EOF terminates that group and `D` explicitly detaches it.
    #[arg(long, hide = true, value_name = "FD")]
    pub chat_parent_lifeline_fd: Option<i32>,

    /// Path to tokenizer.json (if not alongside GGUF).
    #[arg(long)]
    pub tokenizer: Option<PathBuf>,

    /// Path to config.json (if not alongside GGUF).
    #[arg(long)]
    pub config: Option<PathBuf>,

    /// Host to bind to. Explicit CLI wins over the setup config; without
    /// either, defaults to 127.0.0.1 (localhost only) per ADR-005 Decision
    /// #7. Use `--host 0.0.0.0` to expose on the LAN; public-internet is NOT
    /// a supported deployment target (reverse-proxy assumption, Decision
    /// #13).
    #[arg(long)]
    pub host: Option<String>,

    /// Port to listen on. Explicit CLI wins over the setup config; without
    /// either, the built-in default remains 8080.
    #[arg(long)]
    pub port: Option<u16>,

    /// Maximum sequence length (reserved for future iterations — context
    /// length is read from GGUF metadata).
    #[arg(long, default_value = "4096")]
    pub max_seq_len: usize,

    /// Bearer token required on every request (Decision #8). Unset = no auth.
    /// Also read from `HF2Q_AUTH_TOKEN` env var if --auth-token is absent
    /// (handled inside `cmd_serve`, not via clap's `env` feature to keep the
    /// `clap` feature set minimal).
    #[arg(long)]
    pub auth_token: Option<String>,

    /// CORS allowed origin. Repeatable. Empty = allow any (localhost dev);
    /// non-empty = restrictive whitelist (Decision #9).
    #[arg(long = "cors-origin", value_name = "ORIGIN")]
    pub cors_origins: Vec<String>,

    /// Hard cap on the FIFO generation queue. Overflow returns 429 +
    /// Retry-After (Decision #19).
    #[arg(long, default_value = "32")]
    pub queue_capacity: usize,

    /// Cache directory to scan for /v1/models listings. Defaults to
    /// $HOME/.cache/hf2q (Decision #26).
    #[arg(long)]
    pub cache_dir: Option<PathBuf>,

    /// Default context-overflow policy (Decision #23). Per-request
    /// `hf2q_overflow_policy` overrides this.
    #[arg(long, value_enum, default_value = "summarize")]
    pub overflow_policy: OverflowPolicyArg,

    /// Path to a dedicated embedding GGUF (BERT family — nomic-embed-text,
    /// mxbai-embed-large, bge-small-en, etc.). When supplied, the server
    /// validates the file's GGUF header + parses the BERT config at
    /// startup and surfaces it via `/v1/models` with extension fields
    /// (`pooling`, `context_length`, `hidden_size`). The forward pass
    /// that backs `/v1/embeddings` requests lands in a later iter
    /// (ADR-005 Phase 2b, Task #13).
    #[arg(long)]
    pub embedding_model: Option<PathBuf>,

    /// Path to a multimodal projector GGUF (mmproj). When supplied, the
    /// server validates the file's GGUF header + parses the
    /// `MmprojConfig` at startup and surfaces it via `/v1/models`.
    /// Required for `image_url` content parts in `/v1/chat/completions`.
    /// Without it, the server is text-only and rejects image parts with
    /// 400 `no_mmproj_loaded` (ADR-005 Phase 2c Task #14).
    #[arg(long)]
    pub mmproj: Option<PathBuf>,

    /// Legacy ADR-020 experimental overlay for a compatible mlx-affine
    /// safetensors file on top of the GGUF-loaded weights. For each
    /// trained Linear stem (`blk.{i}.attn_q`, `attn_k`, `attn_v`,
    /// `attn_output`, `ffn_gate`, `ffn_up`, `ffn_down`), the matching
    /// slot is replaced with an affine-mode `MlxQWeight` that
    /// dispatches through `qmm_affine_t_packed_simd4_b4` (mlx-native
    /// d0de92a).  Currently only dense families (Gemma 4) honor the
    /// overlay; qwen35moe MoE-expert tensors are skipped with a warning
    /// pending a production full-model affine path. hf2q currently has no
    /// DWQ producer; this narrow consumer is not `--quant dwq` support.
    /// See ADR-046.
    #[arg(long)]
    pub dwq_overlay: Option<PathBuf>,

    /// Suppress the human-readable serve load banner on stdout.
    #[arg(long, default_value_t = false)]
    pub quiet: bool,

    /// Interactive operator surface for a foreground server. `auto` uses a
    /// stable live dashboard when stderr is a terminal and preserves plain
    /// logs for pipes, services, CI, and JSON logging. `plain` always emits
    /// normal logs; `dashboard` requests the terminal UI explicitly.
    #[arg(long, value_enum, default_value = "auto")]
    pub operator_ui: OperatorUiArg,

    /// ADR-005 Phase 3 item 3/4 — skip pre-load cache integrity
    /// verification of the cached GGUF on disk.
    ///
    /// **NOT recommended.** When the model came from `hf2q convert`'s
    /// auto-pipeline (iter-204), the cache manifest carries the SHA-256
    /// recorded at quantize time; serve re-hashes the file on load to
    /// catch disk bit-rot, partial writes, or manual edits. This flag
    /// disables that check; corruption silently passes through.
    #[arg(long, default_value_t = false)]
    pub no_integrity: bool,

    /// ADR-017 Phase C.1 — enable persistent block-prefix KV cache to
    /// disk. The argument is the cache directory (e.g.
    /// `/tmp/hf2q-kv-persist` or `$HOME/.cache/hf2q/kv-persist`). The
    /// directory is created if missing; the recovery scan runs at
    /// startup to rebuild the in-memory `BlockIndex` from any
    /// previously-written envelopes.
    ///
    /// When unset (default), the engine wires `NoopKvSpiller` and
    /// behaves byte-identical to the pre-ADR-017 path. When set, the
    /// engine wires `BlockPrefixCacheSpiller` + a per-loaded-family
    /// `EngineBindable` registration so the spiller's `pre_evict` /
    /// `post_admit` triggers route through the on-disk lifecycle.
    ///
    /// C.1 ships the WIRING substrate. The actual sourdough byte-exact
    /// coherence run + perf-validation matrix lands in Phase D after
    /// B-dense.2's round-trip parity matrix on real GGUF; until then,
    /// the C.1 default registration uses `StubGemma4Spill` (always
    /// `Skipped` on snapshot/restore) so the on-path is observable
    /// but functionally inert.
    #[arg(long = "kv-persist", value_name = "PATH")]
    pub kv_persist_path: Option<PathBuf>,

    /// ADR-040 Phase C iter-4 (C4) — scheduler-policy selection for the
    /// in-process [`serve::api::engine::Engine`].
    ///
    /// `fifo_serial` (default) preserves the ADR-005 Decision #2 + #19
    /// production contract byte-for-byte: one mpsc channel, one worker
    /// thread, serialized FIFO dispatch, 429 + Retry-After on queue
    /// overflow. This is the value the operator gets when the flag and
    /// the `HF2Q_SCHEDULER` env var are BOTH unset (ADR-040 §3.6
    /// backward-compat pledge).
    ///
    /// `inflight_batched` activates ADR-040's slot-aware path
    /// ([`EngineMode::SlotAware`]). Supported families provision independent
    /// full-context cache sessions and interleave active requests. Unsupported
    /// families fail at spawn rather than silently sharing cache state.
    ///
    /// Also read from `HF2Q_SCHEDULER` if `--scheduler` is absent.
    /// CLI flag wins on conflict (mirrors `--auth-token` semantics).
    #[arg(long = "scheduler", value_name = "POLICY", value_enum)]
    pub scheduler: Option<SchedulerArg>,

    /// ADR-040 Phase C iter-4 (C4) — `max_slots` for
    /// [`EngineMode::SlotAware`].
    ///
    /// Honored ONLY when `--scheduler inflight_batched` is selected; with
    /// the default `fifo_serial` policy the engine's `max_slots` is
    /// hard-pinned to `1` (one worker, one in-flight request). Default
    /// `4` per ADR-040 §3.4 — half the reopen-trigger threshold of `8`
    /// to ship the first ramp with headroom.
    ///
    /// `0` is rejected with a clear operator-facing error at parse time
    /// (mirrors ADR-040 iter-2.5 F3a `.max(1)` discipline applied
    /// upstream of the scheduler — refuse the misconfiguration loudly
    /// rather than silently coerce). Range: `1..=u32::MAX`.
    ///
    /// Also read from `HF2Q_MAX_SLOTS` if `--max-slots` is absent.
    #[arg(long = "max-slots", value_name = "N")]
    pub max_slots: Option<u32>,

    /// Aggregate physical KV-cache residency budget shared by every
    /// full-context SlotAware agent. This value never divides or truncates a
    /// slot's logical context; admission charges each slot's retained
    /// high-water growth against the shared total. `0` or omission disables
    /// the physical-budget gate. Also read from
    /// `HF2Q_KV_CACHE_BUDGET_BYTES`; the CLI flag wins.
    #[arg(long = "kv-cache-budget-bytes", value_name = "BYTES")]
    pub kv_cache_budget_bytes: Option<u64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OperatorUiArg {
    Auto,
    Dashboard,
    Plain,
}

/// CLI-facing copy of `serve::api::schema::OverflowPolicy`. Kept local to
/// avoid leaking the schema module into the CLI arg parser.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum OverflowPolicyArg {
    Reject,
    TruncateLeft,
    Summarize,
}

/// ADR-040 Phase C iter-4 (C4) — CLI-facing scheduler-policy selector.
///
/// Mirrors the on-disk env-var values `fifo_serial` and `inflight_batched`
/// — both are accepted case-insensitively by the env-var parser (per
/// `serve::mod::parse_scheduler_config_from_env`). clap's `ValueEnum` is
/// case-insensitive by default (`rename_all = "snake_case"` is the
/// implicit default for snake-case Rust variant names), so the operator
/// can type any of `fifo_serial`, `FIFO_SERIAL`, `inflight_batched`,
/// `INFLIGHT_BATCHED` at the command line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SchedulerArg {
    /// ADR-005 Decision #2 + #19 production path. One mpsc channel, one
    /// worker thread, serialized FIFO dispatch. Default; byte-equivalent
    /// to pre-ADR-040 (per ADR-040 §3.6).
    FifoSerial,
    /// ADR-040 slot-aware path: independent full-context sessions with a
    /// shared physical KV residency ceiling.
    InflightBatched,
}

#[derive(Subcommand, Debug)]
pub enum ParityCommand {
    /// Check hf2q output against locked reference fixtures.
    ///
    /// Default mode: byte-prefix comparison vs `*_llama.txt` (or vs the
    /// frozen hf2q self-baseline when `--self-baseline` is set).  Pass
    /// `--tq-quality` to switch to the ADR-007 §853-866 Gate H envelope
    /// check instead (cosine / argmax / PPL Δ vs a frozen
    /// `<prompt>_tq_quality.json` fixture).
    Check {
        /// Path to GGUF model file
        #[arg(long)]
        model: PathBuf,

        /// Eval prompt name (sourdough, short_hello, sliding_wrap)
        #[arg(long, default_value = "sourdough")]
        prompt: String,

        /// Minimum common byte prefix required to pass
        #[arg(long)]
        min_prefix: Option<usize>,

        /// Maximum tokens to generate
        #[arg(long)]
        max_tokens: Option<usize>,

        /// Compare against the frozen hf2q self-baseline (*_hf2q.txt)
        /// instead of the peer reference (*_llama.txt). Encodes
        /// ADR-005 Closeout Amendment Gate D (hf2q-self bisect-safety
        /// when math deliberately changes and temporary peer drift
        /// is expected). Pass requires byte-identical match (not a
        /// min-prefix floor).
        #[arg(long)]
        self_baseline: bool,

        /// ADR-007 Gate H — switch this invocation to the TQ-active
        /// quality envelope check (cosine on SDPA outputs + argmax flip
        /// rate + PPL Δ vs the frozen `<prompt>_tq_quality.json`
        /// fixture). Requires `--fixture` to point at a fixture produced
        /// by `parity capture --tq-quality`.  All other flags below
        /// (`--cosine-mean-floor`, etc.) only take effect when this is
        /// set.
        #[arg(long)]
        tq_quality: bool,

        /// Path to the frozen `<prompt>_tq_quality.json` fixture (Gate H
        /// only). Required when `--tq-quality` is set; the comparison
        /// is meaningless without a frozen reference, so `parity check
        /// --tq-quality` errors clearly when this is absent.
        #[arg(long)]
        fixture: Option<PathBuf>,

        /// Cosine-similarity mean floor for Gate H (industry std 0.999;
        /// day-of-close envelope measured 0.9998).  ADR-007 §853.
        #[arg(long, default_value_t = 0.999)]
        cosine_mean_floor: f32,

        /// Cosine-similarity p1 floor for Gate H (industry std 0.99; day-
        /// of-close envelope measured 0.9986).  ADR-007 §853.
        #[arg(long, default_value_t = 0.99)]
        cosine_p1_floor: f32,

        /// Argmax-flip-rate ceiling for Gate H (W12 1.5%; day-of-close
        /// envelope measured 0.8% — variance baked in).  ADR-007 §853.
        #[arg(long, default_value_t = 0.015)]
        argmax_max: f32,

        /// PPL-delta ceiling for Gate H expressed as a fraction (W12
        /// 0.02 = 2.0%; day-of-close envelope measured 1.24% — variance
        /// baked in).  ADR-007 §866.
        #[arg(long, default_value_t = 0.02)]
        ppl_delta_max: f32,
    },

    /// Capture fresh reference outputs (requires model).
    ///
    /// Default mode: writes the byte-prefix anchor (`<prompt>_hf2q.txt`)
    /// for Gates C/D/E/F.  Pass `--tq-quality` to instead capture the
    /// frozen Gate H envelope fixture (`<prompt>_tq_quality.json`)
    /// described in ADR-007 §853-866.
    Capture {
        /// Path to GGUF model file
        #[arg(long)]
        model: PathBuf,

        /// Output directory for captured references
        #[arg(long, default_value = "tests/evals/reference")]
        output: PathBuf,

        /// Eval prompt name (sourdough, short_hello, sliding_wrap, all)
        #[arg(long, default_value = "all")]
        prompt: String,

        /// Maximum tokens to generate
        #[arg(long)]
        max_tokens: Option<usize>,

        /// ADR-007 Gate H — capture the frozen `<prompt>_tq_quality.json`
        /// fixture instead of the byte-prefix anchor.  Single prompt only
        /// (`all` is rejected); the in-process two-regime decode loop
        /// runs dense pass 1 + TQ pass 2 on one model load and emits the
        /// dense token stream + dense per-step NLL + the day-of-capture
        /// envelope (cosine / argmax / PPL Δ) into the fixture JSON.
        #[arg(long)]
        tq_quality: bool,
    },
}

#[derive(clap::Args, Debug)]
pub struct ParityArgs {
    #[command(subcommand)]
    pub command: ParityCommand,
}

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

    #[test]
    fn serve_no_integrity_default_false() {
        let cli = Cli::parse_from(["hf2q", "serve"]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert!(!args.no_integrity);
    }

    #[test]
    fn source_teacher_requires_explicit_execute_for_model_allocation() {
        let cli = Cli::parse_from([
            "hf2q",
            "source-teacher",
            "--model-dir",
            "/tmp/qwen38-source",
            "--output",
            "/tmp/qwen38-teacher.bin",
            "--evaluation-split",
            "calibration",
        ]);
        let Command::SourceTeacher(args) = cli.command else {
            panic!("expected SourceTeacher");
        };
        assert_eq!(args.model_dir, PathBuf::from("/tmp/qwen38-source"));
        assert_eq!(args.output, PathBuf::from("/tmp/qwen38-teacher.bin"));
        assert_eq!(
            args.evaluation_split,
            SourceTeacherEvaluationSplitArg::Calibration
        );
        assert!(!args.execute);

        let cli = Cli::parse_from([
            "hf2q",
            "source-teacher",
            "--model-dir",
            "/tmp/qwen38-source",
            "--output",
            "/tmp/qwen38-teacher.bin",
            "--evaluation-split",
            "policy-validation",
            "--execute",
        ]);
        let Command::SourceTeacher(args) = cli.command else {
            panic!("expected SourceTeacher");
        };
        assert_eq!(
            args.evaluation_split,
            SourceTeacherEvaluationSplitArg::PolicyValidation
        );
        assert!(args.execute);

        assert!(Cli::try_parse_from([
            "hf2q",
            "source-teacher",
            "--model-dir",
            "/tmp/qwen38-source",
            "--output",
            "/tmp/qwen38-teacher.bin",
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "hf2q",
            "source-teacher",
            "--model-dir",
            "/tmp/qwen38-source",
            "--output",
            "/tmp/qwen38-teacher.bin",
            "--evaluation-split",
            "acceptance-holdout",
        ])
        .is_err());
    }

    #[test]
    fn source_teacher_reference_requires_all_exact_artifacts() {
        let cli = Cli::parse_from([
            "hf2q",
            "source-teacher-reference",
            "--model-dir",
            "/tmp/qwen38-source",
            "--native-summary",
            "/tmp/native.json",
            "--native-target",
            "/tmp/native.bin",
            "--external-evidence",
            "/tmp/reference.json",
            "--external-target",
            "/tmp/reference.bin",
        ]);
        let Command::SourceTeacherReference(args) = cli.command else {
            panic!("expected SourceTeacherReference");
        };
        assert_eq!(args.native_summary, PathBuf::from("/tmp/native.json"));
        assert_eq!(args.native_target, PathBuf::from("/tmp/native.bin"));
        assert_eq!(args.external_evidence, PathBuf::from("/tmp/reference.json"));
        assert_eq!(args.external_target, PathBuf::from("/tmp/reference.bin"));
    }

    #[test]
    fn source_teacher_acceptance_is_a_closed_source_bound_verifier() {
        let cli = Cli::parse_from([
            "hf2q",
            "source-teacher-acceptance-verify",
            "--model-dir",
            "/tmp/qwen38-source",
        ]);
        let Command::SourceTeacherAcceptanceVerify(args) = cli.command else {
            panic!("expected SourceTeacherAcceptanceVerify");
        };
        assert_eq!(args.model_dir, PathBuf::from("/tmp/qwen38-source"));
        assert!(Cli::try_parse_from([
            "hf2q",
            "source-teacher-acceptance-verify",
            "--model-dir",
            "/tmp/qwen38-source",
            "--output",
            "/tmp/holdout.bin",
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "hf2q",
            "source-teacher-acceptance-reference",
            "--model-dir",
            "/tmp/qwen38-source",
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "hf2q",
            "source-teacher-acceptance",
            "--model-dir",
            "/tmp/qwen38-source",
        ])
        .is_err());
    }

    #[test]
    fn chat_defaults_preserve_zero_hidden_request_policy() {
        let cli = Cli::parse_from(["hf2q", "chat", "--url", "http://127.0.0.1:9123"]);
        let Command::Chat(args) = cli.command else {
            panic!("expected Chat");
        };
        assert_eq!(args.url.as_deref(), Some("http://127.0.0.1:9123"));
        assert!(args.model.is_none());
        assert!(args.quant.is_none());
        assert!(args.artifact.is_none());
        assert!(args.system.is_none());
        assert!(args.temperature.is_none());
        assert!(args.top_p.is_none());
        assert!(args.max_tokens.is_none());
        assert!(args.seed.is_none());
        assert!(args.reasoning_effort.is_none());
        assert!(!args.keep_serving);
    }

    #[test]
    fn chat_accepts_explicit_diagnostic_controls() {
        let cli = Cli::parse_from([
            "hf2q",
            "chat",
            "--url",
            "https://localhost:9443",
            "--model",
            "model-a",
            "--system",
            "diagnose only",
            "--temperature",
            "0.2",
            "--top-p",
            "0.8",
            "--max-tokens",
            "512",
            "--seed",
            "7",
            "--reasoning-effort",
            "high",
            "--keep-serving",
        ]);
        let Command::Chat(args) = cli.command else {
            panic!("expected Chat");
        };
        assert_eq!(args.model.as_deref(), Some("model-a"));
        assert_eq!(args.system.as_deref(), Some("diagnose only"));
        assert_eq!(args.temperature, Some(0.2));
        assert_eq!(args.top_p, Some(0.8));
        assert_eq!(args.max_tokens, Some(512));
        assert_eq!(args.seed, Some(7));
        assert_eq!(args.reasoning_effort.as_deref(), Some("high"));
        assert!(args.keep_serving);
    }

    #[test]
    fn chat_accepts_exact_hub_gguf_selection_without_implicit_conversion() {
        let cli = Cli::try_parse_from([
            "hf2q",
            "chat",
            "--model",
            "owner/mixed-source-and-gguf",
            "--quant",
            "q6_k",
        ])
        .expect("diagnostic chat must expose a non-interactive hosted-GGUF selector");
        let Command::Chat(args) = cli.command else {
            panic!("expected Chat");
        };
        assert_eq!(args.quant, Some(DiagnosticQuantArg::Q6K));
        assert!(args.artifact.is_none());

        let exact = Cli::try_parse_from([
            "hf2q",
            "chat",
            "--model",
            "owner/mixed-source-and-gguf",
            "--artifact",
            "gguf/model-q6_k.gguf",
        ])
        .expect("diagnostic chat must expose an exact hosted-GGUF selector");
        let Command::Chat(args) = exact.command else {
            panic!("expected Chat");
        };
        assert_eq!(args.artifact.as_deref(), Some("gguf/model-q6_k.gguf"));
        assert!(args.quant.is_none());

        assert!(Cli::try_parse_from([
            "hf2q",
            "chat",
            "--model",
            "owner/mixed-source-and-gguf",
            "--quant",
            "q6_k",
            "--artifact",
            "gguf/model-q6_k.gguf",
        ])
        .is_err());
    }

    #[test]
    fn generated_zsh_completion_contains_chat_and_diagnostic_selectors() {
        use clap::CommandFactory;

        let mut command = Cli::command();
        let mut output = Vec::new();
        clap_complete::generate(Shell::Zsh, &mut command, "hf2q", &mut output);
        let completion = String::from_utf8(output).unwrap();
        assert!(completion.contains("chat"));
        assert!(completion.contains("--quant"));
        assert!(completion.contains("Q4_K_M"));
        assert!(completion.contains("--artifact"));
        assert!(completion.contains("--keep-serving"));
    }

    #[test]
    fn serve_no_integrity_flag_parses_to_true() {
        let cli = Cli::parse_from(["hf2q", "serve", "--no-integrity"]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert!(args.no_integrity);
    }

    #[test]
    fn serve_accepts_repeatable_local_model_roots() {
        let cli = Cli::parse_from([
            "hf2q",
            "serve",
            "--model-dir",
            "/models/one",
            "--model-dir=/models/two",
        ]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert_eq!(
            args.model_dirs,
            vec![PathBuf::from("/models/one"), PathBuf::from("/models/two")]
        );
    }

    #[test]
    fn serve_operator_ui_defaults_to_auto_and_accepts_plain() {
        let cli = Cli::parse_from(["hf2q", "serve"]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert_eq!(args.operator_ui, OperatorUiArg::Auto);

        let cli = Cli::parse_from(["hf2q", "serve", "--operator-ui", "plain"]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert_eq!(args.operator_ui, OperatorUiArg::Plain);
    }

    #[test]
    fn convert_revision_is_bound_to_repo_download() {
        let cli = Cli::parse_from([
            "hf2q",
            "convert",
            "--repo",
            "deepseek-ai/DeepSeek-V4-Flash-0731",
            "--revision",
            "7872f01b1d1fe23eabc4c98b48bffcef5a386062",
            "--quant",
            "q2_k_s",
            "-o",
            "/tmp/deepseek4.gguf",
        ]);
        let Command::Convert(args) = cli.command else {
            panic!("expected Convert");
        };
        assert_eq!(
            args.revision.as_deref(),
            Some("7872f01b1d1fe23eabc4c98b48bffcef5a386062")
        );
    }

    #[test]
    fn convert_revision_is_accepted_for_positional_remote_reference() {
        let cli = Cli::parse_from([
            "hf2q",
            "convert",
            "Qwen/Qwen3.8-27B",
            "--revision",
            "main",
            "--quant",
            "q2_k_s",
            "-o",
            "/tmp/deepseek4.gguf",
        ]);
        let Command::Convert(args) = cli.command else {
            panic!("expected Convert");
        };
        assert_eq!(args.revision.as_deref(), Some("main"));
        assert_eq!(args.hf_dir, Some(PathBuf::from("Qwen/Qwen3.8-27B")));
    }

    #[test]
    fn convert_multimodal_pair_is_default_and_text_only_is_explicit() {
        let default = Cli::parse_from([
            "hf2q",
            "convert",
            "/tmp/multimodal-source",
            "--quant",
            "q4_k_m",
            "--output",
            "/tmp/model.gguf",
        ]);
        let Command::Convert(default) = default.command else {
            panic!("expected Convert");
        };
        assert!(!default.mmproj);
        assert!(!default.text_only);

        let text_only = Cli::parse_from([
            "hf2q",
            "convert",
            "/tmp/multimodal-source",
            "--quant",
            "q4_k_m",
            "--output",
            "/tmp/model.gguf",
            "--text-only",
        ]);
        let Command::Convert(text_only) = text_only.command else {
            panic!("expected Convert");
        };
        assert!(text_only.text_only);
        assert!(!text_only.mmproj);
    }

    #[test]
    fn convert_projector_only_conflicts_with_text_only() {
        assert!(Cli::try_parse_from([
            "hf2q",
            "convert",
            "/tmp/multimodal-source",
            "--quant",
            "q4_k_m",
            "--output",
            "/tmp/model.gguf",
            "--mmproj",
            "--text-only",
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "hf2q",
            "convert",
            "/tmp/multimodal-source",
            "--quant",
            "q4_k_m",
            "--output",
            "/tmp/model.gguf",
            "--mmproj",
            "--mmproj-output",
            "/tmp/projector.gguf",
        ])
        .is_err());
        assert!(Cli::try_parse_from([
            "hf2q",
            "convert",
            "/tmp/multimodal-source",
            "--quant",
            "q4_k_m",
            "--output",
            "/tmp/model.gguf",
            "--text-only",
            "--mmproj-output",
            "/tmp/projector.gguf",
        ])
        .is_err());
    }

    #[test]
    fn getting_started_qwen38_commands_parse_exactly() {
        let revision = "08c2f075b43bc06456382db6b918a3dcabdcf4dd";
        let model = "/tmp/Qwen3.8-27B-Abliterated-SFT-Q4_K_M.gguf";
        let cli = Cli::parse_from(["hf2q", "setup", "--accept-defaults"]);
        let Command::Setup(args) = cli.command else {
            panic!("expected Setup");
        };
        assert!(args.accept_defaults);

        let cli = Cli::parse_from([
            "hf2q",
            "convert",
            "jenerallee78/Qwen3.8-27B-Abliterated-SFT",
            "--revision",
            revision,
            "--quant",
            "q4_k_m",
            "--output",
            model,
        ]);
        let Command::Convert(args) = cli.command else {
            panic!("expected Convert");
        };
        assert_eq!(
            args.hf_dir,
            Some(PathBuf::from("jenerallee78/Qwen3.8-27B-Abliterated-SFT"))
        );
        assert_eq!(args.revision.as_deref(), Some(revision));
        assert_eq!(args.quant.as_deref(), Some("q4_k_m"));
        assert_eq!(args.output, PathBuf::from(model));

        let cli = Cli::parse_from(["hf2q", "serve", "--model", model]);
        let Command::Serve(args) = cli.command else {
            panic!("expected Serve");
        };
        assert_eq!(args.model, Some(PathBuf::from(model)));
        assert!(args.host.is_none());
        assert!(args.port.is_none());
        assert!(args.scheduler.is_none());
        assert!(args.max_slots.is_none());
        assert!(args.mmproj.is_none());

        let endpoint = "http://127.0.0.1:8081/v1";
        let cli = Cli::parse_from(["hf2q", "chat", "--url", endpoint]);
        let Command::Chat(args) = cli.command else {
            panic!("expected Chat");
        };
        assert_eq!(args.url.as_deref(), Some(endpoint));
        assert!(args.model.is_none());
    }
}