diff --git a/README.md b/README.md index ce4117b..2accb9a 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ 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: archive unconfirmed memories unseen for 90 days +personakit tidy # plan: fold near-identical twins, archive stale memories personakit tidy --apply # carry the plan out (reverse any 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 @@ -104,8 +104,8 @@ 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) archives unconfirmed memories not seen again for 90 days. It shows a - plan first; nothing changes without `--apply`, nothing is deleted, and `personakit undo ` +6. **Tidy** (on request) folds near-identical memories into one, and + archives unconfirmed memories not seen again for 90 days. It shows a plan first; nothing changes without `--apply`, nothing is deleted, and `personakit undo ` reverses a step. A memory is always in one of four states: @@ -126,6 +126,9 @@ 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 any session, and misses paraphrases on purpose: a missed merge costs nothing, a wrong + one costs trust. Expect it to find little when the same fact is worded differently each time. - **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. @@ -140,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 of near-identical memories (reversible) | Available in 0.2 | | Decay of stale unconfirmed memories (reversible) | Available in 0.2 | | Digest of the last days | Available in 0.2 | | ChatGPT, claude.ai and Gemini export import | Planned for 0.3 | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c95de40..69455c5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -17,7 +17,7 @@ flowchart TB RV[review: CLI] MCP[mcp_server] SS[stats: local counts] - TD[tidy: decay, on request] + TD[tidy: twins + decay, on request] DG[digest: last days, local] end CC --> IN @@ -46,10 +46,11 @@ 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 of one category and scope, across sessions. Word-based, deliberately cautious (the order of shared words must agree); numbers and negation must agree whatever scores a pair. Pure functions. | `model`, `retrieve` | | `decay` | Finds unconfirmed memories not seen again for a long time (90 days by default). Pure functions. | `model` | -| `tidy` | Turns `decay` into a plan (read-only), applies it only on request, and reverses single steps. | `decay`, `store` | -| `digest` | A summary of the last days: new and archived memories, what awaits review, read counts. Prints memory text, never quotes, to your terminal only. | `store`, `decay` | -| `plugins` | One extension point, `relevance`, loaded only when the owner names a plugin in `PERSONAKIT_PLUGINS`. A plugin scores; policy stays in `retrieve` and `store`. See [PLUGINS.md](PLUGINS.md). | `retrieve` | +| `tidy` | Turns `twins` and `decay` into a plan (read-only), applies it only on request, and reverses single steps. | `twins`, `decay`, `store` | +| `digest` | A summary of the last days: new, merged and archived memories, what awaits review, read counts. Prints memory text, never quotes, to your terminal only. | `store`, `decay` | +| `plugins` | Two extension points, `relevance` and `similarity`, loaded only when the owner names a plugin in `PERSONAKIT_PLUGINS`. A plugin scores; policy stays in `retrieve`, `twins` and `store`. See [PLUGINS.md](PLUGINS.md). | `retrieve`, `twins` | | `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 | @@ -61,6 +62,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**: 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. @@ -71,9 +76,10 @@ model, only `ingest` reads session files.** A second implementation of any of th 2. Unconfirmed memories are served, labelled as unconfirmed. Review is a quality tool, not a gate. 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. - One thing changes unconfirmed memories, and only when you run `personakit tidy --apply` (the - default is a plan that changes nothing): archiving memories not seen again for 90 days. It is - reversible with `personakit undo `, and a memory that decay archived comes back by itself + Two things change unconfirmed memories, and only when you run `personakit tidy --apply` (the + default is a plan that changes nothing): folding near-identical twins together, and archiving + memories not seen again for 90 days. Both are reversible with `personakit undo `, and 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. @@ -86,4 +92,6 @@ See the roadmap for what is planned. ## Limits in 0.2 -Decay looks only at how long ago a statement was last extracted, not at whether it is still true. +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. On stores +where the same fact is worded differently each time it finds little. Decay looks only at how long ago a statement was last extracted, not at whether it is still true. diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 98f26d0..cd0954f 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -1,10 +1,11 @@ # Plugins -PersonaKit has one extension point. It replaces a scoring function and nothing else. +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 memories are twins) | ## What a plugin cannot do @@ -12,7 +13,10 @@ Policy stays in the core, whatever a plugin returns: - Restricted and archived memories are never served. A relevance score only orders what the read policy already allows. -- No hook can approve, restrict, archive or forget. +- Only unconfirmed memories with the same category and scope, none resting on an assistant's + proposal, can be proposed as twins, and only when they mention the same numbers and agree on + negation. Merging still needs `personakit tidy --apply` and is reversible. +- 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. @@ -24,7 +28,7 @@ Nothing is loaded just because it is installed. Name the plugins you want: ```sh pip install some-personakit-plugin export PERSONAKIT_PLUGINS=some-name # comma separated for several, applied in order -personakit serve +personakit tidy ``` A name that is not installed is an error, not a silent fallback. @@ -43,9 +47,9 @@ some-name = "some_package:register" ```python # some_package/__init__.py def register(hooks): - hooks.relevance = my_relevance + 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.set_state` is the same operation the CLI -uses. +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 d3766b1..2d607b4 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -16,11 +16,14 @@ - **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`, archives stale - unconfirmed memories. `personakit undo` brings one back. Nothing leaves your machine, nothing - here calls a model, and assistants cannot archive or restore. +- **Tidy and undo:** `personakit tidy` reads your store and, only with `--apply`, folds + 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. - **Plugins:** none are loaded unless you name them in `PERSONAKIT_PLUGINS`. A plugin replaces - how relevance is scored and cannot change what is served, but it is code you installed, running + how relevance or similarity is scored and cannot change what is served or what may be merged, but it is code you installed, running as you. What it does with your data is up to that plugin; read it first. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index 72c6881..827d9bc 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -29,3 +29,6 @@ duplicated logic. Each entry records the result. | `tests/test_decay.py`, `test_store_decay.py`, `test_tidy.py`; `test_cli.py`, `test_mcp_server.py` (changes) | 2026-11-14 | invented sentences only | clean | | `personakit/digest.py`, `tests/test_digest.py`; `store.py`, `cli.py` (changes) | 2026-11-14 | none; local output only, text without quotes; invented test data | clean | | `personakit/plugins.py`, `docs/PLUGINS.md`, `tests/test_plugins.py`; `retrieve.py`, `mcp_server.py`, `cli.py` (changes) | 2026-11-14 | none; opt-in by name, scoring only, a policy test proves a plugin cannot widen what is served | clean | +| `personakit/twins.py`; `store.py`, `tidy.py`, `digest.py`, `cli.py`, `model.py`, `review.py`, `mcp_server.py`, `retrieve.py` (changes) | 2026-11-14 | none; written for this repository, word-based only, thresholds chosen from invented examples. Migration 4 adds `merged_into` and `merge_vetoes`; a folded memory keeps its own rows, so forget leaves nothing behind. Security and code review findings fixed, each with a regression test | clean | +| `tests/test_twins.py`, `test_merge_store.py`; `test_tidy.py`, `test_cli.py`, `test_digest.py` (changes) | 2026-11-14 | invented sentences only | clean | +| `personakit/twins.py`, `plugins.py`, `cli.py` (changes); `tests/test_twins.py`, `test_plugins.py` | 2026-11-16 | none; twins are compared across sessions, a `similarity` hook is added, and numbers and negation must agree whatever scores a pair. Invented sentences only | clean | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 219c914..6c96023 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,13 +3,10 @@ | Release | Scope | Target | |---|---|---| | 0.1 | Claude Code + Codex ingest, extract, store, CLI review, MCP server, local stats | day 10 | -| 0.2 | Decay to archive (reversible), weekly digest, a relevance extension point | in review | +| 0.2 | Merge near-identical duplicates (reversible), decay to archive, weekly digest, extension points for relevance and similarity | in review | | 0.3 | Import from ChatGPT / claude.ai / Gemini exports | after launch | | 0.4 | Third-party name guard | after launch | -Merging duplicate memories was planned for 0.2 and is on hold: matching by shared words found -no duplicates on a real store, because the same fact is usually worded differently each time. - Dates are estimates. Each release ships only after the contributing code has been reviewed for personal data and for duplicate logic. diff --git a/personakit/cli.py b/personakit/cli.py index d807ea2..6f1c1fc 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, plugins, review, stats, sweep, tidy +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 @@ -45,14 +45,18 @@ 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="archive stale unconfirmed memories (shows a plan; --apply to act)") + tidy_cmd = sub.add_parser("tidy", help="fold near-identical 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="bring back one memory that tidy archived") + 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") @@ -99,11 +103,13 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: return _tidy(args, store) elif args.command == "undo": try: - tidy.undo(store, args.memory_id) + print(tidy.undo(store, args.memory_id).capitalize() + ".") except KeyError: - print(f"Nothing to undo for {args.memory_id}: tidy did not archive it", file=sys.stderr) + print(f"Nothing to undo for {args.memory_id}: not a merged or stale-archived memory", file=sys.stderr) return 1 - print("Restored.") + 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": if not 1 <= args.days <= MAX_DAYS: print(f"--days must be between 1 and {MAX_DAYS}", file=sys.stderr) @@ -129,23 +135,40 @@ def _print_json(data: object) -> None: def _tidy(args: argparse.Namespace, store: Store) -> int: - if not 1 <= args.days <= MAX_DAYS: - print(f"--days must be between 1 and {MAX_DAYS}", 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) - if args.apply: - tidy.apply(store, plan) + plan = tidy.make_plan( + 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: - _print_json({"applied": args.apply, "archive": [m.id for m in plan.stale]}) + _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 not plan.stale: - print("Nothing to tidy.") - elif args.apply: - print(f"Archived {len(plan.stale)}. Reverse any with: personakit undo ") + 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(f"{len(plan.stale)} to archive. Nothing changed; add --apply to carry it out.") + print("Nothing to tidy.") return 0 diff --git a/personakit/digest.py b/personakit/digest.py index 99b7bbc..b42fe38 100644 --- a/personakit/digest.py +++ b/personakit/digest.py @@ -21,10 +21,13 @@ def collect(store: Store, now: str, days: int = 7) -> dict: 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": _items(new), + "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": _items(archived), "awaiting_review": store.counts()[State.UNCONFIRMED.value], @@ -40,6 +43,7 @@ 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}") diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 30976d8..98c9464 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 fc5f05d..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.""" diff --git a/personakit/plugins.py b/personakit/plugins.py index 66103d3..aab1fd8 100644 --- a/personakit/plugins.py +++ b/personakit/plugins.py @@ -1,13 +1,13 @@ -"""Extension points: swap how relevance is scored, nothing else. +"""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 function it provides. Nothing is loaded unless you name it in the +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 and every state change stay in `retrieve` -and `store`. A plugin is still code running as you, with access to +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. """ @@ -18,7 +18,7 @@ from dataclasses import dataclass from importlib.metadata import EntryPoint, entry_points -from personakit import retrieve +from personakit import retrieve, twins GROUP = "personakit.plugins" ENABLE_ENV = "PERSONAKIT_PLUGINS" @@ -30,9 +30,10 @@ class PluginError(Exception): @dataclass class Hooks: - """The functions a plugin may replace. The default is the built-in word-based one.""" + """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]: @@ -53,6 +54,6 @@ def load( if name not in installed: raise PluginError(f"plugin {name!r} is named in {ENABLE_ENV} but is not installed") installed[name].load()(hooks) - if not all(callable(hook) for hook in vars(hooks).values()): + 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 66855a2..3803304 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() ) @@ -39,7 +39,7 @@ class Result: def words(text: str) -> set[str]: - return {w for w in _WORD.findall(text.lower()) if w not in _STOP} + return {w for w in _WORD.findall(text.lower()) if w not in STOP_WORDS} def overlap(question: str, memories: Sequence[Memory]) -> list[float]: 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 aa63301..6c7b514 100644 --- a/personakit/store.py +++ b/personakit/store.py @@ -8,6 +8,7 @@ import sqlite3 from collections.abc import Callable, Iterable +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path @@ -54,8 +55,34 @@ ALTER TABLE memories ADD COLUMN last_seen_at TEXT; UPDATE memories SET last_seen_at = created_at; """, + # 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 merged_into TEXT REFERENCES memories(id) ON DELETE CASCADE; + ALTER TABLE memories ADD COLUMN merged_at TEXT; + 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_id: str + survivor_id: str + merged_at: str + duplicate_text: str + def _utc_now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") @@ -136,6 +163,56 @@ def add(self, memory: Memory, observed: bool = True) -> bool: ) return created + def merge(self, duplicate_id: str, survivor_id: str) -> None: + """Fold one unconfirmed memory into another. `undo_merge` reverses it exactly. + + 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") + 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: + self._conn.execute( + "UPDATE memories SET merged_into = ?, merged_at = ? WHERE id = ?", + (survivor_id, self._now(), duplicate_id), + ) + + def undo_merge(self, duplicate_id: str) -> None: + """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 merged_into FROM memories WHERE id = ? AND merged_into IS NOT NULL", (duplicate_id,) + ).fetchone() + if row is None: + raise KeyError(duplicate_id) + with self._conn: + self._conn.execute("UPDATE memories SET merged_into = NULL, merged_at = NULL WHERE id = ?", (duplicate_id,)) + self._conn.execute( + "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) -> 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.""" with self._conn: @@ -151,18 +228,26 @@ 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: 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. + + 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: - 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 + 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: @@ -200,13 +285,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))})") @@ -214,40 +311,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"], @@ -257,6 +359,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 2002cbd..856bab2 100644 --- a/personakit/tidy.py +++ b/personakit/tidy.py @@ -1,35 +1,84 @@ -"""Tidy the store: archive unconfirmed memories that have gone stale. +"""Tidy the store: fold near-identical twins together and archive stale memories. -It is a proposal first. `make_plan` only reads; nothing changes until the owner runs `apply`, and -`undo` reverses any single step. Nothing is ever deleted here, and no memory the owner has -decided on is touched. +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 dataclasses import dataclass, field, replace -from personakit import decay -from personakit.model import Decider, Memory, State +from personakit import decay, twins +from personakit.model import Decider, State from personakit.store import Store @dataclass class Plan: - stale: list[Memory] = field(default_factory=list) + 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) -def make_plan(store: Store, now: str, days: int = decay.DEFAULT_DAYS) -> Plan: - return Plan(decay.find_stale(store.list(states=[State.UNCONFIRMED]), now, days)) +@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, + 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(), 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. + 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 -def apply(store: Store, plan: Plan) -> None: - """Archive what the plan lists.""" + +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". -def undo(store: Store, memory_id: str) -> None: - """Bring back one memory that tidy archived. Raises KeyError for anything else, including - memories the owner archived themselves.""" - store.restore(memory_id) + 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..3dc7a52 --- /dev/null +++ b/personakit/twins.py @@ -0,0 +1,138 @@ +"""Find near-identical memories, whichever sessions they were extracted from. + +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; +* neither may rest on an assistant's proposal; +* same category and scope; +* the numbers they mention (digits or words like "two") must be equal, and they must agree on + negation ("not", "never", "doesn't", "avoid" ...). This holds whatever scores the pair; +* 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. +""" + +from __future__ import annotations + +import re +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 + +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"|\w+n't|(?:don|doesn|didn|isn|aren|won|wasn|weren|can|couldn|shouldn|wouldn|hasn|haven|hadn)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, ...] + + +@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 + + +@lru_cache(maxsize=4096) +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 agree(a: str, b: str) -> bool: + """Whether two texts mention the same numbers and agree on negation.""" + left, right = _features(a), _features(b) + return left.numbers == right.numbers and left.negated == right.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. + """ + if not agree(a, b): + return 0.0 + left, right = _features(a), _features(b) + shared = set(left.words) & set(right.words) + if len(shared) < MIN_SHARED_WORDS: + return 0.0 + 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(left.words) | set(right.words)) + + +Similarity = Callable[[str, str], float] + + +def _eligible(memory: Memory) -> bool: + return memory.state == State.UNCONFIRMED and all(e.session_id != PROPOSED_BY_ASSISTANT for e in memory.evidence) + + +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, and that a pair must + agree on numbers and negation, 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. + """ + def age(memory: Memory) -> tuple[str, str]: + return (memory.created_at or "", memory.id) + + # Only memories of one category and scope are ever compared, so bucket them first. + buckets: dict[tuple[str, str | None], list[Memory]] = {} + for memory in sorted(filter(_eligible, memories), key=age): + buckets.setdefault((memory.category, memory.scope), []).append(memory) + groups: list[TwinGroup] = [] + for bucket in buckets.values(): + taken: set[str] = set() + for index, anchor in enumerate(bucket): + if anchor.id in taken: + continue + twins = tuple( + other + for other in bucket[index + 1 :] + if other.id not in taken + and frozenset((anchor.id, other.id)) not in vetoed + and agree(anchor.text, other.text) + and similarity(anchor.text, other.text) >= threshold + ) + if twins: + taken.update(m.id for m in twins) + groups.append(TwinGroup(anchor, twins)) + return sorted(groups, key=lambda group: age(group.survivor)) diff --git a/tests/test_cli.py b/tests/test_cli.py index 6a9557f..d3f57bd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -122,49 +122,69 @@ def test_db_defaults_to_environment_variable(self): class TidyCliTest(CliCase): - """tidy and undo, on a store seeded with invented memories dated long ago.""" + """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) - with Store(self.db, now=lambda: "2020-01-01T00:00:00Z") as store: - for turn, text in enumerate(["You prefer direct, practical feedback.", "You deploy on Fridays."]): - store.add(Memory(text=text, category="other", evidence=(Evidence("s1", turn, "q"),))) + 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", "--days", "30") + code, out, _ = self.run_cli("tidy", "--only", "merge") self.assertEqual(code, 0) - self.assertIn("2 to archive. Nothing changed", out) - self.assertEqual(json.loads(self.run_cli("list", "--state", "archived", "--json")[1]), []) + self.assertIn("1 to merge, 0 to archive. Nothing changed", out) + self.assertEqual(self.run_cli("merges")[1], "") - def test_apply_archives_and_undo_restores(self): + def test_apply_then_list_merges_then_undo(self): self.seed() - _, out, _ = self.run_cli("tidy", "--apply", "--days", "30") - self.assertIn("Archived 2", out) + _, 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") - self.assertEqual(self.run_cli("undo", listing[0]["id"])[0], 1) def test_tidy_json_lists_ids_only(self): self.seed() _, out, _ = self.run_cli("tidy", "--json", "--days", "30") data = json.loads(out) - self.assertEqual((data["applied"], len(data["archive"])), (False, 2)) + 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_digest_prints_text_or_json_and_rejects_bad_numbers(self): - self.seed() - self.assertIn("PersonaKit digest, last 7 days", self.run_cli("digest")[1]) - self.assertEqual(json.loads(self.run_cli("digest", "--days", "36500", "--json")[1])["new"], 2) - self.assertEqual(self.run_cli("digest", "--days", "-5")[0], 2) - 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", "36500", "--json")[1]) + self.assertEqual(data["new"], 2) if __name__ == "__main__": diff --git a/tests/test_digest.py b/tests/test_digest.py index 088d9ad..d3e248c 100644 --- a/tests/test_digest.py +++ b/tests/test_digest.py @@ -33,6 +33,16 @@ def test_digest_covers_only_the_window_and_lists_ids_with_text(self): self.assertIn("Awaiting your review: 2", text) self.assertNotIn("quote", text) + def test_digest_lists_merged_twins(self): + keep, twin = mem("You prefer direct, practical feedback."), mem("You prefer direct and practical feedback from reviewers.", turn=1) + self.store.add(keep) + self.clock[0] = "2026-01-01T00:00:01Z" + self.store.add(twin) + self.clock[0] = NOW + tidy.apply(self.store, tidy.make_plan(self.store, NOW, archive=False)) + data = digest.collect(self.store, NOW, days=7) + self.assertEqual((data["merged"], data["merged_items"][0]["id"]), (1, twin.id)) + 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} in notes.", turn=i)) diff --git a/tests/test_merge_store.py b/tests/test_merge_store.py new file mode 100644 index 0000000..737ef77 --- /dev/null +++ b/tests/test_merge_store.py @@ -0,0 +1,142 @@ +import unittest + +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import 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 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([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) + 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_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) + 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_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() + 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") + self.assertEqual(self.store.list()[0].last_seen_at, "2026-02-01T00:00:00Z") + + 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.store.merge(self.keep.id, self.third.id) + + 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_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(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_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.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" + 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"), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_plugins.py b/tests/test_plugins.py index 3237b69..5d5ecec 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -1,7 +1,7 @@ import unittest from unittest import mock -from personakit import mcp_server, plugins, retrieve +from personakit import mcp_server, plugins, retrieve, tidy, twins from personakit.model import Decider, Evidence, Memory, State from personakit.store import Store @@ -24,7 +24,11 @@ def use_everything_matches(hooks): hooks.relevance = everything_matches -INSTALLED = [FakePoint("match-all", use_everything_matches), FakePoint("other", lambda hooks: None)] +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): @@ -42,13 +46,17 @@ def load(self, names): return plugins.load(names, discover=lambda: INSTALLED) def test_nothing_is_loaded_unless_named(self): - self.assertIs(self.load([]).relevance, retrieve.overlap) + 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(["other"]).relevance, retrieve.overlap) + self.assertIs(self.load(["twin-all"]).relevance, retrieve.overlap) - def test_named_plugins_replace_what_they_provide(self): - self.assertIs(self.load(["match-all", "other"]).relevance, everything_matches) + 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): @@ -60,14 +68,14 @@ def test_a_plugin_that_breaks_a_hook_is_refused(self): plugins.load(["broken"], discover=lambda: broken) def test_names_come_from_the_environment(self): - with mock.patch.dict("os.environ", {plugins.ENABLE_ENV: " match-all , ,other "}): - self.assertEqual(plugins.enabled_names(), ["match-all", "other"]) + with mock.patch.dict("os.environ", {plugins.ENABLE_ENV: " 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.""" + """A plugin scores; it cannot widen what is served or what may be merged.""" def setUp(self): self.store = Store(":memory:") @@ -87,6 +95,18 @@ def test_relevance_plugin_cannot_serve_restricted_or_archived_memories(self): 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_touch_decisions_or_merge_past_the_guards(self): + same_a, same_b = mem("First statement here."), mem("Completely different words.", session="s2") + negated = mem("Never a statement like those.", turn=1) + numbered = mem("Statement number 7 is here.", turn=2) + approved = mem("An approved statement.", turn=3) + for memory in (same_a, same_b, negated, numbered, 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() diff --git a/tests/test_tidy.py b/tests/test_tidy.py index 75e6879..dcfae6a 100644 --- a/tests/test_tidy.py +++ b/tests/test_tidy.py @@ -7,52 +7,85 @@ NOW = "2026-06-01T00:00:00Z" -def mem(text, session="s1", turn=0): - return Memory(text=text, category="other", evidence=(Evidence(session, turn, f"quote {turn}"),)) +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 = ["2026-01-01T00:00:00Z"] - self.store = Store(":memory:", now=lambda: self.clock[0]) + self.clock = Clock("2026-01-01T00:00:00Z") + self.store = Store(":memory:", now=self.clock) self.addCleanup(self.store.close) - self.old = mem("You deploy on Fridays.") - self.approved = mem("You prefer direct, practical feedback.", turn=1) - for memory in (self.old, self.approved): - self.store.add(memory) - self.store.set_state(self.approved.id, State.APPROVED, Decider.OWNER) - self.clock[0] = NOW - self.fresh = mem("You use Python for scripts.", session="s2") + 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) - def test_plan_lists_only_stale_unconfirmed_memories_and_changes_nothing(self): + @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([m.id for m in plan.stale], [self.old.id]) - self.assertEqual(self.store.counts()["archived"], 0) + self.assertEqual((plan.merges, len(plan.stale)), (1, 2)) + self.assertEqual(self.store.counts()["unconfirmed"], 4) + self.assertEqual(self.store.merges(), []) - def test_apply_archives_by_policy_and_undo_brings_it_back(self): - tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) - archived = self.store.get(self.old.id) - self.assertEqual((archived.state, archived.decided_by), (State.ARCHIVED, Decider.POLICY)) - self.assertEqual(self.store.get(self.approved.id).state, State.APPROVED) - tidy.undo(self.store, self.old.id) - self.assertEqual(self.store.get(self.old.id).state, State.UNCONFIRMED) + 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_a_restored_memory_is_not_archived_again_straight_away(self): - tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) - tidy.undo(self.store, self.old.id) - self.assertEqual(tidy.make_plan(self.store, NOW, days=90).stale, []) + 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_applying_twice_is_a_no_op(self): - tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) + 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_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, []) + 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, self.approved.id): + 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)) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_twins.py b/tests/test_twins.py new file mode 100644 index 0000000..1f63533 --- /dev/null +++ b/tests/test_twins.py @@ -0,0 +1,137 @@ +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.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) + + 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_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_twins_are_found_across_sessions(self): + other = mem(self.b.text, session="s2", created="2026-01-02T00:00:00Z") + both = Memory( + text="You prefer direct practical feedback.", + category="communication", + created_at="2026-01-03T00:00:00Z", + evidence=(Evidence("s3", 0, "q"), Evidence("s4", 1, "q")), + ) + groups = find_twins([both, other, self.a]) + self.assertEqual([(g.survivor.id, [m.id for m in g.duplicates]) for g in groups], [(self.a.id, [other.id, both.id])]) + + def test_numbers_and_negation_must_agree_whatever_scores_the_pair(self): + def always(a, b): + return 1.0 + + for left, right in ( + ("You run the suite on version 3 of the tool.", "You run the suite on version 4 of the tool."), + ("You want long reviews of your drafts.", "You never want long reviews of your drafts."), + ): + self.assertEqual(find_twins([mem(left), mem(right, created="2026-01-02T00:00:00Z")], similarity=always), [], left) + + def test_a_memory_with_any_assistant_proposed_evidence_is_not_eligible(self): + mixed = Memory( + text=self.b.text, + category="communication", + evidence=(Evidence("s1", 0, "q"), Evidence(PROPOSED_BY_ASSISTANT, 0, "q")), + ) + self.assertEqual(find_twins([self.a, mixed]), []) + + 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()