jan-cli 0.13.0

YAML-defined CLI trees with progressive help, optional exec aliases, merged extra specs, and SQLite audit logging keyed by git branch
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
mod builtins;
mod config;
mod cron;
mod deps;
mod inputs;
mod inspect;
mod packages;
pub mod remote;
mod runner;
mod spec_load;
mod yaml_closure;

pub use config::{load_user_config, UserConfig};
pub use runner::run_jan;
pub use spec_load::HostPlatform;

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{bail, Context, Result};
use rusqlite::Connection;
use serde::Deserialize;
use serde::de::{self, Deserializer, Visitor};
use std::fmt;

#[derive(Debug, Deserialize)]
pub struct RootSpec {
    pub metadata: Option<Metadata>,
    #[serde(default)]
    pub commands: BTreeMap<String, CommandNode>,
}

#[derive(Debug, Deserialize)]
pub struct Metadata {
    pub name: Option<String>,
    pub description: Option<String>,
}

/// Child-process environment declaration for a command node.
///
/// Two YAML shapes are accepted:
///
/// ```yaml
/// # Legacy / shorthand — all keys are public assignments
/// env:
///   FOO: bar
///
/// # Explicit sections
/// env:
///   public:
///     FOO: bar
///   private:
///     - GH_TOKEN
///   pass:
///     GH_TOKEN: github/pat
/// ```
///
/// `public` values are taken from the YAML. `private` names must already exist in
/// jan's own environment; their values are copied into the child and never stored
/// in the spec. `pass` maps an environment variable name to a `pass` store id;
/// jan runs `pass <id>` and sets only the first line of stdout as that variable
/// in the child. When any section is non-empty, the child runs with a cleared
/// environment containing only those variables plus a small essential allowlist
/// (PATH, HOME, …).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct EnvSpec {
    pub public: BTreeMap<String, String>,
    pub private: Vec<String>,
    /// Env var name → `pass` store id (e.g. `GH_TOKEN` → `github/pat`).
    pub pass: BTreeMap<String, String>,
}

impl EnvSpec {
    pub fn is_empty(&self) -> bool {
        self.public.is_empty() && self.private.is_empty() && self.pass.is_empty()
    }

    /// True when the child should not inherit the full parent environment.
    pub fn restricts_child_env(&self) -> bool {
        !self.is_empty()
    }

    pub fn merge_from(&mut self, other: EnvSpec) {
        for (k, v) in other.public {
            self.public.insert(k, v);
        }
        for name in other.private {
            if !self.private.iter().any(|p| p == &name) {
                self.private.push(name);
            }
        }
        for (k, v) in other.pass {
            self.pass.insert(k, v);
        }
    }

    /// Reject overlapping private/pass names and empty keys/ids.
    pub fn validate(&self, path: &str) -> Result<()> {
        for name in &self.private {
            if name.trim().is_empty() {
                bail!("command '{path}': env.private entry must not be empty");
            }
        }
        for (env_name, pass_id) in &self.pass {
            if env_name.trim().is_empty() {
                bail!("command '{path}': env.pass key must not be empty");
            }
            if pass_id.trim().is_empty() {
                bail!("command '{path}': env.pass id for `{env_name}` must not be empty");
            }
            if self.private.iter().any(|p| p == env_name) {
                bail!(
                    "command '{path}': env var `{env_name}` cannot be both `env.private` and `env.pass`"
                );
            }
        }
        Ok(())
    }
}

impl<'de> Deserialize<'de> for EnvSpec {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Structured {
            #[serde(default)]
            public: BTreeMap<String, String>,
            #[serde(default, deserialize_with = "deserialize_string_or_seq")]
            private: Vec<String>,
            #[serde(default)]
            pass: BTreeMap<String, String>,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum EnvDe {
            Flat(BTreeMap<String, String>),
            Sections(Structured),
        }

        Ok(match EnvDe::deserialize(deserializer)? {
            EnvDe::Flat(public) => Self {
                public,
                private: Vec::new(),
                pass: BTreeMap::new(),
            },
            EnvDe::Sections(s) => Self {
                public: s.public,
                private: s.private,
                pass: s.pass,
            },
        })
    }
}

/// Whether an include link pointed at YAML (subtree graft) or a script file (exec leaf).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludeLinkKind {
    Yaml,
    Script,
}

/// Retained include identity after load (not authored directly in YAML).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeLink {
    pub kind: IncludeLinkKind,
    /// Relative path under the jan use root (local includes).
    pub path: Option<String>,
    /// Remote URL when the include was fetched over HTTPS.
    pub url: Option<String>,
    /// Declared SHA256 when present (required for remote; optional for local).
    pub sha256: Option<String>,
}

#[derive(Debug, Deserialize, Default, Clone)]
pub struct CommandNode {
    /// If non-empty, this command and its subtree are only offered on these
    /// platforms (`linux`, `macos`, `windows`, …). `darwin` is accepted as an alias for `macos`.
    #[serde(default)]
    pub os: Vec<String>,
    #[serde(default)]
    pub about: String,
    /// Directory prepended to PATH when this script (or a descendant leaf) runs.
    pub path: Option<String>,
    /// Other script names whose `path` directories are prepended before this one runs.
    #[serde(default)]
    pub dependencies: Vec<String>,
    /// External binaries that must be on PATH (e.g. `fzf`, `jq`) before the leaf runs.
    #[serde(default)]
    pub requires: Vec<String>,
    /// Public assignments and/or private names required from the host environment.
    #[serde(default)]
    pub env: EnvSpec,
    /// Named CLI inputs (`--name value`) available as `${{ inputs.name }}` in env/argv.
    #[serde(default)]
    pub inputs: BTreeMap<String, crate::inputs::InputDef>,
    /// Optional crontab schedule(s). When set, `jan cron` runs this script's `run`
    /// leaf whenever the local time matches any expression.
    #[serde(default, deserialize_with = "deserialize_string_or_seq")]
    pub cron: Vec<String>,
    /// Package-manager dependencies (uv now; pnpm reserved).
    #[serde(default)]
    pub packages: PackagesSpec,
    #[serde(default)]
    pub commands: BTreeMap<String, CommandNode>,
    pub exec: Option<ExecSpec>,
    /// Include link this node was loaded from, if any (filled by the loader).
    #[serde(skip)]
    pub source: Option<IncludeLink>,
}

/// Package-manager deps for a command node (`packages:` in YAML).
///
/// Distinct from `dependencies:`, which names other jan scripts whose `path`
/// directories are prepended to PATH.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
pub struct PackagesSpec {
    #[serde(default)]
    pub uv: Option<UvPackages>,
    /// Reserved for a future pnpm backend. Presence is rejected at validate/run.
    #[serde(default)]
    pub pnpm: Option<serde_yaml::Value>,
}

impl PackagesSpec {
    pub fn is_empty(&self) -> bool {
        self.uv.is_none() && self.pnpm.is_none()
    }

    /// Deeper node wins per manager (no list merge).
    pub fn merge_from(&mut self, other: PackagesSpec) {
        if other.uv.is_some() {
            self.uv = other.uv;
        }
        if other.pnpm.is_some() {
            self.pnpm = other.pnpm;
        }
    }

    pub fn validate(&self, path: &str) -> Result<()> {
        if self.pnpm.is_some() {
            bail!("command '{path}': packages.pnpm is not implemented yet");
        }
        if let Some(uv) = &self.uv {
            uv.validate(path)?;
        }
        Ok(())
    }
}

/// uv dependency declaration: inline list, project dir, or requirements file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UvPackages {
    List(Vec<String>),
    Project(String),
    Requirements(String),
}

impl UvPackages {
    pub fn validate(&self, path: &str) -> Result<()> {
        match self {
            Self::List(pkgs) => {
                if pkgs.is_empty() {
                    bail!("command '{path}': packages.uv list must not be empty");
                }
                for p in pkgs {
                    if p.trim().is_empty() {
                        bail!("command '{path}': packages.uv entry must not be empty");
                    }
                }
            }
            Self::Project(p) | Self::Requirements(p) => {
                if p.trim().is_empty() {
                    bail!("command '{path}': packages.uv path must not be empty");
                }
            }
        }
        Ok(())
    }
}

impl<'de> Deserialize<'de> for UvPackages {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct MapForm {
            #[serde(default)]
            project: Option<String>,
            #[serde(default)]
            requirements: Option<String>,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Helper {
            List(Vec<String>),
            Map(MapForm),
        }

        match Helper::deserialize(deserializer)? {
            Helper::List(pkgs) => {
                let pkgs: Vec<String> = pkgs
                    .into_iter()
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                Ok(UvPackages::List(pkgs))
            }
            Helper::Map(m) => {
                let project = m
                    .project
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                let requirements = m
                    .requirements
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                match (project, requirements) {
                    (Some(p), None) => Ok(UvPackages::Project(p)),
                    (None, Some(r)) => Ok(UvPackages::Requirements(r)),
                    (None, None) => Err(de::Error::custom(
                        "packages.uv map must set exactly one of `project` or `requirements`",
                    )),
                    (Some(_), Some(_)) => Err(de::Error::custom(
                        "packages.uv map must set exactly one of `project` or `requirements`, not both",
                    )),
                }
            }
        }
    }
}

pub(crate) fn deserialize_string_or_seq<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    struct StringOrSeq;

    impl<'de> Visitor<'de> for StringOrSeq {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a string or a sequence of strings")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if value.trim().is_empty() {
                Ok(Vec::new())
            } else {
                Ok(vec![value.to_string()])
            }
        }

        fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            self.visit_str(&value)
        }

        fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
        where
            A: de::SeqAccess<'de>,
        {
            let mut out = Vec::new();
            while let Some(s) = seq.next_element::<String>()? {
                if !s.trim().is_empty() {
                    out.push(s);
                }
            }
            Ok(out)
        }

        fn visit_none<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }

        fn visit_unit<E>(self) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            Ok(Vec::new())
        }
    }

    deserializer.deserialize_any(StringOrSeq)
}

/// Local include under the preferred jan directory (YAML subtree or script file).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalInclude {
    pub path: String,
    /// Optional integrity pin; verified when present.
    pub sha256: Option<String>,
    /// Interpreter prefix for script includes only (e.g. `["bash"]`).
    pub argv: Vec<String>,
    /// Passthrough trailing CLI args for script includes only.
    pub passthrough: bool,
}

impl LocalInclude {
    pub fn from_path(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            sha256: None,
            argv: Vec::new(),
            passthrough: false,
        }
    }

    pub fn is_yaml(&self) -> bool {
        let lower = self.path.to_ascii_lowercase();
        lower.ends_with(".yaml") || lower.ends_with(".yml")
    }
}

/// Local path or remote HTTPS include target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IncludeRef {
    /// Relative path under the preferred jan directory (optional sha256 / script opts).
    Local(LocalInclude),
    /// Remote YAML fetched with SHA256 verification.
    Remote(RemoteInclude),
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct RemoteInclude {
    pub url: String,
    pub sha256: String,
    #[serde(default)]
    pub ttl: Option<u64>,
}

impl IncludeRef {
    pub fn is_remote(&self) -> bool {
        matches!(self, Self::Remote(_))
    }

    pub fn local_path(&self) -> Option<&str> {
        match self {
            Self::Local(l) => Some(l.path.as_str()),
            Self::Remote(_) => None,
        }
    }

    pub fn cycle_token(&self) -> String {
        match self {
            Self::Local(l) => match &l.sha256 {
                Some(h) => format!("{}#{}", l.path, h.to_ascii_lowercase()),
                None => l.path.clone(),
            },
            Self::Remote(r) => format!("{}#{}", r.url, r.sha256.to_ascii_lowercase()),
        }
    }
}

impl<'de> Deserialize<'de> for IncludeRef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct LocalMap {
            path: String,
            #[serde(default)]
            sha256: Option<String>,
            #[serde(default)]
            argv: Vec<String>,
            #[serde(default)]
            passthrough: bool,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Helper {
            Path(String),
            Local(LocalMap),
            Remote(RemoteInclude),
        }

        match Helper::deserialize(deserializer)? {
            Helper::Path(path) => {
                let path = path.trim();
                if path.is_empty() {
                    return Err(de::Error::custom("include path must not be empty"));
                }
                Ok(IncludeRef::Local(LocalInclude::from_path(path)))
            }
            Helper::Local(m) => {
                let path = m.path.trim();
                if path.is_empty() {
                    return Err(de::Error::custom("include.path must not be empty"));
                }
                let sha256 = m
                    .sha256
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty());
                Ok(IncludeRef::Local(LocalInclude {
                    path: path.to_string(),
                    sha256,
                    argv: m.argv,
                    passthrough: m.passthrough,
                }))
            }
            Helper::Remote(r) => {
                if r.url.trim().is_empty() {
                    return Err(de::Error::custom("include.url must not be empty"));
                }
                if r.sha256.trim().is_empty() {
                    return Err(de::Error::custom(
                        "include.sha256 is required with include.url",
                    ));
                }
                Ok(IncludeRef::Remote(r))
            }
        }
    }
}

#[derive(Debug, Deserialize, Clone, Default)]
pub struct ExecSpec {
    /// Program argv. For remote `url` / local `file` leaves this is an optional
    /// interpreter prefix (e.g. `["python3"]`); the script path is appended automatically.
    #[serde(default)]
    pub argv: Vec<String>,
    /// Append extra CLI arguments after those from `argv` / the script path.
    #[serde(default)]
    pub passthrough: bool,
    /// HTTPS URL of a remote script to download, verify, and run.
    #[serde(default)]
    pub url: Option<String>,
    /// Local script path relative to the jan use root (optional `sha256` pin).
    #[serde(default)]
    pub file: Option<String>,
    /// SHA256 of the script: required with `url`, optional with `file`.
    #[serde(default)]
    pub sha256: Option<String>,
    /// Optional TTL override (seconds) for the remote script cache.
    #[serde(default)]
    pub ttl: Option<u64>,
}

impl ExecSpec {
    pub fn is_remote(&self) -> bool {
        self.url
            .as_deref()
            .map(|u| !u.trim().is_empty())
            .unwrap_or(false)
    }

    pub fn is_local_file(&self) -> bool {
        self.file
            .as_deref()
            .map(|u| !u.trim().is_empty())
            .unwrap_or(false)
    }

    pub fn validate(&self, path: &str) -> Result<()> {
        let url = self
            .url
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty());
        let file = self
            .file
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty());
        let hash = self
            .sha256
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty());
        if url.is_some() && file.is_some() {
            bail!("command '{path}': exec cannot set both `url` and `file`");
        }
        match (url, file, hash) {
            (Some(_), None, Some(_)) => Ok(()),
            (Some(_), None, None) => {
                bail!("command '{path}': exec.sha256 is required with exec.url")
            }
            (None, Some(_), _) => Ok(()),
            (None, None, Some(_)) => {
                bail!("command '{path}': exec.sha256 requires exec.url or exec.file")
            }
            (None, None, None) => {
                if self.argv.is_empty() {
                    bail!(
                        "command '{path}': exec.argv must not be empty (or set exec.url / exec.file)"
                    );
                }
                Ok(())
            }
            (Some(_), Some(_), _) => unreachable!("checked above"),
        }
    }
}

impl CommandNode {
    pub fn is_leaf_exec(&self) -> bool {
        self.exec.is_some()
    }

    pub fn validate(&self, path: &str) -> Result<()> {
        if self.exec.is_some() && !self.commands.is_empty() {
            bail!("command '{path}' cannot define both `exec` and nested `commands`");
        }
        if let Some(ref e) = self.exec {
            e.validate(path)?;
        }
        self.env.validate(path)?;
        self.packages.validate(path)?;
        for name in self.inputs.keys() {
            inputs::InputDef::validate_name(name)
                .map_err(|e| anyhow::anyhow!("command '{path}': {e}"))?;
        }
        for (name, child) in &self.commands {
            let p = if path.is_empty() {
                name.clone()
            } else {
                format!("{path} {name}")
            };
            child.validate(&p)?;
        }
        Ok(())
    }
}

/// Deep-merge `overlay.commands` into `base`, letting included YAML fragments
/// add or replace leaves and extend nested groups.
pub fn merge_specs_into(base: &mut RootSpec, overlay: RootSpec) -> Result<()> {
    for (name, node) in overlay.commands {
        match base.commands.get_mut(&name) {
            Some(existing) => merge_command_node(existing, node)?,
            None => {
                base.commands.insert(name, node);
            }
        }
    }
    Ok(())
}

fn merge_command_node(dst: &mut CommandNode, src: CommandNode) -> Result<()> {
    if src.exec.is_some() && !src.commands.is_empty() {
        bail!("merge overlay: command cannot define both `exec` and nested `commands`");
    }
    if !src.os.is_empty() {
        dst.os = src.os;
    }
    if !src.about.trim().is_empty() {
        dst.about = src.about;
    }
    if src.path.is_some() {
        dst.path = src.path;
    }
    if !src.dependencies.is_empty() {
        dst.dependencies = src.dependencies;
    }
    if !src.requires.is_empty() {
        dst.requires = src.requires;
    }
    if !src.cron.is_empty() {
        dst.cron = src.cron;
    }
    if !src.env.is_empty() {
        dst.env.merge_from(src.env);
    }
    for (k, v) in src.inputs {
        dst.inputs.insert(k, v);
    }
    if let Some(exec) = src.exec {
        dst.exec = Some(exec);
        dst.commands.clear();
        return Ok(());
    }
    if !src.commands.is_empty() {
        dst.exec = None;
        for (k, child) in src.commands {
            match dst.commands.get_mut(&k) {
                Some(existing) => merge_command_node(existing, child)?,
                None => {
                    dst.commands.insert(k, child);
                }
            }
        }
    }
    Ok(())
}

/// Validate every command in the tree (after merges or programmatic edits).
pub fn validate_spec(spec: &RootSpec) -> Result<()> {
    for (name, node) in &spec.commands {
        node.validate(name)?;
    }
    Ok(())
}

/// Parse YAML from memory. Use `include_base` when the document uses `include:` (root or subtree).
pub fn load_spec_from_str(raw: &str, include_base: Option<&Path>) -> Result<RootSpec> {
    spec_load::load_spec_from_str(raw, include_base, HostPlatform::detect())
}

pub fn load_spec(path: &Path) -> Result<RootSpec> {
    spec_load::load_spec_from_path(path, HostPlatform::detect())
}

pub fn resolve_git_branch(cwd: &Path, override_branch: Option<&str>) -> String {
    if let Some(b) = override_branch {
        if !b.is_empty() {
            return b.to_string();
        }
    }
    if let Ok(v) = std::env::var("JAN_BRANCH") {
        if !v.is_empty() {
            return v;
        }
    }
    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(cwd)
        .output();
    match output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => "(no-git)".to_string(),
    }
}

fn first_line(s: &str) -> String {
    s.lines().next().unwrap_or("").trim().to_string()
}

pub fn format_help(spec: &RootSpec, chain: &[String], node: Option<&CommandNode>) -> String {
    let mut out = String::new();
    let bin = spec
        .metadata
        .as_ref()
        .and_then(|m| m.name.as_deref())
        .unwrap_or("jan");
    let full_cmd = if chain.is_empty() {
        bin.to_string()
    } else {
        format!("{} {}", bin, chain.join(" "))
    };

    let (about, children, exec) = match node {
        Some(n) => (n.about.as_str(), &n.commands, n.exec.as_ref()),
        None => ("", &spec.commands, None),
    };

    if chain.is_empty() {
        if let Some(meta) = &spec.metadata {
            if let Some(desc) = &meta.description {
                out.push_str(desc.trim());
                out.push_str("\n\n");
            }
        }
    }

    if !about.is_empty() {
        out.push_str(about.trim());
        out.push_str("\n\n");
    }

    if exec.is_some() && children.is_empty() {
        out.push_str("This command runs an external program (see spec `exec.argv`).\n");
        let defs = inputs::collect_chain_inputs(chain, spec);
        if !defs.is_empty() {
            out.push('\n');
            out.push_str(&inputs::format_inputs_help(&defs));
        }
        return out;
    }

    if !children.is_empty() {
        out.push_str("Subcommands:\n");
        for (name, child) in children {
            let line = if child.about.is_empty() {
                format!("  {name}\n")
            } else {
                format!("  {name} — {}\n", first_line(&child.about))
            };
            out.push_str(&line);
        }
        out.push('\n');
        out.push_str(&format!(
            "Use `{} --help` for more about a subcommand.\n",
            full_cmd
        ));
        let defs = inputs::collect_chain_inputs(chain, spec);
        if !defs.is_empty() {
            out.push('\n');
            out.push_str(&inputs::format_inputs_help(&defs));
        }
    } else if exec.is_none() {
        out.push_str("(No subcommands defined.)\n");
    }
    if chain.is_empty() && node.is_none() {
        out.push_str(
            "\nPlace `--help` or `-h` right after the subcommand prefix you want. Built-ins: `use`, `bundle`, `alias`, `list`, `search`, `show`, `validate`, `audit`, `cron`.\n",
        );
    }
    out
}

/// Stable identity for where a YAML spec tree is rooted (directory of linked fragments + entry file).
#[derive(Debug, Clone)]
pub struct SpecRootIdentity {
    /// Canonical directory containing top-level YAML fragments.
    pub spec_dir: String,
    /// Entry YAML file name relative to `spec_dir`.
    pub root_yaml: String,
}

/// Resolve the preferred jan directory saved by `jan use`.
pub fn resolve_preferred_spec() -> Result<(PathBuf, SpecRootIdentity)> {
    let cfg = config::load_user_config().context("load user config")?;
    let Some(dir_s) = cfg
        .jan_dir
        .as_ref()
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
    else {
        bail!(
            "no preferred jan directory configured\n\
             Run `jan use <DIR>` to save a YAML command tree (see docs/PORTABLE_SCRIPTS.md)"
        );
    };
    let dir = PathBuf::from(dir_s);
    if !dir.is_dir() {
        bail!(
            "preferred jan directory does not exist: {}\n\
             Fix the path or run `jan use <DIR>` again (config: {})",
            dir.display(),
            config::config_path().display()
        );
    }
    let root = cfg
        .spec_root
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .unwrap_or("scripts.spec.yaml");
    resolve_spec_dir_entry(&dir, root)
}

/// Resolve a jan directory + entry file name into an absolute spec path and identity.
pub fn resolve_spec_dir_entry(
    spec_dir: &Path,
    root_yaml: &str,
) -> Result<(PathBuf, SpecRootIdentity)> {
    let rel = Path::new(root_yaml);
    if rel.is_absolute() {
        bail!("entry YAML must be a relative file name, not an absolute path");
    }
    if rel
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        bail!("entry YAML must not contain `..`");
    }
    let normal_only = rel
        .components()
        .all(|c| matches!(c, std::path::Component::Normal(_)));
    let n = rel
        .components()
        .filter(|c| matches!(c, std::path::Component::Normal(_)))
        .count();
    if !normal_only || n != 1 {
        bail!("entry YAML must be a single file name inside the jan directory");
    }
    let dir = spec_dir
        .canonicalize()
        .with_context(|| format!("canonicalize jan directory {}", spec_dir.display()))?;
    if !dir.is_dir() {
        bail!("not a directory: {}", dir.display());
    }
    let spec_path = dir.join(rel);
    if !spec_path.is_file() {
        bail!(
            "spec entry not found: {} (under {})\n\
             Expected a properly formatted jan directory (e.g. scripts.spec.yaml)",
            spec_path.display(),
            dir.display()
        );
    }
    let identity = SpecRootIdentity {
        spec_dir: dir.to_string_lossy().into_owned(),
        root_yaml: rel
            .file_name()
            .expect("relative root has file_name")
            .to_string_lossy()
            .into_owned(),
    };
    Ok((spec_path, identity))
}

pub struct RunContext<'a> {
    pub cwd: &'a Path,
    pub db_path: Option<&'a Path>,
    pub branch: String,
    pub no_log: bool,
    pub spec_root: &'a SpecRootIdentity,
}

/// True when `argv` is a POSIX-shell inline (`bash`/`zsh`/`sh`/… + `-c`/`-lc` + body)
/// with no `$0` placeholder after the body yet.
///
/// For those interpreters the first word after the `-c` string becomes `$0`, not `$1`.
/// Inlined jan scripts expect normal script semantics (`$1` / `"$@"` = user args), so
/// passthrough must insert a `$0` before forwarding.
fn shell_inline_c_needs_argv0(argv: &[String]) -> bool {
    if argv.len() != 3 {
        return false;
    }
    let prog = Path::new(&argv[0])
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(argv[0].as_str());
    let is_shell = matches!(
        prog,
        "bash" | "zsh" | "sh" | "dash" | "ksh" | "ash" | "busybox"
    );
    is_shell && matches!(argv[1].as_str(), "-c" | "-lc")
}

fn shell_passthrough_argv0(chain: &[String]) -> String {
    chain
        .iter()
        .rev()
        .find(|s| s.as_str() != "run")
        .cloned()
        .or_else(|| chain.last().cloned())
        .unwrap_or_else(|| "jan".to_string())
}

pub fn run_matched(
    spec: &RootSpec,
    chain: &[String],
    node: &CommandNode,
    trailing: &[OsString],
    ctx: &RunContext<'_>,
) -> Result<i32> {
    let exec = match &node.exec {
        Some(e) => e,
        None => {
            let help = format_help(spec, chain, Some(node));
            print!("{help}");
            bail!("missing subcommand");
        }
    };
    exec.validate(&chain.join(" "))?;

    let input_defs = inputs::collect_chain_inputs(chain, spec);
    let (input_vals, rest) = inputs::resolve_inputs(&input_defs, trailing)?;

    let mut argv: Vec<String> = Vec::with_capacity(exec.argv.len() + 1);
    for a in &exec.argv {
        argv.push(inputs::interpolate(a, &input_vals)?);
    }

    if exec.is_remote() {
        let url = exec.url.as_deref().unwrap().trim();
        let hash = exec.sha256.as_deref().unwrap().trim();
        let mut opts = remote::FetchOpts::new();
        if let Some(ttl) = exec.ttl {
            opts = opts.with_ttl(ttl);
        }
        let cached = remote::fetch_verified(url, hash, &opts, true)?;
        argv.push(cached.to_string_lossy().into_owned());
    } else if exec.is_local_file() {
        let rel = exec.file.as_deref().unwrap().trim();
        let use_root = Path::new(&ctx.spec_root.spec_dir);
        let resolved = spec_load::resolve_under_use_root(use_root, rel)?;
        if let Some(hash) = exec.sha256.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
            remote::verify_file_sha256(&resolved, hash)
                .with_context(|| format!("verify exec.file `{rel}`"))?;
        }
        argv.push(resolved.to_string_lossy().into_owned());
    } else if argv.is_empty() {
        bail!("exec.argv must not be empty");
    }

    if exec.passthrough {
        let mut rest = rest;
        // `--` after the leaf is the usual jan separator; drop one leading `--` so
        // `run -- arg` and `run arg` match for both inline shells and `exec.file` /
        // script includes. A literal first arg of `--` needs `run -- --`.
        if rest.first().is_some_and(|a| a == "--") {
            rest = rest[1..].to_vec();
        }
        if shell_inline_c_needs_argv0(&argv) {
            argv.push(shell_passthrough_argv0(chain));
        }
        for a in &rest {
            argv.push(a.to_string_lossy().into_owned());
        }
    } else if !rest.is_empty() {
        let preview = rest
            .iter()
            .take(3)
            .map(|s| s.to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join(" ");
        bail!(
            "unexpected trailing arguments: {preview}{}",
            if rest.len() > 3 { "…" } else { "" }
        );
    }

    let cmd_path = if chain.is_empty() {
        "(root)".to_string()
    } else {
        chain.join(" ")
    };

    let (_, requires, _) = deps::collect_chain_metadata(chain, spec);
    deps::check_requires(&requires)?;

    let pkgs = packages::collect_chain_packages(chain, spec);
    let uv_env = packages::ensure_packages(&pkgs, ctx)?;

    let path_dirs = deps::resolve_path_prefixes(spec, chain, ctx)?;
    let program = packages::resolve_program_with_uv(&argv[0], uv_env.as_ref(), &path_dirs)?;
    let mut env_spec = deps::collect_chain_env(chain, spec);
    for value in env_spec.public.values_mut() {
        *value = inputs::interpolate(value, &input_vals)?;
    }
    deps::check_private_env(&env_spec.private)?;
    let mut path_override = if !path_dirs.is_empty() {
        Some(deps::prepend_path_env(&path_dirs)?)
    } else {
        None
    };
    if let Some(ref uv) = uv_env {
        path_override = Some(packages::prepend_uv_path(uv, path_override)?);
    }

    let mut c = Command::new(&program);
    if argv.len() > 1 {
        c.args(&argv[1..]);
    }
    c.current_dir(ctx.cwd);
    deps::apply_process_env(&mut c, &env_spec, path_override)?;

    let status = c.status().with_context(|| format!("spawn `{}`", argv[0]))?;
    let code = status.code().unwrap_or(255);

    if !ctx.no_log {
        if let Some(db) = ctx.db_path {
            log_invocation(
                db,
                &ctx.branch,
                ctx.cwd,
                &cmd_path,
                &argv,
                code,
                ctx.spec_root,
            )?;
        }
    }

    Ok(code)
}

fn ensure_invocations_spec_root_column(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("PRAGMA table_info(invocations)")?;
    let cols: Vec<String> = stmt
        .query_map([], |row| row.get::<_, String>(1))?
        .collect::<std::result::Result<_, _>>()?;
    if !cols.iter().any(|c| c == "spec_root_id") {
        conn.execute(
            "ALTER TABLE invocations ADD COLUMN spec_root_id INTEGER",
            [],
        )?;
    }
    Ok(())
}

fn upsert_spec_root(conn: &Connection, spec: &SpecRootIdentity) -> Result<i64> {
    let ts = unix_ts();
    conn.execute(
        r"INSERT INTO spec_roots (spec_dir, root_yaml, last_used_ts) VALUES (?1, ?2, ?3)
          ON CONFLICT(spec_dir, root_yaml) DO UPDATE SET last_used_ts = excluded.last_used_ts",
        rusqlite::params![&spec.spec_dir, &spec.root_yaml, &ts],
    )?;
    let id: i64 = conn.query_row(
        "SELECT id FROM spec_roots WHERE spec_dir = ?1 AND root_yaml = ?2",
        [&spec.spec_dir, &spec.root_yaml],
        |r| r.get(0),
    )?;
    Ok(id)
}

fn log_invocation(
    db_path: &Path,
    branch: &str,
    cwd: &Path,
    command_path: &str,
    argv: &[String],
    exit_code: i32,
    spec_root: &SpecRootIdentity,
) -> Result<()> {
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let conn = Connection::open(db_path).with_context(|| format!("open {}", db_path.display()))?;
    conn.execute_batch(
        r"
        CREATE TABLE IF NOT EXISTS spec_roots (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            spec_dir TEXT NOT NULL,
            root_yaml TEXT NOT NULL,
            last_used_ts TEXT NOT NULL,
            UNIQUE(spec_dir, root_yaml)
        );
        CREATE TABLE IF NOT EXISTS invocations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            ts TEXT NOT NULL,
            git_branch TEXT NOT NULL,
            cwd TEXT NOT NULL,
            command_path TEXT NOT NULL,
            argv_json TEXT NOT NULL,
            exit_code INTEGER NOT NULL,
            spec_root_id INTEGER
        );
        ",
    )?;
    ensure_invocations_spec_root_column(&conn)?;
    let spec_root_id = upsert_spec_root(&conn, spec_root)?;
    let ts = unix_ts();
    let argv_json = serde_json::to_string(argv).unwrap_or_else(|_| "[]".to_string());
    let cwd_s = cwd.to_string_lossy();
    conn.execute(
        "INSERT INTO invocations (ts, git_branch, cwd, command_path, argv_json, exit_code, spec_root_id)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        rusqlite::params![
            ts,
            branch,
            cwd_s.as_ref(),
            command_path,
            argv_json,
            exit_code,
            spec_root_id
        ],
    )?;
    Ok(())
}

fn unix_ts() -> String {
    use std::time::SystemTime;
    SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
        .to_string()
}

#[derive(Debug)]
pub struct MatchOutcome<'a> {
    pub chain: Vec<String>,
    pub node: Option<&'a CommandNode>,
    pub trailing: Vec<OsString>,
    pub wants_help: bool,
}

pub fn match_commands<'a>(spec: &'a RootSpec, args: &[OsString]) -> MatchOutcome<'a> {
    let mut chain = Vec::new();
    let mut node: Option<&'a CommandNode> = None;
    let mut map: &BTreeMap<String, CommandNode> = &spec.commands;
    let mut i = 0usize;
    let len = args.len();
    while i < len {
        let raw = &args[i];
        if raw == "--help" || raw == "-h" {
            return MatchOutcome {
                chain,
                node,
                trailing: args[i + 1..].to_vec(),
                wants_help: true,
            };
        }
        let key = raw.to_string_lossy();
        if let Some(next) = map.get(key.as_ref()) {
            chain.push(key.into_owned());
            node = Some(next);
            map = &next.commands;
            i += 1;
            continue;
        }
        break;
    }
    MatchOutcome {
        chain,
        node,
        trailing: args[i..].to_vec(),
        wants_help: false,
    }
}

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

    #[test]
    fn examples_default_spec_validates() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/default.spec.yaml");
        load_spec(&path).unwrap();
    }

    #[test]
    fn merge_specs_adds_and_replaces_leaves() {
        let mut base = load_spec_from_str(
            r"
commands:
  a:
    about: base
    commands:
      x:
        about: old
        exec:
          argv: [echo, old]
",
            None,
        )
        .unwrap();
        let overlay = load_spec_from_str(
            r"
commands:
  a:
    commands:
      x:
        about: new leaf
        exec:
          argv: [echo, new]
  b:
    about: added top
    exec:
      argv: [echo, b]
",
            None,
        )
        .unwrap();
        merge_specs_into(&mut base, overlay).unwrap();
        base.commands["a"].commands["x"].validate("a x").unwrap();
        assert_eq!(
            base.commands["a"].commands["x"].exec.as_ref().unwrap().argv,
            vec!["echo", "new"]
        );
        assert_eq!(
            base.commands["b"].exec.as_ref().unwrap().argv,
            vec!["echo", "b"]
        );
    }

    #[test]
    fn validate_rejects_exec_with_children() {
        let mut tmp = tempfile::NamedTempFile::with_suffix(".yaml").unwrap();
        write!(
            tmp,
            r"
commands:
  x:
    exec:
      argv: [echo]
    commands:
      child:
        about: nested
"
        )
        .unwrap();
        let err = load_spec(tmp.path()).unwrap_err();
        assert!(err.to_string().contains("cannot define both"));
    }

    #[test]
    fn shell_inline_c_needs_argv0_detects_bash_lc() {
        let argv = vec![
            "bash".into(),
            "-lc".into(),
            "case \"$1\" in create) ;; esac".into(),
        ];
        assert!(shell_inline_c_needs_argv0(&argv));
        let with_placeholder = vec![
            "zsh".into(),
            "-c".into(),
            "echo".into(),
            "issue".into(),
        ];
        assert!(!shell_inline_c_needs_argv0(&with_placeholder));
        assert!(!shell_inline_c_needs_argv0(&[
            "echo".into(),
            "start".into()
        ]));
        assert!(!shell_inline_c_needs_argv0(&[
            "python3".into(),
            "-c".into(),
            "print(1)".into()
        ]));
    }

    #[test]
    fn shell_passthrough_argv0_skips_run_leaf() {
        assert_eq!(
            shell_passthrough_argv0(&["scripts".into(), "misc".into(), "issue".into(), "run".into()]),
            "issue"
        );
        assert_eq!(shell_passthrough_argv0(&["probe".into()]), "probe");
    }
}

pub fn default_db_path() -> PathBuf {
    if let Ok(p) = std::env::var("JAN_DB") {
        return PathBuf::from(p);
    }
    dirs::data_local_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("jan-cli")
        .join("audit.db")
}