From 7cd79cdd514206047c6183d9100b27e30105e96a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 13:15:13 +0000 Subject: [PATCH] Decay: archive stale unconfirmed memories on request, reversibly personakit tidy shows a plan and changes nothing; --apply archives unconfirmed memories not extracted again for 90 days; personakit undo brings one back. Migration 3 adds last_seen_at. An extraction refreshes it and revives a memory decay archived; an assistant proposal does neither. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_014dGcvUc3LqzKojYnqVGCjK --- .gitignore | 1 + README.md | 15 +++++-- docs/ARCHITECTURE.md | 25 +++++++++--- docs/PRIVACY.md | 3 ++ docs/REVIEW-LOG.md | 2 + docs/ROADMAP.md | 5 ++- personakit/cli.py | 41 +++++++++++++++++++- personakit/decay.py | 33 ++++++++++++++++ personakit/mcp_server.py | 2 +- personakit/model.py | 1 + personakit/store.py | 43 +++++++++++++++++--- personakit/tidy.py | 35 +++++++++++++++++ tests/test_cli.py | 46 +++++++++++++++++++++- tests/test_decay.py | 45 +++++++++++++++++++++ tests/test_mcp_server.py | 11 ++++++ tests/test_store_decay.py | 82 +++++++++++++++++++++++++++++++++++++++ tests/test_tidy.py | 58 +++++++++++++++++++++++++++ 17 files changed, 430 insertions(+), 18 deletions(-) create mode 100644 personakit/decay.py create mode 100644 personakit/tidy.py create mode 100644 tests/test_decay.py create mode 100644 tests/test_store_decay.py create mode 100644 tests/test_tidy.py diff --git a/.gitignore b/.gitignore index 9044e7b..979002d 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ build/ *.jsonl !tests/fixtures/**/*.jsonl .env +.coverage diff --git a/README.md b/README.md index 38ad04a..d5b94a8 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ memories ("you prefer direct, practical feedback"), keeps the exact quote each o and serves only what you allow back to your assistants over MCP. Everything runs on your own machine. There is no PersonaKit server and no account. -> **Status: pre-release (0.1 in progress).** This repository is being built in public. +> **Status: pre-release (0.2 in progress).** This repository is being built in public. > See [docs/ROADMAP.md](docs/ROADMAP.md) for what exists and what is planned. ## Why PersonaKit @@ -53,11 +53,13 @@ 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 --apply # carry the plan out (reverse any with `personakit undo `) personakit serve # MCP server over stdio for your assistants personakit forget # delete a memory and its quotes for good ``` -`sweep`, `list` and `stats` also take `--json` for stable, sorted machine-readable output. +`sweep`, `list`, `stats` and `tidy` also take `--json` for stable, sorted machine-readable output. The model name is always yours to choose. Nothing leaves your machine except the turns you wrote, sent to the model you named. See [docs/PRIVACY.md](docs/PRIVACY.md). @@ -101,6 +103,9 @@ Your assistant gets two tools: 4. **Review** is optional. Memories you never review are served marked *unconfirmed*; you can approve, restrict, hide or forget any of them at any time. 5. **Serve** exposes the store to assistants over MCP, with the evidence attached. +6. **Tidy** (on request) archives unconfirmed memories not seen again for 90 days. It shows a + plan first; nothing changes without `--apply`, nothing is deleted, and `personakit undo ` + reverses a step. A memory is always in one of four states: @@ -111,7 +116,7 @@ A memory is always in one of four states: | `restricted` | Never | | `archived` | Never | -## Limits in 0.1 +## Limits in 0.2 Stated plainly, so you know what you are installing: @@ -120,6 +125,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. +- **Decay looks only at time.** An unconfirmed memory not extracted again for 90 days is archived + (reversible); that says nothing about whether it is still true. Approved and restricted + memories never decay. - **A memory an assistant already received stays in that conversation.** Restricting it applies to future reads. - **Paste and credential detection is by shape**, not by meaning. Look before you share a store. @@ -131,6 +139,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 | +| Decay of stale unconfirmed memories (reversible) | Available in 0.2 | | ChatGPT, claude.ai and Gemini export import | Planned for 0.3 | ## Documentation diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8710bd9..543e2c2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,4 +1,4 @@ -# Architecture (v0.1 design) +# Architecture (v0.2 design) PersonaKit is a small local pipeline with one database. Each stage has one job and talks to the next only through the store. @@ -17,6 +17,7 @@ flowchart TB RV[review: CLI] MCP[mcp_server] SS[stats: local counts] + TD[tidy: decay, on request] end CC --> IN CX --> IN @@ -26,6 +27,7 @@ flowchart TB ST <--> RV ST --> MCP ST --> SS + ST <--> TD MCP --> AS[Assistants] ``` @@ -42,6 +44,8 @@ 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` | +| `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` | | `stats` | Counts only (memories by state, sessions extracted, reads and how many returned something). Never content. | `store` | | `cli` | Argument parsing and wiring; no logic. | all | @@ -51,7 +55,8 @@ model, only `ingest` reads session files.** A second implementation of any of th ## Data model - **Turn**: `(source, session_id, index, timestamp, text)`. Only owner-authored turns exist here. -- **Memory**: `id, text, category, scope, state, created_at, decided_at, decided_by`. +- **Memory**: `id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by`. + `last_seen_at` moves forward each time the same statement is extracted again. - **Evidence**: `memory_id, session_id, turn_index, quote`. Every memory has at least one. - **State**: `unconfirmed` (default, served with a label) -> `approved` | `restricted` | `archived`. Nothing is ever hard-deleted without an explicit `forget` by the owner. @@ -60,13 +65,21 @@ model, only `ingest` reads session files.** A second implementation of any of th 1. A memory with no evidence is not stored. 2. Unconfirmed memories are served, labelled as unconfirmed. Review is a quality tool, not a gate. -3. The system never changes a memory's state or deletes a memory on its own. Extracting the same - statement again adds evidence to the existing memory and leaves your decision alone. Merging - near-duplicates and archiving stale items are planned for 0.2 and will be reversible. +3. The system never deletes a memory, and never touches a memory you have decided on. Extracting + the same statement again adds evidence to the existing memory and leaves your decision alone. + 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 + if the statement is extracted again from your own words. An assistant proposing the same text + does not bring it back and does not reset its age. 4. Only text the owner wrote is sent to a model. 5. Statistics are counts, never content, and are local unless the owner chooses to share them. -## Out of scope for 0.1 +## Out of scope for now Hosted service, accounts, sync, ChatGPT/Gemini/claude.ai import and third-party name detection. See the roadmap for what is planned. + +## Limits in 0.2 + +Decay looks only at how long ago a statement was last extracted, not at whether it is still true. diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index 91e0542..3ed5de5 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -16,3 +16,6 @@ - **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. diff --git a/docs/REVIEW-LOG.md b/docs/REVIEW-LOG.md index a7b9ff5..4f949c0 100644 --- a/docs/REVIEW-LOG.md +++ b/docs/REVIEW-LOG.md @@ -25,3 +25,5 @@ duplicated logic. Each entry records the result. | `personakit/store.py` (changes) | 2026-11-08 | added `reads` table via migration 2; list order now insertion order | clean | | `personakit/extract.py` (changes) | 2026-11-08 | shared text checks moved into `text_problem` so extraction and assistant proposals use one rule | clean | | `tests/*` (new) | 2026-11-08 | invented data; a key-shaped string is assembled at runtime | clean | +| `personakit/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 | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e2de8ac..219c914 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -3,10 +3,13 @@ | Release | Scope | Target | |---|---|---| | 0.1 | Claude Code + Codex ingest, extract, store, CLI review, MCP server, local stats | day 10 | -| 0.2 | Merge same-session duplicates (reversible), weekly digest, decay to archive | day 14 | +| 0.2 | Decay to archive (reversible), 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 ca941d5..dd589ae 100644 --- a/personakit/cli.py +++ b/personakit/cli.py @@ -8,11 +8,12 @@ import sys from pathlib import Path -from personakit import llm, mcp_server, review, stats, sweep +from personakit import decay, llm, mcp_server, review, stats, sweep, tidy from personakit.ingest import ADAPTERS from personakit.model import State from personakit.store import Store +MAX_DAYS = 36500 CLIENTS = {"claude": llm.ClaudeCli, "codex": llm.CodexCli} @@ -44,6 +45,14 @@ 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.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("--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.add_argument("memory_id") + forget = sub.add_parser("forget", help="permanently delete a memory and its quotes") forget.add_argument("memory_id") @@ -78,6 +87,15 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int: _print_json(collected) else: print(stats.format_stats(collected)) + elif args.command == "tidy": + return _tidy(args, store) + elif args.command == "undo": + try: + tidy.undo(store, args.memory_id) + except KeyError: + print(f"Nothing to undo for {args.memory_id}: tidy did not archive it", file=sys.stderr) + return 1 + print("Restored.") elif args.command == "forget": if not store.forget(args.memory_id): print(f"No memory with id {args.memory_id}", file=sys.stderr) @@ -93,6 +111,27 @@ def _print_json(data: object) -> None: print(json.dumps(data, sort_keys=True, ensure_ascii=False)) +def _tidy(args: argparse.Namespace, store: Store) -> int: + if not 1 <= args.days <= MAX_DAYS: + print(f"--days must be between 1 and {MAX_DAYS}", file=sys.stderr) + return 2 + plan = tidy.make_plan(store, store.now(), args.days) + if args.apply: + tidy.apply(store, plan) + if args.json: + _print_json({"applied": args.apply, "archive": [m.id for m in plan.stale]}) + return 0 + 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 ") + else: + print(f"{len(plan.stale)} to archive. Nothing changed; add --apply to carry it out.") + return 0 + + def _sweep(args: argparse.Namespace, store: Store) -> int: sources = list(ADAPTERS) if args.source == "all" else [args.source] if args.root and len(sources) != 1: diff --git a/personakit/decay.py b/personakit/decay.py new file mode 100644 index 0000000..c40d4a6 --- /dev/null +++ b/personakit/decay.py @@ -0,0 +1,33 @@ +"""Which unconfirmed memories have gone stale. + +A memory is stale when it is still unconfirmed and has not been extracted again for a long time. +Approved and restricted memories never decay: those are the owner's decisions. Staleness only +ever leads to archiving (reversible), never to deletion. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from datetime import datetime, timedelta, timezone + +from personakit.model import Memory, State + +DEFAULT_DAYS = 90 +_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + +def days_ago(now: str, days: int) -> str: + """The timestamp `days` before `now`, in the store's format, so strings compare in time order.""" + moment = datetime.strptime(now, _FORMAT).replace(tzinfo=timezone.utc) + return (moment - timedelta(days=days)).strftime(_FORMAT) + + +def find_stale(memories: Iterable[Memory], now: str, days: int = DEFAULT_DAYS) -> list[Memory]: + if days < 1: + raise ValueError("days must be at least 1") + cutoff = days_ago(now, days) + return [ + m + for m in memories + if m.state == State.UNCONFIRMED and (m.last_seen_at or m.created_at or now) < cutoff + ] diff --git a/personakit/mcp_server.py b/personakit/mcp_server.py index 461f9d3..02c6147 100644 --- a/personakit/mcp_server.py +++ b/personakit/mcp_server.py @@ -52,7 +52,7 @@ def propose_memory(store: Store, text: str, quote: str, category: str = "other") category=category if category in extract.CATEGORIES else "other", evidence=(Evidence(PROPOSED_BY_ASSISTANT, 0, extract.quote_of(quote.strip())),), ) - created = store.add(memory) + created = store.add(memory, observed=False) return {"stored": True, "id": memory.id, "new": created, "state": State.UNCONFIRMED.value} diff --git a/personakit/model.py b/personakit/model.py index 1f8bcd4..fc5f05d 100644 --- a/personakit/model.py +++ b/personakit/model.py @@ -72,6 +72,7 @@ class Memory: created_at: str | None = None decided_at: str | None = None decided_by: Decider | None = None + last_seen_at: str | None = None # last time the same statement was extracted again def __post_init__(self) -> None: if not self.text.strip(): diff --git a/personakit/store.py b/personakit/store.py index 3c7eddf..28b301d 100644 --- a/personakit/store.py +++ b/personakit/store.py @@ -49,6 +49,11 @@ withheld INTEGER NOT NULL ); """, + # When a statement was last seen again. Decay reads it. + """ + ALTER TABLE memories ADD COLUMN last_seen_at TEXT; + UPDATE memories SET last_seen_at = created_at; + """, ] @@ -64,6 +69,10 @@ def __init__(self, path: str | Path, now: Callable[[], str] = _utc_now): self._conn.execute("PRAGMA foreign_keys = ON") self._migrate() + def now(self) -> str: + """The store's clock, in the format it records.""" + return self._now() + def close(self) -> None: self._conn.close() @@ -86,24 +95,29 @@ def _migrate(self) -> None: # -- writing -------------------------------------------------------------------- - def add(self, memory: Memory) -> bool: + def add(self, memory: Memory, observed: bool = True) -> bool: """Store a memory. Returns True if it is new. If the same memory already exists its evidence is extended and its state is left alone, - so extracting a fact twice never undoes a decision the owner made. + so extracting a fact twice never undoes a decision the owner made. `observed` says the + owner was seen stating it again (an extraction): that refreshes its last-seen time and + brings back a memory that decay had archived. An assistant's proposal is not an + observation and does neither. """ with self._conn: + now = self._now() created = self._conn.execute( "INSERT OR IGNORE INTO memories" - " (id, text, category, scope, state, created_at, decided_at, decided_by)" - " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + " (id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ( memory.id, memory.text, memory.category, memory.scope, memory.state.value, - memory.created_at or self._now(), + memory.created_at or now, + memory.last_seen_at or memory.created_at or now, memory.decided_at, memory.decided_by.value if memory.decided_by else None, ), @@ -113,8 +127,26 @@ def add(self, memory: Memory) -> bool: " VALUES (?, ?, ?, ?)", [(memory.id, e.session_id, e.turn_index, e.quote) for e in memory.evidence], ) + if observed and not created: + self._conn.execute("UPDATE memories SET last_seen_at = ? WHERE id = ?", (now, memory.id)) + self._conn.execute( + "UPDATE memories SET state = ?, decided_at = NULL, decided_by = NULL" + " WHERE id = ? AND state = ? AND decided_by = ?", + (State.UNCONFIRMED.value, memory.id, State.ARCHIVED.value, Decider.POLICY.value), + ) return created + def restore(self, memory_id: str) -> None: + """Bring back a memory that decay archived. Raises KeyError unless policy archived it.""" + with self._conn: + changed = self._conn.execute( + "UPDATE memories SET state = ?, decided_at = NULL, decided_by = NULL, last_seen_at = ?" + " WHERE id = ? AND state = ? AND decided_by = ?", + (State.UNCONFIRMED.value, self._now(), memory_id, State.ARCHIVED.value, Decider.POLICY.value), + ).rowcount + if changed == 0: + raise KeyError(memory_id) + def set_state(self, memory_id: str, state: State, by: Decider) -> None: """Move a memory to a new state and record who did it. Raises KeyError if unknown.""" with self._conn: @@ -224,5 +256,6 @@ def _build(row: sqlite3.Row, evidence: tuple[Evidence, ...]) -> Memory: created_at=row["created_at"], decided_at=row["decided_at"], decided_by=Decider(row["decided_by"]) if row["decided_by"] else None, + last_seen_at=row["last_seen_at"], evidence=evidence, ) diff --git a/personakit/tidy.py b/personakit/tidy.py new file mode 100644 index 0000000..2002cbd --- /dev/null +++ b/personakit/tidy.py @@ -0,0 +1,35 @@ +"""Tidy the store: archive unconfirmed memories that have gone stale. + +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. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from personakit import decay +from personakit.model import Decider, Memory, State +from personakit.store import Store + + +@dataclass +class Plan: + stale: list[Memory] = field(default_factory=list) + + +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)) + + +def apply(store: Store, plan: Plan) -> None: + """Archive what the plan lists.""" + for memory in plan.stale: + store.set_state(memory.id, State.ARCHIVED, Decider.POLICY) + + +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) diff --git a/tests/test_cli.py b/tests/test_cli.py index aded799..d8f7744 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -7,6 +7,8 @@ from unittest import mock from personakit import cli, llm +from personakit.model import Evidence, Memory +from personakit.store import Store from tests.helpers import reply FIXTURES = Path(__file__).parent / "fixtures" / "claude_code" @@ -24,7 +26,7 @@ def complete(self, prompt): return reply(MEMORY) -class CliTest(unittest.TestCase): +class CliCase(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp()) self.addCleanup(__import__("shutil").rmtree, self.tmp) @@ -36,6 +38,8 @@ def run_cli(self, *argv): code = cli.main(["--db", str(self.db), *argv]) return code, out.getvalue(), err.getvalue() + +class CliTest(CliCase): def test_sweep_then_list_stats_and_forget(self): root = self.tmp / "projects" (root / "proj").mkdir(parents=True) @@ -111,5 +115,45 @@ def test_db_defaults_to_environment_variable(self): self.assertEqual(cli.default_db(), self.db) +class TidyCliTest(CliCase): + """tidy and undo, 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"),))) + + def test_tidy_shows_a_plan_and_changes_nothing_until_applied(self): + self.seed() + code, out, _ = self.run_cli("tidy", "--days", "30") + self.assertEqual(code, 0) + self.assertIn("2 to archive. Nothing changed", out) + self.assertEqual(json.loads(self.run_cli("list", "--state", "archived", "--json")[1]), []) + + def test_apply_archives_and_undo_restores(self): + self.seed() + _, out, _ = self.run_cli("tidy", "--apply", "--days", "30") + self.assertIn("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.assertNotIn("prefer", out) + + def test_nothing_to_tidy_on_a_fresh_store(self): + self.assertIn("Nothing to tidy.", self.run_cli("tidy")[1]) + + def test_tidy_rejects_bad_numbers(self): + self.assertEqual(self.run_cli("tidy", "--days", "0")[0], 2) + self.assertEqual(self.run_cli("tidy", "--days", "99999999")[0], 2) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_decay.py b/tests/test_decay.py new file mode 100644 index 0000000..5487365 --- /dev/null +++ b/tests/test_decay.py @@ -0,0 +1,45 @@ +import unittest + +from personakit.decay import days_ago, find_stale +from personakit.model import Decider, Evidence, Memory, State + +NOW = "2026-06-01T00:00:00Z" + + +def mem(text, state=State.UNCONFIRMED, created="2026-01-01T00:00:00Z", seen=None): + return Memory( + text=text, + category="other", + state=state, + created_at=created, + last_seen_at=seen, + decided_by=Decider.OWNER if state != State.UNCONFIRMED else None, + evidence=(Evidence("s", 0, "q"),), + ) + + +class DecayTest(unittest.TestCase): + def test_days_ago_counts_back_from_now(self): + self.assertEqual(days_ago(NOW, 7), "2026-05-25T00:00:00Z") + + def test_old_unconfirmed_memory_is_stale(self): + self.assertEqual([m.text for m in find_stale([mem("old")], NOW, 90)], ["old"]) + + def test_recently_seen_memory_is_not_stale_even_if_created_long_ago(self): + self.assertEqual(find_stale([mem("again", seen="2026-05-20T00:00:00Z")], NOW, 90), []) + + def test_owner_decisions_never_decay(self): + kept = [mem("a", State.APPROVED), mem("r", State.RESTRICTED), mem("h", State.ARCHIVED)] + self.assertEqual(find_stale(kept, NOW, 90), []) + + def test_boundary_is_exclusive(self): + edge = mem("edge", seen=days_ago(NOW, 90)) + self.assertEqual(find_stale([edge], NOW, 90), []) + + def test_days_must_be_positive(self): + with self.assertRaises(ValueError): + find_stale([], NOW, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index f46d61e..22c7dcc 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -66,6 +66,17 @@ def setUp(self): self.store = Store(":memory:") self.addCleanup(self.store.close) + def test_proposing_an_archived_statement_does_not_bring_it_back(self): + memory = Memory(text="You use Rust for tools.", category="tools", evidence=(Evidence("s1", 0, "I write Rust."),)) + self.store.add(memory) + self.store.set_state(memory.id, State.ARCHIVED, Decider.POLICY) + before = self.store.get(memory.id).last_seen_at + result = mcp_server.propose_memory(self.store, memory.text, "anything") + self.assertFalse(result["new"]) + after = self.store.get(memory.id) + self.assertEqual((after.state, after.last_seen_at), (State.ARCHIVED, before)) + self.assertEqual(mcp_server.read_memories(self.store, "rust tools")["memories"], []) + def test_proposal_is_stored_unconfirmed_and_marked_as_assistant_proposed(self): result = mcp_server.propose_memory(self.store, "You use Rust.", "I write Rust daily", "tools") self.assertTrue(result["stored"]) diff --git a/tests/test_store_decay.py b/tests/test_store_decay.py new file mode 100644 index 0000000..5b7f003 --- /dev/null +++ b/tests/test_store_decay.py @@ -0,0 +1,82 @@ +import sqlite3 +import tempfile +import unittest +from pathlib import Path + +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import MIGRATIONS, Store + + +class Clock: + def __init__(self, value="2026-01-01T00:00:00Z"): + self.value = value + + def __call__(self): + return self.value + + +def mem(text, *evidence): + return Memory(text=text, category="other", evidence=tuple(Evidence("s1", t, q) for t, q in evidence)) + + +class DecayStoreTest(unittest.TestCase): + def setUp(self): + self.clock = Clock() + self.store = Store(":memory:", now=self.clock) + self.addCleanup(self.store.close) + self.m = mem("You use Python for scripts.", (0, "I write Python.")) + self.store.add(self.m) + + def test_new_memory_is_last_seen_when_created(self): + self.assertEqual(self.store.get(self.m.id).last_seen_at, "2026-01-01T00:00:00Z") + + def test_seeing_it_again_refreshes_last_seen(self): + self.clock.value = "2026-04-01T00:00:00Z" + self.store.add(mem(self.m.text, (3, "More Python."))) + self.assertEqual(self.store.get(self.m.id).last_seen_at, "2026-04-01T00:00:00Z") + + def test_restore_brings_back_a_policy_archive_and_resets_the_clock(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.clock.value = "2026-05-01T00:00:00Z" + self.store.restore(self.m.id) + back = self.store.get(self.m.id) + self.assertEqual((back.state, back.decided_by, back.last_seen_at), (State.UNCONFIRMED, None, "2026-05-01T00:00:00Z")) + + def test_restore_refuses_what_the_owner_archived(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.OWNER) + with self.assertRaises(KeyError): + self.store.restore(self.m.id) + with self.assertRaises(KeyError): + self.store.restore("m_missing") + + def test_extracting_an_archived_statement_again_revives_it_only_if_policy_archived_it(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.store.add(mem(self.m.text, (4, "Python again."))) + self.assertEqual(self.store.get(self.m.id).state, State.UNCONFIRMED) + self.store.set_state(self.m.id, State.ARCHIVED, Decider.OWNER) + self.store.add(mem(self.m.text, (5, "Python once more."))) + self.assertEqual(self.store.get(self.m.id).state, State.ARCHIVED) + + def test_an_unobserved_add_neither_revives_nor_refreshes(self): + self.store.set_state(self.m.id, State.ARCHIVED, Decider.POLICY) + self.clock.value = "2026-09-01T00:00:00Z" + self.assertFalse(self.store.add(mem(self.m.text, (4, "Said by an assistant.")), observed=False)) + kept = self.store.get(self.m.id) + self.assertEqual((kept.state, kept.last_seen_at), (State.ARCHIVED, "2026-01-01T00:00:00Z")) + + def test_database_from_before_decay_is_upgraded_and_backfilled(self): + path = Path(tempfile.mkdtemp()) / "v2.db" + old = sqlite3.connect(path) + for step in MIGRATIONS[:2]: + old.executescript(step) + old.execute("PRAGMA user_version = 2") + old.execute("INSERT INTO memories VALUES ('m_x','kept','c','global','unconfirmed','2026-01-01T00:00:00Z',NULL,NULL)") + old.execute("INSERT INTO evidence VALUES ('m_x','s',0,'q')") + old.commit() + old.close() + with Store(path) as upgraded: + self.assertEqual(upgraded.get("m_x").last_seen_at, "2026-01-01T00:00:00Z") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_tidy.py b/tests/test_tidy.py new file mode 100644 index 0000000..75e6879 --- /dev/null +++ b/tests/test_tidy.py @@ -0,0 +1,58 @@ +import unittest + +from personakit import tidy +from personakit.model import Decider, Evidence, Memory, State +from personakit.store import Store + +NOW = "2026-06-01T00:00:00Z" + + +def mem(text, session="s1", turn=0): + return Memory(text=text, category="other", evidence=(Evidence(session, turn, f"quote {turn}"),)) + + +class TidyTest(unittest.TestCase): + def setUp(self): + self.clock = ["2026-01-01T00:00:00Z"] + self.store = Store(":memory:", now=lambda: self.clock[0]) + 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.store.add(self.fresh) + + def test_plan_lists_only_stale_unconfirmed_memories_and_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) + + 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_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_applying_twice_is_a_no_op(self): + tidy.apply(self.store, tidy.make_plan(self.store, NOW, days=90)) + self.assertEqual(tidy.make_plan(self.store, NOW, days=90).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): + with self.assertRaises(KeyError): + tidy.undo(self.store, memory_id) + + +if __name__ == "__main__": + unittest.main()