astrid 0.10.1

Command-line interface for Astrid secure agent runtime
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
//! Distro manifest validation.
//!
//! Validates structural constraints that TOML deserialization alone cannot
//! enforce: schema version, identifier formats, semver, variable references,
//! role presence, and duplicate names.

use std::collections::HashSet;

use semver::{Version, VersionReq};

use super::manifest::{DistroManifest, SCHEMA_VERSION};

/// The running CLI version, taken from the astrid-cli binary crate
/// (`CARGO_PKG_VERSION`) — the same source `astrid version` prints.
pub(crate) const RUNNING_ASTRID_VERSION: &str = env!("CARGO_PKG_VERSION");

/// The running CLI is older than a distro's `[distro].astrid-version` floor.
///
/// Carried as a *typed* (downcastable) error rather than a bare string so callers
/// can distinguish "your CLI is too old, upgrade" from every other validation
/// failure without fragile message matching. The `Display` text is the
/// actionable upgrade message surfaced to users on the `astrid init` /
/// `astrid distro apply` paths; the post-update sync path
/// (`self_update::sync_distro_and_capsules`) downcasts to this type and
/// substitutes a benign "it takes effect on next run" message instead, because
/// there the new binary is already on disk — only the in-flight process is stale.
#[derive(Debug, thiserror::Error)]
#[error(
    "This distro requires astrid {req}, but you are running {running}. \
     Run `astrid update` to upgrade."
)]
pub(crate) struct AstridVersionTooOld {
    /// The distro's `[distro].astrid-version` requirement string (e.g. `>=0.6.0`).
    pub req: String,
    /// The running CLI version that failed to satisfy `req`.
    pub running: String,
}

/// Check if a string is a valid identifier: `^[a-z][a-z0-9-]*$`.
fn is_valid_id(s: &str) -> bool {
    let mut chars = s.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    first.is_ascii_lowercase()
        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

/// Extract `{{ var_name }}` references from a template string.
fn extract_variable_refs(template: &str) -> Vec<&str> {
    template
        .split("{{")
        .skip(1)
        .filter_map(|s| s.split_once("}}"))
        .map(|(var, _)| var.trim())
        .filter(|var| !var.is_empty())
        .collect()
}

/// Validate a parsed distro manifest.
///
/// Checks that cannot be expressed in serde alone:
/// - Schema version is supported
/// - Distro ID format
/// - Distro version is valid semver
/// - astrid-version (if set) is valid semver requirement
/// - No duplicate capsule names
/// - At least one capsule
/// - At least one capsule with role = "uplink"
/// - Variable references in capsule env resolve to defined variables
/// - Requires version strings are valid semver requirements
#[allow(
    clippy::too_many_lines,
    reason = "flat sequence of independent validation checks; \
              inlining keeps the full ruleset auditable in one place"
)]
pub(crate) fn validate_manifest(manifest: &DistroManifest) -> anyhow::Result<()> {
    // Schema version.
    if manifest.schema_version != SCHEMA_VERSION {
        anyhow::bail!(
            "unsupported schema-version {} (expected {SCHEMA_VERSION})",
            manifest.schema_version,
        );
    }

    // Distro ID format.
    if !is_valid_id(&manifest.distro.id) {
        anyhow::bail!(
            "distro.id '{}' is invalid (must match ^[a-z][a-z0-9-]*$)",
            manifest.distro.id,
        );
    }

    // Distro version is valid semver.
    if semver::Version::parse(&manifest.distro.version).is_err() {
        anyhow::bail!(
            "distro.version '{}' is not valid semver",
            manifest.distro.version,
        );
    }

    // astrid-version is valid semver requirement (if set).
    if let Some(ref av) = manifest.distro.astrid_version
        && semver::VersionReq::parse(av).is_err()
    {
        anyhow::bail!("distro.astrid-version '{av}' is not a valid semver requirement");
    }

    // Requires version strings are valid semver requirements.
    for (ns, ifaces) in &manifest.distro.requires {
        for (name, req) in ifaces {
            if semver::VersionReq::parse(req).is_err() {
                anyhow::bail!(
                    "distro.requires.{ns}.{name} '{req}' is not a valid semver requirement",
                );
            }
        }
    }

    // At least one capsule.
    if manifest.capsules.is_empty() {
        anyhow::bail!("distro must contain at least one capsule");
    }

    // No duplicate capsule names, and each name must be a valid
    // identifier. Names become path components in the `.shuttle` layout
    // (`capsules/<name>.capsule`) and on disk under the capsule store;
    // constraining them to `^[a-z][a-z0-9-]*$` keeps a manifest from
    // introducing `/`, `..`, or other path-hostile characters there.
    let mut seen_names = HashSet::new();
    for cap in &manifest.capsules {
        if !is_valid_id(&cap.name) {
            anyhow::bail!(
                "capsule name '{}' is invalid (must match ^[a-z][a-z0-9-]*$)",
                cap.name,
            );
        }
        if !seen_names.insert(&cap.name) {
            anyhow::bail!("duplicate capsule name '{}'", cap.name);
        }
        // Distros compose *released* capsules. `branch`/`rev` selectors
        // can only be honored by compiling from a git ref — the exact
        // toolchain dependency offline/headless distro seeding exists to
        // remove. Reject them: a distro must pin a released `version` or
        // `tag`. (Git-ref installs remain available via the standalone
        // `astrid capsule install` command.)
        if cap.branch.is_some() || cap.rev.is_some() {
            anyhow::bail!(
                "capsule '{}': branch/rev require building from source and are not allowed in a \
                 distro manifest — pin a released `version` or `tag` (git-ref installs are \
                 available via `astrid capsule install`).",
                cap.name,
            );
        }
        let version = cap.version.trim();
        if cap.version != version {
            anyhow::bail!(
                "capsule '{}': version must not contain surrounding whitespace",
                cap.name
            );
        }
        if !version.is_empty() && Version::parse(version).is_err() {
            anyhow::bail!(
                "capsule '{}': version '{}' is not valid semver",
                cap.name,
                cap.version
            );
        }
        let tag = cap.tag.as_deref().map(str::trim);
        if let Some(raw_tag) = cap.tag.as_deref()
            && raw_tag != raw_tag.trim()
        {
            anyhow::bail!(
                "capsule '{}': tag must not contain surrounding whitespace",
                cap.name
            );
        }
        if matches!(tag, Some("")) {
            anyhow::bail!("capsule '{}': tag must not be empty", cap.name);
        }
        if version.is_empty() && tag.is_none() {
            anyhow::bail!(
                "capsule '{}': distro capsules require a concrete released version or tag",
                cap.name
            );
        }
    }

    // At least one uplink.
    let has_uplink = manifest
        .capsules
        .iter()
        .any(|c| c.role.as_deref() == Some("uplink"));
    if !has_uplink {
        anyhow::bail!("distro must have at least one capsule with role = \"uplink\" (a frontend)");
    }

    // Variable references in capsule env.
    let defined_vars: HashSet<&str> = manifest.variables.keys().map(String::as_str).collect();
    for cap in &manifest.capsules {
        for (key, value) in &cap.env {
            for var_ref in extract_variable_refs(value) {
                if !defined_vars.contains(var_ref) {
                    anyhow::bail!(
                        "capsule '{}' env.{key} references undefined variable '{{{{ {var_ref} }}}}'",
                        cap.name,
                    );
                }
            }
        }
    }

    // Invite policy — additive, so the rule is "if any field is set,
    // the shape must be coherent". The kernel still cap-gates issuance
    // at runtime; this is fail-fast for typos.
    if let Some(invites) = &manifest.invites {
        if !invites.issuers.is_empty() && invites.default_group.is_none() {
            anyhow::bail!(
                "invites.issuers is non-empty but invites.default-group is unset — \
                 either configure both or remove the [invites] section"
            );
        }
        if let Some(exp) = &invites.default_expires {
            parse_invite_duration(exp).map_err(|e| anyhow::anyhow!(e))?;
        }
        if let Some(cap) = &invites.max_principals
            && cap != "unlimited"
            && cap.parse::<u32>().is_err()
        {
            anyhow::bail!(
                "invites.max-principals must be \"unlimited\" or a non-negative integer (got {cap:?})",
            );
        }
    }

    // Branding — only structural rails. The dashboard interprets the
    // values; the parser just refuses obvious garbage.
    if let Some(branding) = &manifest.branding {
        if let Some(icon) = &branding.icon
            && icon.len() > 64 * 1024
        {
            anyhow::bail!(
                "branding.icon is {} bytes — distros must not embed assets larger than 64 KiB",
                icon.len()
            );
        }
        if let Some(color) = &branding.primary_color {
            validate_hex_color(color)
                .map_err(|e| anyhow::anyhow!("branding.primary-color: {e}"))?;
        }
        if let Some(color) = &branding.accent_color {
            validate_hex_color(color).map_err(|e| anyhow::anyhow!("branding.accent-color: {e}"))?;
        }
    }

    Ok(())
}

/// Enforce a manifest's `[distro].astrid-version` floor against the running CLI.
///
/// Called on the init / `distro apply` path *after* the manifest is fetched and
/// parsed but *before* any prompting or install, so a distro whose `Distro.toml`
/// (fetched from the repo `main` tip) bumps its CLI floor fails fast with an
/// actionable message instead of breaking onboarding mid-flight on an older CLI.
///
/// A manifest with no `astrid-version` floor imposes no requirement.
pub(crate) fn enforce_astrid_version(manifest: &DistroManifest) -> anyhow::Result<()> {
    let Some(req) = manifest.distro.astrid_version.as_deref() else {
        return Ok(());
    };
    let running = Version::parse(RUNNING_ASTRID_VERSION).map_err(|e| {
        // The binary's own version should always be valid semver; if it isn't,
        // that's a build-time defect, not a distro problem.
        anyhow::anyhow!(
            "running astrid version {RUNNING_ASTRID_VERSION:?} is not valid semver: {e}"
        )
    })?;
    distro_astrid_version_satisfied(req, &running)
}

/// Decide whether the running CLI `running` satisfies a distro's
/// `[distro].astrid-version` requirement `req`.
///
/// Pure (no fetch, no env) so it is unit-testable in isolation.
///
/// **Prerelease policy.** By default `semver::VersionReq::matches` refuses a
/// prerelease running version (e.g. `0.6.0-dev.3` does *not* satisfy `>=0.6.0`),
/// which would falsely reject a locally-built / dev CLI that is, by release
/// triple, at or above the floor. That is the classic semver footgun. When the
/// requirement is a plain release floor we compare on the **release triple
/// only** — the running version's `(major, minor, patch)` with the prerelease
/// and build metadata stripped — so a dev build of a sufficiently-new astrid is
/// accepted, while still rejecting a CLI whose release triple genuinely falls
/// below the floor. A clean (non-prerelease) running version compares unchanged.
///
/// **When the requirement itself names a prerelease** (e.g. `>=0.6.0-rc.3`) the
/// operator is deliberately gating on a specific prerelease, so triple-stripping
/// the running version would *over-accept*: `0.6.0-rc.2` would be lifted to
/// `0.6.0` and wrongly satisfy `>=0.6.0-rc.3`. In that case we drop the
/// dev-build convenience and compare the running version **as-is** under exact
/// semver semantics, so prerelease ordering (`rc.2 < rc.3`) is honoured.
pub(crate) fn distro_astrid_version_satisfied(req: &str, running: &Version) -> anyhow::Result<()> {
    let version_req = VersionReq::parse(req).map_err(|e| {
        anyhow::anyhow!("distro.astrid-version {req:?} is not a valid requirement: {e}")
    })?;

    // If any comparator in the requirement carries a prerelease, the operator
    // is gating on an exact prerelease — honour real semver semantics (no
    // triple-strip) so a lower prerelease of the same triple is not lifted past
    // the floor. Otherwise apply the dev-build footgun fix below.
    let req_names_prerelease = version_req.comparators.iter().any(|c| !c.pre.is_empty());
    if req_names_prerelease {
        if version_req.matches(running) {
            return Ok(());
        }
        return Err(AstridVersionTooOld {
            req: req.to_string(),
            running: running.to_string(),
        }
        .into());
    }

    // Plain release floor: strip prerelease / build metadata and compare on the
    // release triple so a dev / prerelease CLI at or above the floor is not
    // falsely rejected.
    let release_triple = Version::new(running.major, running.minor, running.patch);

    if version_req.matches(&release_triple) {
        return Ok(());
    }

    // Typed (downcastable) so the post-update sync path can recognise this exact
    // condition and swap in a benign message; init / distro apply propagate it to
    // the top-level handler, where its `Display` is the actionable upgrade text.
    Err(AstridVersionTooOld {
        req: req.to_string(),
        running: running.to_string(),
    }
    .into())
}

/// Parse the operator-friendly duration form (`24h`, `7d`, `30m`, `30s`)
/// into seconds. The kernel caps at 30 days regardless.
pub(crate) fn parse_invite_duration(input: &str) -> Result<u64, String> {
    let trimmed = input.trim();
    let (num_str, multiplier_secs) = if let Some(s) = trimmed.strip_suffix('s') {
        (s, 1_u64)
    } else if let Some(s) = trimmed.strip_suffix('m') {
        (s, 60)
    } else if let Some(s) = trimmed.strip_suffix('h') {
        (s, 3_600)
    } else if let Some(s) = trimmed.strip_suffix('d') {
        (s, 86_400)
    } else {
        return Err(format!(
            "invalid duration {input:?} — must end with s/m/h/d (e.g. 24h, 7d, 30m, 30s)"
        ));
    };
    let n: u64 = num_str
        .parse()
        .map_err(|e| format!("invalid duration number in {input:?}: {e}"))?;
    n.checked_mul(multiplier_secs)
        .ok_or_else(|| format!("duration {input:?} overflows u64 seconds"))
}

/// Validate `#RRGGBB` or `#RGB` style hex colours.
fn validate_hex_color(input: &str) -> Result<(), String> {
    let Some(rest) = input.strip_prefix('#') else {
        return Err(format!("expected leading '#'; got {input:?}"));
    };
    if !matches!(rest.len(), 3 | 6) {
        return Err(format!("{input:?} must be 3 or 6 hex digits after '#'"));
    }
    if !rest.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(format!("{input:?} contains non-hex characters"));
    }
    Ok(())
}

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

    #[test]
    fn is_valid_id_accepts_lowercase() {
        assert!(is_valid_id("example-distro"));
        assert!(is_valid_id("my-distro"));
        assert!(is_valid_id("a1b2c3"));
    }

    #[test]
    fn is_valid_id_rejects_invalid() {
        assert!(!is_valid_id(""));
        assert!(!is_valid_id("UPPER"));
        assert!(!is_valid_id("1starts-with-digit"));
        assert!(!is_valid_id("has space"));
        assert!(!is_valid_id("under_score"));
    }

    #[test]
    fn extract_refs_finds_variables() {
        assert_eq!(extract_variable_refs("{{ foo }}"), vec!["foo"]);
        assert_eq!(
            extract_variable_refs("prefix-{{ bar }}-{{ baz }}-suffix"),
            vec!["bar", "baz"]
        );
        assert_eq!(extract_variable_refs("no refs here"), Vec::<&str>::new());
        assert_eq!(extract_variable_refs("{{}}"), Vec::<&str>::new());
    }

    #[test]
    fn extract_refs_handles_whitespace() {
        assert_eq!(extract_variable_refs("{{  spaced  }}"), vec!["spaced"]);
        assert_eq!(extract_variable_refs("{{no_space}}"), vec!["no_space"]);
    }

    #[test]
    fn parse_invite_duration_accepts_units() {
        assert_eq!(parse_invite_duration("30s"), Ok(30));
        assert_eq!(parse_invite_duration("5m"), Ok(300));
        assert_eq!(parse_invite_duration("24h"), Ok(86_400));
        assert_eq!(parse_invite_duration("7d"), Ok(604_800));
        assert_eq!(parse_invite_duration(" 12h "), Ok(43_200));
    }

    #[test]
    fn parse_invite_duration_rejects_garbage() {
        assert!(parse_invite_duration("").is_err());
        assert!(parse_invite_duration("24").is_err());
        assert!(parse_invite_duration("ten h").is_err());
        assert!(parse_invite_duration("forever").is_err());
    }

    #[test]
    fn hex_color_accepts_standard_forms() {
        assert!(validate_hex_color("#abc").is_ok());
        assert!(validate_hex_color("#ABCDEF").is_ok());
        assert!(validate_hex_color("#123456").is_ok());
    }

    #[test]
    fn hex_color_rejects_garbage() {
        assert!(validate_hex_color("abc").is_err());
        assert!(validate_hex_color("#abcd").is_err());
        assert!(validate_hex_color("#xyz").is_err());
        assert!(validate_hex_color("rgb(1,2,3)").is_err());
    }

    #[test]
    fn invites_block_validates_coherence() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "tenancy-demo"
name = "Tenancy"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@example-org/capsule-cli"
version = "0.7.0"
role = "uplink"

[invites]
issuers = ["admin"]
"#;
        let manifest: DistroManifest =
            toml::from_str(toml_src).expect("manifest should parse syntactically");
        let err = validate_manifest(&manifest).expect_err("missing default-group must reject");
        assert!(
            err.to_string().contains("default-group is unset"),
            "got: {err}"
        );
    }

    #[test]
    fn rejects_path_hostile_capsule_name() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "evil/../escape"
source = "@org/cli"
version = "0.1.0"
role = "uplink"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        let err = validate_manifest(&manifest).expect_err("slash name must be rejected");
        assert!(err.to_string().contains("capsule name"), "got: {err}");
    }

    #[test]
    fn rejects_branch_selector_in_distro() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@org/cli"
version = "0.1.0"
branch = "main"
role = "uplink"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        let err = validate_manifest(&manifest).expect_err("branch must be rejected");
        let msg = err.to_string();
        assert!(msg.contains("branch/rev"), "got: {msg}");
        assert!(msg.contains("astrid-capsule-cli"), "got: {msg}");
    }

    #[test]
    fn rejects_rev_selector_in_distro() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@org/cli"
version = "0.1.0"
rev = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
role = "uplink"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        let err = validate_manifest(&manifest).expect_err("rev must be rejected");
        assert!(err.to_string().contains("branch/rev"), "got: {err}");
    }

    #[test]
    fn accepts_version_and_tag_release_selectors() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@org/cli"
version = "0.1.0"
role = "uplink"

[[capsule]]
name = "astrid-capsule-a"
source = "@org/a"
version = "0.2.0"
tag = "v0.2.0-rc1"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        validate_manifest(&manifest).expect("version/tag release selectors are allowed");
    }

    #[test]
    fn accepts_tag_only_release_selector() {
        let toml_src = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@org/cli"
version = ""
tag = "v0.2.0-rc1"
role = "uplink"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        validate_manifest(&manifest).expect("a non-empty tag is a concrete release selector");
    }

    #[test]
    fn rejects_missing_or_malformed_release_selector() {
        let base = r#"
schema-version = 1

[distro]
id = "test"
name = "Test"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@org/cli"
role = "uplink"
"#;
        for (selector, needle) in [
            ("version = \"\"", "concrete released version or tag"),
            ("version = \"latest\"", "not valid semver"),
            ("version = \"\"\ntag = \"\"", "tag must not be empty"),
        ] {
            let manifest: DistroManifest = toml::from_str(&format!("{base}{selector}\n")).unwrap();
            let err = validate_manifest(&manifest).unwrap_err();
            assert!(err.to_string().contains(needle), "got: {err:#}");
        }
    }

    #[test]
    fn astrid_version_rejects_running_below_floor() {
        // Running CLI is older than the distro's floor — must reject with the
        // actionable upgrade message.
        let running = Version::parse("0.5.0").unwrap();
        let err = distro_astrid_version_satisfied(">=0.6.0", &running)
            .expect_err("0.5.0 must not satisfy >=0.6.0");

        // It must be the TYPED error, downcastable with the right req/running so
        // the post-update sync path can recognise it without string matching.
        let typed = err
            .downcast_ref::<AstridVersionTooOld>()
            .expect("below-floor rejection must be a typed AstridVersionTooOld error");
        assert_eq!(typed.req, ">=0.6.0");
        assert_eq!(typed.running, "0.5.0");

        // And its Display must remain the actionable upgrade message so the
        // init / distro-apply UX is unchanged for users.
        let msg = err.to_string();
        assert!(
            msg.contains("This distro requires astrid >=0.6.0")
                && msg.contains("you are running 0.5.0")
                && msg.contains("astrid update"),
            "expected actionable upgrade message, got: {msg}"
        );
    }

    #[test]
    fn astrid_version_accepts_running_at_or_above_floor() {
        // Exactly at the floor.
        let at = Version::parse("0.6.0").unwrap();
        distro_astrid_version_satisfied(">=0.6.0", &at).expect("0.6.0 satisfies >=0.6.0");

        // Above the floor (same minor and a newer minor).
        let above_patch = Version::parse("0.6.3").unwrap();
        distro_astrid_version_satisfied(">=0.6.0", &above_patch).expect("0.6.3 satisfies >=0.6.0");
        let above_minor = Version::parse("0.7.0").unwrap();
        distro_astrid_version_satisfied(">=0.6.0", &above_minor).expect("0.7.0 satisfies >=0.6.0");
    }

    #[test]
    fn astrid_version_accepts_prerelease_at_or_above_floor() {
        // The footgun: a locally-built / dev CLI whose release triple is at or
        // above the floor must be ACCEPTED, even though raw `VersionReq::matches`
        // refuses a prerelease against `>=0.6.0`. We compare on the release triple.
        let dev_at_floor = Version::parse("0.6.0-dev.3").unwrap();
        // Sanity: prove the naive comparison would have falsely rejected it.
        assert!(
            !VersionReq::parse(">=0.6.0").unwrap().matches(&dev_at_floor),
            "guard: naive matches must reject the prerelease, else the test proves nothing"
        );
        distro_astrid_version_satisfied(">=0.6.0", &dev_at_floor)
            .expect("0.6.0-dev.3 (release triple 0.6.0) satisfies >=0.6.0");

        // A dev build of a newer release is likewise accepted.
        let dev_above = Version::parse("0.7.0-rc.1").unwrap();
        distro_astrid_version_satisfied(">=0.6.0", &dev_above)
            .expect("0.7.0-rc.1 (release triple 0.7.0) satisfies >=0.6.0");
    }

    #[test]
    fn astrid_version_rejects_prerelease_below_floor() {
        // The triple-strip must not over-accept: a prerelease whose release
        // triple is genuinely below the floor still fails.
        let dev_below = Version::parse("0.5.0-dev.9").unwrap();
        distro_astrid_version_satisfied(">=0.6.0", &dev_below)
            .expect_err("0.5.0-dev.9 (release triple 0.5.0) must not satisfy >=0.6.0");
    }

    #[test]
    fn prerelease_requirement_compares_running_exactly_no_triple_strip() {
        // FIX E: when the REQUIREMENT itself names a prerelease, the running
        // version's prerelease must NOT be stripped to its release triple —
        // otherwise a lower prerelease of the same triple is wrongly lifted
        // past the floor.

        // The bug: `0.6.0-rc.2` is BELOW `>=0.6.0-rc.3`. Triple-stripping it to
        // `0.6.0` would have wrongly satisfied the floor. It must be rejected.
        let rc2 = Version::parse("0.6.0-rc.2").unwrap();
        let err = distro_astrid_version_satisfied(">=0.6.0-rc.3", &rc2)
            .expect_err("0.6.0-rc.2 must NOT satisfy >=0.6.0-rc.3");
        let typed = err
            .downcast_ref::<AstridVersionTooOld>()
            .expect("below-floor prerelease rejection must be a typed error");
        assert_eq!(typed.req, ">=0.6.0-rc.3");
        assert_eq!(typed.running, "0.6.0-rc.2");

        // Exactly at the prerelease floor is accepted.
        let rc3 = Version::parse("0.6.0-rc.3").unwrap();
        distro_astrid_version_satisfied(">=0.6.0-rc.3", &rc3)
            .expect("0.6.0-rc.3 satisfies >=0.6.0-rc.3");

        // A later prerelease of the same triple is accepted (rc.4 > rc.3).
        let rc4 = Version::parse("0.6.0-rc.4").unwrap();
        distro_astrid_version_satisfied(">=0.6.0-rc.3", &rc4)
            .expect("0.6.0-rc.4 satisfies >=0.6.0-rc.3");

        // The final release of the same triple is accepted (0.6.0 > any
        // 0.6.0-pre under semver ordering).
        let release = Version::parse("0.6.0").unwrap();
        distro_astrid_version_satisfied(">=0.6.0-rc.3", &release)
            .expect("0.6.0 satisfies >=0.6.0-rc.3");

        // A newer release is also accepted.
        let newer = Version::parse("0.7.0").unwrap();
        distro_astrid_version_satisfied(">=0.6.0-rc.3", &newer)
            .expect("0.7.0 satisfies >=0.6.0-rc.3");
    }

    #[test]
    fn astrid_version_malformed_requirement_is_an_error() {
        // A malformed requirement is still rejected (distinct from "no floor").
        let running = Version::parse("0.6.0").unwrap();
        let err = distro_astrid_version_satisfied("not-a-version", &running)
            .expect_err("a malformed astrid-version requirement must error");
        assert!(
            err.to_string().contains("is not a valid requirement"),
            "got: {err}"
        );
    }

    #[test]
    fn enforce_astrid_version_no_floor_is_ok() {
        // A manifest with no astrid-version imposes no requirement.
        let toml_src = r#"
schema-version = 1

[distro]
id = "no-floor"
name = "No Floor"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@example-org/capsule-cli"
version = "0.7.0"
role = "uplink"
"#;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        assert!(manifest.distro.astrid_version.is_none());
        enforce_astrid_version(&manifest).expect("no floor → no requirement");
    }

    #[test]
    fn running_astrid_version_is_valid_semver() {
        // The enforcement reads RUNNING_ASTRID_VERSION as semver; guard against a
        // build whose CARGO_PKG_VERSION cannot parse (would break every init).
        Version::parse(RUNNING_ASTRID_VERSION).expect("the CLI's own version must be valid semver");
    }

    #[test]
    fn branding_accepts_well_formed_colors() {
        let toml_src = r##"
schema-version = 1

[distro]
id = "branded"
name = "Branded"
version = "0.1.0"

[[capsule]]
name = "astrid-capsule-cli"
source = "@example-org/capsule-cli"
version = "0.7.0"
role = "uplink"

[branding]
primary-color = "#ff8800"
accent-color = "#abc"
"##;
        let manifest: DistroManifest = toml::from_str(toml_src).unwrap();
        validate_manifest(&manifest).expect("branding accepts hex colours");
    }
}