The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: dashboard console skills commands no longer act on the wrong profile (#65828)
Tekniumcc421cb69760
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex edc62c8c52e..1b72435eda3 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -14740,6 +14740,11 @@ def _profile_scope(profile: Optional[str]):temporarily retarget both under a lock and restore themimmediately 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 stillretargeted to the *current* ``get_hermes_home()`` so writes land in thediff --git a/tests/tools/test_skills_sync.py b/tests/tools/test_skills_sync.pyindex d3ca5c97ea2..bb55469c4fc 100644--- a/tests/tools/test_skills_sync.py+++ b/tests/tools/test_skills_sync.py@@ -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)diff --git a/tools/skills_sync.py b/tools/skills_sync.pyindex 8ecca29329c..14bfbc7e4d4 100644--- a/tools/skills_sync.py+++ b/tools/skills_sync.py@@ -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 theskill 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() / reldef _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 / reltarget.parent.mkdir(parents=True, exist_ok=True)if target.exists():@@ -349,10 +388,10 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dictrestored: 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):continuecandidate = skill_md.parenttry:- candidate.relative_to(SKILLS_DIR)+ candidate.relative_to(_skills_dir())except ValueError:continuecandidate_name = _read_skill_name(skill_md, candidate.name)@@ -402,15 +441,15 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dictdef _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):continuecandidate = 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):continueindex.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 abyte-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 Noneif 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.nameif 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:continuetry:- 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):continueskill_dir = skill_md.parent@@ -625,7 +664,7 @@ def _recover_renamed_skill(if candidate == dest or not candidate.is_dir():continuetry:- 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 Nonelogger.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 relreturn 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() / relif 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 letthe next sync re-copy the current bundled version. If False(default), only clear the manifest entry — the user'scurrent 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_MARKERexisted = 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: