nomograph-kit 0.14.1

Verified tool registry manager -- manages developer toolchains from git-based registries
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::sync::LazyLock;

use crate::platform::Platform;

// -- Validation patterns (security-critical: S-3, S-10) --
// F17: compile regexes once via LazyLock, not on every validate() call.

/// Tool names: lowercase alphanumeric + hyphens, must start with alphanumeric.
pub const NAME_PATTERN: &str = r"^[a-z0-9][a-z0-9-]*$";

/// Bin names: alphanumeric + underscores + hyphens.
const BIN_PATTERN: &str = r"^[a-zA-Z0-9_-]+$";

/// Version strings: digits, dots, hyphens, plus, alpha.
pub const VERSION_PATTERN: &str = r"^[0-9][0-9a-zA-Z._+\-]*$";

/// Repo paths: owner/repo with safe characters.
const REPO_PATTERN: &str = r"^[a-zA-Z0-9_.\-]+/[a-zA-Z0-9_.\-]+$";

/// Tag prefixes: alphanumeric, dots, hyphens. Empty string allowed.
const TAG_PREFIX_PATTERN: &str = r"^[a-zA-Z0-9._-]*$";

/// Asset names: safe filename characters only. No path separators.
const ASSET_PATTERN: &str = r"^[a-zA-Z0-9_.{}\-]+$";

/// Branch names: alphanumeric, hyphens, slashes, dots (F9).
const BRANCH_PATTERN: &str = r"^[a-zA-Z0-9._/\-]+$";

// F17: compiled regex statics -- avoids recompilation in hot loops
static NAME_RE: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(NAME_PATTERN).unwrap());
static BIN_RE: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(BIN_PATTERN).unwrap());
static VERSION_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(VERSION_PATTERN).unwrap());
static REPO_RE: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(REPO_PATTERN).unwrap());
static ASSET_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(ASSET_PATTERN).unwrap());
static TAG_PREFIX_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(TAG_PREFIX_PATTERN).unwrap());
static BRANCH_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| regex::Regex::new(BRANCH_PATTERN).unwrap());

/// Trust tiers control review policy for updates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
    Own,
    High,
    Low,
}

impl std::fmt::Display for Tier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Own => f.write_str("own"),
            Self::High => f.write_str("high"),
            Self::Low => f.write_str("low"),
        }
    }
}

/// Source type for a tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    Github,
    Gitlab,
    Npm,
    Crates,
    Direct,
    Rustup,
    Brew,        // macOS Homebrew formula via mise's brew backend
}

/// Checksum verification format.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ChecksumFormat {
    Sha256,
    Sha256PerAsset,
    /// yq (mikefarah/yq) multi-hash format:
    /// `checksums` has rows of `<filename>  <crc32>  <md4>  ... <sha256> ... <sha512> ...`
    /// (filename first, then hashes in the order listed by `checksums_hashes_order`).
    YqMultiHash,
}

/// Signature verification method.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SignatureMethod {
    CosignKeyless,
    GithubAttestation,
    None,
}

/// Checksum configuration for a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChecksumConfig {
    /// Upstream checksum filename (may contain {version} template).
    pub file: Option<String>,
    /// Format of the checksum file.
    #[serde(default = "default_checksum_format")]
    pub format: ChecksumFormat,
}

fn default_checksum_format() -> ChecksumFormat {
    ChecksumFormat::Sha256
}

/// Signature configuration for a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignatureConfig {
    pub method: SignatureMethod,
    /// OIDC issuer for cosign-keyless verification.
    pub issuer: Option<String>,
    /// Certificate identity pattern for cosign verification.
    pub identity: Option<String>,
}

/// A complete tool definition, parsed from tools/<name>.toml.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDef {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    pub source: Source,
    pub version: String,
    #[serde(default = "default_tag_prefix")]
    pub tag_prefix: String,
    #[serde(default)]
    pub bin: Option<String>,
    pub tier: Tier,

    // Source-specific fields
    #[serde(default)]
    pub repo: Option<String>,
    #[serde(default)]
    pub project_id: Option<u64>,
    #[serde(default)]
    pub package: Option<String>,
    #[serde(rename = "crate", default)]
    pub crate_name: Option<String>,
    #[serde(default)]
    pub formula: Option<String>,    // for Source::Brew -- the brew formula name

    /// Mise aqua registry name (e.g., "cli/cli" for gh).
    /// If set, kit generates `tool = "version"` instead of `http:tool`.
    #[serde(default)]
    pub aqua: Option<String>,

    /// Per-platform asset filename templates.
    #[serde(default)]
    pub assets: HashMap<String, String>,

    /// Checksum verification config.
    #[serde(default)]
    pub checksum: Option<ChecksumConfig>,

    /// Inline pre-computed checksums (for tools without upstream checksum files).
    #[serde(default)]
    pub checksums: HashMap<String, String>,

    /// Signature verification config.
    #[serde(default)]
    pub signature: Option<SignatureConfig>,
}

fn default_tag_prefix() -> String {
    "v".to_string()
}

/// Wrapper for the TOML file structure: [tool] table at top level.
#[derive(Debug, Serialize, Deserialize)]
pub struct ToolFile {
    pub tool: ToolDef,
}

/// Validate a tool name against NAME_PATTERN. Public for use by commands.
pub fn validate_name(name: &str) -> Result<()> {
    if !NAME_RE.is_match(name) {
        anyhow::bail!("invalid tool name '{name}': must match {NAME_PATTERN}");
    }
    Ok(())
}

/// Validate a version string. Public for use by commands (e.g. pin).
pub fn validate_version(version: &str) -> Result<()> {
    if !VERSION_RE.is_match(version) {
        anyhow::bail!("invalid version '{version}': must match {VERSION_PATTERN}");
    }
    Ok(())
}

/// Validate a branch name (F9). Public for config validation.
pub fn validate_branch(branch: &str) -> Result<()> {
    if !BRANCH_RE.is_match(branch) {
        anyhow::bail!("invalid branch name '{branch}': must match {BRANCH_PATTERN}");
    }
    Ok(())
}

/// F10: Validate a checksum filename after template expansion.
#[allow(dead_code)]
pub fn validate_checksum_filename(filename: &str) -> Result<()> {
    if !ASSET_RE.is_match(filename) {
        anyhow::bail!("invalid checksum filename '{filename}': must match {ASSET_PATTERN}");
    }
    Ok(())
}

impl ToolDef {
    /// Parse and validate a tool definition from a TOML file.
    pub fn load(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        let file: ToolFile = toml::from_str(&content)
            .with_context(|| format!("failed to parse {}", path.display()))?;
        let def = file.tool;
        def.validate()
            .with_context(|| format!("invalid tool definition: {}", path.display()))?;
        Ok(def)
    }

    /// The effective binary name.
    pub fn bin_name(&self) -> &str {
        self.bin.as_deref().unwrap_or(&self.name)
    }

    /// The git tag for the current version.
    pub fn tag(&self) -> String {
        format!("{}{}", self.tag_prefix, self.version)
    }

    /// Resolve the asset filename for a platform, expanding {version} templates.
    pub fn asset_for(&self, platform: Platform) -> Option<String> {
        let pattern = self.assets.get(platform.key())?;
        Some(pattern.replace("{version}", &self.version))
    }

    /// Resolve the download URL for a platform.
    pub fn url_for(&self, platform: Platform) -> Option<String> {
        let asset = self.asset_for(platform)?;
        let tag = self.tag();

        match self.source {
            Source::Github => {
                let repo = self.repo.as_ref()?;
                Some(format!(
                    "https://github.com/{repo}/releases/download/{tag}/{asset}"
                ))
            }
            Source::Gitlab => {
                if let Some(pid) = self.project_id {
                    // Own tools: generic package registry
                    Some(format!(
                        "https://gitlab.com/api/v4/projects/{pid}/packages/generic/{name}/{tag}/{asset}",
                        name = self.name
                    ))
                } else {
                    let repo = self.repo.as_ref()?;
                    // Third-party: release download
                    Some(format!(
                        "https://gitlab.com/{repo}/-/releases/{tag}/downloads/{asset}"
                    ))
                }
            }
            Source::Direct => {
                // For direct sources, the asset IS the full URL (after version expansion)
                Some(asset)
            }
            // npm, crates, rustup, brew don't have download URLs -- mise handles them
            _ => None,
        }
    }

    /// Resolve the checksum file URL for a platform.
    /// F10: validates the expanded filename against ASSET_PATTERN.
    pub fn checksum_url(&self) -> Option<String> {
        let cfg = self.checksum.as_ref()?;
        let file = cfg.file.as_ref()?;
        let filename = file.replace("{version}", &self.version);
        // F10: validate expanded checksum filename
        if !ASSET_RE.is_match(&filename) {
            eprintln!("  warning: invalid checksum filename '{filename}', skipping");
            return None;
        }
        let tag = self.tag();

        match self.source {
            Source::Github => {
                let repo = self.repo.as_ref()?;
                Some(format!(
                    "https://github.com/{repo}/releases/download/{tag}/{filename}"
                ))
            }
            Source::Gitlab => {
                if let Some(pid) = self.project_id {
                    Some(format!(
                        "https://gitlab.com/api/v4/projects/{pid}/packages/generic/{name}/{tag}/{filename}",
                        name = self.name
                    ))
                } else {
                    let repo = self.repo.as_ref()?;
                    Some(format!(
                        "https://gitlab.com/{repo}/-/releases/{tag}/downloads/{filename}"
                    ))
                }
            }
            _ => None,
        }
    }

    /// Validate all fields against security patterns.
    /// This is the security-critical boundary (S-3, S-10).
    pub fn validate(&self) -> Result<()> {
        if !NAME_RE.is_match(&self.name) {
            anyhow::bail!(
                "invalid tool name '{}': must match {NAME_PATTERN}",
                self.name
            );
        }

        if !VERSION_RE.is_match(&self.version) {
            anyhow::bail!(
                "invalid version '{}' for {}: must match {VERSION_PATTERN}",
                self.version,
                self.name
            );
        }

        if !TAG_PREFIX_RE.is_match(&self.tag_prefix) {
            anyhow::bail!(
                "invalid tag_prefix '{}' for {}: must match {TAG_PREFIX_PATTERN}",
                self.tag_prefix,
                self.name
            );
        }

        // Finding 11: validate direct source URLs are HTTPS
        if self.source == Source::Direct {
            for (platform, url) in &self.assets {
                let expanded = url.replace("{version}", &self.version);
                if !expanded.to_lowercase().starts_with("https://") {
                    anyhow::bail!(
                        "direct source URL for {} ({}) must use https://",
                        self.name,
                        platform
                    );
                }
            }
        }

        if let Some(ref bin) = self.bin
            && !BIN_RE.is_match(bin)
        {
            anyhow::bail!(
                "invalid bin name '{}' for {}: must match {BIN_PATTERN}",
                bin,
                self.name
            );
        }

        if let Some(ref repo) = self.repo
            && !REPO_RE.is_match(repo)
        {
            anyhow::bail!(
                "invalid repo '{}' for {}: must match {REPO_PATTERN}",
                repo,
                self.name
            );
        }

        // Validate asset names: no path separators, no percent-encoding
        for (platform, asset) in &self.assets {
            if Platform::from_key(platform).is_none() {
                anyhow::bail!(
                    "unknown platform '{}' in assets for {}",
                    platform,
                    self.name
                );
            }
            // For direct sources, assets are full URLs -- skip pattern check
            if self.source != Source::Direct && !ASSET_RE.is_match(asset) {
                anyhow::bail!(
                    "invalid asset name '{}' for {} ({}): must match {ASSET_PATTERN}",
                    asset,
                    self.name,
                    platform
                );
            }
        }

        // Source-specific required fields
        match self.source {
            Source::Github => {
                if self.repo.is_none() {
                    anyhow::bail!("{}: github source requires 'repo' field", self.name);
                }
            }
            Source::Gitlab => {
                if self.project_id.is_none() && self.repo.is_none() {
                    anyhow::bail!(
                        "{}: gitlab source requires either 'project_id' or 'repo'",
                        self.name
                    );
                }
            }
            Source::Npm => {
                // package defaults to name, so no required field
            }
            Source::Crates => {
                // crate defaults to name, so no required field
            }
            Source::Brew => {
                // formula defaults to name, so no required field
            }
            Source::Direct => {
                if self.assets.is_empty() {
                    anyhow::bail!("{}: direct source requires 'assets' with URLs", self.name);
                }
            }
            Source::Rustup => {}
        }

        // T3-6: validate inline checksums are valid hex hashes
        for (platform, hash) in &self.checksums {
            // npm-source tools are platform-independent (one tarball) and
            // record their dist.integrity-verified checksum under the "npm"
            // sentinel key rather than a per-platform key.
            let is_npm_key = platform == "npm" && self.source == Source::Npm;
            if !is_npm_key && Platform::from_key(platform).is_none() {
                anyhow::bail!(
                    "unknown platform '{}' in checksums for {}",
                    platform,
                    self.name
                );
            }
            if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
                anyhow::bail!(
                    "invalid inline checksum for {} ({}): must be 64 hex chars, got '{}'",
                    self.name,
                    platform,
                    hash
                );
            }
        }

        Ok(())
    }
}

/// Registry metadata from _meta.toml.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryMeta {
    pub registry: RegistryInfo,
    #[serde(default)]
    pub policy: RegistryPolicy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryInfo {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub maintainer: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RegistryPolicy {
    #[serde(default)]
    pub auto_merge_tiers: Vec<Tier>,
    #[serde(default)]
    pub auto_merge_bump: Vec<String>,
    #[serde(default = "default_true")]
    pub auto_merge_requires_checksum: bool,
}

impl RegistryPolicy {
    /// Check whether an update qualifies for auto-merge under this policy.
    pub fn is_auto_merge_eligible(&self, tier: Tier, bump: &str, checksums_verified: bool) -> bool {
        let tier_ok = self.auto_merge_tiers.contains(&tier);
        let bump_ok = self.auto_merge_bump.iter().any(|b| b == bump);
        let checksum_ok = !self.auto_merge_requires_checksum || checksums_verified;
        tier_ok && bump_ok && checksum_ok
    }
}

fn default_true() -> bool {
    true
}

/// Load all tool definitions from a registry directory.
pub fn load_registry_tools(registry_dir: &Path) -> Result<Vec<ToolDef>> {
    let tools_dir = registry_dir.join("tools");
    if !tools_dir.exists() {
        return Ok(vec![]);
    }

    let mut tools = Vec::new();
    for entry in std::fs::read_dir(&tools_dir)
        .with_context(|| format!("failed to read {}", tools_dir.display()))?
    {
        let entry = entry?;
        let path = entry.path();

        // Finding 3: reject symlinks to prevent path traversal from malicious registries
        if entry.file_type().map(|ft| ft.is_symlink()).unwrap_or(false) {
            eprintln!("  warning: skipping symlink {}", path.display());
            continue;
        }

        // Skip _meta.toml and non-TOML files
        if path.file_name().map(|n| n == "_meta.toml").unwrap_or(false) {
            continue;
        }
        if path.extension().map(|e| e != "toml").unwrap_or(true) {
            continue;
        }

        match ToolDef::load(&path) {
            Ok(def) => tools.push(def),
            Err(e) => {
                eprintln!("  warning: skipping {}: {e}", path.display());
            }
        }
    }

    tools.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(tools)
}

/// Load registry metadata from _meta.toml.
pub fn load_registry_meta(registry_dir: &Path) -> Result<RegistryMeta> {
    let path = registry_dir.join("tools").join("_meta.toml");
    if !path.exists() {
        anyhow::bail!("no _meta.toml found in {}", registry_dir.display());
    }
    let content = std::fs::read_to_string(&path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    let meta: RegistryMeta =
        toml::from_str(&content).with_context(|| format!("failed to parse {}", path.display()))?;
    Ok(meta)
}

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

    #[test]
    fn valid_tool_name() {
        let re = regex::Regex::new(NAME_PATTERN).unwrap();
        assert!(re.is_match("gh"));
        assert!(re.is_match("claude-code"));
        assert!(re.is_match("git-lfs"));
        assert!(re.is_match("yq"));
        assert!(!re.is_match(""));
        assert!(!re.is_match("-bad"));
        assert!(!re.is_match("Bad"));
        assert!(!re.is_match("../evil"));
        assert!(!re.is_match("foo/bar"));
    }

    #[test]
    fn valid_version() {
        let re = regex::Regex::new(VERSION_PATTERN).unwrap();
        assert!(re.is_match("2.89.0"));
        assert!(re.is_match("1.0.0-beta.1"));
        assert!(re.is_match("0.11.3"));
        assert!(re.is_match("5.3.4"));
        assert!(re.is_match("30.2"));
        assert!(!re.is_match(""));
        assert!(!re.is_match("v1.0.0"));
        assert!(!re.is_match("abc"));
    }

    #[test]
    fn valid_asset_name() {
        let re = regex::Regex::new(ASSET_PATTERN).unwrap();
        assert!(re.is_match("gh_{version}_macOS_arm64.zip"));
        assert!(re.is_match("muxr-darwin-arm64"));
        assert!(re.is_match("checksums.txt"));
        assert!(!re.is_match("../../etc/passwd"));
        assert!(!re.is_match("foo/bar.tar.gz"));
        assert!(!re.is_match("evil%2F..%2Fpasswd"));
    }

    #[test]
    fn url_generation_github() {
        let def = ToolDef {
            name: "gh".to_string(),
            description: None,
            source: Source::Github,
            version: "2.89.0".to_string(),
            tag_prefix: "v".to_string(),
            bin: Some("gh".to_string()),
            tier: Tier::High,
            repo: Some("cli/cli".to_string()),
            project_id: None,
            package: None,
            crate_name: None,
            formula: None,
            aqua: Some("cli/cli".to_string()),
            assets: HashMap::from([
                (
                    "macos-arm64".to_string(),
                    "gh_{version}_macOS_arm64.zip".to_string(),
                ),
                (
                    "linux-x64".to_string(),
                    "gh_{version}_linux_amd64.tar.gz".to_string(),
                ),
            ]),
            checksum: Some(ChecksumConfig {
                file: Some("gh_{version}_checksums.txt".to_string()),
                format: ChecksumFormat::Sha256,
            }),
            checksums: HashMap::new(),
            signature: None,
        };

        assert_eq!(
            def.url_for(Platform::MacosArm64).unwrap(),
            "https://github.com/cli/cli/releases/download/v2.89.0/gh_2.89.0_macOS_arm64.zip"
        );
        assert_eq!(def.tag(), "v2.89.0");
        assert_eq!(def.bin_name(), "gh");
    }

    #[test]
    fn url_generation_gitlab_own() {
        let def = ToolDef {
            name: "muxr".to_string(),
            description: None,
            source: Source::Gitlab,
            version: "0.6.2".to_string(),
            tag_prefix: "v".to_string(),
            bin: Some("muxr".to_string()),
            tier: Tier::Own,
            repo: None,
            project_id: Some(80663080),
            package: None,
            crate_name: None,
            formula: None,
            aqua: None,
            assets: HashMap::from([
                ("macos-arm64".to_string(), "muxr-darwin-arm64".to_string()),
                ("linux-x64".to_string(), "muxr-linux-amd64".to_string()),
            ]),
            checksum: Some(ChecksumConfig {
                file: Some("checksums.txt".to_string()),
                format: ChecksumFormat::Sha256,
            }),
            checksums: HashMap::new(),
            signature: Some(SignatureConfig {
                method: SignatureMethod::CosignKeyless,
                issuer: Some("https://gitlab.com".to_string()),
                identity: Some("https://gitlab.com/nomograph/muxr".to_string()),
            }),
        };

        assert_eq!(
            def.url_for(Platform::MacosArm64).unwrap(),
            "https://gitlab.com/api/v4/projects/80663080/packages/generic/muxr/v0.6.2/muxr-darwin-arm64"
        );
    }

    #[test]
    fn validation_rejects_path_traversal() {
        let mut def = make_valid_tool();
        def.name = "../evil".to_string();
        assert!(def.validate().is_err());

        let mut def = make_valid_tool();
        def.bin = Some("../../passwd".to_string());
        assert!(def.validate().is_err());
    }

    #[test]
    fn validation_rejects_bad_repo() {
        let mut def = make_valid_tool();
        def.repo = Some("evil; rm -rf /".to_string());
        assert!(def.validate().is_err());
    }

    fn make_valid_tool() -> ToolDef {
        ToolDef {
            name: "test-tool".to_string(),
            description: None,
            source: Source::Github,
            version: "1.0.0".to_string(),
            tag_prefix: "v".to_string(),
            bin: None,
            tier: Tier::Low,
            repo: Some("owner/repo".to_string()),
            project_id: None,
            package: None,
            crate_name: None,
            formula: None,
            aqua: None,
            assets: HashMap::new(),
            checksum: None,
            checksums: HashMap::new(),
            signature: None,
        }
    }

    #[test]
    fn npm_source_accepts_npm_checksum_key() {
        // npm-source tools record their dist.integrity-verified checksum under
        // the "npm" sentinel key (platform-independent). validate() must accept it.
        let mut def = make_valid_tool();
        def.source = Source::Npm;
        def.repo = None;
        def.package = Some("@mermaid-js/mermaid-cli".to_string());
        def.checksums.insert(
            "npm".to_string(),
            "f6fd0879dbf500e453784bbd9db92ae951097e0e9e8a90ec613f2bd3ca8fa06c".to_string(),
        );
        assert!(def.validate().is_ok(), "npm key must validate for npm source");
    }

    #[test]
    fn non_npm_source_rejects_npm_checksum_key() {
        // A github tool must NOT be allowed to use the "npm" sentinel key.
        let mut def = make_valid_tool();
        def.checksums.insert(
            "npm".to_string(),
            "f6fd0879dbf500e453784bbd9db92ae951097e0e9e8a90ec613f2bd3ca8fa06c".to_string(),
        );
        assert!(
            def.validate().is_err(),
            "npm key must be rejected for non-npm source"
        );
    }

    #[test]
    fn source_brew_serializes_to_brew() {
        // Wrap in a struct so toml can serialize (TOML requires a top-level table).
        #[derive(Serialize)]
        struct W { s: Source }
        let toml_str = toml::to_string(&W { s: Source::Brew }).unwrap();
        assert!(toml_str.contains("brew"), "expected 'brew' in {toml_str}");
    }

    #[test]
    fn tooldef_brew_roundtrip() {
        let def = ToolFile {
            tool: ToolDef {
                name: "chafa".to_string(),
                description: None,
                source: Source::Brew,
                version: "1.18.2".to_string(),
                tag_prefix: String::new(),
                bin: None,
                tier: Tier::Low,
                repo: None,
                project_id: None,
                package: None,
                crate_name: None,
                formula: Some("chafa".to_string()),
                aqua: None,
                assets: HashMap::new(),
                checksum: None,
                checksums: HashMap::new(),
                signature: None,
            },
        };
        let toml_str = toml::to_string_pretty(&def).unwrap();
        assert!(toml_str.contains("source = \"brew\""), "source not brew in {toml_str}");
        assert!(toml_str.contains("formula = \"chafa\""), "formula missing in {toml_str}");
        let roundtripped: ToolFile = toml::from_str(&toml_str).unwrap();
        assert_eq!(roundtripped.tool.source, Source::Brew);
        assert_eq!(roundtripped.tool.formula.as_deref(), Some("chafa"));
        assert_eq!(roundtripped.tool.version, "1.18.2");
    }

    #[test]
    fn auto_merge_eligible_low_patch_verified() {
        let policy = RegistryPolicy {
            auto_merge_tiers: vec![Tier::Low],
            auto_merge_bump: vec!["patch".to_string(), "minor".to_string()],
            auto_merge_requires_checksum: true,
        };
        assert!(policy.is_auto_merge_eligible(Tier::Low, "patch", true));
        assert!(policy.is_auto_merge_eligible(Tier::Low, "minor", true));
    }

    #[test]
    fn auto_merge_rejects_wrong_tier() {
        let policy = RegistryPolicy {
            auto_merge_tiers: vec![Tier::Low],
            auto_merge_bump: vec!["patch".to_string()],
            auto_merge_requires_checksum: true,
        };
        assert!(!policy.is_auto_merge_eligible(Tier::High, "patch", true));
        assert!(!policy.is_auto_merge_eligible(Tier::Own, "patch", true));
    }

    #[test]
    fn auto_merge_rejects_major_bump() {
        let policy = RegistryPolicy {
            auto_merge_tiers: vec![Tier::Low],
            auto_merge_bump: vec!["patch".to_string(), "minor".to_string()],
            auto_merge_requires_checksum: true,
        };
        assert!(!policy.is_auto_merge_eligible(Tier::Low, "major", true));
    }

    #[test]
    fn auto_merge_rejects_unverified_when_required() {
        let policy = RegistryPolicy {
            auto_merge_tiers: vec![Tier::Low],
            auto_merge_bump: vec!["patch".to_string()],
            auto_merge_requires_checksum: true,
        };
        assert!(!policy.is_auto_merge_eligible(Tier::Low, "patch", false));
    }

    #[test]
    fn auto_merge_allows_unverified_when_not_required() {
        let policy = RegistryPolicy {
            auto_merge_tiers: vec![Tier::Low],
            auto_merge_bump: vec!["patch".to_string()],
            auto_merge_requires_checksum: false,
        };
        assert!(policy.is_auto_merge_eligible(Tier::Low, "patch", false));
    }
}