Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(plugins): list every plugin registration, load plugin providers, add SeamRegistry.all and PLUGIN_API_VERSION (#4741)

Raghav Chamadiyafe542b23b05f
diff --git a/packages/cli/src/repowise/cli/commands/plugins_cmd.py b/packages/cli/src/repowise/cli/commands/plugins_cmd.py
index 7577effe1..a234eb47b 100644
--- a/packages/cli/src/repowise/cli/commands/plugins_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/plugins_cmd.py
@@ -2,12 +2,40 @@
from __future__ import annotations
+import importlib
from dataclasses import asdict
import click
from repowise.cli.output import emit_json, format_option
+#: Modules that define a seam or register its built-in implementations. A seam
+#: is only listed once its module is imported; a guard test keeps this complete.
+BUILTIN_SEAM_MODULES = (
+ "repowise.core.changes.outcomes",
+ "repowise.core.changes.source",
+ "repowise.core.events.sinks",
+ "repowise.core.inventory.advisories",
+ "repowise.core.ownership.directory",
+ "repowise.core.report.sections",
+ "repowise.core.report.render",
+ "repowise.core.suspects",
+ "repowise.server.auth",
+ "repowise.server.chat_session",
+ "repowise.server.chat_views",
+ "repowise.server.chat_datasets",
+)
+
+
+def _import_builtin_seams() -> None:
+ for name in BUILTIN_SEAM_MODULES:
+ try:
+ module = importlib.import_module(name)
+ if name == "repowise.server.chat_datasets":
+ module.dataset_names() # imports the built-in dataset families
+ except ImportError: # server extras not installed: those seams go unlisted
+ continue
+
@click.command("plugins")
@format_option()
@@ -16,17 +44,31 @@ def plugins_command(fmt: str) -> None:
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
+ from repowise.core.registry.plugins import (
+ ENTRY_POINT_GROUP,
+ ENV_VAR,
+ PLUGIN_API_VERSION,
+ load_plugins,
+ seams,
+ )
+ _import_builtin_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})
+ emit_json(
+ {
+ "api_version": PLUGIN_API_VERSION,
+ "plugins": [asdict(r) for r in records],
+ "seams": seam_rows,
+ }
+ )
return
+ console.print(f"plugin API version {PLUGIN_API_VERSION}")
if not records:
console.print(
f"No plugins loaded. Install one that declares a [bold]{ENTRY_POINT_GROUP}[/bold] "
diff --git a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
index e413906b3..544f27f69 100644
--- a/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/report_assessment_cmd.py
@@ -108,12 +108,13 @@ def _renderer(fmt: str) -> Any:
"""The renderer *fmt* names on the ``report-renderer`` seam; a usage error otherwise."""
from repowise.core.report.render import report_renderers
- if fmt not in report_renderers.names:
+ available = dict(report_renderers.all()) # loads plugins, so plugin formats count
+ if fmt not in available:
raise click.BadParameter(
- f"unknown format {fmt!r}; available: {', '.join(report_renderers.names)}",
+ f"unknown format {fmt!r}; available: {', '.join(available)}",
param_hint="--format",
)
- return report_renderers.get(fmt)
+ return available[fmt]
def _emit(text: str, fmt: str, out_path: str | None, document: dict) -> None:
diff --git a/packages/core/src/repowise/core/changes/outcomes.py b/packages/core/src/repowise/core/changes/outcomes.py
index 7199f4018..efabf4ee7 100644
--- a/packages/core/src/repowise/core/changes/outcomes.py
+++ b/packages/core/src/repowise/core/changes/outcomes.py
@@ -39,7 +39,7 @@ from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Protocol
-from repowise.core.registry.plugins import SeamRegistry, load_plugins
+from repowise.core.registry.plugins import SeamRegistry
#: The window :func:`file_fix_rate` counts in, unless ``changes.outcome_fix_days`` says.
DEFAULT_FIX_DAYS = 30
@@ -403,9 +403,8 @@ def outcome_links(repo_path: Path | str, head: str, change: OutcomeTarget) -> li
"""
out: list[OutcomeLink] = []
seen: set[tuple[str, str]] = set()
- load_plugins()
- for name in change_outcome_providers.names:
- for link in change_outcome_providers.get(name).links(Path(repo_path), head, change):
+ for _name, provider in change_outcome_providers.all():
+ for link in provider.links(Path(repo_path), head, change):
if (link.kind, link.sha) not in seen:
seen.add((link.kind, link.sha))
out.append(link)
diff --git a/packages/core/src/repowise/core/providers/embedding/registry.py b/packages/core/src/repowise/core/providers/embedding/registry.py
index 15406be30..7ab79ec07 100644
--- a/packages/core/src/repowise/core/providers/embedding/registry.py
+++ b/packages/core/src/repowise/core/providers/embedding/registry.py
@@ -60,6 +60,9 @@ def register_embedder(name: str, factory: Callable[..., Embedder]) -> None:
if name in _BUILTIN_EMBEDDERS:
raise ValueError(f"Cannot register {name!r}: conflicts with a built-in embedder.")
_custom_embedders[name] = factory
+ from repowise.core.registry.plugins import note_registration
+
+ note_registration("embedder", name)
def get_embedder(name: str, **kwargs: Any) -> Embedder:
@@ -80,6 +83,11 @@ def get_embedder(name: str, **kwargs: Any) -> Embedder:
embedder = get_embedder("openai", api_key="sk-...", model="text-embedding-3-large")
vectors = await embedder.embed(["Hello world"])
"""
+ if name not in _custom_embedders and name not in _BUILTIN_EMBEDDERS:
+ # Deferred: a built-in name never pays plugin discovery.
+ from repowise.core.registry.plugins import load_plugins
+
+ load_plugins() # a plugin package may register it
if name in _custom_embedders:
return _custom_embedders[name](**kwargs)
@@ -109,5 +117,8 @@ def get_embedder(name: str, **kwargs: Any) -> Embedder:
def list_embedders() -> list[str]:
- """Return a sorted list of all available embedder names."""
+ """Return a sorted list of all available embedder names, plugins' included."""
+ from repowise.core.registry.plugins import load_plugins
+
+ load_plugins()
return sorted(set(_BUILTIN_EMBEDDERS) | set(_custom_embedders))
diff --git a/packages/core/src/repowise/core/providers/llm/registry.py b/packages/core/src/repowise/core/providers/llm/registry.py
index 4d808832f..9fc78191d 100644
--- a/packages/core/src/repowise/core/providers/llm/registry.py
+++ b/packages/core/src/repowise/core/providers/llm/registry.py
@@ -220,6 +220,9 @@ def register_provider(name: str, factory: Callable[..., BaseProvider]) -> None:
"Choose a different name."
)
_custom_providers[name] = factory
+ from repowise.core.registry.plugins import note_registration
+
+ note_registration("llm-provider", name)
def get_provider(
@@ -258,6 +261,11 @@ def get_provider(
)
response = await provider.generate(system_prompt="...", user_prompt="...")
"""
+ if name not in _custom_providers and name not in PROVIDER_SPECS:
+ # Deferred: a built-in name never pays plugin discovery.
+ from repowise.core.registry.plugins import load_plugins
+
+ load_plugins() # a plugin package may register it
if name in _custom_providers:
return _custom_providers[name](**kwargs)
@@ -290,6 +298,9 @@ def list_providers() -> list[str]:
Includes both built-in and runtime-registered custom providers.
"""
+ from repowise.core.registry.plugins import load_plugins
+
+ load_plugins()
return sorted(set(_BUILTIN_PROVIDERS) | set(_custom_providers))
diff --git a/packages/core/src/repowise/core/registry/README.md b/packages/core/src/repowise/core/registry/README.md
index 80603917f..f7e34c953 100644
--- a/packages/core/src/repowise/core/registry/README.md
+++ b/packages/core/src/repowise/core/registry/README.md
@@ -23,7 +23,13 @@ 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 |
+| `plugins` | `load_plugins()` | Discover plugins (`repowise.plugins` entry points, `REPOWISE_PLUGINS`); `SeamRegistry` maps a seam to named implementations, `get()` picks one and `all()` returns every one |
+
+`PLUGIN_API_VERSION` (exported from `repowise.core.registry`) is bumped on a
+breaking change to any registry or seam contract. Every registry, plus
+`register_provider` and `register_embedder`, records what a loading plugin
+registers as `kind:name` (`cli-command`, `mcp-tool`, `pipeline-hook`,
+`llm-provider`, `embedder`, or the seam name), which `repowise plugins` lists.
The convenience helpers `register_command(...)` and `register_hook(...)`
operate on the default singletons. Tests construct their own
@@ -57,6 +63,9 @@ record of what loaded, and the seams defined so far.
- **Adding a pipeline hook:** call `register_hook("parse", callback,
when="post")`. The orchestrator already wraps its progress callback
with `HookProgressCallback`, so the hook fires automatically.
+- **Adding an LLM provider or embedder:** call `register_provider(name,
+ factory)` or `register_embedder(name, factory)` from a plugin. Asking for a
+ name that is not built in loads plugins first.
## Tests
diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.py
index 35606bd4b..000fd1ff3 100644
--- a/packages/core/src/repowise/core/registry/__init__.py
+++ b/packages/core/src/repowise/core/registry/__init__.py
@@ -42,8 +42,10 @@ from .pipeline_hooks import (
pipeline_hooks,
register_hook,
)
+from .plugins import PLUGIN_API_VERSION
__all__ = [
+ "PLUGIN_API_VERSION",
"TOOL_SAFETY_KINDS",
"TOOL_TIERS",
"CLIRegistry",
diff --git a/packages/core/src/repowise/core/registry/cli_registry.py b/packages/core/src/repowise/core/registry/cli_registry.py
index 05ed08d51..10b201dfc 100644
--- a/packages/core/src/repowise/core/registry/cli_registry.py
+++ b/packages/core/src/repowise/core/registry/cli_registry.py
@@ -54,6 +54,8 @@ import importlib
import logging
from typing import TYPE_CHECKING, NamedTuple
+from .plugins import note_registration
+
if TYPE_CHECKING:
import click
@@ -93,6 +95,7 @@ class CLIRegistry:
) -> None:
"""Schedule *command* for attachment to *parent* (default: root)."""
self._entries.append((parent, command))
+ note_registration("cli-command", str(command.name))
def register_lazy(
self,
@@ -108,6 +111,7 @@ class CLIRegistry:
dispatches on before the module is ever loaded.
"""
self._entries.append((parent, LazyCommand(name, target)))
+ note_registration("cli-command", name)
def apply(self, root: click.BaseCommand, *, replace: bool = True) -> click.BaseCommand:
"""Attach every registered command. Returns *root* for chaining.
diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.py
index 88278288e..32a686232 100644
--- a/packages/core/src/repowise/core/registry/mcp_tool_registry.py
+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py
@@ -35,6 +35,8 @@ from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
+from .plugins import note_registration
+
if TYPE_CHECKING:
from .tool_selection import AvailabilityFacts
@@ -176,6 +178,7 @@ class MCPToolRegistry:
)
)
fn.__dict__["__repowise_trust_kind__"] = trust_kind
+ note_registration("mcp-tool", fn.__name__)
return fn
# Bare-decorator form: @mcp_tool_registry.register
diff --git a/packages/core/src/repowise/core/registry/pipeline_hooks.py b/packages/core/src/repowise/core/registry/pipeline_hooks.py
index 509b143ae..f809e0836 100644
--- a/packages/core/src/repowise/core/registry/pipeline_hooks.py
+++ b/packages/core/src/repowise/core/registry/pipeline_hooks.py
@@ -36,6 +36,8 @@ import enum
from collections.abc import Callable
from typing import Any
+from .plugins import note_registration
+
HookCallback = Callable[[str], None]
@@ -62,6 +64,7 @@ class PipelineHookRegistry:
"""Register *callback* to fire ``pre`` or ``post`` *phase*."""
when_enum = when if isinstance(when, HookPhase) else HookPhase(when)
self._hooks.setdefault((phase, when_enum), []).append(callback)
+ note_registration("pipeline-hook", f"{phase}.{when_enum.value}")
def fire(self, phase: str, when: HookPhase) -> None:
"""Invoke every registered hook for ``(phase, when)``.
diff --git a/packages/core/src/repowise/core/registry/plugins.py b/packages/core/src/repowise/core/registry/plugins.py
index 7417de945..3f8de6b17 100644
--- a/packages/core/src/repowise/core/registry/plugins.py
+++ b/packages/core/src/repowise/core/registry/plugins.py
@@ -14,6 +14,11 @@ A consumer defines and resolves a seam in three lines::
``get`` picks an explicit name, then ``REPOWISE_SEAM_<SEAM>``, then the last
implementation registered with ``default=True``, then the first registered.
+``all()`` returns every implementation, for seams where each one contributes.
+
+Each registry (seams, CLI commands, MCP tools, pipeline hooks, LLM providers,
+embedders) calls ``note_registration`` so ``repowise plugins`` can show what
+every plugin added. Providers import it lazily to keep their import cheap.
Discovery (about 100 ms) runs at ``SeamRegistry.get``, FastAPI app creation,
MCP surface attach and each pipeline run; built-in CLI dispatch never runs
@@ -30,6 +35,7 @@ import importlib
import logging
import os
import re
+import sys
import threading
from dataclasses import dataclass, field
from typing import Generic, TypeVar
@@ -38,6 +44,9 @@ ENTRY_POINT_GROUP = "repowise.plugins"
ENV_VAR = "REPOWISE_PLUGINS"
SEAM_ENV_PREFIX = "REPOWISE_SEAM_"
+#: Bumped on a breaking change to any registry or seam contract.
+PLUGIN_API_VERSION = 1
+
_log = logging.getLogger("repowise.plugins")
_SEAM_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]*")
T = TypeVar("T")
@@ -57,7 +66,9 @@ class PluginRecord:
target: str # "module" or "module:attr"
status: str = "loaded" # or "failed" / "skipped"
error: str | None = None
- #: ``"seam:implementation"`` pairs registered while this plugin loaded.
+ #: ``"kind:name"`` pairs registered while this plugin loaded, where kind is
+ #: a seam name or one of ``cli-command``, ``mcp-tool``, ``pipeline-hook``,
+ #: ``llm-provider``, ``embedder``.
seams: list[str] = field(default_factory=list)
@@ -142,6 +153,32 @@ def reset() -> None:
_records = None
+def note_registration(kind: str, name: str) -> None:
+ """Record ``kind:name`` against the plugin loading now; a no-op otherwise.
+
+ A built-in module first imported inside a plugin's ``register()`` registers
+ its own implementations then, so those are skipped: walking out from the
+ registry call, a repowise module body reached before any plugin frame means
+ the registration is built in. The registered object cannot tell, since a
+ plugin's report section or dataset is an instance of a repowise class.
+ """
+ if _current is not None and not _made_by_builtin_import():
+ _current.seams.append(f"{kind}:{name}")
+
+
+def _made_by_builtin_import() -> bool:
+ frame = sys._getframe(2) # the registry method; its callers follow
+ while frame is not None:
+ module = frame.f_globals.get("__name__", "")
+ if module == "repowise" or module.startswith("repowise."):
+ if frame.f_code.co_name == "<module>":
+ return True
+ elif not module.startswith("importlib"):
+ return False # plugin code asked for it
+ frame = frame.f_back
+ return False
+
+
def seams() -> dict[str, SeamRegistry]:
"""Every seam defined in this process, by name."""
return dict(_SEAMS)
@@ -178,8 +215,7 @@ class SeamRegistry(Generic[T]):
self._impls[name] = impl
if default:
self._chosen = name
- if _current is not None:
- _current.seams.append(f"{self.seam}:{name}")
+ note_registration(self.seam, name)
@property
def names(self) -> list[str]:
@@ -191,6 +227,11 @@ class SeamRegistry(Generic[T]):
selected = os.environ.get(self.env_var, "").strip()
return selected or self._chosen or next(iter(self._impls), None)
+ def all(self) -> list[tuple[str, T]]:
+ """Every ``(name, implementation)`` in registration order, loading plugins first."""
+ load_plugins()
+ return list(self._impls.items())
+
def get(self, name: str | None = None) -> T:
"""Return the selected implementation, loading plugins first."""
load_plugins()
@@ -210,11 +251,13 @@ class SeamRegistry(Generic[T]):
__all__ = [
"ENTRY_POINT_GROUP",
"ENV_VAR",
+ "PLUGIN_API_VERSION",
"SEAM_ENV_PREFIX",
"PluginRecord",
"SeamRegistry",
"is_plugin_control_var",
"load_plugins",
+ "note_registration",
"reset",
"seams",
]
diff --git a/packages/core/src/repowise/core/report/build.py b/packages/core/src/repowise/core/report/build.py
index c1d22a1b0..42723fda7 100644
--- a/packages/core/src/repowise/core/report/build.py
+++ b/packages/core/src/repowise/core/report/build.py
@@ -38,10 +38,8 @@ NOTICE = (
def available_sections(report: str = "assessment") -> list[tuple[str, Section]]:
"""Every registered section of the *report* kind, local ones and plugins', in report order."""
import repowise.core.report.sections # noqa: F401 (registers the local sections)
- from repowise.core.registry.plugins import load_plugins
- load_plugins()
- pairs = [(name, report_sections.get(name)) for name in report_sections.names]
+ pairs = report_sections.all()
return sorted(
((n, s) for n, s in pairs if s.report == report), key=lambda p: (p[1].order, p[0])
)
diff --git a/packages/core/src/repowise/core/suspects/rank.py b/packages/core/src/repowise/core/suspects/rank.py
index fa20777b6..c18a21dc1 100644
--- a/packages/core/src/repowise/core/suspects/rank.py
+++ b/packages/core/src/repowise/core/suspects/rank.py
@@ -17,7 +17,7 @@ from datetime import UTC, datetime
from typing import Protocol
from repowise.core.co_change import CoChangePartner
-from repowise.core.registry.plugins import SeamRegistry, load_plugins
+from repowise.core.registry.plugins import SeamRegistry
from repowise.core.stack_trace import Frame, map_to_repo_paths, parse_trace
RRF_K = 60
@@ -167,14 +167,13 @@ def rank_suspects(
*prepared* is :func:`prepare`'s result for this symptom and these repo
files, when the caller already has it. A signal that raises did not fire.
"""
- load_plugins()
- names = [n for n in suspect_signals.names if signals is None or n in signals]
+ selected = [(n, s) for n, s in suspect_signals.all() if signals is None or n in signals]
prepared = prepared or prepare(symptom, ctx)
fused: dict[str, float] = {c.change_id: 0.0 for c in candidates}
fired: dict[str, dict[str, SignalRank]] = {c.change_id: {} for c in candidates}
- for name in names:
+ for name, signal in selected:
try:
- found = suspect_signals.get(name).rank(prepared, candidates, ctx)
+ found = signal.rank(prepared, candidates, ctx)
hits = {cid: hit for cid, hit in found.items() if cid in fused}
except Exception:
_log.debug("suspect signal %s failed; it did not fire", name, exc_info=True)
diff --git a/packages/server/src/repowise/server/chat_views.py b/packages/server/src/repowise/server/chat_views.py
index 6e923c915..50ab1353c 100644
--- a/packages/server/src/repowise/server/chat_views.py
+++ b/packages/server/src/repowise/server/chat_views.py
@@ -143,8 +143,8 @@ def views_for(artifact_type: str) -> list[str]:
"""View names that accept an artifact of *artifact_type*."""
return [
name
- for name in _view_names()
- if (types := view_builders.get(name).artifact_types) is None or artifact_type in types
+ for name, builder in view_builders.all()
+ if (types := builder.artifact_types) is None or artifact_type in types
]
diff --git a/tests/unit/registry/test_plugins.py b/tests/unit/registry/test_plugins.py
index 98f2956b1..51e8a80d4 100644
--- a/tests/unit/registry/test_plugins.py
+++ b/tests/unit/registry/test_plugins.py
@@ -5,10 +5,12 @@ from __future__ import annotations
import importlib.metadata
import json
import os
+import re
import subprocess
import sys
import textwrap
import uuid
+from pathlib import Path
import click
import pytest
@@ -16,7 +18,14 @@ 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.providers.embedding import registry as embedders
+from repowise.core.providers.llm import registry as llm_providers
+from repowise.core.registry import (
+ CLIRegistry,
+ MCPToolRegistry,
+ PipelineHookRegistry,
+ plugins,
+)
from repowise.core.registry.plugins import SeamRegistry, load_plugins
@@ -35,8 +44,8 @@ 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]}"
+ def make(body: str, prefix: str = "rw_test_plugin") -> str:
+ name = f"{prefix}_{uuid.uuid4().hex[:8]}"
(tmp_path / f"{name}.py").write_text(textwrap.dedent(body), encoding="utf-8")
return name
@@ -267,16 +276,18 @@ def test_plugins_command_json_and_table(monkeypatch, make_module):
result = CliRunner().invoke(plugins_command, ["--format", "json"])
assert result.exit_code == 0, result.output
payload = json.loads(result.output)
+ assert payload["api_version"] == plugins.PLUGIN_API_VERSION == registry_pkg.PLUGIN_API_VERSION
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"]}}
+ 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
+ assert f"plugin API version {plugins.PLUGIN_API_VERSION}" in table.output
def test_plugins_command_with_nothing_installed():
@@ -299,3 +310,163 @@ def test_dispatching_a_builtin_command_never_runs_discovery():
)
out = subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True, check=True)
assert out.stdout.strip().splitlines()[-1] == "True"
+
+
+def test_all_returns_every_implementation_after_loading_plugins(monkeypatch, make_module):
+ seam = SeamRegistry("demo")
+ seam.register("local", "LOCAL")
+ monkeypatch.setenv(plugins.ENV_VAR, f"{make_module(_REGISTER_ACME)}:register")
+
+ assert seam.all() == [("local", "LOCAL"), ("acme", "ACME")]
+ assert plugins._records is not None
+
+
+_REGISTER_EVERYTHING = """
+ from repowise.core import registry
+ from repowise.core.providers.embedding import registry as embedders
+ from repowise.core.providers.llm import registry as llm_providers
+ from repowise.core.registry.plugins import seams
+
+ async def acme_tool() -> dict:
+ return {}
+
+ def register():
+ seams()["demo"].register("acme", "ACME")
+ registry.cli_registry.register_lazy("acme-hello", "acme.cli:hello")
+ registry.mcp_tool_registry.register()(acme_tool)
+ registry.pipeline_hooks.register("parse", lambda phase: None, when="post")
+ llm_providers.register_provider("acme-llm", lambda **kw: "LLM")
+ embedders.register_embedder("acme-embed", lambda **kw: "EMBED")
+"""
+
+
+def isolated_registries(monkeypatch):
+ for attr, cls in (
+ ("cli_registry", CLIRegistry),
+ ("mcp_tool_registry", MCPToolRegistry),
+ ("pipeline_hooks", PipelineHookRegistry),
+ ):
+ monkeypatch.setattr(registry_pkg, attr, cls())
+ monkeypatch.setattr(llm_providers, "_custom_providers", {})
+ monkeypatch.setattr(embedders, "_custom_embedders", {})
+
+
+def test_every_registration_kind_is_recorded_while_a_plugin_loads(
+ monkeypatch, make_module, isolated_registries
+):
+ SeamRegistry("demo")
+ monkeypatch.setenv(plugins.ENV_VAR, f"{make_module(_REGISTER_EVERYTHING)}:register")
+
+ [record] = load_plugins()
+ assert record.status == "loaded", record.error
+ assert record.seams == [
+ "demo:acme",
+ "cli-command:acme-hello",
+ "mcp-tool:acme_tool",
+ "pipeline-hook:parse.post",
+ "llm-provider:acme-llm",
+ "embedder:acme-embed",
+ ]
+ registry_pkg.pipeline_hooks.register("graph", lambda phase: None)
+ assert record.seams[-1] == "embedder:acme-embed" # outside a load, nothing is recorded
+
+
+def test_a_plugin_provider_resolves_by_name(monkeypatch, make_module, isolated_registries):
+ monkeypatch.setenv(plugins.ENV_VAR, f"{make_module(_REGISTER_EVERYTHING)}:register")
+ SeamRegistry("demo")
+
+ assert llm_providers.get_provider("acme-llm") == "LLM"
+ assert embedders.get_embedder("acme-embed") == "EMBED"
+ assert "acme-llm" in llm_providers.list_providers()
+ assert "acme-embed" in embedders.list_embedders()
+ with pytest.raises(ValueError, match="acme-llm"):
+ llm_providers.get_provider("no-such-llm")
+ with pytest.raises(ValueError, match="acme-embed"):
+ embedders.get_embedder("no-such-embedder")
+
+
+def test_a_builtin_provider_never_runs_discovery(isolated_registries):
+ llm_providers.get_provider("mock", with_rate_limiter=False)
+ embedders.get_embedder("mock")
+ assert plugins._records is None
+
+
+_IMPORTS_A_BUILTIN = """
+ from repowise.core.registry import pipeline_hooks
+ from repowise.core.registry.plugins import seams
+
+ def register():
+ import repowise.core.events.sinks as sinks # first import registers jsonl, stdout
+ from repowise.core.report.model import Section
+
+ sinks.event_sinks.register("acme", object())
+ # An instance of a repowise class, still the plugin's own.
+ seams()["report-section"].register("acme", Section(title="t", summary="s", collect=None))
+ pipeline_hooks.register("parse", lambda phase: None)
+"""
+
+
+def test_builtins_imported_while_a_plugin_loads_are_not_its_own(
+ monkeypatch, make_module, isolated_registries
+):
+ import repowise.core.events as events_pkg
+
+ # Unload the built-in so the plugin's import runs its registrations again.
+ monkeypatch.setattr(events_pkg, "sinks", importlib.import_module("repowise.core.events.sinks"))
+ monkeypatch.delitem(sys.modules, "repowise.core.events.sinks")
+ SeamRegistry("report-section")
+ monkeypatch.setenv(plugins.ENV_VAR, f"{make_module(_IMPORTS_A_BUILTIN)}:register")
+
+ [record] = load_plugins()
+ assert record.status == "loaded", record.error
+ assert record.seams == ["event-sink:acme", "report-section:acme", "pipeline-hook:parse.post"]
+ assert plugins.seams()["event-sink"].names == ["jsonl", "stdout", "acme"]
+
+
+def test_a_plugin_package_named_like_repowise_is_still_recorded(monkeypatch, make_module):
+ SeamRegistry("demo")
+ body = """
+ from repowise.core.registry.plugins import seams
+ seams()["demo"].register("hello", "HELLO")
+ """
+ monkeypatch.setenv(plugins.ENV_VAR, make_module(body, prefix="repowise_hello"))
+
+ [record] = load_plugins()
+ assert record.seams == ["demo:hello"]
+
+
+_REPO = Path(__file__).resolve().parents[3]
+_SEAM_DEFINITION = re.compile(r"=\s*SeamRegistry(?:\[[^\]]*\])?\(\s*[\"']([^\"']+)[\"']")
+
+
[email protected](scope="module")
+def plugins_json() -> dict:
+ """``repowise plugins --format json`` in a fresh process with no plugins."""
+ probe = (
+ "from click.testing import CliRunner; "
+ "from repowise.cli.commands.plugins_cmd import plugins_command; "
+ "print(CliRunner().invoke(plugins_command, ['--format', 'json']).output)"
+ )
+ env = {k: v for k, v in os.environ.items() if k != plugins.ENV_VAR}
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True, env=env
+ )
+ return json.loads(out.stdout)
+
+
+def test_plugins_command_lists_builtin_implementations(plugins_json):
+ seams = plugins_json["seams"]
+ assert {"bus-factor", "hotspots"} <= set(seams["report-section"]["implementations"])
+ assert seams["event-sink"] == {"default": "jsonl", "implementations": ["jsonl", "stdout"]}
+
+
+def test_plugins_command_imports_every_seam_defined_in_packages(plugins_json):
+ defined = {
+ m.group(1)
+ for path in (_REPO / "packages").glob("*/src/**/*.py")
+ for m in _SEAM_DEFINITION.finditer(path.read_text(encoding="utf-8"))
+ }
+ assert "report-section" in defined
+ missing = defined - set(plugins_json["seams"])
+ assert not missing, f"add the modules defining {sorted(missing)} to BUILTIN_SEAM_MODULES"