Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions hermes_cli/skills_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,42 @@ def _is_valid_installed_skill_name(name: str) -> bool:
return bool(_VALID_NAME_RE.match(candidate))


def _untracked_skill_dir(name: str, category: str) -> Optional[Path]:
"""Return the install directory when it already holds an untracked skill.

``do_install``'s collision check reads the hub lock file, which only knows
about hub-installed skills. ``install_from_quarantine`` nonetheless calls
``shutil.rmtree`` on whatever sits at the install path, and its own comment
justifies that by pointing at "the lock-file check in ``do_install()``" --
a guarantee that does not hold for a skill with no lock entry. Locally
authored skills and bundled skills the user has edited are exactly that
population.

Resolve the directory ``install_from_quarantine`` would delete, using that
function's own validators so the two agree on the target, and report it
when it is an existing skill directory (one that directly contains
``SKILL.md``). Return ``None`` when nothing is there, when it is a category
bucket, or when the name/category is malformed -- those cases are already
refused downstream with actionable errors, and pre-empting them here would
only change the message the user sees.
"""
from tools.skills_hub import (
_resolve_lock_install_path,
_validate_install_parent_path,
_validate_skill_name,
)

try:
safe_name = _validate_skill_name(name)
safe_category = _validate_install_parent_path(category) if category else ""
install_rel_path = f"{safe_category}/{safe_name}" if safe_category else safe_name
install_dir = _resolve_lock_install_path(install_rel_path, safe_name)
except ValueError:
return None

return install_dir if (install_dir / "SKILL.md").is_file() else None


def _existing_categories() -> List[str]:
"""Return sorted subdirectory names under ``~/.hermes/skills/`` that look
like category buckets (contain at least one ``SKILL.md`` somewhere below).
Expand Down Expand Up @@ -633,6 +669,25 @@ def do_install(identifier: str, category: str = "", force: bool = False,
c.print("Use --force to reinstall.\n")
return

# The lock file only tracks hub-installed skills, so the check above cannot
# see a locally authored or user-edited skill sitting at the install path --
# yet install_from_quarantine() rmtrees it all the same. Consult the
# filesystem too, so an untracked skill gets the same "use --force" consent
# gate a hub-installed one already gets.
if not existing and not force:
untracked = _untracked_skill_dir(bundle.name, category)
if untracked is not None:
shown = (
f"{display_hermes_home()}/skills/"
f"{category + '/' if category else ''}{bundle.name}"
)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in faec6d69a93 (current head).

You're right that the two can diverge, and it's worth spelling out how far: _untracked_skill_dir() routes the category through _validate_install_parent_path() → _normalize_bundle_path(), which drops empty and . segments and rewrites \ → /, then _resolve_lock_install_path() .resolve()s the result. So --category "personal//./notes" produced a prompt naming skills/personal//./notes/note-taker while the directory install_from_quarantine() would have rmtree'd was skills/personal/notes/note-taker. Naming the deletion target is the entire purpose of this prompt, so a mismatch defeats it.

The message is now derived from the resolved untracked path (hermes_cli/skills_hub.py:685-692), keeping the profile-safe display_hermes_home() shorthand and falling back to the absolute path when the target lies outside HERMES_HOME (i.e. a SKILLS_DIR override, where there is no ~/ shorthand to apply).

Pinned by test_untracked_warning_names_the_resolved_deletion_target in tests/hermes_cli/test_skills_hub.py:369. It asserts the emitted path equals _untracked_skill_dir()'s return value — the actual rmtree target — and that the raw category string is absent from the output. Verified red before the change (the assertion diff showed the two paths side by side) and green after; the file's 7 tests pass.

One deliberate exclusion: the same raw-category construct appears in the two "Files will be at:" panels further down (the Official Skill and Disclaimer panels). Those describe an install destination rather than a deletion target, and they are not part of this PR's diff, so I've left them alone rather than widen an in-review change. Happy to send a follow-up for them if you'd like the normalization applied there too.

c.print(
f"[yellow]Warning:[/] '{bundle.name}' already exists at {shown} "
"and is not tracked by the skills hub (a local or user-edited skill)."
)
c.print("Installing would replace it. Use --force to overwrite.\n")
return

extra_metadata = dict(getattr(meta, "extra", {}) or {})
extra_metadata.update(getattr(bundle, "metadata", {}) or {})

Expand Down
131 changes: 131 additions & 0 deletions tests/hermes_cli/test_skills_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,137 @@ def _install_from_quarantine(q, name, category, bundle, result):
return install_calls


# ---------------------------------------------------------------------------
# Untracked skills (no hub lock entry) must not be silently destroyed.
#
# install_from_quarantine() rmtree's whatever sits at the install path and
# justifies it by deferring to "the lock-file check in do_install()". That
# check reads the hub lock file, so it is blind to locally authored skills
# (source_type="local") and to bundled skills the user has edited -- both of
# which live under skills/ with no lock entry.
#
# These tests drive the REAL quarantine/install/lock code so the destructive
# rmtree actually runs; only the remote source and the scanner are faked.
# ---------------------------------------------------------------------------

_LOCAL_SKILL_BODY = "---\nname: note-taker\ndescription: hand written\n---\n# my own notes\n"
_UPSTREAM_SKILL_BODY = "---\nname: note-taker\ndescription: upstream\n---\n# upstream body\n"


def _untracked_source(name, identifier):
class _Source:
def inspect(self, _identifier):
return type("Meta", (), {
"extra": {}, "identifier": identifier, "name": name, "path": name,
})()

def fetch(self, _identifier):
return type("Bundle", (), {
"name": name,
"files": {"SKILL.md": _UPSTREAM_SKILL_BODY},
"source": "github",
"identifier": identifier,
"trust_level": "community",
"metadata": {},
})()

return _Source()


def _real_install_env(monkeypatch, name, identifier):
"""Fake only the remote source and the scanner; keep the disk path real."""
import tools.skills_guard as guard
import tools.skills_hub as hub

monkeypatch.setattr(hub, "GitHubAuth", lambda: None)
monkeypatch.setattr(
hub, "create_source_router",
lambda auth: [_untracked_source(name, identifier)],
)
monkeypatch.setattr(
guard, "scan_skill_cached",
lambda skill_path, source="community", source_url="", cache_dir=None: (
guard.ScanResult(
skill_name=name, source=source,
trust_level="community", verdict="safe",
),
{
"fresh": True, "scanner_version": "test", "bundle_hash": "sha256:t",
"source_url": source_url, "scanned_at": "now", "rules": [],
},
),
)
monkeypatch.setattr(guard, "format_scan_report", lambda _result: "scan ok")
monkeypatch.setattr(
guard, "should_allow_install", lambda _result, force=False: (True, "ok"),
)


def _seed_untracked_skill(tmp_path, name):
"""A skill directory on disk with NO entry in the hub lock file."""
skill_dir = tmp_path / "skills" / name
skill_dir.mkdir(parents=True)
(skill_dir / "SKILL.md").write_text(_LOCAL_SKILL_BODY, encoding="utf-8")
return skill_dir


def _run_install(monkeypatch, name, identifier, **kwargs):
_real_install_env(monkeypatch, name, identifier)
sink = StringIO()
console = Console(file=sink, force_terminal=False, color_system=None, width=200)
do_install(identifier, console=console, skip_confirm=True,
invalidate_cache=False, **kwargs)
# Rich hard-wraps at the console width; collapse it so assertions can match
# message text without depending on where the wrap lands.
return " ".join(sink.getvalue().split())


def test_install_refuses_to_replace_untracked_local_skill(hub_env, monkeypatch, tmp_path):
"""A local/user-edited skill has no lock entry, so the lock-file check
cannot see it -- but install_from_quarantine() would still rmtree it.
Without --force the install must refuse and leave the file untouched."""
skill_dir = _seed_untracked_skill(tmp_path, "note-taker")

out = _run_install(monkeypatch, "note-taker", "acme/note-taker")

# The user's own file survives, byte for byte.
assert (skill_dir / "SKILL.md").read_text(encoding="utf-8") == _LOCAL_SKILL_BODY
assert "not tracked by the skills hub" in out
assert "Use --force to overwrite." in out
# And the install did not report success.
assert "Installed:" not in out


def test_install_force_still_replaces_untracked_local_skill(hub_env, monkeypatch, tmp_path):
"""--force remains the escape hatch: the guard warns but does not block."""
skill_dir = _seed_untracked_skill(tmp_path, "note-taker")

out = _run_install(monkeypatch, "note-taker", "acme/note-taker", force=True)

assert (skill_dir / "SKILL.md").read_text(encoding="utf-8") == _UPSTREAM_SKILL_BODY
assert "Installed:" in out


def test_install_untracked_guard_leaves_lockfile_branch_alone(hub_env, monkeypatch, tmp_path):
"""A hub-installed skill (lock entry present) keeps the existing message
and the existing behaviour -- the new filesystem check must not fire."""
from tools.skills_hub import HubLockFile

skill_dir = _seed_untracked_skill(tmp_path, "note-taker")
HubLockFile().record_install(
name="note-taker", source="github", identifier="acme/note-taker",
trust_level="community", scan_verdict="safe", skill_hash="sha256:old",
install_path="note-taker", files=["SKILL.md"],
)

out = _run_install(monkeypatch, "note-taker", "acme/note-taker")

assert "is already installed at" in out
assert "Use --force to reinstall." in out
assert "not tracked by the skills hub" not in out
assert (skill_dir / "SKILL.md").read_text(encoding="utf-8") == _LOCAL_SKILL_BODY





Expand Down
Loading