Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ build/
*.jsonl
!tests/fixtures/**/*.jsonl
.env
.coverage
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -53,11 +53,13 @@ personakit sweep --cli claude --model <model-name> --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 <id>`)
personakit serve # MCP server over stdio for your assistants
personakit forget <memory-id> # 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).
Expand Down Expand Up @@ -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 <id>`
reverses a step.

A memory is always in one of four states:

Expand All @@ -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:

Expand All @@ -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.
Expand All @@ -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
Expand Down
25 changes: 19 additions & 6 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand All @@ -26,6 +27,7 @@ flowchart TB
ST <--> RV
ST --> MCP
ST --> SS
ST <--> TD
MCP --> AS[Assistants]
```

Expand All @@ -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 |

Expand 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.
Expand All @@ -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 <id>`, 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.
3 changes: 3 additions & 0 deletions docs/PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 2 additions & 0 deletions docs/REVIEW-LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
5 changes: 4 additions & 1 deletion docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
41 changes: 40 additions & 1 deletion personakit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}


Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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)
Expand All @@ -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 <id>")
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:
Expand Down
33 changes: 33 additions & 0 deletions personakit/decay.py
Original file line number Diff line number Diff line change
@@ -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
]
2 changes: 1 addition & 1 deletion personakit/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}


Expand Down
1 change: 1 addition & 0 deletions personakit/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
43 changes: 38 additions & 5 deletions personakit/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;
""",
]


Expand All @@ -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()

Expand All @@ -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,
),
Expand All @@ -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:
Expand Down Expand Up @@ -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,
)
Loading
Loading