From 203a2df36022e2da3d22ccec051101c8d15fa12b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:59:29 +0000 Subject: [PATCH 1/3] 0.2: fold same-session twins, archive stale memories, local digest Adds tidy (plan first, --apply to act, undo for every step), twins (word-based, cautious), decay (unconfirmed memories unseen for 90 days), and digest. Migration 3 adds last_seen_at and a merge record. No model calls, no embeddings. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- .gitignore | 1 + README.md | 19 +++- docs/ARCHITECTURE.md | 33 +++++- docs/PRIVACY.md | 7 ++ docs/REVIEW-LOG.md | 3 + docs/ROADMAP.md | 2 +- personakit/cli.py | 67 ++++++++++- personakit/decay.py | 33 ++++++ personakit/digest.py | 51 +++++++++ personakit/mcp_server.py | 3 +- personakit/model.py | 4 + personakit/retrieve.py | 7 +- personakit/review.py | 4 +- personakit/store.py | 226 ++++++++++++++++++++++++++++++++++---- personakit/tidy.py | 75 +++++++++++++ personakit/twins.py | 111 +++++++++++++++++++ tests/test_cli.py | 69 +++++++++++- tests/test_decay.py | 45 ++++++++ tests/test_merge_store.py | 166 ++++++++++++++++++++++++++++ tests/test_tidy.py | 118 ++++++++++++++++++++ tests/test_twins.py | 103 +++++++++++++++++ 21 files changed, 1106 insertions(+), 41 deletions(-) create mode 100644 personakit/decay.py create mode 100644 personakit/digest.py create mode 100644 personakit/tidy.py create mode 100644 personakit/twins.py create mode 100644 tests/test_decay.py create mode 100644 tests/test_merge_store.py create mode 100644 tests/test_tidy.py create mode 100644 tests/test_twins.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..21772a0 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ memories ("you prefer direct, practical feedback"), keeps the exact quote each o and serves only what you allow back to your assistants over MCP. Everything runs on your own machine. There is no PersonaKit server and no account. -> **Status: pre-release (0.1 in progress).** This repository is being built in public. +> **Status: pre-release (0.2 in progress).** This repository is being built in public. > See [docs/ROADMAP.md](docs/ROADMAP.md) for what exists and what is planned. ## Why PersonaKit @@ -53,11 +53,14 @@ personakit sweep --cli claude --model --max-calls 20 # read sessi personakit review # optional: approve, restrict, hide, forget personakit list # see what is stored personakit stats # counts only, never memory text +personakit tidy # plan: fold same-session twins, archive stale memories +personakit tidy --apply # carry the plan out (reverse any step with `personakit undo `) +personakit digest # what changed in the last 7 days (local, prints memory text) personakit serve # MCP server over stdio for your assistants personakit forget # delete a memory and its quotes for good ``` -`sweep`, `list` and `stats` also take `--json` for stable, sorted machine-readable output. +`sweep`, `list`, `stats`, `tidy` and `digest` also take `--json` for stable, sorted machine-readable output. The model name is always yours to choose. Nothing leaves your machine except the turns you wrote, sent to the model you named. See [docs/PRIVACY.md](docs/PRIVACY.md). @@ -101,6 +104,9 @@ Your assistant gets two tools: 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. +6. **Tidy** (on request) folds near-identical memories from the same session 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. A memory is always in one of four states: @@ -111,7 +117,7 @@ A memory is always in one of four states: | `restricted` | Never | | `archived` | Never | -## Limits in 0.1 +## Limits in 0.2 Stated plainly, so you know what you are installing: @@ -120,6 +126,12 @@ Stated plainly, so you know what you are installing: in other scripts are not matched yet; approved memories are still returned as standing context. - **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, + from the same session, and misses paraphrases on purpose: a missed merge costs nothing, a wrong + one costs trust. Memories from different sessions are never merged. +- **Decay looks only at time.** An unconfirmed memory not extracted again for 90 days is archived + (reversible); that says nothing about whether it is still true. Approved and restricted + memories never decay. - **A memory an assistant already received stays in that conversation.** Restricting it applies to future reads. - **Paste and credential detection is by shape**, not by meaning. Look before you share a store. @@ -131,6 +143,7 @@ Stated plainly, so you know what you are installing: | Claude Code sessions | Available in 0.1 | | Codex sessions | Available in 0.1 | | Any MCP client (read and propose) | Available in 0.1 | +| Merge same-session twins, decay stale memories, weekly digest | Available in 0.2 | | ChatGPT, claude.ai and Gemini export import | Planned for 0.3 | ## Documentation diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8710bd9..9ecf9c5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,4 +1,4 @@ -# Architecture (v0.1 design) +# Architecture (v0.2 design) PersonaKit is a small local pipeline with one database. Each stage has one job and talks to the next only through the store. @@ -17,6 +17,8 @@ flowchart TB RV[review: CLI] MCP[mcp_server] SS[stats: local counts] + TD[tidy: twins + decay, on request] + DG[digest: last days, local] end CC --> IN CX --> IN @@ -26,6 +28,8 @@ flowchart TB ST <--> RV ST --> MCP ST --> SS + ST <--> TD + ST --> DG MCP --> AS[Assistants] ``` @@ -42,6 +46,10 @@ 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` | +| `twins` | Finds near-identical unconfirmed memories that rest on the same single session. Word-based, deliberately cautious (numbers, negation and word order must agree). 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` | +| `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` | | `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 | @@ -51,7 +59,11 @@ 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, decided_at, decided_by`. +- **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. +- **Merge record**: `duplicate_id, survivor_id, merged_at, undone_at, snapshot`. The snapshot holds + the merged-away memory so `undo` can bring it back exactly; it is emptied on undo and deleted + with the survivor on `forget`. - **Evidence**: `memory_id, session_id, turn_index, quote`. Every memory has at least one. - **State**: `unconfirmed` (default, served with a label) -> `approved` | `restricted` | `archived`. Nothing is ever hard-deleted without an explicit `forget` by the owner. @@ -60,13 +72,22 @@ model, only `ingest` reads session files.** A second implementation of any of th 1. A memory with no evidence is not stored. 2. Unconfirmed memories are served, labelled as unconfirmed. Review is a quality tool, not a gate. -3. The system never changes a memory's state or deletes a memory on its own. Extracting the same - statement again adds evidence to the existing memory and leaves your decision alone. Merging - near-duplicates and archiving stale items are planned for 0.2 and will be reversible. +3. The system never deletes a memory, and never touches a memory you have decided on. Extracting + the same statement again adds evidence to the existing memory and leaves your decision alone. + Two things change unconfirmed memories, and only when you run `personakit tidy --apply` + (the default is a plan that changes nothing): folding same-session twins together, and + archiving memories not seen again for 90 days. Both are reversible with `personakit undo `. + A memory that decay archived comes back by itself if the statement is extracted again. 4. Only text the owner wrote is sent to a model. 5. Statistics are counts, never content, and are local unless the owner chooses to share them. -## Out of scope for 0.1 +## Out of scope for now Hosted service, accounts, sync, ChatGPT/Gemini/claude.ai import and third-party name detection. See the roadmap for what is planned. + +## Limits in 0.2 + +Twin detection compares words, not meaning. It catches the same statement phrased almost the +same way and misses paraphrases; it is built to miss rather than to merge wrongly. Decay looks +only at how long ago a statement was last extracted, not at whether it is still true. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 91e0542..88dc003 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -16,3 +16,10 @@ - **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. +- **Tidy and undo:** `personakit tidy` reads your store and, only with `--apply`, folds + near-identical memories together and archives stale ones. A merged memory is kept inside your + store, as a record that lets `personakit undo` restore it; the record is emptied on undo and + deleted when you `forget` the memory it was merged into (or the merged memory itself). Nothing + leaves your machine, and nothing here calls a model. +- **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. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index a7b9ff5..3423e88 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -25,3 +25,6 @@ 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/twins.py`, `decay.py`, `tidy.py`, `digest.py` | 2026-11-13 | none; written for this repository, word-based only (no model call), thresholds chosen from invented examples; no ids or text from any real store | clean | +| `personakit/store.py`, `model.py`, `retrieve.py`, `review.py`, `cli.py` (0.2 changes) | 2026-11-13 | migration 3 (`last_seen_at`, `merges`); merge snapshot is emptied on undo and deleted on forget; `PROPOSED_BY_ASSISTANT` moved to `model` | clean | +| `tests/test_twins.py`, `test_decay.py`, `test_merge_store.py`, `test_tidy.py`, `test_cli.py` (changes) | 2026-11-13 | invented sentences only | clean | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e2de8ac..5bf5cfc 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,7 +3,7 @@ | Release | Scope | Target | |---|---|---| | 0.1 | Claude Code + Codex ingest, extract, store, CLI review, MCP server, local stats | day 10 | -| 0.2 | Merge same-session duplicates (reversible), weekly digest, decay to archive | day 14 | +| 0.2 | Merge same-session duplicates (reversible), weekly digest, decay to archive | in review | | 0.3 | Import from ChatGPT / claude.ai / Gemini exports | after launch | | 0.4 | Third-party name guard | after launch | diff --git a/personakit/cli.py b/personakit/cli.py index ca941d5..3874914 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 decay, digest, llm, mcp_server, review, stats, sweep, tidy, twins from personakit.ingest import ADAPTERS from personakit.model import State from personakit.store import Store @@ -44,6 +44,22 @@ def build_parser() -> argparse.ArgumentParser: stats_cmd = sub.add_parser("stats", help="counts only, never memory text") stats_cmd.add_argument("--json", action="store_true", help="print a JSON object") + tidy_cmd = sub.add_parser("tidy", help="fold same-session twins and archive stale memories (shows a plan; --apply to act)") + tidy_cmd.add_argument("--apply", action="store_true", help="carry out the plan instead of only showing it") + tidy_cmd.add_argument("--days", type=int, default=decay.DEFAULT_DAYS, help="days unseen before unconfirmed is stale") + tidy_cmd.add_argument("--threshold", type=float, default=twins.DEFAULT_THRESHOLD, help="twin similarity, 0 to 1") + tidy_cmd.add_argument("--only", choices=["merge", "archive"], default=None, help="do just one of the two steps") + tidy_cmd.add_argument("--json", action="store_true", help="print a JSON object (ids only)") + + undo_cmd = sub.add_parser("undo", help="reverse one merge or one stale-archive by memory id") + undo_cmd.add_argument("memory_id") + + sub.add_parser("merges", help="list memories that were merged into another, with their ids") + + digest_cmd = sub.add_parser("digest", help="what changed in the last days (prints memory text, locally)") + digest_cmd.add_argument("--days", type=int, default=7) + digest_cmd.add_argument("--json", action="store_true", help="print a JSON object") + forget = sub.add_parser("forget", help="permanently delete a memory and its quotes") forget.add_argument("memory_id") @@ -78,6 +94,23 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: _print_json(collected) else: print(stats.format_stats(collected)) + elif args.command == "tidy": + return _tidy(args, store) + elif args.command == "undo": + try: + print(tidy.undo(store, args.memory_id).capitalize() + ".") + except KeyError: + print(f"Nothing to undo for {args.memory_id}: not a merged or stale-archived memory", file=sys.stderr) + return 1 + elif args.command == "merges": + for record in store.merges(): + print(f"{record.duplicate_id} into {record.survivor_id} {record.duplicate_text}") + elif args.command == "digest": + collected = digest.collect(store, store.now(), args.days) + if args.json: + _print_json(collected) + else: + print(digest.format_digest(collected)) elif args.command == "forget": if not store.forget(args.memory_id): print(f"No memory with id {args.memory_id}", file=sys.stderr) @@ -93,6 +126,38 @@ def _print_json(data: object) -> None: print(json.dumps(data, sort_keys=True, ensure_ascii=False)) +def _tidy(args: argparse.Namespace, store: Store) -> int: + if args.days < 1 or not 0 < args.threshold <= 1: + print("--days must be at least 1 and --threshold between 0 and 1", file=sys.stderr) + return 2 + plan = tidy.make_plan( + store, store.now(), args.days, args.threshold, merge=args.only != "archive", archive=args.only != "merge" + ) + report = tidy.apply(store, plan) if args.apply else None + if args.json: + _print_json( + { + "applied": report is not None, + "merge": [{"keep": g.survivor.id, "fold": [d.id for d in g.duplicates]} for g in plan.groups], + "archive": [m.id for m in plan.stale], + } + ) + return 0 + for group in plan.groups: + print(f"keep {group.survivor.id} {group.survivor.text}") + for duplicate in group.duplicates: + print(f" fold {duplicate.id} {duplicate.text}") + for memory in plan.stale: + print(f"archive {memory.id} {memory.text}") + if report: + print(f"Merged {report.merged}, archived {report.archived}. Reverse any with: personakit undo ") + elif plan.groups or plan.stale: + print(f"{plan.merges} to merge, {len(plan.stale)} to archive. Nothing changed; add --apply to carry it out.") + else: + print("Nothing to tidy.") + return 0 + + def _sweep(args: argparse.Namespace, store: Store) -> int: sources = list(ADAPTERS) if args.source == "all" else [args.source] if args.root and len(sources) != 1: diff --git a/personakit/decay.py b/personakit/decay.py new file mode 100644 index 0000000..c40d4a6 --- /dev/null +++ b/personakit/decay.py @@ -0,0 +1,33 @@ +"""Which unconfirmed memories have gone stale. + +A memory is stale when it is still unconfirmed and has not been extracted again for a long time. +Approved and restricted memories never decay: those are the owner's decisions. Staleness only +ever leads to archiving (reversible), never to deletion. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from datetime import datetime, timedelta, timezone + +from personakit.model import Memory, State + +DEFAULT_DAYS = 90 +_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + +def days_ago(now: str, days: int) -> str: + """The timestamp `days` before `now`, in the store's format, so strings compare in time order.""" + moment = datetime.strptime(now, _FORMAT).replace(tzinfo=timezone.utc) + return (moment - timedelta(days=days)).strftime(_FORMAT) + + +def find_stale(memories: Iterable[Memory], now: str, days: int = DEFAULT_DAYS) -> list[Memory]: + if days < 1: + raise ValueError("days must be at least 1") + cutoff = days_ago(now, days) + return [ + m + for m in memories + if m.state == State.UNCONFIRMED and (m.last_seen_at or m.created_at or now) < cutoff + ] diff --git a/personakit/digest.py b/personakit/digest.py new file mode 100644 index 0000000..46d7ad0 --- /dev/null +++ b/personakit/digest.py @@ -0,0 +1,51 @@ +"""A short summary of the last few days in your own store. + +Unlike `stats`, a digest shows memory ids and text (never evidence quotes) so you can see what changed. +It is printed to your terminal and goes nowhere else. Run it weekly from cron or a scheduler +if you want a routine; PersonaKit does not schedule anything itself. +""" + +from __future__ import annotations + +from personakit import decay +from personakit.model import Decider, State +from personakit.store import Store + +LISTED = 10 # most texts shown per section + + +def collect(store: Store, now: str, days: int = 7) -> dict: + since = decay.days_ago(now, days) + everything = store.list() + new = [m for m in everything if (m.created_at or "") >= since] + archived = [ + m for m in everything if m.state == State.ARCHIVED and m.decided_by == Decider.POLICY and (m.decided_at or "") >= since + ] + merged = store.merges(since=since) + return { + "days": days, + "new": len(new), + "new_items": [{"id": m.id, "text": m.text} for m in new[:LISTED]], + "merged": len(merged), + "merged_items": [{"id": r.duplicate_id, "text": r.duplicate_text} for r in merged[:LISTED]], + "archived_by_decay": len(archived), + "archived_items": [{"id": m.id, "text": m.text} for m in archived[:LISTED]], + "awaiting_review": store.counts()[State.UNCONFIRMED.value], + **store.read_stats(since), + } + + +def format_digest(data: dict) -> str: + lines = [f"PersonaKit digest, last {data['days']} days"] + for label, count, items in ( + ("New memories", data["new"], data["new_items"]), + ("Merged as twins (undo with `personakit undo `)", data["merged"], data["merged_items"]), + ("Archived as stale (undo with `personakit undo `)", data["archived_by_decay"], data["archived_items"]), + ): + lines.append(f"{label}: {count}") + lines += [f" {item['id']} {item['text']}" for item in items] + if count > len(items): + lines.append(f" ... and {count - len(items)} more") + lines.append(f"Awaiting your review: {data['awaiting_review']}") + lines.append(f"Assistant reads: {data['reads']} ({data['reads_with_results']} returned something)") + return "\n".join(lines) diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 461f9d3..0ef3282 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -8,8 +8,7 @@ from __future__ import annotations from personakit import extract, retrieve -from personakit.model import Evidence, Memory, State -from personakit.review import PROPOSED_BY_ASSISTANT +from personakit.model import PROPOSED_BY_ASSISTANT, Evidence, Memory, State from personakit.store import Store NOTE_UNCONFIRMED = "Unconfirmed: extracted from the owner's conversations but not yet reviewed by them." diff --git a/personakit/model.py b/personakit/model.py index 1f8bcd4..0a28015 100644 --- a/personakit/model.py +++ b/personakit/model.py @@ -8,6 +8,9 @@ from dataclasses import dataclass, field from enum import Enum +# Evidence from an assistant's own proposal carries this session id instead of a real session. +PROPOSED_BY_ASSISTANT = "mcp-proposal" + class State(str, Enum): """Where a memory stands. Only the owner can approve, restrict or forget.""" @@ -72,6 +75,7 @@ class Memory: created_at: str | None = None decided_at: str | None = None decided_by: Decider | None = None + last_seen_at: str | None = None # last time the same statement was extracted again def __post_init__(self) -> None: if not self.text.strip(): diff --git a/personakit/retrieve.py b/personakit/retrieve.py index 192ad2a..b9cf7e3 100644 --- a/personakit/retrieve.py +++ b/personakit/retrieve.py @@ -38,8 +38,13 @@ class Result: withheld: int # matching memories the owner restricted, counted but never shown +def word_list(text: str) -> list[str]: + """Content words in the order written, repeats kept.""" + return [w for w in _WORD.findall(text.lower()) if w not in _STOP] + + def words(text: str) -> set[str]: - return {w for w in _WORD.findall(text.lower()) if w not in _STOP} + return set(word_list(text)) def search(memories: Iterable[Memory], question: str, limit: int = 7) -> Result: diff --git a/personakit/review.py b/personakit/review.py index 3ab0bb3..8f85f8c 100644 --- a/personakit/review.py +++ b/personakit/review.py @@ -7,11 +7,9 @@ from collections.abc import Callable from dataclasses import dataclass -from personakit.model import Decider, Memory, State +from personakit.model import PROPOSED_BY_ASSISTANT, Decider, Memory, State from personakit.store import Store -PROPOSED_BY_ASSISTANT = "mcp-proposal" - CHOICES = {"a": State.APPROVED, "r": State.RESTRICTED, "h": State.ARCHIVED} PROMPT = " [a]pprove [r]estrict [h]ide [f]orget [s]kip [q]uit > " diff --git a/personakit/store.py b/personakit/store.py index 3c7eddf..708bfd2 100644 --- a/personakit/store.py +++ b/personakit/store.py @@ -6,8 +6,10 @@ from __future__ import annotations +import json import sqlite3 from collections.abc import Callable, Iterable +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path @@ -49,9 +51,34 @@ withheld INTEGER NOT NULL ); """, + # 0.2: when a statement was last seen again (drives decay), and a reversible record of merges. + # `snapshot` holds the merged-away memory so it can be restored; it is emptied on undo and + # deleted with its survivor on forget. + """ + ALTER TABLE memories ADD COLUMN last_seen_at TEXT; + UPDATE memories SET last_seen_at = created_at; + CREATE TABLE merges ( + duplicate_id TEXT PRIMARY KEY, + survivor_id TEXT NOT NULL, + merged_at TEXT NOT NULL, + undone_at TEXT, + snapshot TEXT NOT NULL + ); + """, ] +@dataclass(frozen=True) +class MergeRecord: + """One memory folded into another. `duplicate_text` is empty once the merge is undone.""" + + duplicate_id: str + survivor_id: str + merged_at: str + undone_at: str | None + duplicate_text: str + + def _utc_now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") @@ -64,6 +91,10 @@ def __init__(self, path: str | Path, now: Callable[[], str] = _utc_now): self._conn.execute("PRAGMA foreign_keys = ON") self._migrate() + def now(self) -> str: + """The store's clock, in the format it records.""" + return self._now() + def close(self) -> None: self._conn.close() @@ -90,31 +121,159 @@ def add(self, memory: Memory) -> bool: """Store a memory. Returns True if it is new. If the same memory already exists its evidence is extended and its state is left alone, - so extracting a fact twice never undoes a decision the owner made. + so extracting a fact twice never undoes a decision the owner made. If it was merged into + another memory, the evidence goes to that memory. Seeing a statement again refreshes + its last-seen time and brings back a memory that decay had archived. """ with self._conn: - created = self._conn.execute( - "INSERT OR IGNORE INTO memories" - " (id, text, category, scope, state, created_at, decided_at, decided_by)" - " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - ( - memory.id, - memory.text, - memory.category, - memory.scope, - memory.state.value, - memory.created_at or self._now(), - memory.decided_at, - memory.decided_by.value if memory.decided_by else None, - ), - ).rowcount == 1 + target = self._merged_into(memory.id) or memory.id + now = self._now() + created = ( + target == memory.id + and self._conn.execute( + "INSERT OR IGNORE INTO memories" + " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + memory.id, + memory.text, + memory.category, + memory.scope, + memory.state.value, + memory.created_at or now, + memory.last_seen_at or memory.created_at or now, + memory.decided_at, + memory.decided_by.value if memory.decided_by else None, + ), + ).rowcount + == 1 + ) self._conn.executemany( "INSERT OR IGNORE INTO evidence (memory_id, session_id, turn_index, quote)" " VALUES (?, ?, ?, ?)", - [(memory.id, e.session_id, e.turn_index, e.quote) for e in memory.evidence], + [(target, e.session_id, e.turn_index, e.quote) for e in memory.evidence], ) + if not created: + self._conn.execute("UPDATE memories SET last_seen_at = ? WHERE id = ?", (now, target)) + self._conn.execute( + "UPDATE memories SET state = ?, decided_at = NULL, decided_by = NULL" + " WHERE id = ? AND state = ? AND decided_by = ?", + (State.UNCONFIRMED.value, target, State.ARCHIVED.value, Decider.POLICY.value), + ) return created + def _merged_into(self, memory_id: str) -> str | None: + row = self._conn.execute( + "SELECT survivor_id FROM merges WHERE duplicate_id = ? AND undone_at IS NULL", (memory_id,) + ).fetchone() + return row["survivor_id"] if row else None + + def merge(self, duplicate_id: str, survivor_id: str) -> None: + """Fold one unconfirmed memory into another, keeping a record that undo_merge can reverse. + + The duplicate's evidence moves to the survivor and the duplicate disappears from the + store. Only unconfirmed memories can be merged: an owner's decision is never overridden. + """ + if duplicate_id == survivor_id: + raise ValueError("cannot merge a memory into itself") + duplicate, survivor = self.get(duplicate_id), self.get(survivor_id) + if duplicate is None or survivor is None: + raise KeyError(duplicate_id if duplicate is None else survivor_id) + if duplicate.state != State.UNCONFIRMED or survivor.state != State.UNCONFIRMED: + raise ValueError("only unconfirmed memories can be merged") + with self._conn: + added = [ + [e.session_id, e.turn_index] + for e in duplicate.evidence + if self._conn.execute( + "INSERT OR IGNORE INTO evidence (memory_id, session_id, turn_index, quote) VALUES (?, ?, ?, ?)", + (survivor_id, e.session_id, e.turn_index, e.quote), + ).rowcount + ] + snapshot = { + "text": duplicate.text, + "category": duplicate.category, + "scope": duplicate.scope, + "created_at": duplicate.created_at, + "last_seen_at": duplicate.last_seen_at, + "evidence": [[e.session_id, e.turn_index, e.quote] for e in duplicate.evidence], + "added": added, + } + self._conn.execute("DELETE FROM memories WHERE id = ?", (duplicate_id,)) + self._conn.execute( + "UPDATE memories SET last_seen_at = MAX(COALESCE(last_seen_at, ''), ?) WHERE id = ?", + (duplicate.last_seen_at or "", survivor_id), + ) + self._conn.execute( + "INSERT OR REPLACE INTO merges (duplicate_id, survivor_id, merged_at, undone_at, snapshot)" + " VALUES (?, ?, ?, NULL, ?)", + (duplicate_id, survivor_id, self._now(), json.dumps(snapshot)), + ) + + def undo_merge(self, duplicate_id: str) -> None: + """Bring a merged memory back and take back the evidence it gave. Raises KeyError if + there is no active merge for that id.""" + row = self._conn.execute( + "SELECT * FROM merges WHERE duplicate_id = ? AND undone_at IS NULL", (duplicate_id,) + ).fetchone() + if row is None: + raise KeyError(duplicate_id) + snap = json.loads(row["snapshot"]) + with self._conn: + self._conn.execute( + "INSERT INTO memories (id, text, category, scope, state, created_at, last_seen_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + duplicate_id, + snap["text"], + snap["category"], + snap["scope"], + State.UNCONFIRMED.value, + snap["created_at"], + snap["last_seen_at"], + ), + ) + self._conn.executemany( + "INSERT INTO evidence (memory_id, session_id, turn_index, quote) VALUES (?, ?, ?, ?)", + [(duplicate_id, *e) for e in snap["evidence"]], + ) + self._conn.executemany( + "DELETE FROM evidence WHERE memory_id = ? AND session_id = ? AND turn_index = ?", + [(row["survivor_id"], *key) for key in snap["added"]], + ) + self._conn.execute( + "UPDATE merges SET undone_at = ?, snapshot = '{}' WHERE duplicate_id = ?", + (self._now(), duplicate_id), + ) + + def merges(self, since: str | None = None, active_only: bool = True) -> list[MergeRecord]: + clauses, params = [], [] + if active_only: + clauses.append("undone_at IS NULL") + if since is not None: + clauses.append("merged_at >= ?") + params.append(since) + where = (" WHERE " + " AND ".join(clauses)) if clauses else "" + rows = self._conn.execute("SELECT * FROM merges" + where + " ORDER BY merged_at, duplicate_id", params) + return [ + MergeRecord( + r["duplicate_id"], r["survivor_id"], r["merged_at"], r["undone_at"], + json.loads(r["snapshot"]).get("text", ""), + ) + for r in rows + ] + + def restore(self, memory_id: str) -> None: + """Bring back a memory that decay archived. Raises KeyError unless policy archived it.""" + with self._conn: + changed = self._conn.execute( + "UPDATE memories SET state = ?, decided_at = NULL, decided_by = NULL, last_seen_at = ?" + " WHERE id = ? AND state = ? AND decided_by = ?", + (State.UNCONFIRMED.value, self._now(), memory_id, State.ARCHIVED.value, Decider.POLICY.value), + ).rowcount + if changed == 0: + raise KeyError(memory_id) + def set_state(self, memory_id: str, state: State, by: Decider) -> None: """Move a memory to a new state and record who did it. Raises KeyError if unknown.""" with self._conn: @@ -126,11 +285,30 @@ def set_state(self, memory_id: str, state: State, by: Decider) -> None: raise KeyError(memory_id) def forget(self, memory_id: str) -> bool: - """Delete a memory and its evidence. Returns False if it did not exist.""" + """Delete a memory and its evidence. Returns False if it did not exist. + + Also deletes what merges kept of it: records that hold this memory as the survivor, and, + if it had been merged into another memory, the evidence it contributed there. + """ with self._conn: - return self._conn.execute( - "DELETE FROM memories WHERE id = ?", (memory_id,) - ).rowcount == 1 + deleted = self._conn.execute("DELETE FROM memories WHERE id = ?", (memory_id,)).rowcount == 1 + # Records held under this memory, and under anything that was itself merged into it. + pending = [memory_id] + while pending: + rows = self._conn.execute( + "SELECT duplicate_id FROM merges WHERE survivor_id = ?", (pending.pop(),) + ).fetchall() + self._conn.executemany("DELETE FROM merges WHERE duplicate_id = ?", [(r[0],) for r in rows]) + pending.extend(r[0] for r in rows) + merged = self._conn.execute("SELECT * FROM merges WHERE duplicate_id = ?", (memory_id,)).fetchone() + if merged is not None: + if merged["undone_at"] is None: + self._conn.executemany( + "DELETE FROM evidence WHERE memory_id = ? AND session_id = ? AND turn_index = ?", + [(merged["survivor_id"], *key) for key in json.loads(merged["snapshot"])["added"]], + ) + self._conn.execute("DELETE FROM merges WHERE duplicate_id = ?", (memory_id,)) + return deleted or merged is not None def mark_session_seen(self, source: str, session_id: str, fingerprint: str) -> None: with self._conn: @@ -150,9 +328,10 @@ def log_read(self, returned: int, withheld: int) -> None: # -- reading -------------------------------------------------------------------- - def read_stats(self) -> dict[str, int]: + def read_stats(self, since: str | None = None) -> dict[str, int]: row = self._conn.execute( - "SELECT COUNT(*) AS reads, COALESCE(SUM(returned > 0), 0) AS with_results FROM reads" + "SELECT COUNT(*) AS reads, COALESCE(SUM(returned > 0), 0) AS with_results FROM reads WHERE at >= ?", + (since or "",), ).fetchone() return {"reads": row["reads"], "reads_with_results": row["with_results"]} @@ -224,5 +403,6 @@ def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...]) -> Memory: created_at=row["created_at"], decided_at=row["decided_at"], decided_by=Decider(row["decided_by"]) if row["decided_by"] else None, + last_seen_at=row["last_seen_at"], evidence=evidence, ) diff --git a/personakit/tidy.py b/personakit/tidy.py new file mode 100644 index 0000000..402c036 --- /dev/null +++ b/personakit/tidy.py @@ -0,0 +1,75 @@ +"""Tidy the store: fold same-session twins together and archive stale memories. + +Both steps are proposals first. `plan` only reads; nothing changes until the owner runs `apply`, +and everything `apply` does can be reversed with `undo`. Nothing is ever deleted here, and no +memory the owner has decided on is touched. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from personakit import decay, twins +from personakit.model import Decider, State +from personakit.store import Store + + +@dataclass +class Plan: + groups: list[twins.TwinGroup] = field(default_factory=list) + stale: list = field(default_factory=list) + + @property + def merges(self) -> int: + return sum(len(g.duplicates) for g in self.groups) + + +@dataclass +class Report: + merged: int = 0 + archived: int = 0 + + +def make_plan( + store: Store, + now: str, + days: int = decay.DEFAULT_DAYS, + threshold: float = twins.DEFAULT_THRESHOLD, + merge: bool = True, + archive: bool = True, +) -> Plan: + plan = Plan() + if merge: + undone = frozenset( + frozenset((r.duplicate_id, r.survivor_id)) for r in store.merges(active_only=False) if r.undone_at + ) + plan.groups = twins.find_twins(store.list(states=[State.UNCONFIRMED]), threshold, undone) + if archive: + folded = {d.id for g in plan.groups for d in g.duplicates} # about to disappear, so not archived too + plan.stale = [m for m in decay.find_stale(store.list(states=[State.UNCONFIRMED]), now, days) if m.id not in folded] + return plan + + +def apply(store: Store, plan: Plan) -> Report: + report = Report() + for group in plan.groups: + for duplicate in group.duplicates: + store.merge(duplicate.id, group.survivor.id) + report.merged += 1 + for memory in plan.stale: + store.set_state(memory.id, State.ARCHIVED, Decider.POLICY) + report.archived += 1 + return report + + +def undo(store: Store, memory_id: str) -> str: + """Reverse one merge or one decay archive. Returns "unmerged" or "restored". + + Raises KeyError for anything else, including memories the owner archived themselves. + """ + try: + store.undo_merge(memory_id) + return "unmerged" + except KeyError: + store.restore(memory_id) + return "restored" diff --git a/personakit/twins.py b/personakit/twins.py new file mode 100644 index 0000000..5f63422 --- /dev/null +++ b/personakit/twins.py @@ -0,0 +1,111 @@ +"""Find near-identical memories that were extracted from the same session. + +Pure functions, no I/O. Detection is lexical (shared content words), so it only catches memories +that are worded almost the same way; paraphrases are left alone on purpose. A false merge is worse +than a missed one, so every rule here leans towards "not a twin": + +* only unconfirmed memories, so an owner's decision is never overridden; +* both memories must rest on the same single session, and neither may be assistant-proposed; +* same category and scope; +* the numbers they mention (digits or words like "two") must be equal, and they must agree on negation ("not", "never", + "avoid" ...), because "uses 2 spaces" and "does not use 2 spaces" share nearly every word. + +Matching is against one anchor memory per group, never chained, so a group cannot drift into +unrelated memories. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable +from dataclasses import dataclass +from difflib import SequenceMatcher + +from personakit.model import PROPOSED_BY_ASSISTANT, Memory, State +from personakit.retrieve import word_list + +DEFAULT_THRESHOLD = 0.8 +MIN_SHARED_WORDS = 3 + +_NUMBER = re.compile(r"\d+(?:[.,]\d+)?|\b(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|twice|once|half)\b") +_NEGATION = re.compile( + r"\b(?:not|no|never|none|nor|cannot|without|avoid(?:s|ed)?|dislike[sd]?|hate[sd]?|stop(?:s|ped)?" + r"|(?:don|doesn|didn|isn|aren|won|wasn|can|shouldn|wouldn)'?t)\b" +) + + +@dataclass(frozen=True) +class TwinGroup: + """One memory to keep and the near-identical ones to fold into it.""" + + survivor: Memory + duplicates: tuple[Memory, ...] + + +def _stem(word: str) -> str: + return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word + + +def _content(text: str) -> list[str]: + return [_stem(w) for w in word_list(text)] + + +def similarity(a: str, b: str) -> float: + """How alike two texts are, from 0 to 1: the lower of the share of content words they have in + common and how well those words line up in order (so "unit before integration tests" is not + the same as "integration before unit tests"). + + 0 when they disagree on numbers or negation, or share fewer than MIN_SHARED_WORDS words. + """ + if sorted(_NUMBER.findall(a.lower())) != sorted(_NUMBER.findall(b.lower())): + return 0.0 + if bool(_NEGATION.search(a.lower())) != bool(_NEGATION.search(b.lower())): + return 0.0 + left, right = _content(a), _content(b) + shared = len(set(left) & set(right)) + if shared < MIN_SHARED_WORDS: + return 0.0 + return min(shared / len(set(left) | set(right)), SequenceMatcher(None, left, right).ratio()) + + +def _single_session(memory: Memory) -> str | None: + sessions = {e.session_id for e in memory.evidence} + if len(sessions) != 1 or PROPOSED_BY_ASSISTANT in sessions: + return None + return next(iter(sessions)) + + +def find_twins( + memories: Iterable[Memory], + threshold: float = DEFAULT_THRESHOLD, + vetoed: frozenset[frozenset[str]] = frozenset(), +) -> list[TwinGroup]: + """Group eligible memories into survivor + duplicates. + + `vetoed` holds id pairs the owner already un-merged; they are never proposed again. + The survivor is the oldest memory in a group, so results do not depend on input order. + """ + eligible = sorted( + (m for m in memories if m.state == State.UNCONFIRMED and _single_session(m)), + key=lambda m: (m.created_at or "", m.id), + ) + taken: set[str] = set() + groups: list[TwinGroup] = [] + for index, anchor in enumerate(eligible): + if anchor.id in taken: + continue + twins = tuple( + other + for other in eligible[index + 1 :] + if other.id not in taken + and _single_session(other) == _single_session(anchor) + and other.category == anchor.category + and other.scope == anchor.scope + and frozenset((anchor.id, other.id)) not in vetoed + and similarity(anchor.text, other.text) >= threshold + ) + if twins: + taken.update(m.id for m in twins) + taken.add(anchor.id) + groups.append(TwinGroup(anchor, twins)) + return groups diff --git a/tests/test_cli.py b/tests/test_cli.py index aded799..fded416 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -7,6 +7,8 @@ from unittest import mock from personakit import cli, llm +from personakit.model import Evidence, Memory +from personakit.store import Store from tests.helpers import reply FIXTURES = Path(__file__).parent / "fixtures" / "claude_code" @@ -24,7 +26,7 @@ def complete(self, prompt): return reply(MEMORY) -class CliTest(unittest.TestCase): +class CliCase(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp()) self.addCleanup(__import__("shutil").rmtree, self.tmp) @@ -36,6 +38,8 @@ def run_cli(self, *argv): code = cli.main(["--db", str(self.db), *argv]) return code, out.getvalue(), err.getvalue() + +class CliTest(CliCase): def test_sweep_then_list_stats_and_forget(self): root = self.tmp / "projects" (root / "proj").mkdir(parents=True) @@ -111,5 +115,68 @@ def test_db_defaults_to_environment_variable(self): self.assertEqual(cli.default_db(), self.db) +class TidyCliTest(CliCase): + """tidy, undo, merges and digest, on a store seeded with invented memories dated long ago.""" + + def seed(self): + self.db.parent.mkdir(parents=True, exist_ok=True) + self.clock = ["2020-01-01T00:00:00Z"] + with Store(self.db, now=lambda: self.clock[0]) as store: + for turn, text in enumerate( + ["You prefer direct, practical feedback.", "You prefer direct and practical feedback from reviewers."] + ): + self.clock[0] = f"2020-01-01T00:00:0{turn}Z" + store.add(Memory(text=text, category="communication", evidence=(Evidence("s1", turn, "q"),))) + + def test_tidy_shows_a_plan_and_changes_nothing_until_applied(self): + self.seed() + code, out, _ = self.run_cli("tidy", "--only", "merge") + self.assertEqual(code, 0) + self.assertIn("1 to merge, 0 to archive. Nothing changed", out) + self.assertEqual(self.run_cli("merges")[1], "") + + def test_apply_then_list_merges_then_undo(self): + self.seed() + _, out, _ = self.run_cli("tidy", "--apply", "--only", "merge") + self.assertIn("Merged 1, archived 0", out) + _, merges, _ = self.run_cli("merges") + duplicate_id = merges.split()[0] + self.assertEqual(len(json.loads(self.run_cli("list", "--json")[1])), 1) + code, out, _ = self.run_cli("undo", duplicate_id) + self.assertEqual((code, out), (0, "Unmerged.\n")) + self.assertEqual(len(json.loads(self.run_cli("list", "--json")[1])), 2) + self.assertEqual(self.run_cli("undo", duplicate_id)[0], 1) + + def test_old_unconfirmed_memories_are_archived_and_can_be_restored(self): + self.seed() + _, out, _ = self.run_cli("tidy", "--apply", "--only", "archive", "--days", "30") + self.assertIn("Merged 0, archived 2", out) + listing = json.loads(self.run_cli("list", "--state", "archived", "--json")[1]) + self.assertEqual(len(listing), 2) + self.assertEqual(self.run_cli("undo", listing[0]["id"])[1], "Restored.\n") + + def test_tidy_json_lists_ids_only(self): + self.seed() + _, out, _ = self.run_cli("tidy", "--json", "--days", "30") + data = json.loads(out) + self.assertFalse(data["applied"]) + self.assertEqual(len(data["merge"][0]["fold"]), 1) + self.assertNotIn("prefer", out) + + def test_nothing_to_tidy_on_a_fresh_store(self): + self.assertIn("Nothing to tidy.", self.run_cli("tidy")[1]) + + def test_tidy_rejects_bad_numbers(self): + self.assertEqual(self.run_cli("tidy", "--days", "0")[0], 2) + self.assertEqual(self.run_cli("tidy", "--threshold", "1.5")[0], 2) + + def test_digest_prints_text_or_json(self): + self.seed() + _, text, _ = self.run_cli("digest") + self.assertIn("PersonaKit digest, last 7 days", text) + data = json.loads(self.run_cli("digest", "--days", "99999", "--json")[1]) + self.assertEqual(data["new"], 2) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_decay.py b/tests/test_decay.py new file mode 100644 index 0000000..5487365 --- /dev/null +++ b/tests/test_decay.py @@ -0,0 +1,45 @@ +import unittest + +from personakit.decay import days_ago, find_stale +from personakit.model import Decider, Evidence, Memory, State + +NOW = "2026-06-01T00:00:00Z" + + +def mem(text, state=State.UNCONFIRMED, created="2026-01-01T00:00:00Z", seen=None): + return Memory( + text=text, + category="other", + state=state, + created_at=created, + last_seen_at=seen, + decided_by=Decider.OWNER if state != State.UNCONFIRMED else None, + evidence=(Evidence("s", 0, "q"),), + ) + + +class DecayTest(unittest.TestCase): + def test_days_ago_counts_back_from_now(self): + self.assertEqual(days_ago(NOW, 7), "2026-05-25T00:00:00Z") + + def test_old_unconfirmed_memory_is_stale(self): + self.assertEqual([m.text for m in find_stale([mem("old")], NOW, 90)], ["old"]) + + def test_recently_seen_memory_is_not_stale_even_if_created_long_ago(self): + self.assertEqual(find_stale([mem("again", seen="2026-05-20T00:00:00Z")], NOW, 90), []) + + def test_owner_decisions_never_decay(self): + kept = [mem("a", State.APPROVED), mem("r", State.RESTRICTED), mem("h", State.ARCHIVED)] + self.assertEqual(find_stale(kept, NOW, 90), []) + + def test_boundary_is_exclusive(self): + edge = mem("edge", seen=days_ago(NOW, 90)) + self.assertEqual(find_stale([edge], NOW, 90), []) + + def test_days_must_be_positive(self): + with self.assertRaises(ValueError): + find_stale([], NOW, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_merge_store.py b/tests/test_merge_store.py new file mode 100644 index 0000000..94736f3 --- /dev/null +++ b/tests/test_merge_store.py @@ -0,0 +1,166 @@ +import json +import sqlite3 +import tempfile +import unittest +from pathlib import Path + +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import MIGRATIONS, Store + + +class Clock: + def __init__(self, value="2026-01-01T00:00:00Z"): + self.value = value + + def __call__(self): + return self.value + + +def mem(text, *evidence): + return Memory(text=text, category="other", evidence=tuple(Evidence("s1", t, q) for t, q in evidence)) + + +class MergeTest(unittest.TestCase): + def setUp(self): + self.clock = Clock() + self.store = Store(":memory:", now=self.clock) + self.addCleanup(self.store.close) + self.keep = mem("You prefer direct practical feedback.", (0, "Skip the pep talk.")) + self.dup = mem("You prefer direct and practical feedback.", (1, "Be blunt."), (0, "Skip the pep talk.")) + self.store.add(self.keep) + self.store.add(self.dup) + + def merged(self): + self.store.merge(self.dup.id, self.keep.id) + + def test_merge_moves_evidence_and_removes_the_duplicate(self): + self.merged() + self.assertIsNone(self.store.get(self.dup.id)) + self.assertEqual([(e.turn_index, e.quote) for e in self.store.get(self.keep.id).evidence], [(0, "Skip the pep talk."), (1, "Be blunt.")]) + self.assertEqual([r.duplicate_id for r in self.store.merges()], [self.dup.id]) + + def test_undo_restores_the_duplicate_and_takes_back_only_what_it_added(self): + self.merged() + self.store.undo_merge(self.dup.id) + restored = self.store.get(self.dup.id) + self.assertEqual((restored.text, restored.state), (self.dup.text, State.UNCONFIRMED)) + self.assertEqual(len(restored.evidence), 2) + # the quote both memories shared stays with the survivor + self.assertEqual([e.turn_index for e in self.store.get(self.keep.id).evidence], [0]) + self.assertEqual(self.store.merges(), []) + + def test_undo_drops_the_stored_text_but_remembers_the_pair(self): + self.merged() + self.store.undo_merge(self.dup.id) + (record,) = self.store.merges(active_only=False) + self.assertEqual((record.duplicate_text, bool(record.undone_at)), ("", True)) + with self.assertRaises(KeyError): + self.store.undo_merge(self.dup.id) + + def test_only_unconfirmed_memories_can_merge(self): + self.store.set_state(self.keep.id, State.APPROVED, Decider.OWNER) + with self.assertRaises(ValueError): + self.merged() + with self.assertRaises(ValueError): + self.store.merge(self.dup.id, self.dup.id) + with self.assertRaises(KeyError): + self.store.merge("m_missing", self.keep.id) + + def test_extracting_a_merged_statement_again_feeds_the_survivor(self): + self.merged() + self.clock.value = "2026-02-01T00:00:00Z" + self.assertFalse(self.store.add(mem(self.dup.text, (5, "Straight talk please.")))) + self.assertIsNone(self.store.get(self.dup.id)) + survivor = self.store.get(self.keep.id) + self.assertEqual(len(survivor.evidence), 3) + self.assertEqual(survivor.last_seen_at, "2026-02-01T00:00:00Z") + + def test_forgetting_the_survivor_deletes_what_the_merge_kept(self): + self.merged() + self.assertTrue(self.store.forget(self.keep.id)) + self.assertEqual(self.store.merges(active_only=False), []) + self.assertNotIn(self.dup.text, json.dumps(self.store._conn.execute("SELECT * FROM merges").fetchall())) + + def test_forgetting_removes_chained_merges_as_well(self): + third = mem("You prefer direct, practical feedback always.", (7, "Always.")) + self.store.add(third) + self.merged() + self.store.merge(self.keep.id, third.id) # the survivor is itself folded into a third memory + self.assertTrue(self.store.forget(third.id)) + self.assertEqual(self.store._conn.execute("SELECT COUNT(*) FROM merges").fetchone()[0], 0) + + def test_forgetting_a_merged_duplicate_removes_it_and_the_evidence_it_gave(self): + self.merged() + self.assertTrue(self.store.forget(self.dup.id)) + self.assertEqual([e.turn_index for e in self.store.get(self.keep.id).evidence], [0]) + self.assertEqual(self.store.merges(active_only=False), []) + self.assertFalse(self.store.forget(self.dup.id)) + + def test_forgetting_after_undo_clears_the_pair_record_too(self): + self.merged() + self.store.undo_merge(self.dup.id) + self.assertTrue(self.store.forget(self.dup.id)) + self.assertEqual(self.store.merges(active_only=False), []) + + def test_merges_can_be_filtered_by_time(self): + self.clock.value = "2026-03-01T00:00:00Z" + self.merged() + self.assertEqual(len(self.store.merges(since="2026-02-01T00:00:00Z")), 1) + self.assertEqual(self.store.merges(since="2026-04-01T00:00:00Z"), []) + + +class DecayStoreTest(unittest.TestCase): + def setUp(self): + self.clock = Clock() + self.store = Store(":memory:", now=self.clock) + self.addCleanup(self.store.close) + self.m = mem("You use Python for scripts.", (0, "I write Python.")) + self.store.add(self.m) + + def test_new_memory_is_last_seen_when_created(self): + self.assertEqual(self.store.get(self.m.id).last_seen_at, "2026-01-01T00:00:00Z") + + def test_seeing_it_again_refreshes_last_seen(self): + self.clock.value = "2026-04-01T00:00:00Z" + self.store.add(mem(self.m.text, (3, "More Python."))) + self.assertEqual(self.store.get(self.m.id).last_seen_at, "2026-04-01T00:00:00Z") + + def test_restore_brings_back_a_policy_archive_and_resets_the_clock(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.clock.value = "2026-05-01T00:00:00Z" + self.store.restore(self.m.id) + back = self.store.get(self.m.id) + self.assertEqual((back.state, back.decided_by, back.last_seen_at), (State.UNCONFIRMED, None, "2026-05-01T00:00:00Z")) + + def test_restore_refuses_what_the_owner_archived(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.OWNER) + with self.assertRaises(KeyError): + self.store.restore(self.m.id) + with self.assertRaises(KeyError): + self.store.restore("m_missing") + + def test_extracting_an_archived_statement_again_revives_it_only_if_policy_archived_it(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.store.add(mem(self.m.text, (4, "Python again."))) + self.assertEqual(self.store.get(self.m.id).state, State.UNCONFIRMED) + self.store.set_state(self.m.id, State.ARCHIVED, Decider.OWNER) + self.store.add(mem(self.m.text, (5, "Python once more."))) + self.assertEqual(self.store.get(self.m.id).state, State.ARCHIVED) + + def test_database_from_before_merges_is_upgraded_and_backfilled(self): + path = Path(tempfile.mkdtemp()) / "v2.db" + old = sqlite3.connect(path) + for step in MIGRATIONS[:2]: + old.executescript(step) + old.execute("PRAGMA user_version = 2") + old.execute("INSERT INTO memories VALUES ('m_x','kept','c','global','unconfirmed','2026-01-01T00:00:00Z',NULL,NULL)") + old.execute("INSERT INTO evidence VALUES ('m_x','s',0,'q')") + old.commit() + old.close() + with Store(path) as upgraded: + self.assertEqual(upgraded.get("m_x").last_seen_at, "2026-01-01T00:00:00Z") + self.assertEqual(upgraded.merges(), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_tidy.py b/tests/test_tidy.py new file mode 100644 index 0000000..6eba97e --- /dev/null +++ b/tests/test_tidy.py @@ -0,0 +1,118 @@ +import unittest + +from personakit import digest, tidy +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import Store + +NOW = "2026-06-01T00:00:00Z" + + +def mem(text, session="s1", turn=0, category="communication"): + return Memory(text=text, category=category, evidence=(Evidence(session, turn, f"quote {turn}"),)) + + +class Clock: + def __init__(self, value): + self.value = value + + def __call__(self): + return self.value + + +class TidyTest(unittest.TestCase): + def setUp(self): + self.clock = Clock("2026-01-01T00:00:00Z") + self.store = Store(":memory:", now=self.clock) + self.addCleanup(self.store.close) + self.keep = mem("You prefer direct, practical feedback.") + self.twin = mem("You prefer direct and practical feedback from reviewers.", turn=1) + self.old = mem("You deploy on Fridays.", session="s2", category="work") + for m in (self.keep, self.twin, self.old): + self.store.add(m) + self.clock.value = self.tick(self.clock.value) + self.clock.value = NOW + self.fresh = mem("You use Python for scripts.", session="s3", category="tools") + self.store.add(self.fresh) + + @staticmethod + def tick(value): + return value[:-3] + f"{int(value[-3:-1]) + 1:02d}Z" + + def test_plan_changes_nothing(self): + plan = tidy.make_plan(self.store, NOW, days=90) + self.assertEqual((plan.merges, len(plan.stale)), (1, 2)) + self.assertEqual(self.store.counts()["unconfirmed"], 4) + self.assertEqual(self.store.merges(), []) + + def test_stale_list_leaves_out_memories_about_to_be_folded_away(self): + plan = tidy.make_plan(self.store, NOW, days=90) + self.assertEqual({m.id for m in plan.stale}, {self.keep.id, self.old.id}) + + def test_apply_merges_and_archives_and_every_step_can_be_undone(self): + report = tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) + self.assertEqual((report.merged, report.archived), (1, 2)) + self.assertEqual(self.store.get(self.old.id).state, State.ARCHIVED) + self.assertEqual(self.store.get(self.old.id).decided_by, Decider.POLICY) + self.assertEqual(tidy.undo(self.store, self.twin.id), "unmerged") + self.assertEqual(tidy.undo(self.store, self.old.id), "restored") + self.assertEqual(tidy.undo(self.store, self.keep.id), "restored") + self.assertEqual(self.store.counts(), {"unconfirmed": 4, "approved": 0, "restricted": 0, "archived": 0}) + + def test_a_merge_the_owner_undid_is_not_proposed_again(self): + tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90, archive=False)) + tidy.undo(self.store, self.twin.id) + self.assertEqual(tidy.make_plan(self.store, NOW, days=90, archive=False).groups, []) + + def test_steps_can_run_alone(self): + self.assertEqual(tidy.make_plan(self.store, NOW, merge=False).groups, []) + self.assertEqual(tidy.make_plan(self.store, NOW, archive=False).stale, []) + + def test_undo_refuses_unknown_ids_and_owner_archives(self): + self.store.set_state(self.fresh.id, State.ARCHIVED, Decider.OWNER) + for memory_id in ("m_missing", self.fresh.id): + with self.assertRaises(KeyError): + tidy.undo(self.store, memory_id) + + def test_applying_twice_is_a_no_op(self): + tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) + again = tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) + self.assertEqual((again.merged, again.archived), (0, 0)) + + +class DigestTest(unittest.TestCase): + def setUp(self): + self.clock = Clock("2026-01-01T00:00:00Z") + self.store = Store(":memory:", now=self.clock) + self.addCleanup(self.store.close) + + def test_digest_covers_only_the_window_and_lists_ids_with_text(self): + self.store.add(mem("You are an old memory about tabs here.")) + self.clock.value = "2026-05-30T00:00:00Z" + a, b = mem("You prefer direct, practical feedback."), mem("You prefer direct and practical feedback from reviewers.", turn=1) + self.store.add(a) + self.clock.value = "2026-05-30T00:00:01Z" + self.store.add(b) + self.store.log_read(2, 0) + tidy.apply(self.store, tidy.make_plan(self.store, "2026-06-01T00:00:00Z", days=400)) + data = digest.collect(self.store, "2026-06-01T00:00:00Z", days=7) + self.assertEqual((data["new"], data["merged"], data["reads"], data["awaiting_review"]), (1, 1, 1, 2)) + self.assertEqual(data["new_items"], [{"id": a.id, "text": a.text}]) + self.assertEqual(data["merged_items"][0]["id"], b.id) + text = digest.format_digest(data) + self.assertIn(a.id, text) + self.assertIn("Awaiting your review: 2", text) + self.assertNotIn("quote", text) + + def test_digest_shows_what_decay_archived_and_caps_long_lists(self): + for i in range(digest.LISTED + 2): + self.store.add(mem(f"You track item number {i} carefully in notes.", session=f"s{i}", turn=i)) + self.clock.value = "2026-06-01T00:00:00Z" + tidy.apply(self.store, tidy.make_plan(self.store, self.clock.value, days=30)) + data = digest.collect(self.store, self.clock.value, days=7) + self.assertEqual(data["archived_by_decay"], digest.LISTED + 2) + self.assertEqual(len(data["archived_items"]), digest.LISTED) + self.assertIn("... and 2 more", digest.format_digest(data)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_twins.py b/tests/test_twins.py new file mode 100644 index 0000000..f14e1af --- /dev/null +++ b/tests/test_twins.py @@ -0,0 +1,103 @@ +import unittest + +from personakit.model import PROPOSED_BY_ASSISTANT, Decider, Evidence, Memory, State +from personakit.twins import find_twins, similarity + + +def mem(text, session="s1", category="communication", scope="global", state=State.UNCONFIRMED, created="2026-01-01T00:00:00Z"): + return Memory( + text=text, + category=category, + scope=scope, + state=state, + created_at=created, + decided_by=Decider.OWNER if state != State.UNCONFIRMED else None, + evidence=(Evidence(session, 0, "invented quote"),), + ) + + +class SimilarityTest(unittest.TestCase): + def test_same_statement_worded_slightly_differently_matches(self): + a = "You prefer direct, practical feedback." + b = "You prefer direct and practical feedback from reviewers." + self.assertGreaterEqual(similarity(a, b), 0.8) + + def test_plural_forms_count_as_the_same_word(self): + self.assertEqual(similarity("You like short answers here.", "You like short answer here."), 1.0) + + def test_unrelated_texts_do_not_match(self): + self.assertEqual(similarity("You prefer direct, practical feedback.", "You deploy services on Fridays."), 0.0) + + def test_different_numbers_are_never_twins(self): + self.assertEqual(similarity("You indent code with 2 spaces.", "You indent code with 4 spaces."), 0.0) + + def test_negation_flips_the_meaning_so_they_are_never_twins(self): + self.assertEqual(similarity("You use tabs for indentation.", "You do not use tabs for indentation."), 0.0) + self.assertEqual(similarity("You like long meetings.", "You dislike long meetings."), 0.0) + self.assertEqual(similarity("You use tabs for indentation.", "You don't use tabs for indentation."), 0.0) + + def test_swapped_order_is_not_a_twin(self): + self.assertLess(similarity("You prefer unit tests before integration tests.", "You prefer integration tests before unit tests."), 0.8) + + def test_number_words_count_like_digits(self): + self.assertEqual(similarity("You live with two cats at home.", "You live with three cats at home."), 0.0) + + def test_extra_detail_is_not_a_twin(self): + self.assertLess(similarity("You prefer short answers.", "You prefer short answers with examples."), 0.8) + + def test_too_few_shared_words_is_not_enough(self): + self.assertEqual(similarity("You like tea.", "You like tea."), 0.0) + + +class FindTwinsTest(unittest.TestCase): + def setUp(self): + self.a = mem("You prefer direct, practical feedback.", created="2026-01-01T00:00:00Z") + self.b = mem("You prefer direct and practical feedback from reviewers.", created="2026-01-02T00:00:00Z") + + def test_twins_from_the_same_session_are_grouped_with_the_oldest_kept(self): + groups = find_twins([self.b, self.a]) + self.assertEqual(len(groups), 1) + self.assertEqual(groups[0].survivor.id, self.a.id) + self.assertEqual([m.id for m in groups[0].duplicates], [self.b.id]) + + def test_other_sessions_are_never_merged(self): + other = mem(self.b.text, session="s2") + self.assertEqual(find_twins([self.a, other]), []) + + def test_memory_resting_on_two_sessions_is_not_eligible(self): + both = Memory(text=self.b.text, category="communication", evidence=(Evidence("s1", 0, "q"), Evidence("s2", 1, "q"))) + self.assertEqual(find_twins([self.a, both]), []) + + def test_assistant_proposals_are_never_merged(self): + one = mem(self.a.text, session=PROPOSED_BY_ASSISTANT) + two = mem(self.b.text, session=PROPOSED_BY_ASSISTANT) + self.assertEqual(find_twins([one, two]), []) + + def test_owner_decisions_are_never_touched(self): + for state in (State.APPROVED, State.RESTRICTED, State.ARCHIVED): + self.assertEqual(find_twins([self.a, mem(self.b.text, state=state)]), [], state) + + def test_category_and_scope_must_match(self): + self.assertEqual(find_twins([self.a, mem(self.b.text, category="tools")]), []) + self.assertEqual(find_twins([self.a, mem(self.b.text, scope="work")]), []) + + def test_matching_is_against_the_anchor_so_groups_do_not_chain(self): + # a~b and b~c but a is not close to c: c must not be pulled in through b. + a = mem("You prefer short direct practical feedback notes.", created="2026-01-01T00:00:00Z") + b = mem("You prefer short direct practical feedback notes always.", created="2026-01-02T00:00:00Z") + c = mem("You prefer short direct practical feedback notes always daily reviews.", created="2026-01-03T00:00:00Z") + groups = find_twins([a, b, c], threshold=0.75) + self.assertEqual([[m.id for m in g.duplicates] for g in groups], [[b.id]]) + + def test_vetoed_pair_is_not_proposed_again(self): + self.assertEqual(find_twins([self.a, self.b], vetoed=frozenset({frozenset((self.a.id, self.b.id))})), []) + + def test_stricter_threshold_finds_fewer(self): + self.assertEqual(find_twins([self.a, self.b], threshold=0.95), []) + + def test_result_does_not_depend_on_input_order(self): + self.assertEqual(find_twins([self.a, self.b]), find_twins([self.b, self.a])) + + +if __name__ == "__main__": + unittest.main() From 3ec07cd6d7372ec28f4ddb66de3eb06d379b5cc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 06:44:07 +0000 Subject: [PATCH 2/3] 0.2 review fixes: merged memories keep their own rows; assistants cannot revive Findings from a security and code review of this branch, each with a regression test: - forget could leave quotes behind through chained merges or evidence that arrived after a merge. A folded memory now keeps its own row and evidence and points at its survivor, so undo is exact and forget removes everything it brought. - an assistant proposal could bring back a decay-archived memory and reset its age. Only an extraction from the owner's own words does that now. - twin detection ignored words shorter than three letters, missed typographic apostrophes and some contractions, and let swapped word order through. - a survivor could be archived as stale right after absorbing a fresh twin. - an undone pair could be proposed again after a later merge. - digest and tidy validate --days. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- docs/ARCHITECTURE.md | 13 +- docs/PRIVACY.md | 9 +- docs/REVIEW-LOG.md | 3 +- personakit/cli.py | 8 +- personakit/mcp_server.py | 2 +- personakit/retrieve.py | 9 +- personakit/store.py | 292 +++++++++++++++++--------------------- personakit/tidy.py | 22 ++- personakit/twins.py | 74 ++++++---- tests/test_cli.py | 5 +- tests/test_mcp_server.py | 11 ++ tests/test_merge_store.py | 115 ++++++++++----- tests/test_tidy.py | 8 ++ tests/test_twins.py | 15 +- 14 files changed, 326 insertions(+), 260 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9ecf9c5..162e7bb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -46,7 +46,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` | -| `twins` | Finds near-identical unconfirmed memories that rest on the same single session. Word-based, deliberately cautious (numbers, negation and word order must agree). Pure functions. | `model`, `retrieve` | +| `twins` | Finds near-identical unconfirmed memories that rest on the same single session. Word-based, deliberately cautious (numbers, negation and the order of shared words must agree). 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` | | `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` | @@ -61,9 +61,10 @@ model, only `ingest` reads session files.** A second implementation of any of th - **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. -- **Merge record**: `duplicate_id, survivor_id, merged_at, undone_at, snapshot`. The snapshot holds - the merged-away memory so `undo` can bring it back exactly; it is emptied on undo and deleted - with the survivor on `forget`. +- **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 + it is not proposed again. `forget` on either memory removes that memory's rows for good. - **Evidence**: `memory_id, session_id, turn_index, quote`. Every memory has at least one. - **State**: `unconfirmed` (default, served with a label) -> `approved` | `restricted` | `archived`. Nothing is ever hard-deleted without an explicit `forget` by the owner. @@ -77,7 +78,9 @@ model, only `ingest` reads session files.** A second implementation of any of th Two things change unconfirmed memories, and only when you run `personakit tidy --apply` (the default is a plan that changes nothing): folding same-session twins together, and archiving memories not seen again for 90 days. Both are reversible with `personakit undo `. - A memory that decay archived comes back by itself if the statement is extracted again. + A memory that decay archived comes back by itself if the statement is extracted again from + your own words. An assistant proposing the same text does not bring it back and does not + reset its age. 4. Only text the owner wrote is sent to a model. 5. Statistics are counts, never content, and are local unless the owner chooses to share them. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 88dc003..bb00062 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -17,9 +17,10 @@ Sharing the output is your choice. - **Deletion:** `personakit forget` removes a memory and its evidence from the store. - **Tidy and undo:** `personakit tidy` reads your store and, only with `--apply`, folds - near-identical memories together and archives stale ones. A merged memory is kept inside your - store, as a record that lets `personakit undo` restore it; the record is emptied on undo and - deleted when you `forget` the memory it was merged into (or the merged memory itself). Nothing - leaves your machine, and nothing here calls a model. + near-identical memories together and archives stale ones. A folded memory stays in your store + with its own quotes, so `personakit undo` restores it exactly. `personakit forget` on a folded + memory deletes it and every quote it brought; `forget` on the memory it was folded into deletes + both, since they are the same statement. Nothing leaves your machine, and nothing here calls a + model. Assistants cannot merge, undo, 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. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index 3423e88..d75688a 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -26,5 +26,6 @@ duplicated logic. Each entry records the result. | `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/twins.py`, `decay.py`, `tidy.py`, `digest.py` | 2026-11-13 | none; written for this repository, word-based only (no model call), thresholds chosen from invented examples; no ids or text from any real store | clean | -| `personakit/store.py`, `model.py`, `retrieve.py`, `review.py`, `cli.py` (0.2 changes) | 2026-11-13 | migration 3 (`last_seen_at`, `merges`); merge snapshot is emptied on undo and deleted on forget; `PROPOSED_BY_ASSISTANT` moved to `model` | clean | +| `personakit/store.py`, `model.py`, `retrieve.py`, `review.py`, `cli.py` (0.2 changes) | 2026-11-13 | migration 3 (`last_seen_at`, `merged_into`, `merge_vetoes`); a folded memory keeps its own rows, so forget leaves nothing behind; assistant proposals cannot revive or refresh a memory; `PROPOSED_BY_ASSISTANT` moved to `model` | clean | | `tests/test_twins.py`, `test_decay.py`, `test_merge_store.py`, `test_tidy.py`, `test_cli.py` (changes) | 2026-11-13 | invented sentences only | clean | +| 0.2 changes, second pass | 2026-11-14 | security and code review run on the branch: quotes could outlive `forget` through chained merges, an assistant proposal could revive a decay-archived memory, short words and typographic apostrophes slipped past twin checks. All fixed, each with a regression test | clean | diff --git a/personakit/cli.py b/personakit/cli.py index 3874914..1c55bd5 100644 --- a/personakit/cli.py +++ b/personakit/cli.py @@ -13,6 +13,7 @@ from personakit.model import State from personakit.store import Store +MAX_DAYS = 36500 CLIENTS = {"claude": llm.ClaudeCli, "codex": llm.CodexCli} @@ -106,6 +107,9 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: for record in store.merges(): print(f"{record.duplicate_id} into {record.survivor_id} {record.duplicate_text}") elif args.command == "digest": + if not 1 <= args.days <= MAX_DAYS: + print(f"--days must be between 1 and {MAX_DAYS}", file=sys.stderr) + return 2 collected = digest.collect(store, store.now(), args.days) if args.json: _print_json(collected) @@ -127,8 +131,8 @@ def _print_json(data: object) -> None: def _tidy(args: argparse.Namespace, store: Store) -> int: - if args.days < 1 or not 0 < args.threshold <= 1: - print("--days must be at least 1 and --threshold between 0 and 1", file=sys.stderr) + 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) return 2 plan = tidy.make_plan( store, store.now(), args.days, args.threshold, merge=args.only != "archive", archive=args.only != "merge" diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 0ef3282..c4d814e 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -51,7 +51,7 @@ def propose_memory(store: Store, text: str, quote: str, category: str = "other") category=category if category in extract.CATEGORIES else "other", evidence=(Evidence(PROPOSED_BY_ASSISTANT, 0, extract.quote_of(quote.strip())),), ) - created = store.add(memory) + created = store.add(memory, observed=False) return {"stored": True, "id": memory.id, "new": created, "state": State.UNCONFIRMED.value} diff --git a/personakit/retrieve.py b/personakit/retrieve.py index b9cf7e3..05ebb3e 100644 --- a/personakit/retrieve.py +++ b/personakit/retrieve.py @@ -26,7 +26,7 @@ _EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+") _WORD = re.compile(r"[a-z0-9']{3,}") -_STOP = frozenset( +STOP_WORDS = frozenset( "the and for you your with that this have from what how should about are was were not but " "can will would could into than then them they their there when where which who why".split() ) @@ -38,13 +38,8 @@ class Result: withheld: int # matching memories the owner restricted, counted but never shown -def word_list(text: str) -> list[str]: - """Content words in the order written, repeats kept.""" - return [w for w in _WORD.findall(text.lower()) if w not in _STOP] - - def words(text: str) -> set[str]: - return set(word_list(text)) + return {w for w in _WORD.findall(text.lower()) if w not in STOP_WORDS} def search(memories: Iterable[Memory], question: str, limit: int = 7) -> Result: diff --git a/personakit/store.py b/personakit/store.py index 708bfd2..fc231df 100644 --- a/personakit/store.py +++ b/personakit/store.py @@ -6,7 +6,6 @@ from __future__ import annotations -import json import sqlite3 from collections.abc import Callable, Iterable from dataclasses import dataclass @@ -51,31 +50,35 @@ withheld INTEGER NOT NULL ); """, - # 0.2: when a statement was last seen again (drives decay), and a reversible record of merges. - # `snapshot` holds the merged-away memory so it can be restored; it is emptied on undo and - # deleted with its survivor on forget. + # 0.2: when a statement was last seen again (drives decay), and reversible merges. A merged + # memory keeps its own row and evidence and points at the memory it was folded into, so + # undoing is exact and forgetting either one leaves nothing behind. """ ALTER TABLE memories ADD COLUMN last_seen_at TEXT; + ALTER TABLE memories ADD COLUMN merged_into TEXT REFERENCES memories(id) ON DELETE CASCADE; + ALTER TABLE memories ADD COLUMN merged_at TEXT; UPDATE memories SET last_seen_at = created_at; - CREATE TABLE merges ( - duplicate_id TEXT PRIMARY KEY, - survivor_id TEXT NOT NULL, - merged_at TEXT NOT NULL, - undone_at TEXT, - snapshot TEXT NOT NULL + CREATE TABLE merge_vetoes ( + first_id TEXT NOT NULL, + second_id TEXT NOT NULL, + PRIMARY KEY (first_id, second_id) ); """, ] +# A memory together with everything folded into it, directly or through another folded memory. +_GROUP = ( + "WITH RECURSIVE grp(id) AS (SELECT ? UNION SELECT m.id FROM memories m JOIN grp ON m.merged_into = grp.id) " +) + @dataclass(frozen=True) class MergeRecord: - """One memory folded into another. `duplicate_text` is empty once the merge is undone.""" + """One memory folded into another.""" duplicate_id: str survivor_id: str merged_at: str - undone_at: str | None duplicate_text: str @@ -117,62 +120,53 @@ def _migrate(self) -> None: # -- writing -------------------------------------------------------------------- - def add(self, memory: Memory) -> bool: + def add(self, memory: Memory, observed: bool = True) -> bool: """Store a memory. Returns True if it is new. If the same memory already exists its evidence is extended and its state is left alone, - so extracting a fact twice never undoes a decision the owner made. If it was merged into - another memory, the evidence goes to that memory. Seeing a statement again refreshes - its last-seen time and brings back a memory that decay had archived. + so extracting a fact twice never undoes a decision the owner made. `observed` says the + owner was seen stating it again (an extraction): that refreshes its last-seen time and + brings back a memory that decay had archived. An assistant's proposal is not an + observation and does neither. """ with self._conn: - target = self._merged_into(memory.id) or memory.id now = self._now() - created = ( - target == memory.id - and self._conn.execute( - "INSERT OR IGNORE INTO memories" - " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by)" - " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - ( - memory.id, - memory.text, - memory.category, - memory.scope, - memory.state.value, - memory.created_at or now, - memory.last_seen_at or memory.created_at or now, - memory.decided_at, - memory.decided_by.value if memory.decided_by else None, - ), - ).rowcount - == 1 - ) + created = self._conn.execute( + "INSERT OR IGNORE INTO memories" + " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ( + memory.id, + memory.text, + memory.category, + memory.scope, + memory.state.value, + memory.created_at or now, + memory.last_seen_at or memory.created_at or now, + memory.decided_at, + memory.decided_by.value if memory.decided_by else None, + ), + ).rowcount == 1 self._conn.executemany( "INSERT OR IGNORE INTO evidence (memory_id, session_id, turn_index, quote)" " VALUES (?, ?, ?, ?)", - [(target, e.session_id, e.turn_index, e.quote) for e in memory.evidence], + [(memory.id, e.session_id, e.turn_index, e.quote) for e in memory.evidence], ) - if not created: - self._conn.execute("UPDATE memories SET last_seen_at = ? WHERE id = ?", (now, target)) + if observed and not created: + self._conn.execute("UPDATE memories SET last_seen_at = ? WHERE id = ?", (now, memory.id)) self._conn.execute( "UPDATE memories SET state = ?, decided_at = NULL, decided_by = NULL" " WHERE id = ? AND state = ? AND decided_by = ?", - (State.UNCONFIRMED.value, target, State.ARCHIVED.value, Decider.POLICY.value), + (State.UNCONFIRMED.value, memory.id, State.ARCHIVED.value, Decider.POLICY.value), ) return created - def _merged_into(self, memory_id: str) -> str | None: - row = self._conn.execute( - "SELECT survivor_id FROM merges WHERE duplicate_id = ? AND undone_at IS NULL", (memory_id,) - ).fetchone() - return row["survivor_id"] if row else None - def merge(self, duplicate_id: str, survivor_id: str) -> None: - """Fold one unconfirmed memory into another, keeping a record that undo_merge can reverse. + """Fold one unconfirmed memory into another. `undo_merge` reverses it exactly. - The duplicate's evidence moves to the survivor and the duplicate disappears from the - store. Only unconfirmed memories can be merged: an owner's decision is never overridden. + The duplicate keeps its row and evidence but is no longer listed or served on its own; + the survivor shows the evidence of both. Only unconfirmed memories can be merged, so an + owner's decision is never overridden. """ if duplicate_id == survivor_id: raise ValueError("cannot merge a memory into itself") @@ -182,86 +176,40 @@ def merge(self, duplicate_id: str, survivor_id: str) -> None: if duplicate.state != State.UNCONFIRMED or survivor.state != State.UNCONFIRMED: raise ValueError("only unconfirmed memories can be merged") with self._conn: - added = [ - [e.session_id, e.turn_index] - for e in duplicate.evidence - if self._conn.execute( - "INSERT OR IGNORE INTO evidence (memory_id, session_id, turn_index, quote) VALUES (?, ?, ?, ?)", - (survivor_id, e.session_id, e.turn_index, e.quote), - ).rowcount - ] - snapshot = { - "text": duplicate.text, - "category": duplicate.category, - "scope": duplicate.scope, - "created_at": duplicate.created_at, - "last_seen_at": duplicate.last_seen_at, - "evidence": [[e.session_id, e.turn_index, e.quote] for e in duplicate.evidence], - "added": added, - } - self._conn.execute("DELETE FROM memories WHERE id = ?", (duplicate_id,)) - self._conn.execute( - "UPDATE memories SET last_seen_at = MAX(COALESCE(last_seen_at, ''), ?) WHERE id = ?", - (duplicate.last_seen_at or "", survivor_id), - ) self._conn.execute( - "INSERT OR REPLACE INTO merges (duplicate_id, survivor_id, merged_at, undone_at, snapshot)" - " VALUES (?, ?, ?, NULL, ?)", - (duplicate_id, survivor_id, self._now(), json.dumps(snapshot)), + "UPDATE memories SET merged_into = ?, merged_at = ? WHERE id = ?", + (survivor_id, self._now(), duplicate_id), ) def undo_merge(self, duplicate_id: str) -> None: - """Bring a merged memory back and take back the evidence it gave. Raises KeyError if - there is no active merge for that id.""" + """Make a merged memory stand on its own again, and never propose that pair again. + Raises KeyError if the memory is not merged.""" row = self._conn.execute( - "SELECT * FROM merges WHERE duplicate_id = ? AND undone_at IS NULL", (duplicate_id,) + "SELECT merged_into FROM memories WHERE id = ? AND merged_into IS NOT NULL", (duplicate_id,) ).fetchone() if row is None: raise KeyError(duplicate_id) - snap = json.loads(row["snapshot"]) with self._conn: + self._conn.execute("UPDATE memories SET merged_into = NULL, merged_at = NULL WHERE id = ?", (duplicate_id,)) self._conn.execute( - "INSERT INTO memories (id, text, category, scope, state, created_at, last_seen_at)" - " VALUES (?, ?, ?, ?, ?, ?, ?)", - ( - duplicate_id, - snap["text"], - snap["category"], - snap["scope"], - State.UNCONFIRMED.value, - snap["created_at"], - snap["last_seen_at"], - ), - ) - self._conn.executemany( - "INSERT INTO evidence (memory_id, session_id, turn_index, quote) VALUES (?, ?, ?, ?)", - [(duplicate_id, *e) for e in snap["evidence"]], - ) - self._conn.executemany( - "DELETE FROM evidence WHERE memory_id = ? AND session_id = ? AND turn_index = ?", - [(row["survivor_id"], *key) for key in snap["added"]], - ) - self._conn.execute( - "UPDATE merges SET undone_at = ?, snapshot = '{}' WHERE duplicate_id = ?", - (self._now(), duplicate_id), + "INSERT OR IGNORE INTO merge_vetoes (first_id, second_id) VALUES (?, ?)", + tuple(sorted((duplicate_id, row["merged_into"]))), ) - def merges(self, since: str | None = None, active_only: bool = True) -> list[MergeRecord]: - clauses, params = [], [] - if active_only: - clauses.append("undone_at IS NULL") - if since is not None: - clauses.append("merged_at >= ?") - params.append(since) - where = (" WHERE " + " AND ".join(clauses)) if clauses else "" - rows = self._conn.execute("SELECT * FROM merges" + where + " ORDER BY merged_at, duplicate_id", params) - return [ - MergeRecord( - r["duplicate_id"], r["survivor_id"], r["merged_at"], r["undone_at"], - json.loads(r["snapshot"]).get("text", ""), - ) - for r in rows - ] + def merges(self, since: str | None = None) -> list[MergeRecord]: + """Memories currently folded into another, oldest merge first.""" + rows = self._conn.execute( + "SELECT id, merged_into, merged_at, text FROM memories" + " WHERE merged_into IS NOT NULL AND merged_at >= ? ORDER BY merged_at, id", + (since or "",), + ) + return [MergeRecord(r["id"], r["merged_into"], r["merged_at"], r["text"]) for r in rows] + + def merge_vetoes(self) -> frozenset[frozenset[str]]: + """Pairs the owner un-merged. They are never proposed as twins again.""" + return frozenset( + frozenset((r["first_id"], r["second_id"])) for r in self._conn.execute("SELECT * FROM merge_vetoes") + ) def restore(self, memory_id: str) -> None: """Bring back a memory that decay archived. Raises KeyError unless policy archived it.""" @@ -278,7 +226,8 @@ def set_state(self, memory_id: str, state: State, by: Decider) -> None: """Move a memory to a new state and record who did it. Raises KeyError if unknown.""" with self._conn: changed = self._conn.execute( - "UPDATE memories SET state = ?, decided_at = ?, decided_by = ? WHERE id = ?", + "UPDATE memories SET state = ?, decided_at = ?, decided_by = ?" + " WHERE id = ? AND merged_into IS NULL", (state.value, self._now(), by.value, memory_id), ).rowcount if changed == 0: @@ -287,28 +236,16 @@ def set_state(self, memory_id: str, state: State, by: Decider) -> None: def forget(self, memory_id: str) -> bool: """Delete a memory and its evidence. Returns False if it did not exist. - Also deletes what merges kept of it: records that hold this memory as the survivor, and, - if it had been merged into another memory, the evidence it contributed there. + Memories folded into it are the same statement and go with it. A memory that is itself + folded into another can be forgotten by its id; the other memory stays. """ with self._conn: deleted = self._conn.execute("DELETE FROM memories WHERE id = ?", (memory_id,)).rowcount == 1 - # Records held under this memory, and under anything that was itself merged into it. - pending = [memory_id] - while pending: - rows = self._conn.execute( - "SELECT duplicate_id FROM merges WHERE survivor_id = ?", (pending.pop(),) - ).fetchall() - self._conn.executemany("DELETE FROM merges WHERE duplicate_id = ?", [(r[0],) for r in rows]) - pending.extend(r[0] for r in rows) - merged = self._conn.execute("SELECT * FROM merges WHERE duplicate_id = ?", (memory_id,)).fetchone() - if merged is not None: - if merged["undone_at"] is None: - self._conn.executemany( - "DELETE FROM evidence WHERE memory_id = ? AND session_id = ? AND turn_index = ?", - [(merged["survivor_id"], *key) for key in json.loads(merged["snapshot"])["added"]], - ) - self._conn.execute("DELETE FROM merges WHERE duplicate_id = ?", (memory_id,)) - return deleted or merged is not None + self._conn.execute( + "DELETE FROM merge_vetoes WHERE first_id NOT IN (SELECT id FROM memories)" + " OR second_id NOT IN (SELECT id FROM memories)" + ) + return deleted def mark_session_seen(self, source: str, session_id: str, fingerprint: str) -> None: with self._conn: @@ -346,13 +283,25 @@ def session_is_current(self, source: str, session_id: str, fingerprint: str) -> return row is not None and row["fingerprint"] == fingerprint def get(self, memory_id: str) -> Memory | None: - row = self._conn.execute("SELECT * FROM memories WHERE id = ?", (memory_id,)).fetchone() - return self._load(row) if row else None + """One memory with the evidence of everything folded into it. None for an unknown id or + a memory that is itself folded into another.""" + row = self._conn.execute( + "SELECT * FROM memories WHERE id = ? AND merged_into IS NULL", (memory_id,) + ).fetchone() + if row is None: + return None + evidence = self._conn.execute( + _GROUP + "SELECT e.* FROM evidence e JOIN grp ON e.memory_id = grp.id", (memory_id,) + ).fetchall() + seen = self._conn.execute( + _GROUP + "SELECT MAX(m.last_seen_at) FROM memories m JOIN grp ON m.id = grp.id", (memory_id,) + ).fetchone()[0] + return self._build(row, _own_first(evidence, memory_id), seen) def list( self, states: Iterable[State] | None = None, scope: str | None = None ) -> list[Memory]: - clauses, params = [], [] + clauses, params = ["merged_into IS NULL"], [] if states is not None: values = [s.value for s in states] clauses.append(f"state IN ({','.join('?' * len(values))})") @@ -360,40 +309,45 @@ def list( if scope is not None: clauses.append("scope = ?") params.append(scope) - where = (" WHERE " + " AND ".join(clauses)) if clauses else "" rows = self._conn.execute( - "SELECT * FROM memories" + where + " ORDER BY created_at, rowid", params + "SELECT * FROM memories WHERE " + " AND ".join(clauses) + " ORDER BY created_at, rowid", params ).fetchall() - evidence: dict[str, list[Evidence]] = {} - for r in self._conn.execute( - "SELECT * FROM evidence WHERE memory_id IN (SELECT id FROM memories" + where + ")" - " ORDER BY memory_id, session_id, turn_index", - params, - ): - evidence.setdefault(r["memory_id"], []).append( - Evidence(r["session_id"], r["turn_index"], r["quote"]) + + # Evidence and last-seen time of folded memories count towards the memory they end up in. + folded = dict(self._conn.execute("SELECT id, merged_into FROM memories WHERE merged_into IS NOT NULL")) + seen_by = dict(self._conn.execute("SELECT id, last_seen_at FROM memories WHERE merged_into IS NOT NULL")) + + def root(memory_id: str) -> str: + while memory_id in folded: + memory_id = folded[memory_id] + return memory_id + + evidence: dict[str, list[sqlite3.Row]] = {} + for r in self._conn.execute("SELECT * FROM evidence"): + evidence.setdefault(root(r["memory_id"]), []).append(r) + last_seen: dict[str, str] = {} + for memory_id, seen in seen_by.items(): + last_seen[root(memory_id)] = max(last_seen.get(root(memory_id), ""), seen or "") + return [ + self._build( + row, + _own_first(evidence.get(row["id"], ()), row["id"]), + max(row["last_seen_at"] or "", last_seen.get(row["id"], "")) or None, ) - return [self._build(row, tuple(evidence.get(row["id"], ()))) for row in rows] + for row in rows + ] def counts(self) -> dict[str, int]: """Number of memories in each state. Counts only, never content.""" result = {state.value: 0 for state in State} - for row in self._conn.execute("SELECT state, COUNT(*) AS n FROM memories GROUP BY state"): + for row in self._conn.execute( + "SELECT state, COUNT(*) AS n FROM memories WHERE merged_into IS NULL GROUP BY state" + ): result[row["state"]] = row["n"] return result - def _load(self, row: sqlite3.Row) -> Memory: - evidence = tuple( - Evidence(r["session_id"], r["turn_index"], r["quote"]) - for r in self._conn.execute( - "SELECT * FROM evidence WHERE memory_id = ? ORDER BY session_id, turn_index", - (row["id"],), - ) - ) - return self._build(row, evidence) - @staticmethod - def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...]) -> Memory: + def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...], last_seen_at: str | None) -> Memory: return Memory( id=row["id"], text=row["text"], @@ -403,6 +357,14 @@ def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...]) -> Memory: created_at=row["created_at"], decided_at=row["decided_at"], decided_by=Decider(row["decided_by"]) if row["decided_by"] else None, - last_seen_at=row["last_seen_at"], + last_seen_at=last_seen_at, evidence=evidence, ) + + +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] = {} + for r in sorted(rows, key=lambda r: (r["session_id"], r["turn_index"], r["memory_id"] != memory_id)): + unique.setdefault((r["session_id"], r["turn_index"]), Evidence(r["session_id"], r["turn_index"], r["quote"])) + return tuple(unique.values()) diff --git a/personakit/tidy.py b/personakit/tidy.py index 402c036..d14da56 100644 --- a/personakit/tidy.py +++ b/personakit/tidy.py @@ -7,7 +7,7 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from personakit import decay, twins from personakit.model import Decider, State @@ -39,14 +39,22 @@ def make_plan( archive: bool = True, ) -> Plan: plan = Plan() + unconfirmed = store.list(states=[State.UNCONFIRMED]) if merge: - undone = frozenset( - frozenset((r.duplicate_id, r.survivor_id)) for r in store.merges(active_only=False) if r.undone_at - ) - plan.groups = twins.find_twins(store.list(states=[State.UNCONFIRMED]), threshold, undone) + plan.groups = twins.find_twins(unconfirmed, threshold, store.merge_vetoes()) if archive: - folded = {d.id for g in plan.groups for d in g.duplicates} # about to disappear, so not archived too - plan.stale = [m for m in decay.find_stale(store.list(states=[State.UNCONFIRMED]), now, days) if m.id not in folded] + # A folded memory is not archived as well, and the memory it folds into counts as seen + # whenever any member of its group was seen. + folded = {d.id for g in plan.groups for d in g.duplicates} + freshest = { + g.survivor.id: max((m.last_seen_at or "") for m in (g.survivor, *g.duplicates)) for g in plan.groups + } + candidates = [ + replace(m, last_seen_at=freshest[m.id]) if m.id in freshest else m + for m in unconfirmed + if m.id not in folded + ] + plan.stale = decay.find_stale(candidates, now, days) return plan diff --git a/personakit/twins.py b/personakit/twins.py index 5f63422..5839aba 100644 --- a/personakit/twins.py +++ b/personakit/twins.py @@ -1,14 +1,16 @@ """Find near-identical memories that were extracted from the same session. -Pure functions, no I/O. Detection is lexical (shared content words), so it only catches memories -that are worded almost the same way; paraphrases are left alone on purpose. A false merge is worse +Pure functions, no I/O. Detection is lexical (shared words), so it only catches memories that +are worded almost the same way; paraphrases are left alone on purpose. A false merge is worse than a missed one, so every rule here leans towards "not a twin": * only unconfirmed memories, so an owner's decision is never overridden; * both memories must rest on the same single session, and neither may be assistant-proposed; * same category and scope; -* the numbers they mention (digits or words like "two") must be equal, and they must agree on negation ("not", "never", - "avoid" ...), because "uses 2 spaces" and "does not use 2 spaces" share nearly every word. +* the numbers they mention (digits or words like "two") must be equal, and they must agree on + negation ("not", "never", "doesn't", "avoid" ...); +* the words they share must appear in the same order, so "X over Y" is not "Y over X"; +* every word counts, however short ("Go", "C", "JS"), apart from common filler words. Matching is against one anchor memory per group, never chained, so a group cannot drift into unrelated memories. @@ -19,18 +21,19 @@ import re from collections.abc import Iterable from dataclasses import dataclass -from difflib import SequenceMatcher from personakit.model import PROPOSED_BY_ASSISTANT, Memory, State -from personakit.retrieve import word_list +from personakit.retrieve import STOP_WORDS DEFAULT_THRESHOLD = 0.8 MIN_SHARED_WORDS = 3 +_TOKEN = re.compile(r"[a-z0-9+#]+") +_FILLER = STOP_WORDS | frozenset("a an as at be by do i in is it me my of on or to we".split()) _NUMBER = re.compile(r"\d+(?:[.,]\d+)?|\b(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|twice|once|half)\b") _NEGATION = re.compile( r"\b(?:not|no|never|none|nor|cannot|without|avoid(?:s|ed)?|dislike[sd]?|hate[sd]?|stop(?:s|ped)?" - r"|(?:don|doesn|didn|isn|aren|won|wasn|can|shouldn|wouldn)'?t)\b" + r"|\w+n't|(?:don|doesn|didn|isn|aren|won|wasn|weren|can|couldn|shouldn|wouldn|hasn|haven|hadn)t)\b" ) @@ -42,30 +45,44 @@ class TwinGroup: duplicates: tuple[Memory, ...] +@dataclass(frozen=True) +class _Features: + """What similarity compares, computed once per memory.""" + + words: tuple[str, ...] + numbers: tuple[str, ...] + negated: bool + + def _stem(word: str) -> str: return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word -def _content(text: str) -> list[str]: - return [_stem(w) for w in word_list(text)] - +def _features(text: str) -> _Features: + lowered = text.lower().replace("’", "'") + negated = bool(_NEGATION.search(lowered)) + words = tuple(_stem(w) for w in _TOKEN.findall(lowered.replace("'", "")) if w not in _FILLER) + return _Features(words, tuple(sorted(_NUMBER.findall(lowered))), negated) -def similarity(a: str, b: str) -> float: - """How alike two texts are, from 0 to 1: the lower of the share of content words they have in - common and how well those words line up in order (so "unit before integration tests" is not - the same as "integration before unit tests"). - 0 when they disagree on numbers or negation, or share fewer than MIN_SHARED_WORDS words. - """ - if sorted(_NUMBER.findall(a.lower())) != sorted(_NUMBER.findall(b.lower())): +def _score(a: _Features, b: _Features) -> float: + if a.numbers != b.numbers or a.negated != b.negated: return 0.0 - if bool(_NEGATION.search(a.lower())) != bool(_NEGATION.search(b.lower())): + shared = set(a.words) & set(b.words) + if len(shared) < MIN_SHARED_WORDS: return 0.0 - left, right = _content(a), _content(b) - shared = len(set(left) & set(right)) - if shared < MIN_SHARED_WORDS: + if [w for w in a.words if w in shared] != [w for w in b.words if w in shared]: return 0.0 - return min(shared / len(set(left) | set(right)), SequenceMatcher(None, left, right).ratio()) + return len(shared) / len(set(a.words) | set(b.words)) + + +def similarity(a: str, b: str) -> float: + """Share of words two texts have in common, from 0 to 1. + + 0 when they disagree on numbers or negation, share fewer than MIN_SHARED_WORDS words, or + use the shared words in a different order. + """ + return _score(_features(a), _features(b)) def _single_session(memory: Memory) -> str | None: @@ -86,23 +103,24 @@ def find_twins( The survivor is the oldest memory in a group, so results do not depend on input order. """ eligible = sorted( - (m for m in memories if m.state == State.UNCONFIRMED and _single_session(m)), - key=lambda m: (m.created_at or "", m.id), + ((m, _single_session(m), _features(m.text)) for m in memories if m.state == State.UNCONFIRMED), + key=lambda item: (item[0].created_at or "", item[0].id), ) + eligible = [item for item in eligible if item[1]] taken: set[str] = set() groups: list[TwinGroup] = [] - for index, anchor in enumerate(eligible): + for index, (anchor, session, features) in enumerate(eligible): if anchor.id in taken: continue twins = tuple( other - for other in eligible[index + 1 :] + for other, other_session, other_features in eligible[index + 1 :] if other.id not in taken - and _single_session(other) == _single_session(anchor) + and other_session == session and other.category == anchor.category and other.scope == anchor.scope and frozenset((anchor.id, other.id)) not in vetoed - and similarity(anchor.text, other.text) >= threshold + and _score(features, other_features) >= threshold ) if twins: taken.update(m.id for m in twins) diff --git a/tests/test_cli.py b/tests/test_cli.py index fded416..0326805 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -169,12 +169,15 @@ def test_nothing_to_tidy_on_a_fresh_store(self): def test_tidy_rejects_bad_numbers(self): self.assertEqual(self.run_cli("tidy", "--days", "0")[0], 2) self.assertEqual(self.run_cli("tidy", "--threshold", "1.5")[0], 2) + self.assertEqual(self.run_cli("tidy", "--days", "99999999")[0], 2) + self.assertEqual(self.run_cli("digest", "--days", "-5")[0], 2) + self.assertEqual(self.run_cli("digest", "--days", "99999999")[0], 2) def test_digest_prints_text_or_json(self): self.seed() _, text, _ = self.run_cli("digest") self.assertIn("PersonaKit digest, last 7 days", text) - data = json.loads(self.run_cli("digest", "--days", "99999", "--json")[1]) + data = json.loads(self.run_cli("digest", "--days", "36500", "--json")[1]) self.assertEqual(data["new"], 2) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index f46d61e..22c7dcc 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -66,6 +66,17 @@ def setUp(self): self.store = Store(":memory:") self.addCleanup(self.store.close) + def test_proposing_an_archived_statement_does_not_bring_it_back(self): + memory = Memory(text="You use Rust for tools.", category="tools", evidence=(Evidence("s1", 0, "I write Rust."),)) + self.store.add(memory) + self.store.set_state(memory.id, State.ARCHIVED, Decider.POLICY) + before = self.store.get(memory.id).last_seen_at + result = mcp_server.propose_memory(self.store, memory.text, "anything") + self.assertFalse(result["new"]) + after = self.store.get(memory.id) + self.assertEqual((after.state, after.last_seen_at), (State.ARCHIVED, before)) + self.assertEqual(mcp_server.read_memories(self.store, "rust tools")["memories"], []) + def test_proposal_is_stored_unconfirmed_and_marked_as_assistant_proposed(self): result = mcp_server.propose_memory(self.store, "You use Rust.", "I write Rust daily", "tools") self.assertTrue(result["stored"]) diff --git a/tests/test_merge_store.py b/tests/test_merge_store.py index 94736f3..4bceb17 100644 --- a/tests/test_merge_store.py +++ b/tests/test_merge_store.py @@ -1,4 +1,3 @@ -import json import sqlite3 import tempfile import unittest @@ -33,38 +32,56 @@ def setUp(self): def merged(self): self.store.merge(self.dup.id, self.keep.id) - def test_merge_moves_evidence_and_removes_the_duplicate(self): + def quotes(self, memory_id): + return [e.quote for e in self.store.get(memory_id).evidence] + + def test_merge_hides_the_duplicate_and_shows_its_evidence_on_the_survivor(self): self.merged() self.assertIsNone(self.store.get(self.dup.id)) - self.assertEqual([(e.turn_index, e.quote) for e in self.store.get(self.keep.id).evidence], [(0, "Skip the pep talk."), (1, "Be blunt.")]) - self.assertEqual([r.duplicate_id for r in self.store.merges()], [self.dup.id]) - - def test_undo_restores_the_duplicate_and_takes_back_only_what_it_added(self): + self.assertEqual([m.id for m in self.store.list()], [self.keep.id]) + self.assertEqual(self.quotes(self.keep.id), ["Skip the pep talk.", "Be blunt."]) + self.assertEqual(self.store.list()[0].evidence, self.store.get(self.keep.id).evidence) + self.assertEqual(self.store.counts()["unconfirmed"], 1) + self.assertEqual([(r.duplicate_id, r.duplicate_text) for r in self.store.merges()], [(self.dup.id, self.dup.text)]) + + def test_undo_is_exact(self): + before = (self.store.get(self.keep.id), self.store.get(self.dup.id)) + self.clock.value = "2026-02-01T00:00:00Z" + self.store.add(mem(self.dup.text, (1, "Be blunt."))) # the duplicate was seen more recently + fresh_dup = self.store.get(self.dup.id) self.merged() + self.assertEqual(self.store.get(self.keep.id).last_seen_at, "2026-02-01T00:00:00Z") self.store.undo_merge(self.dup.id) - restored = self.store.get(self.dup.id) - self.assertEqual((restored.text, restored.state), (self.dup.text, State.UNCONFIRMED)) - self.assertEqual(len(restored.evidence), 2) - # the quote both memories shared stays with the survivor - self.assertEqual([e.turn_index for e in self.store.get(self.keep.id).evidence], [0]) + self.assertEqual((self.store.get(self.keep.id), self.store.get(self.dup.id)), (before[0], fresh_dup)) self.assertEqual(self.store.merges(), []) + with self.assertRaises(KeyError): + self.store.undo_merge(self.dup.id) - def test_undo_drops_the_stored_text_but_remembers_the_pair(self): + def test_an_undone_pair_stays_vetoed_even_after_other_merges(self): + other = mem("You prefer direct, practical feedback always.", (7, "Always.")) + self.store.add(other) self.merged() self.store.undo_merge(self.dup.id) - (record,) = self.store.merges(active_only=False) - self.assertEqual((record.duplicate_text, bool(record.undone_at)), ("", True)) - with self.assertRaises(KeyError): - self.store.undo_merge(self.dup.id) + self.store.merge(self.dup.id, other.id) + self.store.undo_merge(self.dup.id) + self.assertEqual( + self.store.merge_vetoes(), + {frozenset((self.dup.id, self.keep.id)), frozenset((self.dup.id, other.id))}, + ) - def test_only_unconfirmed_memories_can_merge(self): - self.store.set_state(self.keep.id, State.APPROVED, Decider.OWNER) - with self.assertRaises(ValueError): - self.merged() + def test_only_unconfirmed_standalone_memories_can_merge(self): with self.assertRaises(ValueError): self.store.merge(self.dup.id, self.dup.id) with self.assertRaises(KeyError): self.store.merge("m_missing", self.keep.id) + self.store.set_state(self.keep.id, State.APPROVED, Decider.OWNER) + with self.assertRaises(ValueError): + self.merged() + + def test_a_merged_memory_cannot_change_state_on_its_own(self): + self.merged() + with self.assertRaises(KeyError): + self.store.set_state(self.dup.id, State.APPROVED, Decider.OWNER) def test_extracting_a_merged_statement_again_feeds_the_survivor(self): self.merged() @@ -74,33 +91,48 @@ def test_extracting_a_merged_statement_again_feeds_the_survivor(self): survivor = self.store.get(self.keep.id) self.assertEqual(len(survivor.evidence), 3) self.assertEqual(survivor.last_seen_at, "2026-02-01T00:00:00Z") + self.assertEqual(self.store.list()[0].last_seen_at, "2026-02-01T00:00:00Z") - def test_forgetting_the_survivor_deletes_what_the_merge_kept(self): + def chain(self): + """dup folded into keep, then keep folded into a third memory.""" + self.third = mem("You prefer direct, practical feedback always.", (7, "Always.")) + self.store.add(self.third) self.merged() - self.assertTrue(self.store.forget(self.keep.id)) - self.assertEqual(self.store.merges(active_only=False), []) - self.assertNotIn(self.dup.text, json.dumps(self.store._conn.execute("SELECT * FROM merges").fetchall())) + self.store.merge(self.keep.id, self.third.id) - def test_forgetting_removes_chained_merges_as_well(self): - third = mem("You prefer direct, practical feedback always.", (7, "Always.")) - self.store.add(third) - self.merged() - self.store.merge(self.keep.id, third.id) # the survivor is itself folded into a third memory - self.assertTrue(self.store.forget(third.id)) - self.assertEqual(self.store._conn.execute("SELECT COUNT(*) FROM merges").fetchone()[0], 0) + def test_chained_merges_show_all_evidence_on_the_last_survivor(self): + self.chain() + self.assertEqual(self.quotes(self.third.id), ["Skip the pep talk.", "Be blunt.", "Always."]) + self.assertEqual(self.store.list()[0].evidence, self.store.get(self.third.id).evidence) - def test_forgetting_a_merged_duplicate_removes_it_and_the_evidence_it_gave(self): - self.merged() + def test_extracting_again_after_a_chained_merge_works_and_lands_on_the_last_survivor(self): + self.chain() + self.assertFalse(self.store.add(mem(self.dup.text, (9, "Blunt again.")))) + self.assertIn("Blunt again.", self.quotes(self.third.id)) + + def test_forgetting_a_merged_memory_removes_every_quote_it_brought_even_through_a_chain(self): + self.chain() + self.store.add(mem(self.dup.text, (9, "Blunt again."))) # arrived after the merge self.assertTrue(self.store.forget(self.dup.id)) - self.assertEqual([e.turn_index for e in self.store.get(self.keep.id).evidence], [0]) - self.assertEqual(self.store.merges(active_only=False), []) + self.assertEqual(self.quotes(self.third.id), ["Skip the pep talk.", "Always."]) + self.store.undo_merge(self.keep.id) + self.assertEqual(self.quotes(self.keep.id), ["Skip the pep talk."]) + everything = repr([tuple(r) for r in self.store._conn.execute("SELECT * FROM evidence")]) + self.assertNotIn("Be blunt.", everything) + self.assertNotIn("Blunt again.", everything) self.assertFalse(self.store.forget(self.dup.id)) - def test_forgetting_after_undo_clears_the_pair_record_too(self): + def test_forgetting_the_survivor_forgets_everything_folded_into_it(self): + self.chain() + self.assertTrue(self.store.forget(self.third.id)) + for table in ("memories", "evidence", "merge_vetoes"): + self.assertEqual(self.store._conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0], 0, table) + + def test_forgetting_clears_vetoes_that_mention_the_memory(self): self.merged() self.store.undo_merge(self.dup.id) - self.assertTrue(self.store.forget(self.dup.id)) - self.assertEqual(self.store.merges(active_only=False), []) + self.store.forget(self.dup.id) + self.assertEqual(self.store.merge_vetoes(), frozenset()) def test_merges_can_be_filtered_by_time(self): self.clock.value = "2026-03-01T00:00:00Z" @@ -147,6 +179,13 @@ def test_extracting_an_archived_statement_again_revives_it_only_if_policy_archiv self.store.add(mem(self.m.text, (5, "Python once more."))) self.assertEqual(self.store.get(self.m.id).state, State.ARCHIVED) + def test_an_unobserved_add_neither_revives_nor_refreshes(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.clock.value = "2026-09-01T00:00:00Z" + self.assertFalse(self.store.add(mem(self.m.text, (4, "Said by an assistant.")), observed=False)) + kept = self.store.get(self.m.id) + self.assertEqual((kept.state, kept.last_seen_at), (State.ARCHIVED, "2026-01-01T00:00:00Z")) + def test_database_from_before_merges_is_upgraded_and_backfilled(self): path = Path(tempfile.mkdtemp()) / "v2.db" old = sqlite3.connect(path) diff --git a/tests/test_tidy.py b/tests/test_tidy.py index 6eba97e..041acdd 100644 --- a/tests/test_tidy.py +++ b/tests/test_tidy.py @@ -63,6 +63,14 @@ def test_a_merge_the_owner_undid_is_not_proposed_again(self): tidy.undo(self.store, self.twin.id) self.assertEqual(tidy.make_plan(self.store, NOW, days=90, archive=False).groups, []) + def test_a_survivor_is_not_stale_when_its_twin_was_seen_recently(self): + self.store.add(mem(self.twin.text, turn=1)) # the twin is extracted again today + plan = tidy.make_plan(self.store, NOW, days=90) + self.assertEqual((plan.merges, [m.id for m in plan.stale]), (1, [self.old.id])) + tidy.apply(self.store, plan) + self.assertEqual(self.store.get(self.keep.id).state, State.UNCONFIRMED) + self.assertEqual(tidy.make_plan(self.store, NOW, days=90).stale, []) + def test_steps_can_run_alone(self): self.assertEqual(tidy.make_plan(self.store, NOW, merge=False).groups, []) self.assertEqual(tidy.make_plan(self.store, NOW, archive=False).stale, []) diff --git a/tests/test_twins.py b/tests/test_twins.py index f14e1af..31997b1 100644 --- a/tests/test_twins.py +++ b/tests/test_twins.py @@ -37,7 +37,20 @@ def test_negation_flips_the_meaning_so_they_are_never_twins(self): self.assertEqual(similarity("You use tabs for indentation.", "You don't use tabs for indentation."), 0.0) def test_swapped_order_is_not_a_twin(self): - self.assertLess(similarity("You prefer unit tests before integration tests.", "You prefer integration tests before unit tests."), 0.8) + self.assertEqual(similarity("You prefer unit tests before integration tests.", "You prefer integration tests before unit tests."), 0.0) + self.assertEqual(similarity("Prefers JS over TS for frontend projects at work", "Prefers TS over JS for frontend projects at work"), 0.0) + + def test_short_words_count(self): + self.assertLess(similarity("You write backend services in Go.", "You write backend services in C."), 0.8) + + def test_negation_is_seen_with_any_apostrophe_and_any_contraction(self): + plain = "Likes verbose commit messages in reviews" + for negated in ( + "Doesn\u2019t like verbose commit messages in reviews", + "Hasnt liked verbose commit messages in reviews", + "Hadn't liked verbose commit messages in reviews", + ): + self.assertEqual(similarity(negated, plain), 0.0, negated) def test_number_words_count_like_digits(self): self.assertEqual(similarity("You live with two cats at home.", "You live with three cats at home."), 0.0) From ca42c3e800f44320d0459891570426c2b9c93ddc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 07:04:58 +0000 Subject: [PATCH 3/3] Extension points for relevance and similarity, off unless named A plugin registers in the personakit.plugins entry-point group and replaces a scoring function. Nothing loads unless PERSONAKIT_PLUGINS names it. Read policy, twin eligibility and every state change stay in the core; tests prove a plugin cannot serve restricted memories or merge across sessions. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- README.md | 1 + docs/ARCHITECTURE.md | 1 + docs/PLUGINS.md | 54 +++++++++++++++++++ docs/PRIVACY.md | 3 ++ docs/REVIEW-LOG.md | 1 + personakit/cli.py | 18 +++++-- personakit/mcp_server.py | 12 ++--- personakit/plugins.py | 59 +++++++++++++++++++++ personakit/retrieve.py | 26 ++++++--- personakit/tidy.py | 3 +- personakit/twins.py | 39 ++++++++------ tests/test_cli.py | 6 +++ tests/test_plugins.py | 111 +++++++++++++++++++++++++++++++++++++++ 13 files changed, 298 insertions(+), 36 deletions(-) create mode 100644 docs/PLUGINS.md create mode 100644 personakit/plugins.py create mode 100644 tests/test_plugins.py diff --git a/README.md b/README.md index 21772a0..645b116 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,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 two extension points 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 162e7bb..6aff07c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -50,6 +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 them in `PERSONAKIT_PLUGINS`. A plugin scores; 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 | diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md new file mode 100644 index 0000000..4187fcf --- /dev/null +++ b/docs/PLUGINS.md @@ -0,0 +1,54 @@ +# Plugins + +PersonaKit has two extension points. Both replace 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) | +| `similarity` | `(a: str, b: str) -> float` between 0 and 1 | shared words, with number, negation and order guards | `personakit tidy` (which same-session memories are twins) | + +## 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. +- Only unconfirmed memories from the same single session, with the same category and scope, can + be proposed as twins. Merging still needs `personakit tidy --apply` and is reversible. +- No hook can approve, restrict, archive, restore 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 tidy +``` + +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.similarity = my_similarity # leave hooks.relevance alone to keep the built-in +``` + +For anything beyond scoring, use PersonaKit as a library: `personakit.store.Store` is the one +place that reads and writes the database, and `Store.merge`, `Store.undo_merge`, +`Store.set_state` and `Store.restore` are the same reversible operations the CLI uses. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index bb00062..441d2eb 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -24,3 +24,6 @@ model. Assistants cannot merge, undo, 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 or similarity is scored and cannot change what is served or merged, 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 d75688a..0808137 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -29,3 +29,4 @@ duplicated logic. Each entry records the result. | `personakit/store.py`, `model.py`, `retrieve.py`, `review.py`, `cli.py` (0.2 changes) | 2026-11-13 | migration 3 (`last_seen_at`, `merged_into`, `merge_vetoes`); a folded memory keeps its own rows, so forget leaves nothing behind; assistant proposals cannot revive or refresh a memory; `PROPOSED_BY_ASSISTANT` moved to `model` | clean | | `tests/test_twins.py`, `test_decay.py`, `test_merge_store.py`, `test_tidy.py`, `test_cli.py` (changes) | 2026-11-13 | invented sentences only | clean | | 0.2 changes, second pass | 2026-11-14 | security and code review run on the branch: quotes could outlive `forget` through chained merges, an assistant proposal could revive a decay-archived memory, short words and typographic apostrophes slipped past twin checks. All fixed, each with a regression test | clean | +| `personakit/plugins.py`, `docs/PLUGINS.md`, `tests/test_plugins.py` | 2026-11-14 | none; opt-in by name, scoring only, policy tests prove a plugin cannot widen what is served or merged | clean | diff --git a/personakit/cli.py b/personakit/cli.py index 1c55bd5..c0bbfaa 100644 --- a/personakit/cli.py +++ b/personakit/cli.py @@ -8,7 +8,7 @@ import sys from pathlib import Path -from personakit import decay, digest, llm, mcp_server, review, stats, sweep, tidy, twins +from personakit import decay, digest, llm, mcp_server, plugins, review, stats, sweep, tidy, twins from personakit.ingest import ADAPTERS from personakit.model import State from personakit.store import Store @@ -73,7 +73,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: @@ -121,7 +125,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 @@ -135,7 +139,13 @@ def _tidy(args: argparse.Namespace, store: Store) -> int: print(f"--days must be between 1 and {MAX_DAYS} and --threshold between 0 and 1", file=sys.stderr) return 2 plan = tidy.make_plan( - store, store.now(), args.days, args.threshold, merge=args.only != "archive", archive=args.only != "merge" + store, + store.now(), + args.days, + args.threshold, + merge=args.only != "archive", + archive=args.only != "merge", + similarity=plugins.load().similarity, ) report = tidy.apply(store, plan) if args.apply else None if args.json: diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index c4d814e..98c9464 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -14,10 +14,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": [ @@ -55,7 +55,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 @@ -66,7 +66,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: @@ -76,5 +76,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..aab1fd8 --- /dev/null +++ b/personakit/plugins.py @@ -0,0 +1,59 @@ +"""Extension points: swap how relevance and similarity are 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 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 +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. +""" + +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, twins + +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 defaults are the built-in word-based ones.""" + + relevance: retrieve.Relevance = retrieve.overlap # (question, memories) -> one score per memory + similarity: twins.Similarity = twins.similarity # (text, text) -> 0 to 1 + + +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 callable(hooks.relevance) or not callable(hooks.similarity): + 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 05ebb3e..3803304 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_WORDS} -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/personakit/tidy.py b/personakit/tidy.py index d14da56..4283783 100644 --- a/personakit/tidy.py +++ b/personakit/tidy.py @@ -37,11 +37,12 @@ def make_plan( threshold: float = twins.DEFAULT_THRESHOLD, merge: bool = True, archive: bool = True, + similarity: twins.Similarity = twins.similarity, ) -> Plan: plan = Plan() unconfirmed = store.list(states=[State.UNCONFIRMED]) if merge: - plan.groups = twins.find_twins(unconfirmed, threshold, store.merge_vetoes()) + plan.groups = twins.find_twins(unconfirmed, threshold, store.merge_vetoes(), similarity) if archive: # A folded memory is not archived as well, and the memory it folds into counts as seen # whenever any member of its group was seen. diff --git a/personakit/twins.py b/personakit/twins.py index 5839aba..fe4ebce 100644 --- a/personakit/twins.py +++ b/personakit/twins.py @@ -19,8 +19,9 @@ from __future__ import annotations import re -from collections.abc import Iterable +from collections.abc import Callable, Iterable from dataclasses import dataclass +from functools import lru_cache from personakit.model import PROPOSED_BY_ASSISTANT, Memory, State from personakit.retrieve import STOP_WORDS @@ -58,6 +59,7 @@ def _stem(word: str) -> str: return word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word +@lru_cache(maxsize=4096) def _features(text: str) -> _Features: lowered = text.lower().replace("’", "'") negated = bool(_NEGATION.search(lowered)) @@ -65,24 +67,24 @@ def _features(text: str) -> _Features: return _Features(words, tuple(sorted(_NUMBER.findall(lowered))), negated) -def _score(a: _Features, b: _Features) -> float: - if a.numbers != b.numbers or a.negated != b.negated: +def similarity(a: str, b: str) -> float: + """The built-in similarity: share of words two texts have in common, from 0 to 1. + + 0 when they disagree on numbers or negation, share fewer than MIN_SHARED_WORDS words, or + use the shared words in a different order. + """ + left, right = _features(a), _features(b) + if left.numbers != right.numbers or left.negated != right.negated: return 0.0 - shared = set(a.words) & set(b.words) + shared = set(left.words) & set(right.words) if len(shared) < MIN_SHARED_WORDS: return 0.0 - if [w for w in a.words if w in shared] != [w for w in b.words if w in shared]: + if [w for w in left.words if w in shared] != [w for w in right.words if w in shared]: return 0.0 - return len(shared) / len(set(a.words) | set(b.words)) + return len(shared) / len(set(left.words) | set(right.words)) -def similarity(a: str, b: str) -> float: - """Share of words two texts have in common, from 0 to 1. - - 0 when they disagree on numbers or negation, share fewer than MIN_SHARED_WORDS words, or - use the shared words in a different order. - """ - return _score(_features(a), _features(b)) +Similarity = Callable[[str, str], float] def _single_session(memory: Memory) -> str | None: @@ -96,31 +98,34 @@ def find_twins( memories: Iterable[Memory], threshold: float = DEFAULT_THRESHOLD, vetoed: frozenset[frozenset[str]] = frozenset(), + similarity: Similarity = similarity, ) -> list[TwinGroup]: """Group eligible memories into survivor + duplicates. + `similarity` only scores a pair of texts; which memories are eligible is decided here. + `vetoed` holds id pairs the owner already un-merged; they are never proposed again. The survivor is the oldest memory in a group, so results do not depend on input order. """ eligible = sorted( - ((m, _single_session(m), _features(m.text)) for m in memories if m.state == State.UNCONFIRMED), + ((m, _single_session(m)) for m in memories if m.state == State.UNCONFIRMED), key=lambda item: (item[0].created_at or "", item[0].id), ) eligible = [item for item in eligible if item[1]] taken: set[str] = set() groups: list[TwinGroup] = [] - for index, (anchor, session, features) in enumerate(eligible): + for index, (anchor, session) in enumerate(eligible): if anchor.id in taken: continue twins = tuple( other - for other, other_session, other_features in eligible[index + 1 :] + for other, other_session in eligible[index + 1 :] if other.id not in taken and other_session == session and other.category == anchor.category and other.scope == anchor.scope and frozenset((anchor.id, other.id)) not in vetoed - and _score(features, other_features) >= threshold + and similarity(anchor.text, other.text) >= threshold ) if twins: taken.update(m.id for m in twins) diff --git a/tests/test_cli.py b/tests/test_cli.py index 0326805..8f14d37 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -173,6 +173,12 @@ def test_tidy_rejects_bad_numbers(self): self.assertEqual(self.run_cli("digest", "--days", "-5")[0], 2) self.assertEqual(self.run_cli("digest", "--days", "99999999")[0], 2) + 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("tidy") + self.assertEqual(code, 2) + self.assertIn("not-installed", err) + def test_digest_prints_text_or_json(self): self.seed() _, text, _ = self.run_cli("digest") diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..1ab10c3 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,111 @@ +import unittest +from unittest import mock + +from personakit import mcp_server, plugins, retrieve, tidy, twins +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 + + +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 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): + hooks = self.load([]) + self.assertIs(hooks.relevance, retrieve.overlap) + self.assertIs(hooks.similarity, twins.similarity) + + def test_installed_but_unnamed_plugins_stay_off(self): + self.assertIs(self.load(["twin-all"]).relevance, retrieve.overlap) + + def test_named_plugins_replace_only_what_they_provide(self): + hooks = self.load(["match-all", "twin-all"]) + self.assertIs(hooks.relevance, everything_matches) + self.assertEqual(hooks.similarity("a", "b"), 1.0) + + 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 , ,twin-all "}): + self.assertEqual(plugins.enabled_names(), ["match-all", "twin-all"]) + 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 or what may be merged.""" + + 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) + + def test_similarity_plugin_cannot_merge_across_sessions_or_touch_decisions(self): + same_a, same_b = mem("First statement here."), mem("Completely different words.", turn=1) + other_session = mem("Another session entirely.", session="s2") + approved = mem("An approved statement.", turn=2) + for memory in (same_a, same_b, other_session, approved): + self.store.add(memory) + self.store.set_state(approved.id, State.APPROVED, Decider.OWNER) + plan = tidy.make_plan(self.store, self.store.now(), archive=False, similarity=lambda a, b: 1.0) + folded = {d.id for g in plan.groups for d in g.duplicates} | {g.survivor.id for g in plan.groups} + self.assertEqual(folded, {same_a.id, same_b.id}) + + +if __name__ == "__main__": + unittest.main()