Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(core): add pluggable storage seams and capability registries (#219)
Raghav Chamadiya5d130c3859e9
diff --git a/docs/architecture/pluggable-storage.md b/docs/architecture/pluggable-storage.mdnew file mode 100644index 000000000..743007424--- /dev/null+++ b/docs/architecture/pluggable-storage.md@@ -0,0 +1,222 @@+# Pluggable storage and capability seams++repowise ships with sensible defaults — a local SQLite database, an+in-process NetworkX graph, an in-memory or LanceDB vector store, a+hard-coded Click CLI, a fixed set of MCP tools. For a single developer+on a single machine those defaults are the right answer.++The minute a deployment grows past that — a larger repo that wants to+checkpoint its index, a team that backs persistence with PostgreSQL, a+plugin author who wants to add a CLI subcommand, an internal tool that+needs to observe pipeline phase transitions — the defaults stop being+the only answer. The seams documented below let those use cases be+served *without* forking repowise.++This document is the public-facing reference. It deliberately avoids+implementation details that change between releases; the source of+truth for each contract is the ABC in+[`packages/core/src/repowise/core/persistence/_interfaces`](../../packages/core/src/repowise/core/persistence/_interfaces)+and the registries in+[`packages/core/src/repowise/core/registry`](../../packages/core/src/repowise/core/registry).++---++## What's pluggable++Three storage contracts and three capability registries.++### Storage contracts++| ABC | Default impl | What it stores |+|---|---|---|+| `IndexStore` | `SqlIndexStore` | Repositories, pages, decisions, git metadata, dead code, health, coverage — every relational table |+| `GraphStore` | `InProcessGraphStore` | The code dependency graph: nodes, edges, file-level metrics (pagerank, betweenness, communities) |+| `JobStore` | `SqlJobStore` | Pipeline checkpoint/resume state, keyed on phase × repository |+| `VectorStore` | `InMemoryVectorStore`, `LanceDBVectorStore`, `PgVectorStore` | Embedding storage for page text and decision-record snippets |++`VectorStore` already existed before this release; the other three are+new. All four follow the same pattern — an async ABC plus one or more+concrete implementations bundled with repowise.++### Capability registries++| Registry | What it collects | When the host applies it |+|---|---|---|+| `cli_registry` | Click commands and groups | At CLI import time, via `cli_registry.apply(cli)` |+| `mcp_tool_registry` | MCP tool functions | At MCP server boot, via `mcp_tool_registry.apply(mcp)` |+| `pipeline_hooks` | Pre/post phase callbacks | On every phase transition, via `HookProgressCallback` wrapping the orchestrator's progress callback |++---++## When to author a plugin++Reach for these seams when you want one of:++- **A different storage backend.** PostgreSQL, MySQL, a hosted vector+ database — anything that honors the ABC methods works. Write the+ implementation, register it with the application boot code, and+ every caller that depends on the ABC is suddenly using your backend.+- **A larger repository than the defaults handle gracefully.** The+ `JobStore` contract is the foundation for checkpoint/resume; pair it+ with a `GitIndexTier`-aware indexer and a custom pipeline hook that+ flushes state on a fast cadence.+- **An additional CLI subcommand.** Register it through `cli_registry`+ and the root group picks it up at startup.+- **An additional MCP tool.** Decorate the function with+ `@mcp_tool_registry.register` (or the `@mcp_tool_registry.tool()`+ alias) and the FastMCP server attaches it at boot.+- **Cross-cutting observability.** Register a hook on+ `pipeline_hooks` to fire around any phase the orchestrator announces+ — traverse, parse, graph, git, co_change, dead_code, decisions,+ generation.++---++## Writing an `IndexStore`++```python+from repowise.core.persistence._interfaces import IndexStore+from repowise.core.persistence.stores import SqlIndexStore+++class MyScopedIndexStore(SqlIndexStore):+ """Adds tenant-scoped filtering on top of the SQL default."""++ def __init__(self, session, *, tenant_id: str) -> None:+ super().__init__(session)+ self._tenant_id = tenant_id++ async def upsert_repository(self, **kwargs):+ kwargs.setdefault("settings", {})["tenant_id"] = self._tenant_id+ return await super().upsert_repository(**kwargs)++ # Override the read paths to filter by tenant_id, etc.+```++Or replace the storage entirely:++```python+from repowise.core.persistence._interfaces import IndexStore++class RemoteIndexStore(IndexStore):+ async def upsert_repository(self, *, name, local_path, **_):+ ...+ # implement every abstract method+```++The shared contract test in+[`tests/unit/persistence/test_interfaces_contract.py`](../../tests/unit/persistence/test_interfaces_contract.py)+parametrises over registered implementations. Adding your backend to+the parametrisation surfaces any contract drift immediately.++---++## Writing a `GraphStore`++```python+from repowise.core.persistence._interfaces import GraphStore++class RemoteGraphStore(GraphStore):+ def add_node(self, node_id, **attrs): ...+ def add_edge(self, source, target, **attrs): ...+ # ...+```++The contract is intentionally small. Implementations may compute+pagerank / betweenness / community membership however they like — the+in-tree default uses NetworkX, but a hosted graph database can return+its native metric outputs.++---++## Writing a `JobStore`++```python+from repowise.core.persistence._interfaces import JobRecord, JobState, JobStore++class FileJobStore(JobStore):+ async def create_job(self, *, repository_id, phase, metadata=None) -> JobRecord:+ ...+ async def checkpoint(self, job_id, cursor) -> JobRecord:+ ...+ # ...+```++`JobStore` is the foundation for crash-safe long-running pipelines.+The orchestrator integration that calls `create_job` / `checkpoint`+on every phase transition lands in a follow-up release; the contract+is published now so plugin authors can target it.++---++## Adding a CLI subcommand++```python+import click+from repowise.core.registry import register_command+++def my_thing() -> None:+ """Description shown in `repowise --help`."""+ click.echo("hello")+++register_command(my_thing)+```++Import the module that calls `register_command` before+`cli_registry.apply()` runs. In a plugin distributed as a separate+wheel, the simplest pattern is a top-level import in your plugin's+`__init__.py`.++---++## Adding an MCP tool++```python+from repowise.core.registry import mcp_tool_registry as mcp+++async def my_tool(arg: str) -> dict:+ """Tool description visible to MCP clients."""+ return {"arg": arg}+```++The host server calls `mcp_tool_registry.apply(mcp_instance)` once at+boot, attaching every registered tool to the FastMCP server. The+`.tool()` alias on the registry exists so call sites read the same as+they did against the FastMCP instance directly.++---++## Observing pipeline phases++```python+from repowise.core.registry import register_hook+++def warm_caches(phase: str) -> None:+ ...+++register_hook("graph", warm_caches, when="post")+register_hook("parse", lambda phase: ..., when="pre")+```++Hook callbacks receive the phase name as their only positional+argument. Exceptions raised inside a hook are caught and logged so a+broken plugin cannot derail the pipeline.++---++## Defaults stay the defaults++The seams add a layer of indirection but no behavior change for users+of the OSS defaults: `repowise init` still writes to+`.repowise/wiki.db`, the in-process graph still owns ingestion, the+nine MCP tools still expose the same surface, and `repowise --help`+lists the same commands in the same order. Plugins extend the+defaults; they don't replace them unless an integration explicitly+swaps an implementation in.diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 59e7152e0..5e99f8a9d 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -24,6 +24,7 @@ from repowise.cli.commands.status_cmd import status_commandfrom repowise.cli.commands.update_cmd import update_commandfrom repowise.cli.commands.watch_cmd import watch_commandfrom repowise.cli.commands.workspace_cmd import workspace_group+from repowise.core.registry import cli_registry, register_command@click.group()@@ -45,23 +46,28 @@ def cli(ctx: click.Context) -> None:pass-cli.add_command(augment_command)-cli.add_command(init_command)-cli.add_command(delete_command)-cli.add_command(claude_md_command)-cli.add_command(costs_command)-cli.add_command(update_command)-cli.add_command(dead_code_command)-cli.add_command(health_command)-cli.add_command(decision_group)-cli.add_command(search_command)-cli.add_command(export_command)-cli.add_command(hook_group)-cli.add_command(status_command)-cli.add_command(doctor_command)-cli.add_command(watch_command)-cli.add_command(serve_command)-cli.add_command(mcp_command)-cli.add_command(reindex_command)-cli.add_command(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(dead_code_command)+register_command(health_command)+register_command(decision_group)+register_command(search_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(workspace_group)++cli_registry.apply(cli)diff --git a/packages/core/alembic/versions/0020_pipeline_jobs.py b/packages/core/alembic/versions/0020_pipeline_jobs.pynew file mode 100644index 000000000..2de423bad--- /dev/null+++ b/packages/core/alembic/versions/0020_pipeline_jobs.py@@ -0,0 +1,64 @@+"""Add pipeline_jobs table for checkpoint/resume state.++Revision ID: 0020+Revises: 0019+Create Date: 2026-05-23+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "0020"+down_revision: str | None = "0019"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "pipeline_jobs",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("phase", sa.String(64), nullable=False),+ sa.Column("state", sa.String(32), nullable=False, server_default="pending"),+ sa.Column("cursor", sa.Text, nullable=True),+ sa.Column(+ "started_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column("error", sa.Text, nullable=True),+ sa.Column("metadata_json", sa.Text, nullable=False, server_default="{}"),+ )+ op.create_index(+ "ix_pipeline_jobs_repository_id",+ "pipeline_jobs",+ ["repository_id"],+ )+ op.create_index(+ "ix_pipeline_jobs_repo_state",+ "pipeline_jobs",+ ["repository_id", "state"],+ )+++def downgrade() -> None:+ op.drop_index("ix_pipeline_jobs_repo_state", table_name="pipeline_jobs")+ op.drop_index("ix_pipeline_jobs_repository_id", table_name="pipeline_jobs")+ op.drop_table("pipeline_jobs")diff --git a/packages/core/src/repowise/core/ingestion/git_indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer.pyindex e90f91dc9..54b85532c 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import enumimport jsonimport mathimport re@@ -28,6 +29,22 @@ from .languages.registry import REGISTRY as _LANG_REGISTRYlogger = structlog.get_logger(__name__)++class GitIndexTier(enum.StrEnum):+ """Public knob for git-indexing depth on large repositories.++ ``FULL`` (the default) preserves today's behavior — last *commit_depth*+ commits with co-change accumulation and extended blame. ``ESSENTIAL``+ runs only the cheap baseline (last commit, no co-change graph) and is+ intended for the fast orchestrator path; the implementation that+ actually switches on this tier is delivered in a follow-up phase+ addressing large-repo scale. The enum is published in this revision so+ plugin authors and downstream tooling can target it now.+ """++ ESSENTIAL = "essential"+ FULL = "full"+# Silence GitPython's _CatFileContentStream.__del__ ValueError spam.# When git cat-file streams are GC'd after the subprocess pipe is closed,# their __del__ tries to drain remaining bytes and hits a closed file.diff --git a/packages/core/src/repowise/core/persistence/_interfaces/__init__.py b/packages/core/src/repowise/core/persistence/_interfaces/__init__.pynew file mode 100644index 000000000..936088b79--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/__init__.py@@ -0,0 +1,35 @@+"""Pluggable persistence interfaces.++Three abstract storage contracts live here so callers can swap storage+backends without touching call sites:++- :class:`IndexStore` — SQL-backed CRUD facade over the relational model+ (repositories, pages, decisions, git metadata, health, dead code, etc.).+- :class:`GraphStore` — query + persistence surface for the code graph+ (nodes, edges, in-memory traversal, batch upserts).+- :class:`JobStore` — checkpoint/resume state for long-running pipeline runs.++The OSS defaults live in :mod:`repowise.core.persistence.stores`:+``SqlIndexStore``, ``InProcessGraphStore``, ``SqlJobStore``.++These ABCs intentionally describe *what* is stored, not *how*. An+implementation may wrap any SQL dialect, a remote service, or an+in-memory mock — anything that honors the method signatures is a valid+plugin. The in-tree contract tests in+``tests/unit/persistence/test_interfaces_contract.py`` exercise the+shared behavior against every registered implementation.+"""++from __future__ import annotations++from .graph_store import GraphStore+from .index_store import IndexStore+from .job_store import JobRecord, JobState, JobStore++__all__ = [+ "GraphStore",+ "IndexStore",+ "JobRecord",+ "JobState",+ "JobStore",+]diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.pynew file mode 100644index 000000000..4b3ef663d--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/_analysis.py@@ -0,0 +1,251 @@+"""IndexStore mixin: git metadata, dead code, decisions, health, coverage.++The "analysis" surface of IndexStore — anything produced by reading the+repo's history or running quality biomarkers, plus the decision-record+catalog that hangs off the same tables.++Split out from :class:`IndexStore` to keep each interface file under 400+lines per the project code-quality rule.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from datetime import datetime+from typing import Any++from ..models import (+ CoverageFile,+ DeadCodeFinding,+ DecisionRecord,+ GitMetadata,+ HealthFileMetric,+ HealthFinding,+ HealthSnapshot,+)+++class AnalysisIndexStore(ABC):+ """GitMetadata, DeadCode, Decision, Health, Coverage CRUD."""++ # ------------------------------------------------------------------+ # GitMetadata+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_git_metadata(+ self, *, repository_id: str, file_path: str, **kwargs: object+ ) -> GitMetadata: ...++ @abstractmethod+ async def get_git_metadata(+ self, repository_id: str, file_path: str+ ) -> GitMetadata | None: ...++ @abstractmethod+ async def get_git_metadata_bulk(+ self, repository_id: str, file_paths: list[str]+ ) -> dict[str, GitMetadata]: ...++ @abstractmethod+ async def get_all_git_metadata(+ self, repository_id: str+ ) -> dict[str, GitMetadata]: ...++ @abstractmethod+ async def upsert_git_metadata_bulk(+ self, repository_id: str, metadata_list: list[dict]+ ) -> None: ...++ @abstractmethod+ async def recompute_git_percentiles(self, repository_id: str) -> int: ...++ # ------------------------------------------------------------------+ # DeadCode+ # ------------------------------------------------------------------++ @abstractmethod+ async def save_dead_code_findings(+ self, repository_id: str, findings: list[dict]+ ) -> None: ...++ @abstractmethod+ async def get_dead_code_findings(+ self,+ repository_id: str,+ *,+ kind: str | None = None,+ min_confidence: float = 0.0,+ status: str = "open",+ ) -> list[DeadCodeFinding]: ...++ @abstractmethod+ async def update_dead_code_status(+ self, finding_id: str, status: str, note: str | None = None+ ) -> DeadCodeFinding | None: ...++ @abstractmethod+ async def get_dead_code_summary(self, repository_id: str) -> dict: ...++ # ------------------------------------------------------------------+ # DecisionRecord+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_decision(self, **kwargs: Any) -> DecisionRecord: ...++ @abstractmethod+ async def bulk_upsert_decisions(+ self, repository_id: str, decisions: list[dict]+ ) -> None: ...++ @abstractmethod+ async def get_decision(self, decision_id: str) -> DecisionRecord | None: ...++ @abstractmethod+ async def list_decisions(+ self,+ repository_id: str,+ *,+ status: str | None = None,+ source: str | None = None,+ tag: str | None = None,+ module: str | None = None,+ include_proposed: bool = True,+ limit: int = 100,+ offset: int = 0,+ ) -> list[DecisionRecord]: ...++ @abstractmethod+ async def update_decision_metadata(+ self,+ decision_id: str,+ *,+ affected_modules: list[str] | None = None,+ affected_files: list[str] | None = None,+ ) -> DecisionRecord | None: ...++ @abstractmethod+ async def update_decision_status(+ self,+ decision_id: str,+ status: str,+ *,+ superseded_by: str | None = None,+ ) -> DecisionRecord | None: ...++ @abstractmethod+ async def update_decision_by_id(+ self, decision_id: str, **fields: Any+ ) -> DecisionRecord | None: ...++ @abstractmethod+ async def delete_decision(self, decision_id: str) -> bool: ...++ @abstractmethod+ async def recompute_decision_staleness(+ self, repository_id: str, git_meta_map: dict[str, dict]+ ) -> int: ...++ @abstractmethod+ async def get_stale_decisions(+ self, repository_id: str, threshold: float = 0.5+ ) -> list[DecisionRecord]: ...++ @abstractmethod+ async def get_decision_health_summary(self, repository_id: str) -> dict: ...++ # ------------------------------------------------------------------+ # Health+ # ------------------------------------------------------------------++ @abstractmethod+ async def save_health_findings(+ self, repository_id: str, findings: list[Any]+ ) -> None: ...++ @abstractmethod+ async def save_health_metrics(+ self, repository_id: str, metrics: list[Any]+ ) -> None: ...++ @abstractmethod+ async def upsert_health_findings(+ self,+ repository_id: str,+ findings: list[Any],+ *,+ file_paths: list[str],+ ) -> None: ...++ @abstractmethod+ async def upsert_health_metrics(+ self, repository_id: str, metrics: list[Any]+ ) -> None: ...++ @abstractmethod+ async def get_health_findings(+ self,+ repository_id: str,+ *,+ biomarker_type: str | None = None,+ min_severity: str | None = None,+ file_path: str | None = None,+ status: str = "open",+ ) -> list[HealthFinding]: ...++ @abstractmethod+ async def get_health_metrics(+ self, repository_id: str, *, file_paths: list[str] | None = None+ ) -> list[HealthFileMetric]: ...++ @abstractmethod+ async def get_health_summary(self, repository_id: str) -> dict: ...++ @abstractmethod+ async def update_health_finding_status(+ self, finding_id: str, status: str+ ) -> HealthFinding | None: ...++ @abstractmethod+ async def save_health_snapshot(+ self,+ repository_id: str,+ *,+ hotspot_health: float,+ average_health: float,+ worst_performer_path: str | None,+ worst_performer_score: float | None,+ per_file_scores: dict[str, float] | None = None,+ taken_at: datetime | None = None,+ ) -> HealthSnapshot: ...++ @abstractmethod+ async def list_health_snapshots(+ self, repository_id: str, *, limit: int | None = None+ ) -> list[HealthSnapshot]: ...++ # ------------------------------------------------------------------+ # Coverage+ # ------------------------------------------------------------------++ @abstractmethod+ async def save_coverage_files(+ self,+ repository_id: str,+ files: list[Any],+ *,+ source_format: str,+ ingested_commit_sha: str | None = None,+ ) -> None: ...++ @abstractmethod+ async def load_coverage_for_repo(+ self,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+ ) -> list[CoverageFile]: ...++ @abstractmethod+ async def get_coverage_summary(self, repository_id: str) -> dict[str, Any]: ...diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_graph_records.py b/packages/core/src/repowise/core/persistence/_interfaces/_graph_records.pynew file mode 100644index 000000000..7d19b6632--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/_graph_records.py@@ -0,0 +1,111 @@+"""IndexStore mixin: relational graph rows, external systems, symbols.++The "graph records" surface of :class:`IndexStore` — anything that lives+in the SQL ``graph_nodes`` / ``graph_edges`` / ``external_systems`` /+``wiki_symbols`` tables. Read/write of the *in-memory* code graph+(NetworkX) is a separate contract: :class:`GraphStore`.++Split out from :class:`IndexStore` to keep each interface file under 400+lines.+"""++from __future__ import annotations++from abc import ABC, abstractmethod++from ..models import ExternalSystem, GraphEdge, GraphNode+++class GraphRecordsIndexStore(ABC):+ """SQL CRUD for graph_nodes, graph_edges, external_systems, wiki_symbols."""++ # ------------------------------------------------------------------+ # graph_nodes / graph_edges+ # ------------------------------------------------------------------++ @abstractmethod+ async def batch_upsert_graph_nodes(+ self, repository_id: str, nodes: list[dict]+ ) -> None: ...++ @abstractmethod+ async def batch_upsert_graph_edges(+ self, repository_id: str, edges: list[dict]+ ) -> None: ...++ @abstractmethod+ async def get_graph_node(+ self, repository_id: str, node_id: str+ ) -> GraphNode | None: ...++ @abstractmethod+ async def get_graph_edges_for_node(+ self,+ repository_id: str,+ node_id: str,+ *,+ direction: str = "both",+ edge_types: list[str] | None = None,+ limit: int = 50,+ ) -> list[GraphEdge]: ...++ @abstractmethod+ async def get_graph_nodes_by_ids(+ self, repository_id: str, node_ids: list[str]+ ) -> dict[str, GraphNode]: ...++ @abstractmethod+ async def get_all_file_metrics(self, repository_id: str) -> list[GraphNode]: ...++ @abstractmethod+ async def get_community_members(+ self,+ repository_id: str,+ community_id: int,+ *,+ node_type: str = "file",+ limit: int = 50,+ ) -> list[GraphNode]: ...++ @abstractmethod+ async def get_cross_community_edges(+ self, repository_id: str, community_id: int+ ) -> list[dict]: ...++ @abstractmethod+ async def get_top_entry_points(+ self, repository_id: str, *, min_score: float = 0.3, limit: int = 20+ ) -> list[GraphNode]: ...++ @abstractmethod+ async def get_node_degree_counts(+ self, repository_id: str, node_id: str+ ) -> dict[str, int]: ...++ # ------------------------------------------------------------------+ # external_systems+ # ------------------------------------------------------------------++ @abstractmethod+ async def bulk_upsert_external_systems(+ self, repository_id: str, systems: list[dict]+ ) -> dict[tuple[str, str], int]: ...++ @abstractmethod+ async def link_graph_nodes_to_external_systems(+ self, repository_id: str, name_to_id: dict[str, int]+ ) -> int: ...++ @abstractmethod+ async def list_external_systems(+ self, repository_id: str+ ) -> list[ExternalSystem]: ...++ # ------------------------------------------------------------------+ # wiki_symbols+ # ------------------------------------------------------------------++ @abstractmethod+ async def batch_upsert_symbols(+ self, repository_id: str, symbols: list+ ) -> None: ...diff --git a/packages/core/src/repowise/core/persistence/_interfaces/_meta.py b/packages/core/src/repowise/core/persistence/_interfaces/_meta.pynew file mode 100644index 000000000..e26d82d64--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/_meta.py@@ -0,0 +1,191 @@+"""IndexStore mixin: repository, generation jobs, pages, chat, webhooks.++This mixin covers the "meta" surface — the top-level wiki tables that+describe a repository (Repository), the long-running generation jobs that+populate it, the wiki pages themselves, and the conversation/chat history+plus inbound webhook events.++Split out from :class:`IndexStore` to keep each interface file under 400+lines per the project code-quality rule. See ``index_store.py`` for the+aggregate that pulls every mixin together.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from typing import Any++from ..models import (+ ChatMessage,+ Conversation,+ GenerationJob,+ Page,+ PageVersion,+ Repository,+ WebhookEvent,+)+++class MetaIndexStore(ABC):+ """Repository, GenerationJob, Page, Conversation/Chat, Webhook CRUD."""++ # ------------------------------------------------------------------+ # Repository+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_repository(+ self,+ *,+ name: str,+ local_path: str,+ url: str = "",+ default_branch: str = "main",+ settings: dict | None = None,+ ) -> Repository: ...++ @abstractmethod+ async def get_repository(self, repo_id: str) -> Repository | None: ...++ @abstractmethod+ async def get_repository_by_path(self, local_path: str) -> Repository | None: ...++ @abstractmethod+ async def delete_repository(self, repo_id: str) -> bool: ...++ @abstractmethod+ async def list_page_ids(self, repository_id: str) -> list[str]: ...++ # ------------------------------------------------------------------+ # GenerationJob+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_generation_job(+ self,+ *,+ repository_id: str,+ status: str = "pending",+ provider_name: str = "",+ model_name: str = "",+ total_pages: int = 0,+ config: dict | None = None,+ job_id: str | None = None,+ ) -> GenerationJob: ...++ @abstractmethod+ async def get_generation_job(self, job_id: str) -> GenerationJob | None: ...++ @abstractmethod+ async def update_job_status(+ self,+ job_id: str,+ status: str,+ *,+ completed_pages: int | None = None,+ failed_pages: int | None = None,+ current_level: int | None = None,+ total_pages: int | None = None,+ error_message: str | None = None,+ ) -> GenerationJob: ...++ # ------------------------------------------------------------------+ # Page+ # ------------------------------------------------------------------++ @abstractmethod+ async def upsert_page(self, **kwargs: Any) -> Page: ...++ @abstractmethod+ async def upsert_page_from_generated(+ self, generated_page: object, repository_id: str+ ) -> Page: ...++ @abstractmethod+ async def get_page(self, page_id: str) -> Page | None: ...++ @abstractmethod+ async def list_pages(+ self,+ repository_id: str,+ *,+ page_type: str | None = None,+ limit: int = 100,+ offset: int = 0,+ sort_by: str = "updated_at",+ order: str = "desc",+ ) -> list[Page]: ...++ @abstractmethod+ async def get_page_versions(+ self, page_id: str, *, limit: int = 50+ ) -> list[PageVersion]: ...++ @abstractmethod+ async def get_stale_pages(self, repository_id: str) -> list[Page]: ...++ @abstractmethod+ async def load_prior_pages(self, repository_id: str) -> dict[str, Any]: ...++ # ------------------------------------------------------------------+ # WebhookEvent+ # ------------------------------------------------------------------++ @abstractmethod+ async def store_webhook_event(+ self,+ *,+ provider: str,+ event_type: str,+ payload: dict,+ repository_id: str | None = None,+ delivery_id: str = "",+ ) -> WebhookEvent: ...++ @abstractmethod+ async def mark_webhook_processed(+ self, event_id: str, *, job_id: str | None = None+ ) -> None: ...++ # ------------------------------------------------------------------+ # Conversation / ChatMessage+ # ------------------------------------------------------------------++ @abstractmethod+ async def create_conversation(+ self, *, repository_id: str, title: str = "New conversation"+ ) -> Conversation: ...++ @abstractmethod+ async def get_conversation(+ self, conversation_id: str+ ) -> Conversation | None: ...++ @abstractmethod+ async def list_conversations(+ self, repository_id: str, *, limit: int = 50+ ) -> list[Conversation]: ...++ @abstractmethod+ async def update_conversation_title(+ self, conversation_id: str, title: str+ ) -> Conversation | None: ...++ @abstractmethod+ async def delete_conversation(self, conversation_id: str) -> bool: ...++ @abstractmethod+ async def touch_conversation(self, conversation_id: str) -> None: ...++ @abstractmethod+ async def create_chat_message(+ self, *, conversation_id: str, role: str, content: dict+ ) -> ChatMessage: ...++ @abstractmethod+ async def list_chat_messages(+ self, conversation_id: str+ ) -> list[ChatMessage]: ...++ @abstractmethod+ async def count_chat_messages(self, conversation_id: str) -> int: ...diff --git a/packages/core/src/repowise/core/persistence/_interfaces/graph_store.py b/packages/core/src/repowise/core/persistence/_interfaces/graph_store.pynew file mode 100644index 000000000..58392c99b--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/graph_store.py@@ -0,0 +1,106 @@+"""GraphStore — pluggable code-graph contract.++The in-tree default is an in-process NetworkX :class:`DiGraph` wrapped by+:class:`repowise.core.persistence.stores.in_process_graph_store.InProcessGraphStore`,+which delegates to the existing+:class:`repowise.core.ingestion.graph.GraphBuilder`.++The contract is deliberately small in this phase. It captures the+operations call-sites depend on today:++- mutating the graph one file/edge at a time during ingestion,+- finalising the build so cached metrics become valid,+- reading pagerank / betweenness / community membership for nodes,+- iterating neighbours for traversal-style analysis.++A future phase introduces a SQL-backed materialised view so the in-memory+graph can be dropped after build; that work will fit beneath this same+ABC by replacing the implementation, not the interface.++Plugin authors may back ``GraphStore`` with a hosted graph database+(Neo4j, FalkorDB, etc.) by honoring the method signatures here; the+contract test in ``tests/unit/persistence/test_interfaces_contract.py``+exercises the shared behavior.+"""++from __future__ import annotations++from abc import ABC, abstractmethod+from typing import Any+++class GraphStore(ABC):+ """Pluggable contract for the code dependency graph."""++ # ------------------------------------------------------------------+ # Mutation+ # ------------------------------------------------------------------++ @abstractmethod+ def add_node(self, node_id: str, **attrs: Any) -> None:+ """Add a node (or update its attributes if it already exists)."""++ @abstractmethod+ def add_edge(self, source: str, target: str, **attrs: Any) -> None:+ """Add a directed edge. Idempotent on (source, target) pairs."""++ @abstractmethod+ def has_node(self, node_id: str) -> bool: ...++ @abstractmethod+ def has_edge(self, source: str, target: str) -> bool: ...++ @abstractmethod+ def remove_node(self, node_id: str) -> None: ...++ @abstractmethod+ def remove_edge(self, source: str, target: str) -> None: ...++ # ------------------------------------------------------------------+ # Finalisation+ # ------------------------------------------------------------------++ @abstractmethod+ def build(self) -> None:+ """Mark the graph finalised. Implementations may compute cached+ metrics here (pagerank, communities) so subsequent read calls are+ fast. Calling :meth:`add_node` / :meth:`add_edge` after ``build``+ should invalidate caches."""++ # ------------------------------------------------------------------+ # Inspection+ # ------------------------------------------------------------------++ @abstractmethod+ def node_count(self) -> int: ...++ @abstractmethod+ def edge_count(self) -> int: ...++ @abstractmethod+ def get_node_attrs(self, node_id: str) -> dict[str, Any] | None:+ """Return the attribute dict for ``node_id`` or ``None`` if absent."""++ @abstractmethod+ def neighbors(self, node_id: str, *, direction: str = "out") -> list[str]:+ """Return neighbours of ``node_id``.++ ``direction``: ``"out"`` (successors), ``"in"`` (predecessors), or+ ``"both"`` (union). Implementations may apply repo-specific limits.+ """++ # ------------------------------------------------------------------+ # Metrics+ # ------------------------------------------------------------------++ @abstractmethod+ def pagerank(self) -> dict[str, float]:+ """Return ``{node_id: pagerank_score}`` for file-level nodes."""++ @abstractmethod+ def betweenness_centrality(self) -> dict[str, float]:+ """Return ``{node_id: betweenness_score}`` for file-level nodes."""++ @abstractmethod+ def communities(self) -> dict[str, int]:+ """Return ``{node_id: community_id}`` for file-level nodes."""diff --git a/packages/core/src/repowise/core/persistence/_interfaces/index_store.py b/packages/core/src/repowise/core/persistence/_interfaces/index_store.pynew file mode 100644index 000000000..4a88e433f--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/index_store.py@@ -0,0 +1,36 @@+"""IndexStore — aggregate pluggable CRUD facade.++:class:`IndexStore` combines three domain mixins:++- :class:`MetaIndexStore` (repository, page, generation job, webhook, chat)+- :class:`AnalysisIndexStore` (git metadata, dead code, decisions, health, coverage)+- :class:`GraphRecordsIndexStore` (graph_nodes, graph_edges, external_systems, wiki_symbols)++The split is purely a file-size concern — each mixin is in its own module+so no interface file exceeds the project line cap. Callers should depend+on the aggregate :class:`IndexStore`, not on individual mixins.++The OSS default implementation is+:class:`repowise.core.persistence.stores.sql_index_store.SqlIndexStore`,+which binds a single :class:`AsyncSession` and delegates each method to+the existing :mod:`repowise.core.persistence.crud` module. Plugin authors+override individual methods to swap dialects, add scoping (e.g. per-tenant+filtering), or back the store with a remote service.++Behavior is verified by ``tests/unit/persistence/test_interfaces_contract.py``+which runs the same suite against every registered :class:`IndexStore`+implementation.+"""++from __future__ import annotations++from ._analysis import AnalysisIndexStore+from ._graph_records import GraphRecordsIndexStore+from ._meta import MetaIndexStore+++class IndexStore(MetaIndexStore, AnalysisIndexStore, GraphRecordsIndexStore):+ """Aggregate pluggable CRUD facade. See module docstring."""+++__all__ = ["IndexStore"]diff --git a/packages/core/src/repowise/core/persistence/_interfaces/job_store.py b/packages/core/src/repowise/core/persistence/_interfaces/job_store.pynew file mode 100644index 000000000..82ebeefb1--- /dev/null+++ b/packages/core/src/repowise/core/persistence/_interfaces/job_store.py@@ -0,0 +1,113 @@+"""JobStore — pluggable checkpoint/resume state for pipeline runs.++A *job* here is one execution of a pipeline phase against a repository.+Storing per-phase state lets a long-running index survive crashes: on+restart the orchestrator looks for incomplete jobs and resumes them at+their last recorded cursor.++The in-tree default is+:class:`repowise.core.persistence.stores.sql_job_store.SqlJobStore`, which+backs the contract with the ``pipeline_jobs`` table introduced in+Alembic revision ``0020``.++This phase introduces the contract only. The orchestrator integration —+writing checkpoints on a fixed cadence and offering ``--resume`` on+startup — lands in a follow-up that addresses large-repo scale.+"""++from __future__ import annotations++import enum+from abc import ABC, abstractmethod+from dataclasses import dataclass+from datetime import datetime+++class JobState(enum.StrEnum):+ """Lifecycle states for a pipeline job."""++ PENDING = "pending"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELLED = "cancelled"+++@dataclass(frozen=True)+class JobRecord:+ """One pipeline job row.++ ``cursor`` is an opaque string that the phase implementation+ interprets — typically a file path, a commit SHA, or a batch index.+ ``metadata`` carries any auxiliary state (e.g. provider / model used)+ so the resume path doesn't have to recompute it.+ """++ id: str+ repository_id: str+ phase: str+ state: JobState+ cursor: str | None+ started_at: datetime+ updated_at: datetime+ error: str | None+ metadata: dict+++class JobStore(ABC):+ """Pluggable contract for pipeline job checkpoints."""++ @abstractmethod+ async def create_job(+ self,+ *,+ repository_id: str,+ phase: str,+ metadata: dict | None = None,+ ) -> JobRecord:+ """Insert a new job in :attr:`JobState.PENDING`. Returns the row."""++ @abstractmethod+ async def get_job(self, job_id: str) -> JobRecord | None: ...++ @abstractmethod+ async def update_state(+ self,+ job_id: str,+ state: JobState,+ *,+ cursor: str | None = None,+ error: str | None = None,+ ) -> JobRecord:+ """Update lifecycle state. ``cursor`` advances on each checkpoint;+ ``error`` is populated on failure transitions."""++ @abstractmethod+ async def checkpoint(self, job_id: str, cursor: str) -> JobRecord:+ """Record progress without changing :class:`JobState`.++ Implementations should be cheap — this is called on a fixed cadence+ inside a tight loop. The OSS default coalesces writes via a single+ UPDATE per call.+ """++ @abstractmethod+ async def find_resumable(+ self, *, repository_id: str | None = None+ ) -> list[JobRecord]:+ """Return jobs in :attr:`JobState.RUNNING` (or ``PENDING``) that+ the orchestrator should offer to resume on startup.++ Filtered to ``repository_id`` when provided.+ """++ @abstractmethod+ async def list_jobs(+ self,+ *,+ repository_id: str | None = None,+ phase: str | None = None,+ state: JobState | None = None,+ limit: int = 100,+ ) -> list[JobRecord]:+ """Read-side query for the dashboard / CLI ``status`` command."""diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 780fb74cc..ec96e286e 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -670,3 +670,37 @@ class AnswerCache(Base):__table_args__ = (UniqueConstraint("repository_id", "question_hash", name="uq_answer_cache_q"),)+++class PipelineJob(Base):+ """Checkpoint/resume state for one execution of a pipeline phase.++ Inserted at the start of each phase that opts into checkpointing, then+ updated on a fixed cadence with the latest opaque ``cursor`` value+ (interpreted by the phase implementation — typically a file path,+ commit SHA, or batch index). On startup, the orchestrator queries+ rows in state ``running`` / ``pending`` for the active repo and+ offers to resume them.++ The full orchestrator integration is delivered in a follow-up phase;+ this revision introduces the table + ABC so plugin authors can target+ it.+ """++ __tablename__ = "pipeline_jobs"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ phase: Mapped[str] = mapped_column(String(64), nullable=False)+ state: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")+ cursor: Mapped[str | None] = mapped_column(Text, nullable=True)+ started_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+ error: Mapped[str | None] = mapped_column(Text, nullable=True)+ metadata_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")diff --git a/packages/core/src/repowise/core/persistence/stores/README.md b/packages/core/src/repowise/core/persistence/stores/README.mdnew file mode 100644index 000000000..8fd996a5e--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/README.md@@ -0,0 +1,69 @@+# persistence/stores++Default implementations of the pluggable persistence ABCs declared in+[`../\_interfaces/`](../_interfaces). Each implementation is a thin+delegation over an existing OSS subsystem — there is no behaviour change+relative to calling the underlying module functions directly. The+classes exist so callers can depend on the contract rather than on a+module-level function namespace, which is what makes alternate backends+(other SQL dialects, in-memory mocks, remote services, scoped wrappers)+possible without forking.++## Purpose++Concrete backends for the three storage seams. Nothing here is required+reading for a user of repowise — the seams are documented at+[`docs/architecture/pluggable-storage.md`](../../../../../../docs/architecture/pluggable-storage.md).++## Public API++| Class | ABC | Backed by |+|---|---|---|+| `SqlIndexStore` | `IndexStore` | `repowise.core.persistence.crud` + `AsyncSession` |+| `InProcessGraphStore` | `GraphStore` | In-memory `networkx.DiGraph` + NetworkX algorithms |+| `SqlJobStore` | `JobStore` | `pipeline_jobs` table (Alembic revision `0020`) |++Each class is constructed with the resources it needs (a session for+SQL-backed stores, an optional pre-built graph for the in-process graph+store) and exposes the methods declared on its ABC.++## Internal layout++```+stores/+ __init__.py # re-exports+ sql_index_store.py # SqlIndexStore aggregate (thin shell)+ _sql_meta.py # delegations for the meta domain+ _sql_analysis.py # delegations for the analysis domain+ _sql_graph_records.py # delegations for the graph-records domain+ in_process_graph_store.py # InProcessGraphStore (NetworkX wrapper)+ sql_job_store.py # SqlJobStore+ README.md+```++`SqlIndexStore` is split into three private mixins (`_sql_meta`,+`_sql_analysis`, `_sql_graph_records`) to keep every file under the+400-line cap. The mixins are not part of the public API — they exist+only as a file-size split.++## Extension points++To author a new `IndexStore` backend:++1. Implement the methods on `repowise.core.persistence._interfaces.IndexStore`+ (or subclass `SqlIndexStore` and override the methods that change).+2. Construct your store wherever the host application currently+ constructs `SqlIndexStore`.++The shared behavioral test in+`tests/unit/persistence/test_interfaces_contract.py` parametrises over+every registered backend, so adding your implementation to the test+parametrisation surfaces any contract drift immediately.++## Tests++- `tests/unit/persistence/test_interfaces_contract.py` — runs the same+ contract suite against every `IndexStore` / `GraphStore` / `JobStore`+ implementation.+- `tests/integration/persistence/test_sql_job_store_pg.py` — exercises+ `SqlJobStore` against a real PostgreSQL instance via testcontainers.diff --git a/packages/core/src/repowise/core/persistence/stores/__init__.py b/packages/core/src/repowise/core/persistence/stores/__init__.pynew file mode 100644index 000000000..21189af7d--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/__init__.py@@ -0,0 +1,28 @@+"""Default storage implementations.++This subpackage holds the OSS defaults for the three pluggable+persistence ABCs in :mod:`repowise.core.persistence._interfaces`:++- :class:`SqlIndexStore` wraps :mod:`repowise.core.persistence.crud`+ behind the :class:`IndexStore` ABC.+- :class:`InProcessGraphStore` wraps+ :class:`repowise.core.ingestion.graph.GraphBuilder` behind the+ :class:`GraphStore` ABC.+- :class:`SqlJobStore` backs the :class:`JobStore` ABC with the+ ``pipeline_jobs`` table.++Other implementations (test doubles, remote-backed plugins, scoped+wrappers) live outside this subpackage and depend only on the ABCs.+"""++from __future__ import annotations++from .in_process_graph_store import InProcessGraphStore+from .sql_index_store import SqlIndexStore+from .sql_job_store import SqlJobStore++__all__ = [+ "InProcessGraphStore",+ "SqlIndexStore",+ "SqlJobStore",+]diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.pynew file mode 100644index 000000000..3deb76a14--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/_sql_analysis.py@@ -0,0 +1,302 @@+"""Analysis-domain delegations for :class:`SqlIndexStore`.++Git metadata, dead code, decision records, health, coverage — each method+delegates to :mod:`crud`. Split out to keep store files under 400 lines.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from .. import crud+from .._interfaces._analysis import AnalysisIndexStore+from ..models import (+ CoverageFile,+ DeadCodeFinding,+ DecisionRecord,+ GitMetadata,+ HealthFileMetric,+ HealthFinding,+ HealthSnapshot,+)+++class _SqlAnalysisMixin(AnalysisIndexStore):+ """Concrete delegations for the analysis IndexStore surface."""++ _session: AsyncSession++ async def upsert_git_metadata(+ self, *, repository_id: str, file_path: str, **kwargs: object+ ) -> GitMetadata:+ return await crud.upsert_git_metadata(+ self._session,+ repository_id=repository_id,+ file_path=file_path,+ **kwargs,+ )++ async def get_git_metadata(+ self, repository_id: str, file_path: str+ ) -> GitMetadata | None:+ return await crud.get_git_metadata(self._session, repository_id, file_path)++ async def get_git_metadata_bulk(+ self, repository_id: str, file_paths: list[str]+ ) -> dict[str, GitMetadata]:+ return await crud.get_git_metadata_bulk(+ self._session, repository_id, file_paths+ )++ async def get_all_git_metadata(+ self, repository_id: str+ ) -> dict[str, GitMetadata]:+ return await crud.get_all_git_metadata(self._session, repository_id)++ async def upsert_git_metadata_bulk(+ self, repository_id: str, metadata_list: list[dict]+ ) -> None:+ await crud.upsert_git_metadata_bulk(+ self._session, repository_id, metadata_list+ )++ async def recompute_git_percentiles(self, repository_id: str) -> int:+ return await crud.recompute_git_percentiles(self._session, repository_id)++ async def save_dead_code_findings(+ self, repository_id: str, findings: list[dict]+ ) -> None:+ await crud.save_dead_code_findings(self._session, repository_id, findings)++ async def get_dead_code_findings(+ self,+ repository_id: str,+ *,+ kind: str | None = None,+ min_confidence: float = 0.0,+ status: str = "open",+ ) -> list[DeadCodeFinding]:+ return await crud.get_dead_code_findings(+ self._session,+ repository_id,+ kind=kind,+ min_confidence=min_confidence,+ status=status,+ )++ async def update_dead_code_status(+ self, finding_id: str, status: str, note: str | None = None+ ) -> DeadCodeFinding | None:+ return await crud.update_dead_code_status(+ self._session, finding_id, status, note+ )++ async def get_dead_code_summary(self, repository_id: str) -> dict:+ return await crud.get_dead_code_summary(self._session, repository_id)++ async def upsert_decision(self, **kwargs: Any) -> DecisionRecord:+ return await crud.upsert_decision(self._session, **kwargs)++ async def bulk_upsert_decisions(+ self, repository_id: str, decisions: list[dict]+ ) -> None:+ await crud.bulk_upsert_decisions(self._session, repository_id, decisions)++ async def get_decision(self, decision_id: str) -> DecisionRecord | None:+ return await crud.get_decision(self._session, decision_id)++ async def list_decisions(+ self,+ repository_id: str,+ *,+ status: str | None = None,+ source: str | None = None,+ tag: str | None = None,+ module: str | None = None,+ include_proposed: bool = True,+ limit: int = 100,+ offset: int = 0,+ ) -> list[DecisionRecord]:+ return await crud.list_decisions(+ self._session,+ repository_id,+ status=status,+ source=source,+ tag=tag,+ module=module,+ include_proposed=include_proposed,+ limit=limit,+ offset=offset,+ )++ async def update_decision_metadata(+ self,+ decision_id: str,+ *,+ affected_modules: list[str] | None = None,+ affected_files: list[str] | None = None,+ ) -> DecisionRecord | None:+ return await crud.update_decision_metadata(+ self._session,+ decision_id,+ affected_modules=affected_modules,+ affected_files=affected_files,+ )++ async def update_decision_status(+ self,+ decision_id: str,+ status: str,+ *,+ superseded_by: str | None = None,+ ) -> DecisionRecord | None:+ return await crud.update_decision_status(+ self._session, decision_id, status, superseded_by=superseded_by+ )++ async def update_decision_by_id(+ self, decision_id: str, **fields: Any+ ) -> DecisionRecord | None:+ return await crud.update_decision_by_id(self._session, decision_id, **fields)++ async def delete_decision(self, decision_id: str) -> bool:+ return await crud.delete_decision(self._session, decision_id)++ async def recompute_decision_staleness(+ self, repository_id: str, git_meta_map: dict[str, dict]+ ) -> int:+ return await crud.recompute_decision_staleness(+ self._session, repository_id, git_meta_map+ )++ async def get_stale_decisions(+ self, repository_id: str, threshold: float = 0.5+ ) -> list[DecisionRecord]:+ return await crud.get_stale_decisions(+ self._session, repository_id, threshold+ )++ async def get_decision_health_summary(self, repository_id: str) -> dict:+ return await crud.get_decision_health_summary(self._session, repository_id)++ async def save_health_findings(+ self, repository_id: str, findings: list[Any]+ ) -> None:+ await crud.save_health_findings(self._session, repository_id, findings)++ async def save_health_metrics(+ self, repository_id: str, metrics: list[Any]+ ) -> None:+ await crud.save_health_metrics(self._session, repository_id, metrics)++ async def upsert_health_findings(+ self,+ repository_id: str,+ findings: list[Any],+ *,+ file_paths: list[str],+ ) -> None:+ await crud.upsert_health_findings(+ self._session, repository_id, findings, file_paths=file_paths+ )++ async def upsert_health_metrics(+ self, repository_id: str, metrics: list[Any]+ ) -> None:+ await crud.upsert_health_metrics(self._session, repository_id, metrics)++ async def get_health_findings(+ self,+ repository_id: str,+ *,+ biomarker_type: str | None = None,+ min_severity: str | None = None,+ file_path: str | None = None,+ status: str = "open",+ ) -> list[HealthFinding]:+ return await crud.get_health_findings(+ self._session,+ repository_id,+ biomarker_type=biomarker_type,+ min_severity=min_severity,+ file_path=file_path,+ status=status,+ )++ async def get_health_metrics(+ self, repository_id: str, *, file_paths: list[str] | None = None+ ) -> list[HealthFileMetric]:+ return await crud.get_health_metrics(+ self._session, repository_id, file_paths=file_paths+ )++ async def get_health_summary(self, repository_id: str) -> dict:+ return await crud.get_health_summary(self._session, repository_id)++ async def update_health_finding_status(+ self, finding_id: str, status: str+ ) -> HealthFinding | None:+ return await crud.update_health_finding_status(+ self._session, finding_id, status+ )++ async def save_health_snapshot(+ self,+ repository_id: str,+ *,+ hotspot_health: float,+ average_health: float,+ worst_performer_path: str | None,+ worst_performer_score: float | None,+ per_file_scores: dict[str, float] | None = None,+ taken_at: datetime | None = None,+ ) -> HealthSnapshot:+ return await crud.save_health_snapshot(+ self._session,+ repository_id,+ hotspot_health=hotspot_health,+ average_health=average_health,+ worst_performer_path=worst_performer_path,+ worst_performer_score=worst_performer_score,+ per_file_scores=per_file_scores,+ taken_at=taken_at,+ )++ async def list_health_snapshots(+ self, repository_id: str, *, limit: int | None = None+ ) -> list[HealthSnapshot]:+ return await crud.list_health_snapshots(+ self._session, repository_id, limit=limit+ )++ async def save_coverage_files(+ self,+ repository_id: str,+ files: list[Any],+ *,+ source_format: str,+ ingested_commit_sha: str | None = None,+ ) -> None:+ await crud.save_coverage_files(+ self._session,+ repository_id,+ files,+ source_format=source_format,+ ingested_commit_sha=ingested_commit_sha,+ )++ async def load_coverage_for_repo(+ self,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+ ) -> list[CoverageFile]:+ return await crud.load_coverage_for_repo(+ self._session, repository_id, file_paths=file_paths+ )++ async def get_coverage_summary(self, repository_id: str) -> dict[str, Any]:+ return await crud.get_coverage_summary(self._session, repository_id)diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_graph_records.py b/packages/core/src/repowise/core/persistence/stores/_sql_graph_records.pynew file mode 100644index 000000000..0d73782d0--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/_sql_graph_records.py@@ -0,0 +1,127 @@+"""Graph-records delegations for :class:`SqlIndexStore`.++graph_nodes / graph_edges / external_systems / wiki_symbols — each method+delegates to :mod:`crud`. Split out to keep store files under 400 lines.+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession++from .. import crud+from .._interfaces._graph_records import GraphRecordsIndexStore+from ..models import ExternalSystem, GraphEdge, GraphNode+++class _SqlGraphRecordsMixin(GraphRecordsIndexStore):+ """Concrete delegations for the graph-records IndexStore surface."""++ _session: AsyncSession++ async def batch_upsert_graph_nodes(+ self, repository_id: str, nodes: list[dict]+ ) -> None:+ await crud.batch_upsert_graph_nodes(self._session, repository_id, nodes)++ async def batch_upsert_graph_edges(+ self, repository_id: str, edges: list[dict]+ ) -> None:+ await crud.batch_upsert_graph_edges(self._session, repository_id, edges)++ async def get_graph_node(+ self, repository_id: str, node_id: str+ ) -> GraphNode | None:+ return await crud.get_graph_node(self._session, repository_id, node_id)++ async def get_graph_edges_for_node(+ self,+ repository_id: str,+ node_id: str,+ *,+ direction: str = "both",+ edge_types: list[str] | None = None,+ limit: int = 50,+ ) -> list[GraphEdge]:+ return await crud.get_graph_edges_for_node(+ self._session,+ repository_id,+ node_id,+ direction=direction,+ edge_types=edge_types,+ limit=limit,+ )++ async def get_graph_nodes_by_ids(+ self, repository_id: str, node_ids: list[str]+ ) -> dict[str, GraphNode]:+ return await crud.get_graph_nodes_by_ids(+ self._session, repository_id, node_ids+ )++ async def get_all_file_metrics(self, repository_id: str) -> list[GraphNode]:+ return await crud.get_all_file_metrics(self._session, repository_id)++ async def get_community_members(+ self,+ repository_id: str,+ community_id: int,+ *,+ node_type: str = "file",+ limit: int = 50,+ ) -> list[GraphNode]:+ return await crud.get_community_members(+ self._session,+ repository_id,+ community_id,+ node_type=node_type,+ limit=limit,+ )++ async def get_cross_community_edges(+ self, repository_id: str, community_id: int+ ) -> list[dict]:+ return await crud.get_cross_community_edges(+ self._session, repository_id, community_id+ )++ async def get_top_entry_points(+ self,+ repository_id: str,+ *,+ min_score: float = 0.3,+ limit: int = 20,+ ) -> list[GraphNode]:+ return await crud.get_top_entry_points(+ self._session, repository_id, min_score=min_score, limit=limit+ )++ async def get_node_degree_counts(+ self, repository_id: str, node_id: str+ ) -> dict[str, int]:+ return await crud.get_node_degree_counts(+ self._session, repository_id, node_id+ )++ async def bulk_upsert_external_systems(+ self, repository_id: str, systems: list[dict]+ ) -> dict[tuple[str, str], int]:+ return await crud.bulk_upsert_external_systems(+ self._session, repository_id, systems+ )++ async def link_graph_nodes_to_external_systems(+ self, repository_id: str, name_to_id: dict[str, int]+ ) -> int:+ return await crud.link_graph_nodes_to_external_systems(+ self._session, repository_id, name_to_id+ )++ async def list_external_systems(+ self, repository_id: str+ ) -> list[ExternalSystem]:+ return await crud.list_external_systems(self._session, repository_id)++ async def batch_upsert_symbols(+ self, repository_id: str, symbols: list+ ) -> None:+ await crud.batch_upsert_symbols(self._session, repository_id, symbols)diff --git a/packages/core/src/repowise/core/persistence/stores/_sql_meta.py b/packages/core/src/repowise/core/persistence/stores/_sql_meta.pynew file mode 100644index 000000000..551cf2784--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/_sql_meta.py@@ -0,0 +1,217 @@+"""Meta-domain delegations for :class:`SqlIndexStore`.++Each method here is a one-to-one delegation to :mod:`crud`. Split out from+``sql_index_store.py`` to keep every store file under 400 lines.+"""++from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession++from .. import crud+from .._interfaces._meta import MetaIndexStore+from ..models import (+ ChatMessage,+ Conversation,+ GenerationJob,+ Page,+ PageVersion,+ Repository,+ WebhookEvent,+)+++class _SqlMetaMixin(MetaIndexStore):+ """Concrete delegations for the meta IndexStore surface."""++ _session: AsyncSession++ async def upsert_repository(+ self,+ *,+ name: str,+ local_path: str,+ url: str = "",+ default_branch: str = "main",+ settings: dict | None = None,+ ) -> Repository:+ return await crud.upsert_repository(+ self._session,+ name=name,+ local_path=local_path,+ url=url,+ default_branch=default_branch,+ settings=settings,+ )++ async def get_repository(self, repo_id: str) -> Repository | None:+ return await crud.get_repository(self._session, repo_id)++ async def get_repository_by_path(self, local_path: str) -> Repository | None:+ return await crud.get_repository_by_path(self._session, local_path)++ async def delete_repository(self, repo_id: str) -> bool:+ return await crud.delete_repository(self._session, repo_id)++ async def list_page_ids(self, repository_id: str) -> list[str]:+ return await crud.list_page_ids(self._session, repository_id)++ async def upsert_generation_job(+ self,+ *,+ repository_id: str,+ status: str = "pending",+ provider_name: str = "",+ model_name: str = "",+ total_pages: int = 0,+ config: dict | None = None,+ job_id: str | None = None,+ ) -> GenerationJob:+ return await crud.upsert_generation_job(+ self._session,+ repository_id=repository_id,+ status=status,+ provider_name=provider_name,+ model_name=model_name,+ total_pages=total_pages,+ config=config,+ job_id=job_id,+ )++ async def get_generation_job(self, job_id: str) -> GenerationJob | None:+ return await crud.get_generation_job(self._session, job_id)++ async def update_job_status(+ self,+ job_id: str,+ status: str,+ *,+ completed_pages: int | None = None,+ failed_pages: int | None = None,+ current_level: int | None = None,+ total_pages: int | None = None,+ error_message: str | None = None,+ ) -> GenerationJob:+ return await crud.update_job_status(+ self._session,+ job_id,+ status,+ completed_pages=completed_pages,+ failed_pages=failed_pages,+ current_level=current_level,+ total_pages=total_pages,+ error_message=error_message,+ )++ async def upsert_page(self, **kwargs: Any) -> Page:+ return await crud.upsert_page(self._session, **kwargs)++ async def upsert_page_from_generated(+ self, generated_page: object, repository_id: str+ ) -> Page:+ return await crud.upsert_page_from_generated(+ self._session, generated_page, repository_id+ )++ async def get_page(self, page_id: str) -> Page | None:+ return await crud.get_page(self._session, page_id)++ async def list_pages(+ self,+ repository_id: str,+ *,+ page_type: str | None = None,+ limit: int = 100,+ offset: int = 0,+ sort_by: str = "updated_at",+ order: str = "desc",+ ) -> list[Page]:+ return await crud.list_pages(+ self._session,+ repository_id,+ page_type=page_type,+ limit=limit,+ offset=offset,+ sort_by=sort_by,+ order=order,+ )++ async def get_page_versions(+ self, page_id: str, *, limit: int = 50+ ) -> list[PageVersion]:+ return await crud.get_page_versions(self._session, page_id, limit=limit)++ async def get_stale_pages(self, repository_id: str) -> list[Page]:+ return await crud.get_stale_pages(self._session, repository_id)++ async def load_prior_pages(self, repository_id: str) -> dict[str, Any]:+ return await crud.load_prior_pages(self._session, repository_id)++ async def store_webhook_event(+ self,+ *,+ provider: str,+ event_type: str,+ payload: dict,+ repository_id: str | None = None,+ delivery_id: str = "",+ ) -> WebhookEvent:+ return await crud.store_webhook_event(+ self._session,+ provider=provider,+ event_type=event_type,+ payload=payload,+ repository_id=repository_id,+ delivery_id=delivery_id,+ )++ async def mark_webhook_processed(+ self, event_id: str, *, job_id: str | None = None+ ) -> None:+ await crud.mark_webhook_processed(self._session, event_id, job_id=job_id)++ async def create_conversation(+ self, *, repository_id: str, title: str = "New conversation"+ ) -> Conversation:+ return await crud.create_conversation(+ self._session, repository_id=repository_id, title=title+ )++ async def get_conversation(self, conversation_id: str) -> Conversation | None:+ return await crud.get_conversation(self._session, conversation_id)++ async def list_conversations(+ self, repository_id: str, *, limit: int = 50+ ) -> list[Conversation]:+ return await crud.list_conversations(self._session, repository_id, limit=limit)++ async def update_conversation_title(+ self, conversation_id: str, title: str+ ) -> Conversation | None:+ return await crud.update_conversation_title(+ self._session, conversation_id, title+ )++ async def delete_conversation(self, conversation_id: str) -> bool:+ return await crud.delete_conversation(self._session, conversation_id)++ async def touch_conversation(self, conversation_id: str) -> None:+ await crud.touch_conversation(self._session, conversation_id)++ async def create_chat_message(+ self, *, conversation_id: str, role: str, content: dict+ ) -> ChatMessage:+ return await crud.create_chat_message(+ self._session,+ conversation_id=conversation_id,+ role=role,+ content=content,+ )++ async def list_chat_messages(self, conversation_id: str) -> list[ChatMessage]:+ return await crud.list_chat_messages(self._session, conversation_id)++ async def count_chat_messages(self, conversation_id: str) -> int:+ return await crud.count_chat_messages(self._session, conversation_id)diff --git a/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py b/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.pynew file mode 100644index 000000000..7bf6f7517--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/in_process_graph_store.py@@ -0,0 +1,180 @@+"""InProcessGraphStore — default :class:`GraphStore` implementation.++Wraps a :class:`networkx.DiGraph` and computes metrics with NetworkX+algorithms. This matches what the ingestion pipeline does today via+:class:`repowise.core.ingestion.graph.GraphBuilder`; the GraphBuilder+continues to be the entry point for the file-aware build logic+(import resolution, heritage, calls), and an ``InProcessGraphStore``+can be constructed from a finished builder to expose its graph through+the pluggable contract::++ builder = GraphBuilder(repo_path)+ for parsed in parsed_files:+ builder.add_file(parsed)+ builder.build()+ store = InProcessGraphStore.from_graph(builder._graph)++A future phase replaces this with a SQL-backed materialised view so the+in-memory graph can be dropped after build; that work fits underneath+the same ABC by swapping the implementation.+"""++from __future__ import annotations++from typing import Any++import networkx as nx++from .._interfaces.graph_store import GraphStore+++class InProcessGraphStore(GraphStore):+ """In-memory :class:`GraphStore` backed by a NetworkX DiGraph."""++ def __init__(self, graph: nx.DiGraph | None = None) -> None:+ self._graph: nx.DiGraph = graph if graph is not None else nx.DiGraph()+ self._built = False+ self._pagerank_cache: dict[str, float] | None = None+ self._betweenness_cache: dict[str, float] | None = None+ self._communities_cache: dict[str, int] | None = None++ @classmethod+ def from_graph(cls, graph: nx.DiGraph) -> InProcessGraphStore:+ """Adopt an existing DiGraph (e.g. one produced by ``GraphBuilder``)."""+ return cls(graph)++ @property+ def graph(self) -> nx.DiGraph:+ """Expose the underlying graph for callers that need NetworkX APIs."""+ return self._graph++ # ------------------------------------------------------------------+ # Mutation+ # ------------------------------------------------------------------++ def add_node(self, node_id: str, **attrs: Any) -> None:+ self._graph.add_node(node_id, **attrs)+ self._invalidate()++ def add_edge(self, source: str, target: str, **attrs: Any) -> None:+ self._graph.add_edge(source, target, **attrs)+ self._invalidate()++ def has_node(self, node_id: str) -> bool:+ return node_id in self._graph++ def has_edge(self, source: str, target: str) -> bool:+ return self._graph.has_edge(source, target)++ def remove_node(self, node_id: str) -> None:+ if node_id in self._graph:+ self._graph.remove_node(node_id)+ self._invalidate()++ def remove_edge(self, source: str, target: str) -> None:+ if self._graph.has_edge(source, target):+ self._graph.remove_edge(source, target)+ self._invalidate()++ # ------------------------------------------------------------------+ # Finalisation+ # ------------------------------------------------------------------++ def build(self) -> None:+ self._built = True+ # Metric caches are filled lazily on first read.++ # ------------------------------------------------------------------+ # Inspection+ # ------------------------------------------------------------------++ def node_count(self) -> int:+ return self._graph.number_of_nodes()++ def edge_count(self) -> int:+ return self._graph.number_of_edges()++ def get_node_attrs(self, node_id: str) -> dict[str, Any] | None:+ if node_id not in self._graph:+ return None+ return dict(self._graph.nodes[node_id])++ def neighbors(self, node_id: str, *, direction: str = "out") -> list[str]:+ if node_id not in self._graph:+ return []+ if direction == "out":+ return list(self._graph.successors(node_id))+ if direction == "in":+ return list(self._graph.predecessors(node_id))+ if direction == "both":+ return list(+ set(self._graph.successors(node_id))+ | set(self._graph.predecessors(node_id))+ )+ raise ValueError(f"direction must be 'out' | 'in' | 'both', got {direction!r}")++ # ------------------------------------------------------------------+ # Metrics+ # ------------------------------------------------------------------++ def pagerank(self) -> dict[str, float]:+ if self._pagerank_cache is None:+ file_subgraph = self._file_subgraph()+ if file_subgraph.number_of_nodes() == 0:+ self._pagerank_cache = {}+ else:+ self._pagerank_cache = nx.pagerank(file_subgraph)+ return dict(self._pagerank_cache)++ def betweenness_centrality(self) -> dict[str, float]:+ if self._betweenness_cache is None:+ file_subgraph = self._file_subgraph()+ if file_subgraph.number_of_nodes() == 0:+ self._betweenness_cache = {}+ else:+ self._betweenness_cache = nx.betweenness_centrality(file_subgraph)+ return dict(self._betweenness_cache)++ def communities(self) -> dict[str, int]:+ if self._communities_cache is None:+ file_subgraph = self._file_subgraph().to_undirected()+ mapping: dict[str, int] = {}+ if file_subgraph.number_of_nodes():+ # Use NetworkX's greedy modularity communities — deterministic,+ # no external dependency, fine quality at this graph size.+ from networkx.algorithms.community import greedy_modularity_communities++ for cid, members in enumerate(+ greedy_modularity_communities(file_subgraph)+ ):+ for node in members:+ mapping[node] = cid+ self._communities_cache = mapping+ return dict(self._communities_cache)++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ def _invalidate(self) -> None:+ self._built = False+ self._pagerank_cache = None+ self._betweenness_cache = None+ self._communities_cache = None++ def _file_subgraph(self) -> nx.DiGraph:+ """Return the subgraph restricted to file-level nodes.++ Matches the convention used by :class:`GraphBuilder` — symbol+ nodes are excluded from file-centric metrics so PageRank reflects+ module-level importance rather than per-function frequency.+ """+ file_nodes = [+ n+ for n, attrs in self._graph.nodes(data=True)+ if attrs.get("node_type", "file") == "file"+ ]+ return self._graph.subgraph(file_nodes).copy()+++__all__ = ["InProcessGraphStore"]diff --git a/packages/core/src/repowise/core/persistence/stores/sql_index_store.py b/packages/core/src/repowise/core/persistence/stores/sql_index_store.pynew file mode 100644index 000000000..b287c6458--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/sql_index_store.py@@ -0,0 +1,42 @@+"""SqlIndexStore — default :class:`IndexStore` implementation.++Binds a single :class:`AsyncSession` and delegates every method to the+corresponding function in :mod:`repowise.core.persistence.crud`. There is+no behaviour change relative to calling ``crud.foo(session, ...)``+directly; this class exists so callers can depend on the ABC rather than+on a module-level function namespace, which is what makes alternate+implementations (e.g. dialect-specific or scoped variants) possible.++The class body is intentionally thin — the delegations live in three+domain mixins (``_sql_meta``, ``_sql_analysis``, ``_sql_graph_records``)+so no single file exceeds the project line cap.+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession++from .._interfaces.index_store import IndexStore+from ._sql_analysis import _SqlAnalysisMixin+from ._sql_graph_records import _SqlGraphRecordsMixin+from ._sql_meta import _SqlMetaMixin+++class SqlIndexStore(+ _SqlMetaMixin,+ _SqlAnalysisMixin,+ _SqlGraphRecordsMixin,+ IndexStore,+):+ """:class:`IndexStore` backed by :mod:`crud` + an :class:`AsyncSession`."""++ def __init__(self, session: AsyncSession) -> None:+ self._session = session++ @property+ def session(self) -> AsyncSession:+ """Expose the bound session for callers that need raw SQL access."""+ return self._session+++__all__ = ["SqlIndexStore"]diff --git a/packages/core/src/repowise/core/persistence/stores/sql_job_store.py b/packages/core/src/repowise/core/persistence/stores/sql_job_store.pynew file mode 100644index 000000000..de5021274--- /dev/null+++ b/packages/core/src/repowise/core/persistence/stores/sql_job_store.py@@ -0,0 +1,132 @@+"""SqlJobStore — default :class:`JobStore` implementation.++Backed by the ``pipeline_jobs`` table introduced in Alembic revision+``0020``. Binds a single :class:`AsyncSession`; the caller owns commit /+rollback (matching the pattern used by :class:`SqlIndexStore`).+"""++from __future__ import annotations++import json+from uuid import uuid4++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from .._interfaces.job_store import JobRecord, JobState, JobStore+from ..models import PipelineJob, _now_utc+++def _to_record(row: PipelineJob) -> JobRecord:+ """Project an ORM row to the immutable :class:`JobRecord` dataclass."""+ try:+ meta = json.loads(row.metadata_json) if row.metadata_json else {}+ except json.JSONDecodeError:+ meta = {}+ return JobRecord(+ id=row.id,+ repository_id=row.repository_id,+ phase=row.phase,+ state=JobState(row.state),+ cursor=row.cursor,+ started_at=row.started_at,+ updated_at=row.updated_at,+ error=row.error,+ metadata=meta,+ )+++class SqlJobStore(JobStore):+ """:class:`JobStore` backed by the ``pipeline_jobs`` table."""++ def __init__(self, session: AsyncSession) -> None:+ self._session = session++ async def create_job(+ self,+ *,+ repository_id: str,+ phase: str,+ metadata: dict | None = None,+ ) -> JobRecord:+ row = PipelineJob(+ id=uuid4().hex,+ repository_id=repository_id,+ phase=phase,+ state=JobState.PENDING.value,+ cursor=None,+ error=None,+ metadata_json=json.dumps(metadata or {}),+ )+ self._session.add(row)+ await self._session.flush()+ return _to_record(row)++ async def get_job(self, job_id: str) -> JobRecord | None:+ row = await self._session.get(PipelineJob, job_id)+ return _to_record(row) if row is not None else None++ async def update_state(+ self,+ job_id: str,+ state: JobState,+ *,+ cursor: str | None = None,+ error: str | None = None,+ ) -> JobRecord:+ row = await self._session.get(PipelineJob, job_id)+ if row is None:+ raise LookupError(f"No PipelineJob with id={job_id!r}")+ row.state = state.value+ if cursor is not None:+ row.cursor = cursor+ if error is not None:+ row.error = error+ row.updated_at = _now_utc()+ await self._session.flush()+ return _to_record(row)++ async def checkpoint(self, job_id: str, cursor: str) -> JobRecord:+ row = await self._session.get(PipelineJob, job_id)+ if row is None:+ raise LookupError(f"No PipelineJob with id={job_id!r}")+ row.cursor = cursor+ row.updated_at = _now_utc()+ await self._session.flush()+ return _to_record(row)++ async def find_resumable(+ self, *, repository_id: str | None = None+ ) -> list[JobRecord]:+ q = select(PipelineJob).where(+ PipelineJob.state.in_(+ [JobState.PENDING.value, JobState.RUNNING.value]+ )+ )+ if repository_id is not None:+ q = q.where(PipelineJob.repository_id == repository_id)+ q = q.order_by(PipelineJob.started_at.asc())+ result = await self._session.execute(q)+ return [_to_record(row) for row in result.scalars().all()]++ async def list_jobs(+ self,+ *,+ repository_id: str | None = None,+ phase: str | None = None,+ state: JobState | None = None,+ limit: int = 100,+ ) -> list[JobRecord]:+ q = select(PipelineJob)+ if repository_id is not None:+ q = q.where(PipelineJob.repository_id == repository_id)+ if phase is not None:+ q = q.where(PipelineJob.phase == phase)+ if state is not None:+ q = q.where(PipelineJob.state == state.value)+ q = q.order_by(PipelineJob.started_at.desc()).limit(limit)+ result = await self._session.execute(q)+ return [_to_record(row) for row in result.scalars().all()]+++__all__ = ["SqlJobStore"]diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 34c0894e4..564dea1d9 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -25,6 +25,7 @@ from typing import Anyimport structlogfrom repowise.core.pipeline.progress import ProgressCallback+from repowise.core.registry import HookProgressCallbacklogger = structlog.get_logger(__name__)@@ -265,6 +266,10 @@ async def run_pipeline(commit_depth = max(1, min(commit_depth, 5000))+ # Wrap the incoming progress callback so registered pipeline hooks fire+ # around each phase transition. Zero-op when no hooks are registered.+ progress = HookProgressCallback(progress)+# Attach cost tracker to provider if suppliedif cost_tracker is not None and llm_client is not None and hasattr(llm_client, "_cost_tracker"):llm_client._cost_tracker = cost_trackerdiff --git a/packages/core/src/repowise/core/registry/README.md b/packages/core/src/repowise/core/registry/README.mdnew file mode 100644index 000000000..48da71dc3--- /dev/null+++ b/packages/core/src/repowise/core/registry/README.md@@ -0,0 +1,66 @@+# core/registry++Three small process-wide registries that let third-party packages extend+repowise without forking the source tree. Each registry is the seam+documented in [`docs/architecture/pluggable-storage.md`](../../../../../../docs/architecture/pluggable-storage.md).++## Purpose++The OSS CLI, MCP server, and pipeline orchestrator each hard-coded their+extension points before this subpackage existed. Plugins that wanted to+add a CLI command, MCP tool, or phase hook had to monkey-patch a+module-level singleton and hope their import landed at the right time.++These registries invert that dependency. Each command / tool / hook+registers itself on import; the host (CLI entry point, MCP server boot,+pipeline orchestrator) calls a single `apply` / `fire` method when it+needs the collected entries.++## Public API++| Module | Default instance | Purpose |+|---|---|---|+| `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 |++The convenience helpers `register_command(...)` and `register_hook(...)`+operate on the default singletons. Tests construct their own+`CLIRegistry()` / `MCPToolRegistry()` / `PipelineHookRegistry()` for+isolation.++## Internal layout++```+registry/+ __init__.py # re-exports+ cli_registry.py # CLIRegistry + cli_registry singleton+ mcp_tool_registry.py # MCPToolRegistry + mcp_tool_registry singleton+ pipeline_hooks.py # PipelineHookRegistry + HookProgressCallback + singleton+ README.md+```++Every file is under 200 lines; no module-level state beyond the three+singletons.++## Extension points++- **Adding a CLI command:** import the command object, then+ `register_command(my_command)`. Optional `parent=` attaches to a+ subgroup. Order of registration is preserved.+- **Adding an MCP tool:** decorate the function with+ `@mcp_tool_registry.register()` or+ `@mcp_tool_registry.register` (bare form). The host server calls+ `mcp_tool_registry.apply(mcp)` once at boot.+- **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.++## Tests++- `tests/unit/registry/test_cli_registry.py`+- `tests/unit/registry/test_mcp_tool_registry.py`+- `tests/unit/registry/test_pipeline_hooks.py`++Each test uses an isolated registry instance to avoid coupling across+tests.diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.pynew file mode 100644index 000000000..8049ff7cb--- /dev/null+++ b/packages/core/src/repowise/core/registry/__init__.py@@ -0,0 +1,42 @@+"""Capability registries — extension seams for OSS plugin authors.++Three small registries let third-party packages extend repowise without+forking the source tree:++- :mod:`cli_registry` collects Click commands and groups, then attaches+ them to the top-level CLI on startup.+- :mod:`mcp_tool_registry` collects MCP tool functions and registers+ them with a :class:`FastMCP` server at boot.+- :mod:`pipeline_hooks` lets plugins observe (and eventually mutate)+ pipeline phase transitions.++Each registry is a small module-level singleton plus a ``CLIRegistry`` /+``MCPToolRegistry`` / ``PipelineHookRegistry`` class so callers that+prefer dependency injection (tests, multi-server setups) can construct+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 .mcp_tool_registry import MCPToolRegistry, mcp_tool_registry+from .pipeline_hooks import (+ HookPhase,+ HookProgressCallback,+ PipelineHookRegistry,+ pipeline_hooks,+ register_hook,+)++__all__ = [+ "CLIRegistry",+ "HookPhase",+ "HookProgressCallback",+ "MCPToolRegistry",+ "PipelineHookRegistry",+ "cli_registry",+ "mcp_tool_registry",+ "pipeline_hooks",+ "register_command",+ "register_hook",+]diff --git a/packages/core/src/repowise/core/registry/cli_registry.py b/packages/core/src/repowise/core/registry/cli_registry.pynew file mode 100644index 000000000..eab5ca66d--- /dev/null+++ b/packages/core/src/repowise/core/registry/cli_registry.py@@ -0,0 +1,92 @@+"""CLI registry — collect commands, apply them to the root Click group.++The OSS CLI used to hard-code one ``cli.add_command(...)`` call per+command at the bottom of :mod:`repowise.cli.main`. That works, but a+third-party package that wants to add a subcommand has to monkey-patch+the root group at import time and hope its import runs early enough.++This registry is a thin indirection. Each command (OSS or third-party)+registers itself once on import; the CLI entry point calls+:meth:`CLIRegistry.apply` exactly once, after all commands have had a+chance to register, and the resulting Click group looks identical to+the hard-coded version.++Usage::++ # OSS or plugin side+ from repowise.core.registry import register_command+ register_command(my_command)+ register_command(my_subcommand, parent=some_group)++ # CLI entry point+ from repowise.core.registry import cli_registry+ cli_registry.apply(cli)++Registration order is preserved, matching the hard-coded behavior.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++if TYPE_CHECKING:+ import click+++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._applied_to: list[int] = []++ def register(+ self,+ command: click.BaseCommand,+ *,+ parent: click.BaseCommand | None = None,+ ) -> None:+ """Schedule *command* for attachment to *parent* (default: root)."""+ self._entries.append((parent, command))++ def apply(self, root: click.BaseCommand) -> click.BaseCommand:+ """Attach every registered command. Returns *root* for chaining.++ Idempotent per *root* — calling ``apply`` twice with the same+ Click group is a no-op. Passing a different group registers+ every entry against that group too (useful for tests that build+ an isolated root).+ """+ root_id = id(root)+ if root_id in self._applied_to:+ return root+ for parent, command in self._entries:+ target = parent if parent is not None else root+ target.add_command(command) # type: ignore[attr-defined]+ self._applied_to.append(root_id)+ return root++ def reset(self) -> None:+ """Drop every registered entry. Used by tests."""+ self._entries.clear()+ self._applied_to.clear()++ def commands(self) -> list[click.BaseCommand]:+ """Return every registered command. Used by tests."""+ return [cmd for _, cmd in self._entries]+++cli_registry = CLIRegistry()+"""Process-wide default registry used by the OSS CLI."""+++def register_command(+ command: click.BaseCommand,+ *,+ parent: click.BaseCommand | None = None,+) -> None:+ """Module-level convenience over :meth:`CLIRegistry.register`."""+ cli_registry.register(command, parent=parent)+++__all__ = ["CLIRegistry", "cli_registry", "register_command"]diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.pynew file mode 100644index 000000000..be03e2d5c--- /dev/null+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py@@ -0,0 +1,104 @@+"""MCP tool registry — collect tool functions, register them with FastMCP.++The OSS MCP tools previously decorated themselves with ``@mcp.tool()``+directly, which means every tool module had a hard import dependency on+the module-level ``mcp`` singleton in+:mod:`repowise.server.mcp_server._server`. A third-party package adding+its own tools either had to monkey-patch that singleton or replicate the+import wiring.++This registry inverts the dependency. Each tool decorates itself with+:meth:`MCPToolRegistry.register`, which stores the function without+binding it to any server instance. When the server boots, it calls+:meth:`apply` once and the registry attaches every collected tool to the+:class:`FastMCP` instance — same effect as the old decorator, but the+binding now happens at the call site instead of at import time.++Usage::++ # Tool side+ from repowise.core.registry import mcp_tool_registry++ @mcp_tool_registry.register()+ async def get_thing(arg: str) -> dict:+ ...++ # Server side+ from repowise.core.registry import mcp_tool_registry+ mcp = FastMCP("repowise")+ mcp_tool_registry.apply(mcp)+"""++from __future__ import annotations++from collections.abc import Callable+from typing import Any+++class MCPToolRegistry:+ """Holds tool callables until :meth:`apply` attaches them to a server."""++ def __init__(self) -> None:+ self._tools: list[Callable[..., Any]] = []+ self._applied_to: list[Any] = []++ def register(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]] | Callable[..., Any]:+ """Decorator that schedules a function for FastMCP registration.++ Supports both decorator forms — bare ``@register`` and+ ``@register()`` — so call sites read naturally. Keyword arguments+ are currently ignored; they exist as a forward-compat hook for+ future ``description=`` / ``name=`` overrides.+ """+ # Bare-decorator form: @mcp_tool_registry.register+ if len(args) == 1 and callable(args[0]) and not kwargs:+ fn = args[0]+ self._tools.append(fn)+ return fn++ # Called form: @mcp_tool_registry.register()+ def _decorator(fn: Callable[..., Any]) -> Callable[..., Any]:+ self._tools.append(fn)+ return fn++ return _decorator++ # FastMCP-style alias so existing tool modules can swap+ # ``from ._server import mcp`` to+ # ``from repowise.core.registry import mcp_tool_registry as mcp``+ # with no other changes — the ``@mcp.tool()`` call still works.+ tool = register++ def apply(self, mcp: Any) -> None:+ """Attach every registered tool to *mcp* via ``mcp.tool()``.++ Calling :meth:`apply` multiple times with the same server is a+ no-op on subsequent calls; calling it with a different server+ registers everything against that server too (useful for tests+ that spin up isolated :class:`FastMCP` instances).+ """+ if mcp in self._applied_to:+ return+ for fn in self._tools:+ mcp.tool()(fn)+ self._applied_to.append(mcp)++ def reset(self) -> None:+ """Drop every registered tool. Used by tests."""+ self._tools.clear()+ self._applied_to.clear()++ def tools(self) -> list[Callable[..., Any]]:+ """Return every registered tool function. Used by tests."""+ return list(self._tools)+++mcp_tool_registry = MCPToolRegistry()+"""Process-wide default registry used by the OSS MCP server."""+++__all__ = ["MCPToolRegistry", "mcp_tool_registry"]diff --git a/packages/core/src/repowise/core/registry/pipeline_hooks.py b/packages/core/src/repowise/core/registry/pipeline_hooks.pynew file mode 100644index 000000000..41173c014--- /dev/null+++ b/packages/core/src/repowise/core/registry/pipeline_hooks.py@@ -0,0 +1,164 @@+"""Pipeline hooks — observe pipeline phase transitions from a plugin.++The orchestrator already announces every phase transition by calling+``progress.on_phase_start(phase)`` and ``progress.on_phase_done(phase)``+on the active :class:`ProgressCallback`. That single chokepoint is the+natural place to fire third-party callbacks: a hook registered against+phase ``parse`` runs around the parse phase no matter which CLI / Modal /+test entry point launched the pipeline.++:class:`HookProgressCallback` wraps an existing :class:`ProgressCallback`+(or ``None``) and fires registered hooks around each transition while+forwarding every other method to the inner callback unchanged. The+orchestrator only needs to wrap its incoming progress callback in+``HookProgressCallback(progress, pipeline_hooks)`` — a zero-op when no+hooks are registered.++Usage::++ from repowise.core.registry import pipeline_hooks, register_hook++ def warm_caches(phase: str) -> None:+ ...++ register_hook("graph", warm_caches, when="pre")+ register_hook("graph", lambda phase: ..., when="post")++Hook callbacks accept the phase name as their only positional argument.+Exceptions raised inside a hook are caught and logged so a broken plugin+cannot derail the pipeline.+"""++from __future__ import annotations++import enum+from collections.abc import Callable+from typing import Any++import structlog++log = structlog.get_logger(__name__)++HookCallback = Callable[[str], None]+++class HookPhase(enum.StrEnum):+ """When a hook should fire relative to the wrapped phase."""++ PRE = "pre"+ POST = "post"+++class PipelineHookRegistry:+ """Collects callbacks keyed on ``(phase, HookPhase)``."""++ def __init__(self) -> None:+ self._hooks: dict[tuple[str, HookPhase], list[HookCallback]] = {}++ def register(+ self,+ phase: str,+ callback: HookCallback,+ *,+ when: HookPhase | str = HookPhase.POST,+ ) -> None:+ """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)++ def fire(self, phase: str, when: HookPhase) -> None:+ """Invoke every registered hook for ``(phase, when)``.++ Exceptions from individual callbacks are logged and swallowed —+ one broken plugin must not derail the pipeline.+ """+ for cb in self._hooks.get((phase, when), ()):+ 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),+ )++ def reset(self) -> None:+ """Drop every registered hook. Used by tests."""+ self._hooks.clear()++ def hooks_for(self, phase: str, when: HookPhase) -> list[HookCallback]:+ """Return registered hooks for ``(phase, when)``. Used by tests."""+ return list(self._hooks.get((phase, when), ()))+++pipeline_hooks = PipelineHookRegistry()+"""Process-wide default registry used by the orchestrator."""+++def register_hook(+ phase: str,+ callback: HookCallback,+ *,+ when: HookPhase | str = HookPhase.POST,+) -> None:+ """Module-level convenience over :meth:`PipelineHookRegistry.register`."""+ pipeline_hooks.register(phase, callback, when=when)+++class HookProgressCallback:+ """Wraps a :class:`ProgressCallback`, firing hooks around transitions.++ Forwards :meth:`on_phase_start` and :meth:`on_phase_done` to the+ inner callback (when one is supplied) and fires the registered+ pre/post hooks around them. ``on_item_done`` and ``on_message`` (plus+ any other attributes a custom callback exposes) are forwarded as-is.+ """++ def __init__(+ self,+ inner: Any | None,+ registry: PipelineHookRegistry | None = None,+ ) -> None:+ self._inner = inner+ self._registry = registry if registry is not None else pipeline_hooks++ def on_phase_start(self, phase: str, total: int | None = None) -> None:+ self._registry.fire(phase, HookPhase.PRE)+ if self._inner is not None:+ self._inner.on_phase_start(phase, total)++ def on_phase_done(self, phase: str) -> None:+ if self._inner is not None:+ done = getattr(self._inner, "on_phase_done", None)+ if done is not None:+ done(phase)+ self._registry.fire(phase, HookPhase.POST)++ def __getattr__(self, name: str) -> Any:+ # Forward anything else (on_item_done, on_message, custom attrs)+ # to the wrapped callback so existing implementations keep working.+ # When no inner callback was supplied, return a no-op for the well-+ # known ProgressCallback methods so the orchestrator can treat the+ # wrapper as a real callback unconditionally.+ if self._inner is None:+ if name.startswith("on_"):+ return _noop_method+ raise AttributeError(name)+ return getattr(self._inner, name)+++def _noop_method(*_args: Any, **_kwargs: Any) -> None:+ """Default no-op used when ``HookProgressCallback`` wraps a ``None``+ inner callback and code calls a forwarded method on it."""+++__all__ = [+ "HookCallback",+ "HookPhase",+ "HookProgressCallback",+ "PipelineHookRegistry",+ "pipeline_hooks",+ "register_hook",+]diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex c0fcfba7a..847684581 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -40,6 +40,13 @@ from repowise.server.mcp_server.tool_search import search_codebasefrom repowise.server.mcp_server.tool_symbol import get_symbolfrom repowise.server.mcp_server.tool_why import get_why+# Attach every tool that registered itself through the shared registry to+# the FastMCP instance. Idempotent per server, so a second call (e.g. when+# tests build an isolated mcp) is a no-op against the original mcp.+from repowise.core.registry import mcp_tool_registry as _mcp_tool_registry # noqa: E402++_mcp_tool_registry.apply(mcp)+# ---------------------------------------------------------------------------# Backward-compatible access to _state globals.#diff --git a/packages/server/src/repowise/server/mcp_server/tool_annotate.py b/packages/server/src/repowise/server/mcp_server/tool_annotate.pyindex da734e3f5..654063527 100644--- a/packages/server/src/repowise/server/mcp_server/tool_annotate.py+++ b/packages/server/src/repowise/server/mcp_server/tool_annotate.py@@ -1,4 +1,4 @@-"""``annotate_file`` — attach human notes to a wiki page.+"""``annotate_file`` — attach human notes to a wiki page.Notes survive LLM-driven re-generation and appear in ``get_context`` responses."""@@ -15,7 +15,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer.pyindex 1c48918c9..b8a640bfb 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer.py@@ -1,4 +1,4 @@-"""MCP Tool: get_answer — RAG-style synthesis over the wiki layer.+"""MCP Tool: get_answer — RAG-style synthesis over the wiki layer.Single-call retrieval + LLM synthesis. Replaces the agent's multi-turnsearch → context → read loop with one tool call that returns:@@ -59,7 +59,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import answer_hint as _answer_hintfrom repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp# How many top retrieval hits to enrich with WikiSymbol context. Enriching# every hit produces large responses that bloat the cached prompt prefix ondiff --git a/packages/server/src/repowise/server/mcp_server/tool_callers.py b/packages/server/src/repowise/server/mcp_server/tool_callers.pyindex 1f79ff721..c069af927 100644--- a/packages/server/src/repowise/server/mcp_server/tool_callers.py+++ b/packages/server/src/repowise/server/mcp_server/tool_callers.py@@ -1,4 +1,4 @@-"""MCP Tool: get_callers_callees — find who calls a symbol and what it calls.+"""MCP Tool: get_callers_callees — find who calls a symbol and what it calls.Provides symbol-level call graph navigation for AI coding assistants.Supports call edges, heritage edges (extends/implements), and any other@@ -31,7 +31,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp_DEFAULT_EDGE_TYPES = ["calls"]diff --git a/packages/server/src/repowise/server/mcp_server/tool_community.py b/packages/server/src/repowise/server/mcp_server/tool_community.pyindex 4934a90d6..6b713b733 100644--- a/packages/server/src/repowise/server/mcp_server/tool_community.py+++ b/packages/server/src/repowise/server/mcp_server/tool_community.py@@ -1,4 +1,4 @@-"""MCP Tool: get_community — explore architectural communities/clusters.+"""MCP Tool: get_community — explore architectural communities/clusters.Returns the community a file belongs to, its members, cohesion score,label, and neighboring communities. Helps Claude Code understand module@@ -24,7 +24,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcpdef _parse_community_meta(node: GraphNode) -> dict[str, Any]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_context.py b/packages/server/src/repowise/server/mcp_server/tool_context.pyindex 059eb03ac..b3d010187 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context.py@@ -1,4 +1,4 @@-"""MCP Tool: get_context — relationships and triage signals for files / modules / symbols.+"""MCP Tool: get_context — relationships and triage signals for files / modules / symbols.Workhorse for "what is this and what touches it" questions. Returns a triagecard by default (title, summary, signatures, hotspot bit, top callers, pointers@@ -77,7 +77,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import context_hint as _context_hint-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp# Minimum confidence for call edges to filter false positives_MIN_CALL_CONFIDENCE = 0.7diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex 8fe35d762..709cc00ee 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -1,4 +1,4 @@-"""MCP Tool 7: get_dead_code — tiered refactor plan for unused code."""+"""MCP Tool 7: get_dead_code — tiered refactor plan for unused code."""from __future__ import annotations@@ -20,7 +20,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()diff --git a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py b/packages/server/src/repowise/server/mcp_server/tool_decision_records.pyindex fbaada7dd..3a9c83bba 100644--- a/packages/server/src/repowise/server/mcp_server/tool_decision_records.py+++ b/packages/server/src/repowise/server/mcp_server/tool_decision_records.py@@ -1,4 +1,4 @@-"""MCP Tool 9: update_decision_records — CRUD operations on architectural decision records."""+"""MCP Tool 9: update_decision_records — CRUD operations on architectural decision records."""from __future__ import annotations@@ -13,7 +13,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp_VALID_ACTIONS = frozenset({"create", "update", "update_status", "delete", "list", "get"})diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex 1774bcbdd..c702fe8d6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -1,4 +1,4 @@-"""MCP Tool 6: get_dependency_path — dependency graph path finding."""+"""MCP Tool 6: get_dependency_path — dependency graph path finding."""from __future__ import annotations@@ -18,7 +18,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()diff --git a/packages/server/src/repowise/server/mcp_server/tool_diagram.py b/packages/server/src/repowise/server/mcp_server/tool_diagram.pyindex c9fe672ea..d30120eae 100644--- a/packages/server/src/repowise/server/mcp_server/tool_diagram.py+++ b/packages/server/src/repowise/server/mcp_server/tool_diagram.py@@ -1,4 +1,4 @@-"""MCP Tool 8: get_architecture_diagram — Mermaid diagram generation."""+"""MCP Tool 8: get_architecture_diagram — Mermaid diagram generation."""from __future__ import annotations@@ -18,7 +18,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,)-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcpdef _sanitize_mermaid_id(node_id: str) -> str:diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.pyindex e9f9905e1..039b46a6e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py@@ -1,4 +1,4 @@-"""MCP Tool: get_execution_flows — trace how the codebase executes.+"""MCP Tool: get_execution_flows — trace how the codebase executes.Hybrid approach: reads persisted entry-point scores from community_meta_json,then recomputes BFS call-path traces on demand from stored call edges. This@@ -29,7 +29,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex de7910811..e5bb89d0f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -1,4 +1,4 @@-"""MCP tool: get_health — code-health biomarkers and per-file scores."""+"""MCP tool: get_health — code-health biomarkers and per-file scores."""from __future__ import annotations@@ -18,7 +18,7 @@ from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import HealthFileMetric, HealthFindingfrom repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_contextfrom repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcpdef _serialize_finding(f: HealthFinding) -> dict[str, Any]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_metrics.py b/packages/server/src/repowise/server/mcp_server/tool_metrics.pyindex 1a8743b70..96babcc35 100644--- a/packages/server/src/repowise/server/mcp_server/tool_metrics.py+++ b/packages/server/src/repowise/server/mcp_server/tool_metrics.py@@ -1,4 +1,4 @@-"""MCP Tool: get_graph_metrics — importance metrics for a file or symbol.+"""MCP Tool: get_graph_metrics — importance metrics for a file or symbol.Returns PageRank, betweenness centrality, community info, degree counts,and percentile ranks. Helps Claude Code assess how central/important a@@ -24,7 +24,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcpdef _percentile_rank(value: float, all_values: list[float]) -> int:diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex edba58504..ad5daf4cb 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -1,4 +1,4 @@-"""MCP Tool 1: get_overview — repository architecture overview."""+"""MCP Tool 1: get_overview — repository architecture overview."""from __future__ import annotations@@ -26,7 +26,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp# ---------------------------------------------------------------------------diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex 75a7c1838..90cdafafc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -1,4 +1,4 @@-"""MCP Tool 3: get_risk — modification risk assessment."""+"""MCP Tool 3: get_risk — modification risk assessment."""from __future__ import annotations@@ -26,7 +26,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp_FIX_PATTERN = re.compile(r"\b(fix|bug|patch|hotfix|revert|regression|broken|crash|error)\b",diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex 16d2494ca..a2b56f749 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -1,4 +1,4 @@-"""MCP Tool 5: search_codebase — semantic search over the wiki."""+"""MCP Tool 5: search_codebase — semantic search over the wiki."""from __future__ import annotations@@ -20,7 +20,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp# Minimum relevance score below which results are dropped. Prevents# returning semantically unrelated pages when the corpus has no real match.diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 8e5a575f5..5afa0f85f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -1,4 +1,4 @@-"""MCP Tool: get_symbol — byte-precise source retrieval for a single symbol.+"""MCP Tool: get_symbol — byte-precise source retrieval for a single symbol.This is the structural counterpart to get_context. Where get_context returnsfile-level narrative (summary, symbol list, importers), get_symbol returns@@ -44,7 +44,7 @@ from repowise.server.mcp_server._helpers import ()from repowise.server.mcp_server._meta import build_meta as _build_metafrom repowise.server.mcp_server._meta import symbol_hint as _symbol_hint-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp_log = __import__("logging").getLogger("repowise.mcp.symbol")diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex dd53f094f..9efb5e551 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -1,4 +1,4 @@-"""MCP Tool 4: get_why — intent archaeology and decision search."""+"""MCP Tool 4: get_why — intent archaeology and decision search."""from __future__ import annotations@@ -25,7 +25,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta-from repowise.server.mcp_server._server import mcp+from repowise.core.registry import mcp_tool_registry as mcp@mcp.tool()diff --git a/tests/integration/persistence/__init__.py b/tests/integration/persistence/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/integration/persistence/test_sql_job_store_pg.py b/tests/integration/persistence/test_sql_job_store_pg.pynew file mode 100644index 000000000..367ca432a--- /dev/null+++ b/tests/integration/persistence/test_sql_job_store_pg.py@@ -0,0 +1,75 @@+"""SqlJobStore against a real PostgreSQL container.++Skipped automatically when ``testcontainers`` is not installed or Docker+is not running. The test exercises the same surface as the unit-level+contract suite but against the dialect that production deployments use.+"""++from __future__ import annotations++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++from repowise.core.persistence._interfaces import JobState+from repowise.core.persistence.database import init_db+from repowise.core.persistence.stores import SqlIndexStore, SqlJobStore++testcontainers = pytest.importorskip(+ "testcontainers.postgres",+ reason="testcontainers not installed",+)++[email protected](scope="module")+def postgres_container():+ try:+ with testcontainers.PostgresContainer("postgres:16-alpine") as pg:+ yield pg+ except Exception as exc: # pragma: no cover - skip when Docker missing+ pytest.skip(f"PostgreSQL container unavailable: {exc}")+++async def pg_session(postgres_container):+ raw_url = postgres_container.get_connection_url()+ # testcontainers returns psycopg2-style; rewrite for asyncpg.+ url = raw_url.replace("postgresql+psycopg2://", "postgresql+asyncpg://").replace(+ "postgresql://", "postgresql+asyncpg://"+ )+ engine = create_async_engine(url, echo=False)+ try:+ await init_db(engine)+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)+ async with factory() as session:+ yield session+ finally:+ await engine.dispose()+++async def test_sql_job_store_roundtrip_postgres(pg_session: AsyncSession):+ """Same contract as the SQLite unit test, but against Postgres."""+ idx = SqlIndexStore(pg_session)+ repo = await idx.upsert_repository(+ name="pg-test", local_path="/tmp/pg-test"+ )+ store = SqlJobStore(pg_session)++ job = await store.create_job(+ repository_id=repo.id, phase="graph", metadata={"k": 1}+ )+ assert job.state is JobState.PENDING++ running = await store.update_state(job.id, JobState.RUNNING)+ assert running.state is JobState.RUNNING++ cp = await store.checkpoint(job.id, "files/100")+ assert cp.cursor == "files/100"+ assert cp.state is JobState.RUNNING # checkpoint does not flip state++ resumable = await store.find_resumable(repository_id=repo.id)+ assert len(resumable) == 1 and resumable[0].id == job.id++ done = await store.update_state(job.id, JobState.COMPLETED)+ assert done.state is JobState.COMPLETED+ assert (await store.find_resumable(repository_id=repo.id)) == []diff --git a/tests/unit/persistence/test_interfaces_contract.py b/tests/unit/persistence/test_interfaces_contract.pynew file mode 100644index 000000000..8448df852--- /dev/null+++ b/tests/unit/persistence/test_interfaces_contract.py@@ -0,0 +1,212 @@+"""Shared contract tests for the pluggable persistence ABCs.++Every registered ``IndexStore`` / ``GraphStore`` / ``JobStore``+implementation runs through the same behavioral suite. Adding a new+backend means appending to the parametrise list at the top of each+section — no new test methods required for the common contract.++The OSS-only impls are exercised here: ``SqlIndexStore``,+``InProcessGraphStore``, ``SqlJobStore``. Third-party impls extend the+parametrisation in their own packages.+"""++from __future__ import annotations++import pytest+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.persistence._interfaces import JobState+from repowise.core.persistence.stores import (+ InProcessGraphStore,+ SqlIndexStore,+ SqlJobStore,+)+from tests.unit.persistence.helpers import make_repo_kwargs++# ---------------------------------------------------------------------------+# IndexStore — exercises the surface that crud.py exposes today+# ---------------------------------------------------------------------------++[email protected](params=["sql"])+def index_store(request, async_session: AsyncSession):+ """Parametrised over every IndexStore impl. Add new ids to params."""+ if request.param == "sql":+ return SqlIndexStore(async_session)+ raise AssertionError(f"Unknown IndexStore variant {request.param!r}")+++async def test_index_store_repository_roundtrip(index_store):+ """upsert → get_repository round-trips identical values."""+ repo = await index_store.upsert_repository(**make_repo_kwargs(name="contract-1"))+ fetched = await index_store.get_repository(repo.id)+ assert fetched is not None+ assert fetched.id == repo.id+ assert fetched.name == "contract-1"+++async def test_index_store_repository_by_path(index_store):+ """get_repository_by_path locates by local_path."""+ repo = await index_store.upsert_repository(+ **make_repo_kwargs(name="contract-2", local_path="/contract/path")+ )+ fetched = await index_store.get_repository_by_path("/contract/path")+ assert fetched is not None and fetched.id == repo.id+++async def test_index_store_session_property(async_session: AsyncSession):+ """SqlIndexStore exposes its bound session for raw-SQL escapes."""+ store = SqlIndexStore(async_session)+ assert store.session is async_session+++async def test_index_store_delete_returns_false_when_absent(index_store):+ """delete_repository returns False for an unknown id."""+ assert await index_store.delete_repository("does-not-exist") is False+++# ---------------------------------------------------------------------------+# GraphStore — exercises the in-memory NetworkX wrapper+# ---------------------------------------------------------------------------++[email protected](params=["in_process"])+def graph_store(request):+ if request.param == "in_process":+ return InProcessGraphStore()+ raise AssertionError(f"Unknown GraphStore variant {request.param!r}")+++def test_graph_store_basic_mutation(graph_store):+ graph_store.add_node("a.py", node_type="file")+ graph_store.add_node("b.py", node_type="file")+ graph_store.add_edge("a.py", "b.py", edge_type="imports")+ assert graph_store.has_node("a.py")+ assert graph_store.has_edge("a.py", "b.py")+ assert graph_store.node_count() == 2+ assert graph_store.edge_count() == 1+++def test_graph_store_neighbors(graph_store):+ graph_store.add_node("a", node_type="file")+ graph_store.add_node("b", node_type="file")+ graph_store.add_node("c", node_type="file")+ graph_store.add_edge("a", "b")+ graph_store.add_edge("b", "c")+ assert graph_store.neighbors("b", direction="out") == ["c"]+ assert graph_store.neighbors("b", direction="in") == ["a"]+ assert set(graph_store.neighbors("b", direction="both")) == {"a", "c"}+++def test_graph_store_metrics_on_empty_graph(graph_store):+ assert graph_store.pagerank() == {}+ assert graph_store.betweenness_centrality() == {}+ assert graph_store.communities() == {}+++def test_graph_store_pagerank_after_build(graph_store):+ for node in ("a", "b", "c"):+ graph_store.add_node(node, node_type="file")+ graph_store.add_edge("a", "b")+ graph_store.add_edge("b", "c")+ graph_store.add_edge("a", "c")+ graph_store.build()+ pr = graph_store.pagerank()+ assert set(pr.keys()) == {"a", "b", "c"}+ assert all(isinstance(v, float) for v in pr.values())+++def test_graph_store_invalidates_caches_on_mutation(graph_store):+ graph_store.add_node("a", node_type="file")+ graph_store.add_node("b", node_type="file")+ graph_store.add_edge("a", "b")+ _ = graph_store.pagerank() # warm the cache+ graph_store.add_node("c", node_type="file") # invalidate+ pr_after = graph_store.pagerank()+ assert "c" in pr_after+++def test_graph_store_neighbors_invalid_direction(graph_store):+ graph_store.add_node("a", node_type="file")+ with pytest.raises(ValueError):+ graph_store.neighbors("a", direction="sideways")+++# ---------------------------------------------------------------------------+# JobStore — exercises the pipeline_jobs checkpoint surface+# ---------------------------------------------------------------------------++[email protected](params=["sql"])+async def job_store(request, async_session: AsyncSession):+ if request.param == "sql":+ # SqlJobStore requires a real repository row because pipeline_jobs+ # has a FK on repositories.id.+ from repowise.core.persistence.stores import SqlIndexStore++ idx = SqlIndexStore(async_session)+ repo = await idx.upsert_repository(**make_repo_kwargs(name="job-host"))+ store = SqlJobStore(async_session)+ # Stash the repo id on the store for the tests that need it.+ store._test_repo_id = repo.id # type: ignore[attr-defined]+ return store+ raise AssertionError(f"Unknown JobStore variant {request.param!r}")+++async def test_job_store_create_and_get(job_store):+ repo_id = job_store._test_repo_id # type: ignore[attr-defined]+ job = await job_store.create_job(+ repository_id=repo_id, phase="parse", metadata={"k": 1}+ )+ assert job.state is JobState.PENDING+ assert job.phase == "parse"+ assert job.metadata == {"k": 1}+ fetched = await job_store.get_job(job.id)+ assert fetched is not None and fetched.id == job.id+++async def test_job_store_state_transitions(job_store):+ repo_id = job_store._test_repo_id # type: ignore[attr-defined]+ job = await job_store.create_job(repository_id=repo_id, phase="graph")+ updated = await job_store.update_state(job.id, JobState.RUNNING)+ assert updated.state is JobState.RUNNING+ final = await job_store.update_state(+ job.id, JobState.FAILED, error="boom"+ )+ assert final.state is JobState.FAILED+ assert final.error == "boom"+++async def test_job_store_checkpoint_advances_cursor(job_store):+ repo_id = job_store._test_repo_id # type: ignore[attr-defined]+ job = await job_store.create_job(repository_id=repo_id, phase="git")+ cp = await job_store.checkpoint(job.id, "abc/123")+ assert cp.cursor == "abc/123"+ cp = await job_store.checkpoint(job.id, "abc/456")+ assert cp.cursor == "abc/456"+ assert cp.state is JobState.PENDING # checkpoint does not change state+++async def test_job_store_find_resumable_filters_by_state(job_store):+ repo_id = job_store._test_repo_id # type: ignore[attr-defined]+ a = await job_store.create_job(repository_id=repo_id, phase="a")+ b = await job_store.create_job(repository_id=repo_id, phase="b")+ await job_store.update_state(a.id, JobState.COMPLETED)+ await job_store.update_state(b.id, JobState.RUNNING)+ resumable = await job_store.find_resumable(repository_id=repo_id)+ ids = {j.id for j in resumable}+ assert b.id in ids+ assert a.id not in ids+++async def test_job_store_get_unknown_returns_none(job_store):+ assert await job_store.get_job("does-not-exist") is Nonediff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex 5c1f19e5f..2829110bb 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -312,5 +312,6 @@ def test_base_includes_all_models():"health_file_metrics","health_snapshots","coverage_files",+ "pipeline_jobs",}assert expected == table_namesdiff --git a/tests/unit/registry/__init__.py b/tests/unit/registry/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/registry/test_cli_registry.py b/tests/unit/registry/test_cli_registry.pynew file mode 100644index 000000000..3cca18c14--- /dev/null+++ b/tests/unit/registry/test_cli_registry.py@@ -0,0 +1,86 @@+"""CLIRegistry behavior."""++from __future__ import annotations++import click+import pytest++from repowise.core.registry import CLIRegistry+++def _make_command(name: str) -> click.Command:+ @click.command(name=name)+ def _cmd() -> None: # pragma: no cover - never invoked+ pass++ return _cmd+++def registry() -> CLIRegistry:+ return CLIRegistry()+++def root() -> click.Group:+ @click.group()+ def cli() -> None: # pragma: no cover+ pass++ return cli+++def test_register_preserves_order(registry, root):+ a = _make_command("a")+ b = _make_command("b")+ c = _make_command("c")+ registry.register(a)+ registry.register(b)+ registry.register(c)+ registry.apply(root)+ assert list(root.commands.keys()) == ["a", "b", "c"]+++def test_apply_is_idempotent_per_root(registry, root):+ registry.register(_make_command("once"))+ registry.apply(root)+ # Second call must not raise or duplicate.+ registry.apply(root)+ assert list(root.commands.keys()) == ["once"]+++def test_apply_supports_multiple_roots(registry):+ registry.register(_make_command("shared"))++ @click.group()+ def root_a() -> None: # pragma: no cover+ pass++ @click.group()+ def root_b() -> None: # pragma: no cover+ pass++ registry.apply(root_a)+ registry.apply(root_b)+ assert "shared" in root_a.commands+ assert "shared" in root_b.commands+++def test_register_with_parent_attaches_to_subgroup(registry, root):+ @click.group(name="grp")+ def subgroup() -> None: # pragma: no cover+ pass++ registry.register(subgroup)+ leaf = _make_command("leaf")+ registry.register(leaf, parent=subgroup)+ registry.apply(root)+ assert "grp" in root.commands+ assert "leaf" in subgroup.commands+++def test_reset_clears_entries(registry, root):+ registry.register(_make_command("x"))+ registry.reset()+ registry.apply(root)+ assert root.commands == {}diff --git a/tests/unit/registry/test_mcp_tool_registry.py b/tests/unit/registry/test_mcp_tool_registry.pynew file mode 100644index 000000000..d2c61090e--- /dev/null+++ b/tests/unit/registry/test_mcp_tool_registry.py@@ -0,0 +1,100 @@+"""MCPToolRegistry behavior."""++from __future__ import annotations++from typing import Any++import pytest++from repowise.core.registry import MCPToolRegistry+++class _FakeMCP:+ """Minimal stand-in for FastMCP — captures ``mcp.tool()(fn)`` calls."""++ def __init__(self) -> None:+ self.registered: list[Any] = []++ def tool(self) -> Any:+ def _decorator(fn: Any) -> Any:+ self.registered.append(fn)+ return fn++ return _decorator+++def registry() -> MCPToolRegistry:+ return MCPToolRegistry()+++def test_register_decorator_paren_form(registry):+ @registry.register()+ async def my_tool() -> dict:+ return {}++ assert my_tool in registry.tools()+++def test_register_decorator_bare_form(registry):+ @registry.register+ async def my_tool() -> dict:+ return {}++ assert my_tool in registry.tools()+++def test_tool_alias_matches_register(registry):+ @registry.tool()+ async def my_tool() -> dict:+ return {}++ assert my_tool in registry.tools()+++def test_apply_registers_with_server(registry):+ @registry.register+ async def t1() -> dict:+ return {}++ @registry.register+ async def t2() -> dict:+ return {}++ mcp = _FakeMCP()+ registry.apply(mcp)+ assert t1 in mcp.registered+ assert t2 in mcp.registered+++def test_apply_is_idempotent_per_server(registry):+ @registry.register+ async def t1() -> dict:+ return {}++ mcp = _FakeMCP()+ registry.apply(mcp)+ registry.apply(mcp)+ assert mcp.registered.count(t1) == 1+++def test_apply_supports_multiple_servers(registry):+ @registry.register+ async def t1() -> dict:+ return {}++ a = _FakeMCP()+ b = _FakeMCP()+ registry.apply(a)+ registry.apply(b)+ assert t1 in a.registered+ assert t1 in b.registered+++def test_reset_clears_tools(registry):+ @registry.register+ async def t1() -> dict:+ return {}++ registry.reset()+ assert registry.tools() == []diff --git a/tests/unit/registry/test_pipeline_hooks.py b/tests/unit/registry/test_pipeline_hooks.pynew file mode 100644index 000000000..3ae2e9cf4--- /dev/null+++ b/tests/unit/registry/test_pipeline_hooks.py@@ -0,0 +1,91 @@+"""PipelineHookRegistry + HookProgressCallback behavior."""++from __future__ import annotations++import pytest++from repowise.core.registry import (+ HookPhase,+ HookProgressCallback,+ PipelineHookRegistry,+)+++def hooks() -> PipelineHookRegistry:+ return PipelineHookRegistry()+++def test_register_and_fire_post_hook(hooks):+ seen: list[str] = []+ hooks.register("parse", lambda p: seen.append(f"post:{p}"), when="post")+ hooks.fire("parse", HookPhase.POST)+ assert seen == ["post:parse"]+++def test_pre_and_post_separate(hooks):+ seen: list[str] = []+ hooks.register("graph", lambda p: seen.append("pre"), when="pre")+ hooks.register("graph", lambda p: seen.append("post"), when="post")+ hooks.fire("graph", HookPhase.PRE)+ hooks.fire("graph", HookPhase.POST)+ assert seen == ["pre", "post"]+++def test_broken_hook_does_not_propagate(hooks):+ def boom(_p: str) -> None:+ raise RuntimeError("plugin bug")++ hooks.register("parse", boom)+ # Must not raise.+ hooks.fire("parse", HookPhase.POST)+++def test_unknown_phase_is_silent(hooks):+ # Firing a phase nobody registered against is a no-op.+ hooks.fire("nonexistent", HookPhase.POST)+++def test_progress_wrapper_fires_around_inner(hooks):+ class _Inner:+ def __init__(self) -> None:+ self.events: list[str] = []++ def on_phase_start(self, phase: str, total: int | None = None) -> None:+ self.events.append(f"start:{phase}")++ def on_phase_done(self, phase: str) -> None:+ self.events.append(f"done:{phase}")++ def on_item_done(self, phase: str) -> None:+ self.events.append(f"item:{phase}")++ inner = _Inner()+ hook_events: list[str] = []+ hooks.register("parse", lambda p: hook_events.append(f"pre:{p}"), when="pre")+ hooks.register("parse", lambda p: hook_events.append(f"post:{p}"), when="post")++ wrap = HookProgressCallback(inner, hooks)+ wrap.on_phase_start("parse", 3)+ wrap.on_item_done("parse")+ wrap.on_phase_done("parse")++ assert hook_events == ["pre:parse", "post:parse"]+ assert inner.events == ["start:parse", "item:parse", "done:parse"]+++def test_progress_wrapper_works_without_inner(hooks):+ hook_events: list[str] = []+ hooks.register("graph", lambda p: hook_events.append(p), when="post")+ wrap = HookProgressCallback(None, hooks)+ # These must not raise.+ wrap.on_phase_start("graph", None)+ wrap.on_item_done("graph") # forwarded → no-op+ wrap.on_phase_done("graph")+ assert hook_events == ["graph"]+++def test_reset_clears_hooks(hooks):+ hooks.register("parse", lambda p: None)+ hooks.reset()+ assert hooks.hooks_for("parse", HookPhase.POST) == []