jan-cli 0.10.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
mod builtins;
mod config;
mod cron;
mod deps;
mod inputs;
mod inspect;
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
/// ```
///
/// `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. When either 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>,
}

impl EnvSpec {
    pub fn is_empty(&self) -> bool {
        self.public.is_empty() && self.private.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);
            }
        }
    }
}

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>,
        }

        #[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(),
            },
            EnvDe::Sections(s) => Self {
                public: s.public,
                private: s.private,
            },
        })
    }
}

#[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>,
    #[serde(default)]
    pub commands: BTreeMap<String, CommandNode>,
    pub exec: Option<ExecSpec>,
}

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)
}

#[derive(Debug, Deserialize, Clone)]
pub struct ExecSpec {
    /// Full argument vector; first element is the program.
    pub argv: Vec<String>,
    /// Append extra CLI arguments after those from `argv`.
    #[serde(default)]
    pub passthrough: bool,
}

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 {
            if e.argv.is_empty() {
                bail!("command '{path}': exec.argv must not be empty");
            }
        }
        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,
}

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");
        }
    };
    if exec.argv.is_empty() {
        bail!("exec.argv must not be empty");
    }

    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());
    for a in &exec.argv {
        argv.push(inputs::interpolate(a, &input_vals)?);
    }
    if exec.passthrough {
        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 path_dirs = deps::resolve_path_prefixes(spec, chain, ctx)?;
    let program = deps::resolve_program(&argv[0], &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 path_override = if !path_dirs.is_empty() {
        Some(deps::prepend_path_env(&path_dirs)?)
    } else {
        None
    };

    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"));
    }
}

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")
}