Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ec344064f1 | |||
| 30e6648122 | |||
| bc97d425ef | |||
| 7e6c2985dd | |||
| 5e6bbb586c | |||
| 517fe49aef |
@@ -0,0 +1,10 @@
|
|||||||
|
CREATE TABLE event_log (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
branch_id INTEGER NOT NULL DEFAULT 1,
|
||||||
|
ts TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
|
kind TEXT NOT NULL,
|
||||||
|
payload_json TEXT NOT NULL,
|
||||||
|
superseded_by INTEGER REFERENCES event_log(id),
|
||||||
|
hidden INTEGER NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_event_log_branch_kind ON event_log(branch_id, kind);
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
CREATE TABLE bots (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
persona TEXT NOT NULL,
|
||||||
|
voice_samples_json TEXT NOT NULL DEFAULT '[]',
|
||||||
|
traits_json TEXT NOT NULL DEFAULT '[]',
|
||||||
|
backstory TEXT NOT NULL DEFAULT '',
|
||||||
|
initial_relationship_to_you TEXT NOT NULL DEFAULT '',
|
||||||
|
kickoff_prose TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE you_entity (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
pronouns TEXT NOT NULL DEFAULT '',
|
||||||
|
persona TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
CREATE TABLE edges (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
chat_id TEXT,
|
||||||
|
source_id TEXT NOT NULL,
|
||||||
|
target_id TEXT NOT NULL,
|
||||||
|
affinity INTEGER NOT NULL DEFAULT 50,
|
||||||
|
trust INTEGER NOT NULL DEFAULT 50,
|
||||||
|
summary TEXT NOT NULL DEFAULT '',
|
||||||
|
knowledge_json TEXT NOT NULL DEFAULT '[]',
|
||||||
|
last_interaction_chat_id TEXT,
|
||||||
|
last_interaction_at TEXT,
|
||||||
|
UNIQUE (source_id, target_id)
|
||||||
|
);
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
CREATE TABLE memories (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
owner_id TEXT NOT NULL,
|
||||||
|
chat_id TEXT NOT NULL,
|
||||||
|
scene_id INTEGER,
|
||||||
|
pov_summary TEXT NOT NULL,
|
||||||
|
witness_you INTEGER NOT NULL,
|
||||||
|
witness_host INTEGER NOT NULL,
|
||||||
|
witness_guest INTEGER NOT NULL,
|
||||||
|
chat_clock_at TEXT,
|
||||||
|
source TEXT,
|
||||||
|
reliability REAL NOT NULL DEFAULT 1.0,
|
||||||
|
significance INTEGER NOT NULL DEFAULT 1,
|
||||||
|
pinned INTEGER NOT NULL DEFAULT 0,
|
||||||
|
auto_pinned INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_memories_owner ON memories(owner_id);
|
||||||
|
|
||||||
|
CREATE VIRTUAL TABLE memories_fts USING fts5(
|
||||||
|
pov_summary, content='memories', content_rowid='id'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TRIGGER memories_ai AFTER INSERT ON memories BEGIN
|
||||||
|
INSERT INTO memories_fts(rowid, pov_summary) VALUES (new.id, new.pov_summary);
|
||||||
|
END;
|
||||||
|
CREATE TRIGGER memories_au AFTER UPDATE ON memories BEGIN
|
||||||
|
INSERT INTO memories_fts(memories_fts, rowid, pov_summary)
|
||||||
|
VALUES('delete', old.id, old.pov_summary);
|
||||||
|
INSERT INTO memories_fts(rowid, pov_summary) VALUES (new.id, new.pov_summary);
|
||||||
|
END;
|
||||||
|
CREATE TRIGGER memories_ad AFTER DELETE ON memories BEGIN
|
||||||
|
INSERT INTO memories_fts(memories_fts, rowid, pov_summary)
|
||||||
|
VALUES('delete', old.id, old.pov_summary);
|
||||||
|
END;
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
CREATE TABLE chats (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
host_bot_id TEXT NOT NULL,
|
||||||
|
guest_bot_id TEXT,
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chat_state (
|
||||||
|
chat_id TEXT PRIMARY KEY,
|
||||||
|
time TEXT NOT NULL,
|
||||||
|
weather TEXT NOT NULL DEFAULT '',
|
||||||
|
active_scene_id INTEGER,
|
||||||
|
narrative_anchor TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE containers (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
chat_id TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
type TEXT NOT NULL,
|
||||||
|
properties_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
parent_id INTEGER REFERENCES containers(id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE scenes (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
chat_id TEXT NOT NULL,
|
||||||
|
container_id INTEGER REFERENCES containers(id),
|
||||||
|
started_at TEXT NOT NULL,
|
||||||
|
ended_at TEXT,
|
||||||
|
significance INTEGER NOT NULL DEFAULT 0,
|
||||||
|
participants_json TEXT NOT NULL DEFAULT '[]'
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE activity (
|
||||||
|
entity_id TEXT PRIMARY KEY,
|
||||||
|
container_id INTEGER REFERENCES containers(id),
|
||||||
|
slot TEXT,
|
||||||
|
posture TEXT NOT NULL DEFAULT '',
|
||||||
|
action_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
attention TEXT NOT NULL DEFAULT '',
|
||||||
|
holding_json TEXT NOT NULL DEFAULT '[]',
|
||||||
|
status_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Iterator
|
||||||
|
from sqlite3 import Connection
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Event:
|
||||||
|
id: int
|
||||||
|
branch_id: int
|
||||||
|
ts: str
|
||||||
|
kind: str
|
||||||
|
payload: dict[str, Any]
|
||||||
|
superseded_by: int | None
|
||||||
|
hidden: bool
|
||||||
|
|
||||||
|
|
||||||
|
def append_event(conn: Connection, *, kind: str, payload: dict[str, Any], branch_id: int = 1) -> int:
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO event_log (branch_id, kind, payload_json) VALUES (?, ?, ?)",
|
||||||
|
(branch_id, kind, json.dumps(payload)),
|
||||||
|
)
|
||||||
|
return cur.lastrowid
|
||||||
|
|
||||||
|
|
||||||
|
def read_events(conn: Connection, branch_id: int = 1, after_id: int = 0) -> Iterator[Event]:
|
||||||
|
cur = conn.execute(
|
||||||
|
"SELECT id, branch_id, ts, kind, payload_json, superseded_by, hidden "
|
||||||
|
"FROM event_log WHERE branch_id = ? AND id > ? AND hidden = 0 "
|
||||||
|
"AND superseded_by IS NULL ORDER BY id",
|
||||||
|
(branch_id, after_id),
|
||||||
|
)
|
||||||
|
for row in cur:
|
||||||
|
yield Event(
|
||||||
|
id=row[0], branch_id=row[1], ts=row[2], kind=row[3],
|
||||||
|
payload=json.loads(row[4]), superseded_by=row[5], hidden=bool(row[6]),
|
||||||
|
)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
from collections.abc import Callable
|
||||||
|
from sqlite3 import Connection
|
||||||
|
from .log import Event, read_events
|
||||||
|
|
||||||
|
Handler = Callable[[Connection, Event], None]
|
||||||
|
_REGISTRY: dict[str, Handler] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def on(kind: str):
|
||||||
|
def deco(fn: Handler) -> Handler:
|
||||||
|
_REGISTRY[kind] = fn
|
||||||
|
return fn
|
||||||
|
return deco
|
||||||
|
|
||||||
|
|
||||||
|
def project(conn: Connection, branch_id: int = 1) -> None:
|
||||||
|
for event in read_events(conn, branch_id=branch_id):
|
||||||
|
h = _REGISTRY.get(event.kind)
|
||||||
|
if h:
|
||||||
|
h(conn, event)
|
||||||
|
|
||||||
|
|
||||||
|
def apply_event(conn: Connection, event: Event) -> None:
|
||||||
|
h = _REGISTRY.get(event.kind)
|
||||||
|
if h:
|
||||||
|
h(conn, event)
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from sqlite3 import Connection
|
||||||
|
from chat.eventlog.projector import on
|
||||||
|
from chat.eventlog.log import Event
|
||||||
|
|
||||||
|
|
||||||
|
def _clamp(value: int, lo: int = 0, hi: int = 100) -> int:
|
||||||
|
return max(lo, min(hi, value))
|
||||||
|
|
||||||
|
|
||||||
|
@on("edge_update")
|
||||||
|
def _apply_edge_update(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
source_id = p["source_id"]
|
||||||
|
target_id = p["target_id"]
|
||||||
|
chat_id = p.get("chat_id")
|
||||||
|
|
||||||
|
# Upsert: ensure a row exists with defaults, then apply deltas.
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR IGNORE INTO edges (chat_id, source_id, target_id) VALUES (?, ?, ?)",
|
||||||
|
(chat_id, source_id, target_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT affinity, trust, knowledge_json, last_interaction_chat_id, last_interaction_at "
|
||||||
|
"FROM edges WHERE source_id = ? AND target_id = ?",
|
||||||
|
(source_id, target_id),
|
||||||
|
).fetchone()
|
||||||
|
affinity, trust, knowledge_json, last_chat_id, last_at = row
|
||||||
|
|
||||||
|
affinity_delta = int(p.get("affinity_delta", 0))
|
||||||
|
trust_delta = int(p.get("trust_delta", 0))
|
||||||
|
new_affinity = _clamp(affinity + affinity_delta)
|
||||||
|
new_trust = _clamp(trust + trust_delta)
|
||||||
|
|
||||||
|
new_facts = p.get("knowledge_facts") or []
|
||||||
|
if new_facts:
|
||||||
|
knowledge = json.loads(knowledge_json)
|
||||||
|
knowledge.extend(new_facts)
|
||||||
|
knowledge_json = json.dumps(knowledge)
|
||||||
|
|
||||||
|
payload_at = p.get("last_interaction_at")
|
||||||
|
payload_chat_id = p.get("last_interaction_chat_id")
|
||||||
|
if payload_at is not None:
|
||||||
|
last_at = payload_at
|
||||||
|
if payload_chat_id is not None:
|
||||||
|
last_chat_id = payload_chat_id
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE edges SET affinity = ?, trust = ?, knowledge_json = ?, "
|
||||||
|
"last_interaction_chat_id = ?, last_interaction_at = ? "
|
||||||
|
"WHERE source_id = ? AND target_id = ?",
|
||||||
|
(new_affinity, new_trust, knowledge_json, last_chat_id, last_at,
|
||||||
|
source_id, target_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_edge(conn: Connection, source_id: str, target_id: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM edges WHERE source_id = ? AND target_id = ?",
|
||||||
|
(source_id, target_id),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(edges)").fetchall()]
|
||||||
|
d = dict(zip(cols, row))
|
||||||
|
d["knowledge"] = json.loads(d.pop("knowledge_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def list_edges_for(conn: Connection, source_id: str) -> list[dict]:
|
||||||
|
cur = conn.execute(
|
||||||
|
"SELECT * FROM edges WHERE source_id = ? ORDER BY target_id",
|
||||||
|
(source_id,),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(edges)").fetchall()]
|
||||||
|
out: list[dict] = []
|
||||||
|
for row in rows:
|
||||||
|
d = dict(zip(cols, row))
|
||||||
|
d["knowledge"] = json.loads(d.pop("knowledge_json"))
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from sqlite3 import Connection
|
||||||
|
from chat.eventlog.projector import on
|
||||||
|
from chat.eventlog.log import Event
|
||||||
|
|
||||||
|
|
||||||
|
@on("bot_authored")
|
||||||
|
def _apply_bot_authored(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO bots "
|
||||||
|
"(id, name, persona, voice_samples_json, traits_json, backstory, "
|
||||||
|
" initial_relationship_to_you, kickoff_prose) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(p["id"], p["name"], p["persona"],
|
||||||
|
json.dumps(p.get("voice_samples", [])),
|
||||||
|
json.dumps(p.get("traits", [])),
|
||||||
|
p.get("backstory", ""),
|
||||||
|
p.get("initial_relationship_to_you", ""),
|
||||||
|
p.get("kickoff_prose", "")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@on("you_authored")
|
||||||
|
def _apply_you_authored(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO you_entity (id, name, pronouns, persona) VALUES (1, ?, ?, ?)",
|
||||||
|
(p["name"], p.get("pronouns", ""), p.get("persona", "")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_bot(conn: Connection, bot_id: str) -> dict | None:
|
||||||
|
row = conn.execute("SELECT * FROM bots WHERE id = ?", (bot_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(bots)").fetchall()]
|
||||||
|
d = dict(zip(cols, row))
|
||||||
|
d["voice_samples"] = json.loads(d.pop("voice_samples_json"))
|
||||||
|
d["traits"] = json.loads(d.pop("traits_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def list_bots(conn: Connection) -> list[dict]:
|
||||||
|
cur = conn.execute("SELECT id, name FROM bots ORDER BY name")
|
||||||
|
return [{"id": r[0], "name": r[1]} for r in cur]
|
||||||
|
|
||||||
|
|
||||||
|
def get_you(conn: Connection) -> dict | None:
|
||||||
|
row = conn.execute("SELECT name, pronouns, persona FROM you_entity WHERE id = 1").fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return {"name": row[0], "pronouns": row[1], "persona": row[2]}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
from sqlite3 import Connection
|
||||||
|
from chat.eventlog.projector import on
|
||||||
|
from chat.eventlog.log import Event
|
||||||
|
|
||||||
|
_VALID_WITNESS_ROLES = {"you", "host", "guest"}
|
||||||
|
|
||||||
|
|
||||||
|
def _row_to_dict(conn: Connection, row: tuple) -> dict:
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(memories)").fetchall()]
|
||||||
|
return dict(zip(cols, row))
|
||||||
|
|
||||||
|
|
||||||
|
@on("memory_written")
|
||||||
|
def _apply_memory_written(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO memories ("
|
||||||
|
"owner_id, chat_id, scene_id, pov_summary, "
|
||||||
|
"witness_you, witness_host, witness_guest, "
|
||||||
|
"chat_clock_at, source, reliability, significance, pinned, auto_pinned"
|
||||||
|
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
(
|
||||||
|
p["owner_id"],
|
||||||
|
p["chat_id"],
|
||||||
|
p.get("scene_id"),
|
||||||
|
p["pov_summary"],
|
||||||
|
int(p["witness_you"]),
|
||||||
|
int(p["witness_host"]),
|
||||||
|
int(p["witness_guest"]),
|
||||||
|
p.get("chat_clock_at"),
|
||||||
|
p.get("source", "direct"),
|
||||||
|
float(p.get("reliability", 1.0)),
|
||||||
|
int(p.get("significance", 1)),
|
||||||
|
int(p.get("pinned", 0)),
|
||||||
|
int(p.get("auto_pinned", 0)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_memory(conn: Connection, memory_id: int) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM memories WHERE id = ?", (memory_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return _row_to_dict(conn, row)
|
||||||
|
|
||||||
|
|
||||||
|
def get_pinned(conn: Connection, owner_id: str) -> list[dict]:
|
||||||
|
cur = conn.execute(
|
||||||
|
"SELECT * FROM memories WHERE owner_id = ? AND pinned = 1 "
|
||||||
|
"ORDER BY created_at DESC, id DESC",
|
||||||
|
(owner_id,),
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(memories)").fetchall()]
|
||||||
|
return [dict(zip(cols, row)) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def search_memories(
|
||||||
|
conn: Connection,
|
||||||
|
owner_id: str,
|
||||||
|
witness_role: str,
|
||||||
|
query: str,
|
||||||
|
k: int = 4,
|
||||||
|
) -> list[dict]:
|
||||||
|
"""FTS5 search over pov_summary, scoped by owner and witness role.
|
||||||
|
|
||||||
|
witness_role must be one of {"you", "host", "guest"} per the witness flags
|
||||||
|
on each memory row. Returns up to k rows ordered by FTS5 bm25 rank.
|
||||||
|
"""
|
||||||
|
if witness_role not in _VALID_WITNESS_ROLES:
|
||||||
|
raise ValueError(
|
||||||
|
f"witness_role must be one of {sorted(_VALID_WITNESS_ROLES)}, "
|
||||||
|
f"got {witness_role!r}"
|
||||||
|
)
|
||||||
|
witness_col = f"witness_{witness_role}"
|
||||||
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(memories)").fetchall()]
|
||||||
|
select_list = ", ".join(f"m.{c}" for c in cols)
|
||||||
|
sql = (
|
||||||
|
f"SELECT {select_list}, memories_fts.rank AS fts_rank "
|
||||||
|
"FROM memories_fts "
|
||||||
|
"JOIN memories m ON m.id = memories_fts.rowid "
|
||||||
|
f"WHERE m.owner_id = ? AND m.{witness_col} = 1 "
|
||||||
|
"AND memories_fts MATCH ? "
|
||||||
|
"ORDER BY memories_fts.rank "
|
||||||
|
"LIMIT ?"
|
||||||
|
)
|
||||||
|
cur = conn.execute(sql, (owner_id, query, k))
|
||||||
|
rows = cur.fetchall()
|
||||||
|
out: list[dict] = []
|
||||||
|
result_cols = cols + ["fts_rank"]
|
||||||
|
for row in rows:
|
||||||
|
out.append(dict(zip(result_cols, row)))
|
||||||
|
return out
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import json
|
||||||
|
from sqlite3 import Connection
|
||||||
|
from chat.eventlog.projector import on
|
||||||
|
from chat.eventlog.log import Event
|
||||||
|
|
||||||
|
|
||||||
|
def _row_to_dict(conn: Connection, table: str, row: tuple) -> dict:
|
||||||
|
cols = [c[1] for c in conn.execute(f"PRAGMA table_info({table})").fetchall()]
|
||||||
|
return dict(zip(cols, row))
|
||||||
|
|
||||||
|
|
||||||
|
@on("chat_created")
|
||||||
|
def _apply_chat_created(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO chats (id, host_bot_id, guest_bot_id) VALUES (?, ?, ?)",
|
||||||
|
(p["id"], p["host_bot_id"], p.get("guest_bot_id")),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO chat_state (chat_id, time, weather, active_scene_id, narrative_anchor) "
|
||||||
|
"VALUES (?, ?, ?, NULL, ?)",
|
||||||
|
(
|
||||||
|
p["id"],
|
||||||
|
p["initial_time"],
|
||||||
|
p.get("weather", ""),
|
||||||
|
p.get("narrative_anchor", ""),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@on("container_created")
|
||||||
|
def _apply_container_created(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO containers (chat_id, name, type, properties_json, parent_id) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?)",
|
||||||
|
(
|
||||||
|
p["chat_id"],
|
||||||
|
p["name"],
|
||||||
|
p["type"],
|
||||||
|
json.dumps(p.get("properties", {})),
|
||||||
|
p.get("parent_id"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@on("activity_change")
|
||||||
|
def _apply_activity_change(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO activity ("
|
||||||
|
"entity_id, container_id, slot, posture, action_json, "
|
||||||
|
"attention, holding_json, status_json, updated_at"
|
||||||
|
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))",
|
||||||
|
(
|
||||||
|
p["entity_id"],
|
||||||
|
p.get("container_id"),
|
||||||
|
p.get("slot"),
|
||||||
|
p.get("posture", ""),
|
||||||
|
json.dumps(p.get("action", {})),
|
||||||
|
p.get("attention", ""),
|
||||||
|
json.dumps(p.get("holding", [])),
|
||||||
|
json.dumps(p.get("status", {})),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@on("scene_opened")
|
||||||
|
def _apply_scene_opened(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
cur = conn.execute(
|
||||||
|
"INSERT INTO scenes (chat_id, container_id, started_at, ended_at, "
|
||||||
|
"significance, participants_json) VALUES (?, ?, ?, NULL, 0, ?)",
|
||||||
|
(
|
||||||
|
p["chat_id"],
|
||||||
|
p.get("container_id"),
|
||||||
|
p["started_at"],
|
||||||
|
json.dumps(p.get("participants", [])),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
new_id = cur.lastrowid
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE chat_state SET active_scene_id = ? WHERE chat_id = ?",
|
||||||
|
(new_id, p["chat_id"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@on("scene_closed")
|
||||||
|
def _apply_scene_closed(conn: Connection, e: Event) -> None:
|
||||||
|
p = e.payload
|
||||||
|
scene_id = p["scene_id"]
|
||||||
|
significance = int(p.get("significance", 0))
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE scenes SET ended_at = ?, significance = ? WHERE id = ?",
|
||||||
|
(p["ended_at"], significance, scene_id),
|
||||||
|
)
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT chat_id FROM scenes WHERE id = ?", (scene_id,)
|
||||||
|
).fetchone()
|
||||||
|
if row is not None:
|
||||||
|
chat_id = row[0]
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE chat_state SET active_scene_id = NULL WHERE chat_id = ?",
|
||||||
|
(chat_id,),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_select_columns() -> str:
|
||||||
|
return (
|
||||||
|
"c.id, c.host_bot_id, c.guest_bot_id, c.created_at, "
|
||||||
|
"s.time, s.weather, s.active_scene_id, s.narrative_anchor"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_row_to_dict(row: tuple) -> dict:
|
||||||
|
return {
|
||||||
|
"id": row[0],
|
||||||
|
"host_bot_id": row[1],
|
||||||
|
"guest_bot_id": row[2],
|
||||||
|
"created_at": row[3],
|
||||||
|
"time": row[4],
|
||||||
|
"weather": row[5],
|
||||||
|
"active_scene_id": row[6],
|
||||||
|
"narrative_anchor": row[7],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_chat(conn: Connection, chat_id: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
f"SELECT {_chat_select_columns()} FROM chats c "
|
||||||
|
"JOIN chat_state s ON s.chat_id = c.id WHERE c.id = ?",
|
||||||
|
(chat_id,),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
return _chat_row_to_dict(row)
|
||||||
|
|
||||||
|
|
||||||
|
def list_chats(conn: Connection) -> list[dict]:
|
||||||
|
cur = conn.execute(
|
||||||
|
f"SELECT {_chat_select_columns()} FROM chats c "
|
||||||
|
"JOIN chat_state s ON s.chat_id = c.id ORDER BY c.id"
|
||||||
|
)
|
||||||
|
return [_chat_row_to_dict(row) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
|
||||||
|
def get_container(conn: Connection, container_id: int) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM containers WHERE id = ?", (container_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(conn, "containers", row)
|
||||||
|
d["properties"] = json.loads(d.pop("properties_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def find_container(conn: Connection, chat_id: str, name: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM containers WHERE chat_id = ? AND name = ?",
|
||||||
|
(chat_id, name),
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(conn, "containers", row)
|
||||||
|
d["properties"] = json.loads(d.pop("properties_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def get_activity(conn: Connection, entity_id: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM activity WHERE entity_id = ?", (entity_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(conn, "activity", row)
|
||||||
|
d["action"] = json.loads(d.pop("action_json"))
|
||||||
|
d["holding"] = json.loads(d.pop("holding_json"))
|
||||||
|
d["status"] = json.loads(d.pop("status_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def get_scene(conn: Connection, scene_id: int) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM scenes WHERE id = ?", (scene_id,)
|
||||||
|
).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
d = _row_to_dict(conn, "scenes", row)
|
||||||
|
d["participants"] = json.loads(d.pop("participants_json"))
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
def active_scene(conn: Connection, chat_id: str) -> dict | None:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT active_scene_id FROM chat_state WHERE chat_id = ?",
|
||||||
|
(chat_id,),
|
||||||
|
).fetchone()
|
||||||
|
if not row or row[0] is None:
|
||||||
|
return None
|
||||||
|
return get_scene(conn, row[0])
|
||||||
@@ -884,7 +884,7 @@ def get_bot(conn: Connection, bot_id: str) -> dict | None:
|
|||||||
row = conn.execute("SELECT * FROM bots WHERE id = ?", (bot_id,)).fetchone()
|
row = conn.execute("SELECT * FROM bots WHERE id = ?", (bot_id,)).fetchone()
|
||||||
if not row:
|
if not row:
|
||||||
return None
|
return None
|
||||||
cols = [c[0] for c in conn.execute("PRAGMA table_info(bots)").fetchall()]
|
cols = [c[1] for c in conn.execute("PRAGMA table_info(bots)").fetchall()]
|
||||||
d = dict(zip(cols, row))
|
d = dict(zip(cols, row))
|
||||||
d["voice_samples"] = json.loads(d.pop("voice_samples_json"))
|
d["voice_samples"] = json.loads(d.pop("voice_samples_json"))
|
||||||
d["traits"] = json.loads(d.pop("traits_json"))
|
d["traits"] = json.loads(d.pop("traits_json"))
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
from chat.db.migrate import apply_migrations
|
||||||
|
from chat.db.connection import open_db
|
||||||
|
from chat.eventlog.log import append_event
|
||||||
|
from chat.eventlog.projector import project
|
||||||
|
from chat.state.edges import get_edge, list_edges_for
|
||||||
|
import chat.state.entities # registers bot/you handlers
|
||||||
|
import chat.state.edges # registers edge_update handler
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_entities(conn) -> None:
|
||||||
|
append_event(conn, kind="bot_authored", payload={
|
||||||
|
"id": "bot_a", "name": "BotA", "persona": "p",
|
||||||
|
"voice_samples": [], "traits": [],
|
||||||
|
"backstory": "", "initial_relationship_to_you": "",
|
||||||
|
"kickoff_prose": "",
|
||||||
|
})
|
||||||
|
append_event(conn, kind="you_authored", payload={
|
||||||
|
"name": "Me", "pronouns": "", "persona": "",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
def test_edge_update_upsert_applies_first_delta(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 5,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
edge = get_edge(conn, "bot_a", "you")
|
||||||
|
assert edge is not None
|
||||||
|
assert edge["affinity"] == 55
|
||||||
|
assert edge["trust"] == 50
|
||||||
|
assert edge["knowledge"] == []
|
||||||
|
assert edge["summary"] == ""
|
||||||
|
|
||||||
|
|
||||||
|
def test_edge_update_multiple_deltas_accumulate(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 5,
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": -3,
|
||||||
|
"trust_delta": 2,
|
||||||
|
"knowledge_facts": ["she has a sister"],
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
edge = get_edge(conn, "bot_a", "you")
|
||||||
|
assert edge is not None
|
||||||
|
assert edge["affinity"] == 52
|
||||||
|
assert edge["trust"] == 52
|
||||||
|
assert edge["knowledge"] == ["she has a sister"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_edge_update_clamps_affinity_at_max(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 5,
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 100,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
edge = get_edge(conn, "bot_a", "you")
|
||||||
|
assert edge is not None
|
||||||
|
assert edge["affinity"] == 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_edge_update_clamps_trust_at_min(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"trust_delta": -200,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
edge = get_edge(conn, "bot_a", "you")
|
||||||
|
assert edge is not None
|
||||||
|
assert edge["trust"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_edges_are_directed_and_asymmetric(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 5,
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "you", "target_id": "bot_a",
|
||||||
|
"affinity_delta": 10,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
forward = get_edge(conn, "bot_a", "you")
|
||||||
|
reverse = get_edge(conn, "you", "bot_a")
|
||||||
|
assert forward is not None and reverse is not None
|
||||||
|
assert forward["affinity"] == 55
|
||||||
|
assert reverse["affinity"] == 60
|
||||||
|
# Independent rows
|
||||||
|
assert forward["affinity"] != reverse["affinity"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_edge_update_bumps_last_interaction(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you",
|
||||||
|
"affinity_delta": 1,
|
||||||
|
"last_interaction_at": "2026-04-26T10:00:00",
|
||||||
|
"last_interaction_chat_id": "chat_bot_a",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
edge = get_edge(conn, "bot_a", "you")
|
||||||
|
assert edge is not None
|
||||||
|
assert edge["last_interaction_at"] == "2026-04-26T10:00:00"
|
||||||
|
assert edge["last_interaction_chat_id"] == "chat_bot_a"
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_edges_for_returns_outgoing_only(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
_seed_entities(conn)
|
||||||
|
append_event(conn, kind="bot_authored", payload={
|
||||||
|
"id": "bot_b", "name": "BotB", "persona": "p",
|
||||||
|
"voice_samples": [], "traits": [],
|
||||||
|
"backstory": "", "initial_relationship_to_you": "",
|
||||||
|
"kickoff_prose": "",
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "you", "affinity_delta": 1,
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_a", "target_id": "bot_b", "affinity_delta": 2,
|
||||||
|
})
|
||||||
|
append_event(conn, kind="edge_update", payload={
|
||||||
|
"source_id": "bot_b", "target_id": "bot_a", "affinity_delta": 3,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
outgoing = list_edges_for(conn, "bot_a")
|
||||||
|
targets = [e["target_id"] for e in outgoing]
|
||||||
|
assert targets == sorted(targets)
|
||||||
|
assert set(targets) == {"you", "bot_b"}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from chat.db.migrate import apply_migrations
|
||||||
|
from chat.db.connection import open_db
|
||||||
|
from chat.eventlog.log import append_event
|
||||||
|
from chat.eventlog.projector import project
|
||||||
|
from chat.state.entities import get_bot, list_bots, get_you
|
||||||
|
import chat.state.entities # registers handlers
|
||||||
|
|
||||||
|
|
||||||
|
def test_bot_authored_creates_bot_row(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="bot_authored", payload={
|
||||||
|
"id": "bot_a", "name": "BotA",
|
||||||
|
"persona": "...", "voice_samples": ["sample"], "traits": ["shy"],
|
||||||
|
"backstory": "...",
|
||||||
|
"initial_relationship_to_you": "coworker",
|
||||||
|
"kickoff_prose": "you stay late",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
bot = get_bot(conn, "bot_a")
|
||||||
|
assert bot is not None
|
||||||
|
assert bot["name"] == "BotA"
|
||||||
|
assert bot["traits"] == ["shy"]
|
||||||
|
assert "bot_a" in [b["id"] for b in list_bots(conn)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_you_authored_creates_you_singleton(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="you_authored", payload={
|
||||||
|
"name": "Me", "pronouns": "they/them", "persona": "engineer",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
you = get_you(conn)
|
||||||
|
assert you is not None
|
||||||
|
assert you["name"] == "Me"
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from chat.db.migrate import apply_migrations
|
||||||
|
from chat.db.connection import open_db
|
||||||
|
from chat.eventlog.log import append_event, read_events
|
||||||
|
|
||||||
|
|
||||||
|
def test_append_and_read(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
eid = append_event(conn, kind="test_kind", payload={"a": 1})
|
||||||
|
assert eid > 0
|
||||||
|
rows = list(read_events(conn))
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert rows[0].kind == "test_kind"
|
||||||
|
assert rows[0].payload["a"] == 1
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chat.db.connection import open_db
|
||||||
|
from chat.db.migrate import apply_migrations
|
||||||
|
from chat.eventlog.log import append_event
|
||||||
|
from chat.eventlog.projector import project
|
||||||
|
import chat.state.memory # registers memory_written handler
|
||||||
|
from chat.state.memory import get_memory, get_pinned, search_memories
|
||||||
|
|
||||||
|
|
||||||
|
def _base_memory(**overrides):
|
||||||
|
payload = {
|
||||||
|
"owner_id": "bot_a",
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"scene_id": 1,
|
||||||
|
"pov_summary": "She laughed at his joke about owls.",
|
||||||
|
"witness_you": 1,
|
||||||
|
"witness_host": 1,
|
||||||
|
"witness_guest": 0,
|
||||||
|
"chat_clock_at": "2026-04-26T10:00:00",
|
||||||
|
"source": "direct",
|
||||||
|
"reliability": 1.0,
|
||||||
|
"significance": 1,
|
||||||
|
"pinned": 0,
|
||||||
|
"auto_pinned": 0,
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_memory_written_is_projected_and_readable(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory())
|
||||||
|
project(conn)
|
||||||
|
row = conn.execute("SELECT id FROM memories").fetchone()
|
||||||
|
assert row is not None
|
||||||
|
mem = get_memory(conn, row[0])
|
||||||
|
assert mem is not None
|
||||||
|
assert mem["owner_id"] == "bot_a"
|
||||||
|
assert mem["chat_id"] == "chat_bot_a"
|
||||||
|
assert mem["scene_id"] == 1
|
||||||
|
assert mem["pov_summary"] == "She laughed at his joke about owls."
|
||||||
|
assert mem["witness_you"] == 1
|
||||||
|
assert mem["witness_host"] == 1
|
||||||
|
assert mem["witness_guest"] == 0
|
||||||
|
assert mem["chat_clock_at"] == "2026-04-26T10:00:00"
|
||||||
|
assert mem["source"] == "direct"
|
||||||
|
assert mem["reliability"] == 1.0
|
||||||
|
assert mem["significance"] == 1
|
||||||
|
assert mem["pinned"] == 0
|
||||||
|
assert mem["auto_pinned"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_memory_returns_none_for_missing_id(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
assert get_memory(conn, 9999) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_filters_out_non_witness(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="The cat sat on the mat.",
|
||||||
|
witness_you=1, witness_host=1, witness_guest=0,
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
# guest did not witness => excluded
|
||||||
|
results = search_memories(conn, "bot_a", "guest", "cat")
|
||||||
|
assert results == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_includes_witnesses(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="The cat sat on the mat.",
|
||||||
|
witness_you=1, witness_host=1, witness_guest=0,
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
results = search_memories(conn, "bot_a", "host", "cat")
|
||||||
|
assert len(results) == 1
|
||||||
|
assert results[0]["pov_summary"] == "The cat sat on the mat."
|
||||||
|
assert "fts_rank" in results[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_fts_matches_only_relevant_text(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="She loves owls and stars.",
|
||||||
|
))
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="He fixed the broken kettle.",
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
results = search_memories(conn, "bot_a", "you", "owls")
|
||||||
|
assert len(results) == 1
|
||||||
|
assert results[0]["pov_summary"] == "She loves owls and stars."
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_filters_by_owner(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
owner_id="bot_a",
|
||||||
|
pov_summary="Owls hooted at midnight.",
|
||||||
|
))
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
owner_id="bot_b",
|
||||||
|
pov_summary="Owls hooted at midnight.",
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
results_a = search_memories(conn, "bot_a", "you", "owls")
|
||||||
|
results_b = search_memories(conn, "bot_b", "you", "owls")
|
||||||
|
assert len(results_a) == 1
|
||||||
|
assert results_a[0]["owner_id"] == "bot_a"
|
||||||
|
assert len(results_b) == 1
|
||||||
|
assert results_b[0]["owner_id"] == "bot_b"
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_returns_empty_on_no_match(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="The cat sat on the mat.",
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
results = search_memories(conn, "bot_a", "you", "spaceship")
|
||||||
|
assert results == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_invalid_witness_role_raises(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
search_memories(conn, "bot_a", "everyone", "cat")
|
||||||
|
|
||||||
|
|
||||||
|
def test_search_memories_respects_k_limit(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
for i in range(6):
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary=f"Owls hooted at midnight number {i}.",
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
results = search_memories(conn, "bot_a", "you", "owls", k=4)
|
||||||
|
assert len(results) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_pinned_returns_only_pinned(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="Pinned moment.",
|
||||||
|
pinned=1,
|
||||||
|
))
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
pov_summary="Unpinned moment.",
|
||||||
|
pinned=0,
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
pinned = get_pinned(conn, "bot_a")
|
||||||
|
assert len(pinned) == 1
|
||||||
|
assert pinned[0]["pov_summary"] == "Pinned moment."
|
||||||
|
assert pinned[0]["pinned"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_pinned_filters_by_owner(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
owner_id="bot_a", pov_summary="A's pin.", pinned=1,
|
||||||
|
))
|
||||||
|
append_event(conn, kind="memory_written", payload=_base_memory(
|
||||||
|
owner_id="bot_b", pov_summary="B's pin.", pinned=1,
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
pinned_a = get_pinned(conn, "bot_a")
|
||||||
|
assert len(pinned_a) == 1
|
||||||
|
assert pinned_a[0]["owner_id"] == "bot_a"
|
||||||
|
|
||||||
|
|
||||||
|
def test_memory_payload_defaults_when_optional_missing(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="memory_written", payload={
|
||||||
|
"owner_id": "bot_a",
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"pov_summary": "Bare minimum memory.",
|
||||||
|
"witness_you": 1,
|
||||||
|
"witness_host": 1,
|
||||||
|
"witness_guest": 1,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
row = conn.execute("SELECT id FROM memories").fetchone()
|
||||||
|
mem = get_memory(conn, row[0])
|
||||||
|
assert mem["scene_id"] is None
|
||||||
|
assert mem["chat_clock_at"] is None
|
||||||
|
assert mem["source"] == "direct"
|
||||||
|
assert mem["reliability"] == 1.0
|
||||||
|
assert mem["significance"] == 1
|
||||||
|
assert mem["pinned"] == 0
|
||||||
|
assert mem["auto_pinned"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_schema_version_after_migration_is_at_least_6(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT value FROM meta WHERE key = 'schema_version'"
|
||||||
|
).fetchone()
|
||||||
|
assert int(row[0]) >= 6
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from chat.db.connection import open_db
|
||||||
|
from chat.db.migrate import apply_migrations
|
||||||
|
from chat.eventlog.log import append_event
|
||||||
|
from chat.eventlog.projector import project
|
||||||
|
import chat.state.world # registers handlers
|
||||||
|
from chat.state.world import (
|
||||||
|
active_scene,
|
||||||
|
find_container,
|
||||||
|
get_activity,
|
||||||
|
get_chat,
|
||||||
|
get_container,
|
||||||
|
get_scene,
|
||||||
|
list_chats,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_payload(**overrides):
|
||||||
|
payload = {
|
||||||
|
"id": "chat_bot_a",
|
||||||
|
"host_bot_id": "bot_a",
|
||||||
|
"guest_bot_id": None,
|
||||||
|
"initial_time": "2026-04-26T20:00:00+00:00",
|
||||||
|
"narrative_anchor": "Day 1 evening",
|
||||||
|
"weather": "clear",
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _container_payload(**overrides):
|
||||||
|
payload = {
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"name": "office",
|
||||||
|
"type": "workplace",
|
||||||
|
"properties": {
|
||||||
|
"public": True,
|
||||||
|
"moving": False,
|
||||||
|
"audible_range": "normal",
|
||||||
|
"slots": [],
|
||||||
|
},
|
||||||
|
"parent_id": None,
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_created_initializes_chats_and_chat_state(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
project(conn)
|
||||||
|
chat = get_chat(conn, "chat_bot_a")
|
||||||
|
assert chat is not None
|
||||||
|
assert chat["id"] == "chat_bot_a"
|
||||||
|
assert chat["host_bot_id"] == "bot_a"
|
||||||
|
assert chat["guest_bot_id"] is None
|
||||||
|
assert chat["time"] == "2026-04-26T20:00:00+00:00"
|
||||||
|
assert chat["weather"] == "clear"
|
||||||
|
assert chat["narrative_anchor"] == "Day 1 evening"
|
||||||
|
assert chat["active_scene_id"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_chat_returns_none_for_missing_id(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
assert get_chat(conn, "chat_missing") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_chats_returns_all_joined_rows(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload(
|
||||||
|
id="chat_bot_b", host_bot_id="bot_b",
|
||||||
|
))
|
||||||
|
project(conn)
|
||||||
|
chats = list_chats(conn)
|
||||||
|
assert len(chats) == 2
|
||||||
|
ids = [c["id"] for c in chats]
|
||||||
|
assert ids == sorted(ids)
|
||||||
|
assert all("time" in c for c in chats)
|
||||||
|
|
||||||
|
|
||||||
|
def test_chat_created_with_optional_fields_defaulted(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload={
|
||||||
|
"id": "chat_bot_a",
|
||||||
|
"host_bot_id": "bot_a",
|
||||||
|
"initial_time": "2026-04-26T20:00:00+00:00",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
chat = get_chat(conn, "chat_bot_a")
|
||||||
|
assert chat is not None
|
||||||
|
assert chat["guest_bot_id"] is None
|
||||||
|
assert chat["weather"] == ""
|
||||||
|
assert chat["narrative_anchor"] == ""
|
||||||
|
assert chat["active_scene_id"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_container_created_inserts_and_findable_by_name(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="container_created", payload=_container_payload())
|
||||||
|
project(conn)
|
||||||
|
c = find_container(conn, "chat_bot_a", "office")
|
||||||
|
assert c is not None
|
||||||
|
assert c["name"] == "office"
|
||||||
|
assert c["type"] == "workplace"
|
||||||
|
assert c["chat_id"] == "chat_bot_a"
|
||||||
|
assert c["parent_id"] is None
|
||||||
|
assert c["properties"] == {
|
||||||
|
"public": True,
|
||||||
|
"moving": False,
|
||||||
|
"audible_range": "normal",
|
||||||
|
"slots": [],
|
||||||
|
}
|
||||||
|
# get_container by id also works
|
||||||
|
c2 = get_container(conn, c["id"])
|
||||||
|
assert c2 is not None
|
||||||
|
assert c2["name"] == "office"
|
||||||
|
assert c2["properties"]["public"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_find_container_returns_none_when_missing(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
assert find_container(conn, "chat_bot_a", "nope") is None
|
||||||
|
assert get_container(conn, 999) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_activity_change_inserts_then_replaces(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="container_created", payload=_container_payload())
|
||||||
|
# First activity event then a second for the same entity that supersedes it.
|
||||||
|
append_event(conn, kind="activity_change", payload={
|
||||||
|
"entity_id": "bot_a",
|
||||||
|
"container_id": 1,
|
||||||
|
"slot": "desk_chair",
|
||||||
|
"posture": "sitting",
|
||||||
|
"action": {
|
||||||
|
"verb": "writing email",
|
||||||
|
"interruptible": True,
|
||||||
|
"required_attention": "medium",
|
||||||
|
"expected_duration": "a few minutes",
|
||||||
|
"started_at": "2026-04-26T20:00:00+00:00",
|
||||||
|
},
|
||||||
|
"attention": "the screen",
|
||||||
|
"holding": [],
|
||||||
|
"status": {},
|
||||||
|
})
|
||||||
|
append_event(conn, kind="activity_change", payload={
|
||||||
|
"entity_id": "bot_a",
|
||||||
|
"container_id": 1,
|
||||||
|
"posture": "standing",
|
||||||
|
"action": {"verb": "pacing"},
|
||||||
|
"attention": "the window",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
a = get_activity(conn, "bot_a")
|
||||||
|
assert a is not None
|
||||||
|
assert a["entity_id"] == "bot_a"
|
||||||
|
assert a["container_id"] == 1
|
||||||
|
# second event replaced first
|
||||||
|
assert a["posture"] == "standing"
|
||||||
|
assert a["action"]["verb"] == "pacing"
|
||||||
|
assert a["attention"] == "the window"
|
||||||
|
# only one row exists for that entity
|
||||||
|
count = conn.execute(
|
||||||
|
"SELECT COUNT(*) FROM activity WHERE entity_id = ?", ("bot_a",)
|
||||||
|
).fetchone()[0]
|
||||||
|
assert count == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_activity_change_initial_values_persist_when_only_one_event(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="container_created", payload=_container_payload())
|
||||||
|
append_event(conn, kind="activity_change", payload={
|
||||||
|
"entity_id": "bot_a",
|
||||||
|
"container_id": 1,
|
||||||
|
"slot": "desk_chair",
|
||||||
|
"posture": "sitting",
|
||||||
|
"action": {"verb": "writing email"},
|
||||||
|
"attention": "the screen",
|
||||||
|
"holding": ["pen"],
|
||||||
|
"status": {"hungry": False},
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
a = get_activity(conn, "bot_a")
|
||||||
|
assert a is not None
|
||||||
|
assert a["slot"] == "desk_chair"
|
||||||
|
assert a["posture"] == "sitting"
|
||||||
|
assert a["action"]["verb"] == "writing email"
|
||||||
|
assert a["attention"] == "the screen"
|
||||||
|
assert a["holding"] == ["pen"]
|
||||||
|
assert a["status"] == {"hungry": False}
|
||||||
|
|
||||||
|
|
||||||
|
def test_activity_change_defaults_for_minimal_payload(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="activity_change", payload={
|
||||||
|
"entity_id": "you",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
a = get_activity(conn, "you")
|
||||||
|
assert a is not None
|
||||||
|
assert a["container_id"] is None
|
||||||
|
assert a["slot"] is None
|
||||||
|
assert a["posture"] == ""
|
||||||
|
assert a["action"] == {}
|
||||||
|
assert a["attention"] == ""
|
||||||
|
assert a["holding"] == []
|
||||||
|
assert a["status"] == {}
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_activity_returns_none_for_missing(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
assert get_activity(conn, "ghost") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_scene_opened_marks_active_scene_id(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="container_created", payload=_container_payload())
|
||||||
|
append_event(conn, kind="scene_opened", payload={
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"container_id": 1,
|
||||||
|
"started_at": "2026-04-26T20:00:00+00:00",
|
||||||
|
"participants": ["you", "bot_a"],
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
|
||||||
|
s = active_scene(conn, "chat_bot_a")
|
||||||
|
assert s is not None
|
||||||
|
assert s["chat_id"] == "chat_bot_a"
|
||||||
|
assert s["container_id"] == 1
|
||||||
|
assert s["started_at"] == "2026-04-26T20:00:00+00:00"
|
||||||
|
assert s["ended_at"] is None
|
||||||
|
assert s["significance"] == 0
|
||||||
|
assert s["participants"] == ["you", "bot_a"]
|
||||||
|
|
||||||
|
chat = get_chat(conn, "chat_bot_a")
|
||||||
|
assert chat["active_scene_id"] == s["id"]
|
||||||
|
|
||||||
|
s2 = get_scene(conn, s["id"])
|
||||||
|
assert s2 is not None
|
||||||
|
assert s2["participants"] == ["you", "bot_a"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_scene_closed_clears_active_scene_id_and_records_end(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="container_created", payload=_container_payload())
|
||||||
|
append_event(conn, kind="scene_opened", payload={
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"container_id": 1,
|
||||||
|
"started_at": "2026-04-26T20:00:00+00:00",
|
||||||
|
"participants": ["you", "bot_a"],
|
||||||
|
})
|
||||||
|
# The first scene insert will be id=1 (first row in scenes).
|
||||||
|
append_event(conn, kind="scene_closed", payload={
|
||||||
|
"scene_id": 1,
|
||||||
|
"ended_at": "2026-04-26T21:00:00+00:00",
|
||||||
|
"significance": 2,
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
|
||||||
|
assert active_scene(conn, "chat_bot_a") is None
|
||||||
|
chat = get_chat(conn, "chat_bot_a")
|
||||||
|
assert chat["active_scene_id"] is None
|
||||||
|
s = get_scene(conn, 1)
|
||||||
|
assert s["ended_at"] == "2026-04-26T21:00:00+00:00"
|
||||||
|
assert s["significance"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_scene_closed_significance_defaults_to_zero(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
append_event(conn, kind="chat_created", payload=_chat_payload())
|
||||||
|
append_event(conn, kind="scene_opened", payload={
|
||||||
|
"chat_id": "chat_bot_a",
|
||||||
|
"started_at": "2026-04-26T20:00:00+00:00",
|
||||||
|
"participants": ["you", "bot_a"],
|
||||||
|
})
|
||||||
|
append_event(conn, kind="scene_closed", payload={
|
||||||
|
"scene_id": 1,
|
||||||
|
"ended_at": "2026-04-26T21:00:00+00:00",
|
||||||
|
})
|
||||||
|
project(conn)
|
||||||
|
s = get_scene(conn, 1)
|
||||||
|
assert s["significance"] == 0
|
||||||
|
assert s["ended_at"] == "2026-04-26T21:00:00+00:00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_scene_returns_none_for_missing(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
assert get_scene(conn, 999) is None
|
||||||
|
assert active_scene(conn, "chat_missing") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_schema_version_after_migration_is_7(tmp_path):
|
||||||
|
db = tmp_path / "t.db"
|
||||||
|
apply_migrations(db)
|
||||||
|
with open_db(db) as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT value FROM meta WHERE key = 'schema_version'"
|
||||||
|
).fetchone()
|
||||||
|
assert int(row[0]) == 7
|
||||||
Reference in New Issue
Block a user