From 6916df83c3331ab952047f6f9f3fe06bee89aba3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 13:13:49 +0000 Subject: [PATCH] Extension point for relevance, off unless named A plugin registers in the personakit.plugins entry-point group and replaces how relevance is scored. Nothing loads unless PERSONAKIT_PLUGINS names it. The read policy stays in the core; a test proves a plugin cannot serve restricted or archived memories. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- .gitignore | 1 + README.md | 1 + docs/ARCHITECTURE.md | 1 + docs/PLUGINS.md | 51 ++++++++++++++++++++++ docs/PRIVACY.md | 3 ++ docs/REVIEW-LOG.md | 1 + personakit/cli.py | 10 +++-- personakit/mcp_server.py | 12 +++--- personakit/plugins.py | 58 +++++++++++++++++++++++++ personakit/retrieve.py | 26 ++++++++---- tests/test_cli.py | 6 +++ tests/test_plugins.py | 92 ++++++++++++++++++++++++++++++++++++++++ 12 files changed, 245 insertions(+), 17 deletions(-) create mode 100644 docs/PLUGINS.md create mode 100644 personakit/plugins.py create mode 100644 tests/test_plugins.py diff --git a/.gitignore b/.gitignore index 9044e7b..979002d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ build/ *.jsonl !tests/fixtures/**/*.jsonl .env +.coverage diff --git a/README.md b/README.md index 38ad04a..d03e80b 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ Stated plainly, so you know what you are installing: - [personakit.me/docs](https://personakit.me/docs/): guides, concepts, and the MCP tools reference. - [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): the design, module by module. - [docs/PRIVACY.md](docs/PRIVACY.md): exactly what is sent where. +- [docs/PLUGINS.md](docs/PLUGINS.md): the extension point and what a plugin cannot do. - [docs/ROADMAP.md](docs/ROADMAP.md): what exists and what is planned. ## Contributing diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8710bd9..24ad9dd 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,6 +42,7 @@ flowchart TB | `store` | The only module that touches SQLite. Schema, migrations, queries, state changes. | `model` | | `review` | Terminal UI over the store: approve, restrict, hide, forget. Optional by design. | `store` | | `mcp_server` | Two tools for assistants: `personakit_read` and `personakit_propose`. Holds no read-policy constants of its own. Assistants cannot approve, restrict, hide or forget; only the owner can, in `review`. | `store`, `retrieve`, `extract` | +| `plugins` | One extension point, `relevance`, loaded only when the owner names a plugin in `PERSONAKIT_PLUGINS`. A plugin scores; policy stays in `retrieve` and `store`. See [PLUGINS.md](PLUGINS.md). | `retrieve` | | `stats` | Counts only (memories by state, sessions extracted, reads and how many returned something). Never content. | `store` | | `cli` | Argument parsing and wiring; no logic. | all | diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md new file mode 100644 index 0000000..98f26d0 --- /dev/null +++ b/docs/PLUGINS.md @@ -0,0 +1,51 @@ +# Plugins + +PersonaKit has one extension point. It replaces a scoring function and nothing else. + +| Hook | Signature | Built-in | Used by | +|---|---|---|---| +| `relevance` | `(question: str, memories: Sequence[Memory]) -> Sequence[float]` | word overlap | `personakit serve` (which memories answer a question, and in what order) | + +## What a plugin cannot do + +Policy stays in the core, whatever a plugin returns: + +- Restricted and archived memories are never served. A relevance score only orders what the read + policy already allows. +- No hook can approve, restrict, archive or forget. + +A plugin is still Python code running as you, with access to your store file. Enable only +plugins you trust and have read. + +## Enabling one + +Nothing is loaded just because it is installed. Name the plugins you want: + +```sh +pip install some-personakit-plugin +export PERSONAKIT_PLUGINS=some-name # comma separated for several, applied in order +personakit serve +``` + +A name that is not installed is an error, not a silent fallback. + +## Writing one + +Register a function in the `personakit.plugins` entry-point group. It receives a `Hooks` object +and replaces what it provides: + +```toml +# pyproject.toml of the plugin +[project.entry-points."personakit.plugins"] +some-name = "some_package:register" +``` + +```python +# some_package/__init__.py +def register(hooks): + hooks.relevance = my_relevance +``` + +For anything beyond scoring, use PersonaKit as a library: `personakit.store.Store` is the one +place that reads and writes the database, and `Store.set_state` is the same operation the CLI +uses. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 91e0542..8b49bf1 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -16,3 +16,6 @@ - **Statistics:** `personakit stats` prints counts to your terminal. It never includes memory text. Sharing the output is your choice. - **Deletion:** `personakit forget` removes a memory and its evidence from the store. +- **Plugins:** none are loaded unless you name them in `PERSONAKIT_PLUGINS`. A plugin replaces + how relevance is scored and cannot change what is served, but it is code you installed, running + as you. What it does with your data is up to that plugin; read it first. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index a7b9ff5..3e2708a 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -25,3 +25,4 @@ duplicated logic. Each entry records the result. | `personakit/store.py` (changes) | 2026-11-08 | added `reads` table via migration 2; list order now insertion order | clean | | `personakit/extract.py` (changes) | 2026-11-08 | shared text checks moved into `text_problem` so extraction and assistant proposals use one rule | clean | | `tests/*` (new) | 2026-11-08 | invented data; a key-shaped string is assembled at runtime | clean | +| `personakit/plugins.py`, `docs/PLUGINS.md`, `tests/test_plugins.py`; `retrieve.py`, `mcp_server.py`, `cli.py` (changes) | 2026-11-14 | none; opt-in by name, scoring only, a policy test proves a plugin cannot widen what is served | clean | diff --git a/personakit/cli.py b/personakit/cli.py index ca941d5..8fc0e6d 100644 --- a/personakit/cli.py +++ b/personakit/cli.py @@ -8,7 +8,7 @@ import sys from pathlib import Path -from personakit import llm, mcp_server, review, stats, sweep +from personakit import llm, mcp_server, plugins, review, stats, sweep from personakit.ingest import ADAPTERS from personakit.model import State from personakit.store import Store @@ -56,7 +56,11 @@ def main(argv: list[str] | None = None) -> int: db = args.db or default_db() db.parent.mkdir(parents=True, exist_ok=True) with Store(db) as store: - return _dispatch(args, store) + try: + return _dispatch(args, store) + except plugins.PluginError as exc: + print(exc, file=sys.stderr) + return 2 def _dispatch(args: argparse.Namespace, store: Store) -> int: @@ -84,7 +88,7 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: return 1 print("Forgotten.") elif args.command == "serve": - mcp_server.serve(store) + mcp_server.serve(store, plugins.load().relevance) return 0 diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 461f9d3..fe342d6 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -15,10 +15,10 @@ NOTE_UNCONFIRMED = "Unconfirmed: extracted from the owner's conversations but not yet reviewed by them." -def read_memories(store: Store, question: str, limit: int = 7) -> dict: +def read_memories(store: Store, question: str, limit: int = 7, relevance: retrieve.Relevance = retrieve.overlap) -> dict: """Memories relevant to a question, under the one read policy.""" limit = max(1, min(limit, 20)) - result = retrieve.search(store.list(), question, limit) + result = retrieve.search(store.list(), question, limit, relevance) store.log_read(len(result.memories), result.withheld) response = { "memories": [ @@ -56,7 +56,7 @@ def propose_memory(store: Store, text: str, quote: str, category: str = "other") return {"stored": True, "id": memory.id, "new": created, "state": State.UNCONFIRMED.value} -def build_server(store: Store): +def build_server(store: Store, relevance: retrieve.Relevance = retrieve.overlap): try: from mcp.server.fastmcp import FastMCP except ImportError as exc: # pragma: no cover - exercised only without the extra @@ -67,7 +67,7 @@ def build_server(store: Store): @server.tool() def personakit_read(question: str, limit: int = 7) -> dict: """Read the owner's memories relevant to a question. Unconfirmed ones are labelled.""" - return read_memories(store, question, limit) + return read_memories(store, question, limit, relevance) @server.tool() def personakit_propose(text: str, quote: str, category: str = "other") -> dict: @@ -77,5 +77,5 @@ def personakit_propose(text: str, quote: str, category: str = "other") -> dict: return server -def serve(store: Store) -> None: - build_server(store).run() +def serve(store: Store, relevance: retrieve.Relevance = retrieve.overlap) -> None: + build_server(store, relevance).run() diff --git a/personakit/plugins.py b/personakit/plugins.py new file mode 100644 index 0000000..66103d3 --- /dev/null +++ b/personakit/plugins.py @@ -0,0 +1,58 @@ +"""Extension points: swap how relevance is scored, nothing else. + +A plugin is a Python package you installed that registers an entry point in the +`personakit.plugins` group. The entry point is a function that receives a `Hooks` object and +replaces the scoring function it provides. Nothing is loaded unless you name it in the +PERSONAKIT_PLUGINS environment variable (comma separated), so installing a package never +changes how PersonaKit behaves by itself. + +A plugin only scores. Which memories may be served and every state change stay in `retrieve` +and `store`. A plugin is still code running as you, with access to +your store file: enable only ones you trust. +""" + +from __future__ import annotations + +import os +from collections.abc import Callable, Iterable +from dataclasses import dataclass +from importlib.metadata import EntryPoint, entry_points + +from personakit import retrieve + +GROUP = "personakit.plugins" +ENABLE_ENV = "PERSONAKIT_PLUGINS" + + +class PluginError(Exception): + """A plugin that was asked for could not be used.""" + + +@dataclass +class Hooks: + """The functions a plugin may replace. The default is the built-in word-based one.""" + + relevance: retrieve.Relevance = retrieve.overlap # (question, memories) -> one score per memory + + +def enabled_names() -> list[str]: + return [name.strip() for name in os.environ.get(ENABLE_ENV, "").split(",") if name.strip()] + + +def load( + names: Iterable[str] | None = None, + discover: Callable[[], Iterable[EntryPoint]] = lambda: entry_points(group=GROUP), +) -> Hooks: + """Hooks with every named plugin applied, in the order named. No names, no plugins.""" + hooks = Hooks() + wanted = enabled_names() if names is None else list(names) + if not wanted: + return hooks + installed = {point.name: point for point in discover()} + for name in wanted: + if name not in installed: + raise PluginError(f"plugin {name!r} is named in {ENABLE_ENV} but is not installed") + installed[name].load()(hooks) + if not all(callable(hook) for hook in vars(hooks).values()): + raise PluginError("a plugin replaced a hook with something that cannot be called") + return hooks diff --git a/personakit/retrieve.py b/personakit/retrieve.py index 192ad2a..66855a2 100644 --- a/personakit/retrieve.py +++ b/personakit/retrieve.py @@ -10,7 +10,7 @@ from __future__ import annotations import re -from collections.abc import Iterable +from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass from personakit.model import Memory, State @@ -42,20 +42,30 @@ def words(text: str) -> set[str]: return {w for w in _WORD.findall(text.lower()) if w not in _STOP} -def search(memories: Iterable[Memory], question: str, limit: int = 7) -> Result: +def overlap(question: str, memories: Sequence[Memory]) -> list[float]: + """The built-in relevance: how many words of the question each memory shares.""" asked = words(question) + return [float(len(asked & words(m.text + " " + m.category))) for m in memories] + + +Relevance = Callable[[str, Sequence[Memory]], Sequence[float]] + + +def search(memories: Iterable[Memory], question: str, limit: int = 7, relevance: Relevance = overlap) -> Result: + """Apply the read policy. `relevance` only orders memories (above 0 means relevant); what may + be served is decided here and cannot be widened by it.""" + memories = list(memories) scored, standing, withheld = [], [], 0 - for memory in memories: - overlap = len(asked & words(memory.text + " " + memory.category)) + for memory, score in zip(memories, relevance(question, memories), strict=True): if memory.state == State.RESTRICTED: - withheld += overlap > 0 + withheld += score > 0 elif memory.state in SERVED: - if overlap: - scored.append((overlap, memory)) + if score > 0: + scored.append((score, memory)) elif memory.state == State.APPROVED: standing.append(memory) - # Best overlap first; approved before unconfirmed; then oldest first for a stable order. + # Most relevant first; approved before unconfirmed; then oldest first for a stable order. scored.sort(key=lambda s: (-s[0], s[1].state != State.APPROVED, s[1].created_at or "", s[1].id)) chosen = [memory for _, memory in scored][:limit] fill = min(limit, STANDING_CONTEXT) - len(chosen) diff --git a/tests/test_cli.py b/tests/test_cli.py index aded799..ccc9143 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -106,6 +106,12 @@ def complete(self, prompt): self.assertEqual(code, 1) self.assertIn("Not logged in", out) + def test_naming_a_plugin_that_is_not_installed_fails_clearly(self): + with mock.patch.dict("os.environ", {"PERSONAKIT_PLUGINS": "not-installed"}): + code, _, err = self.run_cli("serve") + self.assertEqual(code, 2) + self.assertIn("not-installed", err) + def test_db_defaults_to_environment_variable(self): with mock.patch.dict("os.environ", {"PERSONAKIT_DB": str(self.db)}): self.assertEqual(cli.default_db(), self.db) diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..3237b69 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,92 @@ +import unittest +from unittest import mock + +from personakit import mcp_server, plugins, retrieve +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import Store + + +class FakePoint: + """Stands in for an installed entry point.""" + + def __init__(self, name, register): + self.name, self._register = name, register + + def load(self): + return self._register + + +def everything_matches(question, memories): + return [1.0] * len(memories) + + +def use_everything_matches(hooks): + hooks.relevance = everything_matches + + +INSTALLED = [FakePoint("match-all", use_everything_matches), FakePoint("other", lambda hooks: None)] + + +def mem(text, session="s1", turn=0, state=State.UNCONFIRMED): + return Memory( + text=text, + category="other", + state=state, + decided_by=Decider.OWNER if state != State.UNCONFIRMED else None, + evidence=(Evidence(session, turn, "invented"),), + ) + + +class LoadTest(unittest.TestCase): + def load(self, names): + return plugins.load(names, discover=lambda: INSTALLED) + + def test_nothing_is_loaded_unless_named(self): + self.assertIs(self.load([]).relevance, retrieve.overlap) + + def test_installed_but_unnamed_plugins_stay_off(self): + self.assertIs(self.load(["other"]).relevance, retrieve.overlap) + + def test_named_plugins_replace_what_they_provide(self): + self.assertIs(self.load(["match-all", "other"]).relevance, everything_matches) + + def test_naming_a_missing_plugin_is_an_error_not_a_silent_fallback(self): + with self.assertRaises(plugins.PluginError): + self.load(["not-installed"]) + + def test_a_plugin_that_breaks_a_hook_is_refused(self): + broken = [FakePoint("broken", lambda hooks: setattr(hooks, "relevance", None))] + with self.assertRaises(plugins.PluginError): + plugins.load(["broken"], discover=lambda: broken) + + def test_names_come_from_the_environment(self): + with mock.patch.dict("os.environ", {plugins.ENABLE_ENV: " match-all , ,other "}): + self.assertEqual(plugins.enabled_names(), ["match-all", "other"]) + with mock.patch.dict("os.environ", {plugins.ENABLE_ENV: ""}): + self.assertIs(plugins.load().relevance, retrieve.overlap) + + +class PolicyStaysInCoreTest(unittest.TestCase): + """A plugin scores; it cannot widen what is served.""" + + def setUp(self): + self.store = Store(":memory:") + self.addCleanup(self.store.close) + + def test_relevance_plugin_cannot_serve_restricted_or_archived_memories(self): + for text, state in ( + ("You like tea in the morning.", State.APPROVED), + ("You keep a private diary.", State.RESTRICTED), + ("You once used an old editor.", State.ARCHIVED), + ): + memory = mem(text) + self.store.add(memory) + if state != State.UNCONFIRMED: + self.store.set_state(memory.id, state, Decider.OWNER) + result = mcp_server.read_memories(self.store, "unrelated question", relevance=everything_matches) + self.assertEqual([m["text"] for m in result["memories"]], ["You like tea in the morning."]) + self.assertEqual(result["withheld"], 1) + + +if __name__ == "__main__": + unittest.main()