supercode-harness 0.4.17

The optional native Supercode 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
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! 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 supercode 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 supercode 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(())
}

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

    fn scratch(tag: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "supercode-orch22-{tag}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Every home pinned at an absent path, so a test can never reach a real
    /// harness install.
    fn homes(root: &Path) -> SkillHomes {
        let void = root.join("__absent__");
        SkillHomes {
            claude_code: void.clone(),
            codex: void.clone(),
            opencode: void.clone(),
            pi: void.clone(),
            hermes: void.clone(),
            openclaw: void.clone(),
            agents: void,
        }
    }

    fn write_package(root: &Path, dir_name: &str, front_name: &str) -> PathBuf {
        let dir = root.join(dir_name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("SKILL.md"),
            format!("---\nname: {front_name}\ndescription: a probe skill\nversion: 0.1.0\n---\n\nbody\n"),
        )
        .unwrap();
        dir
    }

    fn claude_mutation(root: &Path, cwd: &Path) -> SkillMutation {
        let mut homes = homes(root);
        homes.claude_code = root.join("claude_home");
        SkillMutation {
            harness: HarnessId::CLAUDE_CODE.into(),
            cwd: Some(cwd.to_path_buf()),
            homes,
            ..SkillMutation::default()
        }
    }

    #[test]
    fn the_directory_door_installs_and_removes_in_the_user_root() {
        let root = scratch("cc-user");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let source = write_package(&root, "probe-src", "orch22-probe");

        let mut mutation = claude_mutation(&root, &cwd);
        mutation.source = Some(source.to_string_lossy().into_owned());
        let installed = mutate_skill(SkillVerb::Install, &mutation).unwrap();
        assert_eq!(installed.name, "orch22-probe");
        let expected = root.join("claude_home/skills/orch22-probe");
        assert_eq!(
            installed.ran,
            format!("cp -R {} {}", source.display(), expected.display())
        );
        let row = installed.skill.expect("the loader's own row is returned");
        assert_eq!(row.scope, SkillScope::User);
        assert_eq!(row.location, expected);
        assert_eq!(row.version.as_deref(), Some("0.1.0"));
        assert!(expected.join("SKILL.md").is_file());

        let mut removal = claude_mutation(&root, &cwd);
        removal.name = Some("orch22-probe".into());
        let removed = mutate_skill(SkillVerb::Remove, &removal).unwrap();
        assert_eq!(removed.removed, Some(true));
        assert_eq!(removed.ran, format!("rm -r {}", expected.display()));
        assert!(!expected.exists());
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn the_project_scope_writes_the_working_tree_root() {
        let root = scratch("cc-project");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let source = write_package(&root, "probe-src", "tree-skill");

        let mut mutation = claude_mutation(&root, &cwd);
        mutation.source = Some(source.to_string_lossy().into_owned());
        mutation.scope = Some(SkillScope::Project);
        let installed = mutate_skill(SkillVerb::Install, &mutation).unwrap();
        let row = installed.skill.expect("row");
        assert_eq!(row.scope, SkillScope::Project);
        assert_eq!(row.location, cwd.join(".claude/skills/tree-skill"));

        let mut removal = claude_mutation(&root, &cwd);
        removal.name = Some("tree-skill".into());
        removal.scope = Some(SkillScope::Project);
        assert_eq!(
            mutate_skill(SkillVerb::Remove, &removal).unwrap().removed,
            Some(true)
        );
        assert!(!cwd.join(".claude/skills/tree-skill").exists());
        std::fs::remove_dir_all(&root).ok();
    }

    /// A package whose own frontmatter names a path is the escape this door
    /// has to refuse — the name comes from data, not from the caller.
    #[test]
    fn a_name_that_escapes_the_root_is_refused() {
        let root = scratch("escape");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let source = write_package(&root, "probe-src", "../../escaped");

        let mut mutation = claude_mutation(&root, &cwd);
        mutation.source = Some(source.to_string_lossy().into_owned());
        let error = mutate_skill(SkillVerb::Install, &mutation).unwrap_err();
        assert!(matches!(error, SkillControlError::Invalid(_)), "{error}");
        assert!(error.to_string().contains("path separator"), "{error}");
        assert!(!root.join("claude_home").exists());
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn a_source_without_a_manifest_is_refused() {
        let root = scratch("no-manifest");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let source = root.join("not-a-skill");
        std::fs::create_dir_all(&source).unwrap();
        std::fs::write(source.join("README.md"), "no frontmatter here").unwrap();

        let mut mutation = claude_mutation(&root, &cwd);
        mutation.source = Some(source.to_string_lossy().into_owned());
        let error = mutate_skill(SkillVerb::Install, &mutation).unwrap_err();
        assert!(matches!(error, SkillControlError::Invalid(_)), "{error}");
        assert!(error.to_string().contains("SKILL.md"), "{error}");
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn a_missing_source_directory_is_refused() {
        let root = scratch("missing");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let mut mutation = claude_mutation(&root, &cwd);
        mutation.source = Some(root.join("nowhere").to_string_lossy().into_owned());
        let error = mutate_skill(SkillVerb::Install, &mutation).unwrap_err();
        assert!(matches!(error, SkillControlError::Invalid(_)), "{error}");
        assert!(error.to_string().contains("not a directory"), "{error}");
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn removing_a_skill_the_loader_does_not_report_is_refused() {
        let root = scratch("absent-row");
        let cwd = root.join("tree");
        std::fs::create_dir_all(&cwd).unwrap();
        let mut removal = claude_mutation(&root, &cwd);
        removal.name = Some("never-installed".into());
        let error = mutate_skill(SkillVerb::Remove, &removal).unwrap_err();
        assert!(matches!(error, SkillControlError::Invalid(_)), "{error}");
        std::fs::remove_dir_all(&root).ok();
    }

    /// The pin's asymmetry, modeled rather than papered over.
    #[test]
    fn openclaw_refuses_remove_at_the_pin() {
        let error = mutate_skill(
            SkillVerb::Remove,
            &SkillMutation {
                harness: HarnessId::OPENCLAW.into(),
                name: Some("clawhub-demo".into()),
                ..SkillMutation::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(error, SkillControlError::Unsupported(_)),
            "{error}"
        );
        assert!(
            error.to_string().contains("no `skills remove` verb"),
            "{error}"
        );
    }

    #[test]
    fn supercode_has_no_skills_root_of_its_own() {
        let error = mutate_skill(
            SkillVerb::Install,
            &SkillMutation {
                harness: HarnessId::SUPERCODE.into(),
                source: Some("/tmp/whatever".into()),
                ..SkillMutation::default()
            },
        )
        .unwrap_err();
        assert!(
            matches!(error, SkillControlError::Unsupported(_)),
            "{error}"
        );
        assert!(error.to_string().contains("no skills root"), "{error}");
    }

    #[test]
    fn hermes_refuses_a_local_directory_and_a_project_scope() {
        let root = scratch("hermes-refusals");
        let source = write_package(&root, "probe-src", "local-only");
        let mut mutation = SkillMutation {
            harness: HarnessId::HERMES.into(),
            source: Some(source.to_string_lossy().into_owned()),
            homes: homes(&root),
            ..SkillMutation::default()
        };
        let error = mutate_skill(SkillVerb::Install, &mutation).unwrap_err();
        assert!(
            matches!(error, SkillControlError::Unsupported(_)),
            "{error}"
        );
        assert!(error.to_string().contains("registry identifier"), "{error}");

        mutation.scope = Some(SkillScope::Project);
        let error = mutate_skill(SkillVerb::Install, &mutation).unwrap_err();
        assert!(
            matches!(error, SkillControlError::Unsupported(_)),
            "{error}"
        );
        assert!(error.to_string().contains("project-scoped"), "{error}");
        std::fs::remove_dir_all(&root).ok();
    }

    /// The narration is the harness's own argv, and HERMES_HOME points at the
    /// home the caller addressed — never this machine's real one.
    #[test]
    fn hermes_translates_onto_its_own_verb() {
        let root = scratch("hermes-argv");
        let mut homes = homes(&root);
        homes.hermes = root.join("hermes_home");
        let mutation = SkillMutation {
            harness: HarnessId::HERMES.into(),
            name: Some("arxiv-search".into()),
            source: Some("openai/skills/arxiv-search".into()),
            homes,
            ..SkillMutation::default()
        };
        let install = hermes_command(SkillVerb::Install, &mutation, SkillScope::User).unwrap();
        assert_eq!(
            install.narrate(),
            "hermes skills install --yes --name arxiv-search openai/skills/arxiv-search"
        );
        assert_eq!(
            install.env,
            vec![(
                "HERMES_HOME".to_string(),
                root.join("hermes_home").to_string_lossy().into_owned()
            )]
        );
        let remove = hermes_command(SkillVerb::Remove, &mutation, SkillScope::User).unwrap();
        assert_eq!(
            remove.narrate(),
            "hermes skills uninstall arxiv-search --yes"
        );
        std::fs::remove_dir_all(&root).ok();
    }

    /// OpenClaw's install argv, with the isolated state dir it must never
    /// step outside of.
    #[test]
    fn openclaw_translates_onto_its_own_verb() {
        let root = scratch("openclaw-argv");
        let mut homes = homes(&root);
        homes.openclaw = root.join("openclaw_home");
        let mutation = SkillMutation {
            harness: HarnessId::OPENCLAW.into(),
            source: Some(root.join("probe-src").to_string_lossy().into_owned()),
            homes,
            ..SkillMutation::default()
        };
        let global = openclaw_command(SkillVerb::Install, &mutation, SkillScope::User).unwrap();
        assert_eq!(
            global.narrate(),
            format!(
                "openclaw skills install {} --global",
                root.join("probe-src").display()
            )
        );
        assert_eq!(
            global.env,
            vec![
                (
                    "OPENCLAW_STATE_DIR".to_string(),
                    root.join("openclaw_home").to_string_lossy().into_owned()
                ),
                (
                    "OPENCLAW_CONFIG_PATH".to_string(),
                    root.join("openclaw_home/openclaw.json")
                        .to_string_lossy()
                        .into_owned()
                ),
            ]
        );
        let workspace =
            openclaw_command(SkillVerb::Install, &mutation, SkillScope::Project).unwrap();
        assert!(!workspace.narrate().contains("--global"), "{workspace:?}");
        std::fs::remove_dir_all(&root).ok();
    }
}