fix: dashboard console skills commands no longer act on the wrong profile (#65828)
tools/skills_sync.py bound HERMES_HOME / SKILLS_DIR / MANIFEST_FILE at import time — the third module in the same lineage as skills_tool (f8723c478) and skill_manager_tool (c6a3d412d). In a long-lived dashboard/TUI process, console skills commands (reset, diff, list-modified, opt-in/out, repair-official) dispatched in-process under _profile_scope's set_hermes_home_override(), but skills_sync's frozen constants kept resolving against whichever profile was live at import. Sharpest edge: reset_bundled_skill()'s #48200 rmtree strict-child guard was computed against the WRONG skills root. Fix: same call-time accessor pattern as the two prior fixes — _hermes_home()/_skills_dir()/_manifest_file() honor an explicitly patched module global (tests, retargeting) and otherwise re-resolve from the live profile-scoped get_hermes_home() on every call. All 37 call sites migrated; module constants kept for compat. Also documents in _profile_scope() that skills_sync needs no module retargeting since the contextvar override now reaches it. Regression tests (sabotage-verified: all 3 fail on the old binding): - accessors follow set_hermes_home_override at call time - explicit module patch still wins over the override - rmtree guard anchors on the overridden profile's skills root Fixes #65828
This commit is contained in:
@@ -14740,6 +14740,11 @@ def _profile_scope(profile: Optional[str]):
|
||||
temporarily retarget both under a lock and restore them
|
||||
immediately after.
|
||||
|
||||
``tools.skills_sync`` (reset/diff/list-modified/opt-in/opt-out/
|
||||
repair-official) needs NO retargeting: since #65828 its directory
|
||||
lookups resolve at call time through the same contextvar override
|
||||
set in step 1.
|
||||
|
||||
``profile`` of None/""/"current" means "the dashboard's own profile" —
|
||||
config resolution is untouched, but the skill-module globals are still
|
||||
retargeted to the *current* ``get_hermes_home()`` so writes land in the
|
||||
|
||||
@@ -936,3 +936,69 @@ class TestUpdateBackupRecovery:
|
||||
result2 = sync_skills(quiet=True)
|
||||
assert "old-skill" in result2["updated"]
|
||||
assert result2["user_modified"] == []
|
||||
|
||||
|
||||
class TestCallTimeDirResolution:
|
||||
"""Regression for #65828: skills_sync bound SKILLS_DIR/MANIFEST_FILE/
|
||||
HERMES_HOME at import, so a long-lived dashboard/TUI process serving a
|
||||
console skills command for another profile resolved (and for
|
||||
reset_bundled_skill DELETED) against whichever home was live at import.
|
||||
The accessors must follow set_hermes_home_override() at call time, while
|
||||
an explicitly patched module global (tests, _profile_scope retargeting)
|
||||
still wins.
|
||||
"""
|
||||
|
||||
def test_accessors_follow_hermes_home_override(self, tmp_path):
|
||||
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
|
||||
import tools.skills_sync as ss
|
||||
|
||||
profile_home = tmp_path / "profiles" / "research"
|
||||
token = set_hermes_home_override(str(profile_home))
|
||||
try:
|
||||
assert ss._hermes_home() == profile_home
|
||||
assert ss._skills_dir() == profile_home / "skills"
|
||||
assert ss._manifest_file() == profile_home / "skills" / ".bundled_manifest"
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
def test_explicit_module_patch_wins_over_override(self, tmp_path):
|
||||
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
|
||||
import tools.skills_sync as ss
|
||||
|
||||
patched = tmp_path / "patched-skills"
|
||||
token = set_hermes_home_override(str(tmp_path / "other-profile"))
|
||||
try:
|
||||
with patch("tools.skills_sync.SKILLS_DIR", patched):
|
||||
assert ss._skills_dir() == patched
|
||||
# MANIFEST_FILE unpatched -> derives from the patched skills dir.
|
||||
assert ss._manifest_file() == patched / ".bundled_manifest"
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
def test_rmtree_guard_anchors_on_overridden_profile(self, tmp_path):
|
||||
"""The #48200 strict-child rmtree guard must anchor on the OVERRIDDEN
|
||||
profile's skills root. Under the stale import-time binding the guard
|
||||
was computed against the wrong home (#65828's sharpest edge): a
|
||||
legitimate delete in the scoped profile would be refused, and a stale
|
||||
path under the import-time home would pass the guard."""
|
||||
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
|
||||
import tools.skills_sync as ss
|
||||
|
||||
profile_home = tmp_path / "profiles" / "worker"
|
||||
victim = profile_home / "skills" / "doomed-skill"
|
||||
victim.mkdir(parents=True)
|
||||
(victim / "SKILL.md").write_text("---\nname: doomed-skill\n---\n", encoding="utf-8")
|
||||
|
||||
token = set_hermes_home_override(str(profile_home))
|
||||
try:
|
||||
# Allowed: strict child of the overridden profile's skills root.
|
||||
ss._rmtree_writable(victim)
|
||||
assert not victim.exists()
|
||||
|
||||
# Refused: a path under the import-time home is OUTSIDE the
|
||||
# overridden profile's skills root now.
|
||||
foreign = ss._SKILLS_DIR_AT_IMPORT / "some-skill"
|
||||
with pytest.raises(ValueError):
|
||||
ss._rmtree_writable(foreign)
|
||||
finally:
|
||||
reset_hermes_home_override(token)
|
||||
|
||||
+73
-34
@@ -57,6 +57,44 @@ HERMES_HOME = get_hermes_home()
|
||||
SKILLS_DIR = HERMES_HOME / "skills"
|
||||
MANIFEST_FILE = SKILLS_DIR / ".bundled_manifest"
|
||||
|
||||
# Import-time snapshots backing the call-time accessors below. Same bug class
|
||||
# and same fix as skills_tool (f8723c478) and skill_manager_tool (c6a3d412d):
|
||||
# long-lived multi-profile runtimes (Dashboard console, TUI/Desktop backend,
|
||||
# cron, kanban workers) import this module once under the launch HERMES_HOME
|
||||
# and later scope requests to a different profile via
|
||||
# set_hermes_home_override(). Frozen module constants would then resolve —
|
||||
# and for reset_bundled_skill() DELETE — against the wrong profile's skills
|
||||
# root (#65828). The accessors honor an explicitly patched module global
|
||||
# (tests, and web_server's _profile_scope retargeting) and otherwise
|
||||
# re-resolve from the live profile-scoped HERMES_HOME on every call.
|
||||
_HERMES_HOME_AT_IMPORT = HERMES_HOME
|
||||
_SKILLS_DIR_AT_IMPORT = SKILLS_DIR
|
||||
_MANIFEST_FILE_AT_IMPORT = MANIFEST_FILE
|
||||
|
||||
|
||||
def _hermes_home() -> Path:
|
||||
"""Return the active profile's HERMES_HOME at call time."""
|
||||
configured = Path(HERMES_HOME)
|
||||
if configured != _HERMES_HOME_AT_IMPORT:
|
||||
return configured
|
||||
return get_hermes_home()
|
||||
|
||||
|
||||
def _skills_dir() -> Path:
|
||||
"""Return the active profile's skills directory at call time."""
|
||||
configured = Path(SKILLS_DIR)
|
||||
if configured != _SKILLS_DIR_AT_IMPORT:
|
||||
return configured
|
||||
return _hermes_home() / "skills"
|
||||
|
||||
|
||||
def _manifest_file() -> Path:
|
||||
"""Return the active profile's bundled-skills manifest at call time."""
|
||||
configured = Path(MANIFEST_FILE)
|
||||
if configured != _MANIFEST_FILE_AT_IMPORT:
|
||||
return configured
|
||||
return _skills_dir() / ".bundled_manifest"
|
||||
|
||||
# Marker file written by `hermes profile create --no-skills` (named profiles)
|
||||
# and by the installer's `--no-skills` flag (the default ~/.hermes profile).
|
||||
# When present in HERMES_HOME, sync_skills() is a no-op so neither the
|
||||
@@ -117,11 +155,11 @@ def _read_manifest() -> Dict[str, str]:
|
||||
Handles both v1 (plain names) and v2 (name:hash) formats.
|
||||
v1 entries get an empty hash string which triggers migration on next sync.
|
||||
"""
|
||||
if not MANIFEST_FILE.exists():
|
||||
if not _manifest_file().exists():
|
||||
return {}
|
||||
try:
|
||||
result = {}
|
||||
for line in MANIFEST_FILE.read_text(encoding="utf-8").splitlines():
|
||||
for line in _manifest_file().read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
@@ -149,7 +187,7 @@ def _read_suppressed_names() -> set:
|
||||
|
||||
return read_suppressed_names()
|
||||
except Exception:
|
||||
path = SKILLS_DIR / ".curator_suppressed"
|
||||
path = _skills_dir() / ".curator_suppressed"
|
||||
if not path.exists():
|
||||
return set()
|
||||
names = set()
|
||||
@@ -171,17 +209,18 @@ def _write_manifest(entries: Dict[str, str]):
|
||||
reset to mkstemp's 0600 — the same mode-preservation contract as the
|
||||
skill manager's document writes.
|
||||
"""
|
||||
_manifest_file().parent.mkdir(parents=True, exist_ok=True)
|
||||
data = "\n".join(f"{name}:{hash_val}" for name, hash_val in sorted(entries.items())) + "\n"
|
||||
|
||||
try:
|
||||
atomic_write_text(
|
||||
MANIFEST_FILE,
|
||||
_manifest_file(),
|
||||
data,
|
||||
tmp_prefix=".bundled_manifest_",
|
||||
preserve_mode=True,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug("Failed to write skills manifest %s: %s", MANIFEST_FILE, e, exc_info=True)
|
||||
logger.debug("Failed to write skills manifest %s: %s", _manifest_file(), e, exc_info=True)
|
||||
|
||||
|
||||
def _read_skill_name(skill_md: Path, fallback: str) -> str:
|
||||
@@ -232,11 +271,11 @@ def _discover_bundled_skills(bundled_dir: Path) -> List[Tuple[str, Path]]:
|
||||
|
||||
def _compute_relative_dest(skill_dir: Path, bundled_dir: Path) -> Path:
|
||||
"""
|
||||
Compute the destination path in SKILLS_DIR preserving the category structure.
|
||||
Compute the destination path in the skills dir preserving the category structure.
|
||||
e.g., bundled/skills/mlops/axolotl -> ~/.hermes/skills/mlops/axolotl
|
||||
"""
|
||||
rel = skill_dir.relative_to(bundled_dir)
|
||||
return SKILLS_DIR / rel
|
||||
return _skills_dir() / rel
|
||||
|
||||
|
||||
def _dir_hash(directory: Path) -> str:
|
||||
@@ -316,7 +355,7 @@ def _optional_skill_index() -> Dict[str, Tuple[str, str, Path]]:
|
||||
|
||||
def _move_to_restore_backup(path: Path, backup_root: Path) -> str:
|
||||
"""Move an existing skill directory into a restore backup, preserving rel path."""
|
||||
rel = path.relative_to(SKILLS_DIR)
|
||||
rel = path.relative_to(_skills_dir())
|
||||
target = backup_root / rel
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if target.exists():
|
||||
@@ -349,10 +388,10 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
|
||||
restored: List[str] = []
|
||||
backed_up: List[str] = []
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
||||
backup_root = SKILLS_DIR / ".restore-backups" / f"official-optional-{timestamp}"
|
||||
backup_root = _skills_dir() / ".restore-backups" / f"official-optional-{timestamp}"
|
||||
|
||||
for folder_name, install_path, src in targets:
|
||||
dest = SKILLS_DIR / Path(*install_path.split("/"))
|
||||
dest = _skills_dir() / Path(*install_path.split("/"))
|
||||
src_hash = _dir_hash(src)
|
||||
canonical_ok = dest.exists() and _dir_hash(dest) == src_hash
|
||||
|
||||
@@ -360,13 +399,13 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
|
||||
# or folder slug, even if curator moved it into another category.
|
||||
src_frontmatter = _read_skill_name(src / "SKILL.md", folder_name)
|
||||
matches: List[Path] = []
|
||||
if SKILLS_DIR.exists():
|
||||
for skill_md in sorted(SKILLS_DIR.rglob("SKILL.md")):
|
||||
if _skills_dir().exists():
|
||||
for skill_md in sorted(_skills_dir().rglob("SKILL.md")):
|
||||
if is_excluded_skill_path(skill_md):
|
||||
continue
|
||||
candidate = skill_md.parent
|
||||
try:
|
||||
candidate.relative_to(SKILLS_DIR)
|
||||
candidate.relative_to(_skills_dir())
|
||||
except ValueError:
|
||||
continue
|
||||
candidate_name = _read_skill_name(skill_md, candidate.name)
|
||||
@@ -402,15 +441,15 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
|
||||
def _index_installed_skill_dirs_by_name() -> Dict[str, List[Path]]:
|
||||
"""Index installed skills by directory name with one active-tree scan."""
|
||||
index: Dict[str, List[Path]] = {}
|
||||
if not SKILLS_DIR.exists():
|
||||
if not _skills_dir().exists():
|
||||
return index
|
||||
for skill_md in SKILLS_DIR.rglob("SKILL.md"):
|
||||
for skill_md in _skills_dir().rglob("SKILL.md"):
|
||||
if is_excluded_skill_path(skill_md):
|
||||
continue
|
||||
candidate = skill_md.parent
|
||||
# Never reach outside the skills tree (symlinked/external dirs).
|
||||
try:
|
||||
candidate.resolve().relative_to(SKILLS_DIR.resolve())
|
||||
candidate.resolve().relative_to(_skills_dir().resolve())
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
index.setdefault(candidate.name, []).append(candidate)
|
||||
@@ -430,7 +469,7 @@ def _find_installed_skill_dir_by_name(
|
||||
would write provenance onto the wrong skill. The caller still verifies a
|
||||
byte-identical content hash before recording anything.
|
||||
"""
|
||||
if not skill_dir_name or not SKILLS_DIR.exists():
|
||||
if not skill_dir_name or not _skills_dir().exists():
|
||||
return None
|
||||
if installed_index is None:
|
||||
installed_index = _index_installed_skill_dirs_by_name()
|
||||
@@ -453,7 +492,7 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
if not optional_dir.exists():
|
||||
return []
|
||||
|
||||
lock_path = SKILLS_DIR / ".hub" / "lock.json"
|
||||
lock_path = _skills_dir() / ".hub" / "lock.json"
|
||||
try:
|
||||
data = json.loads(lock_path.read_text(encoding="utf-8")) if lock_path.exists() else {"version": 1, "installed": {}}
|
||||
except (json.JSONDecodeError, OSError):
|
||||
@@ -480,7 +519,7 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
lock_name = src.name
|
||||
if lock_name in installed or install_path in existing_paths:
|
||||
continue
|
||||
dest = SKILLS_DIR / Path(*install_path.split("/"))
|
||||
dest = _skills_dir() / Path(*install_path.split("/"))
|
||||
if not dest.exists() or not dest.is_dir():
|
||||
# The active tree may hold the same skill under a DIFFERENT
|
||||
# category path than the repo uses — categories get reorganized
|
||||
@@ -496,7 +535,7 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
if dest is None:
|
||||
continue
|
||||
try:
|
||||
install_path = _safe_rel_install_path(dest, SKILLS_DIR)
|
||||
install_path = _safe_rel_install_path(dest, _skills_dir())
|
||||
except ValueError as e:
|
||||
logger.debug("Skipping relocated optional skill %s: %s", dest, e)
|
||||
continue
|
||||
@@ -560,7 +599,7 @@ def _read_hub_install_paths() -> Set[str]:
|
||||
content happens to match a bundled origin hash, or the lock's
|
||||
``install_path`` would point at a directory that no longer exists.
|
||||
"""
|
||||
lock_path = SKILLS_DIR / ".hub" / "lock.json"
|
||||
lock_path = _skills_dir() / ".hub" / "lock.json"
|
||||
if not lock_path.exists():
|
||||
return set()
|
||||
try:
|
||||
@@ -583,9 +622,9 @@ def _index_active_skills() -> Dict[str, List[Path]]:
|
||||
locate a bundled skill that upstream moved to a new category/directory.
|
||||
"""
|
||||
index: Dict[str, List[Path]] = {}
|
||||
if not SKILLS_DIR.exists():
|
||||
if not _skills_dir().exists():
|
||||
return index
|
||||
for skill_md in SKILLS_DIR.rglob("SKILL.md"):
|
||||
for skill_md in _skills_dir().rglob("SKILL.md"):
|
||||
if is_excluded_skill_path(skill_md):
|
||||
continue
|
||||
skill_dir = skill_md.parent
|
||||
@@ -625,7 +664,7 @@ def _recover_renamed_skill(
|
||||
if candidate == dest or not candidate.is_dir():
|
||||
continue
|
||||
try:
|
||||
rel = candidate.relative_to(SKILLS_DIR).as_posix()
|
||||
rel = candidate.relative_to(_skills_dir()).as_posix()
|
||||
except ValueError:
|
||||
continue
|
||||
# Never relocate a hub-installed skill — the hub owns its path.
|
||||
@@ -638,7 +677,7 @@ def _recover_renamed_skill(
|
||||
if not quiet:
|
||||
print(
|
||||
f" ⚠ {skill_name}: upstream moved this skill to "
|
||||
f"{dest.relative_to(SKILLS_DIR).as_posix()}, but your "
|
||||
f"{dest.relative_to(_skills_dir()).as_posix()}, but your "
|
||||
f"modified copy at {rel} was kept — it will not receive "
|
||||
f"updates. Run `hermes skills reset {skill_name} --restore` "
|
||||
f"to move to the new location."
|
||||
@@ -655,7 +694,7 @@ def _recover_renamed_skill(
|
||||
return None
|
||||
logger.info("Relocated renamed bundled skill: %s -> %s", candidate, dest)
|
||||
if not quiet:
|
||||
print(f" → {skill_name} (moved {rel} → {dest.relative_to(SKILLS_DIR).as_posix()})")
|
||||
print(f" → {skill_name} (moved {rel} → {dest.relative_to(_skills_dir()).as_posix()})")
|
||||
return rel
|
||||
return None
|
||||
|
||||
@@ -673,7 +712,7 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
# empty-result shape with skipped_opt_out lets callers report "opted out"
|
||||
# instead of "synced 0 / failed". This is the default-profile counterpart
|
||||
# to seed_profile_skills()'s marker check for named profiles.
|
||||
if (HERMES_HOME / NO_BUNDLED_SKILLS_MARKER).exists():
|
||||
if (_hermes_home() / NO_BUNDLED_SKILLS_MARKER).exists():
|
||||
if not quiet:
|
||||
print(" (skipped — profile opted out of bundled skills via .no-bundled-skills)")
|
||||
return {
|
||||
@@ -690,7 +729,7 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
"optional_provenance_backfilled": [],
|
||||
}
|
||||
|
||||
SKILLS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
_skills_dir().mkdir(parents=True, exist_ok=True)
|
||||
manifest = _read_manifest()
|
||||
bundled_skills = _discover_bundled_skills(bundled_dir)
|
||||
bundled_names = {name for name, _ in bundled_skills}
|
||||
@@ -911,7 +950,7 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
# Also copy DESCRIPTION.md files for categories (if not already present)
|
||||
for desc_md in bundled_dir.rglob("DESCRIPTION.md"):
|
||||
rel = desc_md.relative_to(bundled_dir)
|
||||
dest_desc = SKILLS_DIR / rel
|
||||
dest_desc = _skills_dir() / rel
|
||||
if not dest_desc.exists():
|
||||
try:
|
||||
dest_desc.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -957,7 +996,7 @@ def _rmtree_writable(path: Path) -> None:
|
||||
# ``shutil.rmtree(~/.hermes)`` into a loud, recoverable ``ValueError``
|
||||
# instead of silently destroying the user's install.
|
||||
target = Path(path).resolve()
|
||||
skills_root = SKILLS_DIR.resolve()
|
||||
skills_root = _skills_dir().resolve()
|
||||
# Every legitimate caller passes a skill directory or its ``.bak``
|
||||
# sibling — always a strict child of the skills root. The skills root
|
||||
# itself must never be removed: a ``dest`` that collapses to
|
||||
@@ -996,7 +1035,7 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
|
||||
|
||||
Args:
|
||||
name: The skill name (matches the manifest key / skill frontmatter name).
|
||||
restore: If True, also delete the user's copy in SKILLS_DIR and let
|
||||
restore: If True, also delete the user's copy in the skills dir and let
|
||||
the next sync re-copy the current bundled version. If False
|
||||
(default), only clear the manifest entry — the user's
|
||||
current copy is preserved but future updates work again.
|
||||
@@ -1265,11 +1304,11 @@ def set_bundled_skills_opt_out(enabled: bool) -> dict:
|
||||
dict with keys: ok (bool), changed (bool), marker (str path),
|
||||
message (str).
|
||||
"""
|
||||
marker = HERMES_HOME / NO_BUNDLED_SKILLS_MARKER
|
||||
marker = _hermes_home() / NO_BUNDLED_SKILLS_MARKER
|
||||
existed = marker.exists()
|
||||
try:
|
||||
if enabled:
|
||||
HERMES_HOME.mkdir(parents=True, exist_ok=True)
|
||||
_hermes_home().mkdir(parents=True, exist_ok=True)
|
||||
marker.write_text(
|
||||
"This profile opted out of bundled-skill seeding "
|
||||
"(`hermes skills opt-out`).\n"
|
||||
@@ -1303,7 +1342,7 @@ def set_bundled_skills_opt_out(enabled: bool) -> dict:
|
||||
|
||||
def is_bundled_skills_opt_out() -> bool:
|
||||
"""Return True if the active profile carries the opt-out marker."""
|
||||
return (HERMES_HOME / NO_BUNDLED_SKILLS_MARKER).exists()
|
||||
return (_hermes_home() / NO_BUNDLED_SKILLS_MARKER).exists()
|
||||
|
||||
|
||||
def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:
|
||||
|
||||
Reference in New Issue
Block a user