tuffcli 0.10.2

Capability lifecycle manager for coding agents.
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
use std::path::Path;

use semver::Version;
use serde::Serialize;

use crate::error::Result;
use crate::git;
use crate::lockfile;
use crate::manifest::CapabilityType;
use crate::oci::{self, OciTransferOptions};
use crate::release;

use super::{home_dir_opt, render_table, short_sha, style_outdated_status};

struct OutdatedRow {
    id: String,
    capability_type: CapabilityType,
    target: String,
    /// Shown beside CURRENT for a git install whose version is only what
    /// the source declared, and carried in the JSON for every row.
    version_scheme: lockfile::VersionScheme,
    /// Whether the entry came from git, where a declared version is weaker
    /// than a release and the table says so.
    from_git: bool,
    current: String,
    latest: String,
    status: String,
    /// `major`, `minor`, or `patch` when both sides are releases: the size
    /// of the change the author claimed, shown beside `outdated`.
    change: Option<String>,
    /// The newest release the repository publishes, for a git install. On a
    /// release-pinned entry this is what LATEST already shows; on a commit
    /// or declared install it is the release the entry could be pinned to,
    /// and the reason for the note under the table.
    latest_release: Option<String>,
}

/// The `--json` shape of an [`OutdatedRow`], with the same `type`/`target`
/// keys as `tuff check --json`. The table prints `—` where nothing could be
/// resolved; a script should not have to compare against a dash, so that
/// becomes `null`.
#[derive(Serialize)]
struct JsonOutdatedRow<'a> {
    id: &'a str,
    #[serde(rename = "type")]
    capability_type: CapabilityType,
    target: &'a str,
    version_scheme: lockfile::VersionScheme,
    current: &'a str,
    latest: Option<&'a str>,
    status: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    change: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    latest_release: Option<&'a str>,
}

impl OutdatedRow {
    fn as_json(&self) -> JsonOutdatedRow<'_> {
        JsonOutdatedRow {
            id: &self.id,
            capability_type: self.capability_type,
            target: &self.target,
            version_scheme: self.version_scheme,
            current: &self.current,
            latest: (self.latest != UNRESOLVED).then_some(self.latest.as_str()),
            status: &self.status,
            change: self.change.as_deref(),
            latest_release: self.latest_release.as_deref(),
        }
    }
}

/// What `classify` concluded about one entry: the three columns, plus the
/// newest release a git repository publishes when it publishes any.
struct Verdict {
    current: String,
    latest: String,
    status: String,
    latest_release: Option<String>,
}

impl From<(String, String, String)> for Verdict {
    fn from((current, latest, status): (String, String, String)) -> Self {
        Verdict {
            current,
            latest,
            status,
            latest_release: None,
        }
    }
}

/// What the LATEST column shows when there is nothing to compare against.
const UNRESOLVED: &str = "—";

/// What the registry's tags say about an installed pack version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PackVersionStatus {
    /// A newer semver tag is published.
    Newer(String),
    /// The installed version is the newest semver tag.
    Current,
    /// Nothing conclusive: the installed version or every tag is unparsable.
    Unknown,
}

/// Compare an installed pack version against the tags published for it.
///
/// Tags are not compared as strings: `"1.9.0" > "1.10.0"` under plain
/// lexicographic ordering, which is the wrong answer and exactly the kind of
/// confidently-wrong result `tuff outdated` should not produce. Only tags
/// that parse as semver are compared, using real version ordering; anything
/// else is excluded rather than guessed at. `tuff pack build --version` does
/// not enforce a version scheme, so an unparsable installed version is a
/// real case, not a hypothetical one.
pub(crate) fn compare_pack_versions(installed: &str, tags: &[String]) -> PackVersionStatus {
    let Ok(installed_version) = Version::parse(installed) else {
        return PackVersionStatus::Unknown;
    };
    match tags.iter().filter_map(|tag| Version::parse(tag).ok()).max() {
        None => PackVersionStatus::Unknown,
        Some(latest) if latest > installed_version => PackVersionStatus::Newer(latest.to_string()),
        Some(_) => PackVersionStatus::Current,
    }
}

/// Whether the installed pack tag still names the bytes that were installed.
///
/// A tag is mutable by design. `PackProvenance.digest` records the artifact
/// that was actually installed, and the tag's manifest names the artifact it
/// points at now; when they differ, someone published different bytes under
/// the same version. That is a different finding from "a newer version
/// exists": it means the version you have may not be what you think it is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PackTagIntegrity {
    /// The tag still points at the installed artifact.
    Matches,
    /// The tag now points at a different artifact.
    Repointed { live_digest: String },
    /// The registry no longer has the tag at all.
    Missing,
    /// The tag could not be resolved (network, auth, or protocol failure).
    Unavailable(String),
}

/// Resolve the installed tag and compare it against the recorded digest.
pub(crate) fn verify_pack_tag(
    pack: &lockfile::PackProvenance,
    registry: &str,
    options: &OciTransferOptions,
) -> PackTagIntegrity {
    let reference = format!("{registry}:{}", pack.version);
    match super::block_on_oci(oci::resolve_pack_tag(&reference, options)) {
        Err(error) => PackTagIntegrity::Unavailable(error.to_string()),
        Ok(None) => PackTagIntegrity::Missing,
        Ok(Some(resolved)) => {
            if resolved.artifact_digest == format!("sha256:{}", pack.digest) {
                PackTagIntegrity::Matches
            } else {
                PackTagIntegrity::Repointed {
                    live_digest: resolved.artifact_digest,
                }
            }
        }
    }
}

/// Render [`compare_pack_versions`] as an `outdated` table row.
fn pick_latest_pack_version(installed: &str, tags: &[String]) -> (String, String, String) {
    let current = installed.to_string();
    match compare_pack_versions(installed, tags) {
        PackVersionStatus::Unknown => (current, UNRESOLVED.to_string(), "not checked".to_string()),
        PackVersionStatus::Newer(latest) => (current, latest, "outdated".to_string()),
        PackVersionStatus::Current => (current.clone(), current, "up to date".to_string()),
    }
}

/// Fold the tag integrity into a version row. Integrity findings win: a
/// repointed or deleted tag is reported even when a newer version exists,
/// because "what you have is not what you installed" changes what the
/// LATEST column means. LATEST is still shown, so the way forward is visible.
fn pack_row(
    installed: &str,
    tags: &[String],
    integrity: &PackTagIntegrity,
) -> (String, String, String) {
    let (current, latest, status) = pick_latest_pack_version(installed, tags);
    let status = match integrity {
        PackTagIntegrity::Matches => status,
        PackTagIntegrity::Repointed { .. } => "repointed".to_string(),
        PackTagIntegrity::Missing => "tag missing".to_string(),
        PackTagIntegrity::Unavailable(_) => "error".to_string(),
    };
    (current, latest, status)
}

/// One registry round trip per pack per run, not per member per harness.
///
/// Every member of a pack shares the same provenance, and `outdated` emits a
/// row per member per target, so without this a four-member pack installed
/// for two harnesses would list the registry's tags eight times.
#[derive(Default)]
pub(crate) struct PackCheckCache {
    rows: std::collections::BTreeMap<String, (String, String, String)>,
}

/// Check a pack-sourced capability against its registry.
///
/// `pack.registry` is only present when the pack was installed with
/// `tuff add pack --reference`; the caller already confirmed that before
/// reaching here.
fn classify_pack(
    pack: &lockfile::PackProvenance,
    registry: &str,
    options: &OciTransferOptions,
    cache: &mut PackCheckCache,
) -> (String, String, String) {
    let key = format!("{registry}:{}@{}", pack.version, pack.digest);
    if let Some(row) = cache.rows.get(&key) {
        return row.clone();
    }
    let row = match super::block_on_oci(oci::list_pack_versions(registry, options)) {
        Err(_) => (
            pack.version.clone(),
            "unavailable".to_string(),
            "error".to_string(),
        ),
        Ok(tags) => {
            let integrity = verify_pack_tag(pack, registry, options);
            pack_row(&pack.version, &tags, &integrity)
        }
    };
    cache.rows.insert(key, row.clone());
    row
}

/// Classify one capability against its upstream.
///
/// A capability with no recorded source and no registry-aware pack — anything
/// installed from a pack without `--reference`, or from a local path —
/// cannot be checked at all. That is reported as `not checked` rather than
/// folded into `up to date`: an honest unknown sends someone to look, a
/// confident "up to date" does not.
fn classify(
    id: &str,
    entry: &lockfile::CapabilityLockEntry,
    oci_options: &OciTransferOptions,
    cache: &mut PackCheckCache,
) -> Verdict {
    let git = match &entry.source {
        lockfile::CapabilitySource::Pack(pack) => {
            return match &pack.registry {
                Some(registry) => classify_pack(pack, registry, oci_options, cache),
                None => (
                    entry.version.clone(),
                    UNRESOLVED.to_string(),
                    "not checked".to_string(),
                ),
            }
            .into();
        }
        lockfile::CapabilitySource::Local(_) => {
            return (
                entry.version.clone(),
                UNRESOLVED.to_string(),
                "not checked".to_string(),
            )
                .into();
        }
        lockfile::CapabilitySource::Catalog(catalog) if catalog.registry.is_some() => {
            let registry = catalog.registry.as_deref().expect("registry checked above");
            let (latest, status) =
                match super::block_on_oci(crate::registry::fetch(registry, &catalog.id)) {
                    Ok(Some(server)) if server.version == entry.version => {
                        (server.version, "up to date")
                    }
                    Ok(Some(server)) => (server.version, "outdated"),
                    // Unpublished, or the registry is unreachable: either way
                    // there is nothing current to compare against, and saying
                    // "up to date" would be a conclusion never reached.
                    Ok(None) => ("unpublished".to_string(), "error"),
                    Err(_) => ("unavailable".to_string(), "error"),
                };
            return (entry.version.clone(), latest, status.to_string()).into();
        }
        lockfile::CapabilitySource::Catalog(catalog) => {
            let (latest, status) = match crate::catalog::lookup(&catalog.id) {
                Ok(Some(manifest)) if manifest.version == entry.version => {
                    (manifest.version, "up to date")
                }
                Ok(Some(manifest)) => (manifest.version, "outdated"),
                // Removed from the catalog, or the catalog itself is broken:
                // either way there is nothing current to compare against.
                _ => ("unavailable".to_string(), "error"),
            };
            return (entry.version.clone(), latest, status.to_string()).into();
        }
        lockfile::CapabilitySource::Git(git) if git.tag.is_some() => {
            return classify_release(id, entry, git);
        }
        lockfile::CapabilitySource::Git(git) => git,
    };
    classify_commit(id, entry, git)
}

/// A git install with no release pin is compared commit to commit: HEAD
/// moved or it did not. One `ls-remote` answers that and, from the same
/// listing, whether the repository publishes releases the entry could be
/// pinned to; the hint that release tags exist lives here rather than on
/// `add`, where it would cost every untagged install a round trip. What
/// the columns show depends on what the version is. A `sha` entry shows
/// short commits and needs no clone. A `declared` entry shows the version
/// the source declared then and declares now, which takes a clone once
/// HEAD has moved, with the claimed size of the change when both parse;
/// when HEAD moved but the declared version did not, the row still reads
/// `outdated`, which is exactly why a declared version is weaker than a
/// release.
fn classify_commit(
    id: &str,
    entry: &lockfile::CapabilityLockEntry,
    git: &lockfile::GitSource,
) -> Verdict {
    let declared = entry.version_scheme == lockfile::VersionScheme::Declared;
    let current = if declared {
        entry.version.clone()
    } else {
        short_sha(&entry.version).to_string()
    };
    let unavailable = |current: String, latest_release: Option<String>| Verdict {
        current,
        latest: "unavailable".to_string(),
        status: "error".to_string(),
        latest_release,
    };
    let refs = match git::list_remote_refs(&git.url) {
        Ok(refs) => refs,
        Err(_) => return unavailable(current, None),
    };
    let releases = release::release_tags(refs.tags.iter().map(|tag| tag.name.as_str()), id);
    let latest_release = release::latest_release(&releases).map(|tag| tag.version.to_string());
    // The listing names HEAD unless the URL's `/tree/` segment is not a
    // branch, in which case the clone is the only way to learn the commit.
    let latest_sha = match refs.head.or_else(|| clone_head(&git.url)) {
        Some(sha) => sha,
        None => return unavailable(current, latest_release),
    };
    if latest_sha == git.git_ref {
        return Verdict {
            latest: current.clone(),
            current,
            status: "up to date".to_string(),
            latest_release,
        };
    }
    if !declared {
        return Verdict {
            current,
            latest: short_sha(&latest_sha).to_string(),
            status: "outdated".to_string(),
            latest_release,
        };
    }
    let latest_declared =
        git::clone_to_temp(&git.url, None)
            .ok()
            .and_then(|(_guard, checkout, _)| {
                git::discover_capability(&checkout, &git.path, entry.capability_type)
                    .ok()
                    .and_then(|dir| crate::manifest::declared_version(&dir))
            });
    let latest = latest_declared.unwrap_or_else(|| short_sha(&latest_sha).to_string());
    let status = match (Version::parse(&entry.version), Version::parse(&latest)) {
        (Ok(from), Ok(to)) if to != from => {
            format!("outdated ({})", release::change_kind(&from, &to))
        }
        _ => "outdated".to_string(),
    };
    Verdict {
        current,
        latest,
        status,
        latest_release,
    }
}

/// The commit a shallow clone of the URL lands on.
fn clone_head(url: &str) -> Option<String> {
    let (_guard, checkout, _) = git::clone_to_temp(url, None).ok()?;
    git::resolve_ref(&checkout).ok()
}

/// A tag-pinned install (RFC-101) is compared against the newest release
/// tag, whatever the recorded requirement allows: `outdated` answers "is
/// there something newer", and `update` decides whether the requirement
/// lets you have it. One `ls-remote` per row, no clone.
fn classify_release(
    id: &str,
    entry: &lockfile::CapabilityLockEntry,
    git: &lockfile::GitSource,
) -> Verdict {
    let current = entry.version.clone();
    let tags = match git::list_remote_tags(&git.url) {
        Ok(tags) => tags,
        Err(_) => return (current, "unavailable".to_string(), "error".to_string()).into(),
    };
    let releases = release::release_tags(tags.iter().map(|tag| tag.name.as_str()), id);
    let latest = release::latest_release(&releases).map(|latest| latest.version.to_string());
    let verdict = |current: String, latest: String, status: &str| Verdict {
        current,
        latest_release: (latest != UNRESOLVED).then(|| latest.clone()),
        latest,
        status: status.to_string(),
    };
    // The tag is mutable; the commit is what was installed. A tag that
    // moved, or is gone, changes what LATEST means and wins over the
    // version verdict, while LATEST still shows the way forward.
    let integrity = git
        .tag
        .as_deref()
        .map(|tag| release::tag_integrity(tag, &git.git_ref, &tags));
    match integrity {
        Some(release::TagIntegrity::Repointed { .. }) => {
            return verdict(
                current,
                latest.unwrap_or_else(|| UNRESOLVED.to_string()),
                "repointed",
            );
        }
        Some(release::TagIntegrity::Missing) => {
            return verdict(
                current,
                latest.unwrap_or_else(|| UNRESOLVED.to_string()),
                "tag missing",
            );
        }
        Some(release::TagIntegrity::Matches) | None => {}
    }
    let Some(latest) = release::latest_release(&releases) else {
        return verdict(current, UNRESOLVED.to_string(), "tag missing");
    };
    match Version::parse(&entry.version) {
        Ok(installed) if latest.version > installed => verdict(
            current,
            latest.version.to_string(),
            &format!(
                "outdated ({})",
                release::change_kind(&installed, &latest.version)
            ),
        ),
        Ok(_) => verdict(current, latest.version.to_string(), "up to date"),
        Err(_) => verdict(current, latest.version.to_string(), "not checked"),
    }
}

/// Take the change kind out of an `outdated (minor)` status so the status
/// column and the JSON `status` stay one of the documented words.
fn split_change(status: String) -> (String, Option<String>) {
    match status
        .strip_prefix("outdated (")
        .and_then(|rest| rest.strip_suffix(')'))
    {
        Some(kind) => ("outdated".to_string(), Some(kind.to_string())),
        None => (status, None),
    }
}

fn collect_rows(
    lf: &lockfile::Lockfile,
    oci_options: &OciTransferOptions,
    cache: &mut PackCheckCache,
    rows: &mut Vec<OutdatedRow>,
) {
    for (id, entry) in &lf.capabilities {
        // One upstream check per capability; the rows differ only by target.
        let verdict = classify(id, entry, oci_options, cache);
        let (status, change) = split_change(verdict.status);
        for target_id in entry.targets.keys() {
            rows.push(OutdatedRow {
                id: id.clone(),
                capability_type: entry.capability_type,
                target: target_id.clone(),
                version_scheme: entry.version_scheme,
                from_git: matches!(entry.source, lockfile::CapabilitySource::Git(_)),
                current: verdict.current.clone(),
                latest: verdict.latest.clone(),
                status: status.clone(),
                change: change.clone(),
                latest_release: verdict.latest_release.clone(),
            });
        }
    }
}

/// The note under the table for an untagged git install whose repository
/// publishes releases: the entry follows a commit when it could follow a
/// version. One line per capability, however many targets it has, and
/// only when the check itself succeeded.
fn release_hints(rows: &[OutdatedRow]) -> Vec<String> {
    let mut seen = std::collections::BTreeSet::new();
    rows.iter()
        .filter(|row| row.from_git && row.status != "error")
        .filter(|row| row.version_scheme != lockfile::VersionScheme::Semver)
        .filter_map(|row| {
            let release = row.latest_release.as_deref()?;
            seen.insert(row.id.clone()).then(|| {
                let requirement = match Version::parse(release) {
                    Ok(version) => format!("^{}.{}", version.major, version.minor),
                    Err(_) => release.to_string(),
                };
                format!(
                    "note: {} follows a commit, but its repository publishes releases (newest {release}); 'tuff update {}@{requirement}' pins one",
                    row.id, row.id
                )
            })
        })
        .collect()
}

pub fn cmd_outdated(
    repo_root: &Path,
    plain_http: bool,
    ca_files: &[std::path::PathBuf],
    json: bool,
) -> Result<()> {
    let oci_options = OciTransferOptions {
        plain_http,
        ca_files: ca_files.to_vec(),
    };
    let mut rows: Vec<OutdatedRow> = Vec::new();
    let mut cache = PackCheckCache::default();

    if let Some(lf) = lockfile::read_optional_lockfile(&lockfile::project_lockfile(repo_root))? {
        collect_rows(&lf, &oci_options, &mut cache, &mut rows);
    }

    if let Some(home) = home_dir_opt() {
        let lock_path = crate::paths::global_lockfile(&home);
        if let Some(lf) = lockfile::read_optional_lockfile(&lock_path)? {
            collect_rows(&lf, &oci_options, &mut cache, &mut rows);
        }
    }

    if rows.is_empty() {
        if json {
            println!("[]");
        } else {
            println!("no capabilities installed");
        }
        return Ok(());
    }

    rows.sort_by(|a, b| a.id.cmp(&b.id));

    let hints = release_hints(&rows);
    if json {
        let rows: Vec<JsonOutdatedRow<'_>> = rows.iter().map(OutdatedRow::as_json).collect();
        println!("{}", serde_json::to_string_pretty(&rows)?);
        for hint in hints {
            eprintln!("{hint}");
        }
        return Ok(());
    }

    let table_rows: Vec<Vec<String>> = rows
        .into_iter()
        .map(|r| {
            let status = match &r.change {
                Some(change) => format!("{} ({change})", style_outdated_status(&r.status)),
                None => style_outdated_status(&r.status),
            };
            let current = if r.from_git && r.version_scheme == lockfile::VersionScheme::Declared {
                format!("{} (declared)", r.current)
            } else {
                r.current.clone()
            };
            let row = OutdatedRow {
                status,
                current,
                ..r
            };
            vec![
                row.id,
                row.capability_type.to_string(),
                row.target,
                row.current,
                row.latest,
                row.status,
            ]
        })
        .collect();

    println!(
        "{}",
        render_table(
            &["ID", "TYPE", "AGENT", "CURRENT", "LATEST", "STATUS"],
            &table_rows
        )
    );
    for hint in hints {
        eprintln!("{hint}");
    }
    Ok(())
}

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

    fn entry(source: lockfile::CapabilitySource) -> lockfile::CapabilityLockEntry {
        lockfile::CapabilityLockEntry {
            capability_type: CapabilityType::Skill,
            version: "1.0.0".to_string(),
            version_scheme: lockfile::VersionScheme::Declared,
            description: String::new(),
            source,
            targets: BTreeMap::new(),
            implementation: None,
            parameters: None,
            workflow: None,
            server: None,
        }
    }

    #[test]
    fn a_capability_with_no_source_is_reported_as_unchecked() {
        // Anything installed from a pack without --reference, or from a
        // local path, has no git source and no registry to check. Reporting
        // "up to date" here states a conclusion that was never reached: the
        // row would claim the capability is current while LATEST is unknown.
        let Verdict {
            current,
            latest,
            status,
            latest_release,
        } = classify(
            "example",
            &entry(lockfile::CapabilitySource::local(
                "agent-capabilities/example",
            )),
            &OciTransferOptions::default(),
            &mut PackCheckCache::default(),
        );

        assert_eq!(latest_release, None);
        assert_eq!(status, "not checked");
        assert_ne!(
            status, "up to date",
            "an unchecked capability must not read as current"
        );
        assert_eq!(latest, "—");
        assert_eq!(current, "1.0.0");
    }

    fn row(
        id: &str,
        scheme: lockfile::VersionScheme,
        status: &str,
        release: Option<&str>,
    ) -> OutdatedRow {
        OutdatedRow {
            id: id.to_string(),
            capability_type: CapabilityType::Skill,
            target: "open-agents".to_string(),
            version_scheme: scheme,
            from_git: true,
            current: "abc1234".to_string(),
            latest: "def5678".to_string(),
            status: status.to_string(),
            change: None,
            latest_release: release.map(str::to_string),
        }
    }

    #[test]
    fn the_release_note_names_untagged_git_installs_once_each() {
        // The hint that release tags exist lives on `outdated`, where the
        // listing already happened, not on `add`. It is one line per
        // capability however many targets it has, it suggests the caret
        // range for the newest release, and it stays quiet for an entry
        // already on a release, for one whose check failed, and for a
        // repository with no releases.
        let mut two_targets = row(
            "commit-skill",
            lockfile::VersionScheme::Sha,
            "outdated",
            Some("1.4.0"),
        );
        two_targets.target = "claude".to_string();
        let rows = vec![
            row(
                "commit-skill",
                lockfile::VersionScheme::Sha,
                "outdated",
                Some("1.4.0"),
            ),
            two_targets,
            row(
                "declared-skill",
                lockfile::VersionScheme::Declared,
                "up to date",
                Some("0.3.1"),
            ),
            row(
                "pinned-skill",
                lockfile::VersionScheme::Semver,
                "outdated",
                Some("2.0.0"),
            ),
            row(
                "failed-skill",
                lockfile::VersionScheme::Sha,
                "error",
                Some("1.0.0"),
            ),
            row(
                "untagged-skill",
                lockfile::VersionScheme::Sha,
                "outdated",
                None,
            ),
        ];

        let hints = release_hints(&rows);

        assert_eq!(
            hints,
            vec![
                "note: commit-skill follows a commit, but its repository publishes releases (newest 1.4.0); 'tuff update commit-skill@^1.4' pins one",
                "note: declared-skill follows a commit, but its repository publishes releases (newest 0.3.1); 'tuff update declared-skill@^0.3' pins one",
            ]
        );
    }

    #[test]
    fn a_newer_semver_tag_is_reported_as_outdated() {
        let tags = vec![
            "1.0.0".to_string(),
            "1.2.0".to_string(),
            "0.9.0".to_string(),
        ];
        let (current, latest, status) = pick_latest_pack_version("1.0.0", &tags);

        assert_eq!(status, "outdated");
        assert_eq!(current, "1.0.0");
        assert_eq!(latest, "1.2.0");
    }

    #[test]
    fn the_installed_tag_being_the_newest_reads_as_up_to_date() {
        let tags = vec!["1.0.0".to_string(), "0.9.0".to_string()];
        let (_, _, status) = pick_latest_pack_version("1.0.0", &tags);

        assert_eq!(status, "up to date");
    }

    #[test]
    fn version_ordering_is_semantic_not_lexicographic() {
        // Plain string comparison puts "1.9.0" after "1.10.0", because '9' >
        // '1' as the first differing character. That is the wrong answer,
        // and exactly the shape of bug this function exists to avoid.
        let tags = vec!["1.10.0".to_string()];
        let (_, latest, status) = pick_latest_pack_version("1.9.0", &tags);

        assert_eq!(status, "outdated");
        assert_eq!(latest, "1.10.0");
    }

    #[test]
    fn tags_that_do_not_parse_as_semver_are_excluded_not_guessed_at() {
        let tags = vec!["latest".to_string(), "nightly".to_string()];
        let (_, latest, status) = pick_latest_pack_version("1.0.0", &tags);

        assert_eq!(status, "not checked");
        assert_eq!(latest, "—");
    }

    #[test]
    fn an_unparsable_installed_version_is_reported_as_unchecked() {
        // tuff pack build --version does not enforce a version scheme, so
        // this is a real case: the pack itself may not be semver-tagged.
        let tags = vec!["1.0.0".to_string()];
        let (current, latest, status) = pick_latest_pack_version("release-42", &tags);

        assert_eq!(status, "not checked");
        assert_eq!(latest, "—");
        assert_eq!(current, "release-42");
    }

    #[test]
    fn a_repointed_tag_is_reported_even_when_a_newer_version_exists() {
        // "A newer version exists" and "the version you have is not what
        // you installed" are different findings; the second must not hide
        // behind the first. LATEST still shows the way forward.
        let tags = vec!["1.0.0".to_string(), "1.2.0".to_string()];
        let integrity = PackTagIntegrity::Repointed {
            live_digest: "sha256:beef".to_string(),
        };
        let (current, latest, status) = pack_row("1.0.0", &tags, &integrity);

        assert_eq!(status, "repointed");
        assert_eq!(current, "1.0.0");
        assert_eq!(latest, "1.2.0");
    }

    #[test]
    fn a_repointed_tag_never_reads_as_up_to_date() {
        let tags = vec!["1.0.0".to_string()];
        let integrity = PackTagIntegrity::Repointed {
            live_digest: "sha256:beef".to_string(),
        };
        let (_, _, status) = pack_row("1.0.0", &tags, &integrity);

        assert_eq!(status, "repointed");
    }

    #[test]
    fn a_deleted_tag_is_its_own_status() {
        let tags = vec!["1.2.0".to_string()];
        let (_, latest, status) = pack_row("1.0.0", &tags, &PackTagIntegrity::Missing);

        assert_eq!(status, "tag missing");
        assert_eq!(latest, "1.2.0");
    }

    #[test]
    fn a_matching_tag_leaves_the_version_verdict_alone() {
        let tags = vec!["1.0.0".to_string(), "1.2.0".to_string()];
        let (_, _, status) = pack_row("1.0.0", &tags, &PackTagIntegrity::Matches);
        assert_eq!(status, "outdated");

        let tags = vec!["1.0.0".to_string()];
        let (_, _, status) = pack_row("1.0.0", &tags, &PackTagIntegrity::Matches);
        assert_eq!(status, "up to date");
    }
}