Files
CyberGril/src/cybergril/memory/store.py
T
zonggongandmultica-agent 31970c4dd3 HEL-870 assembly: memory/persona/mood/life/proactive-contact joined into one runnable candidate on an additive R4 migration (no existing table or row replaced; no visual changes beyond mechanical proactive flag passthrough) - src/cybergril/memory/semantic.py productizes the audited Mem0 path per plan-next-HEL-869: input-side pre-grouping sends only public rows outbound (user rows always; companion rows only judged+acked with all-told candidates), every batch anchor turn_ids/turn_roles/input_sha256 equals that exact input set, and the read-time gate independently recomputes the fingerprint against the live archive and re-checks every companion row's share state, fail-closed rejecting no_payload/unknown_source/archive_missing/source_mismatch/hit_text_mismatch/anchor_turn_mismatch/role_text_conflict/companion_unshared with honest row_verbatim/row_anchor/batch provenance; main archive chat_message remains the ONLY permanent quote layer; sem_batch/sem_covered carry a lease-recovered idempotent job loop; EmbedLedgerGuard continues the single authoritative embed ledger and with embed_cap=0 (no approved budget) refuses every real embedding so the frozen 498/500 and 39/60 accounts and the HEL-835 gate stay untouched; fixed Mem0 2c81af3 is lazily imported with zero upstream fork, a deterministic stub backend exists for engineering verification and is never claimed semantic; MoodRuntime makes core.mood live (event impulses scaled by bazi strength sensitivity, heartbeat decay, state_snapshot persistence, restart recovery, model sees one word only); DyadRuntime makes the relationship ledger live (completed exchanges are rituals, daily regression, behavior hints stay instructions); life_activity adds start/continue/interrupt/resume/finish continuity across slots and restarts with chat-completion interrupts; reach_out implements the approved R4 scope from character.yaml (>=6h interval, hours 8-23, salience>=0.6, arousal>=0.5, intimacy>=0.4) with traceable already-public bases only, UNIQUE(basis) so restarts and duplicate tasks can never multiply messages, night suppression, absence-rule fail-closed, phi projection, and messages persisted as companion rows (proactive=1) fully synced on reopen; API health reports R4-assembly with per-capability honesty (voice/vision/weather/materials/backup stay false, semantic_memory names its backend); config/semantic.example.yaml sanitized config and docs/runbook-hel870.md (startup, locked deps, health, independent data dir, disable/rollback, experience chain list, budget request, R1-R7 seams); verification: 250 python tests pass on 3.11 venv + requirements.lock (61 new deterministic/fake-provider cases covering every gate negative, restart recovery, dedupe, red line and the full entry chain incl. reopen epoch sync), ruff clean, web typecheck + 42 vitest + build pass with the original author frontend untouched except the one-line proactive passthrough; dual-target requirement checks 4/4 pass vs origin/main and origin/agent/agent/de8874a3803b with handoff-HEL-870.json; zero real model calls, zero embeddings, zero outbound network this card; local unified-instance smoke on port 8360 (stub semantic) serves the built web and reports the life loop waiting; read-only server check recorded in the runbook (existing 8300-8350 services and voice ports observed, end-to-end voice availability NOT verified); not merged, not deployed, no production or shared services touched
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 21:03:42 +08:00

245 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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