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
docs(plugins): add a plugin author guide, a hello example plugin and a test that keeps it working (#4742)
Raghav Chamadiyaaf2a64a84ce1
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex a36b517a2..1575d91a6 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -36,14 +36,38 @@ uv run pytest tests/providers/ tests/unit/## Getting oriented-This is a ~3,000 file codebase, and reading it front to back is not the plan. Repowise-exists to make that unnecessary, so use it on itself.+This repository has about 7,000 files, and reading it front to back is not the plan.+Repowise exists to make that unnecessary, so use it on itself.-### Without installing anything+### Connect your agent to the hosted index (nothing to install)-We keep a public, always-fresh index of this repository at+We keep a public index of this repository at**[repowise.dev/repo/repowise-dev/repowise](https://repowise.dev/repo/repowise-dev/repowise)**.-It re-indexes on every push. Pick the tab that matches your question:+It re-indexes on every push and serves an MCP server that any contributor can connect+a coding agent to for free:++```bash+claude mcp add --transport http repowise \+ https://api.repowise.dev/mcp/repowise-dev/repowise \+ --header "Authorization: Bearer <your API key>"+```++To get a key, sign in on the repo page and open the+[Use repowise-dev/repowise in your agent](https://repowise.dev/repo/repowise-dev/repowise#agent)+panel. It mints the key and gives a copyable snippet for Cursor, Codex, VS Code and+other editors. Claude's connector can sign in on its own, with no key to paste.++Then ask your agent things like:++```+get_answer("how is the update pipeline put together?")+get_why("why is doc generation split from ingestion?")+get_context(targets=["packages/core/src/repowise/core/pipeline/orchestrator.py"])+```++### Or browse the same index++Pick the tab that matches your question:| Your question | Where to look ||---|---|@@ -54,24 +78,19 @@ It re-indexes on every push. Pick the tab that matches your question:| Why is it built this way? | [Decisions](https://repowise.dev/repo/repowise-dev/repowise/decisions) || What changed recently, and how risky was it? | [Commits](https://repowise.dev/repo/repowise-dev/repowise/commits) |-### Locally, with your agent+### Or index it locally-Better still, index this repo with the tool you are contributing to. It is free, needs-no API key, and takes a couple of minutes:+The hosted index sees what is pushed to `main`. To ask about your unpushed changes, or+to work offline, index your checkout. It is free, needs no API key and runs in a few+minutes:```bashuv run repowise init --no-prose -y # graph, git history, health, decisions. No LLM, no spend.uv run repowise serve # dashboard + MCP server on localhost```-Then point your coding agent at the MCP server (see the-[Start in minutes](../README.md#quickstart) for Claude Code, Codex-and others) and ask it questions directly:--```-get_context for packages/core/src/repowise/core/pipeline/orchestrator.py-get_why "why is doc generation split from ingestion?"-```+`init` connects the coding agents it detects to this local index. For other agents, see+[Set it up in one line](../README.md#set-it-up-in-one-line).If something about this experience is bad, that is a bug worth reporting. Contributorsare the only people who use repowise on repowise with fresh eyes.@@ -132,11 +151,13 @@ Questions about scope before you claim are welcome. Asking is not claiming.Some issues describe several separable pieces of work. Say which piece you are taking,and it can be split into its own issue so more than one person can work in parallel.-Before you start, check the file you are about to edit:+### Before you edit a file++Check the file you are about to edit:```bashuv run repowise health --file <path> --recompute # score, markers, findings-uv run repowise risk HEAD # or ask get_risk from your agent+uv run repowise risk --target <path> # fix history; needs the local index, or ask get_risk```Some files in this repo are bug magnets: high churn, a long run of prior fixes, often a@@ -152,24 +173,28 @@ current ones. Changes there are welcome, but expect closer review and bring testgit checkout -b feat/your-feature```3. **Make your changes**: keep commits focused and well-described-4. **Run tests** before pushing:+4. **Run the CI checks** before pushing:```bashuv run pytest tests/providers/ tests/unit/ # both, CI runs bothnpm run lintnpm run type-check+ uv run ruff check .+ uv run repowise doc-drift --check --baseline .github/doc-drift-baseline.json````tests/providers/` is easy to forget and CI does not forget it, so a run thatskips it is the most common way a green local suite turns red on the PR.5. **Check your own change** with the tool you are contributing to:```bash- uv run repowise risk main..HEAD # 0-10 defect score, plus may_break,- # missing_cochanges and missing_tests- uv run repowise impacted-tests --staged # the tests your diff actually exercises+ uv run repowise health check origin/main...HEAD # the health gate CI runs+ uv run repowise risk main..HEAD # how big and spread out the change is+ uv run repowise impacted-tests --staged # the tests your diff exercisesuv run repowise health --file <path> --recompute # did the file you touched get worse?```- None of this is a gate, and none of it calls an LLM. It is the same signal the- reviewer will be looking at, and running it yourself catches the boring problems- (a forgotten companion file, an untested hotspot) before anyone else has to.+ `health check` is the same gate as the "Repowise gates" CI job: it fails on a+ high-severity health finding your change introduces (complexity, nesting, size,+ duplication, error handling). The rest is not a gate. None of it calls an LLM, and+ running it yourself catches the boring problems (a forgotten companion file, an+ untested hotspot) before a reviewer has to.6. **Push** to your fork and open a **Pull Request** against `main`## Branch Naming@@ -180,7 +205,8 @@ Use descriptive prefixes:|--------|---------|| `feat/` | New features || `fix/` | Bug fixes |-| `chore/` | Maintenance, CI, docs |+| `docs/` | Documentation |+| `chore/` | Maintenance, CI || `refactor/` | Code restructuring |## Commit Messages@@ -203,6 +229,8 @@ repowise/ui/ # Shared React UI componentsweb/ # Next.js frontendvscode/ # VS Code extension (has its own CI job)+ claude-mod/ # Repowise Lens, the Claude Code mod+ plugins/ # Agent plugins (Claude Code and others)tests/ # providers/, unit/ and integration/docs/ # Documentation```@@ -235,17 +263,34 @@ repowise/An agent CLI used as a backend (`claude_cli`, `codex_cli`, `opencode`) follows theagent platform recipe instead.+Providers that most users need ship in core this way. A provider can also live in+its own package: call `register_provider(name, factory)` from a plugin's+`register()`; see the [plugin author guide](../docs/reference/PLUGINS.md).+Adding a new language has a dedicated recipe, see[docs/architecture/language-support.md](../docs/architecture/language-support.md).Adding an agent integration or an agent CLI indexing backend has its own recipe, see[docs/architecture/agent-platform.md](../docs/architecture/agent-platform.md).+### Extending Repowise with a plugin++Write a plugin when your change serves one team or one system (an internal auth+service, a chat app sink, a company report section) and an existing registry or+seam already covers it. Open a core PR when the change helps most users or fixes+behaviour. A new seam starts as an issue that describes its contract, when it+runs and what a failure does. Start from the+[plugin author guide](../docs/reference/PLUGINS.md) and the+[hello example](../examples/plugins/hello/).+## Testing- Add tests for new features and bug fixes-- Place tests in `tests/unit/` or `tests/integration/`-- Run the full suite with `uv run pytest`-- A test asserting on a `caplog` record needs `caplog.set_level(logging.INFO, logger="<the module's full logger name>")` (or the level you're asserting on) — setting the root logger's level is not enough when an ancestor logger (e.g. `repowise.core`, `repowise.server`) has its own level raised, since Python resolves the *effective* level from the nearest ancestor that has one set, not from root.+- Place tests in `tests/unit/`, `tests/providers/` or `tests/integration/`+- Run `uv run pytest tests/providers/ tests/unit/` before you push; that is what CI+ runs on every pull request. `tests/integration/` runs after merge to `main`.+- A test asserting on a `caplog` record sets the level on the module's own logger:+ `caplog.set_level(logging.INFO, logger="<full logger name>")`. Setting the root+ level is not enough, because ancestors such as `repowise.core` set their own.### Retrieval guard@@ -288,6 +333,9 @@ coverage gain that costs precision is a trade-off to justify, not a win.- Reference any related issues- Ensure CI passes before requesting review- All PRs require at least one code owner approval+- Commits do not list a coding agent as author or co-author (for example a+ `Co-authored-by: Copilot` or `Co-Authored-By: Claude` trailer); maintainers ask+ for those to be removed before merge.## Reporting Issuesdiff --git a/docs/README.md b/docs/README.mdindex c9da08d11..4cb43ad61 100644--- a/docs/README.md+++ b/docs/README.md@@ -147,6 +147,7 @@ For a map of every layer and how they feed each other, read| [reference/CONFIG.md](reference/CONFIG.md) | `.repowise/config.yaml`, `health-rules.json`, and environment variables || [reference/MCP_RESPONSE_FIELDS.md](reference/MCP_RESPONSE_FIELDS.md) | The field dictionary for every MCP response, including the `_meta` envelope || [reference/HOOKS_REFERENCE.md](reference/HOOKS_REFERENCE.md) | The exact settings entries each hook install writes |+| [reference/PLUGINS.md](reference/PLUGINS.md) | Build, test and publish a plugin: entry points, every registry and seam, and how one is chosen || [reference/CHANGE_REVIEW_API.md](reference/CHANGE_REVIEW_API.md) | Reviewing a change from Python, with or without a checkout || [reference/PACKAGE_USAGE.md](reference/PACKAGE_USAGE.md) | Where third-party packages are imported, the CycloneDX export, and reading Syft, SPDX or OSV files || [reference/WORKSPACE_CONTRACTS.md](reference/WORKSPACE_CONTRACTS.md) | How a workspace names, reads and matches cross-repo contracts |diff --git a/docs/architecture/README.md b/docs/architecture/README.mdindex e7a1a6aa9..3224d701a 100644--- a/docs/architecture/README.md+++ b/docs/architecture/README.md@@ -24,6 +24,6 @@ curious; you don't need them to *use* repowise (start with| [chat.md](chat.md) | The Codebase Chat feature: schema, `ChatProvider` protocol, SSE streaming, the agentic loop, and per-provider notes || [structurizr-export.md](structurizr-export.md) | Exporting the architecture as Structurizr DSL: the two-file model, health and layer tags, and how to render it || [editor-files.md](editor-files.md) | How `CLAUDE.md` / `AGENTS.md` generation works (no LLM: pure DB + filesystem derivation) and how to add a new editor file |-| [pluggable-storage.md](pluggable-storage.md) | Extension guide for authoring storage / graph / job-store plugins and adding CLI subcommands or MCP tools |+| [pluggable-storage.md](pluggable-storage.md) | Plugins, seams and pluggable storage: the storage contracts, the registries, and how to add a new seam (plugin authors start at [PLUGINS.md](../reference/PLUGINS.md)) |For the design-token and theme tooling, see [../design/](../design/).diff --git a/docs/architecture/pluggable-storage.md b/docs/architecture/pluggable-storage.mdindex 10709c1ba..d11775335 100644--- a/docs/architecture/pluggable-storage.md+++ b/docs/architecture/pluggable-storage.md@@ -1,4 +1,9 @@-# Pluggable storage and capability seams+# Plugins, seams and pluggable storage++Writing a plugin? Start with the plugin author guide,+[docs/reference/PLUGINS.md](../reference/PLUGINS.md), and the example in+[examples/plugins/hello](../../examples/plugins/hello/). This page covers the+storage contracts and how core contributors add a seam.repowise ships with sensible defaults — a local SQLite database, anin-process NetworkX graph, an in-memory or LanceDB vector store, a@@ -225,6 +230,24 @@ from the process environment only, never from a repo's `.repowise/.env`.---+## Adding a new seam++A seam is for a point that plugins should extend. Open an issue first that+describes the contract, when it runs, whether one or every implementation is+used, and what a failure does.++1. Define the registry in the module that consumes it, with a typed protocol:+ `event_sinks: SeamRegistry[EventSink] = SeamRegistry("event-sink")`.+2. Register the local default right after it, with `default=True` for a+ one-implementation seam.+3. Resolve with `get()` (one) or `all()` (every). Both load plugins first, so+ do not read `names` alone.+4. Add a row to the catalog in+ [PLUGINS.md](../reference/PLUGINS.md#extension-points-catalog): name, one+ or every, when it runs, failure behaviour, file.++---+## Defaults stay the defaultsThe seams add a layer of indirection but no behavior change for usersdiff --git a/docs/layers/CHANGES.md b/docs/layers/CHANGES.mdindex d13d9af0a..ff62a7500 100644--- a/docs/layers/CHANGES.md+++ b/docs/layers/CHANGES.md@@ -72,7 +72,7 @@ message closes (`Fixes #12`). A field it cannot read is `null`, which means unknA plugin registers another source under `SeamRegistry("change-metadata")`, selectedwith `REPOWISE_SEAM_CHANGE_METADATA`. See-[pluggable storage and capability seams](../architecture/pluggable-storage.md).+[the plugin author guide](../reference/PLUGINS.md).## Where it showsdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex d96396fb5..f7f603a61 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -2126,7 +2126,7 @@ repowise plugins --format json|------|--------------|---------|| `--format` | `table` or `json`. | `table` |-See [pluggable storage and capability seams](../architecture/pluggable-storage.md).+See the [plugin author guide](PLUGINS.md).### `repowise attribution`diff --git a/docs/reference/PLUGINS.md b/docs/reference/PLUGINS.mdnew file mode 100644index 000000000..75ef6d732--- /dev/null+++ b/docs/reference/PLUGINS.md@@ -0,0 +1,348 @@+# Writing a repowise plugin++A plugin is a Python package that repowise imports at startup. It adds CLI+commands, MCP tools, pipeline hooks, model providers, or an implementation of a+named seam (an event sink, a report section, an authenticator, and so on),+without a fork. The working example is+[`examples/plugins/hello`](../../examples/plugins/hello/); this page explains+each step.++The plugin API is experimental. Read [Stability](#stability) before you publish.++## What a plugin can do++| Goal | Register with | Kind in `repowise plugins` |+|------|---------------|----------------------------|+| Add a CLI command | `register_command(cmd)` or `register_lazy_command(name, "module:attr")` | `cli-command` |+| Add an MCP tool | `mcp_tool_registry.register(default=False)(fn)` | `mcp-tool` |+| Run code before or after a pipeline phase | `register_hook(phase, callback, when="pre"\|"post")` | `pipeline-hook` |+| Add an LLM provider | `register_provider(name, factory)` | `llm-provider` |+| Add an embedding provider | `register_embedder(name, factory)` | `embedder` |+| Add or replace an implementation of a seam | `<seam registry>.register(name, impl)` | the seam name, for example `event-sink` |++Every row is listed in the [extension points catalog](#extension-points-catalog).++## Plugin ideas++| Idea | Uses | What it does |+|------|------|--------------|+| Slack or Teams notifier | `event-sink` | Posts component events (a new hotspot, an ownership shift) to a channel |+| Webhook or SIEM forwarder | `event-sink` | Sends each event as CloudEvents JSON to an HTTP endpoint or a log pipeline |+| Self-hosted model gateway | `llm-provider` | Routes wiki generation and chat through your own model gateway |+| Local embedding model | `embedder` | Embeds pages with a model that runs on your machines |+| LDAP or Okta teams | `team-directory` | Reads team membership from your directory for declared ownership |+| SSO for `repowise serve` | `authenticator` | Accepts your identity provider's tokens on the HTTP API |+| Jira or Linear links | `change-metadata` | Fills linked issues, reviewers and labels on change records from your tracker |+| Internal vulnerability feed | `advisory-source` | Reads advisories from your own feed for `repowise packages import` |+| Compliance report section or format | `report-section`, `report-renderer` | Adds evidence your auditors ask for, or writes the report in their text format |+| Internal API as an agent tool | `mcp-tool` | Gives agents a read-only tool that queries an internal service |+| Team shortcut command | `cli-command` | Wraps a repowise workflow your team runs often in one command |+| Phase timings | `pipeline-hook` | Records when each index phase starts and ends and sends the timings to your metrics system |++## Build your first plugin++1. Write a module with a `register()` function. repowise calls it once per+ process, with no arguments.++ ```python+ # src/repowise_hello/__init__.py+ import click++ from repowise.core.registry import register_command+++ @click.command("hello")+ def hello_command() -> None:+ """Say hello."""+ click.echo("hello")+++ def register() -> None:+ register_command(hello_command)+ ```++2. Declare an entry point in the `repowise.plugins` group. The value is a+ module (imported, nothing called) or `module:callable` (imported, then+ called).++ ```toml+ # pyproject.toml+ [project]+ name = "repowise-hello"+ version = "0.1.0"+ dependencies = ["repowise>=0.59"]++ [project.entry-points."repowise.plugins"]+ hello = "repowise_hello:register"+ ```++3. Install it into the environment repowise runs from.++ ```bash+ pip install -e .+ ```++For local work without installing, list targets in `REPOWISE_PLUGINS`+(comma-separated, same `module` or `module:callable` form). The module must be+importable, so put its source directory on `PYTHONPATH`:++```bash+PYTHONPATH=src REPOWISE_PLUGINS=repowise_hello:register repowise plugins+```++| Source | Form | Read from |+|--------|------|-----------|+| Entry point | `name = "module"` or `name = "module:callable"` in group `repowise.plugins` | installed package metadata |+| `REPOWISE_PLUGINS` | `module` or `module:callable`, comma-separated | the process environment only, never a repository's `.repowise/.env` |++A target listed both ways loads once. Register inside `register()`, not at+module import time, so a test can import your module without side effects.++## Check it loaded++```bash+repowise plugins+repowise plugins --format json+```++The listing shows each plugin with its source, target, status (`loaded`,+`failed` with the error, or `skipped` for a duplicate) and everything it+registered as `"<kind>:<name>"` strings. It then lists every seam with the+implementation `get()` picks and all registered names. The JSON form carries+the same data:++```json+{+ "api_version": 1,+ "plugins": [+ {+ "name": "hello",+ "source": "entry point",+ "target": "repowise_hello:register",+ "status": "loaded",+ "error": null,+ "seams": ["cli-command:hello", "mcp-tool:hello_greet", "event-sink:hello-stderr", "report-section:hello"]+ }+ ],+ "seams": {+ "event-sink": {"default": "jsonl", "implementations": ["jsonl", "stdout", "hello-stderr"]}+ }+}+```++`api_version` is `PLUGIN_API_VERSION` from `repowise.core.registry`. Check it+in your plugin if you depend on a contract that may change:++```python+from repowise.core.registry import PLUGIN_API_VERSION++if PLUGIN_API_VERSION != 1:+ raise RuntimeError(f"repowise-hello supports plugin API 1, found {PLUGIN_API_VERSION}")+```++An exception raised from `register()` (or at import) marks the plugin+`failed`. repowise records it and carries on without it.++## When plugins load++Plugins load once per process, the first time repowise needs them:++| Moment | What triggers loading |+|--------|-----------------------|+| CLI | an unknown command name or a command listing (`repowise --help`); a built-in command runs without loading plugins |+| MCP server | server start, before tools attach |+| `repowise serve` | app creation |+| Index and update | each pipeline run, before hooks are wrapped |+| A seam | `get()` or `all()` on any seam |+| A provider | a lookup of an LLM provider or embedder name that is not built in |++## Extension points catalog++"One" means repowise uses a single selected implementation. "Every" means+repowise runs each registered implementation in registration order.++### Registries++| Kind | Register with | One or every | When it runs | On failure | Defined in |+|------|---------------|--------------|--------------|------------|------------|+| `cli-command` | `register_command(cmd, parent=None)`, `register_lazy_command(name, "module:attr", parent=None)` from `repowise.core.registry` | every | when the command is invoked | a plugin command whose name a built-in already holds is ignored with a warning | `packages/core/src/repowise/core/registry/cli_registry.py` |+| `mcp-tool` | `mcp_tool_registry.register(...)` from `repowise.core.registry` | every, filtered by tool selection | when an MCP client calls the tool | invalid `tier`/`safety` metadata raises `ValueError` at registration, so the plugin is recorded `failed` (registrations made before it stay) | `packages/core/src/repowise/core/registry/mcp_tool_registry.py` |+| `pipeline-hook` | `register_hook(phase, callback, when=...)` from `repowise.core.registry` | every | before (`pre`) or after (`post`) the named phase of `repowise init` and `repowise update` | an exception is logged and the pipeline continues | `packages/core/src/repowise/core/registry/pipeline_hooks.py` |+| `llm-provider` | `register_provider(name, factory)` from `repowise.core.providers.llm` | one, by name | when that provider name is selected | a name that a built-in provider holds raises `ValueError` | `packages/core/src/repowise/core/providers/llm/registry.py` |+| `embedder` | `register_embedder(name, factory)` from `repowise.core.providers.embedding` | one, by name | when that embedder name is selected | a name that a built-in embedder holds raises `ValueError` | `packages/core/src/repowise/core/providers/embedding/registry.py` |++`parent=` attaches a command under an existing Click group instead of the+root. For `register_lazy_command`, `name` must equal the Click command's own+name: the CLI lists it before importing the module.++Plugin MCP tools join the server's registered surface. Register with+`default=False` (an opt-in tool) and users enable it with+`repowise mcp --tools "+your_tool"` or `mcp: {tools: ["+your_tool"]}` in+`.repowise/config.yaml`. A tool registered with `default=True` joins every+default surface, which costs every agent context.++Phase names a hook can target include `traverse`, `parse`, `graph.metrics`,+`git`, `co_change`, `dead_code`, `decisions`, `health`, `doc_drift`,+`generation` and `embedding`. A phase that a run skips fires no hooks. The+callback is a plain synchronous function that receives the phase name as its+only argument; an `async def` callback never runs its body.++```python+from repowise.core.registry import register_hook+++def after_parse(phase: str) -> None:+ print(f"{phase} finished")+++def register() -> None:+ register_hook("parse", after_parse, when="post")+```++An LLM provider factory receives the keyword arguments repowise builds for it+(`model`, plus `api_key` or `base_url` when set) and returns a+`BaseProvider` (`repowise.core.providers.llm.base`). An embedder factory+returns an `Embedder` (`repowise.core.providers.embedding.base`). Users select a+registered provider by name like a built-in one, for example+`REPOWISE_PROVIDER=<name>` or `REPOWISE_EMBEDDER=<name>`.++### Seams++Each seam is a `SeamRegistry` instance. Import the registry object from the+module in the last column and call `.register(name, impl)`, for example+`from repowise.core.events.sinks import event_sinks`.++| Seam | Registry object | One or every | When it runs | On failure | Defined in |+|------|-----------------|--------------|--------------|------------|------------|+| `event-sink` | `event_sinks` | every sink named in `events.sinks` (default: the seam default, `jsonl`) | after an index run stores component events | logged; the events stay in the store | `packages/core/src/repowise/core/events/sinks.py` |+| `report-section` | `report_sections` | every | `repowise report` builds a document | the section becomes one inconclusive item marked `failed`; other sections run | `packages/core/src/repowise/core/report/model.py` |+| `report-renderer` | `report_renderers` | one, chosen by `repowise report assessment --format` | when a report is written | propagates | `packages/core/src/repowise/core/report/render.py` |+| `change-outcome` | `change_outcome_providers` | every | when a change record's outcomes are read | `OutcomeUnknownError` marks the outcome unknown; any other exception propagates | `packages/core/src/repowise/core/changes/outcomes.py` |+| `change-metadata` | `change_metadata_sources` | one | when change records are stored | propagates | `packages/core/src/repowise/core/changes/source.py` |+| `suspect-signal` | `suspect_signals` | every | `repowise suspects` ranks candidate changes | that signal does not fire; the others still rank | `packages/core/src/repowise/core/suspects/rank.py` |+| `advisory-source` | `advisory_sources` | one | `repowise packages import` reads an advisory file | propagates | `packages/core/src/repowise/core/inventory/advisories.py` |+| `team-directory` | `team_directories` | one | when components and declared owners load | propagates | `packages/core/src/repowise/core/ownership/directory.py` |+| `authenticator` | `authenticators` | one | each `repowise serve` request and MCP HTTP request | propagates | `packages/server/src/repowise/server/auth.py` |+| `authorizer` | `authorizers` | one | each repository or tool access check in `repowise serve`, MCP over HTTP and chat | propagates | `packages/server/src/repowise/server/auth.py` |+| `chat-tools` | `tool_backends` | one | each chat turn builds its tool backend | propagates | `packages/server/src/repowise/server/chat_seams.py` |+| `chat-store` | `conversation_stores` | one | each chat request opens its conversation store | propagates | `packages/server/src/repowise/server/chat_seams.py` |+| `chat-hooks` | `turn_hooks` | one | each chat turn (preflight, usage, events) | an `on_event` failure ends the turn with an error; `preflight` and `on_usage` failures propagate | `packages/server/src/repowise/server/chat_seams.py` |+| `chat-dataset` | `datasets` | every | the chat `chart` tool lists or loads a dataset | returned to the model as a tool error; the turn continues | `packages/server/src/repowise/server/chat_datasets/__init__.py` |+| `chat-view` | `view_builders` | every | chat builds a view of a tool result | logged and returned to the model as a tool error; the turn continues | `packages/server/src/repowise/server/chat_views.py` |++"Propagates" means the exception reaches the caller: the command, request or+chat turn fails with it. `get(name)` with a name no implementation holds raises+`KeyError` that lists the registered names; repowise never falls back to the+local default silently.++Each module defines the protocol its implementations follow next to the+registry, for example `EventSink.deliver` in `events/sinks.py`, `Section` and+`check()` in `report/model.py`, `TeamDirectory` in `ownership/directory.py`.+Read that protocol before you write an implementation. The+`chat-dataset` and `chat-view` seams have decorators,+`register_dataset(...)` and `register_view_builder(...)`, in the same modules.++## Choosing an implementation++For a "one" seam, `get()` picks, first match wins:++| Order | Source | Example |+|-------|--------|---------|+| 1 | a name the caller passes, such as `--format html` | `report_renderers.get("html")` |+| 2 | `REPOWISE_SEAM_<NAME>` (seam name upper-cased, `-` becomes `_`) | `REPOWISE_SEAM_TEAM_DIRECTORY=backstage` |+| 3 | the last implementation registered with `default=True` | `team_directories.register("backstage", impl, default=True)` |+| 4 | the first implementation registered | the local default |++`REPOWISE_SEAM_<NAME>` is read from the process environment only, never from a+repository's `.repowise/.env`, so a cloned repository cannot choose code to+run. Register with `default=True` only when installing your package should+switch the seam on its own; otherwise register plainly and let the user opt in+with the variable.++For an "every" seam, registering is enough: repowise reads+`SeamRegistry.all()`, which loads plugins and returns every `(name, impl)` pair+in registration order. Registering a name that already exists replaces that+implementation.++```python+from repowise.core.report.model import report_sections++for name, section in report_sections.all():+ print(name, section.title)+```++## Testing a plugin++Test your implementations directly, then add one test that loads the plugin+the way repowise does.++| Need | Use |+|------|-----|+| A registry with nothing in it | `CLIRegistry()`, `MCPToolRegistry()`, `PipelineHookRegistry()` from `repowise.core.registry` |+| Load plugins again | `repowise.core.registry.plugins.reset()`, then `load_plugins()` |+| Load only your plugin | set `REPOWISE_PLUGINS` with `monkeypatch.setenv` and patch `importlib.metadata.entry_points` to return `[]` |+| What loaded | the `PluginRecord` list from `load_plugins()`: `status`, `error`, `seams` |++```python+import importlib.metadata++from repowise.core.registry import plugins+++def test_plugin_loads(monkeypatch):+ monkeypatch.syspath_prepend("src") # not needed once the package is installed+ monkeypatch.setenv(plugins.ENV_VAR, "repowise_hello:register")+ monkeypatch.setattr(importlib.metadata, "entry_points", lambda **kw: [])+ plugins.reset()+ try:+ [record] = plugins.load_plugins()+ assert record.status == "loaded", record.error+ assert "report-section:hello" in record.seams+ finally:+ plugins.reset()+```++Seams are process-wide: a section or sink your test registers stays registered+for later tests in the same process. The repository's own test for the example,+[`tests/unit/registry/test_example_plugin.py`](../../tests/unit/registry/test_example_plugin.py),+shows how to restore each registry afterwards.++## Publishing++1. Name the distribution `repowise-<thing>` (for example `repowise-backstage`)+ and the import package `repowise_<thing>`, so users find it and it does not+ collide with repowise's own `repowise` namespace.+2. Depend on `repowise` with a lower bound on the version you tested against.+3. Build and upload to PyPI:++ ```bash+ pip install build twine+ python -m build+ python -m twine upload dist/*+ ```++4. In your README, give the install line, the seam names or commands you add,+ and any `REPOWISE_SEAM_<NAME>` value a user sets.++## Stability++The plugin API is experimental and can change in a minor release.++- A breaking change to a registry or seam contract bumps `PLUGIN_API_VERSION`+ and is named in [CHANGELOG.md](../CHANGELOG.md).+- Additive changes (a new seam, a new optional field) keep the version.+- Pin `repowise` to a range you test, and check `PLUGIN_API_VERSION` in+ `register()` if a mismatch would break silently.++## Proposing a new seam++When the point you need to extend has no seam, open an issue before any code.+Describe:++- the contract: the protocol or callable an implementation provides,+- when it runs and whether repowise uses one implementation or every one,+- what a failure does: propagate, log and continue, or mark a result unknown,+- the local default that ships in core.++Core contributors add seams following+[pluggable-storage.md](../architecture/pluggable-storage.md#adding-a-new-seam).diff --git a/examples/README.md b/examples/README.mdindex 052c61031..aa80e3982 100644--- a/examples/README.md+++ b/examples/README.md@@ -14,6 +14,7 @@ self-contained README under `examples/<name>/`.| [distill/](distill/) | `distill` / `expand` / `saved` — compress command output (no LLM key) || [health-coverage/](health-coverage/) | Code health, coverage ingest, and impacted-tests (no LLM key) || [hooks-sync/](hooks-sync/) | `hook install` + `watch` — keep the index fresh (no LLM key) |+| [plugins/hello/](plugins/hello/) | A minimal installable plugin: a CLI command, an MCP tool, an event sink and a report section || [opencode/](opencode/) | OpenCode as the LLM provider for wiki generation || [risk/](risk/) | `repowise risk` change / PR defect scoring (no LLM key) || [search/](search/) | `repowise search` fulltext / symbol / semantic wiki lookup |diff --git a/examples/plugins/hello/README.md b/examples/plugins/hello/README.mdnew file mode 100644index 000000000..56e521ff9--- /dev/null+++ b/examples/plugins/hello/README.md@@ -0,0 +1,39 @@+# repowise-hello: a minimal plugin++One package that registers four things: a CLI command (`repowise hello`), an+opt-in MCP tool (`hello_greet`), an event sink (`hello-stderr`) and a report+section (`hello`). Read [src/repowise_hello/\_\_init\_\_.py](src/repowise_hello/__init__.py)+next to the [plugin author guide](../../../docs/reference/PLUGINS.md).++## Install and check it loaded++```bash+pip install -e examples/plugins/hello # into the same environment as repowise+repowise plugins # hello entry point repowise_hello:register loaded+repowise hello # hello, world+```++## Try each registration++The report and the sink read an index, so run these in a repository indexed+with `repowise init`.++```bash+repowise mcp --tools "+hello_greet" # stdio MCP server with the opt-in tool; point your agent at it+repowise report assessment --format markdown # the "Hello" section runs with the rest+```++To send events to the sink, add it in `.repowise/config.yaml`, then run+`repowise update`. Each delivery prints `repowise-hello: N event(s) for <path>`+on stderr when the run produces component events.++```yaml+events:+ sinks: [jsonl, hello-stderr]+```++## Without installing++```bash+PYTHONPATH=examples/plugins/hello/src REPOWISE_PLUGINS=repowise_hello:register repowise plugins+```diff --git a/examples/plugins/hello/pyproject.toml b/examples/plugins/hello/pyproject.tomlnew file mode 100644index 000000000..549ccfa9c--- /dev/null+++ b/examples/plugins/hello/pyproject.toml@@ -0,0 +1,17 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "repowise-hello"+version = "0.1.0"+description = "A minimal repowise plugin: one CLI command, one MCP tool, one event sink, one report section."+requires-python = ">=3.11"+dependencies = ["repowise>=0.59"]++# repowise imports repowise_hello and calls register() once per process.+[project.entry-points."repowise.plugins"]+hello = "repowise_hello:register"++[tool.hatch.build.targets.wheel]+packages = ["src/repowise_hello"]diff --git a/examples/plugins/hello/src/repowise_hello/__init__.py b/examples/plugins/hello/src/repowise_hello/__init__.pynew file mode 100644index 000000000..33aecc816--- /dev/null+++ b/examples/plugins/hello/src/repowise_hello/__init__.py@@ -0,0 +1,68 @@+"""A minimal repowise plugin.++repowise calls :func:`register` once per process, from the ``repowise.plugins``+entry point in ``pyproject.toml`` (or from ``REPOWISE_PLUGINS=repowise_hello:register``).+Each registration below is a few lines against a public registry or seam.+"""++from __future__ import annotations++import sys+from collections.abc import Sequence+from pathlib import Path+from typing import Any++import click++from repowise.core.events.sinks import event_sinks+from repowise.core.registry import mcp_tool_registry, register_command+from repowise.core.report.model import Section, check, report_sections++[email protected]("hello")[email protected]("name", default="world")+def hello_command(name: str) -> None:+ """Say hello from the repowise-hello plugin."""+ click.echo(f"hello, {name}")+++async def hello_greet(name: str) -> dict[str, Any]:+ """Return a greeting. A minimal MCP tool from the repowise-hello plugin."""+ return {"greeting": f"hello, {name}"}+++class StderrCountSink:+ """An event sink that prints how many events each delivery carries."""++ async def deliver(self, events: Sequence[Any], *, repo_root: Path) -> None:+ print(f"repowise-hello: {len(events)} event(s) for {repo_root}", file=sys.stderr)+++async def collect_hello(ctx: Any) -> list[dict[str, Any]] | None:+ """One evidence item: how many files sit at the repository root."""+ count = sum(1 for p in Path(ctx.repo_root).iterdir() if p.is_file())+ return [+ check(+ "hello:root-files",+ reason=f"{count} file(s) at the repository root",+ method="Counts files directly under the repository root.",+ basis="measured",+ data={"count": count},+ )+ ]+++def register() -> None:+ """Called once by repowise when the plugin loads."""+ register_command(hello_command)+ mcp_tool_registry.register(default=False)(hello_greet)+ event_sinks.register("hello-stderr", StderrCountSink())+ report_sections.register(+ "hello",+ Section(+ title="Hello",+ summary="Files at the repository root, from the repowise-hello plugin.",+ collect=collect_hello,+ order=900,+ ),+ )diff --git a/tests/unit/registry/test_example_plugin.py b/tests/unit/registry/test_example_plugin.pynew file mode 100644index 000000000..0dfe2e75e--- /dev/null+++ b/tests/unit/registry/test_example_plugin.py@@ -0,0 +1,78 @@+"""The example plugin in examples/plugins/hello loads and registers what its README says."""++from __future__ import annotations++import asyncio+import importlib.metadata+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++from repowise.core import registry as registry_pkg+from repowise.core.events.sinks import event_sinks+from repowise.core.registry import cli_registry, mcp_tool_registry, plugins+from repowise.core.report.model import report_sections++EXAMPLE_SRC = Path(__file__).resolve().parents[3] / "examples" / "plugins" / "hello" / "src"++needs_api_surface = pytest.mark.skipif(+ not hasattr(registry_pkg, "PLUGIN_API_VERSION"),+ reason="cli-command and mcp-tool entries in a plugin's seams need PLUGIN_API_VERSION",+)+++def hello(monkeypatch):+ """Load only the example plugin, then put every registry back as it was."""+ monkeypatch.syspath_prepend(str(EXAMPLE_SRC))+ monkeypatch.setenv(plugins.ENV_VAR, "repowise_hello:register")+ monkeypatch.setattr(importlib.metadata, "entry_points", lambda **kw: [])+ monkeypatch.setattr(event_sinks, "_impls", dict(event_sinks._impls))+ monkeypatch.setattr(event_sinks, "_chosen", event_sinks._chosen)+ monkeypatch.setattr(report_sections, "_impls", dict(report_sections._impls))+ monkeypatch.setattr(cli_registry, "_entries", list(cli_registry._entries))+ monkeypatch.setattr(mcp_tool_registry, "_entries", list(mcp_tool_registry._entries))+ sys.modules.pop("repowise_hello", None)+ plugins.reset()+ try:+ [record] = plugins.load_plugins()+ yield record+ finally:+ plugins.reset()+ sys.modules.pop("repowise_hello", None)+++def test_example_plugin_loads_and_registers_its_seams(hello):+ assert (hello.name, hello.source, hello.status, hello.error) == (+ "repowise_hello:register",+ "env",+ "loaded",+ None,+ )+ assert "event-sink:hello-stderr" in hello.seams+ assert "report-section:hello" in hello.seams+ # The example adds a sink without taking over the default.+ assert event_sinks.default == "jsonl"+++def test_example_plugin_registers_a_command_and_an_opt_in_tool(hello):+ import repowise_hello++ assert repowise_hello.hello_command in cli_registry.commands()+ [tool] = [e for e in mcp_tool_registry.entries() if e.name == "hello_greet"]+ assert (tool.default, tool.tier) == (False, "specialist")+++def test_example_report_section_collects_a_valid_check(hello, tmp_path):+ (tmp_path / "README.md").write_text("hi", encoding="utf-8")+ section = report_sections.get("hello")+ [item] = asyncio.run(section.collect(SimpleNamespace(repo_root=tmp_path)))+ assert (item["name"], item["score"], item["data"]) == ("hello:root-files", None, {"count": 1})+++@needs_api_surface+def test_example_plugin_lists_its_command_and_tool(hello):+ assert "cli-command:hello" in hello.seams+ assert "mcp-tool:hello_greet" in hello.seams