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(workspace): make the package init lazy so a leaf import stops loading the analysis stack (#2178)

Raghav Chamadiya920d1c973d64
diff --git a/packages/cli/src/repowise/cli/commands/mcp_cmd.py b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
index 6ce3d0f08..ef7e1832f 100644
--- a/packages/cli/src/repowise/cli/commands/mcp_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/mcp_cmd.py
@@ -9,12 +9,15 @@ import click
from repowise.cli.helpers import console, find_repowise_repo_root, resolve_repo_path
from repowise.cli.ui import load_dotenv
-from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root
def _workspace_summary(path: Path, *, no_workspace: bool = False) -> dict[str, object] | None:
if no_workspace:
return None
+ # Deferred so ``--no-workspace`` and ``--help`` skip the config module and
+ # its yaml import entirely.
+ from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root
+
workspace_root = find_workspace_root(path)
if workspace_root is None:
return None
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 b9c2c5845..a3842b5a7 100644
--- a/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
+++ b/packages/cli/src/repowise/cli/editor_integrations/claude_config.py
@@ -52,11 +52,10 @@ 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.
+ # Deferred: ``migrate_claude_code_hooks`` runs on every agent hook
+ # invocation and never reaches this function. Keep it here —
+ # ``test_augment_hook_perf`` guards the whole ``repowise.core.workspace``
+ # prefix off the hook path.
from repowise.core.workspace.config import find_workspace_root
workspace_root = find_workspace_root(repo_path)
diff --git a/packages/core/src/repowise/core/workspace/__init__.py b/packages/core/src/repowise/core/workspace/__init__.py
index d72a07bd2..d91f8e1a1 100644
--- a/packages/core/src/repowise/core/workspace/__init__.py
+++ b/packages/core/src/repowise/core/workspace/__init__.py
@@ -1,143 +1,97 @@
"""Workspace support — multi-repo detection, configuration, and analysis.
-Public API re-exports for the workspace package.
+This package ``__init__`` is a **lazy re-export shim** and imports nothing at
+module scope. The public names below resolve on first attribute access via
+PEP 562 ``__getattr__``, so ``from repowise.core.workspace import
+WorkspaceConfig`` still works, while importing a sibling submodule costs only
+that submodule.
+
+Why it matters: a package ``__init__`` runs on *any* submodule import, so
+``import repowise.core.workspace.config`` — a leaf whose only dependency is
+yaml, and the first thing ``repowise mcp`` touches — used to be charged the
+whole analysis subsystem: sqlalchemy via :mod:`.registry`, networkx via
+:mod:`.architecture_metrics`, and the ingestion graph via :mod:`.update`.
+Roughly a second of import, to resolve two functions.
"""
from __future__ import annotations
-from .architecture_metrics import (
- ArchitectureMetrics,
- NodeArchitectureRole,
- architecture_score,
- compute_architecture_metrics,
-)
-from .config import (
- WORKSPACE_CONFIG_FILENAME,
- WORKSPACE_DATA_DIR,
- ContractConfig,
- ManualContractLink,
- RepoEntry,
- WorkspaceConfig,
- ensure_workspace_data_dir,
- find_workspace_root,
-)
-from .contracts import (
- CONTRACTS_FILENAME,
- Contract,
- ContractLink,
- ContractStore,
- load_contract_store,
- run_contract_extraction,
- save_contract_store,
-)
-from .cross_repo import (
- CROSS_REPO_EDGES_FILENAME,
- CrossRepoCoChange,
- CrossRepoOverlay,
- CrossRepoPackageDep,
- load_overlay,
- run_cross_repo_analysis,
- save_overlay,
-)
-from .diagnostics import (
- WEAK_LINK_CONFIDENCE_THRESHOLD,
- ExtractionDiagnostics,
- OrphanProvider,
- RepoDiagnostics,
- UnmatchedConsumer,
- UnmatchedReason,
- build_diagnostics,
-)
-from .registry import (
- RepoContext,
- RepoRegistry,
-)
-from .scanner import (
- DiscoveredRepo,
- ScanResult,
- scan_for_repos,
-)
-from .system_graph import (
- EDGE_KINDS,
- SYSTEM_GRAPH_FILENAME,
- SystemEdge,
- SystemGraph,
- SystemNode,
- build_system_graph,
- load_system_graph,
- run_system_graph_build,
- save_system_graph,
-)
-from .update import (
- RepoUpdateResult,
- check_repo_staleness,
- reconcile_repo_head_commit,
- run_cross_repo_hooks,
- update_single_repo_index,
- update_workspace,
-)
+from typing import Any
+
+#: Public name -> defining submodule; the source of truth for ``__all__``,
+#: ``__getattr__`` and ``__dir__``.
+_EXPORTS: dict[str, str] = {
+ "ArchitectureMetrics": "architecture_metrics",
+ "NodeArchitectureRole": "architecture_metrics",
+ "architecture_score": "architecture_metrics",
+ "compute_architecture_metrics": "architecture_metrics",
+ "WORKSPACE_CONFIG_FILENAME": "config",
+ "WORKSPACE_DATA_DIR": "config",
+ "ContractConfig": "config",
+ "ManualContractLink": "config",
+ "RepoEntry": "config",
+ "WorkspaceConfig": "config",
+ "ensure_workspace_data_dir": "config",
+ "find_workspace_root": "config",
+ "CONTRACTS_FILENAME": "contracts",
+ "Contract": "contracts",
+ "ContractLink": "contracts",
+ "ContractStore": "contracts",
+ "load_contract_store": "contracts",
+ "run_contract_extraction": "contracts",
+ "save_contract_store": "contracts",
+ "CROSS_REPO_EDGES_FILENAME": "cross_repo",
+ "CrossRepoCoChange": "cross_repo",
+ "CrossRepoOverlay": "cross_repo",
+ "CrossRepoPackageDep": "cross_repo",
+ "load_overlay": "cross_repo",
+ "run_cross_repo_analysis": "cross_repo",
+ "save_overlay": "cross_repo",
+ "WEAK_LINK_CONFIDENCE_THRESHOLD": "diagnostics",
+ "ExtractionDiagnostics": "diagnostics",
+ "OrphanProvider": "diagnostics",
+ "RepoDiagnostics": "diagnostics",
+ "UnmatchedConsumer": "diagnostics",
+ "UnmatchedReason": "diagnostics",
+ "build_diagnostics": "diagnostics",
+ "RepoContext": "registry",
+ "RepoRegistry": "registry",
+ "DiscoveredRepo": "scanner",
+ "ScanResult": "scanner",
+ "scan_for_repos": "scanner",
+ "EDGE_KINDS": "system_graph",
+ "SYSTEM_GRAPH_FILENAME": "system_graph",
+ "SystemEdge": "system_graph",
+ "SystemGraph": "system_graph",
+ "SystemNode": "system_graph",
+ "build_system_graph": "system_graph",
+ "load_system_graph": "system_graph",
+ "run_system_graph_build": "system_graph",
+ "save_system_graph": "system_graph",
+ "RepoUpdateResult": "update",
+ "check_repo_staleness": "update",
+ "reconcile_repo_head_commit": "update",
+ "run_cross_repo_hooks": "update",
+ "update_single_repo_index": "update",
+ "update_workspace": "update",
+}
+
+__all__ = sorted(_EXPORTS)
+
+
+def __getattr__(name: str) -> Any:
+ """Resolve a public export on first access, importing only its module."""
+ module = _EXPORTS.get(name)
+ if module is None:
+ # AttributeError, not KeyError: ``from repowise.core.workspace import
+ # contracts`` relies on the import system falling back to a submodule.
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+ from importlib import import_module
+
+ value = getattr(import_module(f"{__name__}.{module}"), name)
+ globals()[name] = value # cache: subsequent accesses skip __getattr__
+ return value
+
-__all__ = [
- # Contracts (Phase 4)
- "CONTRACTS_FILENAME",
- # Cross-repo intelligence
- "CROSS_REPO_EDGES_FILENAME",
- # System graph
- "EDGE_KINDS",
- "SYSTEM_GRAPH_FILENAME",
- # Extraction diagnostics
- "WEAK_LINK_CONFIDENCE_THRESHOLD",
- # Config
- "WORKSPACE_CONFIG_FILENAME",
- "WORKSPACE_DATA_DIR",
- # Architecture metrics (Phase 6)
- "ArchitectureMetrics",
- "Contract",
- "ContractConfig",
- "ContractLink",
- "ContractStore",
- "CrossRepoCoChange",
- "CrossRepoOverlay",
- "CrossRepoPackageDep",
- # Scanner
- "DiscoveredRepo",
- "ExtractionDiagnostics",
- "ManualContractLink",
- "NodeArchitectureRole",
- "OrphanProvider",
- # Registry
- "RepoContext",
- "RepoDiagnostics",
- "RepoEntry",
- "RepoRegistry",
- # Update
- "RepoUpdateResult",
- "ScanResult",
- "SystemEdge",
- "SystemGraph",
- "SystemNode",
- "UnmatchedConsumer",
- "UnmatchedReason",
- "WorkspaceConfig",
- "architecture_score",
- "build_diagnostics",
- "build_system_graph",
- "check_repo_staleness",
- "compute_architecture_metrics",
- "ensure_workspace_data_dir",
- "find_workspace_root",
- "load_contract_store",
- "load_overlay",
- "load_system_graph",
- "reconcile_repo_head_commit",
- "run_contract_extraction",
- "run_cross_repo_analysis",
- "run_cross_repo_hooks",
- "run_system_graph_build",
- "save_contract_store",
- "save_overlay",
- "save_system_graph",
- "scan_for_repos",
- "update_single_repo_index",
- "update_workspace",
-]
+def __dir__() -> list[str]:
+ return sorted(__all__)
diff --git a/tests/unit/workspace/test_lazy_workspace_exports.py b/tests/unit/workspace/test_lazy_workspace_exports.py
new file mode 100644
index 000000000..083c52efc
--- /dev/null
+++ b/tests/unit/workspace/test_lazy_workspace_exports.py
@@ -0,0 +1,82 @@
+"""Guard tests for the lazy (PEP 562) ``repowise.core.workspace`` exports.
+
+``repowise mcp`` reaches ``workspace.config`` — a yaml-only leaf — on every
+invocation, and must not pay for the analysis subsystem (sqlalchemy via
+``registry``, networkx via ``architecture_metrics``, the ingestion graph via
+``update``) through the package ``__init__``.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from unittest import mock
+
+import pytest
+
+import repowise.core.workspace as workspace
+
+#: Submodules the startup path must not drag in via the package ``__init__``.
+HEAVY_SUBMODULES = ("registry", "architecture_metrics", "update", "contracts", "system_graph")
+
+
+def _probe(code: str) -> subprocess.CompletedProcess[str]:
+ """Run ``code`` in a clean interpreter, where import state is not shared."""
+ return subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)
+
+
+def test_all_exports_resolve():
+ for name in workspace.__all__:
+ assert getattr(workspace, name) is not None, name
+
+
+def test_dir_includes_lazy_exports():
+ listing = dir(workspace)
+ assert "WorkspaceConfig" in listing
+ assert "find_workspace_root" in listing
+
+
+def test_unknown_attribute_raises():
+ with pytest.raises(AttributeError, match="does_not_exist"):
+ _ = workspace.does_not_exist
+
+
+def test_submodule_import_still_resolves():
+ """``from pkg import submodule`` needs ``__getattr__`` to raise AttributeError."""
+ from repowise.core.workspace import contracts
+
+ assert contracts.__name__ == "repowise.core.workspace.contracts"
+
+
+def test_package_attribute_is_patchable():
+ """Callers do a function-local ``from repowise.core.workspace import X``,
+ so patching the package attribute must still intercept them."""
+ sentinel = object()
+ with mock.patch("repowise.core.workspace.scan_for_repos", sentinel):
+ from repowise.core.workspace import scan_for_repos
+
+ assert scan_for_repos is sentinel
+
+ from repowise.core.workspace import scan_for_repos as restored
+
+ assert restored is not sentinel
+
+
+def test_config_import_does_not_load_analysis_stack():
+ result = _probe(
+ "import sys; import repowise.core.workspace.config; "
+ f"loaded = [n for n in {HEAVY_SUBMODULES!r} "
+ "if f'repowise.core.workspace.{n}' in sys.modules]; "
+ "print('loaded:', loaded); sys.exit(1 if loaded else 0)"
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_lazy_attribute_access_imports_on_demand():
+ result = _probe(
+ "import sys; import repowise.core.workspace as w; "
+ "assert 'repowise.core.workspace.scanner' not in sys.modules; "
+ "assert w.scan_for_repos.__name__ == 'scan_for_repos'; "
+ "assert 'repowise.core.workspace.scanner' in sys.modules"
+ )
+ assert result.returncode == 0, result.stderr