Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(registry): discover plugins from entry points and add named seams (#3717)
Raghav Chamadiya8711c0db76f4
diff --git a/docs/architecture/pluggable-storage.md b/docs/architecture/pluggable-storage.mdindex ed3c2f321..10709c1ba 100644--- a/docs/architecture/pluggable-storage.md+++ b/docs/architecture/pluggable-storage.md@@ -211,6 +211,20 @@ broken plugin cannot derail the pipeline.---+## Loading plugins and choosing a seam++A distribution declares an entry point in the `repowise.plugins` group (or a+module is listed in `REPOWISE_PLUGINS` as `module` or `module:attr`), and+repowise imports it once, calling the target if it is callable, so its+registrations land in the registries above. A plugin that fails to load is+reported by `repowise plugins` and never stops startup. Named seams use+`SeamRegistry` from `repowise.core.registry.plugins`: the local default+registers first and stays chosen unless the plugin passes `default=True` or+`REPOWISE_SEAM_<NAME>` names another implementation. Both variables are read+from the process environment only, never from a repo's `.repowise/.env`.++---+## Defaults stay the defaultsThe seams add a layer of indirection but no behavior change for usersdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 77e94d663..9f3d7c797 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -80,6 +80,7 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details[`doctor`](#repowise-doctor-path) ·[`whats-new`](#repowise-whats-new) ·[`telemetry`](#repowise-telemetry) ·+[`plugins`](#repowise-plugins) ·[`login`](#repowise-login) ·[`logout`](#repowise-logout) ·[`whoami`](#repowise-whoami) ·@@ -2194,6 +2195,16 @@ repowise telemetry disable---+### `repowise plugins`++List the plugins repowise loaded (from `repowise.plugins` entry points and+`REPOWISE_PLUGINS`), whether each loaded or why it failed, the seams each+registered, and the implementation chosen for each seam. `--format json` gives+the same as JSON. Commands a plugin adds load only when you run a name the CLI+does not know or list the commands. See [pluggable storage and capability seams](../architecture/pluggable-storage.md).++---+### `repowise config hints on|off`Now and then, at a moment where it would help (a finished `init`, a slowdiff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.pyindex 0dc19ddfb..09b69cc75 100644--- a/packages/cli/src/repowise/cli/_instrumented_group.py+++ b/packages/cli/src/repowise/cli/_instrumented_group.py@@ -59,10 +59,28 @@ class InstrumentedGroup(click.Group):call it."""- def __init__(self, *args, **kwargs) -> None:+ def __init__(self, *args, discover_plugins: bool = False, **kwargs) -> None:super().__init__(*args, **kwargs)#: name -> "module:attr", for commands not yet imported.self._lazy_commands: dict[str, str] = {}+ #: Only the real root discovers plugins; True once it has.+ self._plugins_pending = discover_plugins++ def _load_plugin_commands(self) -> bool:+ """Load installed plugins once and attach any commands they registered.++ Deferred to an unknown name or a listing because discovery costs+ about 100 ms, which every hook fire would otherwise pay.+ """+ if not self._plugins_pending:+ return False+ self._plugins_pending = False+ from repowise.core.registry import cli_registry+ from repowise.core.registry.plugins import load_plugins++ load_plugins()+ cli_registry.apply(self, replace=False)+ return Truedef main(self, *args, **kwargs):# Click expands wildcards in arguments on Windows by default, so a@@ -89,6 +107,7 @@ class InstrumentedGroup(click.Group):def list_commands(self, ctx: click.Context) -> list[str]:"""Every command name, resolved and unresolved, importing nothing."""+ self._load_plugin_commands()return sorted({*super().list_commands(ctx), *self._lazy_commands})def get_command(self, ctx: click.Context, name: str) -> click.Command | None:@@ -98,6 +117,8 @@ class InstrumentedGroup(click.Group):return resolvedtarget = self._lazy_commands.get(name)if target is None:+ if self._load_plugin_commands():+ return self.get_command(ctx, name)return Nonefrom repowise.core.registry import LazyCommanddiff --git a/packages/cli/src/repowise/cli/commands/plugins_cmd.py b/packages/cli/src/repowise/cli/commands/plugins_cmd.pynew file mode 100644index 000000000..7577effe1--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/plugins_cmd.py@@ -0,0 +1,46 @@+"""``repowise plugins`` — list loaded plugins and the implementation chosen per seam."""++from __future__ import annotations++from dataclasses import asdict++import click++from repowise.cli.output import emit_json, format_option++[email protected]("plugins")+@format_option()+def plugins_command(fmt: str) -> None:+ """List loaded plugins and the implementation each seam uses."""+ from rich.markup import escape++ from repowise.cli.helpers import console+ from repowise.core.registry.plugins import ENTRY_POINT_GROUP, ENV_VAR, load_plugins, seams++ records = load_plugins()+ seam_rows = {+ name: {"default": registry.default, "implementations": registry.names}+ for name, registry in sorted(seams().items())+ }+ if fmt == "json":+ emit_json({"plugins": [asdict(r) for r in records], "seams": seam_rows})+ return++ if not records:+ console.print(+ f"No plugins loaded. Install one that declares a [bold]{ENTRY_POINT_GROUP}[/bold] "+ f"entry point, or list modules in [bold]{ENV_VAR}[/bold]."+ )+ colors = {"loaded": "green", "failed": "red", "skipped": "yellow"}+ for r in records:+ color = colors.get(r.status, "red")+ status = f"[{color}]{r.status}[/{color}]"+ if r.error:+ status += f": {escape(r.error)}"+ console.print(f"[bold]{escape(r.name)}[/bold] {r.source} {escape(r.target)} {status}")+ if r.seams:+ console.print(f" registered: {escape(', '.join(r.seams))}")+ for name, row in seam_rows.items():+ others = ", ".join(row["implementations"])+ console.print(f"seam [bold]{escape(name)}[/bold]: {escape(str(row['default']))} ({escape(others)})")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex fc3bcb1a3..8205fca71 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -20,7 +20,7 @@ from repowise.cli._instrumented_group import InstrumentedGroupfrom repowise.core.registry import cli_registry, register_lazy_command[email protected](cls=InstrumentedGroup)[email protected](cls=InstrumentedGroup, discover_plugins=True)@click.version_option(version=__version__, prog_name="repowise")@click.pass_contextdef cli(ctx: click.Context) -> None:@@ -104,6 +104,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("logout", "login_cmd:logout_command"),("whoami", "login_cmd:whoami_command"),("workspace", "workspace_cmd:workspace_group"),+ ("plugins", "plugins_cmd:plugins_command"),)# Register OSS commands through the shared registry so third-partydiff --git a/packages/cli/src/repowise/cli/ui/env_persistence.py b/packages/cli/src/repowise/cli/ui/env_persistence.pyindex 5beafee59..889854795 100644--- a/packages/cli/src/repowise/cli/ui/env_persistence.py+++ b/packages/cli/src/repowise/cli/ui/env_persistence.py@@ -5,13 +5,20 @@ from __future__ import annotationsimport osfrom pathlib import Path+_warned_plugin_keys = False+def load_dotenv(repo_path: Path) -> None:"""Load ``<repo>/.repowise/.env`` into ``os.environ`` (without overwriting).Supports ``export KEY=value``, quoted values (``KEY="value"``, ``KEY='value'``),and inline comments (``KEY=value # comment``).++ Keys that choose code to run (``REPOWISE_PLUGINS``, ``REPOWISE_SEAM_*``)+ are skipped: a cloned repo's file must never pick what repowise imports."""+ from repowise.core.registry.plugins import is_plugin_control_var+env_file = repo_path / ".repowise" / ".env"if not env_file.exists():return@@ -37,11 +44,28 @@ def load_dotenv(repo_path: Path) -> None:raw_value = raw_value[:hash_idx].rstrip()# Strip matching surrounding quotesvalue = _strip_quotes(raw_value)+ if is_plugin_control_var(key):+ _warn_plugin_key(env_file, key)+ continue# Don't overwrite existing env vars (explicit env takes priority)if key and value and key not in os.environ:os.environ[key] = value+def _warn_plugin_key(env_file: Path, key: str) -> None:+ global _warned_plugin_keys+ if _warned_plugin_keys:+ return+ _warned_plugin_keys = True+ import click++ click.echo(+ f"repowise: ignoring {key} in {env_file}; plugin and seam selection "+ "is read from the process environment only.",+ err=True,+ )++def _strip_quotes(value: str) -> str:"""Strip one pair of matching surrounding single or double quotes."""if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 5c140b37a..5a7dcce92 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -32,6 +32,7 @@ from repowise.core.pipeline.progress import (emit_warning,)from repowise.core.registry import HookProgressCallback+from repowise.core.registry.plugins import load_pluginsfrom .phase_timing import timedfrom .phases._common import TEST_RUN_FILE_LIMIT, _phase_done, limit_to_top_pagerank@@ -282,6 +283,8 @@ async def run_pipeline(# Wrap the incoming progress callback so registered pipeline hooks fire# around each phase transition. Zero-op when no hooks are registered.+ # Plugins load first so the hooks they register are among them.+ load_plugins()progress = HookProgressCallback(progress)# Optional crash-resume checkpointing. When a JobStore is supplied, adiff --git a/packages/core/src/repowise/core/registry/README.md b/packages/core/src/repowise/core/registry/README.mdindex 48da71dc3..80603917f 100644--- a/packages/core/src/repowise/core/registry/README.md+++ b/packages/core/src/repowise/core/registry/README.md@@ -23,6 +23,7 @@ needs the collected entries.| `cli_registry` | `cli_registry` | Collect Click commands; `apply(root)` attaches them || `mcp_tool_registry` | `mcp_tool_registry` | Collect MCP tool functions; `apply(mcp)` registers them with FastMCP || `pipeline_hooks` | `pipeline_hooks` | Pre/post phase hooks; wrap a `ProgressCallback` with `HookProgressCallback` to fire them |+| `plugins` | `load_plugins()` | Discover plugins (`repowise.plugins` entry points, `REPOWISE_PLUGINS`); `SeamRegistry` maps a seam to named implementations |The convenience helpers `register_command(...)` and `register_hook(...)`operate on the default singletons. Tests construct their own@@ -37,11 +38,12 @@ registry/cli_registry.py # CLIRegistry + cli_registry singletonmcp_tool_registry.py # MCPToolRegistry + mcp_tool_registry singletonpipeline_hooks.py # PipelineHookRegistry + HookProgressCallback + singleton+ plugins.py # load_plugins + SeamRegistryREADME.md```-Every file is under 200 lines; no module-level state beyond the three-singletons.+No module-level state beyond the three singletons, the plugin loader's+record of what loaded, and the seams defined so far.## Extension points@@ -61,6 +63,7 @@ singletons.- `tests/unit/registry/test_cli_registry.py`- `tests/unit/registry/test_mcp_tool_registry.py`- `tests/unit/registry/test_pipeline_hooks.py`+- `tests/unit/registry/test_plugins.py`Each test uses an isolated registry instance to avoid coupling acrosstests.diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.pyindex 3cd8f338f..35606bd4b 100644--- a/packages/core/src/repowise/core/registry/__init__.py+++ b/packages/core/src/repowise/core/registry/__init__.py@@ -9,6 +9,8 @@ forking the source tree:them with a :class:`FastMCP` server at boot.- :mod:`pipeline_hooks` lets plugins observe (and eventually mutate)pipeline phase transitions.+- :mod:`plugins` discovers installed plugins and holds named seams+ (``SeamRegistry``) whose local default a plugin can replace.Each registry is a small module-level singleton plus a ``CLIRegistry`` /``MCPToolRegistry`` / ``PipelineHookRegistry`` class so callers thatdiff --git a/packages/core/src/repowise/core/registry/cli_registry.py b/packages/core/src/repowise/core/registry/cli_registry.pyindex 67df2b0e3..05ed08d51 100644--- a/packages/core/src/repowise/core/registry/cli_registry.py+++ b/packages/core/src/repowise/core/registry/cli_registry.py@@ -51,12 +51,16 @@ OSS CLI overrides it whether either side is lazy or eager.from __future__ import annotationsimport importlib+import loggingfrom typing import TYPE_CHECKING, NamedTupleif TYPE_CHECKING:import click+_log = logging.getLogger("repowise.plugins")++class LazyCommand(NamedTuple):"""A command named now and imported later.@@ -78,7 +82,8 @@ class CLIRegistry:def __init__(self) -> None:self._entries: list[tuple[click.BaseCommand | None, click.BaseCommand | LazyCommand]] = []- self._applied_to: list[int] = []+ #: root id -> how many entries are already attached to it.+ self._applied: dict[int, int] = {}def register(self,@@ -104,19 +109,25 @@ class CLIRegistry:"""self._entries.append((parent, LazyCommand(name, target)))- def apply(self, root: click.BaseCommand) -> click.BaseCommand:+ def apply(self, root: click.BaseCommand, *, replace: bool = True) -> click.BaseCommand:"""Attach every registered command. Returns *root* for chaining.- Idempotent per *root* — calling ``apply`` twice with the same- Click group is a no-op. Passing a different group registers- every entry against that group too (useful for tests that build- an isolated root).+ ``replace=False`` (used for discovered plugins) refuses, with a+ warning, any name the target group already holds, lazy or resolved.++ Idempotent per *root* — a repeat call attaches only entries+ registered since the last one (plugins discovered after startup),+ so with nothing new it is a no-op. Passing a different group+ registers every entry against that group too (useful for tests+ that build an isolated root)."""root_id = id(root)- if root_id in self._applied_to:- return root- for parent, command in self._entries:+ start = self._applied.get(root_id, 0)+ for parent, command in self._entries[start:]:target = parent if parent is not None else root+ if not replace and _holds(target, command.name):+ _log.warning("repowise: plugin command %r ignored, the name is taken", command.name)+ continueif isinstance(command, LazyCommand):add_lazy = getattr(target, "add_lazy_command", None)if add_lazy is not None:@@ -126,19 +137,25 @@ class CLIRegistry:# at the cost of importing it now.command = command.load()target.add_command(command) # type: ignore[attr-defined]- self._applied_to.append(root_id)+ self._applied[root_id] = len(self._entries)return rootdef reset(self) -> None:"""Drop every registered entry. Used by tests."""self._entries.clear()- self._applied_to.clear()+ self._applied.clear()def commands(self) -> list[click.BaseCommand]:"""Return every registered command, importing lazy ones. Used by tests."""return [cmd.load() if isinstance(cmd, LazyCommand) else cmd for _, cmd in self._entries]+def _holds(group: click.BaseCommand, name: str | None) -> bool:+ """Whether *group* already has a command called *name*, lazy or resolved."""+ lazy = getattr(group, "_lazy_commands", {})+ return name in getattr(group, "commands", {}) or name in lazy++cli_registry = CLIRegistry()"""Process-wide default registry used by the OSS CLI."""diff --git a/packages/core/src/repowise/core/registry/plugins.py b/packages/core/src/repowise/core/registry/plugins.pynew file mode 100644index 000000000..7417de945--- /dev/null+++ b/packages/core/src/repowise/core/registry/plugins.py@@ -0,0 +1,220 @@+"""Plugin discovery and named seams.++Plugins come from the ``repowise.plugins`` entry-point group and from+``REPOWISE_PLUGINS`` (comma-separated ``module`` or ``module:attr``). Each+is imported once and a callable target is called with no arguments; a+failure is recorded and skipped, never raised. Both variables are read+from the real process environment only, never from a repo's ``.env``.++A consumer defines and resolves a seam in three lines::++ authenticators = SeamRegistry("authenticator")+ authenticators.register("local", SharedKeyAuthenticator())+ authenticator = authenticators.get() # or .get(name) from config++``get`` picks an explicit name, then ``REPOWISE_SEAM_<SEAM>``, then the last+implementation registered with ``default=True``, then the first registered.++Discovery (about 100 ms) runs at ``SeamRegistry.get``, FastAPI app creation,+MCP surface attach and each pipeline run; built-in CLI dispatch never runs+it, only an unknown command name or a command listing does. Ceiling: a+discovered plugin can add CLI commands but not replace a built-in one.+Loading is meant for one thread: a registration made from another thread+while plugins load is misattributed, and a plugin that waits on a thread+calling ``get()`` deadlocks.+"""++from __future__ import annotations++import importlib+import logging+import os+import re+import threading+from dataclasses import dataclass, field+from typing import Generic, TypeVar++ENTRY_POINT_GROUP = "repowise.plugins"+ENV_VAR = "REPOWISE_PLUGINS"+SEAM_ENV_PREFIX = "REPOWISE_SEAM_"++_log = logging.getLogger("repowise.plugins")+_SEAM_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]*")+T = TypeVar("T")+++def is_plugin_control_var(key: str) -> bool:+ """True for env vars that choose code to run: never taken from a repo file."""+ return key == ENV_VAR or key.startswith(SEAM_ENV_PREFIX)+++@dataclass+class PluginRecord:+ """What happened when one plugin loaded."""++ name: str+ source: str # "entry point" or "env"+ target: str # "module" or "module:attr"+ status: str = "loaded" # or "failed" / "skipped"+ error: str | None = None+ #: ``"seam:implementation"`` pairs registered while this plugin loaded.+ seams: list[str] = field(default_factory=list)+++_lock = threading.RLock()+_records: list[PluginRecord] | None = None+_current: PluginRecord | None = None+_SEAMS: dict[str, SeamRegistry] = {}+++def _discover() -> list[PluginRecord]:+ found: list[PluginRecord] = []+ try:+ from importlib.metadata import entry_points++ for ep in entry_points(group=ENTRY_POINT_GROUP):+ target = f"{ep.module}:{ep.attr}" if ep.attr else ep.module+ found.append(PluginRecord(ep.name, "entry point", target))+ except Exception as exc: # corrupt metadata must not stop startup+ found.append(+ PluginRecord(ENTRY_POINT_GROUP, "entry point", "", "failed", _reason(exc))+ )+ for spec in os.environ.get(ENV_VAR, "").split(","):+ spec = spec.strip()+ if spec:+ found.append(PluginRecord(spec, "env", spec))+ return found+++def _reason(exc: BaseException) -> str:+ return f"{type(exc).__name__}: {exc}"+++def _load(record: PluginRecord) -> None:+ global _current+ _current = record+ try:+ module_name, _, attr = record.target.partition(":")+ obj = importlib.import_module(module_name.strip())+ if attr:+ for part in attr.strip().split("."):+ obj = getattr(obj, part)+ if callable(obj):+ obj()+ except (Exception, SystemExit) as exc:+ record.status = "failed"+ record.error = _reason(exc)+ _log.warning("repowise plugin %s (%s) failed to load: %s", record.name, record.source, record.error)+ finally:+ _current = None+++def load_plugins() -> list[PluginRecord]:+ """Discover and load every plugin once; return what happened to each."""+ global _records+ with _lock:+ if _records is not None:+ return list(_records)+ # Set before loading so a plugin that resolves a seam re-enters here+ # and returns instead of recursing.+ _records = []+ try:+ first_source: dict[str, str] = {}+ for record in _discover():+ if record.status == "loaded":+ if record.target in first_source:+ record.status = "skipped"+ record.error = f"duplicate of the {first_source[record.target]} plugin"+ else:+ first_source[record.target] = record.source+ _load(record)+ _records.append(record)+ except BaseException:+ _records = None # a KeyboardInterrupt mid-load must not freeze a partial list+ raise+ return list(_records)+++def reset() -> None:+ """Forget loaded plugins so the next ``load_plugins`` runs again. For tests."""+ global _records+ with _lock:+ _records = None+++def seams() -> dict[str, SeamRegistry]:+ """Every seam defined in this process, by name."""+ return dict(_SEAMS)+++class SeamRegistry(Generic[T]):+ """Seam name to named implementations, with one chosen default.++ Defining a seam name again returns the existing registry, so a module+ reload keeps what plugins registered.+ """++ seam: str+ env_var: str+ _impls: dict[str, T]+ _chosen: str | None++ def __new__(cls, seam: str) -> SeamRegistry[T]:+ if not _SEAM_NAME.fullmatch(seam):+ raise ValueError(f"invalid seam name {seam!r}")+ existing = _SEAMS.get(seam)+ if existing is not None:+ return existing+ self = super().__new__(cls)+ self.seam = seam+ self.env_var = SEAM_ENV_PREFIX + seam.upper().replace("-", "_")+ self._impls = {}+ self._chosen = None+ _SEAMS[seam] = self+ return self++ def register(self, name: str, impl: T, *, default: bool = False) -> None:+ """Add *impl* under *name*; ``default=True`` makes it the chosen one."""+ self._impls[name] = impl+ if default:+ self._chosen = name+ if _current is not None:+ _current.seams.append(f"{self.seam}:{name}")++ @property+ def names(self) -> list[str]:+ return list(self._impls)++ @property+ def default(self) -> str | None:+ """The name ``get()`` resolves when the caller passes none."""+ selected = os.environ.get(self.env_var, "").strip()+ return selected or self._chosen or next(iter(self._impls), None)++ def get(self, name: str | None = None) -> T:+ """Return the selected implementation, loading plugins first."""+ load_plugins()+ name = name or self.default+ if name is None:+ raise LookupError(f"no implementation registered for seam {self.seam!r}")+ try:+ return self._impls[name]+ except KeyError:+ # Loud on purpose: silently falling back to the local default+ # would hide a misconfigured auth or data source.+ raise KeyError(+ f"seam {self.seam!r} has no implementation {name!r}; registered: {self.names}"+ ) from None+++__all__ = [+ "ENTRY_POINT_GROUP",+ "ENV_VAR",+ "SEAM_ENV_PREFIX",+ "PluginRecord",+ "SeamRegistry",+ "is_plugin_control_var",+ "load_plugins",+ "reset",+ "seams",+]diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex db7b8a59b..7407351f0 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -396,6 +396,9 @@ _ROUTERS = (def create_app() -> FastAPI:"""Build and return the configured FastAPI application."""+ from repowise.core.registry.plugins import load_plugins++ load_plugins()app = FastAPI(title="repowise API",description="REST API for repowise — codebase documentation engine",diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 2edf54d2d..73fd53388 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -298,8 +298,10 @@ def ensure_full_surface() -> Any:)from repowise.core.registry import mcp_tool_registry+ from repowise.core.registry.plugins import load_pluginsfrom repowise.server.mcp_server._tool_selection import snapshot_full_surface+ load_plugins() # plugin tools register before the surface is attachedmcp_tool_registry.apply(_mcp, middleware=registered_tool)# Snapshot the full registered surface so per-server tool selectiondiff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 15fe3d1cf..60fcf56b1 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -37,7 +37,8 @@ _EXPECTED_NAMES = frozenset("dead-code", "decision", "delete", "distill", "doc-drift", "doctor","expand","export", "generate", "generate-claude-md", "health", "hook",- "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "publish", "reindex",+ "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "plugins",+ "publish", "reindex","restyle","risk", "saved", "savings", "search", "security", "serve", "status", "symbol","telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why",diff --git a/tests/unit/registry/test_cli_registry.py b/tests/unit/registry/test_cli_registry.pyindex 3cca18c14..42352453e 100644--- a/tests/unit/registry/test_cli_registry.py+++ b/tests/unit/registry/test_cli_registry.py@@ -49,6 +49,15 @@ def test_apply_is_idempotent_per_root(registry, root):assert list(root.commands.keys()) == ["once"]+def test_apply_attaches_entries_registered_after_the_first_call(registry, root):+ """Plugins discovered after startup reach a root that was already applied."""+ registry.register(_make_command("builtin"))+ registry.apply(root)+ registry.register(_make_command("from-plugin"))+ registry.apply(root)+ assert list(root.commands.keys()) == ["builtin", "from-plugin"]++def test_apply_supports_multiple_roots(registry):registry.register(_make_command("shared"))diff --git a/tests/unit/registry/test_plugins.py b/tests/unit/registry/test_plugins.pynew file mode 100644index 000000000..98f2956b1--- /dev/null+++ b/tests/unit/registry/test_plugins.py@@ -0,0 +1,301 @@+"""Plugin discovery, SeamRegistry selection, and the ``repowise plugins`` listing."""++from __future__ import annotations++import importlib.metadata+import json+import os+import subprocess+import sys+import textwrap+import uuid++import click+import pytest+from click.testing import CliRunner++from repowise.cli._instrumented_group import InstrumentedGroup+from repowise.core import registry as registry_pkg+from repowise.core.registry import CLIRegistry, plugins+from repowise.core.registry.plugins import SeamRegistry, load_plugins++[email protected](autouse=True)+def _isolated(monkeypatch):+ monkeypatch.setattr(plugins, "_SEAMS", {})+ monkeypatch.delenv(plugins.ENV_VAR, raising=False)+ monkeypatch.setattr(importlib.metadata, "entry_points", lambda **kw: [])+ plugins.reset()+ yield+ plugins.reset()+++def make_module(tmp_path, monkeypatch):+ """Write a uniquely named module onto sys.path and return its name."""+ monkeypatch.syspath_prepend(str(tmp_path))++ def make(body: str) -> str:+ name = f"rw_test_plugin_{uuid.uuid4().hex[:8]}"+ (tmp_path / f"{name}.py").write_text(textwrap.dedent(body), encoding="utf-8")+ return name++ return make+++_REGISTER_ACME = """+ from repowise.core.registry.plugins import seams+ calls = []++ def register():+ calls.append(1)+ seams()["demo"].register("acme", "ACME", default=True)+"""+++def _entry_points(monkeypatch, *pairs: tuple[str, str]) -> None:+ eps = [importlib.metadata.EntryPoint(n, v, plugins.ENTRY_POINT_GROUP) for n, v in pairs]+ monkeypatch.setattr(+ importlib.metadata,+ "entry_points",+ lambda **kw: eps if kw.get("group") == plugins.ENTRY_POINT_GROUP else [],+ )+++def test_entry_point_plugin_registers_into_a_seam(monkeypatch, make_module):+ seam = SeamRegistry("demo")+ seam.register("local", "LOCAL")+ mod = make_module(_REGISTER_ACME)+ _entry_points(monkeypatch, ("acme", f"{mod}:register"))++ [record] = load_plugins()+ assert (record.name, record.source, record.status) == ("acme", "entry point", "loaded")+ assert record.seams == ["demo:acme"]+ assert seam.get() == "ACME"+++def test_env_var_specs_load_modules_and_callables(monkeypatch, make_module):+ plain = make_module("import sys\nsys.modules[__name__].imported = True\n")+ seam = SeamRegistry("demo")+ seam.register("local", "LOCAL")+ func = make_module(_REGISTER_ACME)+ monkeypatch.setenv(plugins.ENV_VAR, f" {plain} ,{func}:register,")++ records = load_plugins()+ assert [(r.target, r.source, r.status) for r in records] == [+ (plain, "env", "loaded"),+ (f"{func}:register", "env", "loaded"),+ ]+ assert sys.modules[plain].imported is True+ assert seam.get() == "ACME"+++def test_broken_plugins_are_reported_not_raised(monkeypatch, make_module):+ raises = make_module("def register():\n raise RuntimeError('boom')\n")+ exits = make_module("import sys\nsys.exit(3)\n")+ exits_on_call = make_module("import sys\ndef register():\n sys.exit('nope')\n")+ good = make_module("loaded = True\n")+ monkeypatch.setenv(+ plugins.ENV_VAR,+ f"no_such_module_xyz,{raises}:register,{exits},{exits_on_call}:register,"+ f"{good}:missing_attr,{good}",+ )++ records = load_plugins()+ status = {r.target: (r.status, r.error) for r in records}+ assert status["no_such_module_xyz"][0] == "failed"+ assert "ModuleNotFoundError" in status["no_such_module_xyz"][1]+ assert status[f"{raises}:register"] == ("failed", "RuntimeError: boom")+ assert status[exits] == ("failed", "SystemExit: 3")+ assert status[f"{exits_on_call}:register"] == ("failed", "SystemExit: nope")+ assert status[f"{good}:missing_attr"][0] == "failed"+ assert status[good] == ("loaded", None)+++def test_loading_is_idempotent_and_deduplicated(monkeypatch, make_module):+ SeamRegistry("demo")+ mod = make_module(_REGISTER_ACME)+ _entry_points(monkeypatch, ("acme", f"{mod}:register"))+ monkeypatch.setenv(plugins.ENV_VAR, f"{mod}:register")++ first = load_plugins()+ assert load_plugins() == first+ assert [(r.source, r.status) for r in first] == [("entry point", "loaded"), ("env", "skipped")]+ assert first[1].error == "duplicate of the entry point plugin"+ assert sys.modules[mod].calls == [1]+++def test_a_plugin_may_resolve_a_seam_while_loading(monkeypatch, make_module):+ seam = SeamRegistry("demo")+ seam.register("local", "LOCAL")+ mod = make_module(+ """+ from repowise.core.registry.plugins import seams+ seen = []++ def register():+ seen.append(seams()["demo"].get())+ """+ )+ monkeypatch.setenv(plugins.ENV_VAR, f"{mod}:register")+ [record] = load_plugins()+ assert record.status == "loaded"+ assert sys.modules[mod].seen == ["LOCAL"]+++def test_an_interrupt_mid_load_lets_a_later_call_retry(monkeypatch, make_module):+ mod = make_module("def register():\n raise KeyboardInterrupt\n")+ monkeypatch.setenv(plugins.ENV_VAR, f"{mod}:register")+ with pytest.raises(KeyboardInterrupt):+ load_plugins()+ assert plugins._records is None+++def test_local_default_wins_until_something_selects_another(monkeypatch):+ seam: SeamRegistry[str] = SeamRegistry("demo-seam")+ seam.register("local", "LOCAL")+ seam.register("other", "OTHER")+ assert seam.default == "local"+ assert seam.get() == "LOCAL"+ assert seam.get("other") == "OTHER"++ monkeypatch.setenv("REPOWISE_SEAM_DEMO_SEAM", " other ")+ assert seam.get() == "OTHER"+ monkeypatch.delenv("REPOWISE_SEAM_DEMO_SEAM")++ seam.register("chosen", "CHOSEN", default=True)+ assert seam.get() == "CHOSEN"+ assert seam.names == ["local", "other", "chosen"]+++def test_seam_errors_are_loud():+ seam = SeamRegistry("demo")+ with pytest.raises(LookupError):+ seam.get()+ seam.register("local", "LOCAL")+ with pytest.raises(KeyError, match="no implementation 'missing'"):+ seam.get("missing")+ assert SeamRegistry("demo") is seam # a reload reuses what plugins registered+ for bad in ("", "1st", "has space", "a.b"):+ with pytest.raises(ValueError):+ SeamRegistry(bad)+++def test_a_discovered_plugin_adds_a_cli_command(monkeypatch, make_module):+ isolated = CLIRegistry()+ monkeypatch.setattr(registry_pkg, "cli_registry", isolated)+ mod = make_module(+ """+ import click+ from repowise.core import registry++ @click.command("acme-hello")+ def hello():+ click.echo("hi")++ registry.cli_registry.register(hello)+ """+ )+ monkeypatch.setenv(plugins.ENV_VAR, mod)++ plain = InstrumentedGroup("root")+ assert plain.get_command(click.Context(plain), "acme-hello") is None+ assert plugins._records is None # a group that does not discover never loads++ root = InstrumentedGroup("root", discover_plugins=True)+ isolated.apply(root)+ ctx = click.Context(root)+ assert "acme-hello" in root.list_commands(ctx)+ assert root.get_command(ctx, "acme-hello").name == "acme-hello"+++def test_a_plugin_cannot_take_a_builtin_name_even_after_help(monkeypatch, make_module):+ isolated = CLIRegistry()+ monkeypatch.setattr(registry_pkg, "cli_registry", isolated)+ mod = make_module(+ """+ import click+ from repowise.core import registry++ @click.command("expand")+ def impostor():+ click.echo("impostor")++ registry.cli_registry.register(impostor)+ """+ )+ monkeypatch.setenv(plugins.ENV_VAR, mod)+ root = InstrumentedGroup("root", discover_plugins=True)+ root.add_lazy_command("expand", "repowise.cli.commands.expand_cmd:expand_command")++ assert CliRunner().invoke(root, ["--help"]).exit_code == 0 # the listing loads plugins+ assert plugins._records is not None+ resolved = root.get_command(click.Context(root), "expand")+ assert resolved is not sys.modules[mod].impostor+++def test_dotenv_never_sets_plugin_or_seam_selection(tmp_path, monkeypatch, capsys):+ from repowise.cli.ui import env_persistence++ monkeypatch.setattr(env_persistence, "_warned_plugin_keys", False)+ monkeypatch.delenv("REPOWISE_SEAM_AUTHENTICATOR", raising=False)+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / ".env").write_text(+ "REPOWISE_PLUGINS=evil_module:run\n"+ "export REPOWISE_SEAM_AUTHENTICATOR=evil\n"+ "RW_TEST_DOTENV_KEY=kept\n",+ encoding="utf-8",+ )+ try:+ env_persistence.load_dotenv(tmp_path)+ assert plugins.ENV_VAR not in os.environ+ assert "REPOWISE_SEAM_AUTHENTICATOR" not in os.environ+ assert os.environ["RW_TEST_DOTENV_KEY"] == "kept"+ finally:+ os.environ.pop("RW_TEST_DOTENV_KEY", None)+ assert capsys.readouterr().err.count("ignoring") == 1+++def test_plugins_command_json_and_table(monkeypatch, make_module):+ from repowise.cli.commands.plugins_cmd import plugins_command++ seam = SeamRegistry("demo")+ seam.register("local", "LOCAL")+ good = make_module(_REGISTER_ACME)+ monkeypatch.setenv(plugins.ENV_VAR, f"{good}:register,no_such_module_xyz")++ result = CliRunner().invoke(plugins_command, ["--format", "json"])+ assert result.exit_code == 0, result.output+ payload = json.loads(result.output)+ assert [(p["name"], p["status"], p["seams"]) for p in payload["plugins"]] == [+ (f"{good}:register", "loaded", ["demo:acme"]),+ ("no_such_module_xyz", "failed", []),+ ]+ assert payload["seams"] == {"demo": {"default": "acme", "implementations": ["local", "acme"]}}++ table = CliRunner().invoke(plugins_command, [])+ assert table.exit_code == 0, table.output+ assert "loaded" in table.output and "failed" in table.output+ assert "seam demo: acme" in table.output+++def test_plugins_command_with_nothing_installed():+ from repowise.cli.commands.plugins_cmd import plugins_command++ result = CliRunner().invoke(plugins_command, [])+ assert result.exit_code == 0+ assert "No plugins loaded" in result.output+++def test_dispatching_a_builtin_command_never_runs_discovery():+ """Discovery costs ~100 ms, so a known command must not pay it."""+ probe = (+ "from click.testing import CliRunner; "+ "from repowise.cli.main import cli; "+ "from repowise.core.registry import plugins; "+ "res = CliRunner().invoke(cli, ['expand', '--help']); "+ "assert res.exit_code == 0, res.output; "+ "print(plugins._records is None)"+ )+ out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, check=True)+ assert out.stdout.strip().splitlines()[-1] == "True"