The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): doctor stages only the plugin it validates
kshitijk4poor903230b1e23e
diff --git a/hermes_cli/plugin_dev.py b/hermes_cli/plugin_dev.pyindex 329d08aa885..b5b2d5212e4 100644--- a/hermes_cli/plugin_dev.py+++ b/hermes_cli/plugin_dev.py@@ -44,10 +44,21 @@ def _doctor_runtime(plugin_path: Path):plugins_root = home / "plugins"bundled.mkdir(parents=True)plugins_root.mkdir(parents=True)- copied = plugins_root / plugin_path.name- shutil.copytree(- plugin_path, copied,- ignore=shutil.ignore_patterns(".git", "__pycache__", ".pytest_cache", "*.pyc"))+ staging_root = plugins_root / plugin_path.name+ ignore = shutil.ignore_patterns(*_STAGING_SKIPPED_DIRS, "*.pyc")+ if _has_manifest(plugin_path):+ staged = staging_root+ shutil.copytree(plugin_path, staged, ignore=ignore)+ else:+ # A category: stage only its plugin under the category name (discovery keys it+ # ``category/plugin``), never the loose files or skipped dirs beside it.+ members = _category_plugins(plugin_path)+ if len(members) != 1:+ names = ", ".join(member.name for member in members)+ raise _DoctorLoadError(+ f"{plugin_path} holds {len(members)} plugins ({names}); point Doctor at one of them")+ staged = staging_root / members[0].name+ shutil.copytree(members[0], staged, ignore=ignore)stack.enter_context(patch.dict(os.environ, {"HERMES_HOME": str(home),"HERMES_BUNDLED_PLUGINS": str(bundled),@@ -69,13 +80,13 @@ def _doctor_runtime(plugin_path: Path):try:manifests = manager._scan_directory(plugins_root, source="user")if not manifests:- raise _DoctorLoadError(f"Hermes discovery found no valid plugin manifest under {copied}")+ raise _DoctorLoadError(f"Hermes discovery found no valid plugin manifest under {staging_root}")if len(manifests) != 1:raise _DoctorLoadError(- f"Expected one plugin manifest, discovered {len(manifests)} under {copied}")+ f"Expected one plugin manifest, discovered {len(manifests)} under {staging_root}")manifest = manifests[0]if manifest.kind == "model-provider":- with _load_model_provider(copied, manifest) as registered:+ with _load_model_provider(staged, manifest) as registered:yield SimpleNamespace(manifest=manifest, manager=manager, registered_tools=(),registered_hooks=(), registered_providers=registered)return@@ -131,7 +142,7 @@ def _is_plugin_module(name: str) -> bool:@contextmanager-def _load_model_provider(copied: Path, manifest):+def _load_model_provider(plugin_dir: Path, manifest):"""Doctor path for ``kind: model-provider``: those register a ProviderProfile at import throughproviders/ discovery (PluginManager skips the kind), so demanding ``register(ctx)`` would failevery valid provider plugin. Registry additions are undone on exit."""@@ -139,12 +150,12 @@ def _load_model_provider(copied: Path, manifest):# The live install may already have imported this very plugin (same directory name) during# startup discovery; import the copy fresh and put the live module/profiles back afterwards.- module_name = providers._user_module_name(copied, "")+ module_name = providers._user_module_name(plugin_dir, "")prior_module = sys.modules.pop(module_name, None)before = dict(providers._REGISTRY)before_aliases = dict(providers._ALIASES)try:- providers._import_plugin_dir(copied, "user")+ providers._import_plugin_dir(plugin_dir, "user")registered = tuple(sorted(name for name, profile in providers._REGISTRY.items() if before.get(name) is not profile))if not registered:@@ -212,33 +223,40 @@ def _has_manifest(path: Path) -> bool:return any((path / name).exists() or (path / name).is_symlink() for name in _MANIFEST_NAMES)-def _ignored_category_child(name: str) -> bool:- """Cache and VCS dirs are not plugin siblings. ``.hermes`` is: a home that- contains it next to a checkout is not a category layout."""- return name in {".git", ".pytest_cache"} or (- name.startswith("__") and name.endswith("__")- )+# Dirs the staging copy drops, so a category may hold them beside its plugins.+_STAGING_SKIPPED_DIRS = (".git", "__pycache__", ".pytest_cache")-def _holds_plugin(path: Path) -> bool:- """True when discovery would find a manifest in *path* or one immediate subdirectory (category- layout), mirroring ``PluginManager._scan_directory``. Doctor copies the resolved directory- wholesale, so resolving an arbitrary directory (e.g. the default ``.``) would be a disk bug.+def _candidate_dirs(path: Path) -> list[Path]:+ """Subdirectories of *path* that could be plugins: not skipped by discovery or the staging copy."""+ from hermes_cli.plugins_discovery import is_skipped_plugin_dir- A category's immediate subdirectories are plugins. One plugin checkout next to other- directories, such as ``$HOME`` beside ``.hermes``, is not a category."""- if not path.is_dir():- return False- if _has_manifest(path):- return Truetry:- children = [+ return sorted(child for child in path.iterdir()- if child.is_dir() and not _ignored_category_child(child.name)- ]+ if child.is_dir()+ and child.name not in _STAGING_SKIPPED_DIRS+ and not is_skipped_plugin_dir(child.name)+ )except OSError:- return False- return bool(children) and all(_has_manifest(child) for child in children)+ return []+++def _category_plugins(path: Path) -> list[Path]:+ """The plugin subdirectories of a manifest-less *path* when it is a category, else ``[]``.++ A category is a directory whose candidate subdirectories (:func:`_candidate_dirs`) all hold+ a manifest. A plugin checkout next to other directories (``$HOME`` beside ``.hermes``, a repo+ root beside ``tests/``) is not a category."""+ children = _candidate_dirs(path)+ return children if children and all(_has_manifest(child) for child in children) else []+++def _holds_plugin(path: Path) -> bool:+ """True when *path* holds a manifest or is a category (:func:`_category_plugins`). Stricter+ than discovery on purpose: resolving an arbitrary directory (e.g. the default ``.``) would+ send Doctor to validate whatever plugin happens to sit inside it."""+ return path.is_dir() and (_has_manifest(path) or bool(_category_plugins(path)))def _is_plugin_id(raw: str) -> bool:@@ -272,10 +290,15 @@ def resolve_plugin_path(target: str | os.PathLike[str] | None = None) -> Path:if _holds_plugin(candidate):return candidate.resolve()if direct_is_dir:+ nested = [os.path.join(raw, c.name) for c in _candidate_dirs(direct) if _has_manifest(c)]+ if nested:+ hint = f"Point Doctor at a plugin directory inside it: {', '.join(nested)}."+ else:+ hint = "Point Doctor at a plugin directory."raise FileNotFoundError(f"{direct.resolve()} holds no plugin manifest "f"({', '.join(_MANIFEST_NAMES)}), and {raw!r} is not an installed "- "plugin id. Point Doctor at a plugin directory.")+ f"plugin id. {hint}")raise FileNotFoundError(f"Plugin {raw!r} was not found as a path or installed plugin id")diff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.pyindex 852e667d2d3..24685d94a5e 100644--- a/hermes_cli/plugins_discovery.py+++ b/hermes_cli/plugins_discovery.py@@ -131,6 +131,13 @@ def _get_enabled_plugins() -> Optional[set]:return None+def is_skipped_plugin_dir(name: str) -> bool:+ """True for directory names discovery never treats as plugins. Cache/dunder dirs (__pycache__,+ __MACOSX__, …) can raise PermissionError when walked and take down every later tool call+ (#86996); foreign-harness dirs hold another tool's manifest convention."""+ return (name.startswith("__") and name.endswith("__")) or name in _FOREIGN_HARNESS_MANIFEST_DIRS++def scan_directory(path: Path, source: str, *, skip_names: Optional[set[str]] = None, prefix: str = "", depth: int = 0) -> list[PluginManifest]:@@ -147,14 +154,8 @@ def scan_directory(logger.warning("Skipping unreadable plugin directory %s: %s", path, exc)return manifestsfor child in children:- # Cache/dunder dirs (__pycache__, __MACOSX__, …) are never- # plugins. Walking them can raise PermissionError and take- # down every subsequent tool call (#86996).- if child.name.startswith("__") and child.name.endswith("__"):- logger.debug("Skipping dunder plugin path %s", child)- continue- if child.name in _FOREIGN_HARNESS_MANIFEST_DIRS:- logger.debug("Skipping %s (foreign-harness manifest convention)", child)+ if is_skipped_plugin_dir(child.name):+ logger.debug("Skipping %s (dunder or foreign-harness manifest dir)", child)continue# pathlib.Path.is_dir() swallows OSError, but injected Path-likes# and test doubles can still raise. Fail closed per child.diff --git a/tests/hermes_cli/test_plugin_dev.py b/tests/hermes_cli/test_plugin_dev.pyindex 068be7ff45c..f27bdd6612c 100644--- a/tests/hermes_cli/test_plugin_dev.py+++ b/tests/hermes_cli/test_plugin_dev.py@@ -197,6 +197,80 @@ def test_resolve_accepts_category_layout(tmp_path: Path) -> None:assert resolve_plugin_path(category) == category.resolve()+def test_doctor_stages_only_the_plugin_of_a_category(tmp_path: Path, monkeypatch) -> None:+ """A category may hold loose files and dirs the staging copy drops or discovery never scans;+ none of them is copied."""+ import os+ import shutil++ from hermes_cli import plugin_dev++ category = tmp_path / "tools"+ plugin = category / "minimal"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: minimal\n", encoding="utf-8")+ (plugin / "__init__.py").write_text("def register(ctx):\n pass\n", encoding="utf-8")+ (category / "disk-image.iso").write_bytes(b"x" * 1024)+ for skipped in ("__data__", ".git", ".claude-plugin"):+ (category / skipped).mkdir()++ copied: list[str] = []+ real_copytree = shutil.copytree++ def _tracking_copytree(src, dst, *args, **kwargs):+ copied.append(os.fspath(src))+ return real_copytree(src, dst, *args, **kwargs)++ monkeypatch.setattr(plugin_dev.shutil, "copytree", _tracking_copytree)++ report = plugin_dev.doctor_plugin(category)+ assert report.ok, report.format_text()+ assert copied == [os.fspath(plugin.resolve())]+ assert report.manifest is not None+ assert report.manifest.key == "tools/minimal" # staged under the category, as discovery keys it+++def test_doctor_rejects_category_of_several_plugins_before_copying(+ tmp_path: Path, monkeypatch+) -> None:+ """Doctor validates one plugin, so copying a whole category first only wastes disk."""+ from hermes_cli import plugin_dev++ category = tmp_path / "web"+ for name in ("a", "b"):+ (category / name).mkdir(parents=True)+ (category / name / "plugin.yaml").write_text(f"name: {name}\n", encoding="utf-8")++ copied: list[object] = []+ monkeypatch.setattr(plugin_dev.shutil, "copytree", lambda src, *a, **k: copied.append(src))++ report = plugin_dev.doctor_plugin(category)+ assert copied == []+ assert report.ok is False+ assert "holds 2 plugins (a, b)" in report.format_text()+++def test_doctor_names_plugin_dirs_of_a_target_that_is_not_a_category(+ tmp_path: Path, monkeypatch+) -> None:+ """The refusal names the plugin inside, so the user knows what to pass instead."""+ import os++ from hermes_cli import plugin_dev++ repo = tmp_path / "repo"+ (repo / "tests").mkdir(parents=True)+ for name, manifest in (("myplugin", "plugin.yaml"), (".claude-plugin", "plugin.json")):+ (repo / name).mkdir()+ (repo / name / manifest).write_text("name: x\n", encoding="utf-8")+ monkeypatch.chdir(repo)++ report = plugin_dev.doctor_plugin(".")+ assert report.ok is False+ # Discovery skips .claude-plugin, so suggesting it would send the user to a dead end.+ assert f"plugin directory inside it: {os.path.join('.', 'myplugin')}." in report.format_text()++def test_resolve_prefers_installed_id_over_unrelated_local_dir(tmp_path: Path, monkeypatch) -> None:@@ -286,3 +360,26 @@ def test_doctor_loads_model_provider_plugins_through_provider_discovery(tmp_pathreport = doctor_plugin(plugin)assert not report.okassert any("registered no ProviderProfile" in f.message for f in report.findings)+++def test_doctor_loads_a_model_provider_plugin_from_its_category(tmp_path: Path) -> None:+ """``plugins/model-providers/<name>`` is the runtime layout; the provider loader must get the+ staged plugin directory, not the category around it."""+ import providers+ from hermes_cli.plugin_dev import doctor_plugin++ plugin = tmp_path / "model-providers" / "acme-provider"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: acme-provider\nkind: model-provider\n", encoding="utf-8")+ (plugin / "__init__.py").write_text(+ "from providers import register_provider\nfrom providers.base import ProviderProfile\n"+ "register_provider(ProviderProfile(name='acme-category-probe', auth_type='external_process',\n"+ " process_command='acme'))\n",+ encoding="utf-8")++ registry_before = dict(providers._REGISTRY)++ report = doctor_plugin(plugin.parent)+ assert report.ok, report.format_text()+ assert report.registered_providers == ("acme-category-probe",)+ assert providers._REGISTRY == registry_before