Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(plugins): discover plugins under the dodaios.<slot> entry-point groups (#579)
Ruben Lütke44468f867687
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.mdindex 2d0ed91ee0..de6d4f89bc 100644--- a/docs/LLM-CONTEXT.md+++ b/docs/LLM-CONTEXT.md@@ -272,7 +272,7 @@ L0 OS/Hardware Win32, CUDA, Mic/Speakers, global-hotkeysSeven groups frozen as `PLUGIN_GROUPS` in `jarvis/core/protocols.py:363-371`: `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`, `jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel` (plus `jarvis.turn` for end-of-turn detection, declared in `pyproject.toml:104`).-Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."jarvis.<group>"]`, and **must not import from `jarvis.*`** — only structural Protocol compatibility (registry at `jarvis/core/registry.py`). After editing entry-points: **`pip install -e . --no-deps`** is mandatory to activate them (this is the fourth layer of BUG-006/014).+Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."dodaios.<group>"]` (the earlier `jarvis.<group>` name stays valid and is read alongside it; the first-party tables still use it), and **must not import from `jarvis.*`** — only structural Protocol compatibility (registry at `jarvis/core/registry.py`). After editing entry-points: **`pip install -e . --no-deps`** is mandatory to activate them (this is the fourth layer of BUG-006/014).---diff --git a/docs/SINGLE-SOURCE-OF-TRUTH.md b/docs/SINGLE-SOURCE-OF-TRUTH.mdindex 2208b864ba..cea1e7fd18 100644--- a/docs/SINGLE-SOURCE-OF-TRUTH.md+++ b/docs/SINGLE-SOURCE-OF-TRUTH.md@@ -114,13 +114,18 @@ the first sentence while the rest is still being generated.## 4. The Plugin SystemPlugins live under `jarvis/plugins/<group>/<name>.py` and register via `pyproject.toml`-entry-points (`[project.entry-points."jarvis.<group>"]`). The system is **structural, not+entry-points (`[project.entry-points."dodaios.<group>"]`). The system is **structural, notnominal**: a plugin must satisfy the *shape* of a protocol, but **must not import from`jarvis.*`** inside the plugin module. This keeps plugins decoupled and independentlydistributable.-The seven frozen plugin groups: `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`,-`jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel`.+The plugin groups: `dodaios.wakeword`, `dodaios.stt`, `dodaios.tts`, `dodaios.brain`,+`dodaios.harness`, `dodaios.tool`, `dodaios.channel`, `dodaios.realtime`.++Each group is also read under its earlier name, `jarvis.<group>`, and that name stays+valid: a plugin published against it keeps loading without a change. A plugin that+registers the same name under both loads once; if the two point at different objects,+the `dodaios.<group>` registration is the one that loads.After editing entry-points, you must re-run `pip install -e . --no-deps` to make the newplugin active — a subtle trap that has caused real "my fix doesn't work" incidents.diff --git a/docs/architecture-overview.md b/docs/architecture-overview.mdindex c5530ad1fd..5efb3c20f3 100644--- a/docs/architecture-overview.md+++ b/docs/architecture-overview.md@@ -86,7 +86,9 @@ L0 OS/Hardware Win32, CUDA, Mic/Speakers, global-hotkeys### Plugin system (structural, not nominal)-Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."jarvis.<group>"]`, and **must not import from `jarvis.*`** inside the plugin module — only structural compatibility with the protocol (registry at `jarvis/core/registry.py`). After editing entry-points: `pip install -e . --no-deps`.+Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."dodaios.<group>"]`, and **must not import from `jarvis.*`** inside the plugin module — only structural compatibility with the protocol (registry at `jarvis/core/registry.py`). After editing entry-points: `pip install -e . --no-deps`.++Every group has two names. `dodaios.<group>` is the one to register a new plugin under; `jarvis.<group>` is the name plugins were published under before, and it stays valid: both are read in one scan of the installed distributions (`jarvis/core/entry_points.py`), and the first-party tables in `pyproject.toml` still use it. A name registered under both loads once, and if the two registrations point at different objects the `dodaios.<group>` one loads.Groups (frozen in `PLUGIN_GROUPS`): `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`, `jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel`.diff --git a/jarvis/__main__.py b/jarvis/__main__.pyindex d159a14e0d..ab379c05a5 100644--- a/jarvis/__main__.py+++ b/jarvis/__main__.py@@ -229,7 +229,7 @@ def _cmd_phase5_doctor() -> int:"""Status check for all Phase-5 features. Shows what is enabled,what is missing, and what is running on defaults. No config changes."""- import importlib.metadata as _md+ from jarvis.core.entry_points import entry_pointsconfig = cfg.load_config()lines: list[str] = []@@ -241,7 +241,7 @@ def _cmd_phase5_doctor() -> int:# Computer-use harness name sourced from the local action gate# (single home for the literal).from jarvis.brain.local_action_gate import HARNESS_NAME- eps = list(_md.entry_points(group="jarvis.harness"))+ eps = list(entry_points(group="jarvis.harness"))have_cu = any(ep.name == HARNESS_NAME for ep in eps)lines.append(f"[{'OK' if have_cu else 'FAIL'}] Harness plugin "f"{HARNESS_NAME!r} in entry-points index: {have_cu}")@@ -249,7 +249,7 @@ def _cmd_phase5_doctor() -> int:lines.append(f"[FAIL] Harness entry points not readable: {exc}")try:- eps = list(_md.entry_points(group="jarvis.tool"))+ eps = list(entry_points(group="jarvis.tool"))have_admin = any(ep.name == "dispatch-to-admin" for ep in eps)lines.append(f"[{'OK' if have_admin else 'FAIL'}] Tool plugin "f"'dispatch-to-admin' in entry-points index: {have_admin}")diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 53ea3b3a2b..16708cb315 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -407,7 +407,7 @@ def _load_tools_for_tier(mission_manager: MissionManager instance for ``spawn_worker``.When None, the tool is removed from the set."""- from importlib.metadata import entry_points+ from jarvis.core.entry_points import entry_pointsif tier != "router":raise ValueError(@@ -1128,7 +1128,7 @@ def _phase2_full_brain(# the cu_tools dict — otherwise the brain plans actions that the# loop cannot execute. These tools are CU-specific and not in# ROUTER_TOOLS, so they are loaded directly from entry_points.- from importlib.metadata import entry_points as _eps+ from jarvis.core.entry_points import entry_points as _eps_CU_EXTRA = {# Verify / wait helpers already wired in earlier waves."wait-for-ui-state",@@ -1395,7 +1395,7 @@ def _phase2_full_brain(def _legacy_full_brain(bus: Any | None = None) -> Any:"""Legacy BrainManager path (before tiered routing) — only via JARVIS_BRAIN=legacy."""- from importlib.metadata import entry_points+ from jarvis.core.entry_points import entry_pointsfrom jarvis.brain.manager import BrainManagerfrom jarvis.core import config as cfgdiff --git a/jarvis/brain/launcher.py b/jarvis/brain/launcher.pyindex 5a7b3402bc..6e274403d0 100644--- a/jarvis/brain/launcher.py+++ b/jarvis/brain/launcher.py@@ -143,7 +143,7 @@ def _load_tools() -> dict:integration that needs one tool per connected CLI) to work despite staticentry points."""- from importlib.metadata import entry_points+ from jarvis.core.entry_points import entry_pointstools: dict = {}for ep in entry_points(group="jarvis.tool"):try:diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 87d2418c07..74f65464ef 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -13640,7 +13640,7 @@ class BrainManager:cache: dict[str, Tool | None] = self.__dict__.setdefault("_task_only_tool_cache", {})if name in cache:return cache[name]- from importlib.metadata import entry_points # noqa: PLC0415+ from jarvis.core.entry_points import entry_points # noqa: PLC0415tool: Tool | None = Nonefor ep in entry_points(group="jarvis.tool"):diff --git a/jarvis/brain/provider_registry.py b/jarvis/brain/provider_registry.pyindex d918875119..343eea5487 100644--- a/jarvis/brain/provider_registry.py+++ b/jarvis/brain/provider_registry.py@@ -6,9 +6,9 @@ the error is recorded in the log."""from __future__ import annotations-from importlib.metadata import entry_pointsfrom typing import Any+from jarvis.core.entry_points import entry_pointsfrom jarvis.core.protocols import BrainPLUGIN_GROUP = "jarvis.brain"diff --git a/jarvis/channels/manager.py b/jarvis/channels/manager.pyindex 36af521609..727f5a5074 100644--- a/jarvis/channels/manager.py+++ b/jarvis/channels/manager.py@@ -7,7 +7,8 @@ platform-specific config), so the bus and dependencies are bundled ina :class:`ChannelContext` and passed to plugins.Discovery:- Lazy-load via ``importlib.metadata.entry_points(group="jarvis.channel")``.+ Lazy-load via ``jarvis.core.entry_points.entry_points(group="jarvis.channel")``,+ which also reads the group's ``dodaios.channel`` spelling.Failed loads end up in ``self._failed_load`` and do not block the others.Instantiation:@@ -26,10 +27,10 @@ from __future__ import annotationsimport asyncioimport loggingfrom dataclasses import dataclass, field-from importlib.metadata import entry_pointsfrom typing import TYPE_CHECKING, Anyfrom jarvis.core.bus import EventBus+from jarvis.core.entry_points import entry_pointsfrom jarvis.core.protocols import ChannelAdapterif TYPE_CHECKING: # pragma: no coverdiff --git a/jarvis/core/branding.py b/jarvis/core/branding.pyindex 1849372d35..e0f0def3fe 100644--- a/jarvis/core/branding.py+++ b/jarvis/core/branding.py@@ -106,6 +106,14 @@ LINUX_APP_NAME = PERSISTENT_PRODUCT_NAMELINUX_DESKTOP_ENTRY_FILE_NAME = f"{PERSISTENT_SLUG}.desktop"LINUX_WM_CLASS = PERSISTENT_SLUG+# --- Plugin entry-point groups -------------------------------------------------+# A plugin registers under ``<namespace>.<slot>`` (``dodaios.tool``,+# ``dodaios.brain``, ...). The legacy namespaces are a wire contract with every+# plugin already published: they are read forever, next to the current one, by+# ``jarvis.core.entry_points``.+PLUGIN_GROUP_NAMESPACE = "dodaios"+LEGACY_PLUGIN_GROUP_NAMESPACES = ("jarvis",)+DEFAULT_OFFICIAL_REPO_SLUG = "Dodaios/Dodaios"# Checkouts cloned before the GitHub rename still store this origin. The# updater accepts it and rewrites origin to the current slug when it applies.@@ -158,6 +166,7 @@ __all__ = ["DEFAULT_OFFICIAL_REPO_SLUG","DEFAULT_INSTALL_DIR_NAME","LEGACY_OFFICIAL_REPO_SLUGS",+ "LEGACY_PLUGIN_GROUP_NAMESPACES","DESKTOP_OUTPUT_MIRROR_DIR_NAME","DISTRIBUTION_NAME","FALLBACK_USER_DATA_DIR_NAME",@@ -187,6 +196,7 @@ __all__ = ["PERSISTENT_COMPACT_NAME","PERSISTENT_PRODUCT_NAME","PERSISTENT_SLUG",+ "PLUGIN_GROUP_NAMESPACE","PRODUCT_COMPACT_NAME","PRODUCT_NAME","PRODUCT_SLUG",diff --git a/jarvis/core/entry_points.py b/jarvis/core/entry_points.pyindex f06b120a7f..2c1bc2553e 100644--- a/jarvis/core/entry_points.py+++ b/jarvis/core/entry_points.py@@ -1,4 +1,4 @@-"""One cached read of the installed entry-point catalogue, shared process-wide.+"""The installed plugin catalogue: one read per group, under every name it has.``importlib.metadata.entry_points()`` is not a lookup — it is a filesystemsweep. Every call re-walks ``sys.path``, enumerates every installed@@ -14,7 +14,7 @@ the same loop that serves every WebSocket, HTTP route and terminal pane. A16.5 s loop stall was captured with exactly this call at the bottom of thestack (``_dictation_session`` → ``build_stt_from_config`` →``_load_provider_class`` → ``entry_points()`` → ``read_text`` → ``io.open``),-which is why this module exists.+which is why :func:`entry_points_for` exists.Caching for the life of the process is correct rather than merely convenient:the catalogue only changes when a distribution is installed or removed, and a@@ -22,14 +22,33 @@ new entry-point does not take effect in an already-running interpreter anyway(hence AGENTS.md §10's ``pip install -e . --no-deps`` followed by a restart).:func:`invalidate` is provided for the one case that does need it — a test, oran in-process install that wants the next read to see new plugins.++**Two names, one group.** A plugin slot is published as ``dodaios.<slot>`` and,+for every plugin written before the product was renamed, as ``jarvis.<slot>``.+Both spellings are one group here: :func:`entry_points` and+:func:`entry_points_for` accept either and answer with the union, so every+reader of a plugin group goes through this module and never asks+``importlib.metadata`` itself. The union costs **one** sweep, not one per+spelling — see :class:`_AnySpelling`.++When both spellings carry an entry of the same name, the ``dodaios.<slot>``+entry is the one that loads and the ``jarvis.<slot>`` entry is dropped: a+plugin that registers under both (so it also loads in an older host) is loaded+once, and a plugin that deliberately points the two names at different objects+gets the one written for this host. The second case is logged as a conflict."""from __future__ import annotations+import loggingimport threadingfrom importlib import metadata-__all__ = ["entry_points_for", "invalidate"]+from .branding import LEGACY_PLUGIN_GROUP_NAMESPACES, PLUGIN_GROUP_NAMESPACE++__all__ = ["entry_points", "entry_points_for", "group_spellings", "invalidate"]++log = logging.getLogger(__name__)# Guards the fill, not the read. Without it, the several subsystems that resolve# plugins concurrently during boot would each pay the cold sweep in parallel —@@ -37,29 +56,150 @@ __all__ = ["entry_points_for", "invalidate"]_LOCK = threading.Lock()_CACHE: dict[str, tuple[metadata.EntryPoint, ...]] = {}+_NAMESPACES: tuple[str, ...] = (PLUGIN_GROUP_NAMESPACE, *LEGACY_PLUGIN_GROUP_NAMESPACES)+++def group_spellings(group: str) -> tuple[str, ...]:+ """Every name ``group`` is published under, the current one first.++ ``"jarvis.tool"`` and ``"dodaios.tool"`` both answer+ ``("dodaios.tool", "jarvis.tool")``. A group outside the plugin namespaces+ (``"console_scripts"``) has one spelling: its own.+ """+ namespace, dot, slot = group.partition(".")+ if not dot or not slot or namespace not in _NAMESPACES:+ return (group,)+ return tuple(f"{candidate}.{slot}" for candidate in _NAMESPACES)+++class _AnySpelling(str):+ """A group name that compares equal to each of the group's spellings.++ ``importlib.metadata`` selects entry points with ``group == <the value+ passed>``, so handing it this value selects every spelling during the one+ sweep the call makes anyway. Its text is the spelling the caller asked+ for. Whether the running interpreter really compares that way is checked+ once, by :func:`_selects_in_one_sweep`, never assumed.+ """++ __slots__ = ("_spellings",)+ _spellings: frozenset[str]++ def __new__(cls, asked: str, spellings: tuple[str, ...]) -> _AnySpelling:+ self = super().__new__(cls, asked)+ self._spellings = frozenset(spellings)+ return self++ def __eq__(self, other: object) -> bool:+ return isinstance(other, str) and str(other) in self._spellings++ def __ne__(self, other: object) -> bool:+ return not self.__eq__(other)++ __hash__ = str.__hash__+++_ONE_SWEEP: bool | None = None+++def _selects_in_one_sweep() -> bool:+ """Whether this interpreter's entry-point selection honours :class:`_AnySpelling`.++ Asked of an in-memory entry point, so it costs nothing and touches no disk.+ An interpreter that selects some other way answers ``False`` and the caller+ reads each spelling separately: the result is the same, only slower.+ """+ global _ONE_SWEEP # noqa: PLW0603 — a process-wide capability answer+ if _ONE_SWEEP is None:+ probe = metadata.EntryPoint(name="probe", value="probe:probe", group="b.slot")+ try:+ matched = probe.matches(group=_AnySpelling("a.slot", ("a.slot", "b.slot")))+ missed = probe.matches(group=_AnySpelling("a.slot", ("a.slot", "c.slot")))+ _ONE_SWEEP = bool(matched) and not missed+ except Exception: # noqa: BLE001 — an unknown selection API means "not supported"+ log.debug("entry points: one-sweep selection is unavailable", exc_info=True)+ _ONE_SWEEP = False+ return _ONE_SWEEP+++def _group_of(ep: metadata.EntryPoint) -> str:+ """The plain group name an entry point was declared in, ``""`` when it has none."""+ return str(getattr(ep, "group", "") or "")+++def _prefer_current(+ found: list[metadata.EntryPoint], spellings: tuple[str, ...]+) -> tuple[metadata.EntryPoint, ...]:+ """Drop a legacy-group entry that the current group also declares by name."""+ current_group = spellings[0]+ current: dict[str, metadata.EntryPoint] = {}+ for ep in found:+ if _group_of(ep) == current_group:+ current.setdefault(ep.name, ep)+ if not current:+ return tuple(found)+ kept: list[metadata.EntryPoint] = []+ for ep in found:+ winner = current.get(ep.name)+ if winner is None or _group_of(ep) == current_group:+ kept.append(ep)+ continue+ if getattr(ep, "value", None) != winner.value:+ log.warning(+ "Plugin %r is registered twice with different targets: %s -> %s "+ "and %s -> %s. Loading the %s one.",+ ep.name,+ current_group,+ winner.value,+ _group_of(ep),+ getattr(ep, "value", "?"),+ current_group,+ )+ return tuple(kept)+++def entry_points(*, group: str) -> tuple[metadata.EntryPoint, ...]:+ """Every entry point of ``group``, read fresh, under all of its spellings.++ The drop-in for ``importlib.metadata.entry_points(group=...)``: same+ keyword, same one sweep over the installed distributions, and the answer+ also holds what plugins registered under the group's other spelling. Use+ :func:`entry_points_for` on a path that asks repeatedly.+ """+ spellings = group_spellings(group)+ if len(spellings) == 1:+ return tuple(metadata.entry_points(group=group))+ if _selects_in_one_sweep():+ found = list(metadata.entry_points(group=_AnySpelling(group, spellings)))+ else:+ found = [ep for spelling in spellings for ep in metadata.entry_points(group=spelling)]+ return _prefer_current(found, spellings)+def entry_points_for(group: str) -> tuple[metadata.EntryPoint, ...]:"""Every entry-point declared in ``group``, read from disk at most once.Args:- group: An entry-point group name, e.g. ``"jarvis.stt"``.+ group: An entry-point group name under either spelling, e.g.+ ``"dodaios.stt"`` or ``"jarvis.stt"``. Both share one cache entry.Returns:The group's entry-points as an immutable tuple. Empty when the grouphas no registered plugins — indistinguishable, deliberately, from agroup nobody declared: both mean "nothing to load here"."""- cached = _CACHE.get(group)+ key = group_spellings(group)[0]+ cached = _CACHE.get(key)if cached is not None:return cachedwith _LOCK:# A second caller may have filled it while this one waited.- cached = _CACHE.get(group)+ cached = _CACHE.get(key)if cached is not None:return cached- resolved = tuple(metadata.entry_points(group=group))- _CACHE[group] = resolved+ resolved = entry_points(group=group)+ _CACHE[key] = resolvedreturn resolveddiff --git a/jarvis/core/registry.py b/jarvis/core/registry.pyindex 3e02baadd2..55466e1229 100644--- a/jarvis/core/registry.py+++ b/jarvis/core/registry.py@@ -1,7 +1,8 @@"""Plugin discovery via entry_points.-All plugin slots are declared in pyproject.toml under-[project.entry-points."jarvis.*"]. This module lists them at runtime, loads+A plugin registers under ``[project.entry-points."dodaios.<slot>"]``; the+earlier ``jarvis.<slot>`` spelling stays valid forever and is read alongside it+(``jarvis.core.entry_points``). This module lists the plugins at runtime, loadsthem lazily, and checks them against the matching Protocol.Important: `load()` only imports on actual invocation — this allows optional@@ -12,7 +13,7 @@ from __future__ import annotationsfrom typing import Any, Protocol-from .entry_points import entry_points_for+from .entry_points import entry_points_for, group_spellingsfrom .protocols import PLUGIN_GROUPS@@ -28,13 +29,18 @@ class PluginContractError(TypeError):"""Plugin does not structurally implement the expected Protocol."""+def _is_plugin_group(group: str) -> bool:+ """Whether ``group`` names a plugin slot under either of its spellings."""+ return any(spelling in PLUGIN_GROUPS for spelling in group_spellings(group))++def list_plugins(group: str) -> list[str]:"""Lists all available plugin names in a group.Args:- group: e.g. "jarvis.brain", "jarvis.stt", see PLUGIN_GROUPS.+ group: e.g. "jarvis.brain" or "dodaios.brain", see PLUGIN_GROUPS."""- if group not in PLUGIN_GROUPS:+ if not _is_plugin_group(group):raise ValueError(f"Unknown plugin group: {group}. Allowed: {PLUGIN_GROUPS}")eps = entry_points_for(group)return sorted(ep.name for ep in eps)@@ -60,7 +66,7 @@ def load(group: str, name: str, protocol: type[Protocol] | None = None) -> type[Raises:PluginNotFoundError, PluginLoadError, PluginContractError."""- if group not in PLUGIN_GROUPS:+ if not _is_plugin_group(group):raise ValueError(f"Unknown plugin group: {group}")eps = entry_points_for(group)diff --git a/jarvis/diagnostics/doctor.py b/jarvis/diagnostics/doctor.pyindex 8599ed154b..85757b1ca9 100644--- a/jarvis/diagnostics/doctor.py+++ b/jarvis/diagnostics/doctor.py@@ -30,9 +30,10 @@ from __future__ import annotationsimport loggingimport shutilfrom dataclasses import dataclass-from importlib.metadata import entry_pointsfrom typing import Any, Literal+from jarvis.core.entry_points import entry_points+log = logging.getLogger(__name__)Status = Literal["ok", "warn", "fail", "info"]diff --git a/jarvis/harness/manager.py b/jarvis/harness/manager.pyindex 9632c8d6ed..cf8a7974db 100644--- a/jarvis/harness/manager.py+++ b/jarvis/harness/manager.py@@ -9,9 +9,9 @@ from __future__ import annotationsimport asyncioimport loggingfrom collections.abc import AsyncIterator-from importlib.metadata import entry_pointsfrom jarvis.core.bus import EventBus+from jarvis.core.entry_points import entry_pointsfrom jarvis.core.events import HarnessCompleted, HarnessDispatched, HarnessProgressfrom jarvis.core.protocols import Harness, HarnessResult, HarnessTaskdiff --git a/jarvis/local_models/assistant_session.py b/jarvis/local_models/assistant_session.pyindex 587b9ef8d4..3679828511 100644--- a/jarvis/local_models/assistant_session.py+++ b/jarvis/local_models/assistant_session.py@@ -67,7 +67,7 @@ def _tool_capable(provider: str) -> bool:that cannot be loaded here answers True: the turn then fails honestlyinstead of a healthy provider being skipped by a probe glitch."""- from importlib.metadata import entry_points+ from jarvis.core.entry_points import entry_pointstry:eps = [ep for ep in entry_points(group="jarvis.brain") if ep.name == provider]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 3ceb2df133..86f2f9ccdd 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -4663,7 +4663,7 @@ class DesktopApp:# complex dependencies (dispatch-to-harness, spawn-worker) are# skipped; those are Jarvis-Agent specialties anyway, not meant for# skill bodies. ``remember`` and friends all fit this schema.- from importlib.metadata import entry_points as _eps+ from jarvis.core.entry_points import entry_points as _epsskill_tool_registry: dict[str, Any] = {}for _ep in _eps(group="jarvis.tool"):diff --git a/pyproject.toml b/pyproject.tomlindex ad237423e2..65d2bc2225 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -522,6 +522,18 @@ jctl = "jarvis.cli_ctl.__main__:main"# Plugin entry points — all slots are already declared.# New plugins are discovered without any core changes.+#+# A slot has two names: `dodaios.<slot>` (what a new plugin registers under)+# and `jarvis.<slot>` (what every plugin published earlier registers under).+# The app reads both in one scan, for good (jarvis/core/entry_points.py).+#+# The first-party plugins below stay in the `jarvis.<slot>` tables on purpose:+# an install's entry points are frozen into its `*.dist-info` when the+# environment is built, so an install that updates its source without+# rebuilding still carries the tables of the version that wrote them, and an+# older version rolled back onto a newer environment reads `jarvis.<slot>`+# only. One table that both read keeps every first-party plugin loading+# exactly once in each case.[project.entry-points."jarvis.wakeword"]openwakeword = "jarvis.plugins.wake.openwakeword_provider:OpenWakeWordProvider"diff --git a/tests/unit/core/test_entry_point_group_spellings.py b/tests/unit/core/test_entry_point_group_spellings.pynew file mode 100644index 0000000000..7fdce2ad9e--- /dev/null+++ b/tests/unit/core/test_entry_point_group_spellings.py@@ -0,0 +1,375 @@+"""A plugin group is one group under two names: ``dodaios.<slot>`` and ``jarvis.<slot>``.++Plugins published before the product was renamed register under+``jarvis.<slot>`` and must keep loading untouched, forever. New plugins register+under ``dodaios.<slot>``. These tests run against a real, temporary+``site-packages`` holding synthetic distributions, and count the scans+``importlib.metadata`` makes through its own extension point (a+``DistributionFinder`` on ``sys.meta_path``), so "one pass over the installed+distributions" is measured rather than asserted from the code's shape.+"""++from __future__ import annotations++import ast+import logging+import sys+import tomllib+from collections.abc import Iterator+from importlib import metadata+from pathlib import Path++import pytest++import jarvis.core.branding as branding+from jarvis.core import entry_points as ep_module+from jarvis.core import registry+from jarvis.core.protocols import PLUGIN_GROUPS++_ROOT = Path(__file__).resolve().parents[3]++#: A slot no real distribution declares, so the answers below are exactly the+#: synthetic distributions and nothing the test environment happens to hold.+_OLD = "jarvis.selftest"+_NEW = "dodaios.selftest"+++class _ScanCounter(metadata.DistributionFinder):+ """Counts how often ``importlib.metadata`` enumerates the distributions."""++ def __init__(self) -> None:+ self.scans = 0++ def find_spec(self, fullname, path=None, target=None): # noqa: ANN001, ANN201, ARG002+ return None++ def find_distributions(self, context=None): # noqa: ANN001, ANN201, ARG002+ self.scans += 1+ return iter(())+++class _Site:+ """A temporary ``site-packages`` that synthetic distributions are written to."""++ def __init__(self, root: Path) -> None:+ self.root = root++ def add(self, name: str, entry_points: dict[str, dict[str, str]], module: str = "") -> None:+ # The directory carries the normalised name: ``importlib.metadata``+ # reads a distribution's identity from the stem up to the first dash.+ package = name.replace("-", "_")+ info = self.root / f"{package}-1.0.dist-info"+ info.mkdir()+ (info / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: {name}\nVersion: 1.0\n", encoding="utf-8"+ )+ lines: list[str] = []+ for group, entries in entry_points.items():+ lines.append(f"[{group}]")+ lines.extend(f"{key} = {value}" for key, value in entries.items())+ lines.append("")+ (info / "entry_points.txt").write_text("\n".join(lines), encoding="utf-8")+ if module:+ (self.root / f"{package}.py").write_text(module, encoding="utf-8")+++def site(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[_Site]:+ monkeypatch.syspath_prepend(str(tmp_path))+ ep_module.invalidate()+ yield _Site(tmp_path)+ for name in [key for key in sys.modules if key.startswith("selftest_")]:+ del sys.modules[name]+++def scans(monkeypatch: pytest.MonkeyPatch) -> _ScanCounter:+ counter = _ScanCounter()+ monkeypatch.setattr(sys, "meta_path", [*sys.meta_path, counter])+ return counter+++def _names(group: str) -> list[str]:+ return sorted(ep.name for ep in ep_module.entry_points(group=group))+++# ---------------------------------------------------------------------------+# The two spellings+# ---------------------------------------------------------------------------+++def test_the_current_and_the_legacy_namespace_come_from_branding() -> None:+ assert branding.PLUGIN_GROUP_NAMESPACE == "dodaios"+ assert branding.LEGACY_PLUGIN_GROUP_NAMESPACES == ("jarvis",)+ assert ep_module.group_spellings("jarvis.tool") == ("dodaios.tool", "jarvis.tool")+ assert ep_module.group_spellings("dodaios.tool") == ("dodaios.tool", "jarvis.tool")++[email protected]("group", ["console_scripts", "jarvis", "other.tool", "jarvis."])+def test_a_group_outside_the_plugin_namespaces_has_one_spelling(group: str) -> None:+ assert ep_module.group_spellings(group) == (group,)+++def test_every_plugin_slot_is_readable_under_the_new_name() -> None:+ for group in PLUGIN_GROUPS:+ current, legacy = ep_module.group_spellings(group)+ assert legacy == group+ assert current == f"dodaios.{group.partition('.')[2]}"+++# ---------------------------------------------------------------------------+# Discovery against real synthetic distributions+# ---------------------------------------------------------------------------+++def test_a_plugin_published_under_the_old_group_keeps_loading(site: _Site) -> None:+ """The compatibility promise: a third-party plugin nobody touches still loads."""+ site.add(+ "selftest-old", {_OLD: {"alpha": "selftest_old:Alpha"}}, "class Alpha:\n tag = 'old'\n"+ )++ for asked in (_OLD, _NEW):+ (found,) = ep_module.entry_points(group=asked)+ assert (found.name, found.group) == ("alpha", _OLD)+ assert found.load().tag == "old"+++def test_a_plugin_published_under_the_new_group_is_discovered(site: _Site) -> None:+ site.add(+ "selftest-new", {_NEW: {"beta": "selftest_new:Beta"}}, "class Beta:\n tag = 'new'\n"+ )++ for asked in (_OLD, _NEW):+ (found,) = ep_module.entry_points(group=asked)+ assert (found.name, found.group) == ("beta", _NEW)+ assert found.load().tag == "new"+++def test_both_groups_are_one_catalogue(site: _Site) -> None:+ site.add("selftest-old", {_OLD: {"alpha": "selftest_old:Alpha"}})+ site.add("selftest-new", {_NEW: {"beta": "selftest_new:Beta"}})++ assert _names(_OLD) == _names(_NEW) == ["alpha", "beta"]+++def test_a_plugin_registered_under_both_groups_loads_once(+ site: _Site, caplog: pytest.LogCaptureFixture+) -> None:+ """One wheel that serves an older host and this one is not a duplicate."""+ site.add(+ "selftest-both",+ {_OLD: {"gamma": "selftest_both:Gamma"}, _NEW: {"gamma": "selftest_both:Gamma"}},+ "class Gamma:\n pass\n",+ )++ with caplog.at_level(logging.WARNING, logger=ep_module.__name__):+ found = ep_module.entry_points(group=_OLD)++ assert [(ep.name, ep.group) for ep in found] == [("gamma", _NEW)]+ assert caplog.records == []+++def test_a_name_claimed_by_two_objects_resolves_to_the_new_group(+ site: _Site, caplog: pytest.LogCaptureFixture+) -> None:+ """The conflict rule: ``dodaios.<slot>`` wins, and the clash is logged."""+ site.add(+ "selftest-clash",+ {_OLD: {"delta": "selftest_clash:Legacy"}, _NEW: {"delta": "selftest_clash:Current"}},+ "class Legacy:\n pass\n\n\nclass Current:\n pass\n",+ )++ with caplog.at_level(logging.WARNING, logger=ep_module.__name__):+ (found,) = ep_module.entry_points(group=_OLD)++ assert found.load().__name__ == "Current"+ (record,) = caplog.records+ message = record.getMessage()+ assert "'delta'" in message+ assert "selftest_clash:Legacy" in message and "selftest_clash:Current" in message+++def test_the_conflict_rule_holds_across_two_distributions(site: _Site) -> None:+ site.add("selftest-a", {_OLD: {"delta": "selftest_a:Legacy", "kept": "selftest_a:Kept"}})+ site.add("selftest-b", {_NEW: {"delta": "selftest_b:Current"}})++ found = {ep.name: ep.value for ep in ep_module.entry_points(group=_NEW)}++ assert found == {"delta": "selftest_b:Current", "kept": "selftest_a:Kept"}+++# ---------------------------------------------------------------------------+# Cost: one scan of the installed distributions per read, not one per spelling+# ---------------------------------------------------------------------------+++def test_reading_both_spellings_costs_the_one_scan_a_single_group_costs(+ site: _Site, scans: _ScanCounter+) -> None:+ site.add("selftest-old", {_OLD: {"alpha": "selftest_old:Alpha"}})+ site.add("selftest-new", {_NEW: {"beta": "selftest_new:Beta"}})++ list(metadata.entry_points(group=_OLD))+ baseline = scans.scans+ assert baseline == 1, "importlib.metadata reads one group in one scan"++ assert _names(_OLD) == ["alpha", "beta"]+ assert scans.scans - baseline == 1+++def test_the_cache_holds_both_spellings_under_one_entry(site: _Site, scans: _ScanCounter) -> None:+ site.add("selftest-old", {_OLD: {"alpha": "selftest_old:Alpha"}})+ site.add("selftest-new", {_NEW: {"beta": "selftest_new:Beta"}})++ for _ in range(5):+ old = ep_module.entry_points_for(_OLD)+ new = ep_module.entry_points_for(_NEW)++ assert old is new+ assert sorted(ep.name for ep in old) == ["alpha", "beta"]+ assert scans.scans == 1+++def test_every_plugin_slot_under_both_names_costs_one_scan_per_slot(+ scans: _ScanCounter,+) -> None:+ """Boot resolves each slot; the second name must not buy a second scan."""+ ep_module.invalidate()+ for group in PLUGIN_GROUPS:+ for spelling in ep_module.group_spellings(group):+ ep_module.entry_points_for(spelling)++ assert scans.scans == len(PLUGIN_GROUPS)+++def test_an_interpreter_without_one_sweep_selection_still_finds_both(+ site: _Site, scans: _ScanCounter, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The fallback is slower, never wrong."""+ site.add("selftest-old", {_OLD: {"alpha": "selftest_old:Alpha"}})+ site.add("selftest-new", {_NEW: {"beta": "selftest_new:Beta"}})+ monkeypatch.setattr(ep_module, "_ONE_SWEEP", False)++ assert _names(_OLD) == ["alpha", "beta"]+ assert scans.scans == 2+++def test_this_interpreter_selects_in_one_sweep(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ep_module, "_ONE_SWEEP", None)+ assert ep_module._selects_in_one_sweep() is True+++# ---------------------------------------------------------------------------+# Readers+# ---------------------------------------------------------------------------+++def test_the_registry_serves_a_slot_under_either_name(site: _Site) -> None:+ site.add(+ "selftest-tool",+ {"dodaios.tool": {"selftest-new-tool": "selftest_tool:NewTool"}},+ "class NewTool:\n pass\n",+ )+ site.add(+ "selftest-legacy-tool",+ {"jarvis.tool": {"selftest-old-tool": "selftest_legacy_tool:OldTool"}},+ "class OldTool:\n pass\n",+ )++ for group in ("jarvis.tool", "dodaios.tool"):+ listed = registry.list_plugins(group)+ assert listed.count("selftest-new-tool") == 1+ assert listed.count("selftest-old-tool") == 1+ assert registry.load(group, "selftest-new-tool").__name__ == "NewTool"+ assert registry.load(group, "selftest-old-tool").__name__ == "OldTool"++ with pytest.raises(ValueError, match="Unknown plugin group"):+ registry.list_plugins("dodaios.nonexistent")+++def _shipped_python_files() -> list[Path]:+ return [+ path+ for path in (_ROOT / "jarvis").rglob("*.py")+ if "node_modules" not in path.parts+ ]+++def test_no_module_reads_a_plugin_group_behind_the_helpers_back() -> None:+ """A direct ``importlib.metadata`` read sees one spelling and misses the other."""+ offenders: list[str] = []+ for path in _shipped_python_files():+ relative = path.relative_to(_ROOT).as_posix()+ if relative == "jarvis/core/entry_points.py":+ continue+ source = path.read_text(encoding="utf-8-sig")+ if "entry_points" not in source:+ continue+ for node in ast.walk(ast.parse(source)):+ if (+ isinstance(node, ast.ImportFrom)+ and node.module == "importlib.metadata"+ and any(alias.name == "entry_points" for alias in node.names)+ ):+ offenders.append(f"{relative}:{node.lineno}: imports entry_points")+ elif (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "entry_points"+ and isinstance(node.func.value, (ast.Name, ast.Attribute))+ and ast.unparse(node.func.value).endswith(("metadata", "_md"))+ ):+ offenders.append(f"{relative}:{node.lineno}: calls metadata.entry_points")+ assert not offenders, "read plugin groups through jarvis.core.entry_points:\n" + "\n".join(+ offenders+ )+++ "module",+ [+ "jarvis.brain.provider_registry",+ "jarvis.channels.manager",+ "jarvis.diagnostics.doctor",+ "jarvis.harness.manager",+ ],+)+def test_a_manager_discovers_through_the_helper(module: str) -> None:+ import importlib++ assert importlib.import_module(module).entry_points is ep_module.entry_points+++# ---------------------------------------------------------------------------+# First-party plugins+# ---------------------------------------------------------------------------+++def _declared_groups() -> dict[str, dict[str, str]]:+ project = tomllib.loads((_ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]+ return project.get("entry-points", {})+++def test_a_first_party_plugin_is_never_declared_with_two_targets() -> None:+ """Whichever spelling ``pyproject.toml`` uses, one name means one object.++ A stale ``*.dist-info`` (an install updated without rebuilding its+ environment) holds the entry points of the version that wrote it; a fresh+ one holds today's. Both load each first-party plugin exactly once as long+ as the two spellings never disagree about a name.+ """+ groups = _declared_groups()+ for group in PLUGIN_GROUPS:+ current, legacy = ep_module.group_spellings(group)+ ours, theirs = groups.get(current, {}), groups.get(legacy, {})+ clashes = {name for name in ours.keys() & theirs.keys() if ours[name] != theirs[name]}+ assert not clashes, f"{current} and {legacy} disagree about {sorted(clashes)}"+++def test_first_party_plugins_stay_reachable_by_a_host_that_reads_only_the_old_group() -> None:+ """A rollback to an older version reads ``jarvis.<slot>`` and nothing else."""+ groups = _declared_groups()+ for group in PLUGIN_GROUPS:+ current, legacy = ep_module.group_spellings(group)+ missing = sorted(set(groups.get(current, {})) - set(groups.get(legacy, {})))+ assert not missing, f"{missing} are only in {current}; an older host cannot load them"