From 12f843a888c4fed79ad10861460127a846fc5691 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 13:16:47 +0000 Subject: [PATCH] Twins: fold near-identical same-session memories, reversibly Word-based detection with guards (numbers, negation, order of shared words, same category and scope, unconfirmed only, one session). A folded memory keeps its own row and evidence and points at its survivor, so undo is exact and forget removes everything it brought. Migration 4 adds merged_into and merge_vetoes. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- README.md | 10 ++- docs/ARCHITECTURE.md | 22 +++-- docs/PRIVACY.md | 9 +- docs/REVIEW-LOG.md | 2 + docs/ROADMAP.md | 5 +- personakit/cli.py | 51 +++++++---- personakit/digest.py | 4 + personakit/mcp_server.py | 3 +- personakit/model.py | 3 + personakit/retrieve.py | 4 +- personakit/review.py | 4 +- personakit/store.py | 174 +++++++++++++++++++++++++++++++------- personakit/tidy.py | 81 ++++++++++++++---- personakit/twins.py | 134 +++++++++++++++++++++++++++++ tests/test_cli.py | 56 ++++++++---- tests/test_digest.py | 10 +++ tests/test_merge_store.py | 142 +++++++++++++++++++++++++++++++ tests/test_tidy.py | 89 +++++++++++++------ tests/test_twins.py | 116 +++++++++++++++++++++++++ 19 files changed, 784 insertions(+), 135 deletions(-) create mode 100644 personakit/twins.py create mode 100644 tests/test_merge_store.py create mode 100644 tests/test_twins.py diff --git a/README.md b/README.md index 24a5276..d16a81f 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 same-session 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 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: @@ -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 the same 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 same-session 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 f03b3f7..2f33311 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,9 +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 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 `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` | +| `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 | @@ -60,6 +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**: 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. @@ -70,9 +75,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 same-session 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. @@ -85,4 +91,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/PRIVACY.md b/docs/PRIVACY.md index 1bef935..bb00062 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -16,8 +16,11 @@ - **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. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index aec16f6..a6a69a0 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -28,3 +28,5 @@ duplicated logic. Each entry records the result. | `personakit/decay.py`, `tidy.py`; `store.py`, `model.py`, `mcp_server.py`, `cli.py` (changes) | 2026-11-14 | none; migration 3 adds `last_seen_at`; an assistant proposal cannot revive or refresh a memory. Checked on a copy of a real store: upgrade, archive, undo and reads behave as documented | clean | | `tests/test_decay.py`, `test_store_decay.py`, `test_tidy.py`; `test_cli.py`, `test_mcp_server.py` (changes) | 2026-11-14 | invented sentences only | clean | | `personakit/digest.py`, `tests/test_digest.py`; `store.py`, `cli.py` (changes) | 2026-11-14 | none; local output only, text without quotes; invented test data | clean | +| `personakit/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 | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 219c914..588a964 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 same-session duplicates (reversible), decay to archive, weekly digest, a relevance extension point | 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 97d1694..1c55bd5 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 +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 @@ -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 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="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") @@ -95,11 +99,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) @@ -125,23 +131,34 @@ 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" + ) + 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 02c6147..c4d814e 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/retrieve.py b/personakit/retrieve.py index 192ad2a..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() ) @@ -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 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 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..4283783 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 same-session 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..fe4ebce --- /dev/null +++ b/personakit/twins.py @@ -0,0 +1,134 @@ +"""Find near-identical memories that were extracted from the same session. + +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", "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. +""" + +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 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(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 _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(), + 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)) 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) in enumerate(eligible): + if anchor.id in taken: + continue + twins = tuple( + other + 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 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 930c9a6..0326805 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -116,49 +116,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_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..31997b1 --- /dev/null +++ b/tests/test_twins.py @@ -0,0 +1,116 @@ +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_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()