capsule-runtime 0.7.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
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
//! The bound on removing an artifact mid-session — `murmur:artifact-manager/manage.remove` on the
//! script path, the `remove-artifact` tool on the http agent loop, both
//! `CapsuleStoreState::remove_artifact`: a capsule removes only an artifact it pulled.
//!
//! # The bound
//!
//! An artifact is removable when all three hold:
//!
//! - the session's [`InstalledArtifactSummary::origin`] is [`LockOrigin::Runtime`];
//! - the `murmur.lock` entry, read at the moment of removal, is [`LockOrigin::Runtime`];
//! - `murmur.yaml` does not declare the name.
//!
//! The origin says who pinned an artifact; the declaration says the next launch depends on it.
//! Deleting the lock entry of a declared artifact makes the operator's next `mur run` fail with
//! `E-RUN-003`, so a declared artifact is refused whatever its origin. The session record covers
//! a pull that matched an existing operator pin; the lock read covers `mur install` adopting the
//! pin while the session runs. Neither is scoped to this session: an undeclared runtime entry an
//! earlier session pulled, and this one pulled again, is removable. A hook or a driver is fixed at
//! launch and is refused on its role alone, whatever its origin: a policy hook vanishing
//! mid-session is privilege escalation, and a driver vanishing is fatal.
//!
//! Every refusal is a string beginning [`NOT_REMOVABLE`], or [`NOT_GRANTED`] for a capsule with
//! no `capabilities.install` or a name outside the artifact-name rule: the same token and
//! wording a pull refuses with. A refusal is a value the guest branches on, never a trap,
//! and is decided before anything changes. A name the session has not installed, including a
//! `shell.allow` binary `manage.list` shows, is `Ok(false)` rather than a refusal.
//!
//! # Order of effects
//!
//! After [`refuse_before_lock`] and [`refuse_against_lock`] pass, `remove_artifact` writes
//! `murmur.lock` without the entry, then updates the session (`tool_components`,
//! `native_entrypoints`, `allowlisted_tools`, `installed_artifacts`, `removed_artifacts`,
//! `installed_generation`), then deletes `<runtime dir>/tools/<name>/`. A lock write that fails
//! leaves everything unchanged. A directory that cannot be deleted is reported with
//! [`undeletable_directory`], and the name is already out of the session and the lock, so
//! dispatch refuses it. The compiled form under
//! `~/.murmur/compiled` is shared across sessions and kept, so pulling the same version again is
//! warm. A form nothing uses is deleted by the age-based prune in `compiled_forms`.
//!
//! # In-flight calls
//!
//! A pull and a remove take the session exclusively: both run on `&mut CapsuleStoreState`, and
//! every dispatch borrows that store for its whole duration, so no call of any tool is in flight
//! on it when either runs.
//!
//! - On the script path the guest is the only caller, and each host call returns before the next.
//! - The http agent loop runs a turn's calls one at a time, in the order the model listed them,
//!   awaiting each before it starts the next. A call listed before a `remove-artifact` completes
//!   on the artifact as it was; one listed after it is refused with [`called_after_removal`].
//! - The process-transport tool bridge and plan steps dispatch concurrently on a shared store and
//!   cannot reach either tool: the shared dispatch answers both names with an error and changes
//!   nothing, and `plan::validate_plan` refuses them as steps.
//! - A native tool's process never outlives its call, so no process of a removed tool runs on.
//!
//! An instance already built holds its own reference-counted `Component`; removal applies to
//! calls that start after it.
//!
//! # What the model and the guest see
//!
//! The removed name is recorded in `removed_artifacts`, and `invoke()` and the agent-loop dispatch
//! answer a call to it with [`called_after_removal`]. A native tool shadows a same-named
//! `shell.allow` binary, because the native branch dispatches first; removal hands the name back
//! to the shell branch, the state before the pull.
//!
//! Conversation history is never rewritten. Every earlier `tool_use` and `tool_result`, in the
//! history, the conversation record and the trace, records what happened, and rewriting them
//! would break the durable record and the prompt-cache prefix. A held tool array is not shrunk by
//! the removal itself: removal moves `installed_generation`, and the array drops the name at the
//! next rebuild, because the rebuild reads `<runtime dir>/tools/`. After the model's own
//! `remove-artifact` that is its next call; after `manage.remove` it is the boundary
//! `inference.tool_refresh` releases.
//!
//! No trace line records a removal, and the WIT signature `remove(name) -> result<bool, string>`
//! is unchanged.

use std::collections::HashSet;
use std::path::Path;

use murmur_artifact::{ArtifactName, ArtifactRuntime, LockOrigin, MurmurLock};

use crate::install_grant::{self, NOT_GRANTED};
use crate::types::{CapabilityPolicy, InstalledArtifactSummary};

/// The leading token of every refusal this module returns for an artifact the capsule may not
/// remove.
pub(crate) const NOT_REMOVABLE: &str = "not-removable:";

/// The refusal for removing `name` decided on session state alone, or the installed entry to go
/// on and check against `murmur.lock`. `Ok(None)` means the session has not installed `name` and
/// `remove` answers `Ok(false)`.
///
/// Checks, in order: the session holds an install grant; `name` is a full artifact name; the session
/// has installed `name`; it is not a hook or a driver; `murmur.yaml` does not declare it; the
/// session's record of its origin is runtime.
pub(crate) fn refuse_before_lock<'a>(
    policy: &CapabilityPolicy,
    name: &str,
    installed: &'a [InstalledArtifactSummary],
    declared: &HashSet<String>,
) -> Result<Option<&'a InstalledArtifactSummary>, String> {
    if !install_grant::is_granted(policy) {
        return Err(format!(
            "{NOT_GRANTED} this capsule declares no capabilities.install, so removing '{name}' is \
             refused"
        ));
    }
    if let Err(error) = ArtifactName::parse(name) {
        return Err(install_grant::name_refusal(&error));
    }
    let Some(summary) = installed.iter().find(|artifact| artifact.name == name) else {
        return Ok(None);
    };
    let fixed_role = match summary.runtime {
        ArtifactRuntime::Hook => Some("hook"),
        ArtifactRuntime::Driver => Some("driver"),
        ArtifactRuntime::Tool | ArtifactRuntime::Skill => None,
    };
    if let Some(role) = fixed_role {
        return Err(format!(
            "{NOT_REMOVABLE} '{name}' is a {role}; hooks and drivers are fixed at launch and \
             cannot be removed while the session runs"
        ));
    }
    if declared.contains(name) {
        return Err(format!(
            "{NOT_REMOVABLE} '{name}' is declared in murmur.yaml; an artifact the operator \
             declared stays for the life of the session"
        ));
    }
    if summary.origin == LockOrigin::Operator {
        return Err(operator_pinned(name));
    }
    Ok(Some(summary))
}

/// The refusal for removing `name` decided on `murmur.lock` as read at the moment of removal, or
/// `None` to remove it. A missing lock file is passed as a lock with no entries.
///
/// Refuses a missing entry, since then nothing records that the capsule pulled the artifact, and
/// an entry whose origin is operator.
pub(crate) fn refuse_against_lock(name: &str, lock: &MurmurLock) -> Option<String> {
    let Some(entry) = lock.artifact_for(name) else {
        return Some(format!(
            "{NOT_REMOVABLE} murmur.lock has no entry for '{name}', so nothing records that this \
             capsule pulled it"
        ));
    };
    (entry.origin == LockOrigin::Operator).then(|| operator_pinned(name))
}

/// What `invoke()` and the agent-loop dispatch return for a call to a name this session removed.
pub(crate) fn called_after_removal(name: &str) -> String {
    format!("tool '{name}' was removed from this session; it can no longer be called")
}

/// The error for a removal whose lock write and session update succeeded but whose directory
/// could not be deleted.
pub(crate) fn undeletable_directory(name: &str, dir: &Path, err: &std::io::Error) -> String {
    format!(
        "'{name}' is removed from this session and from murmur.lock, but {} could not be \
         deleted: {err}",
        dir.display()
    )
}

fn operator_pinned(name: &str) -> String {
    format!(
        "{NOT_REMOVABLE} murmur.lock pins '{name}' with origin: operator; only an artifact this \
         capsule pulled (origin: runtime) can be removed"
    )
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;
    use std::fs;
    use std::path::PathBuf;

    use murmur_artifact::{
        read_lockfile, write_lockfile_atomic, ArtifactImplementation, ArtifactRuntime, LockOrigin,
        LockedArtifact, LockedSha256, MurmurLock, LOCK_VERSION, PACKED_MANIFEST_ENTRY,
    };

    use murmur_artifact::tool_name_of;

    use super::*;
    use crate::agent::inventory::build_tool_inventory;
    use crate::bindings::host::murmur::{
        artifact_manager::manage, tool::run::ToolInput, tool_registry::invoke,
    };
    use crate::hooks::ResolvedCall;
    use crate::install_grant::{pull, tree, Project, VERSION};
    use crate::runtime::{cwasm_entries, scratch_compiled_dir, CapsuleStoreState};

    const SKILL: &str = "local/late-skill";
    /// The tool name `SKILL` is dispatched by.
    const SKILL_TOOL: &str = "late-skill";
    const SKILL_TEXT: &str = "# late guidance";

    /// Runs `artifact_removal::tests::<inner>` in a child process whose `HOME` is a fresh
    /// tempdir, so the compiled-form cache under `$HOME/.murmur/compiled` is a scratch one.
    fn under_scratch_home(inner: &str) {
        let home = tempfile::tempdir().unwrap();
        crate::murmur_home::run_with_home(
            &format!("artifact_removal::tests::{inner}"),
            home.path(),
        );
    }

    fn remove(state: &mut CapsuleStoreState, name: &str) -> Result<bool, String> {
        manage::Host::remove(state, name.to_string())
    }

    fn input() -> ToolInput {
        ToolInput {
            data: Some(r#"{"command":"--version"}"#.to_string()),
            log_path: None,
        }
    }

    fn listed(state: &mut CapsuleStoreState) -> Vec<String> {
        manage::Host::list(state)
            .into_iter()
            .map(|summary| summary.name)
            .collect()
    }

    fn lock_bytes(project: &Project) -> Option<Vec<u8>> {
        fs::read(&project.lock_path).ok()
    }

    /// Everything a removal can change: the workdir, the lock file and the session's record.
    #[derive(Debug, PartialEq)]
    struct Snapshot {
        tree: Vec<PathBuf>,
        lock: Option<Vec<u8>>,
        installed: Vec<InstalledArtifactSummary>,
        components: Vec<String>,
        removed: HashSet<String>,
        generation: u64,
    }

    fn snapshot(project: &Project, state: &CapsuleStoreState) -> Snapshot {
        let mut components: Vec<String> = state.tool_components.keys().cloned().collect();
        components.sort();
        Snapshot {
            tree: tree(&project.workdir),
            lock: lock_bytes(project),
            installed: state.installed_artifacts.clone(),
            components,
            removed: state.removed_artifacts.clone(),
            generation: state.installed_generation,
        }
    }

    async fn dispatch(state: &CapsuleStoreState, name: &str) -> Result<String, String> {
        state
            .dispatch_agent_tool_async(name, input(), None)
            .await
            .map(|outcome| outcome.result.data.unwrap_or_default())
    }

    /// Asserts that `state` and `project` hold no trace of `name`: no directory, no lock entry,
    /// no installed entry, not listed, not described.
    fn assert_gone(project: &Project, state: &mut CapsuleStoreState, name: &str) {
        assert!(!project.installed(name).exists());
        assert!(!project.locked(name));
        assert!(state.installed_artifacts.iter().all(|a| a.name != name));
        assert!(!listed(state).contains(&name.to_string()));
        let err = manage::Host::describe(state, name.to_string())
            .expect_err("a removed artifact is not described");
        assert!(err.contains("is not installed"), "{err}");
        assert!(state.removed_artifacts.contains(tool_name_of(name)));
    }

    fn summary(
        name: &str,
        runtime: ArtifactRuntime,
        origin: LockOrigin,
    ) -> InstalledArtifactSummary {
        InstalledArtifactSummary {
            name: name.to_string(),
            version: VERSION.to_string(),
            runtime,
            implementation: Some(ArtifactImplementation::Wasm),
            origin,
        }
    }

    fn runtime_origin(session: &str) -> LockOrigin {
        LockOrigin::Runtime {
            session: session.to_string(),
        }
    }

    /// Installs each of `artifacts` in `state` as staging would: a directory with its manifest, a
    /// `murmur.lock` entry of the same origin, and an installed entry.
    fn stage(
        project: &Project,
        state: &mut CapsuleStoreState,
        artifacts: &[InstalledArtifactSummary],
    ) {
        let mut lock = MurmurLock {
            lock_version: LOCK_VERSION,
            artifacts: Vec::new(),
        };
        for artifact in artifacts {
            let dir = project.installed(&artifact.name);
            fs::create_dir_all(&dir).unwrap();
            fs::write(
                dir.join(PACKED_MANIFEST_ENTRY),
                format!(
                    "name: {}\nversion: {VERSION}\nruntime: tool\n",
                    tool_name_of(&artifact.name)
                ),
            )
            .unwrap();
            lock.artifacts.push(LockedArtifact {
                name: artifact.name.clone(),
                resolved_version: VERSION.to_string(),
                sha256: LockedSha256::any("aaa"),
                origin: artifact.origin.clone(),
                owner_id: None,
            });
            state.installed_artifacts.push(artifact.clone());
        }
        write_lockfile_atomic(&project.lock_path, &lock).unwrap();
    }

    fn operator_pinned_refusal(name: &str) -> String {
        format!(
            "not-removable: murmur.lock pins '{name}' with origin: operator; only an artifact \
             this capsule pulled (origin: runtime) can be removed"
        )
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_pulled_skill_is_removed_from_every_place_it_was_installed() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).expect("a granted skill pulls");
        assert!(dispatch(&state, SKILL_TOOL)
            .await
            .unwrap()
            .contains(SKILL_TEXT));
        let generation = state.installed_generation;

        assert_eq!(remove(&mut state, SKILL), Ok(true));

        assert_gone(&project, &mut state, SKILL);
        assert_eq!(state.installed_generation, generation + 1);
    }

    #[test]
    fn a_pulled_wasm_tool_is_removed_and_its_component_dropped() {
        under_scratch_home("inner_a_pulled_wasm_tool_is_removed_and_its_component_dropped");
    }

    #[test]
    #[ignore = "run by a_pulled_wasm_tool_is_removed_and_its_component_dropped"]
    fn inner_a_pulled_wasm_tool_is_removed_and_its_component_dropped() {
        if !crate::murmur_home::in_scratch_home() {
            return;
        }
        let project = Project::new();
        project.publish_wasm_tool("local/wasm-tool");
        let mut state = project.session(&[], &["local/wasm-tool"]);
        pull(&mut state, "local/wasm-tool").expect("a granted WASM tool pulls");
        assert!(state.tool_components.contains_key("wasm-tool"));
        let sha256 = read_lockfile(&project.lock_path)
            .unwrap()
            .artifact_for("local/wasm-tool")
            .unwrap()
            .sha256
            .any
            .clone()
            .unwrap();

        assert_eq!(remove(&mut state, "local/wasm-tool"), Ok(true));

        assert_gone(&project, &mut state, "local/wasm-tool");
        assert!(!state.tool_components.contains_key("wasm-tool"));
        let forms = cwasm_entries(&scratch_compiled_dir());
        assert_eq!(forms.len(), 1, "{forms:?}");
        let form = forms[0].file_name().unwrap().to_string_lossy().into_owned();
        assert!(form.starts_with(&format!("{sha256}-")), "{form}");
    }

    #[test]
    fn a_pulled_native_tool_is_removed_and_its_binary_deleted() {
        let project = Project::new();
        project.publish_native_tool("local/native-tool");
        let mut state = project.session(&[], &["local/native-tool"]);
        pull(&mut state, "local/native-tool").expect("a granted native tool pulls");
        let binary = project.installed("local/native-tool").join("native-tool");
        assert!(binary.is_file());

        assert!(state.allowlisted_tools.contains("native-tool"));

        assert_eq!(remove(&mut state, "local/native-tool"), Ok(true));

        assert!(!binary.exists());
        assert!(
            !state.allowlisted_tools.contains("native-tool"),
            "a removal takes the pulled tool out of the dispatch allowlist"
        );
        assert!(!state.native_entrypoints.contains_key("native-tool"));
        assert_gone(&project, &mut state, "local/native-tool");
    }

    #[test]
    fn a_scoped_artifact_is_removed_by_its_full_name_and_refused_by_its_bare_one() {
        let project = Project::new();
        project.publish_native_tool("ana/tool-x");
        let mut state = project.session(&[], &["ana/tool-*"]);
        pull(&mut state, "ana/tool-x").expect("a granted scoped tool pulls");
        let dir = project.workdir.join("tools").join("tool-x");
        assert!(dir.is_dir());
        let before = snapshot(&project, &state);

        let err = remove(&mut state, "tool-x").expect_err("a bare name is refused");
        assert!(
            err.starts_with("not-granted: 'tool-x' is not a full artifact name"),
            "{err}"
        );
        assert!(err.contains("'local/tool-x'"), "{err}");
        assert_eq!(snapshot(&project, &state), before);

        assert_eq!(remove(&mut state, "ana/tool-x"), Ok(true));

        assert!(!dir.exists());
        assert!(read_lockfile(&project.lock_path)
            .unwrap()
            .artifact_for("ana/tool-x")
            .is_none());
        assert_gone(&project, &mut state, "ana/tool-x");
    }

    #[test]
    fn a_removed_artifact_cannot_be_called() {
        under_scratch_home("inner_a_removed_artifact_cannot_be_called");
    }

    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "run by a_removed_artifact_cannot_be_called"]
    async fn inner_a_removed_artifact_cannot_be_called() {
        if !crate::murmur_home::in_scratch_home() {
            return;
        }
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        project.publish_wasm_tool("local/wasm-tool");
        let mut state = project.session(&[SKILL], &["local/wasm-tool"]);
        pull(&mut state, SKILL).unwrap();
        pull(&mut state, "local/wasm-tool").unwrap();
        state.allowlisted_tools.insert("wasm-tool".to_string());

        for name in [SKILL, "local/wasm-tool"] {
            assert_eq!(remove(&mut state, name), Ok(true));
            let tool = tool_name_of(name);
            let refusal = format!(
                "tool '{tool}' was removed from this session; it can no longer \
                 be called"
            );
            assert_eq!(dispatch(&state, tool).await, Err(refusal.clone()));
            assert_eq!(
                invoke::Host::invoke(&mut state, tool.to_string(), input()).map(|_| ()),
                Err(refusal)
            );
        }
    }

    #[test]
    fn a_removed_artifact_is_absent_from_a_rebuilt_inventory() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let existing = project.installed("zzz-existing-tool");
        fs::create_dir_all(&existing).unwrap();
        fs::write(
            existing.join(PACKED_MANIFEST_ENTRY),
            "name: zzz-existing-tool\nversion: 1.0.0\nruntime: tool\n",
        )
        .unwrap();
        let mut state = project.session(&[SKILL], &[]);
        let names = |state: &CapsuleStoreState| -> Vec<String> {
            crate::agent::inventory::tool_names(&build_tool_inventory(
                &state.session_root,
                None,
                &state.installed_artifacts,
            ))
        };

        pull(&mut state, SKILL).unwrap();
        assert_eq!(names(&state), vec![SKILL_TOOL, "zzz-existing-tool"]);

        assert_eq!(remove(&mut state, SKILL), Ok(true));
        assert_eq!(names(&state), vec!["zzz-existing-tool"]);
    }

    #[test]
    fn a_shell_binary_shadowed_by_a_pulled_tool_is_reachable_again_after_removal() {
        let project = Project::new();
        project.publish_native_tool("local/shadow-tool");
        let mut state = project.session(&[], &["local/shadow-tool"]);
        state.capability_policy.shell_allow = vec!["shadow-tool".to_string()];

        pull(&mut state, "local/shadow-tool").unwrap();
        assert!(matches!(
            state.resolve_call("shadow-tool", &input()),
            ResolvedCall::Tool { .. }
        ));

        assert_eq!(remove(&mut state, "local/shadow-tool"), Ok(true));
        match state.resolve_call("shadow-tool", &input()) {
            ResolvedCall::Shell { argv, .. } => assert_eq!(argv, vec!["--version"]),
            ResolvedCall::Tool { .. } => panic!("the shell branch is reachable again"),
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_operator_pinned_artifact_cannot_be_removed() {
        let project = Project::new();
        let sha256 = project.publish_skill(SKILL, SKILL_TEXT);
        write_lockfile_atomic(
            &project.lock_path,
            &MurmurLock {
                lock_version: LOCK_VERSION,
                artifacts: vec![LockedArtifact {
                    name: SKILL.to_string(),
                    resolved_version: VERSION.to_string(),
                    sha256: LockedSha256::any(sha256),
                    origin: LockOrigin::Operator,
                    owner_id: None,
                }],
            },
        )
        .unwrap();
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).expect("a pull matching the operator pin succeeds");
        let before = snapshot(&project, &state);

        assert_eq!(
            remove(&mut state, SKILL),
            Err(operator_pinned_refusal(SKILL))
        );

        assert_eq!(snapshot(&project, &state), before);
        assert!(dispatch(&state, SKILL_TOOL)
            .await
            .unwrap()
            .contains(SKILL_TEXT));
    }

    #[test]
    fn an_artifact_declared_in_murmur_yaml_cannot_be_removed_whatever_its_pin_origin() {
        let project = Project::new();
        let mut state = project.session(&["*"], &["*"]);
        stage(
            &project,
            &mut state,
            &[
                summary("local/decl-op", ArtifactRuntime::Tool, LockOrigin::Operator),
                summary(
                    "local/decl-rt",
                    ArtifactRuntime::Tool,
                    runtime_origin("ses_prev"),
                ),
            ],
        );
        state.declared_artifacts = ["local/decl-op", "local/decl-rt"].map(String::from).into();
        let before = snapshot(&project, &state);

        for name in ["local/decl-op", "local/decl-rt"] {
            assert_eq!(
                remove(&mut state, name),
                Err(format!(
                    "not-removable: '{name}' is declared in murmur.yaml; an artifact the \
                     operator declared stays for the life of the session"
                ))
            );
        }
        assert_eq!(snapshot(&project, &state), before);
    }

    #[test]
    fn a_hook_or_driver_cannot_be_removed() {
        let project = Project::new();
        let mut state = project.session(&["*"], &["*"]);
        let cases = [
            (
                "local/decl-hook",
                ArtifactRuntime::Hook,
                LockOrigin::Operator,
                "hook",
            ),
            (
                "local/decl-driver",
                ArtifactRuntime::Driver,
                LockOrigin::Operator,
                "driver",
            ),
            (
                "local/rt-hook",
                ArtifactRuntime::Hook,
                runtime_origin("ses_test"),
                "hook",
            ),
            (
                "local/rt-driver",
                ArtifactRuntime::Driver,
                runtime_origin("ses_test"),
                "driver",
            ),
        ];
        let artifacts: Vec<_> = cases
            .iter()
            .map(|(name, runtime, origin, _)| summary(name, runtime.clone(), origin.clone()))
            .collect();
        stage(&project, &mut state, &artifacts);
        state.declared_artifacts = ["local/decl-hook", "local/decl-driver"]
            .map(String::from)
            .into();
        let before = snapshot(&project, &state);

        for (name, _, _, role) in cases {
            assert_eq!(
                remove(&mut state, name),
                Err(format!(
                    "not-removable: '{name}' is a {role}; hooks and drivers are fixed at launch \
                     and cannot be removed while the session runs"
                ))
            );
        }
        assert_eq!(snapshot(&project, &state), before);
    }

    #[test]
    fn a_capsule_without_an_install_grant_cannot_remove() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).unwrap();
        let granted = state.capability_policy.clone();

        state.capability_policy = CapabilityPolicy::default();
        let before = snapshot(&project, &state);
        assert_eq!(
            remove(&mut state, SKILL),
            Err(format!(
                "not-granted: this capsule declares no capabilities.install, so removing \
                 '{SKILL}' is refused"
            ))
        );
        assert_eq!(snapshot(&project, &state), before);

        state.capability_policy = granted;
        let err = remove(&mut state, "../x").expect_err("a path is not an artifact name");
        assert!(
            err.starts_with("not-granted: '../x' is not a valid artifact name: "),
            "{err}"
        );
        assert_eq!(snapshot(&project, &state), before);
    }

    #[test]
    fn removing_what_is_not_installed_changes_nothing() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let mut state = project.session(&[SKILL], &[]);
        state.capability_policy.shell_allow = vec!["some-binary".to_string()];
        pull(&mut state, SKILL).unwrap();
        assert!(listed(&mut state).contains(&"some-binary".to_string()));

        let before = snapshot(&project, &state);
        assert_eq!(remove(&mut state, "local/never-pulled"), Ok(false));
        assert_eq!(snapshot(&project, &state), before);
        // A shell binary has no full name, so `remove` refuses it as it refuses any bare name.
        let err = remove(&mut state, "some-binary").expect_err("a bare name is refused");
        assert!(
            err.starts_with("not-granted: 'some-binary' is not a full artifact name"),
            "{err}"
        );
        assert_eq!(snapshot(&project, &state), before);

        assert_eq!(remove(&mut state, SKILL), Ok(true));
        let before = snapshot(&project, &state);
        assert_eq!(remove(&mut state, SKILL), Ok(false));
        assert_eq!(snapshot(&project, &state), before);
    }

    #[test]
    fn the_lock_decides_at_removal_time() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).unwrap();
        let pulled = read_lockfile(&project.lock_path).unwrap();

        let mut adopted = pulled.clone();
        adopted.artifacts[0].origin = LockOrigin::Operator;
        write_lockfile_atomic(&project.lock_path, &adopted).unwrap();
        let before = snapshot(&project, &state);
        assert_eq!(
            remove(&mut state, SKILL),
            Err(operator_pinned_refusal(SKILL))
        );
        assert_eq!(snapshot(&project, &state), before);

        let mut dropped = pulled;
        dropped.remove(SKILL);
        write_lockfile_atomic(&project.lock_path, &dropped).unwrap();
        let before = snapshot(&project, &state);
        assert_eq!(
            remove(&mut state, SKILL),
            Err(format!(
                "not-removable: murmur.lock has no entry for '{SKILL}', so nothing records that \
                 this capsule pulled it"
            ))
        );
        assert_eq!(snapshot(&project, &state), before);
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_removed_runtime_artifact_can_be_pulled_again_at_another_version() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        project.publish_skill_at(SKILL, "2.0.0", "# second guidance");
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).unwrap();
        assert_eq!(remove(&mut state, SKILL), Ok(true));

        manage::Host::pull(&mut state, SKILL.to_string(), "2.0.0".to_string())
            .expect("a removed runtime artifact pulls again");

        let lock = read_lockfile(&project.lock_path).unwrap();
        let entry = lock.artifact_for(SKILL).unwrap();
        assert_eq!(entry.resolved_version, "2.0.0");
        assert_eq!(entry.origin, runtime_origin("ses_test"));
        let installed: Vec<_> = state
            .installed_artifacts
            .iter()
            .filter(|a| a.name == SKILL)
            .map(|a| a.version.as_str())
            .collect();
        assert_eq!(installed, vec!["2.0.0"]);
        assert!(!state.removed_artifacts.contains(SKILL_TOOL));
        assert!(dispatch(&state, SKILL_TOOL)
            .await
            .unwrap()
            .contains("# second guidance"));
    }

    fn set_mode(path: &Path, mode: u32) {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
    }

    /// Whether a new file can be created in `dir`. A read-only mode does not bind root.
    fn accepts_new_file(dir: &Path) -> bool {
        let probe = dir.join(".write-probe");
        let created = fs::write(&probe, b"").is_ok();
        let _ = fs::remove_file(&probe);
        created
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_failed_lock_write_changes_nothing_and_a_failed_deletion_still_refuses_calls() {
        let project = Project::new();
        project.publish_skill(SKILL, SKILL_TEXT);
        let mut state = project.session(&[SKILL], &[]);
        pull(&mut state, SKILL).unwrap();
        let root = project.lock_path.parent().unwrap().to_path_buf();
        let dir = project.installed(SKILL);

        // Root writes through a read-only mode, so neither failure can be provoked there.
        set_mode(&root, 0o555);
        if accepts_new_file(&root) {
            set_mode(&root, 0o755);
            return;
        }
        let before = snapshot(&project, &state);
        let write_failed = remove(&mut state, SKILL);
        set_mode(&root, 0o755);
        let err = write_failed.expect_err("the lock cannot be written");
        assert!(err.starts_with("failed to write murmur.lock: "), "{err}");
        assert_eq!(snapshot(&project, &state), before);
        assert!(dispatch(&state, SKILL_TOOL)
            .await
            .unwrap()
            .contains(SKILL_TEXT));

        set_mode(&dir, 0o555);
        let delete_failed = remove(&mut state, SKILL);
        set_mode(&dir, 0o755);
        let err = delete_failed.expect_err("the directory cannot be deleted");
        let prefix = format!(
            "'{SKILL}' is removed from this session and from murmur.lock, but {} could not be \
             deleted: ",
            dir.display()
        );
        assert!(err.starts_with(&prefix), "{err}");
        assert!(dir.join("skill.md").is_file());
        assert!(!project.locked(SKILL));
        assert!(state.installed_artifacts.iter().all(|a| a.name != SKILL));
        assert_eq!(
            dispatch(&state, SKILL_TOOL).await,
            Err(called_after_removal(SKILL_TOOL))
        );
    }
}