supercode-harness 0.5.45

The optional native Volter Harness agent and tool harness
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
//! Controlled-tier skills (Domain 11, concept 15) — `install` and `remove`,
//! each through the door the harness itself publishes.
//!
//! Charter (`docs/plans/orchestration-domain-11-2026-09-02.md` §0.4):
//! supercode never runs a skill registry, never resolves a slug, never
//! unpacks an archive. Every mutation is the harness's own door:
//!
//! * **Hermes** — `hermes skills install <identifier> --yes` /
//!   `hermes skills uninstall <name> --yes`, with `HERMES_HOME` in the
//!   environment. The pinned help (`parity/fixtures/hermes-help.txt`,
//!   re-checked against the installed 0.21.0) says the positional is a
//!   registry identifier or a direct HTTP(S) URL to a `SKILL.md`; hermes
//!   publishes NO local-directory install form, so a local path is refused
//!   rather than handed to a verb that cannot take it.
//! * **OpenClaw** — `openclaw skills install <skill-ref>` (`@owner/slug`,
//!   `git:<repo>`, or a local skill directory; `--global` for the shared
//!   managed directory, `--as <slug>` to name it). At the pin there is NO
//!   `openclaw skills remove`, so `remove` is refused with
//!   `UnsupportedAction` — supercode does not delete files behind the
//!   harness's back.
//! * **Claude Code, Codex, opencode, pi** — the door IS the directory. These
//!   four have no skills CLI at all; a skill is installed by placing its
//!   package at the root the harness's own loader reads
//!   (`crate::skills::writable_skill_roots`, transcribed from the same
//!   inventories ORCH-11 reads), and removed by deleting that directory.
//!   Both operations are confined to those roots: a name that would escape
//!   one, or a package the loader does not recognize, is refused.
//! * **supercode itself** — refused: it has no skills root of its own
//!   (`crate::skills::SKILL_HARNESSES` names the six harnesses it reads).
//!
//! The three ORCH-18 rules are inherited verbatim:
//!
//! 1. **The harness's answer is the answer.** After the door succeeds the row
//!    is re-read through the ORCH-11 loader ([`crate::skills::list_skills`])
//!    and returned; a `remove` that leaves the row behind is a failure. Note
//!    that `hermes skills install` exits 0 on a fetch failure, so the re-read
//!    — not the exit status — is what decides.
//! 2. **The door is narrated.** Every outcome carries `ran`: the harness
//!    command that was executed, or the directory operation in its shell
//!    spelling (`cp -R <source> <dest>`, `rm -r <dest>`).
//! 3. **A door the harness does not have is refused**
//!    ([`SkillControlError::Unsupported`] → `UnsupportedAction`), never a
//!    silent no-op and never a file supercode writes on its own authority.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::jobs_control::{harness_program, shell_quote, HarnessCommand, JobControlError};
use crate::skills::{
    declared_skill_name, list_skills, skill_roots, writable_skill_roots, SkillHomes, SkillRow,
    SkillScope, SkillsQuery, SKILL_HARNESSES,
};
use crate::HarnessId;

/// Harnesses whose installed skills supercode can MUTATE through a door the
/// harness publishes. Identical to [`SKILL_HARNESSES`] today: the two CLI
/// harnesses have a verb, the core four have their loader's directory.
pub const CONTROLLED_SKILL_HARNESSES: &[&str] = SKILL_HARNESSES;

/// Why supercode refuses to install a skill into itself.
pub const SUPERCODE_REFUSAL: &str =
    "supercode has no skills root of its own: its skill surface is the SIX harnesses it reads \
     (`skills.list`), so there is nothing here to install into. Name the harness whose root the \
     package belongs in";

/// Why `remove` is refused on OpenClaw at the pinned version.
pub const OPENCLAW_REMOVE_REFUSAL: &str =
    "openclaw 2026.7.1-2 publishes no `skills remove` verb (`openclaw skills` has \
     search|install|update|verify|curator|workshop|list|info|check). supercode refuses rather \
     than deleting files out of the harness's managed directory behind its back";

/// One uniform mutating verb.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SkillVerb {
    /// Place a skill package where the harness's loader reads it.
    Install,
    /// Take a skill package back out.
    Remove,
}

impl SkillVerb {
    /// Uniform spelling used in the RPC method and in outcomes.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Install => "install",
            Self::Remove => "remove",
        }
    }
}

/// One mutating request, in the uniform Domain 11 vocabulary.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillMutation {
    /// Harness whose root the package belongs in.
    pub harness: String,
    /// Skill name. Required by `remove`; on `install` it overrides the name
    /// the package declares (`hermes --name`, `openclaw --as`, the directory
    /// name for the core four).
    pub name: Option<String>,
    /// What to install: a local skill directory, or — where the harness's own
    /// verb accepts one — its registry identifier / URL.
    pub source: Option<String>,
    /// Which root class to act in. `user` (the default) or `project`.
    pub scope: Option<SkillScope>,
    /// Working tree whose project roots are addressed. Defaults to the
    /// process working directory, exactly as `skills.list` does.
    pub cwd: Option<PathBuf>,
    /// Config homes, so an isolated home is addressed the same way the read
    /// side addresses it.
    pub homes: SkillHomes,
}

/// What one mutation did, with the harness's own row read back afterwards.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillMutationOutcome {
    /// Harness that owns the root.
    pub harness: String,
    /// Uniform verb that was asked for.
    pub verb: String,
    /// The harness command, or the directory operation, that was performed.
    pub ran: String,
    /// Affected skill name.
    pub name: String,
    /// The skill as the ORCH-11 loader reports it AFTER the verb. Absent for
    /// `remove`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skill: Option<SkillRow>,
    /// `true` on a successful `remove`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub removed: Option<bool>,
}

/// Why a mutation could not be performed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SkillControlError {
    /// The harness has no door for what was asked (refused, never faked).
    Unsupported(String),
    /// The request itself is incoherent.
    Invalid(String),
    /// The door was opened and failed; the message carries what it said.
    Failed(String),
}

impl std::fmt::Display for SkillControlError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Unsupported(message) | Self::Invalid(message) | Self::Failed(message) => {
                formatter.write_str(message)
            }
        }
    }
}

impl std::error::Error for SkillControlError {}

impl From<JobControlError> for SkillControlError {
    fn from(error: JobControlError) -> Self {
        match error {
            JobControlError::Unsupported(message) => Self::Unsupported(message),
            JobControlError::Invalid(message) => Self::Invalid(message),
            JobControlError::Failed(message) => Self::Failed(message),
        }
    }
}

type Result<T> = std::result::Result<T, SkillControlError>;

/// Whether `harness` has any skills door supercode can drive.
pub fn supports_skill_control(harness: &str) -> bool {
    CONTROLLED_SKILL_HARNESSES.contains(&harness)
}

fn unsupported_harness(harness: &str) -> String {
    if harness == HarnessId::SUPERCODE {
        return SUPERCODE_REFUSAL.to_string();
    }
    format!(
        "`{harness}` has no skills root Volter Harness reads; skills verbs are supported for: {}",
        CONTROLLED_SKILL_HARNESSES.join(", ")
    )
}

/// Perform one mutation through the harness's own door, then re-read the row.
pub fn mutate_skill(verb: SkillVerb, mutation: &SkillMutation) -> Result<SkillMutationOutcome> {
    if !supports_skill_control(&mutation.harness) {
        return Err(SkillControlError::Unsupported(unsupported_harness(
            &mutation.harness,
        )));
    }
    let scope = mutation.scope.unwrap_or(SkillScope::User);
    if !matches!(scope, SkillScope::User | SkillScope::Project) {
        return Err(SkillControlError::Invalid(format!(
            "`{}` is a root the harness owns, not one a client may write; use user or project",
            scope.as_str()
        )));
    }
    match mutation.harness.as_str() {
        HarnessId::HERMES => hermes(verb, mutation, scope),
        HarnessId::OPENCLAW => openclaw(verb, mutation, scope),
        _ => directory(verb, mutation, scope),
    }
}

// ---------------------------------------------------------------------------
// Shared: re-reading through the ORCH-11 loader
// ---------------------------------------------------------------------------

fn cwd_of(mutation: &SkillMutation) -> PathBuf {
    mutation
        .cwd
        .clone()
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_else(|| PathBuf::from("."))
}

/// Every skill the harness's own loader reports right now.
fn read_rows(mutation: &SkillMutation) -> Vec<SkillRow> {
    list_skills(&SkillsQuery {
        harness: Some(mutation.harness.clone()),
        scope: None,
        cwd: Some(cwd_of(mutation)),
        homes: mutation.homes.clone(),
    })
}

fn read_names(mutation: &SkillMutation) -> BTreeSet<String> {
    read_rows(mutation)
        .into_iter()
        .map(|row| row.name)
        .collect()
}

fn find_by_name(mutation: &SkillMutation, name: &str) -> Option<SkillRow> {
    read_rows(mutation).into_iter().find(|row| row.name == name)
}

fn find_at(mutation: &SkillMutation, location: &Path) -> Option<SkillRow> {
    read_rows(mutation)
        .into_iter()
        .find(|row| row.location == location)
}

fn require_source(mutation: &SkillMutation) -> Result<&str> {
    mutation
        .source
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            SkillControlError::Invalid(
                "`skills.install` needs a `source`: a local skill directory, or the identifier \
                 the harness's own install verb accepts"
                    .into(),
            )
        })
}

fn require_name(mutation: &SkillMutation) -> Result<&str> {
    mutation
        .name
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            SkillControlError::Invalid("`skills.remove` needs the skill `name` to remove".into())
        })
}

/// A skill name that can only ever address one directory INSIDE a root.
///
/// This is the containment gate for the directory door: the name comes from a
/// package's own frontmatter, so `../…`, an absolute path, or a separator in
/// it would otherwise write outside the root the harness reads.
fn validate_name(name: &str) -> Result<&str> {
    let trimmed = name.trim();
    let rejected = trimmed.is_empty()
        || trimmed == "."
        || trimmed == ".."
        || trimmed.starts_with('.')
        || trimmed.contains('/')
        || trimmed.contains('\\')
        || trimmed.contains('\0')
        || Path::new(trimmed).components().count() != 1;
    if rejected {
        return Err(SkillControlError::Invalid(format!(
            "`{name}` is not a skill name: a skill is one directory inside the harness's own \
             root, so a name may not be empty, hidden, or contain a path separator"
        )));
    }
    Ok(trimmed)
}

// ---------------------------------------------------------------------------
// Hermes — `hermes skills install | uninstall` over HERMES_HOME
// ---------------------------------------------------------------------------

/// Hermes's own argv for one verb, ready to run and ready to narrate.
fn hermes_command(
    verb: SkillVerb,
    mutation: &SkillMutation,
    scope: SkillScope,
) -> Result<HarnessCommand> {
    if scope != SkillScope::User {
        return Err(SkillControlError::Unsupported(
            "hermes keeps skills in one root per HERMES_HOME (`<HERMES_HOME>/skills`, and a \
             profile IS a HERMES_HOME); it has no project-scoped skills root, so supercode \
             refuses rather than inventing one"
                .into(),
        ));
    }
    let mut command = HarnessCommand::new(harness_program(HarnessId::HERMES)?);
    command.env("HERMES_HOME", mutation.homes.hermes.to_string_lossy());
    command.arg("skills");
    match verb {
        SkillVerb::Install => {
            let source = require_source(mutation)?;
            if Path::new(source).is_dir() {
                return Err(SkillControlError::Unsupported(format!(
                    "`hermes skills install` takes a registry identifier (`owner/repo/skills/x`) \
                     or a direct HTTP(S) URL to a SKILL.md — its pinned help enumerates no \
                     local-directory form, so `{source}` cannot be handed to it. Serve the \
                     package's SKILL.md over HTTP, or install it into a harness whose door is the \
                     directory"
                )));
            }
            command.args(["install", "--yes"]);
            if let Some(name) = trimmed_name(mutation) {
                command.args(["--name", name]);
            }
            command.arg(source);
        }
        SkillVerb::Remove => {
            command.args(["uninstall", require_name(mutation)?, "--yes"]);
        }
    }
    Ok(command)
}

fn hermes(
    verb: SkillVerb,
    mutation: &SkillMutation,
    scope: SkillScope,
) -> Result<SkillMutationOutcome> {
    let command = hermes_command(verb, mutation, scope)?;
    run_and_reread(verb, mutation, command)
}

/// Run one CLI door, then let the ORCH-11 loader answer for what it did.
///
/// `hermes skills install` prints a failed fetch and still exits 0, so the
/// harness's own root — never the exit status alone — decides.
fn run_and_reread(
    verb: SkillVerb,
    mutation: &SkillMutation,
    command: HarnessCommand,
) -> Result<SkillMutationOutcome> {
    let ran = command.narrate();
    match verb {
        SkillVerb::Install => {
            let before = read_names(mutation);
            command.run().map_err(SkillControlError::Failed)?;
            let name = installed_name(mutation, &before, trimmed_name(mutation), &ran)?;
            let skill = find_by_name(mutation, &name).ok_or_else(|| {
                SkillControlError::Failed(format!(
                    "`{ran}` exited 0 but {}'s skills roots hold no `{name}` afterwards",
                    mutation.harness
                ))
            })?;
            Ok(SkillMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                name,
                skill: Some(skill),
                removed: None,
            })
        }
        SkillVerb::Remove => {
            let name = require_name(mutation)?.to_string();
            command.run().map_err(SkillControlError::Failed)?;
            refuse_if_still_present(mutation, &name, &ran)?;
            Ok(SkillMutationOutcome {
                harness: mutation.harness.clone(),
                verb: verb.as_str().to_string(),
                ran,
                name,
                skill: None,
                removed: Some(true),
            })
        }
    }
}

fn trimmed_name(mutation: &SkillMutation) -> Option<&str> {
    mutation
        .name
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
}

/// Which skill a CLI install verb actually landed: the name the harness's own
/// root GAINED. A caller-supplied name decides between several.
fn installed_name(
    mutation: &SkillMutation,
    before: &BTreeSet<String>,
    requested: Option<&str>,
    ran: &str,
) -> Result<String> {
    let after = read_names(mutation);
    let mut fresh: Vec<String> = after.difference(before).cloned().collect();
    if fresh.len() == 1 {
        return Ok(fresh.remove(0));
    }
    if let Some(name) = requested {
        if after.contains(name) {
            return Ok(name.to_string());
        }
    }
    Err(SkillControlError::Failed(format!(
        "`{ran}` exited 0 but {}'s skills root gained {} skill(s), so the installed skill cannot \
         be identified — pass `name` to say which one it should be",
        mutation.harness,
        fresh.len()
    )))
}

fn refuse_if_still_present(mutation: &SkillMutation, name: &str, ran: &str) -> Result<()> {
    match find_by_name(mutation, name) {
        Some(row) => Err(SkillControlError::Failed(format!(
            "`{ran}` reported success but `{name}` is still installed at {}",
            row.location.display()
        ))),
        None => Ok(()),
    }
}

// ---------------------------------------------------------------------------
// OpenClaw — `openclaw skills install`; no remove verb at the pin
// ---------------------------------------------------------------------------

/// OpenClaw's own argv. `remove` never reaches the runner: the pin has no verb.
fn openclaw_command(
    verb: SkillVerb,
    mutation: &SkillMutation,
    scope: SkillScope,
) -> Result<HarnessCommand> {
    if matches!(verb, SkillVerb::Remove) {
        return Err(SkillControlError::Unsupported(
            OPENCLAW_REMOVE_REFUSAL.to_string(),
        ));
    }
    let source = require_source(mutation)?;
    let mut command = HarnessCommand::new(harness_program(HarnessId::OPENCLAW)?);
    // The same environment contract the read side and `jobs_control` use:
    // `OPENCLAW_STATE_DIR` names the state dir, `OPENCLAW_CONFIG_PATH` the
    // config file inside it, so an isolated home stays isolated.
    command.env(
        "OPENCLAW_STATE_DIR",
        mutation.homes.openclaw.to_string_lossy(),
    );
    command.env(
        "OPENCLAW_CONFIG_PATH",
        mutation
            .homes
            .openclaw
            .join("openclaw.json")
            .to_string_lossy(),
    );
    command.args(["skills", "install", source]);
    // OpenClaw's own two destinations: the shared managed directory, or the
    // agent workspace. `user` is the shared one; `project` is the workspace
    // the CLI infers, which is also where the ORCH-11 loader reads it from.
    if scope == SkillScope::User {
        command.arg("--global");
    }
    if let Some(name) = trimmed_name(mutation) {
        command.args(["--as", name]);
    }
    Ok(command)
}

fn openclaw(
    verb: SkillVerb,
    mutation: &SkillMutation,
    scope: SkillScope,
) -> Result<SkillMutationOutcome> {
    let command = openclaw_command(verb, mutation, scope)?;
    run_and_reread(verb, mutation, command)
}

// ---------------------------------------------------------------------------
// Claude Code, Codex, opencode, pi — the door IS the directory
// ---------------------------------------------------------------------------

fn directory(
    verb: SkillVerb,
    mutation: &SkillMutation,
    scope: SkillScope,
) -> Result<SkillMutationOutcome> {
    let cwd = cwd_of(mutation);
    let roots = writable_skill_roots(&mutation.harness, scope, &mutation.homes, &cwd);
    if roots.is_empty() {
        return Err(SkillControlError::Unsupported(format!(
            "`{}` has no {} skills root Volter Harness may write; its inventory names none",
            mutation.harness,
            scope.as_str()
        )));
    }
    match verb {
        SkillVerb::Install => directory_install(mutation, scope, &roots),
        SkillVerb::Remove => directory_remove(mutation, scope, &roots, &cwd),
    }
}

fn directory_install(
    mutation: &SkillMutation,
    scope: SkillScope,
    roots: &[PathBuf],
) -> Result<SkillMutationOutcome> {
    let source = PathBuf::from(require_source(mutation)?);
    if !source.is_dir() {
        return Err(SkillControlError::Invalid(format!(
            "`{}` is not a directory: `{}`'s skills door is its loader's own root, so the source \
             must be the skill PACKAGE — a directory holding SKILL.md",
            source.display(),
            mutation.harness
        )));
    }
    let declared = declared_skill_name(&source).ok_or_else(|| {
        SkillControlError::Invalid(format!(
            "`{}` holds no SKILL.md, so it is not a skill package the harness's loader would \
             read",
            source.display()
        ))
    })?;
    let requested = mutation
        .name
        .as_deref()
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .unwrap_or(declared.as_str());
    let name = validate_name(requested)?.to_string();
    let root = &roots[0];
    let destination = root.join(&name);
    if destination.exists() {
        return Err(SkillControlError::Invalid(format!(
            "`{name}` is already installed at {}; remove it first",
            destination.display()
        )));
    }
    std::fs::create_dir_all(root).map_err(|error| {
        SkillControlError::Failed(format!(
            "{}'s {} skills root {} could not be created: {error}",
            mutation.harness,
            scope.as_str(),
            root.display()
        ))
    })?;
    contained_in(&destination, std::slice::from_ref(root))?;
    let ran = format!(
        "cp -R {} {}",
        shell_quote(&source.to_string_lossy()),
        shell_quote(&destination.to_string_lossy())
    );
    if let Err(error) = copy_package(&source, &destination) {
        // Never leave half a package where the loader would read it.
        let _ = std::fs::remove_dir_all(&destination);
        return Err(error);
    }
    let skill = find_at(mutation, &destination).ok_or_else(|| {
        SkillControlError::Failed(format!(
            "`{ran}` succeeded but {}'s loader does not report a skill at {}",
            mutation.harness,
            destination.display()
        ))
    })?;
    Ok(SkillMutationOutcome {
        harness: mutation.harness.clone(),
        verb: SkillVerb::Install.as_str().to_string(),
        ran,
        name: skill.name.clone(),
        skill: Some(skill),
        removed: None,
    })
}

fn directory_remove(
    mutation: &SkillMutation,
    scope: SkillScope,
    writable: &[PathBuf],
    cwd: &Path,
) -> Result<SkillMutationOutcome> {
    let name = validate_name(require_name(mutation)?)?.to_string();
    let matches: Vec<SkillRow> = read_rows(mutation)
        .into_iter()
        .filter(|row| row.name == name && row.scope == scope)
        .collect();
    let row = match matches.len() {
        0 => {
            return Err(SkillControlError::Invalid(format!(
                "`{}` has no {} skill `{name}`",
                mutation.harness,
                scope.as_str()
            )))
        }
        1 => matches.into_iter().next().expect("one match"),
        _ => {
            return Err(SkillControlError::Invalid(format!(
                "`{}` reports {} skills named `{name}` in its {} roots ({}); supercode refuses to \
                 guess which one to delete",
                mutation.harness,
                matches.len(),
                scope.as_str(),
                matches
                    .iter()
                    .map(|row| row.location.display().to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            )))
        }
    };
    // Containment: the package must sit directly under a root this harness's
    // own loader consults, writable or already-existing.
    let mut recognized: Vec<PathBuf> = writable.to_vec();
    recognized.extend(
        skill_roots(&mutation.harness, &mutation.homes, cwd)
            .into_iter()
            .filter(|(found, _)| *found == scope)
            .map(|(_, root)| root),
    );
    contained_in(&row.location, &recognized)?;
    if !row.location.join("SKILL.md").is_file() {
        return Err(SkillControlError::Invalid(format!(
            "{} holds no SKILL.md; supercode removes skill PACKAGES, never a directory it cannot \
             identify as one",
            row.location.display()
        )));
    }
    let ran = format!("rm -r {}", shell_quote(&row.location.to_string_lossy()));
    std::fs::remove_dir_all(&row.location)
        .map_err(|error| SkillControlError::Failed(format!("`{ran}` failed: {error}")))?;
    refuse_if_still_present(mutation, &name, &ran)?;
    Ok(SkillMutationOutcome {
        harness: mutation.harness.clone(),
        verb: SkillVerb::Remove.as_str().to_string(),
        ran,
        name,
        skill: None,
        removed: Some(true),
    })
}

/// Refuse any path that is not a DIRECT child of one of `roots`.
///
/// Both sides are canonicalized as far as they exist, so a symlinked home
/// (`/tmp` → `/private/tmp` on macOS) and a `..` inside the path are compared
/// the same way the filesystem would resolve them.
fn contained_in(path: &Path, roots: &[PathBuf]) -> Result<()> {
    let resolved = resolve(path);
    for root in roots {
        let root = resolve(root);
        if resolved.parent() == Some(root.as_path()) {
            return Ok(());
        }
    }
    Err(SkillControlError::Invalid(format!(
        "{} is outside the skills roots supercode recognizes ({}); every install and removal \
         stays inside the harness's own root",
        path.display(),
        roots
            .iter()
            .map(|root| root.display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    )))
}

/// Canonicalize the longest existing prefix and re-attach the rest, so a
/// destination that does not exist yet still compares against a real root.
fn resolve(path: &Path) -> PathBuf {
    if let Ok(canonical) = path.canonicalize() {
        return canonical;
    }
    match (path.parent(), path.file_name()) {
        (Some(parent), Some(name)) => resolve(parent).join(name),
        _ => path.to_path_buf(),
    }
}

/// Copy a skill package. Regular files and directories only: a symlink could
/// point anywhere, so it is refused rather than followed or silently dropped.
fn copy_package(source: &Path, destination: &Path) -> Result<()> {
    std::fs::create_dir_all(destination).map_err(|error| {
        SkillControlError::Failed(format!(
            "{} could not be created: {error}",
            destination.display()
        ))
    })?;
    let entries = std::fs::read_dir(source).map_err(|error| {
        SkillControlError::Failed(format!("{} could not be read: {error}", source.display()))
    })?;
    for entry in entries {
        let entry = entry.map_err(|error| {
            SkillControlError::Failed(format!("{} could not be read: {error}", source.display()))
        })?;
        let from = entry.path();
        let kind = std::fs::symlink_metadata(&from).map_err(|error| {
            SkillControlError::Failed(format!("{} could not be read: {error}", from.display()))
        })?;
        let to = destination.join(entry.file_name());
        if kind.is_symlink() {
            return Err(SkillControlError::Invalid(format!(
                "{} is a symlink; supercode copies a skill package's own files only, so a link \
                 that could point outside it is refused",
                from.display()
            )));
        }
        if kind.is_dir() {
            copy_package(&from, &to)?;
        } else if kind.is_file() {
            std::fs::copy(&from, &to).map_err(|error| {
                SkillControlError::Failed(format!(
                    "{} could not be copied to {}: {error}",
                    from.display(),
                    to.display()
                ))
            })?;
        } else {
            return Err(SkillControlError::Invalid(format!(
                "{} is neither a file nor a directory; a skill package holds only its own files",
                from.display()
            )));
        }
    }
    Ok(())
}