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.

perf(cli): stop paying the whole import graph to run one command (#1273)

Raghav Chamadiya9a0b27a76ba6
diff --git a/packages/cli/src/repowise/cli/_instrumented_group.py b/packages/cli/src/repowise/cli/_instrumented_group.py
index bf907c978..775c34e51 100644
--- a/packages/cli/src/repowise/cli/_instrumented_group.py
+++ b/packages/cli/src/repowise/cli/_instrumented_group.py
@@ -45,7 +45,59 @@ def _option_name(token: str) -> str:
class InstrumentedGroup(click.Group):
- """Root group that emits one telemetry event per invocation."""
+ """Root group that emits one telemetry event per invocation.
+
+ Also the lazy half of the CLI registry: a command can be registered
+ as a ``"module:attr"`` string and is imported only when it is the one
+ being run. Dispatching ``repowise status`` used to import all ~35
+ command modules; now it imports one.
+
+ ``--help`` still resolves everything, because Click needs each
+ command's ``short_help`` to render the listing. That is deliberate:
+ the alternative is a duplicated static help map that drifts, and
+ ``--help`` is human-interactive while hooks, MCP and scripts never
+ call it.
+ """
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ #: name -> "module:attr", for commands not yet imported.
+ self._lazy_commands: dict[str, str] = {}
+
+ def add_lazy_command(self, name: str, target: str) -> None:
+ """Register *name* without importing the module that defines it."""
+ # Last registration wins, which is what ``click.Group.add_command``
+ # does and therefore what plugin overrides have always relied on.
+ # Without this drop, an already-resolved (or eagerly registered)
+ # command of the same name would keep winning in ``get_command``,
+ # silently inverting precedence between a plugin and the OSS CLI.
+ self.commands.pop(name, None)
+ self._lazy_commands[name] = target
+
+ def add_command(self, cmd: click.Command, name: str | None = None) -> None:
+ """Attach *cmd*, superseding any lazy registration of the same name."""
+ super().add_command(cmd, name)
+ self._lazy_commands.pop(name or cmd.name or "", None)
+
+ def list_commands(self, ctx: click.Context) -> list[str]:
+ """Every command name, resolved and unresolved, importing nothing."""
+ return sorted({*super().list_commands(ctx), *self._lazy_commands})
+
+ def get_command(self, ctx: click.Context, name: str) -> click.Command | None:
+ """Resolve one command, importing its module on first use."""
+ resolved = super().get_command(ctx, name)
+ if resolved is not None:
+ return resolved
+ target = self._lazy_commands.get(name)
+ if target is None:
+ return None
+ from repowise.core.registry import LazyCommand
+
+ command = LazyCommand(name, target).load()
+ # Cached on the group, so a second lookup in the same process
+ # (``--help`` after dispatch, telemetry's tail match) is free.
+ self.add_command(command, name)
+ return command
def invoke(self, ctx: click.Context):
from repowise.cli.platform import telemetry
diff --git a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
index 5d083089c..d881b87d1 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -12,7 +12,6 @@ from repowise.cli.mcp_config import (
merge_mcp_entry,
resolve_repowise_command,
)
-from repowise.core.workspace.config import find_workspace_root
def _claude_desktop_config_path() -> Path | None:
@@ -52,6 +51,13 @@ def _resolve_mcp_target(repo_path: Path) -> Path:
repos. Otherwise fall back to the per-repo path, preserving single-repo
behavior.
"""
+ # Deferred: importing ``core.workspace.config`` runs ``core.workspace``'s
+ # package init, which pulls the extractor stack, the language registry,
+ # networkx and sqlalchemy — 849ms measured. ``migrate_claude_code_hooks``
+ # is called on every agent hook invocation and never reaches this
+ # function, so at module scope the whole graph was hook hot-path cost.
+ from repowise.core.workspace.config import find_workspace_root
+
workspace_root = find_workspace_root(repo_path)
return workspace_root if workspace_root is not None else repo_path
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index 93543b485..e62149eca 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -6,39 +6,7 @@ import click
from repowise.cli import __version__
from repowise.cli._instrumented_group import InstrumentedGroup
-from repowise.cli.commands.augment_cmd import augment_command
-from repowise.cli.commands.claude_md_cmd import claude_md_command
-from repowise.cli.commands.corrections_cmd import corrections_command
-from repowise.cli.commands.costs_cmd import costs_command
-from repowise.cli.commands.coverage_cmd import coverage_group
-from repowise.cli.commands.dead_code_cmd import dead_code_command
-from repowise.cli.commands.decision_cmd import decision_group
-from repowise.cli.commands.delete_cmd import delete_command
-from repowise.cli.commands.distill_cmd import distill_command
-from repowise.cli.commands.doctor_cmd import doctor_command
-from repowise.cli.commands.expand_cmd import expand_command
-from repowise.cli.commands.export_cmd import export_command
-from repowise.cli.commands.generate_cmd import generate_command
-from repowise.cli.commands.health_cmd import health_command
-from repowise.cli.commands.hook_cmd import hook_group
-from repowise.cli.commands.impacted_tests_cmd import impacted_tests_command
-from repowise.cli.commands.init_cmd import init_command
-from repowise.cli.commands.login_cmd import login_command, logout_command, whoami_command
-from repowise.cli.commands.mcp_cmd import mcp_command
-from repowise.cli.commands.reindex_cmd import reindex_command
-from repowise.cli.commands.restyle_cmd import restyle_command, wiki_styles_command
-from repowise.cli.commands.risk_cmd import risk_command
-from repowise.cli.commands.saved_cmd import saved_command
-from repowise.cli.commands.search_cmd import search_command
-from repowise.cli.commands.security_cmd import security_command
-from repowise.cli.commands.serve_cmd import serve_command
-from repowise.cli.commands.status_cmd import status_command
-from repowise.cli.commands.telemetry_cmd import telemetry_command
-from repowise.cli.commands.update_cmd import update_command
-from repowise.cli.commands.watch_cmd import watch_command
-from repowise.cli.commands.whats_new_cmd import whats_new_command
-from repowise.cli.commands.workspace_cmd import workspace_group
-from repowise.core.registry import cli_registry, register_command
+from repowise.core.registry import cli_registry, register_lazy_command
@click.group(cls=InstrumentedGroup)
@@ -60,43 +28,58 @@ def cli(ctx: click.Context) -> None:
pass
+_COMMANDS_PKG = "repowise.cli.commands"
+
+#: ``command name -> "module:attr"``, resolved one at a time by
+#: :class:`InstrumentedGroup`. Registering objects here instead of strings
+#: is what used to import all ~35 command modules (1.1s) to dispatch one,
+#: on every invocation including every agent hook fire and MCP start.
+#:
+#: The name on the left must equal the Click command's own name — it is
+#: what `--help`, dispatch and shell completion see before the module is
+#: imported. `tests/unit/cli/test_lazy_commands.py` asserts every pair.
+_OSS_COMMANDS: tuple[tuple[str, str], ...] = (
+ ("augment", "augment_cmd:augment_command"),
+ ("init", "init_cmd:init_command"),
+ ("delete", "delete_cmd:delete_command"),
+ ("generate-claude-md", "claude_md_cmd:claude_md_command"),
+ ("costs", "costs_cmd:costs_command"),
+ ("update", "update_cmd:update_command"),
+ ("generate", "generate_cmd:generate_command"),
+ ("dead-code", "dead_code_cmd:dead_code_command"),
+ ("health", "health_cmd:health_command"),
+ ("risk", "risk_cmd:risk_command"),
+ ("decision", "decision_cmd:decision_group"),
+ ("coverage", "coverage_cmd:coverage_group"),
+ ("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),
+ ("search", "search_cmd:search_command"),
+ ("distill", "distill_cmd:distill_command"),
+ ("expand", "expand_cmd:expand_command"),
+ ("saved", "saved_cmd:saved_command"),
+ ("security", "security_cmd:security_command"),
+ ("corrections", "corrections_cmd:corrections_command"),
+ ("export", "export_cmd:export_command"),
+ ("hook", "hook_cmd:hook_group"),
+ ("status", "status_cmd:status_command"),
+ ("doctor", "doctor_cmd:doctor_command"),
+ ("watch", "watch_cmd:watch_command"),
+ ("serve", "serve_cmd:serve_command"),
+ ("mcp", "mcp_cmd:mcp_command"),
+ ("reindex", "reindex_cmd:reindex_command"),
+ ("restyle", "restyle_cmd:restyle_command"),
+ ("wiki-styles", "restyle_cmd:wiki_styles_command"),
+ ("whats-new", "whats_new_cmd:whats_new_command"),
+ ("telemetry", "telemetry_cmd:telemetry_command"),
+ ("login", "login_cmd:login_command"),
+ ("logout", "login_cmd:logout_command"),
+ ("whoami", "login_cmd:whoami_command"),
+ ("workspace", "workspace_cmd:workspace_group"),
+)
+
# Register OSS commands through the shared registry so third-party
# packages can extend the CLI without monkey-patching the root group.
# Order is preserved by the registry, so `repowise --help` reads the same.
-register_command(augment_command)
-register_command(init_command)
-register_command(delete_command)
-register_command(claude_md_command)
-register_command(costs_command)
-register_command(update_command)
-register_command(generate_command)
-register_command(dead_code_command)
-register_command(health_command)
-register_command(risk_command)
-register_command(decision_group)
-register_command(coverage_group)
-register_command(impacted_tests_command)
-register_command(search_command)
-register_command(distill_command)
-register_command(expand_command)
-register_command(saved_command)
-register_command(security_command)
-register_command(corrections_command)
-register_command(export_command)
-register_command(hook_group)
-register_command(status_command)
-register_command(doctor_command)
-register_command(watch_command)
-register_command(serve_command)
-register_command(mcp_command)
-register_command(reindex_command)
-register_command(restyle_command)
-register_command(wiki_styles_command)
-register_command(whats_new_command)
-register_command(telemetry_command)
-register_command(login_command)
-register_command(logout_command)
-register_command(whoami_command)
-register_command(workspace_group)
+for _name, _target in _OSS_COMMANDS:
+ register_lazy_command(_name, f"{_COMMANDS_PKG}.{_target}")
cli_registry.apply(cli)
diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.py
index 9e7dcf11b..27db7d3a3 100644
--- a/packages/core/src/repowise/core/registry/__init__.py
+++ b/packages/core/src/repowise/core/registry/__init__.py
@@ -18,7 +18,13 @@ their own. The OSS CLI and MCP server use the module-level instances.
from __future__ import annotations
-from .cli_registry import CLIRegistry, cli_registry, register_command
+from .cli_registry import (
+ CLIRegistry,
+ LazyCommand,
+ cli_registry,
+ register_command,
+ register_lazy_command,
+)
from .mcp_tool_registry import MCPToolRegistry, ToolEntry, mcp_tool_registry
from .pipeline_hooks import (
HookPhase,
@@ -32,6 +38,7 @@ __all__ = [
"CLIRegistry",
"HookPhase",
"HookProgressCallback",
+ "LazyCommand",
"MCPToolRegistry",
"PipelineHookRegistry",
"ToolEntry",
@@ -40,4 +47,5 @@ __all__ = [
"pipeline_hooks",
"register_command",
"register_hook",
+ "register_lazy_command",
]
diff --git a/packages/core/src/repowise/core/registry/cli_registry.py b/packages/core/src/repowise/core/registry/cli_registry.py
index eab5ca66d..67df2b0e3 100644
--- a/packages/core/src/repowise/core/registry/cli_registry.py
+++ b/packages/core/src/repowise/core/registry/cli_registry.py
@@ -14,30 +14,70 @@ the hard-coded version.
Usage::
# OSS or plugin side
- from repowise.core.registry import register_command
+ from repowise.core.registry import register_command, register_lazy_command
register_command(my_command)
register_command(my_subcommand, parent=some_group)
+ register_lazy_command("my-command", "my_pkg.commands.mine:my_command")
# CLI entry point
from repowise.core.registry import cli_registry
cli_registry.apply(cli)
Registration order is preserved, matching the hard-coded behavior.
+
+Eager vs lazy
+-------------
+
+:func:`register_command` takes an already-imported Click object, so every
+registered command's module is imported before the CLI can dispatch even
+one of them. For the OSS CLI that was ~1.1s of import cost paid by every
+single invocation. :func:`register_lazy_command` takes a
+``"module:attr"`` string instead: the name is known without importing
+anything, and the module is imported only when that command is the one
+being run.
+
+Laziness needs a root group that knows how to hold an unresolved name —
+:class:`repowise.cli._instrumented_group.InstrumentedGroup` implements
+``add_lazy_command`` for this. Against any other Click group (a plain
+``click.Group`` built by a test, or a non-root ``parent``) a lazy entry
+resolves immediately and attaches eagerly, so behavior is identical and
+only the timing differs.
+
+Either way the last registration of a name wins, matching
+``click.Group.add_command`` — a plugin registering ``status`` after the
+OSS CLI overrides it whether either side is lazy or eager.
"""
from __future__ import annotations
-from typing import TYPE_CHECKING
+import importlib
+from typing import TYPE_CHECKING, NamedTuple
if TYPE_CHECKING:
import click
+class LazyCommand(NamedTuple):
+ """A command named now and imported later.
+
+ *target* is a ``"module:attr"`` string, the same shape setuptools
+ uses for console-script entry points.
+ """
+
+ name: str
+ target: str
+
+ def load(self) -> click.BaseCommand:
+ """Import the module and return the Click object it holds."""
+ module_name, _, attr = self.target.partition(":")
+ return getattr(importlib.import_module(module_name), attr)
+
+
class CLIRegistry:
"""Holds (parent, command) pairs until :meth:`apply` attaches them."""
def __init__(self) -> None:
- self._entries: list[tuple[click.BaseCommand | None, click.BaseCommand]] = []
+ self._entries: list[tuple[click.BaseCommand | None, click.BaseCommand | LazyCommand]] = []
self._applied_to: list[int] = []
def register(
@@ -49,6 +89,21 @@ class CLIRegistry:
"""Schedule *command* for attachment to *parent* (default: root)."""
self._entries.append((parent, command))
+ def register_lazy(
+ self,
+ name: str,
+ target: str,
+ *,
+ parent: click.BaseCommand | None = None,
+ ) -> None:
+ """Schedule the command at *target* under *name*, importing nothing.
+
+ *target* is ``"module:attr"``. *name* must match the Click
+ command's own name, since it is what the root group lists and
+ dispatches on before the module is ever loaded.
+ """
+ self._entries.append((parent, LazyCommand(name, target)))
+
def apply(self, root: click.BaseCommand) -> click.BaseCommand:
"""Attach every registered command. Returns *root* for chaining.
@@ -62,6 +117,14 @@ class CLIRegistry:
return root
for parent, command in self._entries:
target = parent if parent is not None else root
+ if isinstance(command, LazyCommand):
+ add_lazy = getattr(target, "add_lazy_command", None)
+ if add_lazy is not None:
+ add_lazy(command.name, command.target)
+ continue
+ # A target that cannot defer still gets the command, just
+ # at the cost of importing it now.
+ command = command.load()
target.add_command(command) # type: ignore[attr-defined]
self._applied_to.append(root_id)
return root
@@ -72,8 +135,8 @@ class CLIRegistry:
self._applied_to.clear()
def commands(self) -> list[click.BaseCommand]:
- """Return every registered command. Used by tests."""
- return [cmd for _, cmd in self._entries]
+ """Return every registered command, importing lazy ones. Used by tests."""
+ return [cmd.load() if isinstance(cmd, LazyCommand) else cmd for _, cmd in self._entries]
cli_registry = CLIRegistry()
@@ -89,4 +152,20 @@ def register_command(
cli_registry.register(command, parent=parent)
-__all__ = ["CLIRegistry", "cli_registry", "register_command"]
+def register_lazy_command(
+ name: str,
+ target: str,
+ *,
+ parent: click.BaseCommand | None = None,
+) -> None:
+ """Module-level convenience over :meth:`CLIRegistry.register_lazy`."""
+ cli_registry.register_lazy(name, target, parent=parent)
+
+
+__all__ = [
+ "CLIRegistry",
+ "LazyCommand",
+ "cli_registry",
+ "register_command",
+ "register_lazy_command",
+]
diff --git a/packages/core/src/repowise/core/registry/pipeline_hooks.py b/packages/core/src/repowise/core/registry/pipeline_hooks.py
index 41173c014..509b143ae 100644
--- a/packages/core/src/repowise/core/registry/pipeline_hooks.py
+++ b/packages/core/src/repowise/core/registry/pipeline_hooks.py
@@ -31,14 +31,11 @@ cannot derail the pipeline.
from __future__ import annotations
+import contextlib
import enum
from collections.abc import Callable
from typing import Any
-import structlog
-
-log = structlog.get_logger(__name__)
-
HookCallback = Callable[[str], None]
@@ -76,13 +73,25 @@ class PipelineHookRegistry:
try:
cb(phase)
except Exception as exc: # pragma: no cover - safety net
- log.warning(
- "pipeline_hook_failed",
- phase=phase,
- when=when.value,
- callback=getattr(cb, "__qualname__", repr(cb)),
- error=str(exc),
- )
+ # Deferred: ``structlog`` costs ~190ms to import (it pulls
+ # rich and asyncio), and this package's ``__init__`` is what
+ # the CLI entry point imports to reach the command registry.
+ # Only a broken plugin hook ever reaches this line.
+ #
+ # Suppressed as a whole because this handler's contract is
+ # that one broken plugin never derails the pipeline — a
+ # failure to import the logger must not become the thing
+ # that does, chained onto the exception it was reporting.
+ with contextlib.suppress(Exception):
+ import structlog
+
+ structlog.get_logger(__name__).warning(
+ "pipeline_hook_failed",
+ phase=phase,
+ when=when.value,
+ callback=getattr(cb, "__qualname__", repr(cb)),
+ error=str(exc),
+ )
def reset(self) -> None:
"""Drop every registered hook. Used by tests."""
diff --git a/tests/unit/cli/test_augment_hook_perf.py b/tests/unit/cli/test_augment_hook_perf.py
new file mode 100644
index 000000000..ccce24075
--- /dev/null
+++ b/tests/unit/cli/test_augment_hook_perf.py
@@ -0,0 +1,103 @@
+"""Import-graph guarantees for the ``repowise-augment`` PostToolUse hook.
+
+The hook fires on every Bash/Grep/Glob/Read/Edit/Write tool call an agent
+makes, and ~98% of those fires emit nothing — so whatever it imports is
+paid roughly 50-100 times a session for silence. Two module-level imports
+have each cost ~800ms here already (``persistence.sql`` in
+``augment_cmd.search``, ``core.workspace.config`` in ``claude_config``),
+and neither was visible until someone ran ``-X importtime``. These guards
+make the next one fail a test instead.
+
+Structured like ``tests/unit/distill/test_rewrite_perf.py``, which does the
+same job for the ``repowise-rewrite`` PreToolUse hook.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+#: Import roots that mean the heavy stack got pulled in. ``repowise.cli.main``
+#: is here because the hook has its own console script precisely so it never
+#: pays the CLI's command surface.
+_HEAVY_PREFIXES = (
+ "networkx",
+ "scipy",
+ "sqlalchemy",
+ "repowise.core.workspace",
+ "repowise.core.ingestion",
+ "repowise.core.pipeline",
+ "repowise.core.persistence",
+ "repowise.cli.main",
+)
+
+
+def _fake_home(tmp_path: Path) -> dict[str, str]:
+ """A throwaway HOME so the self-heal cannot touch the real settings.json.
+
+ ``migrate_claude_code_hooks`` *writes* ``~/.claude/settings.json`` when it
+ finds anything to migrate, and ``Path.home()`` reads ``USERPROFILE`` on
+ Windows and ``HOME`` elsewhere. Both are redirected. What is under test is
+ the import graph, which is identical either way.
+ """
+ env = dict(os.environ)
+ env["HOME"] = env["USERPROFILE"] = str(tmp_path)
+ return env
+
+
+def _heavy_after(statements: str, env: dict[str, str] | None = None) -> str:
+ code = (
+ "import sys; "
+ f"{statements} "
+ f"heavy = sorted(m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})); "
+ "print('\\n'.join(heavy))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", code], capture_output=True, text=True, check=True, env=env
+ )
+ return out.stdout.strip()
+
+
+def test_hook_entry_point_imports_nothing_heavy() -> None:
+ heavy = _heavy_after("import repowise.cli.augment_hook;")
+ assert heavy == "", f"the augment hook entry point pulled in:\n{heavy}"
+
+
+def test_the_self_heal_imports_nothing_heavy(tmp_path: Path) -> None:
+ """``migrate_claude_code_hooks`` runs after *every* hook invocation.
+
+ It reads and rewrites ``~/.claude/settings.json`` — pure JSON work. A
+ module-level ``core.workspace.config`` import for the unrelated MCP
+ registration helpers made it cost 849ms of that, on every fire.
+ """
+ heavy = _heavy_after(
+ "from repowise.cli.editor_integrations.claude_config import migrate_claude_code_hooks; "
+ "migrate_claude_code_hooks();",
+ env=_fake_home(tmp_path),
+ )
+ assert heavy == "", f"the hook self-heal pulled in:\n{heavy}"
+
+
+def test_a_silent_invocation_imports_nothing_heavy(tmp_path: Path) -> None:
+ """A payload the hook has nothing to say about must stay on the cheap path."""
+ code = (
+ "import sys, json, io; "
+ "payload = json.dumps({'hook_event_name': 'PostToolUse', 'tool_name': 'Grep', "
+ "'tool_input': {'pattern': 'zzz_no_such_symbol'}, 'tool_response': {'numFiles': 0}, "
+ "'cwd': '', 'session_id': ''}); "
+ "sys.stdin = io.StringIO(payload); "
+ "from repowise.cli.commands.augment_cmd import _run_augment; "
+ "_run_augment(client=None); "
+ f"heavy = sorted(m for m in sys.modules if m.startswith({_HEAVY_PREFIXES!r})); "
+ "print('\\n'.join(heavy))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ check=True,
+ env=_fake_home(tmp_path),
+ )
+ assert out.stdout.strip() == "", f"a silent hook invocation pulled in:\n{out.stdout}"
diff --git a/tests/unit/cli/test_init_ux.py b/tests/unit/cli/test_init_ux.py
index 0264a96f9..30ae90d1d 100644
--- a/tests/unit/cli/test_init_ux.py
+++ b/tests/unit/cli/test_init_ux.py
@@ -121,11 +121,14 @@ def test_the_progress_module_does_not_drag_in_the_pipeline_package() -> None:
def test_the_cli_entry_point_does_not_drag_in_the_pipeline_package() -> None:
"""The guard above covers one module; this covers the whole entry point.
- ``repowise.cli.main`` imports every command module at module scope, so a
- single ``from repowise.core.pipeline...`` anywhere under it is paid by every
- invocation — ``repowise --help`` and each post-commit hook run included.
+ ``repowise.cli.main`` now registers commands lazily, so this no longer
+ covers the command modules themselves — but the entry point still imports
+ the root group, the registry and click, and a single
+ ``from repowise.core.pipeline...`` on that path would be paid by every
+ invocation, ``repowise --help`` and each post-commit hook run included.
Generation is the only thing that needs the package, and it is always
reached through a function body, so nothing here should load it.
+ (Per-command import cost is guarded in ``test_lazy_commands.py``.)
"""
import subprocess
import sys
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
new file mode 100644
index 000000000..5f4e6d72c
--- /dev/null
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -0,0 +1,210 @@
+"""The root CLI group must dispatch a subcommand without importing the rest.
+
+``repowise.cli.main`` used to import all ~35 command modules at startup —
+1.1s paid by every invocation, including every agent hook fire, to run one
+subcommand. Commands are now registered as ``"module:attr"`` strings and
+resolved one at a time.
+
+Three things have to stay true for that to be safe, and each has a test
+below: the static names must match the real Click names (nothing else
+checks a string table), dispatch must import exactly one command module,
+and ``--help`` must still list every command.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+
+import click
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli._instrumented_group import InstrumentedGroup
+from repowise.cli.main import _OSS_COMMANDS, cli
+from repowise.core.registry import CLIRegistry, LazyCommand
+
+#: The CLI surface, frozen independently of ``_OSS_COMMANDS``.
+#:
+#: Deliberately duplicated: every other assertion here derives its
+#: expectation from ``_OSS_COMMANDS`` itself, so deleting a row would make
+#: the whole file agree that the command never existed. This is the one
+#: tripwire that catches a dropped command. Adding or removing a CLI
+#: command is meant to require editing it.
+_EXPECTED_NAMES = frozenset(
+ {
+ "augment", "corrections", "costs", "coverage", "dead-code", "decision",
+ "delete", "distill", "doctor", "expand", "export", "generate",
+ "generate-claude-md", "health", "hook", "impacted-tests", "init", "login",
+ "logout", "mcp", "reindex", "restyle", "risk", "saved", "search",
+ "security", "serve", "status", "telemetry", "update", "watch",
+ "whats-new", "whoami", "wiki-styles", "workspace",
+ }
+) # fmt: skip
+
+
+def test_the_command_surface_is_unchanged() -> None:
+ registered = {name for name, _target in _OSS_COMMANDS}
+ assert registered == _EXPECTED_NAMES
+
+
[email protected](("name", "target"), _OSS_COMMANDS)
+def test_every_lazy_name_matches_the_real_command_name(name: str, target: str) -> None:
+ """A wrong name in the table is invisible until the command is run.
+
+ ``list_commands`` reports the static name, so a typo would advertise a
+ command that fails to dispatch — and only for that one command.
+ """
+ command = LazyCommand(name, f"repowise.cli.commands.{target}").load()
+ assert command.name == name
+
+
+def test_help_lists_every_registered_command() -> None:
+ result = CliRunner().invoke(cli, ["--help"])
+ assert result.exit_code == 0
+ for name, _target in _OSS_COMMANDS:
+ assert f"\n {name} " in result.output or f"\n {name}\n" in result.output
+
+
+def test_list_commands_imports_nothing() -> None:
+ """Dispatch and shell completion read names only — no module loads."""
+ probe = (
+ "import repowise.cli.main as m, click, sys; "
+ "ctx = click.Context(m.cli); "
+ "names = m.cli.list_commands(ctx); "
+ "loaded = [x for x in sys.modules if x.startswith('repowise.cli.commands.')]; "
+ "print(len(names)); print(loaded)"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True
+ )
+ lines = out.stdout.strip().splitlines()
+ assert int(lines[-2]) == len(_OSS_COMMANDS)
+ assert lines[-1] == "[]", f"listing command names imported: {lines[-1]}"
+
+
+def _dispatch_and_report_loaded(argv: list[str]) -> str:
+ """Run *argv* in a fresh interpreter; return the command modules it loaded.
+
+ A subprocess because ``sys.modules`` is shared for the whole pytest
+ session — an in-process check would be answering for every earlier test
+ as well. The exit code is asserted so a command that imports and then
+ crashes cannot pass as "only imported one module".
+ """
+ probe = (
+ "import sys; "
+ "from repowise.cli.main import cli; "
+ "from click.testing import CliRunner; "
+ f"res = CliRunner().invoke(cli, {argv!r}); "
+ "assert res.exit_code == 0, res.output; "
+ "print(sorted({m.split('.')[3] for m in sys.modules "
+ "if m.startswith('repowise.cli.commands.')}))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True
+ )
+ return out.stdout.strip().splitlines()[-1]
+
+
+def test_dispatch_imports_only_the_invoked_command() -> None:
+ """The whole point: running one command must not load the other 34."""
+ loaded = _dispatch_and_report_loaded(["expand", "--help"])
+ assert loaded == "['expand_cmd']", f"dispatching `expand` also imported: {loaded}"
+
+
+def test_a_group_subcommand_resolves() -> None:
+ """Groups (decision/coverage/workspace/hook) resolve once the group loads."""
+ result = CliRunner().invoke(cli, ["hook", "--help"])
+ assert result.exit_code == 0
+ assert "stats" in result.output
+
+
+def test_unknown_command_still_errors() -> None:
+ result = CliRunner().invoke(cli, ["definitely-not-a-command"])
+ assert result.exit_code != 0
+ assert "No such command" in result.output
+
+
+def test_a_plain_group_gets_the_command_eagerly() -> None:
+ """A root that cannot defer must still end up with every command.
+
+ Third-party code (and tests) build isolated ``click.Group`` roots. The
+ registry resolves lazy entries against those rather than dropping them.
+ """
+ registry = CLIRegistry()
+ registry.register_lazy("expand", "repowise.cli.commands.expand_cmd:expand_command")
+ root = click.Group("root")
+ registry.apply(root)
+ assert "expand" in root.commands
+
+
+def test_instrumented_group_caches_the_resolved_command() -> None:
+ group = InstrumentedGroup("root")
+ group.add_lazy_command("expand", "repowise.cli.commands.expand_cmd:expand_command")
+ ctx = click.Context(group)
+ first = group.get_command(ctx, "expand")
+ assert first is not None
+ assert group.get_command(ctx, "expand") is first
+ assert "expand" in group.commands
+
+
+def test_the_last_registration_of_a_name_wins() -> None:
+ """Plugin override precedence must not depend on lazy vs eager.
+
+ ``click.Group.add_command`` overwrites, so a plugin registering
+ ``status`` after the OSS CLI has always taken over. Holding lazy names
+ in a second dict would quietly invert that in whichever direction the
+ lookup happened to check first — in both directions here.
+ """
+ plugin = click.Command("status", callback=lambda: None)
+ group = InstrumentedGroup("root")
+ ctx = click.Context(group)
+
+ group.add_lazy_command("status", "repowise.cli.commands.status_cmd:status_command")
+ group.add_command(plugin)
+ assert group.get_command(ctx, "status") is plugin
+
+ group.add_lazy_command("status", "repowise.cli.commands.status_cmd:status_command")
+ assert group.get_command(ctx, "status") is not plugin
+
+ # Either way the name is listed exactly once.
+ assert group.list_commands(ctx).count("status") == 1
+
+
+def test_a_resolved_command_does_not_outlive_a_re_registration() -> None:
+ """``get_command`` caches into ``self.commands``; re-registering must win."""
+ group = InstrumentedGroup("root")
+ ctx = click.Context(group)
+ group.add_lazy_command("thing", "repowise.cli.commands.status_cmd:status_command")
+ first = group.get_command(ctx, "thing")
+ group.add_lazy_command("thing", "repowise.cli.commands.expand_cmd:expand_command")
+ second = group.get_command(ctx, "thing")
+ assert first is not None and second is not None
+ assert second is not first
+
+
+def test_the_command_registry_pulls_no_structlog() -> None:
+ """``core.registry`` is what the CLI entry point imports.
+
+ ``pipeline_hooks`` held a module-level ``structlog.get_logger``, worth
+ 192ms (structlog pulls rich and asyncio) charged to every ``repowise``
+ invocation for one warning in a broken-plugin path.
+ """
+ probe = (
+ "import sys, repowise.core.registry; "
+ "print(sorted(m for m in sys.modules if m.startswith(('structlog', 'rich'))))"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", probe], capture_output=True, text=True, check=True
+ )
+ assert out.stdout.strip().splitlines()[-1] == "[]", out.stdout
+
+
+def test_telemetry_tail_match_does_not_resolve_every_command() -> None:
+ """``InstrumentedGroup.invoke`` matches the arg tail for telemetry.
+
+ It resolves the one invoked command to read that command's own
+ subcommands. Resolving all of them there would silently undo laziness.
+ """
+ loaded = _dispatch_and_report_loaded(["hook", "stats", "--help"])
+ assert loaded == "['hook_cmd']", loaded