feat(memory): v2 conversation history store and its context in the reply prompt

- src/jarvis/memory/history.py keeps voice transcripts, Jarvis's answers,
  registered chat channel messages (with edits and deletes) and voice channel
  presence in one SQLite file. Every read is scoped to the asker: own records
  always, chat channels and others' words (only while the asker was in the
  same voice channel) behind settings, plus an optional since and off.
- Search is language-agnostic: Unicode words, prefixes keeping 60% of the
  word, rarer words weigh more, newer wins ties. 100k records search in
  24-61 ms here. context() returns the recent window and the matches cut to a
  token budget, matches at most half so chatter cannot push out the record
  the question is about.
- run_reply_engine(history=...) puts that context into the system prompt
  under "Information shared in previous conversations", fenced as data.
  evals/test_history_context_recall.py: with the block qwen2.5:7b answers the
  stored day in Korean and English (3 of 3 runs), without it the day is unknown.
- Spec history.spec.md, registry entry in CLAUDE.md, reply.spec.md,
  docs/llm_contexts.md, docs/v2/memory.md and roadmap updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 12:45:33 +09:00
parent 6b23a8adc7
commit 54a465948a
11 changed files with 774 additions and 2 deletions

View File

@@ -0,0 +1,294 @@
"""Conversation history store (v2): voice transcripts, Jarvis's answers and
registered chat channel messages, searched per asker. Contract:
``history.spec.md`` next to this file."""
from __future__ import annotations
import math
import re
import sqlite3
import threading
import time
from dataclasses import dataclass, field
from typing import Iterable, List, Optional
from ..debug import debug_log
_SCHEMA = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY,
ts REAL NOT NULL,
kind TEXT NOT NULL, -- voice | reply | chat
channel_id TEXT NOT NULL,
author_id TEXT NOT NULL,
author_name TEXT NOT NULL,
to_id TEXT,
message_id TEXT,
text TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS history_ts ON history(ts);
CREATE INDEX IF NOT EXISTS history_author ON history(author_id);
CREATE INDEX IF NOT EXISTS history_to ON history(to_id);
CREATE UNIQUE INDEX IF NOT EXISTS history_message ON history(channel_id, message_id)
WHERE message_id IS NOT NULL;
CREATE TABLE IF NOT EXISTS presence (
id INTEGER PRIMARY KEY,
user_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
joined REAL NOT NULL,
left_at REAL
);
CREATE INDEX IF NOT EXISTS presence_user ON presence(user_id, channel_id);
"""
_WORD = re.compile(r"\w{2,}", re.UNICODE)
_SEARCH_CANDIDATES = 5000
_BYTES_PER_TOKEN = 3
@dataclass(frozen=True)
class Scope:
"""What an asker may see besides their own records (``history.spec.md``)."""
chat: bool = True
others: bool = True
since: Optional[float] = None
off: bool = False
@dataclass(frozen=True)
class Record:
id: int
ts: float
kind: str
channel_id: str
author_id: str
author_name: str
to_id: Optional[str]
message_id: Optional[str]
text: str
@dataclass
class HistoryContext:
"""Lines for the prompt: the recent window and the search matches, kept apart for labelling."""
recent: List[str] = field(default_factory=list)
matches: List[str] = field(default_factory=list)
def _word_patterns(query: str) -> List[List[str]]:
"""For each query word, its accepted forms, longest first (the word, then shorter prefixes)."""
out: List[List[str]] = []
seen = set()
for w in _WORD.findall(query.lower()):
if w in seen:
continue
seen.add(w)
shortest = max(2, math.ceil(len(w) * 0.6))
out.append([w[:n] for n in range(len(w), shortest - 1, -1)])
return out
def _tokens(line: str) -> float:
return len(line.encode("utf-8")) / _BYTES_PER_TOKEN
class HistoryStore:
def __init__(self, path: str, assistant_name: str = "Jarvis") -> None:
self.assistant_name = assistant_name
self._lock = threading.Lock()
self._conn = sqlite3.connect(path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._conn.execute("PRAGMA journal_mode=WAL")
self._conn.execute("PRAGMA synchronous=NORMAL")
self._conn.executescript(_SCHEMA)
self._conn.commit()
def close(self) -> None:
with self._lock:
self._conn.close()
# -- writes -------------------------------------------------------------
def _insert(self, kind: str, channel_id: str, author_id: str, author_name: str, text: str,
ts: float, to_id: Optional[str] = None, message_id: Optional[str] = None) -> Optional[int]:
text = (text or "").strip()
if not text:
return None
with self._lock:
cur = self._conn.execute(
"INSERT OR REPLACE INTO history(ts, kind, channel_id, author_id, author_name, to_id, message_id, text)"
" VALUES (?,?,?,?,?,?,?,?)",
(ts, kind, channel_id, author_id, author_name, to_id, message_id, text),
)
self._conn.commit()
return int(cur.lastrowid)
def add_voice(self, channel_id: str, speaker_id: str, speaker_name: str, text: str, ts: float) -> Optional[int]:
return self._insert("voice", channel_id, speaker_id, speaker_name, text, ts)
def add_reply(self, channel_id: str, to_id: str, text: str, ts: float) -> Optional[int]:
return self._insert("reply", channel_id, "", self.assistant_name, text, ts, to_id=to_id)
def add_chat(self, channel_id: str, message_id: str, author_id: str, author_name: str, text: str,
ts: float, to_id: Optional[str] = None) -> Optional[int]:
return self._insert("chat", channel_id, author_id, author_name, text, ts, to_id=to_id, message_id=message_id)
def edit_chat(self, channel_id: str, message_id: str, text: str) -> None:
text = (text or "").strip()
if not text:
self.delete_chat(channel_id, message_id)
return
with self._lock:
self._conn.execute("UPDATE history SET text=? WHERE channel_id=? AND message_id=?",
(text, channel_id, message_id))
self._conn.commit()
def delete_chat(self, channel_id: str, message_id: str) -> None:
with self._lock:
self._conn.execute("DELETE FROM history WHERE channel_id=? AND message_id=?", (channel_id, message_id))
self._conn.commit()
def presence_join(self, user_id: str, channel_id: str, ts: float) -> None:
with self._lock:
open_row = self._conn.execute(
"SELECT 1 FROM presence WHERE user_id=? AND channel_id=? AND left_at IS NULL",
(user_id, channel_id)).fetchone()
if open_row is None:
self._conn.execute("INSERT INTO presence(user_id, channel_id, joined) VALUES (?,?,?)",
(user_id, channel_id, ts))
self._conn.commit()
def presence_leave(self, user_id: str, channel_id: str, ts: float) -> None:
with self._lock:
self._conn.execute(
"UPDATE presence SET left_at=? WHERE user_id=? AND channel_id=? AND left_at IS NULL",
(ts, user_id, channel_id))
self._conn.commit()
def presence_close_channel(self, channel_id: str, ts: float) -> None:
with self._lock:
self._conn.execute("UPDATE presence SET left_at=? WHERE channel_id=? AND left_at IS NULL",
(ts, channel_id))
self._conn.commit()
# -- maintenance --------------------------------------------------------
def records_of(self, person: str) -> List[Record]:
with self._lock:
rows = self._conn.execute(
"SELECT * FROM history WHERE author_id=? OR to_id=? ORDER BY ts, id", (person, person)).fetchall()
return [Record(**dict(r)) for r in rows]
def forget_person(self, person: str) -> None:
with self._lock:
n = self._conn.execute("DELETE FROM history WHERE author_id=? OR to_id=?", (person, person)).rowcount
self._conn.execute("DELETE FROM presence WHERE user_id=?", (person,))
self._conn.commit()
debug_log(f"history: forgot a person ({n} records)", "memory")
def purge_older_than(self, ts: float) -> None:
with self._lock:
n = self._conn.execute("DELETE FROM history WHERE ts < ?", (ts,)).rowcount
self._conn.execute("DELETE FROM presence WHERE left_at IS NOT NULL AND left_at < ?", (ts,))
self._conn.commit()
debug_log(f"history: retention removed {n} records", "memory")
# -- reads --------------------------------------------------------------
@staticmethod
def _scope_sql(asker: str, scope: Scope) -> tuple[str, list]:
clauses = ["h.author_id = ? OR h.to_id = ?"]
params: list = [asker, asker]
if scope.chat:
clauses.append("h.kind = 'chat'")
if scope.others:
clauses.append(
"h.kind IN ('voice','reply') AND EXISTS (SELECT 1 FROM presence p WHERE p.user_id = ?"
" AND p.channel_id = h.channel_id AND p.joined <= h.ts AND (p.left_at IS NULL OR p.left_at >= h.ts))")
params.append(asker)
sql = "(" + " OR ".join(f"({c})" for c in clauses) + ")"
if scope.since is not None:
sql += " AND h.ts >= ?"
params.append(scope.since)
return sql, params
def recent(self, asker: str, now: float, scope: Scope, minutes: float = 30,
max_records: int = 20) -> List[Record]:
if scope.off or max_records <= 0:
return []
where, params = self._scope_sql(asker, scope)
with self._lock:
rows = self._conn.execute(
f"SELECT h.* FROM history h WHERE {where} AND h.ts >= ? AND h.ts <= ?"
" ORDER BY h.ts DESC, h.id DESC LIMIT ?",
(*params, now - minutes * 60, now, max_records)).fetchall()
return [Record(**dict(r)) for r in reversed(rows)]
def _scored_search(self, asker: str, query: str, scope: Scope, limit: int,
exclude: Iterable[int]) -> List[tuple[float, Record]]:
words = _word_patterns(query)
if scope.off or not words or limit <= 0:
return []
where, params = self._scope_sql(asker, scope)
patterns = sorted({p for forms in words for p in forms})
match_sql = " OR ".join("instr(lower(h.text), ?) > 0" for _ in patterns)
skip = sorted(set(exclude))
skip_sql = f" AND h.id NOT IN ({','.join('?' * len(skip))})" if skip else ""
t0 = time.perf_counter()
with self._lock:
rows = self._conn.execute(
f"SELECT h.* FROM history h WHERE {where} AND ({match_sql}){skip_sql}"
" ORDER BY h.ts DESC, h.id DESC LIMIT ?",
(*params, *patterns, *skip, _SEARCH_CANDIDATES)).fetchall()
records = [Record(**dict(r)) for r in rows]
lowered = [r.text.lower() for r in records]
# Per word: matched fraction for every candidate, then inverse document frequency.
fractions = []
for forms in words:
col = []
for text in lowered:
hit = next((len(f) for f in forms if f in text), 0)
col.append(hit / len(forms[0]))
fractions.append(col)
n = len(records)
weights = [math.log(1 + n / max(1, sum(1 for x in col if x))) for col in fractions]
scored = []
for i, rec in enumerate(records):
score = sum(w * col[i] for w, col in zip(weights, fractions))
if score > 0:
scored.append((score, rec))
scored.sort(key=lambda sr: (sr[0], sr[1].ts, sr[1].id), reverse=True)
debug_log(f"history search: {n} candidates, {len(scored)} scored, "
f"{(time.perf_counter() - t0) * 1000:.0f} ms", "memory")
return scored[:limit]
def search(self, asker: str, query: str, scope: Scope, limit: int = 5,
exclude: Iterable[int] = ()) -> List[Record]:
return [rec for _, rec in self._scored_search(asker, query, scope, limit, exclude)]
@staticmethod
def format_line(rec: Record) -> str:
stamp = time.strftime("%Y-%m-%d %H:%M", time.localtime(rec.ts))
return f"[{stamp}] {rec.author_name}: {rec.text}"
def context(self, asker: str, query: str, now: float, scope: Scope, minutes: float = 30,
max_records: int = 20, limit: int = 5, budget_tokens: float = 4000) -> HistoryContext:
recent = self.recent(asker, now, scope, minutes=minutes, max_records=max_records)
matches = self.search(asker, query, scope, limit=limit, exclude={r.id for r in recent})
recent_lines = [self.format_line(r) for r in recent]
match_lines = [self.format_line(r) for r in matches] # best first
total = sum(_tokens(x) for x in recent_lines + match_lines)
# Matches get at most half the budget so a long recent window cannot crowd out the
# one record the question is about; the recent window gets the rest.
while match_lines and sum(_tokens(x) for x in match_lines) > budget_tokens / 2:
total -= _tokens(match_lines.pop())
while total > budget_tokens and recent_lines:
total -= _tokens(recent_lines.pop(0))
# Oldest match first reads like a timeline.
by_line = dict(zip((self.format_line(r) for r in matches), matches))
match_lines.sort(key=lambda line: by_line[line].ts)
debug_log(f"history context: {len(recent_lines)} recent, {len(match_lines)} matches, "
f"~{total:.0f} tokens", "memory")
return HistoryContext(recent=recent_lines, matches=match_lines)