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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
the limit.
- Owner-written `answers` and `applies_when` on a memory, set with `personakit hints`. They
help ranking and are never sent to assistants. Existing stores upgrade in place.
- A third extension point, `select`: once per read, after the read policy, a plugin may narrow
the relevant servable memories to fewer. It cannot add memories or change their order, and
never sees restricted or archived ones. It is told the name the assistant connected with.

## 0.2.0

Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ flowchart TB
| `decay` | Finds unconfirmed memories not seen again for a long time (90 days by default). Pure functions. | `model` |
| `tidy` | Turns `twins` and `decay` into a plan (read-only), applies it only on request, and reverses single steps. | `twins`, `decay`, `store` |
| `digest` | A summary of the last days: new, merged and archived memories, what awaits review, read counts. Prints memory text, never quotes, to your terminal only. | `store`, `decay` |
| `plugins` | Two extension points, `relevance` and `similarity`, loaded only when the owner names a plugin in `PERSONAKIT_PLUGINS`. A plugin scores; policy stays in `retrieve`, `twins` and `store`. See [PLUGINS.md](PLUGINS.md). | `retrieve`, `twins` |
| `plugins` | Three extension points, `relevance`, `similarity` and `select`, loaded only when the owner names a plugin in `PERSONAKIT_PLUGINS`. A plugin scores, or narrows a read to fewer of the memories the policy allows; policy stays in `retrieve`, `twins` and `store`. See [PLUGINS.md](PLUGINS.md). | `retrieve`, `twins` |
| `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
8 changes: 6 additions & 2 deletions docs/PLUGINS.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
# Plugins

PersonaKit has two extension points. Both replace a scoring function and nothing else.
PersonaKit has three extension points. Two replace a scoring function; the third may narrow a
read to fewer memories. None can do anything else.

| Hook | Signature | Built-in | Used by |
|---|---|---|---|
| `relevance` | `(question: str, memories: Sequence[Memory]) -> Sequence[float]` | word overlap (text, category and the owner's hints) | `personakit serve` (which memories answer a question, and in what order; when the assistant states a context it is called a second time with that text, and each memory keeps its higher score) |
| `similarity` | `(a: str, b: str) -> float` between 0 and 1 | shared words, with number, negation and order guards | `personakit tidy` (which memories are twins) |
| `select` | `(question: str, context: str, memories: Sequence[Memory], client: str) -> Sequence[Memory] \| None` | none (off) | `personakit serve`, once per read, after the read policy: it sees only the relevant memories that may be served, best first, and the name the assistant connected with (`""` when unknown). It returns the ones to serve, or `None` to leave the read as it is |

## 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.
policy already allows, and `select` never sees them.
- `select` can only narrow. A memory it returns that it was not offered is ignored, the order of
what is served stays the core's, and the limit still applies.
- Only unconfirmed memories with the same category and scope, none resting on an assistant's
proposal, can be proposed as twins, and only when they mention the same numbers and agree on
negation. Merging still needs `personakit tidy --apply` and is reversible.
Expand Down
5 changes: 3 additions & 2 deletions docs/PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,6 @@
- **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 or similarity is scored and cannot change what is served or what may be merged, but it is code you installed, running
as you. What it does with your data is up to that plugin; read it first.
how relevance or similarity is scored, or narrows a read to fewer of the memories the core already allows, and cannot widen
what is served or what may be merged, but it is code you installed, running as you. A `select` plugin receives the text of
the memories it is offered and may send it wherever its code does: check what yours does before enabling it. 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 @@ -32,3 +32,4 @@ duplicated logic. Each entry records the result.
| `personakit/twins.py`; `store.py`, `tidy.py`, `digest.py`, `cli.py`, `model.py`, `review.py`, `mcp_server.py`, `retrieve.py` (changes) | 2026-11-14 | none; written for this repository, word-based only, thresholds chosen from invented examples. Migration 4 adds `merged_into` and `merge_vetoes`; a folded memory keeps its own rows, so forget leaves nothing behind. Security and code review findings fixed, each with a regression test | clean |
| `tests/test_twins.py`, `test_merge_store.py`; `test_tidy.py`, `test_cli.py`, `test_digest.py` (changes) | 2026-11-14 | invented sentences only | clean |
| `personakit/twins.py`, `plugins.py`, `cli.py` (changes); `tests/test_twins.py`, `test_plugins.py` | 2026-11-16 | none; twins are compared across sessions, a `similarity` hook is added, and numbers and negation must agree whatever scores a pair. Invented sentences only | clean |
| `personakit/retrieve.py`, `plugins.py`, `mcp_server.py`, `cli.py` (changes); `tests/test_retrieve.py`, `test_plugins.py`, `test_mcp_server.py`; `docs/PLUGINS.md`, `ARCHITECTURE.md`, `PRIVACY.md` | 2026-11-24 | none; a `select` hook that may only narrow a read, never sees restricted or archived memories, and hears the assistant's self-reported name. Invented sentences only | clean |
3 changes: 2 additions & 1 deletion personakit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int:
return 1
print("Forgotten.")
elif args.command == "serve":
mcp_server.serve(store, plugins.load().relevance)
hooks = plugins.load()
mcp_server.serve(store, hooks.relevance, hooks.select)
return 0


Expand Down
27 changes: 22 additions & 5 deletions personakit/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ def read_memories(
include_evidence: bool = False,
include_seen: bool = False,
seen: set[str] | None = None,
select: retrieve.Select | None = None,
client: str = "",
) -> dict:
"""Memories relevant to a question, under the one read policy.

Expand All @@ -34,7 +36,7 @@ def read_memories(
in full are added to it. With no set, every memory is sent in full.
"""
limit = max(1, min(limit, 20))
result = retrieve.search(store.list(), question, limit, relevance, context, scope)
result = retrieve.search(store.list(), question, limit, relevance, context, scope, select, client)
store.log_read(len(result.memories), result.withheld)
items, full = [], []
for m in result.memories:
Expand Down Expand Up @@ -74,7 +76,9 @@ 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, relevance: retrieve.Relevance = retrieve.overlap):
def build_server(
store: Store, relevance: retrieve.Relevance = retrieve.overlap, select: retrieve.Select | None = None
):
try:
from mcp.server.fastmcp import FastMCP
except ImportError as exc: # pragma: no cover - exercised only without the extra
Expand Down Expand Up @@ -104,7 +108,10 @@ def personakit_read(
it, ask again with include_seen. Ask for evidence only when you need the owner's own words.
`scope` (optional) limits the read to one project's memories plus general ones.
"""
return read_memories(store, question, limit, relevance, context, scope, include_evidence, include_seen, sent)
return read_memories(
store, question, limit, relevance, context, scope, include_evidence, include_seen, sent,
select, _client_name(server),
)

@server.tool()
def personakit_propose(text: str, quote: str, category: str = "other") -> dict:
Expand All @@ -114,5 +121,15 @@ def personakit_propose(text: str, quote: str, category: str = "other") -> dict:
return server


def serve(store: Store, relevance: retrieve.Relevance = retrieve.overlap) -> None:
build_server(store, relevance).run()
def _client_name(server) -> str:
"""The name the assistant gave when it connected ("claude-code", for example), "" when unknown."""
try:
return str(server.get_context().session.client_params.clientInfo.name or "")
except (AttributeError, LookupError, ValueError):
return ""


def serve(
store: Store, relevance: retrieve.Relevance = retrieve.overlap, select: retrieve.Select | None = None
) -> None:
build_server(store, relevance, select).run()
8 changes: 5 additions & 3 deletions personakit/plugins.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Extension points: swap how relevance and similarity are scored, nothing else.
"""Extension points: swap how relevance and similarity are scored, and narrow a read, 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 functions 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, which may be merged, and every state change
A plugin only scores, or narrows a read to fewer of the memories the core already chose to serve
(`select`). Which memories may be served, which may be merged, and every state change
stay in `retrieve`, `twins` and `store`. A plugin is still code running as you, with access to
your store file: enable only ones you trust.
"""
Expand Down Expand Up @@ -34,6 +35,7 @@ class Hooks:

relevance: retrieve.Relevance = retrieve.overlap # (question, memories) -> one score per memory
similarity: twins.Similarity = twins.similarity # (text, text) -> 0 to 1
select: retrieve.Select | None = None # (question, context, servable memories, assistant) -> fewer, or None


def enabled_names() -> list[str]:
Expand All @@ -54,6 +56,6 @@ def load(
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 callable(hooks.relevance) or not callable(hooks.similarity):
if not callable(hooks.relevance) or not callable(hooks.similarity) or not (hooks.select is None or callable(hooks.select)):
raise PluginError("a plugin replaced a hook with something that cannot be called")
return hooks
21 changes: 19 additions & 2 deletions personakit/retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ def overlap(question: str, memories: Sequence[Memory]) -> list[float]:


Relevance = Callable[[str, Sequence[Memory]], Sequence[float]]
# (question, context, the relevant servable memories best first, the assistant's name) -> the ones
# to serve, or None to leave the read as it is. It may only narrow: see `search`.
Select = Callable[[str, str, Sequence[Memory], str], "Sequence[Memory] | None"]


def search(
Expand All @@ -61,13 +64,21 @@ def search(
relevance: Relevance = overlap,
context: str = "",
scope: str = "",
select: Select | None = None,
client: str = "",
) -> 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.

`context` is what the assistant is about to do. It is scored like a second question and a
memory keeps the better of its two scores, so the hook itself never changes. With a `scope`,
only memories of that scope or "global" ones are considered at all.

`select`, when given, sees only the memories that may be served and are relevant, best first,
once per read, with the question, the context and the assistant's name (`client`, "" when
unknown). It may only narrow them: whatever it returns that was not offered is ignored, the
order stays this one, and None leaves the read unchanged. Restricted and archived memories
never reach it.
"""
memories = [m for m in memories if not scope or m.scope in ("global", scope)]
scores = list(relevance(question, memories))
Expand All @@ -84,8 +95,14 @@ def search(

# 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]
return Result(chosen, withheld, len(scored) - len(chosen))
ranked = [memory for _, memory in scored]
if select is not None and ranked:
picked = select(question, context, tuple(ranked), client)
if picked is not None:
keep = {m.id for m in picked}
ranked = [m for m in ranked if m.id in keep]
chosen = ranked[:limit]
return Result(chosen, withheld, len(ranked) - len(chosen))


def served_quote(quote: str) -> str:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,29 @@ def read(server, **args):
self.assertIn("evidence", read(server, include_evidence=True))
self.assertIn("text", read(mcp_server.build_server(store)))

def test_select_hears_the_name_the_assistant_connected_with(self):
from mcp import types
from mcp.shared.memory import create_connected_server_and_client_session

store = Store(":memory:")
self.addCleanup(store.close)
seed(store)
heard = []

def select(question, context, memories, client):
heard.append(client)
return None

server = mcp_server.build_server(store, select=select)

async def run():
info = types.Implementation(name="claude-code", version="1.0")
async with create_connected_server_and_client_session(server._mcp_server, client_info=info) as session:
await session.call_tool("personakit_read", {"question": "feedback"})

asyncio.run(run())
self.assertEqual(heard, ["claude-code"])


if __name__ == "__main__":
unittest.main()
17 changes: 16 additions & 1 deletion tests/test_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,15 @@ def use_always_twins(hooks):
hooks.similarity = lambda a, b: 1.0


INSTALLED = [FakePoint("match-all", use_everything_matches), FakePoint("twin-all", use_always_twins)]
def use_keep_first(hooks):
hooks.select = lambda question, context, memories, client: memories[:1]


INSTALLED = [
FakePoint("match-all", use_everything_matches),
FakePoint("twin-all", use_always_twins),
FakePoint("keep-first", use_keep_first),
]


def mem(text, session="s1", turn=0, state=State.UNCONFIRMED):
Expand All @@ -49,6 +57,7 @@ def test_nothing_is_loaded_unless_named(self):
hooks = self.load([])
self.assertIs(hooks.relevance, retrieve.overlap)
self.assertIs(hooks.similarity, twins.similarity)
self.assertIsNone(hooks.select)

def test_installed_but_unnamed_plugins_stay_off(self):
self.assertIs(self.load(["twin-all"]).relevance, retrieve.overlap)
Expand All @@ -67,6 +76,12 @@ def test_a_plugin_that_breaks_a_hook_is_refused(self):
with self.assertRaises(plugins.PluginError):
plugins.load(["broken"], discover=lambda: broken)

def test_a_select_hook_is_loaded_and_a_broken_one_refused(self):
self.assertTrue(callable(self.load(["keep-first"]).select))
broken = [FakePoint("broken", lambda hooks: setattr(hooks, "select", "not callable"))]
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 , ,twin-all "}):
self.assertEqual(plugins.enabled_names(), ["match-all", "twin-all"])
Expand Down
50 changes: 50 additions & 0 deletions tests/test_retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,56 @@ def test_stop_words_alone_do_not_match(self):
self.assertEqual(search([mem("You prefer the quiet.")], "what should the").memories, [])


class SelectTest(unittest.TestCase):
"""A select hook sees only what may be served, once per read, and can only narrow it."""

def setUp(self):
self.a = mem("You use Python and Rust for data pipelines.")
self.b = mem("You use Python for data work.")
self.c = mem("You use Python at home.", state=State.APPROVED)
self.restricted = mem("You use Python for a secret project.", state=State.RESTRICTED)
self.archived = mem("You used Python for data long ago.", state=State.ARCHIVED)
self.calls = []

def search(self, picked, **kw):
def select(question, context, memories, client):
self.calls.append((question, context, list(memories), client))
return picked(memories) if callable(picked) else picked
pool = [self.a, self.b, self.c, self.restricted, self.archived]
return search(pool, "python data pipelines", select=select, **kw)

def test_select_sees_only_relevant_servable_memories_best_first_once(self):
self.search(None, context="writing a script", client="claude-code")
self.assertEqual(len(self.calls), 1)
question, context, offered, client = self.calls[0]
self.assertEqual((question, context, client), ("python data pipelines", "writing a script", "claude-code"))
self.assertEqual(offered[0], self.a)
self.assertNotIn(self.restricted, offered)
self.assertNotIn(self.archived, offered)

def test_none_leaves_the_read_unchanged(self):
self.assertEqual(self.search(None).memories, search([self.a, self.b, self.c], "python data pipelines").memories)

def test_select_narrows_and_the_order_stays_the_cores(self):
result = self.search(lambda offered: [offered[2], offered[0]])
offered = self.calls[0][2]
self.assertEqual(result.memories, [offered[0], offered[2]])

def test_select_cannot_widen(self):
result = self.search([self.b, self.restricted, self.archived, mem("You use Go.")])
self.assertEqual(result.memories, [self.b])
self.assertEqual(result.withheld, 1)

def test_an_empty_selection_serves_nothing_and_more_counts_after_it(self):
self.assertEqual(self.search([]).memories, [])
result = self.search(lambda offered: offered[:2], limit=1)
self.assertEqual((len(result.memories), result.more), (1, 1))

def test_no_relevant_memory_means_select_is_not_called(self):
search([self.a], "unrelated words entirely", select=lambda *a: self.calls.append(a))
self.assertEqual(self.calls, [])


class ServedQuoteTest(unittest.TestCase):
def test_served_quotes_mask_emails_and_end_at_a_word_boundary(self):
self.assertEqual(retrieve.served_quote("write to me at someone@example.com please"),
Expand Down
Loading