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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## Unreleased

- `personakit_read` returns only relevant memories. When nothing is relevant the answer is
empty: approved memories are no longer added as standing context.
- Evidence quotes are sent only with `include_evidence`. A memory already sent by the same
server process comes back as its id with `seen: true`, unless `include_seen`.
- Reads take `context` (what the assistant is about to do, ranked like a second question) and
`scope` (that scope plus global). `more` in the answer counts relevant memories left out by
the limit.
- Owner-written `answers` and `applies_when` on a memory, set with `personakit hints`. They
help ranking and are never sent to assistants. Existing stores upgrade in place.

## 0.2.0

- `personakit tidy`: a plan that folds near-identical unconfirmed memories into the oldest one
Expand Down
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ personakit tidy --apply # carry the
personakit merges # list what was folded, with ids
personakit undo <memory-id> # reverse one fold or one stale archive
personakit digest # what changed in the last 7 days (local, prints memory text)
personakit hints <memory-id> --answers "<question>" # help the right question find a memory (never sent to assistants)
personakit serve # MCP server over stdio for your assistants
personakit forget <memory-id> # delete a memory and its quotes for good
```
Expand Down Expand Up @@ -90,7 +91,7 @@ Your assistant gets two tools:

| Tool | What it does |
|---|---|
| `personakit_read` | Returns the memories relevant to a question, each with its evidence quotes and whether you have confirmed it. |
| `personakit_read` | Returns only the memories relevant to a question (and, if the assistant says, to what it is about to do), each with whether you have confirmed it. Nothing relevant means an empty answer. Evidence quotes are sent only when the assistant asks for them, and a memory already sent in the same session comes back as its id only. |
| `personakit_propose` | Lets the assistant suggest a new memory. It is stored as *unconfirmed* until you review it. |

## How it works
Expand All @@ -105,7 +106,8 @@ Your assistant gets two tools:
3. **Store** keeps each memory with its source quote, a state, and a scope.
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.
5. **Serve** exposes the store to assistants over MCP: a small packet of relevant memories, with
evidence on request.
6. **Tidy** (on request) folds near-identical memories into one, and
archives unconfirmed memories not seen again for 90 days. It shows a plan first; nothing changes without `--apply`, nothing is deleted, and `personakit undo <id>`
reverses a step.
Expand All @@ -125,7 +127,8 @@ Stated plainly, so you know what you are installing:

- **Extraction is a model's guess.** Review is how you correct it.
- **Ranking is word overlap**, on whole words in Latin letters and digits. Questions and memories
in other scripts are not matched yet; approved memories are still returned as standing context.
in other scripts are not matched yet, so such a question gets an empty answer. `personakit hints`
lets you add the questions and situations a memory is for, which counts towards matching.
- **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,
Expand Down
10 changes: 6 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ flowchart TB
| `llm` | One interface, `complete(prompt) -> str`, implemented by two CLI-backed clients (`claude`, `codex`). The per-run call budget lives here. | nothing |
| `extract` | Builds the prompt from owner turns, validates the reply into `Memory` + `Evidence`, and counts what it rejects and why. | `model`, `llm` |
| `sweep` | Runs ingest, extract and store over new sessions. Skips unchanged files, stops only on budget or model error, never because unreviewed memories are piling up. | `ingest`, `extract`, `llm`, `store` |
| `retrieve` | The one read policy: approved and unconfirmed memories are served, restricted and archived never are. It also shapes the evidence quotes an assistant receives (email addresses masked, cut at a word boundary). Word-overlap ranking, a baseline to be measured. | `model` |
| `retrieve` | The one read policy: approved and unconfirmed memories are served, restricted and archived never are, and only relevant ones (nothing relevant, nothing served). A read may name a scope (that scope and `global` only) and a context (scored like a second question). It also shapes the evidence quotes an assistant receives (email addresses masked, cut at a word boundary). Word-overlap ranking, a baseline to be measured. | `model` |
| `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` |
| `mcp_server` | Two tools for assistants: `personakit_read` and `personakit_propose`. Holds no read-policy constants of its own. Shapes the packet: evidence only on request, and a memory already sent by this server process comes back as its id only (kept in memory, never stored). Assistants cannot approve, restrict, hide or forget; only the owner can, in `review`. | `store`, `retrieve`, `extract` |
| `twins` | Finds near-identical unconfirmed memories of one category and scope, across sessions. Word-based, deliberately cautious (the order of shared words must agree); numbers and negation must agree whatever scores a pair. Pure functions. | `model`, `retrieve` |
| `decay` | Finds unconfirmed memories not seen again for a long time (90 days by default). Pure functions. | `model` |
| `tidy` | Turns `twins` and `decay` into a plan (read-only), applies it only on request, and reverses single steps. | `twins`, `decay`, `store` |
Expand All @@ -60,8 +60,10 @@ 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, last_seen_at, decided_at, decided_by`.
`last_seen_at` moves forward each time the same statement is extracted again.
- **Memory**: `id, text, category, scope, state, created_at, last_seen_at, decided_at, decided_by,
answers, applies_when`. `last_seen_at` moves forward each time the same statement is extracted
again. `answers` (questions it answers) and `applies_when` (situations it applies in) are written
by the owner with `personakit hints`; they count towards relevance and are never served.
- **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
Expand Down
2 changes: 1 addition & 1 deletion docs/PLUGINS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ PersonaKit has two extension points. Both replace a scoring function and nothing

| Hook | Signature | Built-in | Used by |
|---|---|---|---|
| `relevance` | `(question: str, memories: Sequence[Memory]) -> Sequence[float]` | word overlap | `personakit serve` (which memories answer a question, and in what order) |
| `relevance` | `(question: str, memories: Sequence[Memory]) -> Sequence[float]` | word overlap (text, category and the owner's hints) | `personakit serve` (which memories answer a question, and in what order; when the assistant states a context it is called a second time with that text, and each memory keeps its higher score) |
| `similarity` | `(a: str, b: str) -> float` between 0 and 1 | shared words, with number, negation and order guards | `personakit tidy` (which memories are twins) |

## What a plugin cannot do
Expand Down
10 changes: 7 additions & 3 deletions docs/PRIVACY.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@
name, through your own signed-in `claude` or `codex` CLI, under that provider's terms. Assistant replies,
tool output and file contents from sessions are not sent.
- **What assistants see:** only what the MCP server returns. Restricted and archived
memories are never returned; unconfirmed ones are labelled. The evidence quotes it returns are shortened to a word boundary and email
addresses in them are masked; the store itself keeps the quote as you wrote it.
memories are never returned; unconfirmed ones are labelled. Only memories relevant to the
assistant's question, or to what it says it is about to do, are returned. Evidence quotes are
returned only when the assistant asks for them; they are shortened to a word boundary and email
addresses in them are masked; the store itself keeps the quote as you wrote it. The hints you add
with `personakit hints` help ranking and are never returned.
- **Read log:** each read stores the time and two counts (returned, withheld) in your local
store. The question and the memory text are not recorded.
store. The question, the assistant's stated context and the memory text are not recorded. The
server remembers which memory ids it has already sent, in memory only, until it stops.
- **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.
Expand Down
27 changes: 27 additions & 0 deletions personakit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ def build_parser() -> argparse.ArgumentParser:
digest_cmd.add_argument("--days", type=int, default=7)
digest_cmd.add_argument("--json", action="store_true", help="print a JSON object")

hints = sub.add_parser("hints", help="show or set the questions a memory answers and when it applies")
hints.add_argument("memory_id")
hints.add_argument("--answers", action="append", metavar="QUESTION", help="a question it answers (repeat for more)")
hints.add_argument("--applies-when", action="append", metavar="SITUATION", help="a situation it applies in (repeat for more)")
hints.add_argument("--clear", action="store_true", help="remove both kinds of hint (before adding any given here)")

forget = sub.add_parser("forget", help="permanently delete a memory and its quotes")
forget.add_argument("memory_id")

Expand Down Expand Up @@ -119,6 +125,8 @@ def _dispatch(args: argparse.Namespace, store: Store) -> int:
_print_json(collected)
else:
print(digest.format_digest(collected))
elif args.command == "hints":
return _hints(args, store)
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 @@ -134,6 +142,25 @@ def _print_json(data: object) -> None:
print(json.dumps(data, sort_keys=True, ensure_ascii=False))


def _hints(args: argparse.Namespace, store: Store) -> int:
"""Each kind of hint given replaces that kind; one not given is kept, unless --clear."""
empty = [] if args.clear else None
try:
if args.clear or args.answers or args.applies_when:
memory = store.set_hints(args.memory_id, args.answers or empty, args.applies_when or empty)
else:
memory = store.get(args.memory_id)
if memory is None:
raise KeyError(args.memory_id)
except KeyError:
print(f"No memory with id {args.memory_id}", file=sys.stderr)
return 1
print(memory.text)
for label, entries in (("answers", memory.answers), ("applies when", memory.applies_when)):
print(f" {label}: " + ("; ".join(entries) if entries else "(none)"))
return 0


def _tidy(args: argparse.Namespace, store: Store) -> int:
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)
Expand Down
82 changes: 60 additions & 22 deletions personakit/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,47 @@
from personakit.store import Store

NOTE_UNCONFIRMED = "Unconfirmed: extracted from the owner's conversations but not yet reviewed by them."


def read_memories(store: Store, question: str, limit: int = 7, relevance: retrieve.Relevance = retrieve.overlap) -> dict:
"""Memories relevant to a question, under the one read policy."""
NOTE_SEEN = "Entries marked seen were sent earlier in this session. If you no longer have them, ask again with include_seen."
EVIDENCE_QUOTES = 2


def read_memories(
store: Store,
question: str,
limit: int = 7,
relevance: retrieve.Relevance = retrieve.overlap,
context: str = "",
scope: str = "",
include_evidence: bool = False,
include_seen: bool = False,
seen: set[str] | None = None,
) -> dict:
"""Memories relevant to a question, under the one read policy.

`seen` holds the ids already sent in full during this session. A memory in it comes back as
its id only, unless `include_seen`, or `include_evidence` (the quotes would be new). Ids sent
in full are added to it. With no set, every memory is sent in full.
"""
limit = max(1, min(limit, 20))
result = retrieve.search(store.list(), question, limit, relevance)
result = retrieve.search(store.list(), question, limit, relevance, context, scope)
store.log_read(len(result.memories), result.withheld)
response = {
"memories": [
{
"id": m.id,
"text": m.text,
"category": m.category,
"confirmed": m.state == State.APPROVED,
"evidence": [retrieve.served_quote(e.quote) for e in m.evidence[:2]],
}
for m in result.memories
],
"withheld": result.withheld,
}
if any(m.state != State.APPROVED for m in result.memories):
items, full = [], []
for m in result.memories:
if seen is not None and m.id in seen and not (include_seen or include_evidence):
items.append({"id": m.id, "seen": True})
continue
item = {"id": m.id, "text": m.text, "category": m.category, "confirmed": m.state == State.APPROVED}
if include_evidence:
item["evidence"] = [retrieve.served_quote(e.quote) for e in m.evidence[:EVIDENCE_QUOTES]]
items.append(item)
full.append(m)
if seen is not None:
seen.add(m.id)
response = {"memories": items, "withheld": result.withheld, "more": result.more}
if any(m.state != State.APPROVED for m in full):
response["note"] = NOTE_UNCONFIRMED
if len(full) < len(items):
response["seen_note"] = NOTE_SEEN
return response


Expand Down Expand Up @@ -63,10 +82,29 @@ def build_server(store: Store, relevance: retrieve.Relevance = retrieve.overlap)

server = FastMCP("personakit")

# One server process serves one assistant session, so what it has already sent lives here,
# in memory only. It is never written to the store.
sent: set[str] = set()

@server.tool()
def personakit_read(question: str, limit: int = 7) -> dict:
"""Read the owner's memories relevant to a question. Unconfirmed ones are labelled."""
return read_memories(store, question, limit, relevance)
def personakit_read(
question: str,
context: str = "",
scope: str = "",
limit: int = 7,
include_evidence: bool = False,
include_seen: bool = False,
) -> dict:
"""Read what the owner has said that is relevant to one focused question.

Ask before you act, one focused question at a time, and say in `context` what you are
about to do. An empty `memories` list means nothing relevant is known. `more` counts
relevant memories left out by `limit`. Unconfirmed memories are labelled and may be wrong.
An entry with only `seen: true` was sent earlier in this session; if you no longer have
it, ask again with include_seen. Ask for evidence only when you need the owner's own words.
`scope` (optional) limits the read to one project's memories plus general ones.
"""
return read_memories(store, question, limit, relevance, context, scope, include_evidence, include_seen, sent)

@server.tool()
def personakit_propose(text: str, quote: str, category: str = "other") -> dict:
Expand Down
6 changes: 6 additions & 0 deletions personakit/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ class Memory:
decided_at: str | None = None
decided_by: Decider | None = None
last_seen_at: str | None = None # last time the same statement was extracted again
# Written by the owner to help the right question find this memory. Used for ranking only;
# never sent to an assistant.
answers: tuple[str, ...] = () # questions this memory answers
applies_when: tuple[str, ...] = () # situations it applies in

def __post_init__(self) -> None:
if not self.text.strip():
Expand All @@ -95,6 +99,8 @@ def as_dict(self) -> dict[str, object]:
"text": self.text,
"quotes": len(self.evidence),
"created_at": self.created_at,
"answers": list(self.answers),
"applies_when": list(self.applies_when),
}


Expand Down
Loading
Loading