a3s 0.9.8

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

use a3s_updater::{
    parse_version, uninstall_owned_files, ComponentReceipt, InstallProvenance,
    RECEIPT_SCHEMA_VERSION,
};
use anyhow::{bail, Context};
use serde::Serialize;

use super::catalog::{self, ComponentSpec, Distribution, ReleaseSpec};
use super::discovery::find_state;
use super::id::ComponentId;
use super::lock::ComponentOperationLock;
use super::paths::ComponentPaths;
use super::probe::probe_release;
use super::release_install::{install_release, ResolvedRelease};
use super::state::{ComponentState, Health, Presence};
use crate::registry::ResolvedRegistryPackage;

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum InstallSource {
    #[default]
    Auto,
    Homebrew,
    Release,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum InstallIntent {
    #[default]
    Install,
    Upgrade,
}

impl InstallIntent {
    pub fn action(self) -> &'static str {
        match self {
            Self::Install => "install",
            Self::Upgrade => "upgrade",
        }
    }
}

#[derive(Debug, Clone)]
pub struct InstallRequest {
    pub version: Option<String>,
    pub source: InstallSource,
    pub intent: InstallIntent,
    pub package: Option<PathBuf>,
    pub force: bool,
    pub allow_unsigned: bool,
    pub progress: bool,
    pub resolved_releases: BTreeMap<String, ResolvedRelease>,
    pub resolved_sources: BTreeMap<String, InstallSource>,
    pub resolved_registry_packages: BTreeMap<String, ResolvedRegistryPackage>,
}

impl Default for InstallRequest {
    fn default() -> Self {
        Self {
            version: None,
            source: InstallSource::Auto,
            intent: InstallIntent::Install,
            package: None,
            force: false,
            allow_unsigned: false,
            progress: true,
            resolved_releases: BTreeMap::new(),
            resolved_sources: BTreeMap::new(),
            resolved_registry_packages: BTreeMap::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationRecord {
    pub component: ComponentId,
    pub action: &'static str,
    pub changed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<InstallProvenance>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    pub message: String,
}

pub async fn install_component(
    id: &ComponentId,
    request: &InstallRequest,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    let _lock = ComponentOperationLock::acquire(paths.operation_lock_path(id), id).await?;
    install_component_locked(id, request, paths).await
}

pub(super) async fn install_component_locked(
    id: &ComponentId,
    request: &InstallRequest,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    if let Some(spec) = catalog::find(id) {
        if request.package.is_some() {
            bail!("--from is valid only for external Use extensions");
        }
        if request.allow_unsigned {
            bail!("--allow-unsigned is valid only for external Use extensions");
        }
        if request.version.is_some() && !matches!(spec.distribution, Distribution::Release(_)) {
            bail!(
                "component '{}' does not own a versioned release; --version is not supported",
                id
            );
        }
        if request.source != InstallSource::Auto
            && !matches!(spec.distribution, Distribution::Release(_))
        {
            bail!(
                "component '{}' does not own an install source; --source is not supported",
                id
            );
        }
        return match spec.distribution {
            Distribution::Bundled => install_bundled(id, spec, paths),
            Distribution::Release(release) => {
                if request.package.is_some() {
                    bail!("--from is valid only for external Use extensions");
                }
                install_product(id, spec, release, request, paths).await
            }
            Distribution::Delegated { parent } => {
                let parent = ComponentId::parse(parent)?;
                let parent_path = ensure_parent(&parent, paths, request).await?;
                delegate_install(id, &parent, &parent_path, request)
            }
        };
    }

    let use_id = ComponentId::parse("use")?;
    if !id.is_child_of(&use_id) || id.as_str().split('/').count() < 3 {
        bail!("component '{}' is not registered", id);
    }
    if request.source != InstallSource::Auto {
        bail!(
            "external component '{}' is resolved through its package source; --source is not supported",
            id
        );
    }
    if request.package.is_some() {
        if !request.allow_unsigned {
            bail!(
                "external component '{}' uses an unsigned local package; rerun with --allow-unsigned",
                id
            );
        }
        if request.version.is_some() {
            bail!(
                "external component '{}' derives its version from the local package manifest; --version is not supported",
                id
            );
        }
    } else {
        if request.allow_unsigned {
            bail!("--allow-unsigned is valid only with an explicit local --from package");
        }
        let resolved = request
            .resolved_registry_packages
            .get(id.as_str())
            .with_context(|| {
                format!(
                    "external component '{}' has no reviewed signed-registry resolution",
                    id
                )
            })?;
        validate_registry_resolution(id, resolved)?;
    }
    let parent_path = ensure_parent(&use_id, paths, request).await?;
    delegate_install(id, &use_id, &parent_path, request)
}

#[cfg(test)]
pub fn uninstall_component(
    id: &ComponentId,
    cascade: bool,
    purge: bool,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    let _lock = ComponentOperationLock::acquire_sync(&paths.operation_lock_path(id), id)?;
    uninstall_component_locked(id, cascade, purge, paths)
}

pub(super) fn uninstall_component_locked(
    id: &ComponentId,
    cascade: bool,
    purge: bool,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    if let Some(spec) = catalog::find(id) {
        if !spec.removable {
            bail!("component '{}' is bundled and cannot be uninstalled", id);
        }
        if let Distribution::Delegated { parent } = spec.distribution {
            let parent = ComponentId::parse(parent)?;
            let parent_state = find_state(&parent, paths)?;
            let parent_path = ready_path(&parent_state)?;
            return delegate_uninstall(id, &parent, &parent_path);
        }
    } else {
        let use_id = ComponentId::parse("use")?;
        if !id.is_child_of(&use_id) || id.as_str().split('/').count() < 3 {
            bail!("component '{}' is not registered", id);
        }
        let parent_state = find_state(&use_id, paths)?;
        let parent_path = ready_path(&parent_state)?;
        return delegate_uninstall(id, &use_id, &parent_path);
    }

    let store = paths.receipt_store();
    let receipt = store
        .read(id.as_str())?
        .with_context(|| ownership_error(id, paths))?;
    let children = store
        .list()?
        .into_iter()
        .filter(|candidate| {
            ComponentId::parse(&candidate.component_id)
                .map(|candidate_id| candidate_id.is_child_of(id))
                .unwrap_or(false)
        })
        .collect::<Vec<_>>();
    if !children.is_empty() && !cascade {
        bail!(
            "component '{}' has managed children; rerun with --cascade",
            id
        );
    }
    if cascade {
        for child in children.into_iter().rev() {
            let child_id = ComponentId::parse(&child.component_id)?;
            uninstall_component_locked(&child_id, true, purge, paths)?;
        }
    }

    match receipt.provenance {
        InstallProvenance::Homebrew => uninstall_homebrew(id, &receipt, paths)?,
        provenance if provenance.owns_files() => {
            stop_owned_service(id, &receipt)?;
            uninstall_owned_files(&receipt, &paths.data_root)?;
            store.remove(id.as_str())?;
        }
        _ => bail!(ownership_error(id, paths)),
    }
    if purge {
        let cache = paths.cache_dir(id);
        if cache.exists() {
            std::fs::remove_dir_all(&cache)
                .with_context(|| format!("failed to remove cache {}", cache.display()))?;
        }
    }
    Ok(OperationRecord {
        component: id.clone(),
        action: "uninstall",
        changed: true,
        version: Some(receipt.version),
        provenance: Some(receipt.provenance),
        path: receipt.executable_path,
        message: format!("Uninstalled component '{}'.", id),
    })
}

async fn ensure_parent(
    parent: &ComponentId,
    paths: &ComponentPaths,
    request: &InstallRequest,
) -> anyhow::Result<PathBuf> {
    let state = find_state(parent, paths)?;
    if state.is_ready() {
        return ready_path(&state);
    }
    let spec = catalog::find(parent)
        .with_context(|| format!("parent component '{}' is not registered", parent))?;
    let release = catalog::release(spec)
        .with_context(|| format!("parent component '{}' is not installable", parent))?;
    let parent_request = InstallRequest {
        progress: request.progress,
        resolved_releases: request.resolved_releases.clone(),
        resolved_sources: request.resolved_sources.clone(),
        ..InstallRequest::default()
    };
    let record = install_product(parent, spec, release, &parent_request, paths).await?;
    record
        .path
        .context("installed parent did not report an executable path")
}

fn install_bundled(
    id: &ComponentId,
    spec: &ComponentSpec,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    let state = find_state(id, paths)?;
    if !state.is_ready() {
        bail!("bundled component '{}' failed its health check", id);
    }
    Ok(OperationRecord {
        component: id.clone(),
        action: "install",
        changed: false,
        version: state.version,
        provenance: state.provenance,
        path: state.path,
        message: format!("{} is bundled with a3s.", spec.description),
    })
}

async fn install_product(
    id: &ComponentId,
    _spec: &ComponentSpec,
    release: ReleaseSpec,
    request: &InstallRequest,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    let state = find_state(id, paths)?;
    let requested_version_is_ready = request.version.as_deref().is_none_or(|requested| {
        state
            .version
            .as_deref()
            .is_some_and(|installed| parse_version(installed).ok() == parse_version(requested).ok())
    });
    if state.is_ready() && requested_version_is_ready && !request.force {
        return Ok(OperationRecord {
            component: id.clone(),
            action: "install",
            changed: false,
            version: state.version,
            provenance: state.provenance,
            path: state.path,
            message: format!("Component '{}' is already ready.", id),
        });
    }
    if state.health == Health::Broken && !request.force {
        bail!(
            "component '{}' is broken; rerun install with --force to repair it",
            id
        );
    }

    let source = resolve_install_source(id, release, request)?;
    match source {
        InstallSource::Homebrew => install_homebrew(id, release, request, paths),
        InstallSource::Release => {
            install_release(
                id,
                release,
                request,
                request.resolved_releases.get(id.as_str()),
                paths,
            )
            .await
        }
        InstallSource::Auto => {
            bail!("automatic install source was not resolved")
        }
    }
}

pub(super) fn resolve_install_source(
    id: &ComponentId,
    release: ReleaseSpec,
    request: &InstallRequest,
) -> anyhow::Result<InstallSource> {
    if let Some(resolved) = request.resolved_sources.get(id.as_str()).copied() {
        if request.source != InstallSource::Auto && request.source != resolved {
            bail!(
                "reviewed install source {:?} does not match requested source {:?}",
                resolved,
                request.source
            );
        }
        return Ok(resolved);
    }
    Ok(match request.source {
        InstallSource::Auto
            if request.version.is_none()
                && release.homebrew_formula.is_some()
                && a3s_is_homebrew_managed() =>
        {
            InstallSource::Homebrew
        }
        InstallSource::Auto => InstallSource::Release,
        explicit => explicit,
    })
}

fn install_homebrew(
    id: &ComponentId,
    release: ReleaseSpec,
    request: &InstallRequest,
    paths: &ComponentPaths,
) -> anyhow::Result<OperationRecord> {
    if request.version.is_some() {
        bail!(
            "component '{}' cannot select an exact version through Homebrew; use --source release",
            id
        );
    }
    let formula = release
        .homebrew_formula
        .with_context(|| format!("component '{}' has no Homebrew formula", id))?;
    let verb = match (request.intent, request.force) {
        (InstallIntent::Upgrade, _) => "upgrade",
        (InstallIntent::Install, true) => "reinstall",
        (InstallIntent::Install, false) => "install",
    };
    super::progress(
        request.progress,
        format!("a3s: {} '{}' with Homebrew...", verb, id),
    );
    let status = Command::new("brew")
        .args([verb, formula])
        .status()
        .context("failed to run Homebrew")?;
    if !status.success() {
        bail!("Homebrew failed to {verb} '{}'", id);
    }
    let prefix_output = Command::new("brew")
        .args(["--prefix", formula])
        .output()
        .context("failed to query Homebrew prefix")?;
    if !prefix_output.status.success() {
        bail!("Homebrew installed '{}', but its prefix is unavailable", id);
    }
    let prefix = PathBuf::from(String::from_utf8(prefix_output.stdout)?.trim());
    let executable = prefix.join("bin").join(release.binary);
    let version = match probe_release(release, &executable)? {
        Some(version) => version,
        None => homebrew_formula_version(formula)?,
    };
    let receipt = ComponentReceipt {
        schema_version: RECEIPT_SCHEMA_VERSION,
        component_id: id.to_string(),
        version: version.clone(),
        provenance: InstallProvenance::Homebrew,
        install_root: prefix,
        executable_path: Some(executable.clone()),
        owned_paths: Vec::new(),
        source: Some(formula.to_string()),
        artifact_checksums: BTreeMap::new(),
        installed_at: chrono::Utc::now().to_rfc3339(),
    };
    paths.receipt_store().write(&receipt)?;
    Ok(OperationRecord {
        component: id.clone(),
        action: request.intent.action(),
        changed: true,
        version: Some(version),
        provenance: Some(InstallProvenance::Homebrew),
        path: Some(executable),
        message: format!("Homebrew completed {verb} for component '{}'.", id),
    })
}

fn homebrew_formula_version(formula: &str) -> anyhow::Result<String> {
    let output = Command::new("brew")
        .args(["list", "--versions", formula])
        .output()
        .context("failed to query the installed Homebrew formula version")?;
    if !output.status.success() {
        bail!("Homebrew installed '{formula}', but its version is unavailable");
    }
    let output = String::from_utf8(output.stdout)?;
    output
        .split_whitespace()
        .rev()
        .find(|field| parse_version(field).is_ok())
        .map(str::to_string)
        .with_context(|| format!("Homebrew returned no installed version for formula '{formula}'"))
}

fn delegate_install(
    id: &ComponentId,
    parent: &ComponentId,
    parent_path: &Path,
    request: &InstallRequest,
) -> anyhow::Result<OperationRecord> {
    let relative = id
        .relative_to(parent)
        .context("delegated component is outside its parent namespace")?;
    let mut command = Command::new(parent_path);
    command.args(["component", "install", relative, "--json"]);
    if let Some(package) = &request.package {
        command.arg("--from").arg(package);
    }
    if request.force {
        command.arg("--force");
    }
    if request.allow_unsigned {
        command.arg("--allow-unsigned");
    }
    if let Some(resolved) = request.resolved_registry_packages.get(id.as_str()) {
        validate_registry_resolution(id, resolved)?;
        let plan_digest = resolved.package.plan_digest().map_err(anyhow::Error::new)?;
        command
            .arg("--registry-name")
            .arg(&resolved.registry.name)
            .arg("--registry-url")
            .arg(&resolved.registry.url)
            .arg("--trust-root")
            .arg(&resolved.registry.trust_root)
            .arg("--version")
            .arg(&resolved.package.version)
            .arg("--channel")
            .arg(&resolved.package.channel)
            .arg("--registry-plan-digest")
            .arg(plan_digest);
        if let Some(path) = &resolved.registry.trusted_root_path {
            command.arg("--trusted-root").arg(path);
        }
    }
    let output = command.output().with_context(|| {
        format!(
            "failed to delegate install to parent component '{}'",
            parent
        )
    })?;
    if !output.status.success() {
        bail!(delegated_failure(parent, "install", &output));
    }
    let value = serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .context("parent install returned invalid JSON")?;
    validate_delegated_success(&value, "install")?;
    let data = value.get("data").unwrap_or(&value);
    let component = data.get("component");
    Ok(OperationRecord {
        component: id.clone(),
        action: request.intent.action(),
        changed: data
            .get("changed")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(true),
        version: component
            .and_then(|value| value.get("version"))
            .and_then(serde_json::Value::as_str)
            .map(str::to_string),
        provenance: Some(InstallProvenance::Delegated),
        path: component
            .and_then(|value| value.get("path"))
            .and_then(serde_json::Value::as_str)
            .map(PathBuf::from),
        message: format!("Parent component '{}' installed '{}'.", parent, id),
    })
}

fn validate_registry_resolution(
    id: &ComponentId,
    resolved: &ResolvedRegistryPackage,
) -> anyhow::Result<()> {
    let parent = ComponentId::parse("use")?;
    let package_id = id
        .relative_to(&parent)
        .context("signed registry package is outside the Use namespace")?;
    if resolved.package.package_id != package_id {
        bail!(
            "reviewed registry package '{}' does not match component '{}'",
            resolved.package.package_id,
            id
        );
    }
    if resolved.package.registry_name != resolved.registry.name
        || resolved.package.registry_url != resolved.registry.url
        || resolved.package.root_sha256
            != resolved.registry.trust_root.trim_start_matches("sha256:")
    {
        bail!("reviewed registry package provenance is internally inconsistent");
    }
    Ok(())
}

fn delegate_uninstall(
    id: &ComponentId,
    parent: &ComponentId,
    parent_path: &Path,
) -> anyhow::Result<OperationRecord> {
    let relative = id
        .relative_to(parent)
        .context("delegated component is outside its parent namespace")?;
    let output = Command::new(parent_path)
        .args(["component", "uninstall", relative, "--json"])
        .output()
        .with_context(|| {
            format!(
                "failed to delegate uninstall to parent component '{}'",
                parent
            )
        })?;
    if !output.status.success() {
        bail!(delegated_failure(parent, "uninstall", &output));
    }
    let value = serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .context("parent uninstall returned invalid JSON")?;
    validate_delegated_success(&value, "uninstall")?;
    let data = value.get("data").unwrap_or(&value);
    Ok(OperationRecord {
        component: id.clone(),
        action: "uninstall",
        changed: data
            .get("changed")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(true),
        version: None,
        provenance: Some(InstallProvenance::Delegated),
        path: None,
        message: format!("Parent component '{}' uninstalled '{}'.", parent, id),
    })
}

fn validate_delegated_success(value: &serde_json::Value, action: &str) -> anyhow::Result<()> {
    if value
        .get("schemaVersion")
        .and_then(serde_json::Value::as_u64)
        != Some(1)
    {
        bail!("parent {action} returned an incompatible CLI schema");
    }
    if value.get("ok").and_then(serde_json::Value::as_bool) == Some(false) {
        bail!("parent {action} returned an error response with a successful exit status");
    }
    Ok(())
}

fn delegated_failure(parent: &ComponentId, action: &str, output: &Output) -> String {
    let machine_message = serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .ok()
        .and_then(|value| {
            value
                .get("error")
                .and_then(|error| error.get("message"))
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        });
    let message = machine_message.unwrap_or_else(|| {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stderr.trim().is_empty() {
            stdout.trim().to_string()
        } else {
            stderr.trim().to_string()
        }
    });
    format!("parent component '{parent}' rejected {action}: {message}")
}

fn uninstall_homebrew(
    id: &ComponentId,
    receipt: &ComponentReceipt,
    paths: &ComponentPaths,
) -> anyhow::Result<()> {
    let formula = receipt
        .source
        .as_deref()
        .context("Homebrew receipt has no formula")?;
    let status = Command::new("brew")
        .args(["uninstall", formula])
        .status()
        .context("failed to run Homebrew")?;
    if !status.success() {
        bail!("Homebrew failed to uninstall '{}'", id);
    }
    paths.receipt_store().remove(id.as_str())
}

fn stop_owned_service(id: &ComponentId, receipt: &ComponentReceipt) -> anyhow::Result<()> {
    if id.as_str() != "use" {
        return Ok(());
    }
    let Some(executable) = &receipt.executable_path else {
        return Ok(());
    };
    let output = Command::new(executable)
        .args(["mcp", "stop", "--json"])
        .output()
        .context("failed to stop the a3s-use MCP service")?;
    if !output.status.success() {
        bail!(
            "a3s-use MCP service did not stop safely: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .context("a3s-use MCP stop returned invalid JSON")?;
    Ok(())
}

fn ready_path(state: &ComponentState) -> anyhow::Result<PathBuf> {
    if state.presence == Presence::Missing || !state.is_ready() {
        bail!("component '{}' is not ready", state.id);
    }
    state
        .path
        .clone()
        .with_context(|| format!("component '{}' has no executable path", state.id))
}

fn ownership_error(id: &ComponentId, paths: &ComponentPaths) -> String {
    match find_state(id, paths) {
        Ok(state) if state.presence != Presence::Missing => format!(
            "component '{}' is present at {}, but A3S does not own it",
            id,
            state
                .path
                .as_deref()
                .map(Path::display)
                .map(|value| value.to_string())
                .unwrap_or_else(|| "an external location".to_string())
        ),
        _ => format!("component '{}' is not installed", id),
    }
}

fn a3s_is_homebrew_managed() -> bool {
    Command::new("brew")
        .args(["list", "--versions", "a3s"])
        .output()
        .map(|output| output.status.success() && !output.stdout.is_empty())
        .unwrap_or(false)
}

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

    #[test]
    fn install_request_defaults_to_safe_release_selection() {
        let request = InstallRequest::default();
        assert_eq!(request.source, InstallSource::Auto);
        assert!(!request.force);
        assert!(request.package.is_none());
    }
}