Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,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
Expand Down
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ flowchart TB
| `decay` | Finds unconfirmed memories not seen again for a long time (90 days by default). Pure functions. | `model` |
| `tidy` | Turns `decay` into a plan (read-only), applies it only on request, and reverses single steps. | `decay`, `store` |
| `digest` | A summary of the last days: new and archived memories, what awaits review, read counts. Prints memory text, never quotes, to your terminal only. | `store`, `decay` |
| `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 |

Expand Down
51 changes: 51 additions & 0 deletions docs/PLUGINS.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions docs/PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@
here calls a model, and assistants cannot archive or restore.
- **Digest:** `personakit digest` prints memory ids and text (never evidence quotes) to your
terminal. Unlike `stats` it is not counts-only, so look before pasting it anywhere.
- **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.
1 change: 1 addition & 0 deletions docs/REVIEW-LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ duplicated logic. Each entry records the result.
| `personakit/decay.py`, `tidy.py`; `store.py`, `model.py`, `mcp_server.py`, `cli.py` (changes) | 2026-11-14 | none; migration 3 adds `last_seen_at`; an assistant proposal cannot revive or refresh a memory. Checked on a copy of a real store: upgrade, archive, undo and reads behave as documented | clean |
| `tests/test_decay.py`, `test_store_decay.py`, `test_tidy.py`; `test_cli.py`, `test_mcp_server.py` (changes) | 2026-11-14 | invented sentences only | clean |
| `personakit/digest.py`, `tests/test_digest.py`; `store.py`, `cli.py` (changes) | 2026-11-14 | none; local output only, text without quotes; invented test data | 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 |
10 changes: 7 additions & 3 deletions personakit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import sys
from pathlib import Path

from personakit import decay, digest, llm, mcp_server, review, stats, sweep, tidy
from personakit import decay, digest, llm, mcp_server, plugins, review, stats, sweep, tidy
from personakit.ingest import ADAPTERS
from personakit.model import State
from personakit.store import Store
Expand Down Expand Up @@ -69,7 +69,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:
Expand Down Expand Up @@ -115,7 +119,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


Expand Down
12 changes: 6 additions & 6 deletions personakit/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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()
58 changes: 58 additions & 0 deletions personakit/plugins.py
Original file line number Diff line number Diff line change
@@ -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
26 changes: 18 additions & 8 deletions personakit/retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,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)
Expand Down
92 changes: 92 additions & 0 deletions tests/test_plugins.py
Original file line number Diff line number Diff line change
@@ -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()
Loading