"""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")) self.conn.commit() 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, ) -> int: cur = self.execute( """INSERT INTO mem_episodic (ts, role, raw, gist, affect, salience, accessibility, recall_count, consolidated, withheld, source) 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, ), ) # 同步 FTS self.execute( "INSERT INTO mem_fts(rowid, raw, gist) VALUES (?,?,?)", (cur.lastrowid, raw, None), ) self.commit() return int(cur.lastrowid or 0) def decay_accessibility(self, dt_hours: float, *, floor: float = 0.03) -> 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 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