nomograph-kit 0.11.0

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
use anyhow::{Context, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

use crate::config::Config;

// -- Lockfile data model --

/// A single resolved tool entry in the lockfile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockEntry {
    /// Resolved version string (e.g., "2.89.0").
    pub version: String,
    /// Name of the registry this tool was resolved from.
    pub registry: String,
    /// Fully resolved download URL for this platform.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// T3-1: Registry-provided inline checksum (archive hash).
    /// Used by S-2 integrity check -- compares registry-to-registry.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry_sha256: Option<String>,
    /// F6: SHA-256 of the installed binary (computed after mise install).
    /// Different from registry_sha256 for archive-distributed tools.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binary_sha256: Option<String>,
    /// T3-3: backwards-compatible alias for pre-rename lockfiles.
    #[serde(default, alias = "verified", alias = "sha256")]
    pub verification_method: String,
    /// ISO 8601 timestamp of last update.
    pub updated: String,
}

/// Result of an integrity check against an existing lock entry (S-2, S-9).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IntegrityResult {
    /// Same version, same checksum. No action needed.
    Ok,
    /// Version changed -- checksum change is expected.
    VersionChanged,
    /// SAME version but DIFFERENT checksum. Supply chain attack indicator (S-2).
    ChecksumChanged,
    /// Tool resolved from a different registry than previously locked (S-9).
    #[allow(dead_code)]
    RegistryChanged { from: String, to: String },
    /// Tool not present in lockfile yet.
    New,
}

/// A change between old and new lockfile state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
    Added {
        name: String,
    },
    Updated {
        name: String,
        from: String,
        to: String,
    },
    Removed {
        name: String,
    },
    RegistryMoved {
        name: String,
        from: String,
        to: String,
    },
}

// -- TOML file structure --
//
// The lockfile uses [resolved.<name>] tables so that tool names are
// TOML keys under a single `resolved` table:
//
//   # Auto-generated by kit sync. Do not edit.
//   [resolved.gh]
//   version = "2.89.0"
//   registry = "dunn"
//   ...

#[derive(Debug, Clone, Serialize, Deserialize)]
struct LockfileDoc {
    #[serde(default)]
    resolved: HashMap<String, LockEntry>,
}

/// The kit lockfile -- records exact resolved state of all managed tools.
///
/// In project mode: `.kit.lock` next to `kit.toml`.
/// In global mode: `~/.config/kit/kit.lock`.
#[derive(Debug, Clone)]
pub struct Lockfile {
    pub entries: HashMap<String, LockEntry>,
}

impl Lockfile {
    /// Load the lockfile from a specific path.
    /// Returns an empty lockfile if the file does not exist yet (first run).
    pub fn load_from(path: &std::path::Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self {
                entries: HashMap::new(),
            });
        }
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("failed to read {}", path.display()))?;
        let doc: LockfileDoc = toml::from_str(&content)
            .with_context(|| format!("failed to parse {}", path.display()))?;
        Ok(Self {
            entries: doc.resolved,
        })
    }

    /// Write the lockfile atomically to a specific path.
    pub fn save_to(&self, path: &std::path::Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create {}", parent.display()))?;
        }

        let doc = LockfileDoc {
            resolved: self.entries.clone(),
        };
        let mut content = String::from("# Auto-generated by kit sync. Do not edit.\n");
        content.push_str(&toml::to_string_pretty(&doc).context("failed to serialize lockfile")?);

        // Atomic write: write to .tmp then rename to avoid partial writes
        let tmp_path = path.with_extension("lock.tmp");
        std::fs::write(&tmp_path, &content)
            .with_context(|| format!("failed to write {}", tmp_path.display()))?;
        std::fs::rename(&tmp_path, path).with_context(|| {
            format!(
                "failed to rename {} -> {}",
                tmp_path.display(),
                path.display()
            )
        })?;

        Ok(())
    }

    /// Resolved path to the global lockfile.
    #[allow(dead_code)]
    pub fn global_path() -> Result<PathBuf> {
        let config_dir = Config::config_dir()?;
        Ok(config_dir.join("kit.lock"))
    }

    /// Look up an entry by tool name.
    pub fn get(&self, name: &str) -> Option<&LockEntry> {
        self.entries.get(name)
    }

    /// Insert or update an entry for a tool.
    pub fn set(&mut self, name: &str, entry: LockEntry) {
        self.entries.insert(name.to_string(), entry);
    }

    /// Remove an entry by tool name. Returns the removed entry if it existed.
    #[allow(dead_code)]
    pub fn remove(&mut self, name: &str) -> Option<LockEntry> {
        self.entries.remove(name)
    }

    /// Check integrity of a new version/checksum against the existing lock entry.
    ///
    /// T3-1: Compares registry-to-registry checksums (not binary hash).
    /// The registry_sha256 field stores the inline checksum from the registry
    /// (which is an archive hash). Comparing this against the new registry
    /// checksum detects upstream tampering without false positives from
    /// binary-vs-archive hash differences.
    ///
    /// - **S-2**: Same version + changed registry checksum = hard stop.
    /// - **S-9**: Registry source change = warning (dependency confusion).
    pub fn check_integrity(
        &self,
        name: &str,
        new_version: &str,
        new_registry_sha256: Option<&str>,
    ) -> IntegrityResult {
        let existing = match self.entries.get(name) {
            Some(e) => e,
            None => return IntegrityResult::New,
        };

        // Version changed -- checksum difference is expected
        if existing.version != new_version {
            return IntegrityResult::VersionChanged;
        }

        // Same version -- compare registry checksums (T3-1: registry-to-registry)
        if let (Some(existing_sha), Some(new_sha)) =
            (existing.registry_sha256.as_deref(), new_registry_sha256)
            && existing_sha != new_sha
        {
            return IntegrityResult::ChecksumChanged;
        }

        IntegrityResult::Ok
    }

    /// Check whether a tool's registry source has changed (S-9).
    ///
    /// Separated from `check_integrity` because registry changes are
    /// warnings, not hard stops, and callers may want to handle them
    /// differently.
    #[allow(dead_code)]
    pub fn check_registry(&self, name: &str, new_registry: &str) -> Option<IntegrityResult> {
        let existing = self.entries.get(name)?;
        if existing.registry != new_registry {
            Some(IntegrityResult::RegistryChanged {
                from: existing.registry.clone(),
                to: new_registry.to_string(),
            })
        } else {
            None
        }
    }
}

/// Create a new `LockEntry` with the current timestamp.
/// T3-1: accepts separate registry (archive) and binary checksums.
pub fn new_entry(
    version: &str,
    registry: &str,
    url: Option<&str>,
    registry_sha256: Option<&str>,
    binary_sha256: Option<&str>,
    verification_method: &str,
) -> LockEntry {
    LockEntry {
        version: version.to_string(),
        registry: registry.to_string(),
        url: url.map(String::from),
        registry_sha256: registry_sha256.map(String::from),
        binary_sha256: binary_sha256.map(String::from),
        verification_method: verification_method.to_string(),
        updated: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
    }
}

/// Compute the diff between an existing lockfile and a set of newly resolved tools.
///
/// `new_resolved` is a slice of `(name, version, registry)` tuples
/// representing the desired state after sync.
pub fn diff(old: &Lockfile, new_resolved: &[(String, String, String)]) -> Vec<Change> {
    let mut changes = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for (name, version, registry) in new_resolved {
        seen.insert(name.as_str());

        match old.entries.get(name.as_str()) {
            None => {
                changes.push(Change::Added { name: name.clone() });
            }
            Some(existing) => {
                // Check registry move first
                if existing.registry != *registry {
                    changes.push(Change::RegistryMoved {
                        name: name.clone(),
                        from: existing.registry.clone(),
                        to: registry.clone(),
                    });
                }
                // Check version change
                if existing.version != *version {
                    changes.push(Change::Updated {
                        name: name.clone(),
                        from: existing.version.clone(),
                        to: version.clone(),
                    });
                }
            }
        }
    }

    // Tools in old lockfile but not in new resolved set = removed
    for name in old.entries.keys() {
        if !seen.contains(name.as_str()) {
            changes.push(Change::Removed { name: name.clone() });
        }
    }

    // Sort for deterministic output
    changes.sort_by(|a, b| {
        let name_a = match a {
            Change::Added { name } => name,
            Change::Updated { name, .. } => name,
            Change::Removed { name } => name,
            Change::RegistryMoved { name, .. } => name,
        };
        let name_b = match b {
            Change::Added { name } => name,
            Change::Updated { name, .. } => name,
            Change::Removed { name } => name,
            Change::RegistryMoved { name, .. } => name,
        };
        name_a.cmp(name_b)
    });

    changes
}

impl std::fmt::Display for Change {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Change::Added { name } => write!(f, "  + {name} (new)"),
            Change::Updated { name, from, to } => {
                write!(f, "  ~ {name} {from} -> {to}")
            }
            Change::Removed { name } => write!(f, "  - {name} (removed)"),
            Change::RegistryMoved { name, from, to } => {
                write!(f, "  ! {name} registry: {from} -> {to}")
            }
        }
    }
}

impl std::fmt::Display for IntegrityResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IntegrityResult::Ok => write!(f, "ok"),
            IntegrityResult::VersionChanged => write!(f, "version changed"),
            IntegrityResult::ChecksumChanged => {
                write!(f, "CHECKSUM CHANGED -- possible supply chain attack")
            }
            IntegrityResult::RegistryChanged { from, to } => {
                write!(f, "registry changed: {from} -> {to}")
            }
            IntegrityResult::New => write!(f, "new"),
        }
    }
}

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

    fn make_lockfile(entries: Vec<(&str, LockEntry)>) -> Lockfile {
        Lockfile {
            entries: entries
                .into_iter()
                .map(|(k, v)| (k.to_string(), v))
                .collect(),
        }
    }

    fn entry(version: &str, registry: &str, sha256: Option<&str>) -> LockEntry {
        LockEntry {
            version: version.to_string(),
            registry: registry.to_string(),
            url: Some("https://example.com/tool".to_string()),
            registry_sha256: sha256.map(String::from),
            binary_sha256: None,
            verification_method: "checksum".to_string(),
            updated: "2026-04-06T14:30:00Z".to_string(),
        }
    }

    // -- Integrity checks --

    #[test]
    fn integrity_new_tool() {
        let lock = make_lockfile(vec![]);
        let result = lock.check_integrity("gh", "2.89.0", Some("abc123"));
        assert_eq!(result, IntegrityResult::New);
    }

    #[test]
    fn integrity_same_version_same_checksum() {
        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc123")))]);
        let result = lock.check_integrity("gh", "2.89.0", Some("abc123"));
        assert_eq!(result, IntegrityResult::Ok);
    }

    #[test]
    fn integrity_version_changed() {
        let lock = make_lockfile(vec![("gh", entry("2.88.0", "dunn", Some("old123")))]);
        let result = lock.check_integrity("gh", "2.89.0", Some("new456"));
        assert_eq!(result, IntegrityResult::VersionChanged);
    }

    #[test]
    fn integrity_checksum_changed_same_version_is_attack() {
        // S-2: same version + different checksum = supply chain attack
        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc123")))]);
        let result = lock.check_integrity("gh", "2.89.0", Some("TAMPERED"));
        assert_eq!(result, IntegrityResult::ChecksumChanged);
    }

    #[test]
    fn integrity_no_checksums_is_ok() {
        // If either side lacks a checksum, we can't compare -- treat as ok
        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", None))]);
        let result = lock.check_integrity("gh", "2.89.0", Some("abc123"));
        assert_eq!(result, IntegrityResult::Ok);

        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc123")))]);
        let result = lock.check_integrity("gh", "2.89.0", None);
        assert_eq!(result, IntegrityResult::Ok);
    }

    // -- Registry change detection --

    #[test]
    fn registry_change_detected() {
        // S-9: tool moves between registries
        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc123")))]);
        let result = lock.check_registry("gh", "untrusted");
        assert_eq!(
            result,
            Some(IntegrityResult::RegistryChanged {
                from: "dunn".to_string(),
                to: "untrusted".to_string(),
            })
        );
    }

    #[test]
    fn registry_same_returns_none() {
        let lock = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc123")))]);
        assert_eq!(lock.check_registry("gh", "dunn"), None);
    }

    #[test]
    fn registry_check_unknown_tool() {
        let lock = make_lockfile(vec![]);
        assert_eq!(lock.check_registry("gh", "dunn"), None);
    }

    // -- Diff --

    #[test]
    fn diff_added() {
        let old = make_lockfile(vec![]);
        let new_resolved = vec![("gh".to_string(), "2.89.0".to_string(), "dunn".to_string())];
        let changes = diff(&old, &new_resolved);
        assert_eq!(
            changes,
            vec![Change::Added {
                name: "gh".to_string()
            }]
        );
    }

    #[test]
    fn diff_updated() {
        let old = make_lockfile(vec![("gh", entry("2.88.0", "dunn", Some("old")))]);
        let new_resolved = vec![("gh".to_string(), "2.89.0".to_string(), "dunn".to_string())];
        let changes = diff(&old, &new_resolved);
        assert_eq!(
            changes,
            vec![Change::Updated {
                name: "gh".to_string(),
                from: "2.88.0".to_string(),
                to: "2.89.0".to_string(),
            }]
        );
    }

    #[test]
    fn diff_removed() {
        let old = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc")))]);
        let new_resolved: Vec<(String, String, String)> = vec![];
        let changes = diff(&old, &new_resolved);
        assert_eq!(
            changes,
            vec![Change::Removed {
                name: "gh".to_string()
            }]
        );
    }

    #[test]
    fn diff_registry_moved() {
        let old = make_lockfile(vec![("gh", entry("2.89.0", "dunn", Some("abc")))]);
        let new_resolved = vec![(
            "gh".to_string(),
            "2.89.0".to_string(),
            "community".to_string(),
        )];
        let changes = diff(&old, &new_resolved);
        assert_eq!(
            changes,
            vec![Change::RegistryMoved {
                name: "gh".to_string(),
                from: "dunn".to_string(),
                to: "community".to_string(),
            }]
        );
    }

    #[test]
    fn diff_complex_scenario() {
        let old = make_lockfile(vec![
            ("gh", entry("2.88.0", "dunn", Some("old"))),
            ("jq", entry("1.7.0", "dunn", Some("jq_hash"))),
            ("removed-tool", entry("1.0.0", "dunn", Some("x"))),
        ]);
        let new_resolved = vec![
            ("gh".to_string(), "2.89.0".to_string(), "dunn".to_string()),
            ("jq".to_string(), "1.7.0".to_string(), "dunn".to_string()),
            ("yq".to_string(), "4.40.0".to_string(), "dunn".to_string()),
        ];
        let changes = diff(&old, &new_resolved);

        // Should have: gh updated, removed-tool removed, yq added
        // jq unchanged so not in changes
        assert!(changes.contains(&Change::Updated {
            name: "gh".to_string(),
            from: "2.88.0".to_string(),
            to: "2.89.0".to_string(),
        }));
        assert!(changes.contains(&Change::Removed {
            name: "removed-tool".to_string(),
        }));
        assert!(changes.contains(&Change::Added {
            name: "yq".to_string(),
        }));
        // jq is unchanged
        assert!(!changes.iter().any(|c| matches!(c,
            Change::Updated { name, .. } | Change::Added { name } if name == "jq"
        )));
    }

    // -- Serialization round-trip --

    #[test]
    fn toml_round_trip() {
        let doc = LockfileDoc {
            resolved: HashMap::from([
                (
                    "gh".to_string(),
                    LockEntry {
                        version: "2.89.0".to_string(),
                        registry: "dunn".to_string(),
                        url: Some(
                            "https://github.com/cli/cli/releases/download/v2.89.0/gh_2.89.0_macOS_arm64.zip"
                                .to_string(),
                        ),
                        registry_sha256: Some("abc123".to_string()),
                        binary_sha256: None,
                        verification_method: "checksum".to_string(),
                        updated: "2026-04-06T14:30:00Z".to_string(),
                    },
                ),
                (
                    "muxr".to_string(),
                    LockEntry {
                        version: "0.6.2".to_string(),
                        registry: "dunn".to_string(),
                        url: None,
                        registry_sha256: None,
                        binary_sha256: None,
                        verification_method: "cosign".to_string(),
                        updated: "2026-04-06T14:30:00Z".to_string(),
                    },
                ),
            ]),
        };

        let serialized = toml::to_string_pretty(&doc).unwrap();
        let parsed: LockfileDoc = toml::from_str(&serialized).unwrap();

        assert_eq!(parsed.resolved.len(), 2);
        assert_eq!(parsed.resolved["gh"].version, "2.89.0");
        assert_eq!(parsed.resolved["gh"].registry, "dunn");
        assert_eq!(
            parsed.resolved["gh"].url.as_deref(),
            Some("https://github.com/cli/cli/releases/download/v2.89.0/gh_2.89.0_macOS_arm64.zip")
        );
        assert_eq!(parsed.resolved["muxr"].version, "0.6.2");
        assert!(parsed.resolved["muxr"].url.is_none());
        assert!(parsed.resolved["muxr"].registry_sha256.is_none());
    }

    #[test]
    fn get_set_remove() {
        let mut lock = Lockfile {
            entries: HashMap::new(),
        };

        assert!(lock.get("gh").is_none());

        lock.set("gh", entry("2.89.0", "dunn", Some("abc")));
        assert_eq!(lock.get("gh").unwrap().version, "2.89.0");

        lock.set("gh", entry("2.90.0", "dunn", Some("def")));
        assert_eq!(lock.get("gh").unwrap().version, "2.90.0");

        let removed = lock.remove("gh");
        assert!(removed.is_some());
        assert!(lock.get("gh").is_none());
    }

    #[test]
    fn new_entry_has_timestamp() {
        let e = new_entry("2.89.0", "dunn", None, None, None, "none");
        // Should parse as a valid RFC 3339 timestamp
        assert!(chrono::DateTime::parse_from_rfc3339(&e.updated).is_ok());
    }

    #[test]
    fn display_impls() {
        assert_eq!(format!("{}", IntegrityResult::Ok), "ok");
        assert_eq!(format!("{}", IntegrityResult::New), "new");
        assert!(format!("{}", IntegrityResult::ChecksumChanged).contains("supply chain"));

        let change = Change::Updated {
            name: "gh".to_string(),
            from: "2.88.0".to_string(),
            to: "2.89.0".to_string(),
        };
        assert!(format!("{change}").contains("2.88.0 -> 2.89.0"));
    }
}