|
| 1 | +"""The four plugin hooks plus the registry that loads and dispatches them. |
| 2 | +
|
| 3 | +Per PLAN.md "Plugin/extension architecture": |
| 4 | +
|
| 5 | + A plugin is a Python package implementing any subset of the four |
| 6 | + hooks. No fork, no monkey-patch. |
| 7 | +
|
| 8 | +The four hooks |
| 9 | +-------------- |
| 10 | +
|
| 11 | +- `SourceIngester(file_path) -> Optional[ParsedFile]` |
| 12 | + Decide if/how to index a file. Chio-pack's Rust tree-sitter |
| 13 | + extractor is one example. |
| 14 | +
|
| 15 | +- `GraphProjector(parsed: ParsedFile) -> Iterable[Node | Edge]` |
| 16 | + Take parsed AST/symbols and emit nodes + edges using a schema |
| 17 | + pack's vocabulary. |
| 18 | +
|
| 19 | +- `ToolRegistrar(server: object) -> None` |
| 20 | + Declare MCP tools on the gateway. `server` is the Phase 1.3+ |
| 21 | + MCP-server-framework handle; here typed as `object` to keep the |
| 22 | + plugin protocol stable across server-framework iterations. |
| 23 | +
|
| 24 | +- `FrontmatterHandler(type: str, frontmatter: dict) -> Iterable[DerivedRecord]` |
| 25 | + Interpret a vault note's `type:` value to decide what derived |
| 26 | + store(s) to write to. |
| 27 | +
|
| 28 | +Each hook is a Protocol, not an abstract base class. Plugins can be |
| 29 | +plain functions OR classes — whatever fits. The registry dispatches by |
| 30 | +type rather than by inheritance. |
| 31 | +""" |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import importlib |
| 35 | +import importlib.metadata |
| 36 | +from collections.abc import Iterable |
| 37 | +from dataclasses import dataclass, field |
| 38 | +from typing import Any, Protocol, runtime_checkable |
| 39 | + |
| 40 | +from .types import DerivedRecord, Edge, Node, ParsedFile |
| 41 | + |
| 42 | + |
| 43 | +# === Hook protocols === |
| 44 | + |
| 45 | + |
| 46 | +@runtime_checkable |
| 47 | +class SourceIngester(Protocol): |
| 48 | + """Decide if/how to index a single file. |
| 49 | +
|
| 50 | + Plugins return None to skip a file (most files are skipped — a |
| 51 | + Rust ingester returns None for .py files, etc). |
| 52 | + """ |
| 53 | + |
| 54 | + def __call__(self, file_path: str) -> ParsedFile | None: ... |
| 55 | + |
| 56 | + |
| 57 | +@runtime_checkable |
| 58 | +class GraphProjector(Protocol): |
| 59 | + """Emit graph nodes and edges from a parsed file.""" |
| 60 | + |
| 61 | + def __call__(self, parsed: ParsedFile) -> Iterable[Node | Edge]: ... |
| 62 | + |
| 63 | + |
| 64 | +@runtime_checkable |
| 65 | +class ToolRegistrar(Protocol): |
| 66 | + """Declare MCP tools on the gateway server. |
| 67 | +
|
| 68 | + `server` is the Phase 1.3+ MCP-server-framework handle. The protocol |
| 69 | + keeps it as `object` so plugin signatures stay stable across server |
| 70 | + iterations. Plugins call methods on `server` per its documented API. |
| 71 | + """ |
| 72 | + |
| 73 | + def __call__(self, server: object) -> None: ... |
| 74 | + |
| 75 | + |
| 76 | +@runtime_checkable |
| 77 | +class FrontmatterHandler(Protocol): |
| 78 | + """Interpret a vault note's `type:` value, emit derived records. |
| 79 | +
|
| 80 | + The handler decides what derived stores to write (Graphiti, pgvector, |
| 81 | + Neo4j, ...) based on the frontmatter's `type` and content. Multiple |
| 82 | + handlers can fire for the same note; results are unioned. |
| 83 | + """ |
| 84 | + |
| 85 | + def __call__( |
| 86 | + self, type: str, frontmatter: dict[str, Any] |
| 87 | + ) -> Iterable[DerivedRecord]: ... |
| 88 | + |
| 89 | + |
| 90 | +# === Registry === |
| 91 | + |
| 92 | + |
| 93 | +@dataclass |
| 94 | +class Registry: |
| 95 | + """Loads and dispatches plugin hooks. |
| 96 | +
|
| 97 | + Two registration modes: |
| 98 | +
|
| 99 | + 1. **Entry-point loading** (production): plugins declare themselves |
| 100 | + in their pyproject.toml under |
| 101 | + [project.entry-points."kb_engine.plugins"]. Call `load_entry_points()` |
| 102 | + to discover them. |
| 103 | +
|
| 104 | + 2. **Direct registration** (tests, single-file plugins): call |
| 105 | + `register_*()` methods to add hooks programmatically. |
| 106 | +
|
| 107 | + Both modes coexist; entry-point hooks merge with direct ones. |
| 108 | + """ |
| 109 | + |
| 110 | + source_ingesters: list[SourceIngester] = field(default_factory=list) |
| 111 | + graph_projectors: list[GraphProjector] = field(default_factory=list) |
| 112 | + tool_registrars: list[ToolRegistrar] = field(default_factory=list) |
| 113 | + frontmatter_handlers: dict[str, list[FrontmatterHandler]] = field(default_factory=dict) |
| 114 | + |
| 115 | + # === Direct registration === |
| 116 | + |
| 117 | + def register_source_ingester(self, hook: SourceIngester) -> None: |
| 118 | + if not isinstance(hook, SourceIngester) and not callable(hook): |
| 119 | + raise TypeError(f"hook {hook!r} is not callable / not a SourceIngester") |
| 120 | + self.source_ingesters.append(hook) |
| 121 | + |
| 122 | + def register_graph_projector(self, hook: GraphProjector) -> None: |
| 123 | + if not isinstance(hook, GraphProjector) and not callable(hook): |
| 124 | + raise TypeError(f"hook {hook!r} is not callable / not a GraphProjector") |
| 125 | + self.graph_projectors.append(hook) |
| 126 | + |
| 127 | + def register_tool_registrar(self, hook: ToolRegistrar) -> None: |
| 128 | + if not isinstance(hook, ToolRegistrar) and not callable(hook): |
| 129 | + raise TypeError(f"hook {hook!r} is not callable / not a ToolRegistrar") |
| 130 | + self.tool_registrars.append(hook) |
| 131 | + |
| 132 | + def register_frontmatter_handler( |
| 133 | + self, type_value: str, hook: FrontmatterHandler |
| 134 | + ) -> None: |
| 135 | + if not isinstance(hook, FrontmatterHandler) and not callable(hook): |
| 136 | + raise TypeError(f"hook {hook!r} is not callable / not a FrontmatterHandler") |
| 137 | + self.frontmatter_handlers.setdefault(type_value, []).append(hook) |
| 138 | + |
| 139 | + # === Entry-point loading === |
| 140 | + |
| 141 | + def load_entry_points(self, group: str = "kb_engine.plugins") -> int: |
| 142 | + """Discover plugins via importlib.metadata entry points. |
| 143 | +
|
| 144 | + Each entry point should be a module with a `register(registry)` |
| 145 | + function that calls back into `register_*` methods. |
| 146 | +
|
| 147 | + Returns the number of entry points successfully loaded. |
| 148 | + """ |
| 149 | + n = 0 |
| 150 | + for ep in importlib.metadata.entry_points(group=group): |
| 151 | + try: |
| 152 | + module = ep.load() |
| 153 | + except Exception as e: |
| 154 | + print(f"warning: failed to load entry point {ep.name}: {e}") |
| 155 | + continue |
| 156 | + register_fn = getattr(module, "register", None) |
| 157 | + if register_fn is None: |
| 158 | + print(f"warning: entry point {ep.name} has no `register` function") |
| 159 | + continue |
| 160 | + register_fn(self) |
| 161 | + n += 1 |
| 162 | + return n |
| 163 | + |
| 164 | + # === Dispatch === |
| 165 | + |
| 166 | + def ingest_file(self, file_path: str) -> ParsedFile | None: |
| 167 | + """Run source ingesters in registration order; first non-None wins.""" |
| 168 | + for ingester in self.source_ingesters: |
| 169 | + result = ingester(file_path) |
| 170 | + if result is not None: |
| 171 | + return result |
| 172 | + return None |
| 173 | + |
| 174 | + def project_graph(self, parsed: ParsedFile) -> list[Node | Edge]: |
| 175 | + """Run all graph projectors and union their output.""" |
| 176 | + out: list[Node | Edge] = [] |
| 177 | + for projector in self.graph_projectors: |
| 178 | + out.extend(projector(parsed)) |
| 179 | + return out |
| 180 | + |
| 181 | + def register_tools(self, server: object) -> None: |
| 182 | + """Run all tool registrars against the given server.""" |
| 183 | + for registrar in self.tool_registrars: |
| 184 | + registrar(server) |
| 185 | + |
| 186 | + def handle_frontmatter( |
| 187 | + self, type_value: str, frontmatter: dict[str, Any] |
| 188 | + ) -> list[DerivedRecord]: |
| 189 | + """Run handlers registered for `type_value` and union their output. |
| 190 | +
|
| 191 | + Handlers registered with `type_value="*"` always run. |
| 192 | + """ |
| 193 | + out: list[DerivedRecord] = [] |
| 194 | + for hook in self.frontmatter_handlers.get(type_value, []): |
| 195 | + out.extend(hook(type_value, frontmatter)) |
| 196 | + for hook in self.frontmatter_handlers.get("*", []): |
| 197 | + out.extend(hook(type_value, frontmatter)) |
| 198 | + return out |
0 commit comments