Add Discord-native hybrid front-end for Jarvis (bot + bridge)
Some checks failed
Release / semantic-release (push) Successful in 59s
tests / Unit tests (Linux, Python 3.11) (push) Successful in 13m45s
Release / build-linux (push) Failing after 7m47s
Release / build-windows (push) Has been cancelled
Release / build-macos (arm64, macos-latest) (push) Has been cancelled
Release / build-macos (x64, macos-15-intel) (push) Has been cancelled
Release / release-main (push) Has been cancelled
Release / release-develop (push) Has been cancelled

Transform isair/jarvis into a Discord-controlled voice assistant running on
the Ubuntu VNC desktop, keeping the mature ~39k-line Python brain intact.

- bot/ (Node + bun, discord.js): /자비스 slash commands (ephemeral),
  voice channel join + voice receive/playback, pluggable VNC screen broadcast
  (selfbot live / noVNC / screenshot)
- bridge/ (Python, Flask): wraps jarvis STT + run_reply_engine + Piper TTS
  behind a thin localhost HTTP API
- .env.example, scripts/ (start_bridge/start_bot/dev), README rewrite,
  docs/language-comparison.md and docs/vnc-xfce-setup.md

Language decision: hybrid (Python brain + Node/bun Discord layer) because
Discord blocks bot video; native screen broadcast only works via a Node
selfbot library.
This commit is contained in:
javis-bot
2026-06-09 14:51:05 +09:00
parent a5bf8d1826
commit c4abf63f38
308 changed files with 94135 additions and 1 deletions

View File

File diff suppressed because it is too large Load Diff

442
src/jarvis/memory/db.py Normal file
View File

@@ -0,0 +1,442 @@
from __future__ import annotations
import sqlite3
import re
from typing import Sequence, Optional
from pathlib import Path
import threading
from datetime import datetime, timezone
from ..debug import debug_log
_SCHEMA_SQL = """
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;
-- Structured meals log (optional feature)
CREATE TABLE IF NOT EXISTS meals (
id INTEGER PRIMARY KEY,
ts_utc TEXT NOT NULL,
source_app TEXT NOT NULL,
description TEXT NOT NULL,
calories_kcal REAL,
protein_g REAL,
carbs_g REAL,
fat_g REAL,
fiber_g REAL,
sugar_g REAL,
sodium_mg REAL,
potassium_mg REAL,
micros_json TEXT,
confidence REAL
);
-- Conversation summaries for diary/memory system
CREATE TABLE IF NOT EXISTS conversation_summaries (
id INTEGER PRIMARY KEY,
date_utc TEXT NOT NULL, -- YYYY-MM-DD format
ts_utc TEXT NOT NULL, -- When summary was created
summary TEXT NOT NULL, -- Concise summary of the day's conversations
topics TEXT, -- Comma-separated list of main topics discussed
source_app TEXT NOT NULL, -- Source app that generated the conversation
UNIQUE(date_utc, source_app)
);
CREATE VIRTUAL TABLE IF NOT EXISTS summaries_fts USING fts5(
summary,
topics,
content='conversation_summaries',
content_rowid='id',
tokenize='porter'
);
-- Triggers for conversation summaries FTS
CREATE TRIGGER IF NOT EXISTS summaries_ai AFTER INSERT ON conversation_summaries BEGIN
INSERT INTO summaries_fts(rowid, summary, topics) VALUES (new.id, new.summary, new.topics);
END;
CREATE TRIGGER IF NOT EXISTS summaries_ad AFTER DELETE ON conversation_summaries BEGIN
INSERT INTO summaries_fts(summaries_fts, rowid, summary, topics) VALUES('delete', old.id, old.summary, old.topics);
END;
CREATE TRIGGER IF NOT EXISTS summaries_au AFTER UPDATE ON conversation_summaries BEGIN
INSERT INTO summaries_fts(summaries_fts, rowid, summary, topics) VALUES('delete', old.id, old.summary, old.topics);
INSERT INTO summaries_fts(rowid, summary, topics) VALUES (new.id, new.summary, new.topics);
END;
"""
_VSS_SCHEMA_SQL = """
CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vss0(
id INTEGER PRIMARY KEY,
vec FLOAT[768]
);
CREATE TABLE IF NOT EXISTS summary_vec (
summary_id INTEGER PRIMARY KEY REFERENCES conversation_summaries(id) ON DELETE CASCADE,
emb_id INTEGER NOT NULL REFERENCES embeddings(id)
);
"""
def _normalize_fts_query(raw: str) -> str:
# Use improved fuzzy search query generation
try:
from .fuzzy_search import generate_flexible_fts_query
flexible_query = generate_flexible_fts_query(raw)
if flexible_query:
return flexible_query
except ImportError:
pass
# Fallback: Extract alphanumeric tokens and join them with spaces (logical AND)
tokens = re.findall(r"[A-Za-z0-9_]+", raw)
return " ".join(tokens)
class Database:
def __init__(self, db_path: str, sqlite_vss_path: Optional[str] = None) -> None:
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
self.db_path = db_path
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._lock = threading.RLock()
self.is_vss_enabled = False
self._python_vector_store = None
if sqlite_vss_path:
try:
self.conn.enable_load_extension(True)
self.conn.load_extension(sqlite_vss_path)
self.is_vss_enabled = True
except Exception:
self.is_vss_enabled = False
# If sqlite-vss is not available, use best available vector store (FAISS or Python fallback)
if not self.is_vss_enabled:
from ..utils.vector_store import get_best_vector_store
self._python_vector_store = get_best_vector_store(db_path, dimension=768)
# Log which vector store implementation is being used
import sys
store_type = type(self._python_vector_store).__name__
if store_type == "FAISSVectorStore":
debug_log("Using FAISS vector store for fast search", "jarvis")
else:
debug_log("Using Python fallback vector store", "jarvis")
self._init_schema()
def _init_schema(self) -> None:
with self._lock:
cur = self.conn.cursor()
cur.executescript(_SCHEMA_SQL)
if self.is_vss_enabled:
cur.executescript(_VSS_SCHEMA_SQL)
self.conn.commit()
def search_hybrid(self, fts_query: str, query_vec_json: Optional[str], top_k: int = 8) -> list[sqlite3.Row]:
with self._lock:
cur = self.conn.cursor()
safe_q = _normalize_fts_query(fts_query)
# Use Python vector store if sqlite-vss is not available
if not self.is_vss_enabled and self._python_vector_store and query_vec_json is not None and safe_q:
# Parse query vector
import json as _json
query_vec = _json.loads(query_vec_json)
# Get vector search results (use max of top_k*3 and 50 for good hybrid scoring)
vector_search_limit = max(top_k * 3, 50)
vector_results = self._python_vector_store.search(query_vec, top_k=vector_search_limit)
# Get FTS results (use max of top_k*3 and 50 for good hybrid scoring)
fts_search_limit = max(top_k * 3, 50)
fts_sql = f"""
SELECT s.id, bm25(summaries_fts) AS bm
FROM summaries_fts
JOIN conversation_summaries s ON s.id = summaries_fts.rowid
WHERE summaries_fts MATCH ?
ORDER BY bm
LIMIT {fts_search_limit}
"""
fts_rows = cur.execute(fts_sql, (safe_q,)).fetchall()
fts_scores = {row['id']: row['bm'] for row in fts_rows}
# Combine scores
combined_scores = {}
# Add vector scores (60% weight)
for summary_id, distance in vector_results:
combined_scores[summary_id] = (1.0 / (1.0 + distance)) * 0.6
# Add FTS scores (40% weight)
for summary_id, bm_score in fts_scores.items():
if summary_id in combined_scores:
combined_scores[summary_id] += (1.0 / (1.0 + bm_score)) * 0.4
else:
combined_scores[summary_id] = (1.0 / (1.0 + bm_score)) * 0.4
# Sort by combined score and fetch summaries
sorted_ids = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
if sorted_ids:
# Fetch summaries for top results
placeholders = ','.join('?' * len(sorted_ids))
summary_sql = f"""
SELECT s.id,
'[' || s.date_utc || '] ' || s.summary || ' (Topics: ' || COALESCE(s.topics, '') || ')' AS text,
'summary' AS result_type
FROM conversation_summaries s
WHERE s.id IN ({placeholders})
"""
rows = cur.execute(summary_sql, [sid for sid, _ in sorted_ids]).fetchall()
# Create result rows with scores
results = []
id_to_score = {sid: score for sid, score in sorted_ids}
for row in rows:
# Create a new row dict with score
result = dict(row)
result['score'] = id_to_score.get(row['id'], 0.0)
results.append(result)
# Sort by score again (in case DB returned in different order)
results.sort(key=lambda x: x['score'], reverse=True)
return results
else:
return []
elif self.is_vss_enabled and query_vec_json is not None and safe_q:
# Hybrid search: 60% vector similarity (semantic) + 40% FTS (exact terms)
# This balances finding semantically related content with keyword matches
# Use dynamic limits for efficiency on large datasets
search_limit = max(top_k * 3, 50)
summary_sql = f"""
WITH fts_sum AS (
SELECT s.id, bm25(summaries_fts) AS bm
FROM summaries_fts
JOIN conversation_summaries s ON s.id = summaries_fts.rowid
WHERE summaries_fts MATCH ?
ORDER BY bm LIMIT {search_limit}
),
v_sum AS (
SELECT sv.summary_id AS id, distance
FROM vss_search(embeddings, 'vec', ?)
JOIN summary_vec sv ON sv.emb_id = rowid
LIMIT {search_limit}
)
SELECT s.id, (
(1.0/(1.0+COALESCE(v_sum.distance, 1))) * 0.6 +
(1.0/(1.0+COALESCE(fts_sum.bm, 10))) * 0.4
) AS score,
'[' || s.date_utc || '] ' || s.summary || ' (Topics: ' || COALESCE(s.topics, '') || ')' AS text,
'summary' AS result_type
FROM conversation_summaries s
LEFT JOIN v_sum ON v_sum.id = s.id
LEFT JOIN fts_sum ON fts_sum.id = s.id
WHERE v_sum.id IS NOT NULL OR fts_sum.id IS NOT NULL
ORDER BY score DESC
LIMIT {int(top_k)};
"""
rows = cur.execute(summary_sql, (safe_q, query_vec_json)).fetchall()
elif safe_q:
# FTS-only search over conversation summaries
summary_sql = f"""
SELECT s.id, bm25(summaries_fts) AS score,
'[' || s.date_utc || '] ' || s.summary || ' (Topics: ' || COALESCE(s.topics, '') || ')' AS text,
'summary' AS result_type
FROM summaries_fts
JOIN conversation_summaries s ON s.id = summaries_fts.rowid
WHERE summaries_fts MATCH ?
ORDER BY score
LIMIT {int(top_k)};
"""
rows = cur.execute(summary_sql, (safe_q,)).fetchall()
else:
# Fallback: latest conversation summaries
summary_sql = f"""
SELECT id, 0.0 AS score,
'[' || date_utc || '] ' || summary || ' (Topics: ' || COALESCE(topics, '') || ')' AS text,
'summary' AS result_type
FROM conversation_summaries
ORDER BY date_utc DESC
LIMIT {int(top_k)};
"""
rows = cur.execute(summary_sql).fetchall()
return rows
@staticmethod
def _pack_vector(vec: Sequence[float]) -> bytes:
# SQLite-vss expects a float array; packing via array('f') ensures binary blob layout.
import array
arr = array.array('f', [float(x) for x in vec])
return arr.tobytes()
# --- Meals API ---
def insert_meal(
self,
ts_utc: str,
source_app: str,
description: str,
calories_kcal: Optional[float] = None,
protein_g: Optional[float] = None,
carbs_g: Optional[float] = None,
fat_g: Optional[float] = None,
fiber_g: Optional[float] = None,
sugar_g: Optional[float] = None,
sodium_mg: Optional[float] = None,
potassium_mg: Optional[float] = None,
micros_json: Optional[str] = None,
confidence: Optional[float] = None,
) -> int:
with self._lock:
cur = self.conn.cursor()
cur.execute(
"""
INSERT INTO meals(ts_utc, source_app, description, calories_kcal, protein_g, carbs_g, fat_g, fiber_g, sugar_g, sodium_mg, potassium_mg, micros_json, confidence)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
ts_utc,
source_app,
description,
calories_kcal,
protein_g,
carbs_g,
fat_g,
fiber_g,
sugar_g,
sodium_mg,
potassium_mg,
micros_json,
confidence,
),
)
self.conn.commit()
return int(cur.lastrowid)
def get_meals_between(self, ts_utc_min: str, ts_utc_max: str) -> list[sqlite3.Row]:
with self._lock:
cur = self.conn.cursor()
rows = cur.execute(
"""
SELECT * FROM meals
WHERE ts_utc >= ? AND ts_utc <= ?
ORDER BY ts_utc ASC
""",
(ts_utc_min, ts_utc_max),
).fetchall()
return rows
def delete_meal(self, meal_id: int) -> bool:
with self._lock:
cur = self.conn.cursor()
cur.execute("DELETE FROM meals WHERE id = ?", (meal_id,))
self.conn.commit()
return cur.rowcount > 0
# --- Conversation Summaries API ---
def upsert_conversation_summary(
self,
date_utc: str, # YYYY-MM-DD format
summary: str,
topics: Optional[str] = None,
source_app: str = "jarvis",
ts_utc: Optional[str] = None,
) -> int:
"""Insert or update a conversation summary for a given date.
``ts_utc`` defaults to "now". Maintenance ops that rewrite an
existing row's content without changing what it represents (e.g.
the deflection scrub bulk sweep) should pass through the row's
original ``ts_utc`` so the audit trail is preserved.
"""
if ts_utc is None:
ts_utc = datetime.now(timezone.utc).isoformat()
with self._lock:
cur = self.conn.cursor()
cur.execute(
"""
INSERT OR REPLACE INTO conversation_summaries(date_utc, ts_utc, summary, topics, source_app)
VALUES (?, ?, ?, ?, ?)
""",
(date_utc, ts_utc, summary, topics, source_app),
)
self.conn.commit()
return int(cur.lastrowid)
def get_conversation_summary(self, date_utc: str, source_app: str = "jarvis") -> Optional[sqlite3.Row]:
"""Get conversation summary for a specific date."""
with self._lock:
cur = self.conn.cursor()
row = cur.execute(
"""
SELECT * FROM conversation_summaries
WHERE date_utc = ? AND source_app = ?
""",
(date_utc, source_app),
).fetchone()
return row
def get_recent_conversation_summaries(self, days: int = 7) -> list[sqlite3.Row]:
"""Get conversation summaries from the last N days."""
from datetime import datetime, timedelta, timezone
cutoff_date = (datetime.now(timezone.utc) - timedelta(days=days)).date().isoformat()
with self._lock:
cur = self.conn.cursor()
rows = cur.execute(
"""
SELECT * FROM conversation_summaries
WHERE date_utc >= ?
ORDER BY date_utc DESC
""",
(cutoff_date,),
).fetchall()
return rows
def get_all_conversation_summaries(self) -> list[sqlite3.Row]:
"""Get all conversation summaries, ordered by date ascending (oldest first).
Used for bulk import into graph memory — processes diary entries
chronologically so the graph builds up naturally.
"""
with self._lock:
cur = self.conn.cursor()
rows = cur.execute(
"""
SELECT * FROM conversation_summaries
ORDER BY date_utc ASC
""",
).fetchall()
return rows
def upsert_summary_embedding(self, summary_id: int, vec: Sequence[float]) -> Optional[int]:
"""Store or update embedding for a conversation summary."""
if self.is_vss_enabled:
# Use sqlite-vss
with self._lock:
cur = self.conn.cursor()
cur.execute("INSERT INTO embeddings(vec) VALUES (?)", (sqlite3.Binary(self._pack_vector(vec)),))
emb_id = cur.lastrowid
cur.execute(
"INSERT OR REPLACE INTO summary_vec(summary_id, emb_id) VALUES (?, ?)",
(summary_id, emb_id),
)
self.conn.commit()
return int(emb_id)
elif self._python_vector_store:
# Use Python vector store
self._python_vector_store.add_vector(summary_id, list(vec))
return summary_id # Return summary_id as a placeholder for emb_id
else:
return None
def close(self) -> None:
try:
with self._lock:
self.conn.close()
except Exception:
pass

View File

@@ -0,0 +1,19 @@
from __future__ import annotations
import requests
def get_embedding(text: str, base_url: str, model: str, timeout_sec: float = 15.0) -> list[float] | None:
try:
resp = requests.post(
f"{base_url.rstrip('/')}/api/embeddings",
json={"model": model, "prompt": text},
timeout=timeout_sec,
)
resp.raise_for_status()
data = resp.json()
vec = data.get("embedding")
if isinstance(vec, list):
return [float(x) for x in vec]
except Exception:
return None
return None

820
src/jarvis/memory/graph.py Normal file
View File

@@ -0,0 +1,820 @@
"""
🧠 Knowledge Graph
A self-organising node graph that stores the assistant's accumulated world
knowledge — anything learned during conversations that it wouldn't already know.
Three fast-access entry points (recent nodes, top nodes, root node) ensure the
most relevant knowledge is always reachable without exhaustive search.
See graph.spec.md for the full specification.
"""
from __future__ import annotations
import re
import sqlite3
import threading
import unicodedata
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Optional
from ..debug import debug_log
# ── Mutation listeners ─────────────────────────────────────────────────────
#
# Lightweight observer registry so consumers (e.g. DialogueMemory's warm
# profile cache) can invalidate derived state when a node is created,
# updated, or deleted. The listener receives the action name, node id, and
# the FIXED_BRANCH ancestor (e.g. ``"user"``, ``"directives"``, ``"world"``)
# so it can scope its reaction. Failures in listeners are logged and
# swallowed so they cannot break a write.
_MUTATION_LISTENERS: "list[Callable[..., None]]" = []
def register_graph_mutation_listener(cb: Callable[..., None]) -> None:
"""Register a callback invoked after every node mutation.
The callback is invoked with keyword arguments ``action``, ``node_id``,
and ``branch`` where ``branch`` is the id of the FIXED_BRANCH ancestor
(or the node id itself when the node is a fixed branch), or ``None``
when the branch cannot be resolved (e.g. root mutations).
"""
if cb not in _MUTATION_LISTENERS:
_MUTATION_LISTENERS.append(cb)
def unregister_graph_mutation_listener(cb: Callable[..., None]) -> None:
"""Remove a previously registered mutation listener (idempotent)."""
try:
_MUTATION_LISTENERS.remove(cb)
except ValueError:
pass
def _notify_graph_mutation(action: str, node_id: str, branch: Optional[str]) -> None:
for cb in list(_MUTATION_LISTENERS):
try:
cb(action=action, node_id=node_id, branch=branch)
except Exception as exc:
debug_log(f"graph mutation listener failed (non-fatal): {exc}", "memory")
# ── Fact normalisation ─────────────────────────────────────────────────────
#
# Used for dedupe comparisons. Locale-safe — the user base includes
# non-Latin scripts (e.g. Turkish, where ``"İ".lower()`` returns ``"i"``
# but Turkish lowercase is ``"ı"``), so we use ``unicodedata.NFKC`` plus
# ``str.casefold`` rather than ``str.lower``. ``casefold`` also folds
# German ß to ss, and NFKC collapses visually identical code points.
_WS_RE = re.compile(r"\s+")
def normalise_fact(text: str) -> str:
"""Lowercase (Unicode-aware) + collapse all whitespace, including
newlines, into single spaces for fuzzy equality. ``_WS_RE`` matches
``\\s+``, so any newline embedded in an extracted fact collapses to
a space on the candidate side, keeping the dedupe key well-formed
even if the extractor accidentally emits a multi-line statement."""
folded = unicodedata.normalize("NFKC", text).casefold()
return _WS_RE.sub(" ", folded.strip())
# ── Configuration defaults ──────────────────────────────────────────────────
SPLIT_THRESHOLD = 1500 # tokens — when to split a node into children
MERGE_THRESHOLD = 200 # tokens — when to collapse sparse children back
RECENT_NODES_COUNT = 10 # number of recently-accessed nodes to track
TOP_NODES_COUNT = 15 # most-accessed nodes to surface
TOP_NODES_WINDOW_DAYS = 30 # time window for top-nodes ranking (legacy, kept for compat)
MAX_TRAVERSAL_DEPTH = 8 # safety limit on graph traversal
SUMMARY_MAX_LENGTH = 300 # max characters for a node description
DECAY_HALF_LIFE_DAYS = 14 # days until a node's access score halves
# ── Fixed top-level branches ────────────────────────────────────────────────
#
# The root is seeded with three fixed children on first run. The graph
# is still self-organising below these — auto-split/merge runs within
# each branch — but the top level is purpose-shaped, not content-shaped,
# so the extractor can route each new fact into the right semantic slot.
#
# - USER: everything about the person the assistant serves (identity,
# tastes, preferences, plans, opinions). Warm-loaded into the system
# prompt on every turn.
# - DIRECTIVES: imperatives the user issued at the assistant about its
# own behaviour ("be concise", "use British English", "stop apologising").
# Verbatim rules, never summarised. Warm-loaded on every turn.
# - WORLD: external facts with attribution (current graph content —
# films, businesses, recipes, techniques). Unbounded. Not warm-loaded;
# retrieved on demand via searchMemory.
#
# The IDs are stable strings so re-opening an existing graph is
# idempotent — no duplicate branches get seeded if the store already
# has them.
BRANCH_USER = "user"
BRANCH_DIRECTIVES = "directives"
BRANCH_WORLD = "world"
FIXED_BRANCHES: tuple[tuple[str, str, str], ...] = (
(
BRANCH_USER,
"User",
"Everything about the user: identity, location, relationships, "
"tastes, preferences, history, plans, opinions. Always injected "
"into the system prompt.",
),
(
BRANCH_DIRECTIVES,
"Directives",
"Imperatives the user issued at the assistant about its own "
"behaviour — tone, verbosity, language, style rules. Verbatim, "
"never summarised. Always injected into the system prompt.",
),
(
BRANCH_WORLD,
"World",
"External facts the assistant has learned and wants to carry "
"forward: films, businesses, recipes, techniques, events. "
"Retrieved on demand via searchMemory.",
),
)
FIXED_BRANCH_IDS: frozenset[str] = frozenset(bid for bid, _, _ in FIXED_BRANCHES)
# ── SQL helpers ────────────────────────────────────────────────────────────
def _decay_score_sql(half_life_days: int = DECAY_HALF_LIFE_DAYS) -> str:
"""Return a SQL expression that computes a time-decayed access score.
Uses hyperbolic decay: access_count / (1 + age_days / half_life).
A node accessed 100 times 14 days ago scores the same as one
accessed 50 times today (with default half-life of 14 days).
The raw access_count is never modified — decay is computed at query time
so no data is lost and the half-life can be changed freely.
"""
return (
f"(access_count * 1.0 / "
f"(1.0 + MAX(0, julianday('now') - julianday(last_accessed)) / {half_life_days}.0))"
)
# ── Data model ──────────────────────────────────────────────────────────────
@dataclass
class MemoryNode:
"""A single node in the memory graph."""
id: str
name: str
description: str
data: str = ""
parent_id: Optional[str] = None
access_count: int = 0
last_accessed: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
created_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
updated_at: str = field(
default_factory=lambda: datetime.now(timezone.utc).isoformat()
)
data_token_count: int = 0
def to_dict(self) -> dict:
"""Serialise to a dictionary."""
return {
"id": self.id,
"name": self.name,
"description": self.description,
"data": self.data,
"parent_id": self.parent_id,
"access_count": self.access_count,
"last_accessed": self.last_accessed,
"created_at": self.created_at,
"updated_at": self.updated_at,
"data_token_count": self.data_token_count,
}
def _estimate_tokens(text: str) -> int:
"""Rough token estimate — ~4 chars per token for English text."""
if not text:
return 0
return max(1, len(text) // 4)
# ── Schema ──────────────────────────────────────────────────────────────────
_GRAPH_SCHEMA_SQL = """
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS memory_nodes (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL,
data TEXT NOT NULL DEFAULT '',
parent_id TEXT REFERENCES memory_nodes(id) ON DELETE SET NULL,
access_count INTEGER NOT NULL DEFAULT 0,
last_accessed TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
data_token_count INTEGER NOT NULL DEFAULT 0,
CHECK(parent_id IS NULL OR parent_id != id)
);
CREATE INDEX IF NOT EXISTS idx_nodes_parent ON memory_nodes(parent_id);
CREATE INDEX IF NOT EXISTS idx_nodes_last_accessed ON memory_nodes(last_accessed DESC);
CREATE INDEX IF NOT EXISTS idx_nodes_access_count ON memory_nodes(access_count DESC);
"""
# ── Graph Memory Store ──────────────────────────────────────────────────────
class GraphMemoryStore:
"""
Self-organising node graph for persistent memory.
Backed by SQLite with thread-safe access. Provides three entry points
for fast retrieval: recent nodes, top nodes, and the root node.
"""
def __init__(self, db_path: str) -> None:
from pathlib import Path
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
self.db_path = db_path
self.conn = sqlite3.connect(db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._lock = threading.RLock()
self._init_schema()
self._ensure_root()
# ── Schema & bootstrap ──────────────────────────────────────────────
def _init_schema(self) -> None:
with self._lock:
self.conn.execute("PRAGMA foreign_keys = ON")
self.conn.executescript(_GRAPH_SCHEMA_SQL)
self.conn.commit()
def _ensure_root(self) -> None:
"""Create the root node and the three fixed top-level branches
(User / Directives / World) if they don't exist.
Idempotent: each branch has a stable string id, so re-opening an
existing graph never duplicates them. Branches are also created
on first boot for existing graphs that predate the taxonomy —
this is the migration path.
"""
now = datetime.now(timezone.utc).isoformat()
with self._lock:
row = self.conn.execute(
"SELECT id FROM memory_nodes WHERE parent_id IS NULL LIMIT 1"
).fetchone()
if row is None:
self.conn.execute(
"""INSERT INTO memory_nodes
(id, name, description, data, parent_id,
access_count, last_accessed, created_at, updated_at,
data_token_count)
VALUES (?, ?, ?, ?, NULL, 0, ?, ?, ?, 0)""",
("root", "Root", "Top-level memory node — contains all knowledge domains.", "", now, now, now),
)
self.conn.commit()
debug_log("Created root memory node", "memory")
# Seed fixed top-level branches under root. Each row is
# inserted with INSERT OR IGNORE keyed on the stable id so
# repeated boots are no-ops.
for branch_id, name, description in FIXED_BRANCHES:
self.conn.execute(
"""INSERT OR IGNORE INTO memory_nodes
(id, name, description, data, parent_id,
access_count, last_accessed, created_at, updated_at,
data_token_count)
VALUES (?, ?, ?, '', 'root', 0, ?, ?, ?, 0)""",
(branch_id, name, description, now, now, now),
)
self.conn.commit()
def migrate_legacy_shape(self) -> bool:
"""Wipe the graph if it has a non-conforming (pre-taxonomy) shape.
The purpose-driven taxonomy (root → User / Directives / World)
is a hard reorganisation: pre-existing nodes under root that
don't match this shape would sit invisible to the warm profile
forever.
Rather than carrying them as dead weight, we wipe on daemon
start-up and let the diary re-import repopulate with correctly
classified facts.
Called ONLY from the daemon start-up path — the memory viewer
instantiates ``GraphMemoryStore`` read-mostly and must not
trigger a wipe mid-session.
Non-conforming shape is defined as:
- root has a direct child whose id is not in ``FIXED_BRANCHES``
- OR root's own ``data`` column is non-empty (cold-start writes
that landed on root before the taxonomy existed).
Returns True if a wipe happened, False if the graph was already
in the expected shape.
"""
expected_ids = FIXED_BRANCH_IDS
with self._lock:
root_row = self.conn.execute(
"SELECT data FROM memory_nodes WHERE id = 'root'"
).fetchone()
root_has_data = bool(root_row and (root_row["data"] or "").strip())
rogue_child = self.conn.execute(
"SELECT id FROM memory_nodes "
"WHERE parent_id = 'root' AND id NOT IN ({}) LIMIT 1".format(
",".join("?" * len(expected_ids))
),
tuple(expected_ids),
).fetchone()
if not root_has_data and rogue_child is None:
return False
reason = (
"root holds pre-taxonomy data"
if root_has_data
else f"found non-conforming root child: {rogue_child['id']!r}"
)
debug_log(
f"wiping knowledge graph ({reason}); will re-seed fixed branches",
"memory",
)
self.conn.execute("DELETE FROM memory_nodes")
self.conn.commit()
# Re-seed root + fixed branches from scratch.
self._ensure_root()
return True
# ── CRUD ────────────────────────────────────────────────────────────
def get_node(self, node_id: str) -> Optional[MemoryNode]:
"""Fetch a single node by ID."""
with self._lock:
row = self.conn.execute(
"SELECT * FROM memory_nodes WHERE id = ?", (node_id,)
).fetchone()
if row is None:
return None
return self._row_to_node(row)
def get_children(self, node_id: str) -> list[MemoryNode]:
"""Get all direct children of a node, ordered by decayed access score."""
score = _decay_score_sql()
with self._lock:
rows = self.conn.execute(
f"SELECT * FROM memory_nodes WHERE parent_id = ? ORDER BY {score} DESC",
(node_id,),
).fetchall()
return [self._row_to_node(r) for r in rows]
def get_root(self) -> MemoryNode:
"""Return the root node."""
with self._lock:
row = self.conn.execute(
"SELECT * FROM memory_nodes WHERE parent_id IS NULL LIMIT 1"
).fetchone()
return self._row_to_node(row)
def _resolve_branch(self, node_id: Optional[str]) -> Optional[str]:
"""Walk parents from ``node_id`` up to find the FIXED_BRANCH id it
belongs to (or itself, if the node IS a fixed branch). Returns
``None`` for the root or when the node cannot be located.
Capped at ``MAX_TRAVERSAL_DEPTH`` so a corrupt parent cycle cannot
spin the loop. SQLite reads only — safe to call from write paths.
"""
if not node_id or node_id == "root":
return None
if node_id in FIXED_BRANCH_IDS:
return node_id
current = node_id
for _ in range(MAX_TRAVERSAL_DEPTH):
row = self.conn.execute(
"SELECT parent_id FROM memory_nodes WHERE id = ?", (current,)
).fetchone()
if row is None:
return None
parent = row["parent_id"]
if parent is None or parent == "root":
return None
if parent in FIXED_BRANCH_IDS:
return parent
current = parent
return None
def create_node(
self,
name: str,
description: str,
data: str = "",
parent_id: Optional[str] = None,
) -> MemoryNode:
"""Create a new node and return it.
Raises ValueError if parent_id references a non-existent node.
"""
if parent_id is not None:
parent = self.get_node(parent_id)
if parent is None:
raise ValueError(f"Parent node '{parent_id}' does not exist")
# Enforce description length limit from spec
if len(description) > SUMMARY_MAX_LENGTH:
description = description[:SUMMARY_MAX_LENGTH]
node_id = str(uuid.uuid4())
now = datetime.now(timezone.utc).isoformat()
token_count = _estimate_tokens(data)
with self._lock:
self.conn.execute(
"""INSERT INTO memory_nodes
(id, name, description, data, parent_id,
access_count, last_accessed, created_at, updated_at,
data_token_count)
VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)""",
(node_id, name, description, data, parent_id, now, now, now, token_count),
)
self.conn.commit()
debug_log(f"Created memory node '{name}' ({node_id[:8]})", "memory")
_notify_graph_mutation("create", node_id, self._resolve_branch(parent_id))
return MemoryNode(
id=node_id,
name=name,
description=description,
data=data,
parent_id=parent_id,
access_count=0,
last_accessed=now,
created_at=now,
updated_at=now,
data_token_count=token_count,
)
def update_node(
self,
node_id: str,
*,
name: Optional[str] = None,
description: Optional[str] = None,
data: Optional[str] = None,
parent_id: Optional[str] = ..., # type: ignore[assignment]
) -> Optional[MemoryNode]:
"""Update fields on an existing node. Returns the updated node."""
node = self.get_node(node_id)
if node is None:
return None
now = datetime.now(timezone.utc).isoformat()
if name is not None:
node.name = name
if description is not None:
if len(description) > SUMMARY_MAX_LENGTH:
description = description[:SUMMARY_MAX_LENGTH]
node.description = description
if data is not None:
node.data = data
node.data_token_count = _estimate_tokens(data)
if parent_id is not ...:
node.parent_id = parent_id
node.updated_at = now
with self._lock:
self.conn.execute(
"""UPDATE memory_nodes
SET name = ?, description = ?, data = ?, parent_id = ?,
updated_at = ?, data_token_count = ?
WHERE id = ?""",
(node.name, node.description, node.data, node.parent_id,
node.updated_at, node.data_token_count, node_id),
)
self.conn.commit()
_notify_graph_mutation("update", node_id, self._resolve_branch(node_id))
return node
def delete_node(self, node_id: str) -> bool:
"""Delete a node. Children are orphaned (parent_id set to NULL by FK).
Root and the seeded fixed branches (see ``FIXED_BRANCHES``) are
non-deletable — the warm profile and extractor routing rely on
their stable presence (graph.spec.md §"Fixed Top-Level Branches").
"""
if node_id == "root" or node_id in FIXED_BRANCH_IDS:
return False
# Resolve branch BEFORE the delete so listeners get a meaningful
# branch attribution even though the row is about to vanish.
branch = self._resolve_branch(node_id)
with self._lock:
cur = self.conn.execute(
"DELETE FROM memory_nodes WHERE id = ?", (node_id,)
)
self.conn.commit()
deleted = cur.rowcount > 0
if deleted:
_notify_graph_mutation("delete", node_id, branch)
return deleted
def node_contains_fact(self, node_id: str, fact: str) -> bool:
"""True if ``fact`` matches any line of the node's data after
``normalise_fact`` folding. Used to dedupe graph appends when the
cumulative daily summary re-seeds the same facts across diary flushes.
"""
node = self.get_node(node_id)
if node is None or not node.data:
return False
target = normalise_fact(fact)
if not target:
return False
for line in node.data.split("\n"):
if normalise_fact(line) == target:
return True
return False
def append_to_node(self, node_id: str, text: str) -> bool:
"""Append text to a node's data field.
Returns True if the node's data_token_count now exceeds SPLIT_THRESHOLD.
"""
node = self.get_node(node_id)
if node is None:
return False
separator = "\n" if node.data else ""
new_data = node.data + separator + text
self.update_node(node_id, data=new_data)
updated = self.get_node(node_id)
return updated is not None and updated.data_token_count > SPLIT_THRESHOLD
def touch_node(self, node_id: str) -> None:
"""Increment access_count and update last_accessed."""
now = datetime.now(timezone.utc).isoformat()
with self._lock:
self.conn.execute(
"""UPDATE memory_nodes
SET access_count = access_count + 1, last_accessed = ?
WHERE id = ?""",
(now, node_id),
)
self.conn.commit()
# ── Entry points ────────────────────────────────────────────────────
def get_recent_nodes(self, limit: int = RECENT_NODES_COUNT) -> list[MemoryNode]:
"""Get the most recently accessed nodes."""
with self._lock:
rows = self.conn.execute(
"""SELECT * FROM memory_nodes
WHERE id != 'root'
ORDER BY last_accessed DESC
LIMIT ?""",
(limit,),
).fetchall()
return [self._row_to_node(r) for r in rows]
def get_top_nodes(
self,
limit: int = TOP_NODES_COUNT,
window_days: int = TOP_NODES_WINDOW_DAYS,
) -> list[MemoryNode]:
"""Get nodes with the highest time-decayed access score.
Uses hyperbolic decay so frequently accessed nodes that haven't
been touched in a while naturally fall off without needing a hard
window cutoff. The ``window_days`` parameter is kept for backward
compatibility but is no longer used for filtering.
"""
score = _decay_score_sql()
with self._lock:
rows = self.conn.execute(
f"""SELECT * FROM memory_nodes
WHERE id != 'root'
ORDER BY {score} DESC
LIMIT ?""",
(limit,),
).fetchall()
return [self._row_to_node(r) for r in rows]
# ── Tree queries ────────────────────────────────────────────────────
def get_subtree(self, node_id: str, max_depth: int = 3) -> dict:
"""
Return a nested dict representing the subtree rooted at node_id.
Each dict has keys: node (MemoryNode.to_dict()) and children (list of subtrees).
Useful for the tree sidebar in the UI.
"""
node = self.get_node(node_id)
if node is None:
return {}
def _build(nid: str, depth: int) -> dict:
n = self.get_node(nid)
if n is None:
return {}
children = []
if depth < max_depth:
for child in self.get_children(nid):
children.append(_build(child.id, depth + 1))
return {"node": n.to_dict(), "children": children}
return _build(node_id, 0)
def get_ancestors(self, node_id: str) -> list[MemoryNode]:
"""Return the path from root to this node (inclusive), root first."""
ancestors: list[MemoryNode] = []
visited: set[str] = set()
current = self.get_node(node_id)
while current is not None:
if current.id in visited or len(ancestors) > MAX_TRAVERSAL_DEPTH:
debug_log(f"Cycle or depth limit hit in get_ancestors for {node_id}", "memory")
break
visited.add(current.id)
ancestors.append(current)
if current.parent_id is None:
break
current = self.get_node(current.parent_id)
ancestors.reverse()
return ancestors
def get_all_nodes(self) -> list[MemoryNode]:
"""Return all nodes — use with care on large graphs."""
score = _decay_score_sql()
with self._lock:
rows = self.conn.execute(
f"SELECT * FROM memory_nodes ORDER BY {score} DESC"
).fetchall()
return [self._row_to_node(r) for r in rows]
def get_node_count(self) -> int:
"""Return total number of nodes in the graph."""
with self._lock:
row = self.conn.execute("SELECT COUNT(*) as cnt FROM memory_nodes").fetchone()
return row["cnt"]
def get_total_tokens(self) -> int:
"""Return total data tokens across all nodes. Zero means no knowledge stored."""
with self._lock:
row = self.conn.execute(
"SELECT COALESCE(SUM(data_token_count), 0) as total FROM memory_nodes"
).fetchone()
return int(row["total"])
# ── Search ─────────────────────────────────────────────────────────
def search_nodes(self, query: str, limit: int = 10) -> list[MemoryNode]:
"""Search nodes by keyword match across name, description, and data.
Uses case-insensitive LIKE matching on each keyword (split by whitespace).
Scoring weights: name/description matches are worth 3× data matches, so
specific nodes about a topic rank above broad category nodes that merely
contain the keyword somewhere in their data blob.
Excludes the root node from results and touches matched nodes.
"""
keywords = [k.strip() for k in query.split() if k.strip()]
if not keywords:
return []
# Build a score expression: name/description matches worth 3, data worth 1
score_parts: list[str] = []
params: list[str] = []
for kw in keywords:
# Escape LIKE wildcards so literal %, _, \ are matched exactly
escaped = kw.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
pattern = f"%{escaped}%"
score_parts.append(
"(CASE WHEN name LIKE ? ESCAPE '\\' THEN 3 ELSE 0 END"
" + CASE WHEN description LIKE ? ESCAPE '\\' THEN 3 ELSE 0 END"
" + CASE WHEN data LIKE ? ESCAPE '\\' THEN 1 ELSE 0 END)"
)
params.extend([pattern, pattern, pattern])
score_expr = " + ".join(score_parts)
# Use a subquery to avoid duplicating the score expression (and its bindings)
sql = f"""
SELECT * FROM (
SELECT *, ({score_expr}) AS relevance
FROM memory_nodes
WHERE id != 'root'
) WHERE relevance > 0
ORDER BY relevance DESC, {_decay_score_sql()} DESC
LIMIT ?
"""
params.append(str(limit))
with self._lock:
rows = self.conn.execute(sql, params).fetchall()
nodes = [self._row_to_node(r) for r in rows]
# Touch matched nodes (updates access tracking)
for node in nodes:
self.touch_node(node.id)
debug_log(f"Graph search for '{query}' found {len(nodes)} nodes", "memory")
return nodes
def find_node_by_name(self, name: str, parent_id: Optional[str] = None) -> Optional[MemoryNode]:
"""Find a node by exact name match (case-insensitive), optionally under a specific parent."""
with self._lock:
if parent_id is not None:
row = self.conn.execute(
"SELECT * FROM memory_nodes WHERE LOWER(name) = LOWER(?) AND parent_id = ? LIMIT 1",
(name, parent_id),
).fetchone()
else:
row = self.conn.execute(
"SELECT * FROM memory_nodes WHERE LOWER(name) = LOWER(?) AND id != 'root' LIMIT 1",
(name,),
).fetchone()
if row is None:
return None
return self._row_to_node(row)
# ── Graph edges for visualisation ───────────────────────────────────
def get_graph_data(self, root_id: str = "root", max_depth: int = 4) -> dict:
"""
Return nodes and edges suitable for graph visualisation.
Returns:
{"nodes": [...], "edges": [...]}
Each node: {id, name, description, data_token_count, access_count,
last_accessed, parent_id, has_children, depth}
Each edge: {source, target}
"""
nodes_out: list[dict] = []
edges_out: list[dict] = []
visited: set[str] = set()
def _walk(nid: str, depth: int) -> None:
if nid in visited or depth > max_depth:
return
visited.add(nid)
node = self.get_node(nid)
if node is None:
return
children = self.get_children(nid)
nodes_out.append({
"id": node.id,
"name": node.name,
"description": node.description,
"data_token_count": node.data_token_count,
"access_count": node.access_count,
"last_accessed": node.last_accessed,
"parent_id": node.parent_id,
"has_children": len(children) > 0,
"depth": depth,
})
for child in children:
edges_out.append({"source": nid, "target": child.id})
_walk(child.id, depth + 1)
_walk(root_id, 0)
return {"nodes": nodes_out, "edges": edges_out}
# ── Internal helpers ────────────────────────────────────────────────
@staticmethod
def _row_to_node(row: sqlite3.Row) -> MemoryNode:
return MemoryNode(
id=row["id"],
name=row["name"],
description=row["description"],
data=row["data"],
parent_id=row["parent_id"],
access_count=row["access_count"],
last_accessed=row["last_accessed"],
created_at=row["created_at"],
updated_at=row["updated_at"],
data_token_count=row["data_token_count"],
)
def close(self) -> None:
"""Close the database connection."""
try:
with self._lock:
self.conn.close()
except Exception:
pass

View File

@@ -0,0 +1,256 @@
# Knowledge Graph Specification
## Overview
A self-organising node graph that stores the assistant's accumulated world knowledge — anything learned during conversations that it wouldn't already know from training data. This includes user-specific facts, real-world discoveries (opening hours, local businesses), practical knowledge (recipes, solutions), and current events. The diary records *what happened*; the knowledge graph records *what was learned*.
The graph dynamically structures knowledge by topic relevance using a hierarchical tree where nodes auto-split when they grow too large. Three fast-access entry points — **recent nodes**, **top nodes**, and **root node** — ensure the most relevant knowledge is always reachable without exhaustive search.
## Fixed Top-Level Branches
On first bootstrap the graph seeds three non-deletable branches under root, defined in `FIXED_BRANCHES` in `graph.py`:
| Branch ID | Name | Purpose |
|-----------|------|---------|
| `user` | User | Everything about the user: identity, location, tastes, habits, history |
| `directives` | Directives | Imperatives the user issued at the assistant: reply style, tone rules, standing instructions |
| `world` | World | External facts the assistant has learned: discoveries, practical knowledge, current events |
These branches are created idempotently via `INSERT OR IGNORE` on stable IDs. The structure is intentionally shallow and purpose-driven — splits deepen each subtree over time, but the top layer stays fixed so the **warm profile** (see below) has a stable shape.
No Other branch: the extractor defaults unknown classifications to `user`. A fact that genuinely belongs nowhere should not be stored.
### Legacy-Shape Migration (destructive)
`GraphMemoryStore.migrate_legacy_shape()` checks the on-disk graph against the expected shape at daemon start-up. The graph is considered non-conforming if root has any direct child that isn't one of the fixed branches, or if root's own `data` column is non-empty (cold-start writes that landed on root before the taxonomy existed). In either case the entire `memory_nodes` table is wiped and root + the three fixed branches are re-seeded.
Why destructive: pre-taxonomy nodes sitting under root would remain invisible to the warm profile forever. Carrying them as dead weight is worse than a clean slate. The diary is untouched, so users can re-populate via "Import from Diary" in the memory viewer once the wipe completes. Knowledge nodes are in beta — the structure and classification are now stable but the extractor quality is still being tuned.
Called **only** from the daemon start-up path in `daemon.main()`. The memory viewer and reply engine instantiate `GraphMemoryStore` without triggering the migration, so a mid-session open never wipes anything.
### Branch-Pinned Traversal
`find_best_node(..., branch_root_id=...)` skips the recent/top entry points and descends from the given branch root only. This prevents cross-branch contamination when routing extracted facts: a User fact cannot land in the World subtree just because a World node was recently touched.
## Warm Profile
`build_warm_profile(store, *, user_max_chars, directives_max_chars)` returns a `{"user": "...", "directives": "..."}` dict by walking the User and Directives subtrees breadth-first (ordered by each sibling's decayed access score) and concatenating node data up to the char caps. `format_warm_profile_block(profile)` renders it as a labelled system-prompt section using denial-template mirroring (see CLAUDE.md): the headings literally occupy the semantic slot that small-model canonical denials refer to ("INFORMATION THE USER HAS SHARED IN PRIOR CONVERSATIONS", "STANDING INSTRUCTIONS FROM THE USER").
The warm profile is injected into every reply's initial system message (see `reply/engine.py` Step 3.5) unconditionally and query-agnostically — personalisation is the default, not something gated behind a question-detection heuristic. No LLM call is involved in composition; it's a pure SQLite read.
## Data Model
### MemoryNode
| Field | Type | Description |
|-------|------|-------------|
| `id` | UUID string | Unique identifier (root node has id `"root"`) |
| `name` | string | Human-readable label |
| `description` | string | 1-2 sentences used by traversal to decide which branch to explore |
| `data` | string | The actual memories held at this node |
| `parent_id` | UUID or null | Back-reference (null for root) |
| `access_count` | int | Total accesses (for top-nodes ranking) |
| `last_accessed` | ISO 8601 | For recent-nodes ranking |
| `created_at` | ISO 8601 | When the node was created |
| `updated_at` | ISO 8601 | Last modification time |
| `data_token_count` | int | Cached token estimate (len/4 heuristic) |
### Storage
SQLite table `memory_nodes` in the same database as the diary system. Schema is initialised automatically on first access. The root node is created if absent.
### Entry Points
| Entry Point | Query | Purpose |
|-------------|-------|---------|
| Recent nodes | Last N accessed (excl. root) | Fast path for ongoing conversations |
| Top nodes | Highest decayed access score (excl. root) | Core knowledge domains |
| Root node | Single root | Full graph traversal for novel queries |
## Core Operations
### Create
New nodes are created with a name, description, optional data, and a parent_id (defaults to root). Token count is computed on creation.
### Read
Nodes can be fetched individually, as children of a parent, as a subtree (nested dict), or as graph data (flat nodes + edges for visualisation).
### Update
Any combination of name, description, and data can be updated. Token count is recomputed when data changes. `updated_at` is always refreshed.
### Delete
Any node except root can be deleted. Children are orphaned (parent_id set to NULL via FK). The UI should warn before deleting nodes with children.
### Touch
Increments `access_count` and updates `last_accessed`. Called automatically when a node is viewed in the UI or retrieved during query traversal.
### Mutation Listeners
The graph module exposes a small observer registry, `register_graph_mutation_listener(cb)` / `unregister_graph_mutation_listener(cb)`, invoked after every successful `create_node`, `update_node`, `delete_node`, and (transitively) `append_to_node`. Callbacks receive `action`, `node_id`, and `branch` (the FIXED_BRANCH ancestor id, or `None` for root-level mutations and unresolvable nodes). Listener exceptions are logged via `debug_log` and swallowed so they cannot break a write.
Touch is intentionally NOT a mutation event: it changes access metadata only, not the warm-profile-relevant fields, so it does not need to invalidate caches.
The reply layer uses this hook from `daemon.py` to invalidate `DialogueMemory`'s warm-profile cache when the User or Directives branches change mid-conversation. World-branch writes are filtered out because the warm profile does not include the world branch.
### Access Decay
All ordering by access frequency uses a **time-decayed score** computed at query time: `access_count / (1 + age_days / half_life)`. This is hyperbolic decay — a node's effective score halves every `DECAY_HALF_LIFE_DAYS` (default 14) since its last access. The raw `access_count` is never modified, so changing the half-life retroactively reweights all nodes. This applies to `get_top_nodes`, `get_children`, `get_all_nodes`, and `search_nodes` tie-breaking.
### Search
- **search_nodes(query, limit)** — Keyword search across name, description, and data fields. Case-insensitive LIKE matching; nodes matching more keywords rank higher. Excludes root. Touches matched nodes for access tracking.
- **find_node_by_name(name, parent_id)** — Exact name match (case-insensitive), optionally scoped to a parent node. Excludes root when no parent specified.
## Tree & Graph Queries
- **get_subtree(node_id, max_depth)** — Nested dict for tree sidebar
- **get_ancestors(node_id)** — Path from root to node (breadcrumb)
- **get_graph_data(root_id, max_depth)** — Flat {nodes, edges} for canvas rendering. Each node includes depth and has_children flags.
## Auto-Split (Natural Reduction)
Triggered automatically when `data_token_count > SPLIT_THRESHOLD` (1500 tokens) after a write. Auto-split is the system's primary consolidation and pruning mechanism — it's where temporal events get distilled into patterns, common knowledge gets dropped, and the tree structure deepens organically.
1. LLM analyses the node's data and proposes 2-5 child categories
2. Each fact is assigned to exactly one child
3. **Consolidation**: duplicate facts are merged, and repeated similar activities across different dates are consolidated into patterns (e.g. "ate sushi on Mon, ate sushi on Thu" → "regularly eats sushi"). Date context is preserved only for significant events.
4. **Pruning**: facts that the LLM already knows from its training data are dropped. This keeps the graph as a delta from the model's baseline knowledge. When migrating to a newer model with broader training data, subsequent splits will naturally prune more — reducing the graph's memory footprint over time.
5. Child nodes are created under the split node
6. Parent data is cleared; parent description updated to a summary
This means the tree depth itself encodes a raw→refined spectrum: surface-level nodes hold recently ingested knowledge, deeper nodes hold distilled novel knowledge that survived multiple split cycles. Model upgrades naturally shrink the graph as previously-novel facts become common knowledge.
Split quality safeguards:
- Minimum 2 categories required (abort if LLM proposes fewer)
- Each category must have at least one fact
- If the split fails (LLM error, bad JSON), the node retains its data and the next write retries
## Auto-Merge (Future — requires LLM integration)
When all children collectively hold < MERGE_THRESHOLD (200 tokens):
1. Collapse children's data back into parent
2. Delete child nodes
3. Update parent description
4. Cascade summaries upward
## Housekeeping (Future)
Periodic process that:
- Promotes buried-but-hot nodes (high access, depth > 3)
- Compresses cold branches (no access in > Y days)
- Merges sparse subtrees
- Validates parent summaries
## LLM Integration
The graph memory system is fully automatic — no tool calls required. It integrates at two points in the existing pipeline.
### Automatic Writes (via `graph_ops.py`)
Piggybacks on the existing diary update flow in `conversation.py`:
1. After a successful diary update, the conversation summary is passed to `update_graph_from_dialogue()`
2. **Extract + classify**: LLM extracts novel knowledge from the summary and classifies each fact into one of the three fixed branches (`USER` / `DIRECTIVES` / `WORLD`). Output is a JSON list of `{"branch": "...", "fact": "..."}` objects. Rough routing heuristic baked into the prompt: if the user is *telling the assistant how to behave* → DIRECTIVES; if the user is *telling the assistant about themselves* → USER; if the assistant *discovered a fact about the world* → WORLD. Unknown branches default to USER. Requests are reframed as knowledge ("user asked about CEX hours" → "CEX Kensington closes at 6pm on Sundays"). Patterns and consolidation emerge through auto-split.
3. **Traverse**: Each fact is placed in the best-fitting node using branch-pinned descent from its tagged branch root (recent/top shortcuts are skipped so cross-branch contamination is impossible):
- **Recent nodes** — checked first; follows conversational momentum
- **Top nodes** — checked second; matches frequently accessed knowledge domains
- **Root traversal** — greedy top-down descent; LLM picks the best child at each level, or stops at the current node if none fit
- **Picker model**: `update_graph_from_dialogue` / `find_best_node` / `_llm_pick_best_child` accept an optional `picker_model` override. Callers (daemon, memory viewer's diary-import endpoint) resolve it via `resolve_tool_router_model(cfg)` so the best-child classification runs on the small warm router model instead of the big chat model. When `picker_model` is `None` the picker falls back to `ollama_chat_model`.
4. **Dedupe (fast-path)**: Before any LLM call, `GraphMemoryStore.node_contains_fact` compares the fact against each line of the chosen node's data under Unicode-aware folding (`unicodedata.NFKC` + `str.casefold` + whitespace collapse), so ASCII casing, locale quirks (Turkish `İ`/`ı`, German `ß`/`ss`), and incidental whitespace don't cause false negatives. Exact matches are skipped, **not** reported as newly learned, and do **not** touch the node's access score (a re-extraction isn't fresh reinforcement). The merge step below would also collapse re-extractions, but cumulative daily summaries re-emit the same lines often enough that catching them with a cheap SQL read avoids a flood of small-model calls — semantically equivalent, just faster. Skips are still counted: `update_graph_from_dialogue` returns a `GraphUpdateResult(stored, skipped)` so the CLI can log "nothing new (N duplicates skipped)" on all-duplicate flushes; silencing that line would make the memory pipeline look broken. The check only covers the picker's chosen node, so a later flush that routes the same fact to a different node within the branch can still leak through — caught by the merge step on that node instead.
5. **Merge** (batched per node): `merge_node_data(store, node_id, new_facts: list[str], ...)` sends the existing node data + **all** new facts routed to that node in this flush to the picker model and asks it to produce a clean, consolidated, contradiction-free fact list, which is written back as the node's full `data`. The orchestrator groups the flush by `node_id` first so a 5-fact flush against the User node fires **one** rewrite that incorporates all five facts, not five separate rewrites of the same `data`. The call returns a `MergeResult(success: bool, incorporated_indices: list[int])` so the orchestrator can report only the facts that actually survived as new lines (consolidated-out facts aren't claimed as "newly stored"). One LLM call subsumes four behaviours: (a) **supersession** — contradictions, negations, and same-attribute updates drop the old line ("user does not need a daily check-in" replaces both "user has a need for a daily check-in" and the same need framed as an interest); (b) **near-duplicate dedupe** — different wordings of the same fact collapse to one canonical phrasing; (c) **consolidation** — repeated daily activities fold into patterns ("ate sushi on Monday", "ate sushi on Thursday" → "regularly eats sushi"); (d) **meta-narrative pruning** — lines that narrate the assistant's own behaviour, capabilities, or denials ("The assistant is unable to navigate to a web page", "The assistant suggested grilled salmon") are extractor artefacts from earlier prompt versions and get dropped. Counterpart to the extractor's BANNED FACT FORMS list: the extractor blocks them at write-time, the merge prompt scrubs the historical leftovers that a `consolidate-all` sweep can then surface. Genuine user-issued imperatives ("Always reply in British English") are not meta-narrative and survive. Independent facts coexist (a "user ate a Big Mac" line does not silently drop "user is vegetarian"; the contradiction stays visible). Because the latest prompt always rewrites the whole node, updated conventions propagate to old data without a separate migration. **Hallucination guard**: the rewrite is rejected if it returns more lines than `len(existing) + len(new) + 2` — a runaway model can't quietly inflate the node. Fail-open: empty/cold node, LLM error, parse failure, oversized rewrite, or an empty rewrite all fall back to plain `append_to_node` for each new fact so they still land — a contradiction is recoverable, a silent wipe or hallucinated bloat is not.
6. **Split**: If the merge or fallback append pushes the node past `SPLIT_THRESHOLD`, auto-split is triggered
Cold start: each fact lands directly on its tagged branch root (User / Directives / World) until enough data accumulates there for the first auto-split. The tree structure emerges organically under each branch.
LLM failure at any step is non-fatal — the diary update still succeeds, and the graph simply misses that cycle.
### Automatic Reads (via enrichment in `engine.py`)
At the start of each reply cycle, the reply engine enriches the system prompt with graph context:
1. **Question-driven**: Graph enrichment runs only when the query generator produced implicit personal questions. Utility queries (time, maths) and queries whose context is already live skip the graph entirely — the knowledge graph is a Q&A index, not a topic index.
2. **Question search**: Questions are joined, stop-worded, and used to find matching nodes (up to 5 results with data previews).
3. Results are injected as "Stored knowledge about the user" — separate from diary history to preserve provenance.
No tool calls needed. The LLM sees relevant graph memories as part of its system context.
Controlled by `memory_enrichment_source` config:
- `"all"` — both diary and graph enrich replies
- `"diary"` — only diary (conversation summaries) used for enrichment
- `"graph"` — only graph (structured knowledge) used for enrichment
Default is `"all"` — both channels enrich replies. The graph has graduated from alpha to beta with the purpose-driven taxonomy and warm profile now always-on, so the default flipped from `"diary"` to include graph recall too. Both systems always receive writes regardless of this setting.
Note: the always-on warm profile (User + Directives injected on every turn) is separate from query-driven enrichment. Warm profile covers "who the user is"; enrichment covers "what the user has said/seen about this specific topic". The graph contributes to both.
## Configuration
| Setting | Default | Description |
|---------|---------|-------------|
| `SPLIT_THRESHOLD` | 1500 | Tokens before auto-split |
| `MERGE_THRESHOLD` | 200 | Tokens below which children collapse |
| `RECENT_NODES_COUNT` | 10 | Recent nodes to surface |
| `TOP_NODES_COUNT` | 15 | Top nodes to surface |
| `TOP_NODES_WINDOW_DAYS` | 30 | Legacy — kept for API compat, no longer used for filtering |
| `DECAY_HALF_LIFE_DAYS` | 14 | Days until a node's access score halves |
| `MAX_TRAVERSAL_DEPTH` | 8 | Safety limit on graph traversal |
| `SUMMARY_MAX_LENGTH` | 300 | Max chars for node description |
| `memory_enrichment_source` | `"all"` | Which system enriches replies: `"all"`, `"diary"`, or `"graph"` |
## UI: Memory Viewer Integration
The graph explorer appears as the **Knowledge** tab in the memory viewer, positioned between the Diary and Meals tabs.
### Three-Panel Layout
1. **Left sidebar — Tree navigator**: Collapsible tree showing the full hierarchy. Clicking a node selects it in both the tree and the graph canvas. Shows child count badges.
2. **Centre — Graph canvas**: Interactive HTML5 Canvas with radial tree layout. Supports pan (drag), zoom (scroll wheel), and click-to-select. Toolbar provides zoom in/out, fit-to-view, add-node, and import-from-diary actions. Node size reflects access count. Selected node is highlighted with accent glow.
3. **Right sidebar — Node detail**: Shows breadcrumb path, name, description, metadata (accesses, tokens, last seen, children count), stored data, children list, and action buttons (edit, add child, delete).
### API Endpoints
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/graph/nodes` | Graph data (nodes + edges) for canvas |
| GET | `/api/graph/tree` | Nested tree structure for sidebar |
| GET | `/api/graph/node/<id>` | Single node + children + ancestors |
| POST | `/api/graph/node` | Create new node |
| PUT | `/api/graph/node/<id>` | Update node fields |
| DELETE | `/api/graph/node/<id>` | Delete node (not root) |
| GET | `/api/graph/recent` | Recently accessed nodes |
| GET | `/api/graph/top` | Most frequently accessed nodes |
| GET | `/api/graph/stats` | Node count and total data tokens (`total_tokens = 0` means the graph holds no knowledge) |
| POST | `/api/graph/import-diary` | Import all diary summaries into graph (streaming NDJSON) |
| POST | `/api/graph/consolidate-all` | Self-consolidate every populated node (streaming NDJSON) — runs the merge LLM with no new facts on each node so updated conventions and supersession rules apply to historical data |
### Import from Diary
The graph toolbar includes an "Import from Diary" button (📥) that bootstraps the graph with existing diary data. This is a one-time migration path so users don't lose their accumulated memories when switching from diary-only to graph enrichment.
The endpoint streams NDJSON progress events (`start`, `progress`, `complete`, `error`) so the UI shows real-time feedback. Each diary summary is processed through the standard `update_graph_from_dialogue()` pipeline (extract → traverse → append → split). Failures on individual summaries are non-fatal — the import continues with the remaining entries.
### Consolidate All (🧹)
The toolbar's 🧹 button walks every populated node and calls `merge_node_data` with an empty `new_facts` list, prompting the picker model to re-apply the latest supersession/dedupe/consolidation rules to data that landed before those rules existed (or before the prompt was tightened). Like Import from Diary, it streams NDJSON progress events. Per-node failures are non-fatal so a single bad node can't abort the sweep. The UI confirms before starting and reports the total line-count delta on completion.
## Relationship to Existing Systems
The graph memory system lives alongside the existing diary system (conversation_summaries + FTS + vector search). It shares the same SQLite database but uses its own table. The diary system remains the primary memory system for now; the graph is a v2 system being built in parallel.
Users can import existing diary data into the graph via the "Import from Diary" button in the Memory Viewer. This processes all historical summaries through the extract-and-place pipeline, building the graph structure organically.
### Diary Summariser Hygiene
Graph extraction ingests diary summaries, so the graph inherits whatever corruption the summary contains. Summariser hygiene rules (no deflection narration, attribution preservation, topic separation) are documented in [`summariser.spec.md`](summariser.spec.md).
## Privacy
All data is stored locally in the user's SQLite database. No data leaves the device. The graph store has no network dependencies.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,96 @@
"""Cheap heuristic for deciding whether long-term memory enrichment (diary
recall, graph recall, memory digest) is worth running for the current query.
When the hot-window transcript already covers the topic (same content words
*and* a fresh tool result is present), running the diary/graph hops adds cost
and context bloat for no new information. Fail open: if in doubt, recall.
No LLM hop — keyword Jaccard + tool-row presence is deterministic and cheap.
"""
from __future__ import annotations
import re
from typing import List
from ..debug import debug_log
from ..utils.redact import redact
_STOPWORDS = {
"a", "an", "the", "and", "or", "but", "if", "then", "is", "are", "was",
"were", "be", "been", "being", "do", "does", "did", "have", "has", "had",
"of", "in", "on", "at", "to", "for", "with", "by", "from", "about",
"what", "who", "where", "when", "why", "how", "which", "whose",
"it", "this", "that", "these", "those", "his", "her", "their", "my",
"your", "our", "me", "you", "i", "we", "they", "he", "she", "them",
"can", "could", "would", "should", "will", "may", "might", "shall",
"tell", "show", "give", "find", "know", "think", "want", "need", "get",
"so", "too", "more", "less", "some", "any", "no", "not", "also", "just",
"as", "than", "up", "out", "over", "under", "again", "further", "here",
"there", "all", "most", "other", "such", "own", "same", "very", "s",
"t", "don", "now", "ll", "m", "re", "ve", "d",
}
def _content_words(text: str) -> set[str]:
# \w with UNICODE (default in Py3) matches letters in any script —
# Latin, Cyrillic, CJK, Arabic, Hebrew, etc. Keeps Jarvis language-agnostic
# per CLAUDE.md. Digit-only runs are excluded by the stopword-style filter.
words = re.findall(r"\w{3,}", (text or "").lower(), flags=re.UNICODE)
return {w for w in words if w not in _STOPWORDS and not w.isdigit()}
def _has_fresh_tool_result(recent_messages: List[dict]) -> bool:
from .conversation import is_tool_message
return any(is_tool_message(m) for m in recent_messages)
def should_recall(
query: str,
recent_messages: List[dict],
*,
min_coverage: float = 0.5,
) -> bool:
"""Return True iff diary/graph recall should run for this query.
False only when:
1. Hot-window contains at least one fresh tool result, AND
2. At least `min_coverage` fraction of the query's content words
appear in the combined hot-window text (coverage, not symmetric
Jaccard — the window is always larger than the query).
Fail-open: any exception or missing data → True.
"""
try:
if not recent_messages:
return True
if not _has_fresh_tool_result(recent_messages):
return True
q_words = _content_words(query)
if not q_words:
# Stopword-only query cannot justify skipping recall.
return True
window_text_parts: list[str] = []
for m in recent_messages:
c = m.get("content")
if isinstance(c, str) and c:
window_text_parts.append(c)
window_words = _content_words(" ".join(window_text_parts))
if not window_words:
return True
overlap = q_words & window_words
coverage = len(overlap) / len(q_words) if q_words else 0.0
if coverage >= min_coverage:
# Overlap words come from the user query and may carry names or
# PII; push them through the structural scrub before logging so
# debug logs don't become a side-channel.
safe_overlap = redact(" ".join(sorted(overlap)[:5]))
debug_log(
f"recall gate: skip (coverage={coverage:.2f}, overlap=[{safe_overlap}])",
"memory",
)
return False
return True
except Exception as e:
debug_log(f"recall gate failed open: {e}", "memory")
return True

View File

@@ -0,0 +1,48 @@
# Recall Gate
A deterministic, no-LLM heuristic that lets the reply engine skip diary, graph and memory-digest enrichment when the hot window already grounds the user's follow-up.
The gate is a cheap pre-flight check, not a routing decision. It either tells the engine "keep going as planned" (recall) or "the hot window has this covered, you can short-circuit enrichment" (skip).
## Scope
- File: `src/jarvis/memory/recall_gate.py`.
- Caller: `run_reply_engine` in `src/jarvis/reply/engine.py`, between the planner's `needs_memory` decision and the diary/graph search.
- Inputs: the redacted user query, the recent dialogue messages (already including tool-carryover rows from prior replies in the hot window).
- Output: `True` to recall, `False` to skip.
## When the gate runs
The gate runs only when:
1. The planner did **not** explicitly emit a `searchMemory` step. An explicit planner intent always wins; the gate does not second-guess it.
2. There is at least one recent message in the hot window.
When the planner returned an empty plan (fail-open), the gate is allowed to short-circuit. When the planner returned a concrete plan that doesn't include `searchMemory`, the engine is already skipping enrichment, so the gate is a no-op.
## Heuristic
The gate returns `False` (skip enrichment) only if both hold:
1. The hot window contains at least one tool-related message — i.e. an entry for which `is_tool_message()` returns true. This is the freshness signal: a tool was already invoked in this conversation, so grounded data is sitting in the messages array.
2. The query's content words have ≥ 50% overlap with the words in the hot-window transcript. Coverage is asymmetric (`|overlap| / |query_words|`), not Jaccard — long histories shouldn't penalise a short follow-up.
Anything else returns `True`. On any exception the gate fails open with `True`.
## Language-agnostic by construction
Per the project's no-hardcoded-language-patterns rule, content-word extraction uses `re.findall(r"\w{3,}", text, flags=re.UNICODE)`. The unicode flag makes `\w` match Cyrillic, CJK, Arabic, Hebrew, etc.
A small English stopword list (`is`, `the`, `what`, etc.) filters function words before scoring. Non-English queries simply skip stopword filtering — the worst case is a slightly more conservative (i.e. more recall-prone) decision, which is the safe direction for a fail-open gate. Adding language-specific stopword lists is out of scope; the heuristic is intentionally conservative and the cost of recalling unnecessarily is one extractor LLM call, not user-visible failure.
## Privacy
The overlap words can include user-supplied query terms. Before they reach `debug_log`, they are passed through `redact()` so emails, JWTs, and other structurally-detectable secrets in the query don't leak into logs. The gate does not store anything itself.
## Why not have the planner do this?
The planner is an LLM call and runs once per turn regardless. Adding "is the hot window enough?" to its prompt would make every planner call slower and more brittle. The gate is a 1 ms pure-Python pass that only fires after the planner has decided memory might be useful, so it's strictly additive and trivially removable.
## Failure mode
`should_recall()` returns `True` on every exception path. The gate cannot make a turn worse by failing — at most it stops being an optimisation.

View File

@@ -0,0 +1,117 @@
# Diary Summariser Specification
## Overview
The diary summariser (`conversation.py::generate_conversation_summary`) condenses raw conversation chunks into a daily `conversation_summaries` row. That row feeds every downstream memory consumer — direct diary retrieval for enrichment, vector search, FTS, and knowledge-graph extraction. A corrupted summary therefore poisons every consumer, often silently: downstream code has no way to tell that a summary misrepresents what actually happened.
The summariser prompt enforces a fixed set of hygiene rules. Each rule exists because a specific field incident produced corrupted diary entries that misled later sessions. Rules are cumulative — none supersedes another.
The summariser prompt is the only write-time defence. There is no post-process scrub — the prompt is single-source-of-truth, language-agnostic, and improves automatically as the underlying chat model improves. Historical entries written before the prompt was tightened can be cleaned via a user-triggered LLM rewrite (see [LLM Rewrite Sweep](#llm-rewrite-sweep)).
## Core Behaviour
- Input: recent conversation chunks (last 10) plus, if present, the previous summary for the same day.
- Output: a free-form summary (≤ 200 words) and 3–5 comma-separated topic keywords.
- Storage: one row per `(date_utc, source_app)` in `conversation_summaries`, upserted on each update.
- Embedding: the concatenation of summary + topics is embedded and stored for vector retrieval.
- LLM failure is non-fatal — the summariser returns `(None, None)` and the update is skipped entirely. Pending messages remain queued for the next cycle.
## Hygiene Rules
### 1. No deflection narration
The summariser must not record the assistant's own failures, uncertainty, or offers to search. Those events are transient. If preserved, they are retrieved by future sessions as "conversation history" and prime the model to repeat the same deflection pattern.
- If the assistant eventually answered (e.g. after a tool call), record only the final answer.
- If the topic was raised but never resolved, record only the topic and the user's intent — strip every phrase describing the assistant's inability, uncertainty, or offer to help.
### 2. Attribution preservation
Claims the assistant made about third-party entities (films, books, products, people, places, scientific facts) must be attributed in the summary — "the assistant said X" rather than bare "X". The attribution lets downstream readers treat the claim with appropriate scepticism.
- Never paraphrase an attributed claim into an unattributed assertion. Unattributed claims poison enrichment by reading as established fact.
- If the user later corrects the assistant, record both the original claim and the correction. Do not silently replace.
- Tool-grounded data (weather, time, calculator results) and user-stated facts about the user themselves are safe without attribution caveats.
### 3. Topic separation
Unrelated topics must never be welded into one grammatical clause. No shared "and", shared appositive, or shared relative clause across distinct referents. Each topic gets its own sentence.
- A welded clause like "the film X and the character Y, identified as Z" is read by downstream retrievers as a single claim about both referents and silently corrupts future enrichment.
- A dangling appositive attaching to multiple antecedents is the exact failure mode — small models produce it frequently when two topics are raised in one conversation.
## Applicability
All three rules apply in any language, not only English. The prompt states this explicitly because small models otherwise assume the rule is keyed to the English phrases it names.
## LLM Rewrite Sweep
`rewrite_all_diary_summaries(db, ollama_base_url, ollama_chat_model, ...)` is a user-triggered bulk operation that walks every row in `conversation_summaries` and asks the chat model to remove deflection narration from each. It exists for cleaning **historical** poisoning from rows written before the summariser prompt was tightened. There is no equivalent on the write path — new writes rely on the prompt alone.
**Why an LLM rather than regex:** the leak shows up in any language the user speaks, in any phrasing the model invents. A regex set is English-first by definition (you can only enumerate the patterns you can think of) and grows into a whack-a-mole. A small instruction-following model handles the semantic check in one shot, in any language, and improves automatically as the user's chat model upgrades. Mirrors `optimise_diary_topics` in shape and privacy guarantees.
**Prompt contract (`_REWRITE_DEFLECTION_SYSTEM_PROMPT`):**
- Return the entry with EVERY sentence removed whose subject is the assistant and whose verb describes inability, deflection, hesitation, or non-knowledge.
- Keep every other sentence verbatim — no paraphrasing, reordering, translating, or "improving".
- Keep attributed assistant claims ("the assistant said Possessor is a 2020 film") — those carry information.
- Keep user-stated facts and tool-grounded data — those are not assistant failures.
- Output the cleaned text only. Empty string if the entire summary is deflection. Verbatim input if nothing needs removing.
- Applies in every language; do NOT translate the output.
**Untrusted-input fence:** the diary text is wrapped in `<<<BEGIN UNTRUSTED WEB EXTRACT>>>` / `<<<END UNTRUSTED WEB EXTRACT>>>` markers (the same fence used for web-search content) before being passed to the model, so a row containing what looks like instructions is treated as data, not as a directive to follow. The fence markers, if echoed back, are stripped from the response.
**Empty-rewrite guard:** if the model returns an empty string (a row that was *entirely* deflection), the original is kept and a `would_empty: true` flag is surfaced. An empty diary entry is worse than a slightly-leaky one — downstream retrieval treats absence as "no record" and the user loses the topic entirely.
**Privacy:** the sweep streams per-row events as `{date_utc, chars_before, chars_after, rewritten, would_empty, embedding_refreshed, error?}` — counts and booleans only, never raw summary text. The `error` value is the exception class name only (e.g. `"RuntimeError"`), never the stringified exception message, because Python exception messages can echo offending input back to the caller. The progress-event key set is locked behind a whitelist test so any future field addition forces deliberate review (`tests/test_memory_viewer_diary_scrub_api.py::test_progress_event_keys_are_a_known_whitelist`). The diary clean button must not become a data-exfiltration channel through the streaming progress UI.
**Audit trail:** preserves each row's original `ts_utc` on rewrite. A maintenance pass that stomped `ts_utc` would make every cleaned row look as though it had been written today, destroying the only signal users have to verify when each diary entry was actually authored.
**Vector embedding:** when a row is rewritten, the embedding stored alongside the summary is regenerated inline from the cleaned text if the caller passes both an `ollama_base_url` and an `ollama_embed_model`. Without an embed model the rewrite still happens (FTS stays consistent via SQLite triggers); the vector embedding stays anchored to the pre-rewrite text until the next user-driven write to that date. Per-row embedding refresh is best-effort: an embedding-service failure is logged but does not roll back the summary write.
**Fail-open at every layer:**
- LLM call failure on a row → row is left untouched and reported with `error` set to the exception class name.
- Empty rewrite → row is left untouched, `would_empty: true` surfaced.
- Per-row write failure → row is reported with `error`, the sweep continues.
**Cache invariant:** diary content is never cached across turns. The reply engine's hot cache holds the warm-profile block (graph-derived, not diary), the per-query router decision, and the per-query memory-extractor parameters. None are derived from diary text, so the rewrite sweep does not need a listener-style invalidation hook. The actual diary search hits SQLite live on every enrichment-bearing turn. Concurrency between the sweep and an in-flight reply is handled by SQLite WAL. There is one inherent limitation: the previous turn's already-spoken assistant reply lives in `DialogueMemory._messages`. If a follow-up lands on the recall-gate fast path, the user is answered from rolling dialogue rather than a fresh enrichment. The rewrite does not retroactively rewrite spoken history; the next turn that triggers fresh enrichment sees the cleaned diary.
**Read paths:** none. The rewrite only touches the bulk sweep. Read-time diary retrieval is untouched.
## Bulk Sweep UI
The memory viewer's diary tab carries a Maintenance section in the sidebar with two operations:
**"🧹 Clean up deflection narration"** — asks the chat model to rewrite each old diary entry, removing only sentences that narrate assistant failures. The rest of each entry is preserved verbatim, no diary entries are deleted, and a summary that is *entirely* deflection narration is kept rather than emptied. Requires the chat model to be running. Backed by `POST /api/diary/scrub-deflections` (NDJSON-streaming) which calls `rewrite_all_diary_summaries`. The endpoint URL still says "scrub" for backwards compatibility; the implementation is now LLM-driven.
**"🏷️ Optimise tags"** — normalises topic tags across all diary entries using the configured chat model. Because each diary write generates topics independently, the same concept may accumulate multiple surface forms over time ("cook", "cooking", "meal prep"). The optimiser collects all unique tags, makes a single LLM call to propose a normalised taxonomy (merging synonyms, splitting compound tags), then applies the mapping to every row whose tags change. Backed by `POST /api/diary/optimise-topics` (NDJSON-streaming) which calls `optimise_diary_topics`. Requires the chat model to be running. Diary text is untouched; only the `topics` column is rewritten. Preserves `ts_utc` on every rewrite. Re-embeds updated rows best-effort. Fail-open: LLM failure or bad JSON leaves all rows unchanged.
## Tag Optimisation
`optimise_diary_topics(db, ollama_base_url, ollama_chat_model, ...)` in `conversation.py` implements the bulk tag normalisation sweep:
1. Collect all unique topic strings from every `conversation_summaries` row (one pass, in memory).
2. One `call_llm_direct` call to `ollama_chat_model` with `_TOPIC_OPTIMISE_SYSTEM_PROMPT` — returns a JSON object mapping each input tag to its normalised form (string for merge, list for split).
3. Apply the mapping via `_apply_topic_mapping()` to each row's comma-separated topics string. Deduplicates the result while preserving order so a merge that produces two identical tags (e.g. "cook, cooking" → "cooking, cooking") collapses cleanly.
4. Write back only rows whose topics changed, preserving `ts_utc` (same contract as the deflection rewrite).
5. Re-embed updated rows if an embed model is configured.
Yields one event per row: `{date_utc, topics_changed, old_topic_count, new_topic_count, error?}`. No raw tag values in events — counts only.
Idempotent once the mapping has been applied: a second run finds no tags to change.
## Evals and Regression Guards
| Test | Location | Guards |
|------|----------|--------|
| `test_omits_deflection_narration_for_unknown_entity` | `evals/test_diary_summariser_hygiene.py` | Rule 1, resolved case |
| `test_omits_deflection_when_topic_never_resolved` | `evals/test_diary_summariser_hygiene.py` | Rule 1, unresolved case |
| `test_unrelated_topics_are_not_welded_into_one_clause` | `evals/test_diary_summariser_hygiene.py` | Rule 3 |
| `test_preserves_legitimate_user_preferences` | `evals/test_diary_summariser_hygiene.py` | Cross-rule: hygiene must not strip real content |
| `TestSummariserForbidsDeflectionNarration` | `tests/test_diary_poisoning_defence.py` | Prompt-content regression (rules 1–3) |
| `TestRewriteSweepBehaviour` | `tests/test_diary_rewrite_sweep.py` | LLM-rewrite bulk sweep DB integration, fail-open, audit trail |
| `TestDiaryScrubEndpoint` | `tests/test_memory_viewer_diary_scrub_api.py` | Endpoint streaming + privacy contract |
| `TestOptimiseContract` / `TestOptimiseMerge` / `TestOptimiseSplit` / `TestOptimiseDeduplicate` / `TestOptimiseAuditTrail` / `TestOptimiseFailOpen` / `TestOptimiseIdempotence` | `tests/test_diary_topic_optimise.py` | Tag optimisation — generator contract, merge/split semantics, dedup, audit trail, fail-open, idempotence |
Live evals target the smallest supported model (gemma4:e2b) and `xfail` softly on weaker models rather than hard-failing, documenting residual risk instead of masking it.
## Relationship to Other Systems
- **Diary retrieval** (`engine.py`): injects retrieved summaries under a "reference only" framing, not as authoritative instructions. This partially mitigates corrupted summaries, but the primary defence is the summariser itself — see `reply.spec.md`.
- **Knowledge graph** (`graph.spec.md`): ingests summaries via `update_graph_from_dialogue()`. Graph extraction inherits whatever corruption the summary contains; hygiene at the summariser is the only place to fix this at source.