245 lines
10 KiB
Python
245 lines
10 KiB
Python
"""SQLite 存储层。
|
||
|
||
单文件、WAL、无外部服务。
|
||
|
||
设计取舍:
|
||
不上 Mem0 / Graphiti / Cognee / Letta。理由见规格 §6.1:
|
||
它们全部是任务/事实记忆,没有一个是面向「情感/关系」的,
|
||
而且单用户场景下多一层 LLM 抽取只带来成本与延迟。
|
||
宁可自建两张它们都没有的字段:salience(情感显著性)和 dyad。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import sqlite3
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
SCHEMA_PATH = Path(__file__).with_name("schema.sql")
|
||
|
||
|
||
class Store:
|
||
"""轻量 SQLite 封装。
|
||
|
||
刻意保持同步接口:所有调用都在本地、微秒级,
|
||
引入 async 只会增加复杂度而不带来收益。
|
||
"""
|
||
|
||
def __init__(self, path: str | Path, *, init: bool = True) -> None:
|
||
self.path = Path(path)
|
||
self.path.parent.mkdir(parents=True, exist_ok=True) if self.path.parent != Path(".") else None
|
||
self.conn = sqlite3.connect(str(self.path), check_same_thread=False)
|
||
self.conn.row_factory = sqlite3.Row
|
||
if init:
|
||
self.init_schema()
|
||
|
||
# ---------------------------------------------------------------- 基础
|
||
|
||
def init_schema(self) -> None:
|
||
self.conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8"))
|
||
# Guarded ALTER supports populated R1 databases and repeated starts.
|
||
with self.conn:
|
||
self.execute("BEGIN IMMEDIATE")
|
||
columns = {r["name"] for r in self.query("PRAGMA table_info(life_event)")}
|
||
for name, kind in {
|
||
"run_id": "INTEGER REFERENCES life_run(id)", "tz": "TEXT",
|
||
"slot": "INTEGER", "told_at": "INTEGER", "told_via_message_id": "INTEGER",
|
||
}.items():
|
||
if name not in columns:
|
||
self.execute(f"ALTER TABLE life_event ADD COLUMN {name} {kind}")
|
||
self.conn.executescript(SCHEMA_PATH.with_name("r2.sql").read_text(encoding="utf-8"))
|
||
self.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_life_run ON life_event(run_id)")
|
||
self.conn.commit()
|
||
with self.conn:
|
||
columns = {r["name"] for r in self.query("PRAGMA table_info(mem_episodic)")}
|
||
for name, kind in {"turn_id": "TEXT", "message_id": "INTEGER REFERENCES chat_message(id)"}.items():
|
||
if name not in columns:
|
||
self.execute(f"ALTER TABLE mem_episodic ADD COLUMN {name} {kind}")
|
||
self.conn.executescript(SCHEMA_PATH.with_name("r3.sql").read_text(encoding="utf-8"))
|
||
with self.conn:
|
||
if not self.query_one("SELECT value FROM life_control WHERE key='mem_fts_zh_version'"):
|
||
self.execute("INSERT INTO mem_fts_zh(mem_fts_zh) VALUES('rebuild')")
|
||
self.execute("INSERT INTO life_control VALUES('mem_fts_zh_version','1')")
|
||
self.conn.executescript(SCHEMA_PATH.with_name("r4.sql").read_text(encoding="utf-8"))
|
||
with self.conn:
|
||
columns = {r["name"] for r in self.query("PRAGMA table_info(chat_message)")}
|
||
if "proactive" not in columns:
|
||
self.execute("ALTER TABLE chat_message ADD COLUMN proactive INTEGER NOT NULL DEFAULT 0")
|
||
# R4 chat columns: reach-out messages mark themselves on their own rows.
|
||
|
||
def close(self) -> None:
|
||
self.conn.close()
|
||
|
||
def __enter__(self) -> Store:
|
||
return self
|
||
|
||
def __exit__(self, *exc: object) -> None:
|
||
self.close()
|
||
|
||
# ---------------------------------------------------------------- 便捷
|
||
|
||
def execute(self, sql: str, params: tuple[Any, ...] = ()) -> sqlite3.Cursor:
|
||
return self.conn.execute(sql, params)
|
||
|
||
def query(self, sql: str, params: tuple[Any, ...] = ()) -> list[sqlite3.Row]:
|
||
return self.conn.execute(sql, params).fetchall()
|
||
|
||
def query_one(self, sql: str, params: tuple[Any, ...] = ()) -> sqlite3.Row | None:
|
||
return self.conn.execute(sql, params).fetchone()
|
||
|
||
def commit(self) -> None:
|
||
self.conn.commit()
|
||
|
||
# ---------------------------------------------------------------- 状态
|
||
|
||
def save_state(self, *, v: float, a: float, d: float, e: float,
|
||
mood_word: str, ts: int | None = None, version: int = 1,
|
||
drivers: list[int] | None = None) -> None:
|
||
self.execute(
|
||
"""INSERT OR REPLACE INTO state_snapshot
|
||
(ts, valence, arousal, dominance, energy, mood_word, drivers, fortune, version)
|
||
VALUES (?,?,?,?,?,?,?,?,?)""",
|
||
(
|
||
ts if ts is not None else int(time.time() * 1000),
|
||
v, a, d, e, mood_word,
|
||
json.dumps(drivers or [], ensure_ascii=False),
|
||
None, version,
|
||
),
|
||
)
|
||
self.commit()
|
||
|
||
def last_state(self) -> sqlite3.Row | None:
|
||
return self.query_one("SELECT * FROM state_snapshot ORDER BY ts DESC LIMIT 1")
|
||
|
||
# ---------------------------------------------------------------- 记忆
|
||
|
||
def add_episodic(
|
||
self,
|
||
*,
|
||
role: str,
|
||
raw: str,
|
||
salience: float,
|
||
affect: dict[str, float] | None = None,
|
||
withheld: str | None = None,
|
||
source: str | None = None,
|
||
ts: int | None = None,
|
||
turn_id: str | None = None,
|
||
message_id: int | None = None,
|
||
commit: bool = True,
|
||
) -> int:
|
||
cur = self.execute(
|
||
"""INSERT INTO mem_episodic
|
||
(ts, role, raw, gist, affect, salience, accessibility,
|
||
recall_count, consolidated, withheld, source, turn_id, message_id)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(
|
||
ts if ts is not None else int(time.time() * 1000),
|
||
role, raw, None,
|
||
json.dumps(affect, ensure_ascii=False) if affect else None,
|
||
salience, 1.0, 0, 0, withheld, source, turn_id, message_id,
|
||
),
|
||
)
|
||
# 同步 FTS
|
||
self.execute(
|
||
"INSERT INTO mem_fts(rowid, raw, gist) VALUES (?,?,?)",
|
||
(cur.lastrowid, raw, None),
|
||
)
|
||
# R3's SQL trigger maintains the Chinese index, including legacy writers.
|
||
if commit:
|
||
self.commit()
|
||
return int(cur.lastrowid or 0)
|
||
|
||
def set_gist(self, epi_id: int, gist: str, affect: dict) -> None:
|
||
"""Caller owns the transaction, including job completion and both indexes."""
|
||
row = self.query_one("SELECT * FROM mem_episodic WHERE id=?", (epi_id,))
|
||
self.execute("INSERT INTO mem_fts(mem_fts,rowid,raw,gist) VALUES('delete',?,?,?)",
|
||
(epi_id, row["raw"], row["gist"]))
|
||
self.execute("UPDATE mem_episodic SET gist=?,affect=? WHERE id=?",
|
||
(gist, json.dumps(affect), epi_id))
|
||
self.execute("INSERT INTO mem_fts(rowid,raw,gist) VALUES(?,?,?)",
|
||
(epi_id, row["raw"], gist))
|
||
|
||
def decay_accessibility(self, dt_hours: float, *, floor: float = 0.03, commit: bool = True) -> int:
|
||
"""遗忘:指数衰减,但不下探到 0。
|
||
|
||
floor 是关键:正常检索拿不到(想不起来),
|
||
但情绪线索命中时仍能捞出来(但还在)。
|
||
"""
|
||
rows = self.query("SELECT id, salience, accessibility FROM mem_episodic")
|
||
import math
|
||
|
||
n = 0
|
||
for r in rows:
|
||
tau = 24.0 * (1 + 3 * r["salience"])
|
||
new = r["accessibility"] * math.exp(-dt_hours / tau)
|
||
new = max(new, floor)
|
||
if abs(new - r["accessibility"]) > 1e-6:
|
||
self.execute("UPDATE mem_episodic SET accessibility=? WHERE id=?", (new, r["id"]))
|
||
n += 1
|
||
if commit:
|
||
self.commit()
|
||
return n
|
||
|
||
def reinforce(self, epi_id: int, *, boost: float = 0.25) -> None:
|
||
"""间隔效应:被想起的记忆更容易再被想起。"""
|
||
self.execute(
|
||
"""UPDATE mem_episodic
|
||
SET accessibility = MIN(1.0, accessibility + ?),
|
||
recall_count = recall_count + 1
|
||
WHERE id = ?""",
|
||
(boost, epi_id),
|
||
)
|
||
self.commit()
|
||
|
||
def search_fts(self, query: str, limit: int = 20) -> list[sqlite3.Row]:
|
||
return self.query(
|
||
"""SELECT e.* FROM mem_fts f
|
||
JOIN mem_episodic e ON e.id = f.rowid
|
||
WHERE mem_fts MATCH ?
|
||
ORDER BY rank LIMIT ?""",
|
||
(query, limit),
|
||
)
|
||
|
||
# ---------------------------------------------------------------- 关系
|
||
|
||
def add_dyad_event(self, *, kind: str, summary: str, severity: float,
|
||
topics: list[str] | None = None) -> int:
|
||
cur = self.execute(
|
||
"""INSERT INTO dyad_event (ts, kind, summary, severity, topics)
|
||
VALUES (?,?,?,?,?)""",
|
||
(int(time.time() * 1000), kind, summary, severity,
|
||
json.dumps(topics or [], ensure_ascii=False)),
|
||
)
|
||
self.commit()
|
||
return int(cur.lastrowid or 0)
|
||
|
||
def last_dyad(self) -> sqlite3.Row | None:
|
||
return self.query_one("SELECT * FROM dyad_state ORDER BY ts DESC LIMIT 1")
|
||
|
||
def save_dyad(self, *, trust: float, intimacy: float, debt: float,
|
||
security: float, unresolved: list[int]) -> None:
|
||
self.execute(
|
||
"""INSERT OR REPLACE INTO dyad_state
|
||
(ts, trust, intimacy, debt, security, unresolved)
|
||
VALUES (?,?,?,?,?,?)""",
|
||
(int(time.time() * 1000), trust, intimacy, debt, security,
|
||
json.dumps(unresolved)),
|
||
)
|
||
self.commit()
|
||
|
||
# ---------------------------------------------------------------- 投影
|
||
|
||
def record_projection_gap(self, event_key: str, payload: dict[str, Any]) -> None:
|
||
self.execute(
|
||
"INSERT INTO projection_gap (ts, event_key, payload) VALUES (?,?,?)",
|
||
(int(time.time() * 1000), event_key,
|
||
json.dumps(payload, ensure_ascii=False)),
|
||
)
|
||
self.commit()
|
||
|
||
def projection_gap_count(self) -> int:
|
||
row = self.query_one("SELECT COUNT(*) AS n FROM projection_gap")
|
||
return int(row["n"]) if row else 0
|