From b81430dc93be8e386aee5c2eeb523494fe7e746c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 09:53:20 +0000 Subject: [PATCH 1/2] Serve only relevant memories in a small packet - retrieve.search: drop the standing fill (nothing relevant, nothing served); optional context scored like a second question (element-wise maximum, relevance hook unchanged); optional scope (that scope and "global" only); Result.more counts relevant memories cut by the limit. - read_memories / personakit_read: evidence only with include_evidence; a memory already sent by this server process comes back as its id only unless include_seen (or include_evidence); "more" in the response; assistant-facing docstring rewritten. - Memory.answers and Memory.applies_when: owner-written hints, stored as JSON lists (new migration, existing stores keep their data), counted by word overlap, never served. New `personakit hints` command. - README, ARCHITECTURE, PRIVACY and PLUGINS describe the new behaviour. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- README.md | 9 ++-- docs/ARCHITECTURE.md | 10 +++-- docs/PLUGINS.md | 2 +- docs/PRIVACY.md | 10 +++-- personakit/cli.py | 27 ++++++++++++ personakit/mcp_server.py | 82 ++++++++++++++++++++++++++---------- personakit/model.py | 6 +++ personakit/retrieve.py | 54 +++++++++++++++--------- personakit/store.py | 39 +++++++++++++++++- tests/test_cli.py | 19 +++++++++ tests/test_mcp_server.py | 89 ++++++++++++++++++++++++++++++++++++++-- tests/test_retrieve.py | 61 ++++++++++++++++++++++----- tests/test_store.py | 44 ++++++++++++++++++++ 13 files changed, 383 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 42eb00d..7a89b8e 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ personakit tidy --apply # carry the personakit merges # list what was folded, with ids personakit undo # reverse one fold or one stale archive personakit digest # what changed in the last 7 days (local, prints memory text) +personakit hints --answers "" # help the right question find a memory (never sent to assistants) personakit serve # MCP server over stdio for your assistants personakit forget # delete a memory and its quotes for good ``` @@ -90,7 +91,7 @@ Your assistant gets two tools: | Tool | What it does | |---|---| -| `personakit_read` | Returns the memories relevant to a question, each with its evidence quotes and whether you have confirmed it. | +| `personakit_read` | Returns only the memories relevant to a question (and, if the assistant says, to what it is about to do), each with whether you have confirmed it. Nothing relevant means an empty answer. Evidence quotes are sent only when the assistant asks for them, and a memory already sent in the same session comes back as its id only. | | `personakit_propose` | Lets the assistant suggest a new memory. It is stored as *unconfirmed* until you review it. | ## How it works @@ -105,7 +106,8 @@ Your assistant gets two tools: 3. **Store** keeps each memory with its source quote, a state, and a scope. 4. **Review** is optional. Memories you never review are served marked *unconfirmed*; you can approve, restrict, hide or forget any of them at any time. -5. **Serve** exposes the store to assistants over MCP, with the evidence attached. +5. **Serve** exposes the store to assistants over MCP: a small packet of relevant memories, with + evidence on request. 6. **Tidy** (on request) folds near-identical memories into one, and archives unconfirmed memories not seen again for 90 days. It shows a plan first; nothing changes without `--apply`, nothing is deleted, and `personakit undo ` reverses a step. @@ -125,7 +127,8 @@ Stated plainly, so you know what you are installing: - **Extraction is a model's guess.** Review is how you correct it. - **Ranking is word overlap**, on whole words in Latin letters and digits. Questions and memories - in other scripts are not matched yet; approved memories are still returned as standing context. + in other scripts are not matched yet, so such a question gets an empty answer. `personakit hints` + lets you add the questions and situations a memory is for, which counts towards matching. - **A decision cannot be changed, only undone by forgetting.** `review` shows unconfirmed memories; there is no command yet to edit a memory's wording or move a decided memory to another state. - **Twin detection compares words, not meaning.** It folds memories phrased almost the same way, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 69455c5..94badd7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,10 +42,10 @@ flowchart TB | `llm` | One interface, `complete(prompt) -> str`, implemented by two CLI-backed clients (`claude`, `codex`). The per-run call budget lives here. | nothing | | `extract` | Builds the prompt from owner turns, validates the reply into `Memory` + `Evidence`, and counts what it rejects and why. | `model`, `llm` | | `sweep` | Runs ingest, extract and store over new sessions. Skips unchanged files, stops only on budget or model error, never because unreviewed memories are piling up. | `ingest`, `extract`, `llm`, `store` | -| `retrieve` | The one read policy: approved and unconfirmed memories are served, restricted and archived never are. It also shapes the evidence quotes an assistant receives (email addresses masked, cut at a word boundary). Word-overlap ranking, a baseline to be measured. | `model` | +| `retrieve` | The one read policy: approved and unconfirmed memories are served, restricted and archived never are, and only relevant ones (nothing relevant, nothing served). A read may name a scope (that scope and `global` only) and a context (scored like a second question). It also shapes the evidence quotes an assistant receives (email addresses masked, cut at a word boundary). Word-overlap ranking, a baseline to be measured. | `model` | | `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` | +| `mcp_server` | Two tools for assistants: `personakit_read` and `personakit_propose`. Holds no read-policy constants of its own. Shapes the packet: evidence only on request, and a memory already sent by this server process comes back as its id only (kept in memory, never stored). Assistants cannot approve, restrict, hide or forget; only the owner can, in `review`. | `store`, `retrieve`, `extract` | | `twins` | Finds near-identical unconfirmed memories of one category and scope, across sessions. Word-based, deliberately cautious (the order of shared words must agree); numbers and negation must agree whatever scores a pair. Pure functions. | `model`, `retrieve` | | `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` | @@ -60,8 +60,10 @@ model, only `ingest` reads session files.** A second implementation of any of th ## Data model - **Turn**: `(source, session_id, index, timestamp, text)`. Only owner-authored turns exist here. -- **Memory**: `id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by`. - `last_seen_at` moves forward each time the same statement is extracted again. +- **Memory**: `id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by, + answers, applies_when`. `last_seen_at` moves forward each time the same statement is extracted + again. `answers` (questions it answers) and `applies_when` (situations it applies in) are written + by the owner with `personakit hints`; they count towards relevance and are never served. - **Merge**: a folded memory keeps its own row and evidence and points at the memory it was folded into (`merged_into`, `merged_at`). It is not listed or served on its own; the surviving memory shows the evidence of both. `undo` clears the pointer, so it is exact, and remembers the pair so diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index cd0954f..c7051b7 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -4,7 +4,7 @@ PersonaKit has two extension points. Both replace a scoring function and nothing | 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) | +| `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) | ## What a plugin cannot do diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 2d607b4..e58f620 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -9,10 +9,14 @@ name, through your own signed-in `claude` or `codex` CLI, under that provider's terms. Assistant replies, tool output and file contents from sessions are not sent. - **What assistants see:** only what the MCP server returns. Restricted and archived - memories are never returned; unconfirmed ones are labelled. The evidence quotes it returns are shortened to a word boundary and email - addresses in them are masked; the store itself keeps the quote as you wrote it. + memories are never returned; unconfirmed ones are labelled. Only memories relevant to the + assistant's question, or to what it says it is about to do, are returned. Evidence quotes are + returned only when the assistant asks for them; they are shortened to a word boundary and email + addresses in them are masked; the store itself keeps the quote as you wrote it. The hints you add + with `personakit hints` help ranking and are never returned. - **Read log:** each read stores the time and two counts (returned, withheld) in your local - store. The question and the memory text are not recorded. + store. The question, the assistant's stated context and the memory text are not recorded. The + server remembers which memory ids it has already sent, in memory only, until it stops. - **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. diff --git a/personakit/cli.py b/personakit/cli.py index 6f1c1fc..5915b61 100644 --- a/personakit/cli.py +++ b/personakit/cli.py @@ -61,6 +61,12 @@ def build_parser() -> argparse.ArgumentParser: digest_cmd.add_argument("--days", type=int, default=7) digest_cmd.add_argument("--json", action="store_true", help="print a JSON object") + hints = sub.add_parser("hints", help="show or set the questions a memory answers and when it applies") + hints.add_argument("memory_id") + hints.add_argument("--answers", action="append", metavar="QUESTION", help="a question it answers (repeat for more)") + hints.add_argument("--applies-when", action="append", metavar="SITUATION", help="a situation it applies in (repeat for more)") + hints.add_argument("--clear", action="store_true", help="remove both kinds of hint (before adding any given here)") + forget = sub.add_parser("forget", help="permanently delete a memory and its quotes") forget.add_argument("memory_id") @@ -119,6 +125,8 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: _print_json(collected) else: print(digest.format_digest(collected)) + elif args.command == "hints": + return _hints(args, store) elif args.command == "forget": if not store.forget(args.memory_id): print(f"No memory with id {args.memory_id}", file=sys.stderr) @@ -134,6 +142,25 @@ def _print_json(data: object) -> None: print(json.dumps(data, sort_keys=True, ensure_ascii=False)) +def _hints(args: argparse.Namespace, store: Store) -> int: + """Each kind of hint given replaces that kind; one not given is kept, unless --clear.""" + empty = [] if args.clear else None + try: + if args.clear or args.answers or args.applies_when: + memory = store.set_hints(args.memory_id, args.answers or empty, args.applies_when or empty) + else: + memory = store.get(args.memory_id) + if memory is None: + raise KeyError(args.memory_id) + except KeyError: + print(f"No memory with id {args.memory_id}", file=sys.stderr) + return 1 + print(memory.text) + for label, entries in (("answers", memory.answers), ("applies when", memory.applies_when)): + print(f" {label}: " + ("; ".join(entries) if entries else "(none)")) + return 0 + + def _tidy(args: argparse.Namespace, store: Store) -> int: if not 1 <= args.days <= MAX_DAYS or not 0 < args.threshold <= 1: print(f"--days must be between 1 and {MAX_DAYS} and --threshold between 0 and 1", file=sys.stderr) diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 98c9464..c4a8e0d 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -12,28 +12,47 @@ from personakit.store import Store 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, relevance: retrieve.Relevance = retrieve.overlap) -> dict: - """Memories relevant to a question, under the one read policy.""" +NOTE_SEEN = "Entries marked seen were sent earlier in this session. If you no longer have them, ask again with include_seen." +EVIDENCE_QUOTES = 2 + + +def read_memories( + store: Store, + question: str, + limit: int = 7, + relevance: retrieve.Relevance = retrieve.overlap, + context: str = "", + scope: str = "", + include_evidence: bool = False, + include_seen: bool = False, + seen: set[str] | None = None, +) -> dict: + """Memories relevant to a question, under the one read policy. + + `seen` holds the ids already sent in full during this session. A memory in it comes back as + its id only, unless `include_seen`, or `include_evidence` (the quotes would be new). Ids sent + 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) + result = retrieve.search(store.list(), question, limit, relevance, context, scope) store.log_read(len(result.memories), result.withheld) - response = { - "memories": [ - { - "id": m.id, - "text": m.text, - "category": m.category, - "confirmed": m.state == State.APPROVED, - "evidence": [retrieve.served_quote(e.quote) for e in m.evidence[:2]], - } - for m in result.memories - ], - "withheld": result.withheld, - } - if any(m.state != State.APPROVED for m in result.memories): + items, full = [], [] + for m in result.memories: + if seen is not None and m.id in seen and not (include_seen or include_evidence): + items.append({"id": m.id, "seen": True}) + continue + item = {"id": m.id, "text": m.text, "category": m.category, "confirmed": m.state == State.APPROVED} + if include_evidence: + item["evidence"] = [retrieve.served_quote(e.quote) for e in m.evidence[:EVIDENCE_QUOTES]] + items.append(item) + full.append(m) + if seen is not None: + seen.add(m.id) + response = {"memories": items, "withheld": result.withheld, "more": result.more} + if any(m.state != State.APPROVED for m in full): response["note"] = NOTE_UNCONFIRMED + if len(full) < len(items): + response["seen_note"] = NOTE_SEEN return response @@ -63,10 +82,29 @@ def build_server(store: Store, relevance: retrieve.Relevance = retrieve.overlap) server = FastMCP("personakit") + # One server process serves one assistant session, so what it has already sent lives here, + # in memory only. It is never written to the store. + sent: set[str] = set() + @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, relevance) + def personakit_read( + question: str, + context: str = "", + scope: str = "", + limit: int = 7, + include_evidence: bool = False, + include_seen: bool = False, + ) -> dict: + """Read what the owner has said that is relevant to one focused question. + + Ask before you act, one focused question at a time, and say in `context` what you are + about to do. An empty `memories` list means nothing relevant is known. `more` counts + relevant memories left out by `limit`. Unconfirmed memories are labelled and may be wrong. + An entry with only `seen: true` was sent earlier in this session; if you no longer have + 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) @server.tool() def personakit_propose(text: str, quote: str, category: str = "other") -> dict: diff --git a/personakit/model.py b/personakit/model.py index 0a28015..1ac95ec 100644 --- a/personakit/model.py +++ b/personakit/model.py @@ -76,6 +76,10 @@ class Memory: decided_at: str | None = None decided_by: Decider | None = None last_seen_at: str | None = None # last time the same statement was extracted again + # Written by the owner to help the right question find this memory. Used for ranking only; + # never sent to an assistant. + answers: tuple[str, ...] = () # questions this memory answers + applies_when: tuple[str, ...] = () # situations it applies in def __post_init__(self) -> None: if not self.text.strip(): @@ -95,6 +99,8 @@ def as_dict(self) -> dict[str, object]: "text": self.text, "quotes": len(self.evidence), "created_at": self.created_at, + "answers": list(self.answers), + "applies_when": list(self.applies_when), } diff --git a/personakit/retrieve.py b/personakit/retrieve.py index 3803304..60b2016 100644 --- a/personakit/retrieve.py +++ b/personakit/retrieve.py @@ -4,7 +4,8 @@ to an assistant. Approved and unconfirmed memories are served (unconfirmed ones are labelled as such); restricted and archived memories are never served. -Ranking is word overlap. It is a deliberately simple baseline, not a finished retriever. +Only relevant memories are served: when nothing matches, the answer is empty. Ranking is word +overlap. It is a deliberately simple baseline, not a finished retriever. """ from __future__ import annotations @@ -17,10 +18,6 @@ SERVED = (State.APPROVED, State.UNCONFIRMED) -# When fewer than this many memories match the question, approved ones fill the rest, so an -# assistant always gets the owner's confirmed standing preferences. -STANDING_CONTEXT = 3 - # Evidence quotes are shortened and email-masked before an assistant sees them. SERVED_QUOTE_CHARS = 240 _EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+") @@ -36,42 +33,59 @@ class Result: memories: list[Memory] withheld: int # matching memories the owner restricted, counted but never shown + more: int = 0 # further relevant, servable memories left out by the limit def words(text: str) -> set[str]: return {w for w in _WORD.findall(text.lower()) if w not in STOP_WORDS} +def about(memory: Memory) -> str: + """Everything a memory is about: its text, category and the owner's own hints.""" + return " ".join((memory.text, memory.category, *memory.answers, *memory.applies_when)) + + 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] + return [float(len(asked & words(about(m)))) 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: +def search( + memories: Iterable[Memory], + question: str, + limit: int = 7, + relevance: Relevance = overlap, + context: str = "", + scope: 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.""" - memories = list(memories) - scored, standing, withheld = [], [], 0 - for memory, score in zip(memories, relevance(question, memories), strict=True): + 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. + """ + memories = [m for m in memories if not scope or m.scope in ("global", scope)] + scores = list(relevance(question, memories)) + if context.strip(): + scores = [max(a, b) for a, b in zip(scores, relevance(context, memories), strict=True)] + scored, withheld = [], 0 + for memory, score in zip(memories, scores, strict=True): + if score <= 0: + continue if memory.state == State.RESTRICTED: - withheld += score > 0 + withheld += 1 elif memory.state in SERVED: - if score > 0: - scored.append((score, memory)) - elif memory.state == State.APPROVED: - standing.append(memory) + scored.append((score, memory)) # 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) - if fill > 0: - chosen.extend(sorted(standing, key=lambda m: (m.created_at or "", m.id))[:fill]) - return Result(chosen, withheld) + return Result(chosen, withheld, len(scored) - len(chosen)) def served_quote(quote: str) -> str: diff --git a/personakit/store.py b/personakit/store.py index 6c7b514..f48ea0e 100644 --- a/personakit/store.py +++ b/personakit/store.py @@ -6,6 +6,7 @@ from __future__ import annotations +import json import sqlite3 from collections.abc import Callable, Iterable from dataclasses import dataclass @@ -66,6 +67,12 @@ PRIMARY KEY (first_id, second_id) ); """, + # The owner's own hints: questions a memory answers and situations it applies in, each a JSON + # list of strings. Existing memories start with none. + """ + ALTER TABLE memories ADD COLUMN answers TEXT NOT NULL DEFAULT '[]'; + ALTER TABLE memories ADD COLUMN applies_when TEXT NOT NULL DEFAULT '[]'; + """, ] # A memory together with everything folded into it, directly or through another folded memory. @@ -135,8 +142,9 @@ def add(self, memory: Memory, observed: bool = True) -> bool: now = self._now() created = self._conn.execute( "INSERT OR IGNORE INTO memories" - " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by)" - " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by," + " answers, applies_when)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( memory.id, memory.text, @@ -147,6 +155,8 @@ def add(self, memory: Memory, observed: bool = True) -> bool: memory.last_seen_at or memory.created_at or now, memory.decided_at, memory.decided_by.value if memory.decided_by else None, + json.dumps(list(memory.answers)), + json.dumps(list(memory.applies_when)), ), ).rowcount == 1 self._conn.executemany( @@ -235,6 +245,23 @@ def set_state(self, memory_id: str, state: State, by: Decider) -> None: if changed == 0: raise KeyError(memory_id) + def set_hints( + self, memory_id: str, answers: Iterable[str] | None = None, applies_when: Iterable[str] | None = None + ) -> Memory: + """Replace the owner's hints on a memory; a field left as None is kept. Blank entries are + dropped. Its state and decision are untouched. Raises KeyError if unknown or folded.""" + current = self.get(memory_id) + if current is None: + raise KeyError(memory_id) + new_answers = current.answers if answers is None else _clean(answers) + new_applies = current.applies_when if applies_when is None else _clean(applies_when) + with self._conn: + self._conn.execute( + "UPDATE memories SET answers = ?, applies_when = ? WHERE id = ?", + (json.dumps(list(new_answers)), json.dumps(list(new_applies)), memory_id), + ) + return self.get(memory_id) + def forget(self, memory_id: str) -> bool: """Delete a memory and its evidence. Returns False if it did not exist. @@ -361,9 +388,17 @@ def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...], last_seen_at: str | decided_by=Decider(row["decided_by"]) if row["decided_by"] else None, last_seen_at=last_seen_at, evidence=evidence, + answers=tuple(json.loads(row["answers"])), + applies_when=tuple(json.loads(row["applies_when"])), ) +def _clean(entries: Iterable[str]) -> tuple[str, ...]: + """Hints as stored: whitespace collapsed, blanks and repeats dropped, order kept.""" + cleaned = (" ".join(entry.split()) for entry in entries) + return tuple(dict.fromkeys(entry for entry in cleaned if entry)) + + def _own_first(rows: Iterable[sqlite3.Row], memory_id: str) -> tuple[Evidence, ...]: """Evidence in session and turn order, one per turn, preferring the memory's own quote.""" unique: dict[tuple[str, int], Evidence] = {} diff --git a/tests/test_cli.py b/tests/test_cli.py index d3f57bd..e9b91ef 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -87,6 +87,25 @@ def test_json_outputs_are_structured_and_repeatable(self): self.assertEqual(json.loads(stats_out)["memories_unconfirmed"], 1) self.assertEqual(self.run_cli("stats", "--json")[1], stats_out) + def test_hints_can_be_shown_set_and_cleared(self): + self.db.parent.mkdir(parents=True) + with Store(self.db) as store: + memory = Memory(text="You prefer tabs.", category="tools", evidence=(Evidence("s", 0, "Tabs."),)) + store.add(memory) + code, out, _ = self.run_cli("hints", memory.id) + self.assertEqual((code, out), (0, "You prefer tabs.\n answers: (none)\n applies when: (none)\n")) + code, out, _ = self.run_cli("hints", memory.id, "--answers", "Tabs or spaces?", "--answers", "Indent style?", + "--applies-when", "editing Go code") + self.assertIn("answers: Tabs or spaces?; Indent style?", out) + _, out, _ = self.run_cli("hints", memory.id, "--applies-when", "writing scripts") + self.assertIn("answers: Tabs or spaces?; Indent style?\n applies when: writing scripts", out) + _, listing, _ = self.run_cli("list", "--json") + self.assertEqual(json.loads(listing)[0]["applies_when"], ["writing scripts"]) + _, out, _ = self.run_cli("hints", memory.id, "--clear", "--answers", "Tabs?") + self.assertIn("answers: Tabs?\n applies when: (none)", out) + self.assertEqual(self.run_cli("hints", "m_missing")[0], 1) + self.assertEqual(self.run_cli("hints", "m_missing", "--clear")[0], 1) + def test_model_is_required(self): with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()): cli.main(["--db", str(self.db), "sweep"]) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 22c7dcc..cad6720 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -31,12 +31,76 @@ def setUp(self): self.addCleanup(self.store.close) self.approved, self.secret = seed(self.store) - def test_read_returns_served_memories_with_evidence_and_confirmation(self): + def test_read_returns_a_lean_packet_without_evidence_by_default(self): result = mcp_server.read_memories(self.store, "how should I give feedback") (item,) = result["memories"] - self.assertEqual(item["id"], self.approved.id) - self.assertTrue(item["confirmed"]) - self.assertEqual(item["evidence"], ["Skip the pep talk."]) + self.assertEqual(item, {"id": self.approved.id, "text": self.approved.text, + "category": "communication", "confirmed": True}) + self.assertEqual((result["withheld"], result["more"]), (0, 0)) + + def test_evidence_is_sent_only_when_asked_for(self): + result = mcp_server.read_memories(self.store, "feedback", include_evidence=True) + self.assertEqual(result["memories"][0]["evidence"], ["Skip the pep talk."]) + + def test_owner_hints_are_used_for_ranking_but_never_sent(self): + self.store.set_hints(self.approved.id, ["How do I review code?"], ["reviewing a pull request"]) + result = mcp_server.read_memories(self.store, "pull request review", include_evidence=True) + self.assertEqual([m["id"] for m in result["memories"]], [self.approved.id]) + self.assertNotIn("pull request", json.dumps(result)) + self.assertNotIn("answers", result["memories"][0]) + + def test_nothing_relevant_gives_an_empty_answer(self): + result = mcp_server.read_memories(self.store, "zzzz unmatched topic") + self.assertEqual((result["memories"], result["more"]), ([], 0)) + + def test_more_and_context_and_scope_reach_the_read_policy(self): + for i in range(3): + self.store.add(Memory(text=f"You keep feedback notes, set {i}.", category="other", + evidence=(Evidence("s", 10 + i, "Notes."),))) + self.assertEqual(mcp_server.read_memories(self.store, "feedback", limit=2)["more"], 2) + by_context = mcp_server.read_memories(self.store, "zzzz", context="giving practical feedback") + self.assertEqual(len(by_context["memories"]), 4) + self.store.add(Memory(text="You lint before pushing.", category="tools", scope="project-b", + evidence=(Evidence("s", 20, "Lint first."),))) + self.assertEqual(mcp_server.read_memories(self.store, "lint", scope="project-a")["memories"], []) + self.assertEqual(len(mcp_server.read_memories(self.store, "lint", scope="project-b")["memories"]), 1) + + +class SeenTest(unittest.TestCase): + def setUp(self): + self.store = Store(":memory:") + self.addCleanup(self.store.close) + self.approved, _ = seed(self.store) + self.seen = set() + + def read(self, **options): + return mcp_server.read_memories(self.store, "feedback", seen=self.seen, **options) + + def test_a_memory_sent_in_full_comes_back_as_its_id_only(self): + first = self.read() + self.assertIn("text", first["memories"][0]) + self.assertNotIn("seen_note", first) + self.assertEqual(self.seen, {self.approved.id}) + again = self.read() + self.assertEqual(again["memories"], [{"id": self.approved.id, "seen": True}]) + self.assertEqual(again["seen_note"], mcp_server.NOTE_SEEN) + + def test_include_seen_or_evidence_sends_it_in_full_again(self): + self.read() + self.assertEqual(self.read(include_seen=True)["memories"][0]["text"], self.approved.text) + with_quotes = self.read(include_evidence=True)["memories"][0] + self.assertEqual(with_quotes["evidence"], ["Skip the pep talk."]) + + def test_unconfirmed_note_follows_only_full_entries(self): + extra = Memory(text="You prefer short feedback.", category="communication", + evidence=(Evidence("s", 2, "Keep it short."),)) + self.store.add(extra) + self.assertIn("note", self.read()) + self.assertNotIn("note", self.read()) + + def test_without_a_set_every_read_is_in_full(self): + mcp_server.read_memories(self.store, "feedback") + self.assertIn("text", mcp_server.read_memories(self.store, "feedback")["memories"][0]) def test_unconfirmed_note_only_when_an_unconfirmed_memory_is_served(self): confirmed_only = mcp_server.read_memories(self.store, "how should I give feedback") @@ -108,6 +172,23 @@ def test_server_exposes_exactly_read_and_propose(self): content = content[0] if isinstance(content, tuple) else content # (content, structured) in some 1.x result = json.loads(content[0].text) self.assertEqual(result["memories"][0]["text"], "You prefer direct, practical feedback.") + self.assertNotIn("evidence", result["memories"][0]) + + def test_one_server_remembers_what_it_sent_and_a_new_server_starts_fresh(self): + store = Store(":memory:") + self.addCleanup(store.close) + seed(store) + + def read(server, **args): + content = asyncio.run(server.call_tool("personakit_read", {"question": "feedback", **args})) + content = content[0] if isinstance(content, tuple) else content + return json.loads(content[0].text)["memories"][0] + + server = mcp_server.build_server(store) + self.assertIn("text", read(server, context="writing a review")) + self.assertEqual(read(server).get("seen"), True) + self.assertIn("evidence", read(server, include_evidence=True)) + self.assertIn("text", read(mcp_server.build_server(store))) if __name__ == "__main__": diff --git a/tests/test_retrieve.py b/tests/test_retrieve.py index e6e0f98..8f71945 100644 --- a/tests/test_retrieve.py +++ b/tests/test_retrieve.py @@ -2,12 +2,12 @@ from personakit import retrieve from personakit.model import Evidence, Memory, State -from personakit.retrieve import SERVED, STANDING_CONTEXT, search +from personakit.retrieve import SERVED, search -def mem(text, state=State.UNCONFIRMED, created="2026-01-01", category="other"): - return Memory(text=text, category=category, state=state, created_at=created, - evidence=(Evidence("s", 0, "q"),)) +def mem(text, state=State.UNCONFIRMED, created="2026-01-01", category="other", scope="global", **hints): + return Memory(text=text, category=category, state=state, created_at=created, scope=scope, + evidence=(Evidence("s", 0, "q"),), **hints) class SearchTest(unittest.TestCase): @@ -30,12 +30,53 @@ def test_restricted_and_archived_are_never_served_and_restricted_matches_are_cou self.assertEqual(result.memories, []) self.assertEqual(result.withheld, 1) - def test_approved_standing_context_fills_when_little_matches(self): - standing = [mem(f"Standing preference number {i}.", state=State.APPROVED, created=f"2026-01-0{i + 1}") for i in range(5)] - unrelated_unconfirmed = mem("You collect stamps.") - result = search(standing + [unrelated_unconfirmed], "completely different topic") - self.assertEqual(len(result.memories), STANDING_CONTEXT) - self.assertTrue(all(m.state == State.APPROVED for m in result.memories)) + def test_nothing_relevant_means_an_empty_result_even_with_approved_memories(self): + approved = [mem(f"Standing preference number {i}.", state=State.APPROVED) for i in range(5)] + result = search(approved + [mem("You collect stamps.")], "completely different topic") + self.assertEqual((result.memories, result.withheld, result.more), ([], 0, 0)) + + def test_more_counts_relevant_servable_memories_left_out_by_the_limit(self): + many = [mem(f"You like topic {i} apples.") for i in range(6)] + hidden = [mem("You grow apples secretly.", state=State.RESTRICTED), mem("You sold apples.", state=State.ARCHIVED)] + result = search(many + hidden + [mem("You like pears.")], "apples", limit=4) + self.assertEqual((len(result.memories), result.more, result.withheld), (4, 2, 1)) + self.assertEqual(search(many, "apples", limit=10).more, 0) + + def test_context_is_scored_separately_and_the_better_score_counts(self): + tests = mem("You always write tests before a refactor.") + tabs = mem("You indent with tabs.") + calls = [] + + def relevance(text, memories): + calls.append(text) + return retrieve.overlap(text, memories) + + result = search([tests, tabs], "indent style", relevance=relevance, context="about to refactor the parser") + self.assertEqual(calls, ["indent style", "about to refactor the parser"]) + self.assertEqual(set(result.memories), {tests, tabs}) + self.assertEqual(search([tests, tabs], "indent style").memories, [tabs]) + + def test_blank_context_does_not_call_relevance_again(self): + calls = [] + search([mem("You like tea.")], "tea", relevance=lambda q, ms: calls.append(q) or [1.0] * len(ms), context=" ") + self.assertEqual(calls, ["tea"]) + + def test_scope_keeps_global_and_matching_memories_only(self): + general = mem("You like terse commit messages.") + here = mem("You run the commit hooks in this project.", scope="project-a") + elsewhere = mem("You squash every commit there.", scope="project-b") + secret = mem("You commit late at night.", scope="project-b", state=State.RESTRICTED) + unscoped = search([general, here, elsewhere, secret], "commit") + self.assertEqual((len(unscoped.memories), unscoped.withheld), (3, 1)) + scoped = search([general, here, elsewhere, secret], "commit", scope="project-a") + self.assertEqual((set(scoped.memories), scoped.withheld), ({general, here}, 0)) + + def test_owner_hints_count_towards_word_overlap(self): + hinted = mem("You prefer short replies.", answers=("How long should answers be?",), + applies_when=("writing release notes",)) + self.assertEqual(search([hinted], "release notes").memories, [hinted]) + self.assertEqual(search([hinted], "answers length").memories, [hinted]) + self.assertEqual(search([mem("You prefer short replies.")], "release notes").memories, []) def test_limit_is_respected(self): many = [mem(f"You like topic {i} apples.") for i in range(10)] diff --git a/tests/test_store.py b/tests/test_store.py index a76a906..01c4c6c 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -132,6 +132,50 @@ def test_existing_database_is_upgraded_in_place(self): version = upgraded._conn.execute("PRAGMA user_version").fetchone()[0] self.assertEqual(version, len(MIGRATIONS)) + def test_database_from_before_hints_opens_without_losing_anything(self): + import sqlite3 + import tempfile + from pathlib import Path + path = Path(tempfile.mkdtemp()) / "before-hints.db" + old = sqlite3.connect(path) + for number, script in enumerate(MIGRATIONS[:4]): + old.executescript(script) + old.execute(f"PRAGMA user_version = {number + 1}") + old.execute("INSERT INTO memories (id, text, category, scope, state, created_at, decided_at, decided_by, last_seen_at)" + " VALUES ('m_old','You keep notes in plain text.','tools','global','approved','2026-01-01T00:00:00Z'," + "'2026-01-02T00:00:00Z','owner','2026-01-03T00:00:00Z')") + old.execute("INSERT INTO evidence VALUES ('m_old','s',4,'Plain text forever.')") + old.execute("INSERT INTO reads VALUES ('2026-01-04T00:00:00Z', 1, 0)") + old.commit() + old.close() + with Store(path) as upgraded: + loaded = upgraded.get("m_old") + self.assertEqual((loaded.text, loaded.state, loaded.decided_by), ("You keep notes in plain text.", State.APPROVED, Decider.OWNER)) + self.assertEqual((loaded.last_seen_at, loaded.evidence), ("2026-01-03T00:00:00Z", (Evidence("s", 4, "Plain text forever."),))) + self.assertEqual((loaded.answers, loaded.applies_when), ((), ())) + self.assertEqual(upgraded.read_stats()["reads"], 1) + upgraded.set_hints("m_old", answers=["Where do notes go?"]) + self.assertEqual(upgraded.get("m_old").answers, ("Where do notes go?",)) + with Store(path) as reopened: + self.assertEqual(reopened.get("m_old").answers, ("Where do notes go?",)) + self.assertEqual(reopened._conn.execute("PRAGMA user_version").fetchone()[0], len(MIGRATIONS)) + + def test_hints_round_trip_and_leave_the_decision_alone(self): + m = Memory(text="You prefer tabs.", category="tools", evidence=(Evidence("s", 0, "Tabs."),), + answers=("Tabs or spaces?",)) + self.store.add(m) + self.store.set_state(m.id, State.APPROVED, Decider.OWNER) + self.assertEqual(self.store.get(m.id).answers, ("Tabs or spaces?",)) + updated = self.store.set_hints(m.id, applies_when=[" editing Go code ", "", "editing Go code"]) + self.assertEqual((updated.answers, updated.applies_when), (("Tabs or spaces?",), ("editing Go code",))) + self.assertEqual((updated.state, updated.decided_at), (State.APPROVED, "2026-01-07T00:00:00Z")) + self.assertEqual(self.store.list()[0].applies_when, ("editing Go code",)) + cleared = self.store.set_hints(m.id, answers=[]) + self.assertEqual((cleared.answers, cleared.applies_when), ((), ("editing Go code",))) + self.assertEqual(updated.as_dict()["applies_when"], ["editing Go code"]) + with self.assertRaises(KeyError): + self.store.set_hints("m_missing", answers=["x"]) + def test_database_records_its_schema_version(self): version = self.store._conn.execute("PRAGMA user_version").fetchone()[0] self.assertEqual(version, len(MIGRATIONS)) From 7e019999d46212b050d211a8baee178cb3e381dd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 10:14:56 +0000 Subject: [PATCH 2/2] Changelog: unreleased read changes Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bee689..df72f05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## Unreleased + +- `personakit_read` returns only relevant memories. When nothing is relevant the answer is + empty: approved memories are no longer added as standing context. +- Evidence quotes are sent only with `include_evidence`. A memory already sent by the same + server process comes back as its id with `seen: true`, unless `include_seen`. +- Reads take `context` (what the assistant is about to do, ranked like a second question) and + `scope` (that scope plus global). `more` in the answer counts relevant memories left out by + 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. + ## 0.2.0 - `personakit tidy`: a plan that folds near-identical unconfirmed memories into the oldest one