runx-cli 0.6.19

Cargo-installed launcher for the runx governed agent workflow CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
// rust-style-allow: large-file - router argument parity is centralized for CLI routing tests.
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;

use crate::cli_args::{flag_value, optional_flag_value, os_arg, split_flag};
use crate::config::ConfigPlan;
use crate::export::ExportPlan;
use crate::kernel::{KernelInputSource, KernelPlan};
use crate::login::LoginPlan;
use crate::mcp::McpPlan;
use crate::parser::{ParserInputSource, ParserPlan};
use crate::payment::{PaymentAction, PaymentAdmissionPlan, PaymentInputSource, PaymentPlan};
use crate::policy::{PolicyAction, PolicyPlan};
use crate::publish::PublishPlan;
use crate::registry::{RegistryAction, RegistryPlan};
use crate::resume::ResumePlan;
use crate::skill::SkillPlan;
use runx_runtime::registry::parse_registry_ref;

#[derive(Debug, PartialEq)]
pub enum RouterAction {
    Error(String),
    JsonError(JsonErrorPlan),
    RunDev(DevPlan),
    RunDoctor(DoctorPlan),
    RunExport(ExportPlan),
    RunInit(InitPlan),
    RunList(ListPlan),
    RunLogin(LoginPlan),
    RunMcp(McpPlan),
    RunParser(ParserPlan),
    RunNew(NewPlan),
    RunHistory(HistoryPlan),
    RunVerify(VerifyPlan),
    RunHarness(HarnessPlan),
    RunKernel(KernelPlan),
    RunPayment(PaymentPlan),
    RunConfig(ConfigPlan),
    RunPolicy(PolicyPlan),
    RunPublish(PublishPlan),
    RunRegistry(RegistryPlan),
    RunResume(ResumePlan),
    RunSkill(SkillPlan),
    RunTool(ToolPlan),
    RunAddUrl(AddUrlPlan),
    PrintHelp,
    PrintAddHelp,
    PrintHistoryHelp,
    PrintListHelp,
    PrintLoginHelp,
    PrintPublishHelp,
    PrintRegistryHelp,
    PrintRegistryUsageError,
    PrintResumeHelp,
    PrintSkillHelp,
    PrintVerifyHelp,
    PrintVersion,
}

#[derive(Debug, Eq, PartialEq)]
pub struct JsonErrorPlan {
    pub message: String,
    pub code: String,
    pub exit_code: u8,
}

/// Arguments for indexing a GitHub repository via `runx add <github-url>`.
#[derive(Debug, Eq, PartialEq)]
pub struct AddUrlPlan {
    pub repo: String,
    pub repo_ref: Option<String>,
    pub api_base_url: Option<String>,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub struct DevPlan {
    pub root: Option<PathBuf>,
    pub lane: Option<String>,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub struct HarnessPlan {
    /// Replay targets: standalone fixture `.yaml` files, or a skill package
    /// (directory / `SKILL.md`) whose declared inline `harness.cases` are run.
    pub fixture_paths: Vec<OsString>,
    /// Where receipts the cases seal are written (`--receipt-dir`).
    pub receipt_dir: Option<OsString>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct HistoryPlan {
    pub args: Vec<OsString>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct VerifyPlan {
    pub args: Vec<OsString>,
}

#[derive(Debug, Eq, PartialEq)]
pub struct DoctorPlan {
    pub mode: DoctorMode,
    pub path: Option<PathBuf>,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub enum DoctorMode {
    Workspace,
    Authority,
    Registry,
}

#[derive(Debug, Eq, PartialEq)]
pub struct ListPlan {
    pub kind: ListKind,
    pub filter: FilterMode,
    pub json: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum FilterMode {
    #[default]
    All,
    OkOnly,
    InvalidOnly,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ListKind {
    All,
    Tools,
    Skills,
    Graphs,
    Packets,
    Overlays,
}

#[derive(Debug, Eq, PartialEq)]
pub struct NewPlan {
    pub name: String,
    pub directory: Option<PathBuf>,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub struct InitPlan {
    pub global: bool,
    pub prefetch_official: bool,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub struct ToolPlan {
    pub action: ToolAction,
    pub path: Option<PathBuf>,
    pub ref_or_query: Option<String>,
    pub all: bool,
    pub source: Option<String>,
    pub json: bool,
}

#[derive(Debug, Eq, PartialEq)]
pub enum ToolAction {
    Build,
    Search,
    Inspect,
}

// rust-style-allow: long-function because router routing is the cutover gate:
// every native command branch and fail-closed decision is reviewed here.
pub fn route_args(args: Vec<OsString>) -> RouterAction {
    if args.is_empty() || single_arg_is(&args, "--help") || single_arg_is(&args, "-h") {
        return RouterAction::PrintHelp;
    }

    if single_arg_is(&args, "--version") || single_arg_is(&args, "-V") {
        return RouterAction::PrintVersion;
    }

    if first_arg_is(&args, "harness") {
        return native_harness_plan(&args);
    }

    if first_arg_is(&args, "config") {
        return crate::config::parse_config_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunConfig);
    }

    if first_arg_is(&args, "login") {
        if nested_help_requested(&args) {
            return RouterAction::PrintLoginHelp;
        }
        return crate::login::parse_login_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunLogin);
    }

    if first_arg_is(&args, "policy") {
        return parse_policy_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunPolicy);
    }

    if first_arg_is(&args, "publish") {
        if nested_help_requested(&args) {
            return RouterAction::PrintPublishHelp;
        }
        return crate::publish::parse_publish_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunPublish);
    }

    if first_arg_is(&args, "kernel") {
        return parse_kernel_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunKernel);
    }

    if first_arg_is(&args, "payment") {
        return parse_payment_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunPayment);
    }

    if first_arg_is(&args, "parser") {
        return parse_parser_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunParser);
    }

    if first_arg_is(&args, "doctor") {
        return parse_doctor_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunDoctor);
    }

    if first_arg_is(&args, "dev") {
        return parse_dev_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunDev);
    }

    if first_arg_is(&args, "export") {
        if args.len() == 2
            && args
                .get(1)
                .and_then(|arg| arg.to_str())
                .is_some_and(|arg| matches!(arg, "--help" | "-h"))
        {
            return RouterAction::PrintHelp;
        }
        return crate::export::parse_export_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunExport);
    }

    if first_arg_is(&args, "list") {
        if nested_help_requested(&args) {
            return RouterAction::PrintListHelp;
        }
        return parse_list_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunList);
    }

    if first_arg_is(&args, "new") {
        return parse_new_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunNew);
    }

    if first_arg_is(&args, "init") {
        return parse_init_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunInit);
    }

    if first_arg_is(&args, "history") {
        if nested_help_requested(&args) {
            return RouterAction::PrintHistoryHelp;
        }
        return RouterAction::RunHistory(HistoryPlan { args });
    }

    if first_arg_is(&args, "resume") {
        if nested_help_requested(&args) {
            return RouterAction::PrintResumeHelp;
        }
        return crate::resume::parse_resume_plan(&args).map_or_else(
            |message| json_or_human_error(&args, message),
            RouterAction::RunResume,
        );
    }

    if first_arg_is(&args, "verify") {
        if nested_help_requested(&args) {
            return RouterAction::PrintVerifyHelp;
        }
        return RouterAction::RunVerify(VerifyPlan { args });
    }

    if first_arg_is(&args, "mcp") {
        if mcp_runner_before_serve(&args) {
            return RouterAction::Error(
                "runx mcp --runner must follow the serve subcommand".to_owned(),
            );
        }
        return crate::mcp::parse_mcp_plan(&args)
            .map_or_else(RouterAction::Error, RouterAction::RunMcp);
    }

    if first_arg_is(&args, "tool") {
        return parse_tool_plan(&args).map_or_else(RouterAction::Error, RouterAction::RunTool);
    }

    if first_arg_is(&args, "registry") {
        if nested_help_requested(&args) {
            return RouterAction::PrintRegistryHelp;
        }
        if args.len() == 1 {
            return RouterAction::PrintRegistryUsageError;
        }
        return parse_registry_plan(&args).map_or_else(
            |message| json_or_human_error(&args, message),
            RouterAction::RunRegistry,
        );
    }

    if first_arg_is(&args, "add") {
        if nested_help_requested(&args) {
            return RouterAction::PrintAddHelp;
        }
        return parse_add_plan(&args).unwrap_or_else(|message| json_or_human_error(&args, message));
    }

    if first_arg_is(&args, "skill") {
        if nested_help_requested(&args) {
            return RouterAction::PrintSkillHelp;
        }
        if second_arg_is(&args, "add") {
            return json_or_human_error(
                &args,
                "runx skill add has been removed; use runx add <ref>".to_owned(),
            );
        }
        return crate::skill::parse_skill_plan(&args).map_or_else(
            |message| json_or_human_error(&args, message),
            RouterAction::RunSkill,
        );
    }

    RouterAction::Error(format!(
        "unknown command {}",
        args.first()
            .and_then(|arg| arg.to_str())
            .unwrap_or("<non-utf8>")
    ))
}

pub fn help_text() -> String {
    "\
runx

Usage:
  runx <command> [args]
  runx --help
  runx --version

Commands:
  runx new <name> [--directory dir] [--json]
  runx init [-g|--global] [--prefetch official] [--json]
  runx verify [receipt-id] [--receipt-dir dir] [--receipt <path|->] [--notary <path|-> --notary-key trusted.pem] [-j|--json]
  runx history [query] [--skill s] [--status s] [--source s] [--actor a] [--artifact-type t] [--since iso] [--until iso] [--receipt-dir dir] [--json]
  runx resume <run-id> <answers.json> [-R dir] [-j|--json]
  runx list [tools|skills|graphs|packets|overlays] [--ok-only|--invalid-only] [-j|--json]
  runx login [--provider github|google|gitlab] [--for default|publish] [--api-base-url url] [--allow-local-api] [-j|--json]
  runx config set|get|list [provider|model|api-key|public-token] [value] [-j|--json]
  runx policy inspect|lint <policy.json> [--json]
  runx publish <receipt.json> [--api-base-url url] [--token token] [--allow-local-api] [-j|--json]
  runx kernel eval --input <file|-> --json
  runx payment admission issue --input <file|-> --json
  runx parser eval --input <file|-> --json
  runx doctor [path|authority|registry] [--json]
  runx dev [root] [--lane lane] [--json]
  runx export <claude|codex> [skill-ref...] [--project] [--json]
  runx mcp serve <skill-ref...> [--receipt-dir dir] [--http-listen [addr]] [--http-allow-non-loopback]
  runx skill <skill-ref|owner/name@version|skill-dir|SKILL.md> [runner] [-p profile] [-i key=value] [--input-json key=json] [-j] [--registry url|path] [--digest sha256] [--flag value] [--credential descriptor --secret-env NAME] [-R dir]
  runx skill inspect <skill-ref|owner/name@version|skill-dir|SKILL.md> [runner] [-j] [--registry url|path] [--digest sha256]
  runx add <skill-ref|github-url> [--registry url|path] [--version version] [--ref git-ref] [--digest sha256] [--to dir] [--api-base-url url] [--json]
  runx harness <fixture.yaml...|skill-dir|SKILL.md> [-R dir] [-j|--json]
  runx tool build <tool-dir>|--all [--json]
  runx tool search <query> [--source source] [--json]
  runx tool inspect <ref> [--source source] [--json]
  runx registry search|read|resolve|install|publish ... --json
"
    .to_owned()
}

pub fn history_help_text() -> String {
    "\
runx history

Usage:
  runx history [query] [--skill s] [--status s] [--source s] [--actor a] [--artifact-type t] [--since iso] [--until iso] [--receipt-dir dir] [--json]

Options:
  --skill s
  --status s
  --source s
  --actor a
  --artifact-type t
  --since iso
  --until iso
  --receipt-dir dir
  --json
"
    .to_owned()
}

pub fn resume_help_text() -> String {
    "\
runx resume

Usage:
  runx resume <run-id> <answers.json> [-R dir] [-j|--json]

Options:
  -R, --receipts dir
  --receipt-dir dir
  -j, --json
"
    .to_owned()
}

pub fn list_help_text() -> String {
    "\
runx list

Usage:
  runx list [tools|skills|graphs|packets|overlays] [--ok-only|--invalid-only] [-j|--json]

Options:
  --ok-only
  --invalid-only
  -j, --json
"
    .to_owned()
}

pub fn login_help_text() -> String {
    "\
runx login

Usage:
  runx login [--provider github|google|gitlab] [--for default|publish] [--api-base-url url] [--allow-local-api] [-j|--json]

Options:
  --provider provider
  --for purpose
  --api-base-url url
  --allow-local-api
  -j, --json
"
    .to_owned()
}

pub fn publish_help_text() -> String {
    "\
runx publish

Usage:
  runx publish <receipt.json> [--api-base-url url] [--token token] [--allow-local-api] [-j|--json]

Options:
  --api-base-url url  Public API base URL (default: RUNX_PUBLIC_API_BASE_URL or https://api.runx.ai)
  --token token       Public API token (default: RUNX_PUBLIC_API_TOKEN or runx login)
  --allow-local-api   Allow loopback/private public API URLs for local dogfood only
  -j, --json          Print the raw notary response as JSON
"
    .to_owned()
}

pub fn add_help_text() -> String {
    "\
runx add

Usage:
  runx add <skill-ref|github-url> [--registry url|path] [--version version] [--ref git-ref] [--digest sha256] [--to dir] [--api-base-url url] [--json]

Options:
  --registry url|path  Registry URL or local registry path for skill refs
  --version version    Registry version for skill refs
  --ref git-ref        Git ref for GitHub repository URLs
  --digest sha256      Expected package digest for skill refs
  --to dir             Install destination for skill refs
  --api-base-url url   Hosted index API for GitHub repository URLs
  -j, --json
"
    .to_owned()
}

pub fn registry_help_text() -> String {
    "\
runx registry

Usage:
  runx registry search <query> [--registry url|path] [--registry-dir dir] [--limit n] [-j|--json]
  runx registry read <ref> [--registry url|path] [--registry-dir dir] [--version version] [-j|--json]
  runx registry resolve <ref> [--registry url|path] [--registry-dir dir] [--version version] [-j|--json]
  runx registry install <ref> [--registry url|path] [--registry-dir dir] [--version version] [--digest sha256] [--to dir] [-j|--json]
  runx registry publish <SKILL.md|skill-dir> [--registry url|path] [--owner owner] [--version version] [--profile X.yaml] [--trust-tier tier] [--upsert] [-j|--json]

Options:
  --registry url|path
  --registry-dir dir
  --version version
  --digest sha256
  --to dir
  --owner owner
  --profile X.yaml
  --trust-tier first_party|verified|community
  --limit n
  --upsert
  -j, --json
"
    .to_owned()
}

pub fn verify_help_text() -> String {
    "\
runx verify

Usage:
  runx verify [receipt-id] [--receipt-dir dir] [--receipt <path|->] [--notary <path|-> --notary-key trusted.pem] [-j|--json]

Options:
  --receipt-dir dir
  --receipt <path|->
  --notary <path|->
  --notary-key trusted.pem
  -j, --json
"
    .to_owned()
}

pub fn skill_help_text() -> String {
    "\
runx skill

Usage:
  runx skill <skill-ref|owner/name@version|skill-dir|SKILL.md> [runner] [-p profile] [-i key=value] [--input-json key=json] [-j] [--registry url|path] [--digest sha256] [--flag value] [--credential descriptor --secret-env NAME] [-R dir]
  runx skill inspect <skill-ref|owner/name@version|skill-dir|SKILL.md> [runner] [-j] [--registry url|path] [--digest sha256]

Options:
  -p, --profile name       Use a local credential profile from .runx/credentials.json
  -i, --input key=value    Set a structured input; repeat for multiple inputs
  --input-json key=json    Set an input that must parse as JSON
  -R, --receipts dir       Write receipts under dir
  --receipt-dir dir        Alias for --receipts
  -j, --json               Print machine-readable output
  --registry url|path
  --digest sha256
  --flag value
  --credential descriptor  One-shot local credential descriptor
  --secret-env NAME        Env var holding the one-shot credential secret
"
    .to_owned()
}

pub fn json_failure_output(message: &str, code: &str) -> String {
    let message = json_string(message, "failed to serialize error message");
    let code = json_string(code, "runtime_error");
    format!(
        "{{\n  \"status\": \"failure\",\n  \"error\": {{\n    \"message\": {message},\n    \"code\": {code}\n  }}\n}}\n"
    )
}

pub fn json_requested(args: &[OsString]) -> bool {
    args.iter().any(|arg| {
        arg.to_str()
            .is_some_and(|token| token == "--json" || token.starts_with("--json="))
    })
}

fn single_arg_is(args: &[OsString], expected: &str) -> bool {
    args.len() == 1 && first_arg_is(args, expected)
}

fn second_arg_is(args: &[OsString], expected: &str) -> bool {
    args.get(1).is_some_and(|arg| arg == OsStr::new(expected))
}

fn json_or_human_error(args: &[OsString], message: String) -> RouterAction {
    if json_requested(args) {
        RouterAction::JsonError(JsonErrorPlan {
            message,
            code: "invalid_args".to_owned(),
            exit_code: 64,
        })
    } else {
        RouterAction::Error(message)
    }
}

fn json_string(value: &str, fallback: &str) -> String {
    match serde_json::to_string(value) {
        Ok(value) => value,
        Err(_) => format!("\"{fallback}\""),
    }
}

fn nested_help_requested(args: &[OsString]) -> bool {
    args.iter()
        .skip(1)
        .any(|arg| matches!(arg.to_str(), Some("--help" | "-h")))
}

fn first_arg_is(args: &[OsString], expected: &str) -> bool {
    args.first().is_some_and(|arg| arg == OsStr::new(expected))
}

fn mcp_runner_before_serve(args: &[OsString]) -> bool {
    args.iter()
        .skip(1)
        .take_while(|arg| arg.as_os_str() != OsStr::new("serve"))
        .any(|arg| {
            arg.to_str()
                .is_some_and(|token| token == "--runner" || token.starts_with("--runner="))
        })
}

// rust-style-allow: long-function - harness flag parsing stays local to the
// router boundary so native dispatch does not grow a second parser surface.
fn native_harness_plan(args: &[OsString]) -> RouterAction {
    let mut fixture_paths = Vec::new();
    let mut receipt_dir = None;
    let mut index = 1;

    while index < args.len() {
        let Some(token) = args.get(index).and_then(|arg| arg.to_str()) else {
            return RouterAction::Error("harness arguments must be UTF-8".to_owned());
        };

        if !token.starts_with('-') {
            fixture_paths.push(args[index].clone());
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" | "-j" => {
                if inline_value.is_some() {
                    return RouterAction::Error("--json does not take a value".to_owned());
                }
                index += 1;
            }
            "--receipt-dir" | "--receipts" => match inline_value {
                Some(value) => {
                    receipt_dir = Some(OsString::from(value));
                    index += 1;
                }
                None => {
                    let Some(value) = args.get(index + 1) else {
                        return RouterAction::Error(
                            "--receipt-dir requires a directory".to_owned(),
                        );
                    };
                    receipt_dir = Some(value.clone());
                    index += 2;
                }
            },
            "-R" => {
                if inline_value.is_some() {
                    return RouterAction::Error(
                        "-R requires a separate directory value".to_owned(),
                    );
                }
                let Some(value) = args.get(index + 1) else {
                    return RouterAction::Error("-R requires a directory".to_owned());
                };
                receipt_dir = Some(value.clone());
                index += 2;
            }
            _ => return RouterAction::Error(format!("unknown harness flag {flag}")),
        }
    }

    if fixture_paths.is_empty() {
        return RouterAction::Error(
            "runx harness requires a fixture path or skill package".to_owned(),
        );
    }

    RouterAction::RunHarness(HarnessPlan {
        fixture_paths,
        receipt_dir,
    })
}

fn parse_new_plan(args: &[OsString]) -> Result<NewPlan, String> {
    let mut name = None;
    let mut directory = None;
    let mut json = false;
    let mut positional_directory = None;
    let mut extra_positionals = Vec::new();
    let mut index = 1;

    while index < args.len() {
        let token = os_arg(args, index, "new")?;
        if !token.starts_with("--") {
            if name.is_none() {
                name = Some(token.to_owned());
            } else if positional_directory.is_none() {
                positional_directory = Some(PathBuf::from(token));
            } else {
                extra_positionals.push(token.to_owned());
            }
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            "--directory" | "--dir" => {
                let (value, next_index) = flag_value(args, index, flag, inline_value, "new")?;
                directory = Some(PathBuf::from(value));
                index = next_index;
            }
            _ => return Err(format!("unknown new flag {flag}")),
        }
    }

    if !extra_positionals.is_empty() {
        return Err("runx new accepts at most one directory argument".to_owned());
    }

    Ok(NewPlan {
        name: name.ok_or_else(|| "runx new requires a package name".to_owned())?,
        directory: directory.or(positional_directory),
        json,
    })
}

fn parse_add_plan(args: &[OsString]) -> Result<RouterAction, String> {
    let parsed = parse_add_args(args)?;
    if is_github_repo_url_like(parsed.subject.as_deref().unwrap_or_default()) {
        return add_url_plan(parsed).map(RouterAction::RunAddUrl);
    }
    add_registry_plan(parsed).map(RouterAction::RunRegistry)
}

#[derive(Default)]
struct AddParseState {
    subject: Option<String>,
    registry: Option<String>,
    version: Option<String>,
    repo_ref: Option<String>,
    expected_digest: Option<String>,
    destination: Option<PathBuf>,
    api_base_url: Option<String>,
    json: bool,
}

fn parse_add_args(args: &[OsString]) -> Result<AddParseState, String> {
    let mut parsed = AddParseState::default();
    let mut index = 1;
    while index < args.len() {
        let token = os_arg(args, index, "add")?;
        if !token.starts_with("--") {
            if parsed.subject.is_some() {
                return Err("runx add accepts exactly one ref or repository URL".to_owned());
            }
            parsed.subject = Some(token.to_owned());
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        index = parse_add_flag(&mut parsed, args, index, flag, inline_value)?;
    }
    if parsed.subject.is_none() {
        return Err("runx add requires a skill ref or repository URL".to_owned());
    }
    Ok(parsed)
}

fn parse_add_flag(
    parsed: &mut AddParseState,
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
) -> Result<usize, String> {
    match flag {
        "--json" => {
            if inline_value.is_some() {
                return Err("--json does not take a value".to_owned());
            }
            parsed.json = true;
            Ok(index + 1)
        }
        "--registry" => set_add_string(args, index, flag, inline_value, &mut parsed.registry),
        "--version" => set_add_string(args, index, flag, inline_value, &mut parsed.version),
        "--ref" => set_add_string(args, index, flag, inline_value, &mut parsed.repo_ref),
        "--digest" => set_add_string(args, index, flag, inline_value, &mut parsed.expected_digest),
        "--to" => {
            let (value, next_index) = flag_value(args, index, flag, inline_value, "add")?;
            parsed.destination = Some(PathBuf::from(value));
            Ok(next_index)
        }
        "--api-base-url" => {
            set_add_string(args, index, flag, inline_value, &mut parsed.api_base_url)
        }
        _ => Err(format!("unknown add flag {flag}")),
    }
}

fn set_add_string(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    slot: &mut Option<String>,
) -> Result<usize, String> {
    let (value, next_index) = flag_value(args, index, flag, inline_value, "add")?;
    *slot = Some(value);
    Ok(next_index)
}

fn add_url_plan(parsed: AddParseState) -> Result<AddUrlPlan, String> {
    if parsed.registry.is_some() {
        return Err(
            "runx add <github-url> uses --api-base-url for the hosted index API, not --registry"
                .to_owned(),
        );
    }
    if parsed.version.is_some() {
        return Err("runx add <github-url> uses --ref for git refs, not --version".to_owned());
    }
    if parsed.expected_digest.is_some() || parsed.destination.is_some() {
        return Err(
            "runx add <github-url> indexes the repository and does not support --to or --digest"
                .to_owned(),
        );
    }
    Ok(AddUrlPlan {
        repo: parsed.subject.unwrap_or_default(),
        repo_ref: parsed.repo_ref,
        api_base_url: parsed.api_base_url,
        json: parsed.json,
    })
}

fn add_registry_plan(parsed: AddParseState) -> Result<RegistryPlan, String> {
    if parsed.repo_ref.is_some() {
        return Err(
            "runx add <skill-ref> uses --version for registry versions, not --ref".to_owned(),
        );
    }
    if parsed.api_base_url.is_some() {
        return Err("runx add <skill-ref> does not accept --api-base-url".to_owned());
    }
    Ok(RegistryPlan {
        action: RegistryAction::Install,
        subject: parsed.subject.unwrap_or_default(),
        registry: parsed.registry,
        registry_dir: None,
        version: parsed.version,
        expected_digest: parsed.expected_digest,
        destination: parsed.destination,
        owner: None,
        profile: None,
        trust_tier: None,
        limit: None,
        upsert: false,
        json: parsed.json,
    })
}

fn is_github_repo_url_like(value: &str) -> bool {
    let value = value.trim();
    let Some(path) = value
        .strip_prefix("https://github.com/")
        .or_else(|| value.strip_prefix("http://github.com/"))
        .or_else(|| value.strip_prefix("github.com/"))
    else {
        return false;
    };
    let mut parts = path.split('/').filter(|part| !part.is_empty());
    parts.next().is_some() && parts.next().is_some()
}

fn parse_init_plan(args: &[OsString]) -> Result<InitPlan, String> {
    let mut global = false;
    let mut prefetch_official = false;
    let mut json = false;
    let mut index = 1;

    while index < args.len() {
        let token = os_arg(args, index, "init")?;
        if token == "-g" {
            global = true;
            index += 1;
            continue;
        }
        if !token.starts_with("--") {
            return Err(format!("unexpected init argument {token}"));
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            "--global" => {
                if inline_value.is_some() {
                    return Err("--global does not take a value".to_owned());
                }
                global = true;
                index += 1;
            }
            "--prefetch" | "--prefetch-official" => {
                if matches!(inline_value, Some("false") | Some("0")) {
                    prefetch_official = false;
                    index += 1;
                    continue;
                }
                let (value, next_index) = optional_flag_value(args, index, inline_value, "init")?;
                prefetch_official = value.is_none_or(|value| truthy(&value));
                index = next_index;
            }
            _ => return Err(format!("unknown init flag {flag}")),
        }
    }

    Ok(InitPlan {
        global,
        prefetch_official,
        json,
    })
}

fn parse_dev_plan(args: &[OsString]) -> Result<DevPlan, String> {
    let mut root = None;
    let mut lane = None;
    let mut json = false;
    let mut index = 1;

    while index < args.len() {
        let token = os_arg(args, index, "dev")?;
        if !token.starts_with("--") {
            if root.is_some() {
                return Err("runx dev accepts at most one root path".to_owned());
            }
            root = Some(PathBuf::from(token));
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            "--lane" => {
                let (value, next_index) = flag_value(args, index, flag, inline_value, "dev")?;
                if value.is_empty() {
                    return Err("--lane must not be empty".to_owned());
                }
                lane = Some(value);
                index = next_index;
            }
            _ => return Err(format!("unknown dev flag {flag}")),
        }
    }

    Ok(DevPlan { root, lane, json })
}

fn parse_doctor_plan(args: &[OsString]) -> Result<DoctorPlan, String> {
    let mut mode = DoctorMode::Workspace;
    let mut path = None;
    let mut json = false;
    let mut index = 1;

    while index < args.len() {
        let token = os_arg(args, index, "doctor")?;
        if !token.starts_with('-') {
            if matches!(token, "authority" | "registry")
                && path.is_none()
                && mode == DoctorMode::Workspace
            {
                mode = if token == "authority" {
                    DoctorMode::Authority
                } else {
                    DoctorMode::Registry
                };
                index += 1;
                continue;
            }
            if mode != DoctorMode::Workspace {
                return Err(format!(
                    "runx doctor {} does not accept a path",
                    doctor_mode_name(&mode)
                ));
            }
            if path.is_some() {
                return Err("runx doctor accepts at most one path".to_owned());
            }
            path = Some(PathBuf::from(token));
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" | "-j" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            _ => return Err(format!("unknown doctor flag {flag}")),
        }
    }

    Ok(DoctorPlan { mode, path, json })
}

fn doctor_mode_name(mode: &DoctorMode) -> &'static str {
    match mode {
        DoctorMode::Workspace => "workspace",
        DoctorMode::Authority => "authority",
        DoctorMode::Registry => "registry",
    }
}

fn parse_list_plan(args: &[OsString]) -> Result<ListPlan, String> {
    let mut kind = ListKind::All;
    let mut filter = FilterMode::All;
    let mut json = false;
    let mut saw_kind = false;
    let mut index = 1;

    while index < args.len() {
        let token = os_arg(args, index, "list")?;
        if !token.starts_with('-') {
            if saw_kind {
                return Err("runx list accepts at most one kind".to_owned());
            }
            kind = parse_list_kind(token).ok_or_else(|| {
                "runx list kind must be tools, skills, graphs, packets, or overlays".to_owned()
            })?;
            saw_kind = true;
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        if inline_value.is_some() {
            return Err(format!("{flag} does not take a value"));
        }
        let requested = match flag {
            "--json" | "-j" => {
                json = true;
                index += 1;
                continue;
            }
            "--ok-only" | "--okOnly" => FilterMode::OkOnly,
            "--invalid-only" | "--invalidOnly" => FilterMode::InvalidOnly,
            _ => return Err(format!("unknown list flag {flag}")),
        };
        if filter != FilterMode::All && filter != requested {
            return Err("runx list accepts either --ok-only or --invalid-only".to_owned());
        }
        filter = requested;
        index += 1;
    }

    Ok(ListPlan { kind, filter, json })
}

fn parse_list_kind(value: &str) -> Option<ListKind> {
    match value {
        "tools" => Some(ListKind::Tools),
        "skills" => Some(ListKind::Skills),
        "graphs" => Some(ListKind::Graphs),
        "packets" => Some(ListKind::Packets),
        "overlays" => Some(ListKind::Overlays),
        _ => None,
    }
}

fn parse_kernel_plan(args: &[OsString]) -> Result<KernelPlan, String> {
    let subcommand = os_arg(args, 1, "kernel")?;
    if subcommand != "eval" {
        return Err(format!("unknown kernel subcommand {subcommand}"));
    }
    let parsed = parse_json_eval_input(
        args,
        2,
        JsonEvalCommand {
            command: "kernel",
            subject: "kernel eval",
            duplicate_input: "runx kernel eval accepts exactly one --input",
            requires_json: "runx kernel eval requires --json",
            requires_input: "runx kernel eval requires --input <file|->",
        },
    )?;
    Ok(KernelPlan {
        input: parsed.input.into_kernel_source(),
        json: true,
    })
}

// rust-style-allow: long-function because this flat argument parser walks the
// payment subcommand grammar in a single readable pass; extracting sub-parsers
// would obscure which flags belong to which positional verb.
fn parse_payment_plan(args: &[OsString]) -> Result<PaymentPlan, String> {
    let topic = os_arg(args, 1, "payment")?;
    if topic != "admission" {
        return Err(format!("unknown payment subcommand {topic}"));
    }
    let action = os_arg(args, 2, "payment admission")?;
    if action != "issue" {
        return Err(format!("unknown payment admission subcommand {action}"));
    }
    let parsed = parse_json_eval_input(
        args,
        3,
        JsonEvalCommand {
            command: "payment admission issue",
            subject: "payment admission issue",
            duplicate_input: "runx payment admission issue accepts exactly one --input",
            requires_json: "runx payment admission issue requires --json",
            requires_input: "runx payment admission issue requires --input <file|->",
        },
    )?;
    Ok(PaymentPlan {
        action: PaymentAction::IssueAdmission(PaymentAdmissionPlan {
            input: parsed.input.into_payment_source(),
            json: true,
        }),
    })
}

fn parse_parser_plan(args: &[OsString]) -> Result<ParserPlan, String> {
    let subcommand = os_arg(args, 1, "parser")?;
    if subcommand != "eval" {
        return Err(format!("unknown parser subcommand {subcommand}"));
    }
    let parsed = parse_json_eval_input(
        args,
        2,
        JsonEvalCommand {
            command: "parser",
            subject: "parser eval",
            duplicate_input: "runx parser eval accepts exactly one --input",
            requires_json: "runx parser eval requires --json",
            requires_input: "runx parser eval requires --input <file|->",
        },
    )?;
    Ok(ParserPlan {
        input: parsed.input.into_parser_source(),
        json: true,
    })
}

struct JsonEvalCommand {
    command: &'static str,
    subject: &'static str,
    duplicate_input: &'static str,
    requires_json: &'static str,
    requires_input: &'static str,
}

struct JsonEvalPlan {
    input: JsonEvalInput,
}

enum JsonEvalInput {
    Stdin,
    Path(PathBuf),
}

impl JsonEvalInput {
    fn into_kernel_source(self) -> KernelInputSource {
        match self {
            Self::Stdin => KernelInputSource::Stdin,
            Self::Path(path) => KernelInputSource::Path(path),
        }
    }

    fn into_payment_source(self) -> PaymentInputSource {
        match self {
            Self::Stdin => PaymentInputSource::Stdin,
            Self::Path(path) => PaymentInputSource::Path(path),
        }
    }

    fn into_parser_source(self) -> ParserInputSource {
        match self {
            Self::Stdin => ParserInputSource::Stdin,
            Self::Path(path) => ParserInputSource::Path(path),
        }
    }
}

fn parse_json_eval_input(
    args: &[OsString],
    mut index: usize,
    command: JsonEvalCommand,
) -> Result<JsonEvalPlan, String> {
    let mut input = None;
    let mut json = false;
    while index < args.len() {
        let token = os_arg(args, index, command.command)?;
        if !token.starts_with("--") {
            return Err(format!("unexpected {} argument {token}", command.subject));
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            "--input" => {
                if input.is_some() {
                    return Err(command.duplicate_input.to_owned());
                }
                let (value, next_index) =
                    flag_value(args, index, flag, inline_value, command.command)?;
                input = Some(if value == "-" {
                    JsonEvalInput::Stdin
                } else {
                    JsonEvalInput::Path(PathBuf::from(value))
                });
                index = next_index;
            }
            _ => return Err(format!("unknown {} flag {flag}", command.subject)),
        }
    }
    if !json {
        return Err(command.requires_json.to_owned());
    }
    Ok(JsonEvalPlan {
        input: input.ok_or_else(|| command.requires_input.to_owned())?,
    })
}

fn parse_policy_plan(args: &[OsString]) -> Result<PolicyPlan, String> {
    let subcommand = os_arg(args, 1, "policy")?;
    let action = match subcommand {
        "inspect" => PolicyAction::Inspect,
        "lint" => PolicyAction::Lint,
        _ => return Err(format!("unknown policy subcommand {subcommand}")),
    };
    let mut json = false;
    let mut positionals = Vec::new();
    let mut index = 2;

    while index < args.len() {
        let token = os_arg(args, index, "policy")?;
        if !token.starts_with("--") {
            positionals.push(PathBuf::from(token));
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            _ => return Err(format!("unknown policy flag {flag}")),
        }
    }

    let [path] = positionals.as_slice() else {
        return Err("runx policy inspect|lint requires exactly one policy path".to_owned());
    };
    Ok(PolicyPlan {
        action,
        path: path.clone(),
        json,
    })
}

fn parse_tool_plan(args: &[OsString]) -> Result<ToolPlan, String> {
    let subcommand = os_arg(args, 1, "tool")?;
    let action = match subcommand {
        "build" => ToolAction::Build,
        "search" => ToolAction::Search,
        "inspect" => ToolAction::Inspect,
        _ => return Err(format!("unknown tool subcommand {subcommand}")),
    };
    let mut json = false;
    let mut all = false;
    let mut source = None;
    let mut positionals = Vec::new();
    let mut index = 2;

    while index < args.len() {
        let token = os_arg(args, index, "tool")?;
        if !token.starts_with("--") {
            positionals.push(token.to_owned());
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        match flag {
            "--json" => {
                if inline_value.is_some() {
                    return Err("--json does not take a value".to_owned());
                }
                json = true;
                index += 1;
            }
            "--all" => {
                if inline_value.is_some() {
                    return Err("--all does not take a value".to_owned());
                }
                all = true;
                index += 1;
            }
            "--source" => {
                let (value, next_index) = flag_value(args, index, flag, inline_value, "tool")?;
                source = Some(value);
                index = next_index;
            }
            _ => return Err(format!("unknown tool flag {flag}")),
        }
    }

    match action {
        ToolAction::Build => build_tool_plan(positionals, all, source, json),
        ToolAction::Search => search_tool_plan(positionals, all, source, json),
        ToolAction::Inspect => inspect_tool_plan(positionals, all, source, json),
    }
}

fn build_tool_plan(
    positionals: Vec<String>,
    all: bool,
    source: Option<String>,
    json: bool,
) -> Result<ToolPlan, String> {
    if source.is_some() {
        return Err("runx tool build does not accept --source".to_owned());
    }
    if all && !positionals.is_empty() {
        return Err("runx tool build accepts either --all or one tool directory".to_owned());
    }
    if !all && positionals.len() != 1 {
        return Err("runx tool build requires a tool directory or --all".to_owned());
    }

    Ok(ToolPlan {
        action: ToolAction::Build,
        path: positionals.first().map(PathBuf::from),
        ref_or_query: None,
        all,
        source: None,
        json,
    })
}

fn search_tool_plan(
    positionals: Vec<String>,
    all: bool,
    source: Option<String>,
    json: bool,
) -> Result<ToolPlan, String> {
    if all {
        return Err("runx tool search does not accept --all".to_owned());
    }
    let query = positionals.join(" ");
    if query.is_empty() {
        return Err("runx tool search requires a query".to_owned());
    }

    Ok(ToolPlan {
        action: ToolAction::Search,
        path: None,
        ref_or_query: Some(query),
        all: false,
        source,
        json,
    })
}

fn inspect_tool_plan(
    positionals: Vec<String>,
    all: bool,
    source: Option<String>,
    json: bool,
) -> Result<ToolPlan, String> {
    if all {
        return Err("runx tool inspect does not accept --all".to_owned());
    }
    let tool_ref = positionals.join(" ");
    if tool_ref.is_empty() {
        return Err("runx tool inspect requires a tool reference".to_owned());
    }

    Ok(ToolPlan {
        action: ToolAction::Inspect,
        path: None,
        ref_or_query: Some(tool_ref),
        all: false,
        source,
        json,
    })
}

fn parse_registry_plan(args: &[OsString]) -> Result<RegistryPlan, String> {
    let subcommand = os_arg(args, 1, "registry")?;
    let action = parse_registry_action(subcommand)?;
    let mut state = RegistryParseState::default();
    parse_registry_args(args, &mut state)?;
    let subject = registry_subject(&action, subcommand, &mut state.positionals)?;

    Ok(RegistryPlan {
        action,
        subject,
        registry: state.registry,
        registry_dir: state.registry_dir,
        version: state.version,
        expected_digest: state.expected_digest,
        destination: state.destination,
        owner: state.owner,
        profile: state.profile,
        trust_tier: state.trust_tier,
        limit: state.limit,
        upsert: state.upsert,
        json: state.json,
    })
}

#[derive(Default)]
struct RegistryParseState {
    json: bool,
    upsert: bool,
    registry: Option<String>,
    registry_dir: Option<PathBuf>,
    version: Option<String>,
    expected_digest: Option<String>,
    destination: Option<PathBuf>,
    owner: Option<String>,
    profile: Option<PathBuf>,
    trust_tier: Option<runx_runtime::registry::TrustTier>,
    limit: Option<usize>,
    positionals: Vec<String>,
}

fn parse_registry_action(subcommand: &str) -> Result<RegistryAction, String> {
    match subcommand {
        "search" => Ok(RegistryAction::Search),
        "read" => Ok(RegistryAction::Read),
        "resolve" => Ok(RegistryAction::Resolve),
        "install" => Ok(RegistryAction::Install),
        "publish" => Ok(RegistryAction::Publish),
        _ => Err(format!("unknown registry subcommand {subcommand}")),
    }
}

fn parse_registry_args(args: &[OsString], state: &mut RegistryParseState) -> Result<(), String> {
    let mut index = 2;
    while index < args.len() {
        let token = os_arg(args, index, "registry")?;
        if !token.starts_with("--") {
            state.positionals.push(token.to_owned());
            index += 1;
            continue;
        }

        let (flag, inline_value) = split_flag(token);
        index = parse_registry_flag(args, index, flag, inline_value, state)?;
    }
    Ok(())
}

fn parse_registry_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    state: &mut RegistryParseState,
) -> Result<usize, String> {
    match flag {
        "--json" => set_registry_bool_flag(flag, inline_value, &mut state.json, index),
        "--upsert" => set_registry_bool_flag(flag, inline_value, &mut state.upsert, index),
        "--registry" => {
            set_registry_string_flag(args, index, flag, inline_value, &mut state.registry)
        }
        "--registry-dir" => {
            set_registry_path_flag(args, index, flag, inline_value, &mut state.registry_dir)
        }
        "--version" => set_registry_version_flag(args, index, flag, inline_value, state),
        "--digest" => {
            set_registry_string_flag(args, index, flag, inline_value, &mut state.expected_digest)
        }
        "--to" => set_registry_path_flag(args, index, flag, inline_value, &mut state.destination),
        "--owner" => set_registry_string_flag(args, index, flag, inline_value, &mut state.owner),
        "--profile" => set_registry_path_flag(args, index, flag, inline_value, &mut state.profile),
        "--trust-tier" => set_registry_trust_tier_flag(args, index, flag, inline_value, state),
        "--limit" => set_registry_limit_flag(args, index, flag, inline_value, state),
        _ => Err(format!("unknown registry flag {flag}")),
    }
}

fn set_registry_trust_tier_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    state: &mut RegistryParseState,
) -> Result<usize, String> {
    if state.trust_tier.is_some() {
        return Err(format!("{flag} was provided more than once"));
    }
    let (value, next_index) = flag_value(args, index, flag, inline_value, "registry")?;
    state.trust_tier = Some(parse_registry_trust_tier(&value)?);
    Ok(next_index)
}

fn parse_registry_trust_tier(value: &str) -> Result<runx_runtime::registry::TrustTier, String> {
    match value {
        "first_party" | "first-party" => Ok(runx_runtime::registry::TrustTier::FirstParty),
        "verified" => Ok(runx_runtime::registry::TrustTier::Verified),
        "community" => Ok(runx_runtime::registry::TrustTier::Community),
        _ => Err(format!(
            "invalid registry trust tier {value}; expected first_party, verified, or community"
        )),
    }
}

fn set_registry_bool_flag(
    flag: &str,
    inline_value: Option<&str>,
    target: &mut bool,
    index: usize,
) -> Result<usize, String> {
    if inline_value.is_some() {
        return Err(format!("{flag} does not take a value"));
    }
    *target = true;
    Ok(index + 1)
}

fn set_registry_string_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    target: &mut Option<String>,
) -> Result<usize, String> {
    let (value, next_index) = flag_value(args, index, flag, inline_value, "registry")?;
    *target = Some(value);
    Ok(next_index)
}

fn set_registry_path_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    target: &mut Option<PathBuf>,
) -> Result<usize, String> {
    let (value, next_index) = flag_value(args, index, flag, inline_value, "registry")?;
    *target = Some(PathBuf::from(value));
    Ok(next_index)
}

fn set_registry_limit_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    state: &mut RegistryParseState,
) -> Result<usize, String> {
    let (value, next_index) = flag_value(args, index, flag, inline_value, "registry")?;
    let limit = value
        .parse::<usize>()
        .map_err(|_| "--limit must be a positive integer".to_owned())?;
    if limit == 0 {
        return Err("--limit must be greater than zero".to_owned());
    }
    state.limit = Some(limit);
    Ok(next_index)
}

fn set_registry_version_flag(
    args: &[OsString],
    index: usize,
    flag: &str,
    inline_value: Option<&str>,
    state: &mut RegistryParseState,
) -> Result<usize, String> {
    let (value, next_index) = flag_value(args, index, flag, inline_value, "registry")?;
    validate_registry_version(&value)?;
    state.version = Some(value);
    Ok(next_index)
}

fn registry_subject(
    action: &RegistryAction,
    subcommand: &str,
    positionals: &mut Vec<String>,
) -> Result<String, String> {
    match action {
        RegistryAction::Search => {
            if positionals.is_empty() {
                return Err("runx registry search requires a query".to_owned());
            }
            let subject = positionals.join(" ");
            validate_registry_ref_version(&subject)?;
            Ok(subject)
        }
        RegistryAction::Read | RegistryAction::Resolve | RegistryAction::Install => {
            if positionals.len() != 1 {
                return Err(format!(
                    "runx registry {subcommand} requires exactly one ref"
                ));
            }
            let subject = positionals.remove(0);
            validate_registry_ref_version(&subject)?;
            Ok(subject)
        }
        RegistryAction::Publish => {
            if positionals.len() != 1 {
                return Err(
                    "runx registry publish requires exactly one skill markdown path".to_owned(),
                );
            }
            Ok(positionals.remove(0))
        }
    }
}

fn validate_registry_ref_version(value: &str) -> Result<(), String> {
    if let Some(version) = parse_registry_ref(value).version {
        validate_registry_version(&version)?;
    }
    Ok(())
}

fn validate_registry_version(value: &str) -> Result<(), String> {
    if value.trim().is_empty() {
        return Err("registry version must not be empty".to_owned());
    }
    if value.len() > 128 {
        return Err("registry version must be 128 characters or fewer".to_owned());
    }
    if value.chars().any(|character| {
        !character.is_ascii_alphanumeric() && !matches!(character, '.' | '_' | '-' | '+')
    }) {
        return Err(
            "registry version may only contain ASCII letters, numbers, '.', '_', '-', or '+'"
                .to_owned(),
        );
    }
    if matches!(value, "." | "..") {
        return Err("registry version must not be '.' or '..'".to_owned());
    }
    Ok(())
}

fn truthy(value: &str) -> bool {
    matches!(value, "true" | "1" | "yes" | "official")
}