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
//! Capsule removal with dependency safety checks.
//!
//! Before removing a capsule, checks whether it is the sole provider of any
//! capability required by another installed capsule. Blocks removal unless
//! `--force` is passed. Content-addressed WASM binaries in `bin/` are cleaned
//! up only if no other installed capsule references the same hash.

use std::collections::HashSet;

use anyhow::{Context, bail};
use astrid_core::PrincipalId;
use astrid_core::dirs::AstridHome;

use super::meta::CapsuleMeta;

/// Remove an installed capsule by name.
///
/// The caller must run [`validate_capsule_removal`] before any live unload and
/// this on-disk deletion. Keeping deletion validation-free avoids a second
/// dependency scan after daemon unload and prevents a stale second snapshot
/// from disagreeing with the already-authorized operation.
pub(crate) fn remove_capsule(
    name: &str,
    workspace: bool,
    force: bool,
    purge: bool,
) -> anyhow::Result<()> {
    let home = AstridHome::resolve()?;
    let principal = crate::principal::current();
    remove_capsule_from_home_for(&home, &principal, name, workspace, force, purge)
}

fn remove_capsule_from_home(
    home: &AstridHome,
    name: &str,
    workspace: bool,
    force: bool,
    purge: bool,
) -> anyhow::Result<()> {
    let principal = astrid_capsule_install::paths::install_principal();
    remove_capsule_from_home_for(home, &principal, name, workspace, force, purge)
}

fn remove_capsule_from_home_for(
    home: &AstridHome,
    principal: &PrincipalId,
    name: &str,
    workspace: bool,
    force: bool,
    purge: bool,
) -> anyhow::Result<()> {
    let target_dir = astrid_capsule_install::resolve_target_dir_for_with_layout(
        home,
        principal,
        name,
        workspace,
        crate::workspace_layout::current(),
    )?;

    // Content-addressed artifacts in bin/ and wit/ are NEVER deleted.
    // They are the audit trail — the BLAKE3 hash in audit entries must always
    // resolve to a real binary. Append-only by default, explicit `astrid gc`
    // for operator-initiated cleanup (future).

    // Remove the capsule directory (metadata, Capsule.toml, config).
    std::fs::remove_dir_all(&target_dir)
        .with_context(|| format!("failed to remove {}", target_dir.display()))?;

    // Only delete user configuration (API keys, env vars) with --purge.
    // By default, env.json is preserved so reinstall skips prompting.
    if purge {
        let env_path = home
            .principal_home(principal)
            .env_dir()
            .join(format!("{name}.env.json"));
        if env_path.exists() {
            std::fs::remove_file(&env_path).with_context(|| {
                format!("failed to purge configuration at {}", env_path.display())
            })?;
            eprintln!("Purged configuration for '{name}'.");
        }
    }

    if force {
        eprintln!("Removed '{name}' (forced).");
    } else {
        eprintln!("Removed '{name}'.");
    }

    Ok(())
}

/// Validate that `name` exists and passes dependency safety checks.
///
/// Split from [`remove_capsule`] so the async dispatch path can perform the
/// daemon-side authorization/unload before deleting the on-disk capsule.
pub(crate) fn validate_capsule_removal(
    name: &str,
    workspace: bool,
    force: bool,
) -> anyhow::Result<()> {
    let home = AstridHome::resolve()?;
    let principal = crate::principal::current();
    validate_capsule_removal_from_home_for(&home, &principal, name, workspace, force)
}

fn validate_capsule_removal_from_home(
    home: &AstridHome,
    name: &str,
    workspace: bool,
    force: bool,
) -> anyhow::Result<()> {
    let principal = astrid_capsule_install::paths::install_principal();
    validate_capsule_removal_from_home_for(home, &principal, name, workspace, force)
}

fn validate_capsule_removal_from_home_for(
    home: &AstridHome,
    principal: &PrincipalId,
    name: &str,
    workspace: bool,
    force: bool,
) -> anyhow::Result<()> {
    let target_dir = astrid_capsule_install::resolve_target_dir_for_with_layout(
        home,
        principal,
        name,
        workspace,
        crate::workspace_layout::current(),
    )?;

    if !target_dir.exists() {
        bail!("Capsule '{name}' is not installed.");
    }

    let target_meta = super::meta::read_meta(&target_dir);

    // Scan once, reuse for both dependency check and binary cleanup
    let all_capsules = super::meta::scan_installed_capsules_in_home_for_with_layout(
        home,
        principal,
        crate::workspace_layout::current(),
    )?;

    // Dependency safety check (skip with --force)
    if !force && let Some(block) = check_removal_safety(name, target_meta.as_ref(), &all_capsules) {
        bail!(
            "Cannot remove '{name}': it is the sole provider of '{}' \
             which is required by '{}'. Use --force to override.",
            block.capability,
            block.dependent,
        );
    }

    Ok(())
}

/// A blocked removal: the target capsule is the sole provider of a capability
/// that another capsule requires.
struct RemovalBlocked {
    capability: String,
    dependent: String,
}

/// Check whether removing `target_name` would leave any required capability
/// without a provider.
///
/// Returns `Some(RemovalBlocked)` on the first blocking dependency found,
/// or `None` if removal is safe.
fn check_removal_safety(
    target_name: &str,
    target_meta: Option<&CapsuleMeta>,
    all_capsules: &[super::meta::InstalledCapsule],
) -> Option<RemovalBlocked> {
    // Collect all interfaces the target exports as (namespace, name) pairs.
    let target_exports: HashSet<(&str, &str)> = target_meta
        .map(|m| {
            m.exports
                .iter()
                .flat_map(|(ns, ifaces)| {
                    ifaces.keys().map(move |name| (ns.as_str(), name.as_str()))
                })
                .collect()
        })
        .unwrap_or_default();

    if target_exports.is_empty() {
        return None;
    }

    // Collect all interfaces exported by capsules other than the target.
    let mut other_exported: HashSet<(&str, &str)> = HashSet::new();
    for capsule in all_capsules {
        if capsule.name == target_name {
            continue;
        }
        if let Some(ref meta) = capsule.meta {
            for (ns, ifaces) in &meta.exports {
                for name in ifaces.keys() {
                    other_exported.insert((ns.as_str(), name.as_str()));
                }
            }
        }
    }

    // Check if any other capsule imports something only the target exports.
    for capsule in all_capsules {
        if capsule.name == target_name {
            continue;
        }
        if let Some(ref meta) = capsule.meta {
            for (ns, ifaces) in &meta.imports {
                for name in ifaces.keys() {
                    let key = (ns.as_str(), name.as_str());
                    if target_exports.contains(&key) && !other_exported.contains(&key) {
                        return Some(RemovalBlocked {
                            capability: format!("{ns}/{name}"),
                            dependent: capsule.name.clone(),
                        });
                    }
                }
            }
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::super::meta::{CapsuleLocation, CapsuleMeta, InstalledCapsule};
    use super::*;
    use crate::commands::capsule::meta::write_meta;

    fn meta_ie(
        exports: &[(&str, &str, &str)],
        imports: &[(&str, &str, &str)],
        hash: Option<&str>,
    ) -> CapsuleMeta {
        let mut export_map = std::collections::HashMap::new();
        for (ns, iface, ver) in exports {
            export_map
                .entry(ns.to_string())
                .or_insert_with(std::collections::HashMap::new)
                .insert(iface.to_string(), ver.to_string());
        }
        let mut import_map = std::collections::HashMap::new();
        for (ns, iface, ver) in imports {
            import_map
                .entry(ns.to_string())
                .or_insert_with(std::collections::HashMap::new)
                .insert(iface.to_string(), ver.to_string());
        }
        CapsuleMeta {
            version: "1.0.0".into(),
            installed_at: "2026-01-01T00:00:00Z".into(),
            updated_at: "2026-01-01T00:00:00Z".into(),
            source: None,
            exports: export_map,
            imports: import_map,
            wasm_hash: hash.map(String::from),
            wit_files: std::collections::HashMap::new(),
            ..Default::default()
        }
    }

    fn capsule(
        name: &str,
        exports: &[(&str, &str, &str)],
        imports: &[(&str, &str, &str)],
    ) -> InstalledCapsule {
        InstalledCapsule {
            name: name.to_string(),
            meta: Some(meta_ie(exports, imports, None)),
            location: CapsuleLocation::User,
        }
    }

    #[test]
    fn removal_safe_when_no_dependents() {
        let target_meta = Some(meta_ie(&[("astrid", "llm", "1.0.0")], &[], None));
        let all = vec![
            capsule("target", &[("astrid", "llm", "1.0.0")], &[]),
            capsule("other", &[("astrid", "tool", "1.0.0")], &[]),
        ];
        assert!(check_removal_safety("target", target_meta.as_ref(), &all).is_none());
    }

    #[test]
    fn removal_blocked_when_sole_provider() {
        let target_meta = Some(meta_ie(&[("astrid", "llm", "1.0.0")], &[], None));
        let all = vec![
            capsule("target", &[("astrid", "llm", "1.0.0")], &[]),
            capsule("react", &[], &[("astrid", "llm", "^1.0")]),
        ];
        let block =
            check_removal_safety("target", target_meta.as_ref(), &all).expect("should be blocked");
        assert_eq!(block.capability, "astrid/llm");
        assert_eq!(block.dependent, "react");
    }

    #[test]
    fn removal_safe_when_another_provider_exists() {
        let target_meta = Some(meta_ie(&[("astrid", "llm", "1.0.0")], &[], None));
        let all = vec![
            capsule("openai", &[("astrid", "llm", "1.0.0")], &[]),
            capsule("ollama", &[("astrid", "llm", "1.0.0")], &[]),
            capsule("react", &[], &[("astrid", "llm", "^1.0")]),
        ];
        assert!(check_removal_safety("openai", target_meta.as_ref(), &all).is_none());
    }

    #[test]
    fn removal_safe_when_no_exports() {
        let target_meta = Some(meta_ie(&[], &[], None));
        let all = vec![
            capsule("target", &[], &[]),
            capsule(
                "other",
                &[("astrid", "tool", "1.0.0")],
                &[("astrid", "llm", "^1.0")],
            ),
        ];
        assert!(check_removal_safety("target", target_meta.as_ref(), &all).is_none());
    }

    #[test]
    fn removal_safe_when_no_meta() {
        let all = vec![
            InstalledCapsule {
                name: "target".into(),
                meta: None,
                location: CapsuleLocation::User,
            },
            capsule(
                "other",
                &[("astrid", "tool", "1.0.0")],
                &[("astrid", "llm", "^1.0")],
            ),
        ];
        assert!(check_removal_safety("target", None, &all).is_none());
    }

    #[test]
    fn removal_blocked_on_first_conflict_only() {
        let target_meta = Some(meta_ie(
            &[("astrid", "llm", "1.0.0"), ("astrid", "tool", "1.0.0")],
            &[],
            None,
        ));
        let all = vec![
            capsule(
                "target",
                &[("astrid", "llm", "1.0.0"), ("astrid", "tool", "1.0.0")],
                &[],
            ),
            capsule("react", &[], &[("astrid", "llm", "^1.0")]),
            capsule("cli", &[], &[("astrid", "tool", "^1.0")]),
        ];
        let block = check_removal_safety("target", target_meta.as_ref(), &all);
        assert!(block.is_some());
    }

    #[test]
    fn validate_nonexistent_capsule_fails() {
        let home_dir = tempfile::tempdir().unwrap();
        let home = AstridHome::from_path(home_dir.path());
        let target_dir =
            astrid_capsule_install::resolve_target_dir(&home, "nonexistent", false).unwrap();
        assert!(!target_dir.exists());

        let err = validate_capsule_removal_from_home(&home, "nonexistent", false, false);
        assert!(err.is_err());
        let msg = format!("{}", err.unwrap_err());
        assert!(msg.contains("not installed"), "got: {msg}");
    }

    #[test]
    fn remove_capsule_cleans_directory() {
        let home_dir = tempfile::tempdir().unwrap();
        let home = AstridHome::from_path(home_dir.path());

        // Install a minimal capsule
        let capsule_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            capsule_dir.path().join("Capsule.toml"),
            "[package]\nname = \"remove-test\"\nversion = \"1.0.0\"\n",
        )
        .unwrap();

        super::super::install::install_from_local_path(capsule_dir.path(), false, &home, None)
            .expect("install should succeed");

        let target =
            astrid_capsule_install::resolve_target_dir(&home, "remove-test", false).unwrap();
        assert!(target.exists());

        remove_capsule_from_home(&home, "remove-test", false, true, false).unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn remove_capsule_from_home_for_targets_principal_install() {
        let home_dir = tempfile::tempdir().unwrap();
        let home = AstridHome::from_path(home_dir.path());
        let default = astrid_capsule_install::paths::install_principal();
        let user = PrincipalId::new("regular-user").unwrap();
        let default_target =
            astrid_capsule_install::resolve_target_dir_for(&home, &default, "shared", false)
                .unwrap();
        let user_target =
            astrid_capsule_install::resolve_target_dir_for(&home, &user, "shared", false).unwrap();

        std::fs::create_dir_all(&default_target).unwrap();
        std::fs::create_dir_all(&user_target).unwrap();

        remove_capsule_from_home_for(&home, &user, "shared", false, true, false).unwrap();
        assert!(
            default_target.exists(),
            "default install must not be removed by a principal-scoped remove"
        );
        assert!(!user_target.exists(), "principal install should be removed");
    }

    #[test]
    fn remove_capsule_does_not_repeat_dependency_validation() {
        let home_dir = tempfile::tempdir().unwrap();
        let home = AstridHome::from_path(home_dir.path());
        let capsules_dir = home
            .principal_home(&astrid_capsule_install::paths::install_principal())
            .capsules_dir();

        let target = capsules_dir.join("target");
        let dependent = capsules_dir.join("dependent");
        std::fs::create_dir_all(&target).unwrap();
        std::fs::create_dir_all(&dependent).unwrap();
        write_meta(&target, &meta_ie(&[("astrid", "llm", "1.0.0")], &[], None)).unwrap();
        write_meta(
            &dependent,
            &meta_ie(&[], &[("astrid", "llm", "^1.0")], None),
        )
        .unwrap();

        let validation_err = validate_capsule_removal_from_home(&home, "target", false, false)
            .expect_err("fixture should make preflight validation fail");
        assert!(
            validation_err
                .to_string()
                .contains("it is the sole provider"),
            "got: {validation_err}"
        );

        remove_capsule_from_home(&home, "target", false, false, false)
            .expect("delete path must trust the caller's single preflight validation");
        assert!(!target.exists());
    }

    #[test]
    fn remove_without_purge_preserves_env() {
        let tmp = tempfile::tempdir().unwrap();
        let env_dir = tmp.path().join("env");
        std::fs::create_dir_all(&env_dir).unwrap();
        let env_path = env_dir.join("test-capsule.env.json");
        std::fs::write(&env_path, r#"{"api_key":"secret"}"#).unwrap();

        // Simulate the purge=false path: env file should not be touched.
        let purge = false;
        if purge {
            let _ = std::fs::remove_file(&env_path);
        }
        assert!(
            env_path.exists(),
            "env.json should be preserved when purge=false"
        );
    }

    #[test]
    fn remove_with_purge_deletes_env() {
        let tmp = tempfile::tempdir().unwrap();
        let env_dir = tmp.path().join("env");
        std::fs::create_dir_all(&env_dir).unwrap();
        let env_path = env_dir.join("test-capsule.env.json");
        std::fs::write(&env_path, r#"{"api_key":"secret"}"#).unwrap();

        // Simulate the purge=true path: env file should be deleted.
        let purge = true;
        if purge && env_path.exists() {
            std::fs::remove_file(&env_path).unwrap();
        }
        assert!(
            !env_path.exists(),
            "env.json should be deleted when purge=true"
        );
    }

    #[test]
    fn purge_with_no_env_file_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let env_path = tmp.path().join("nonexistent.env.json");

        // Simulate purge on a capsule that has no env config.
        let purge = true;
        if purge && env_path.exists() {
            std::fs::remove_file(&env_path).unwrap();
        }
        // Should not error — just a no-op.
        assert!(!env_path.exists());
    }
}