import json import os import sqlite3 from collections.abc import Iterator from contextlib import contextmanager from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Optional from afk_developer.cortex.models import FadingMemory, PermanentMemory, ReflectionLog def _parse_cortex_timestamp(raw_timestamp: str) -> datetime: """Read legacy naive Cortex timestamps as UTC alongside new aware values.""" timestamp = datetime.fromisoformat(raw_timestamp) if timestamp.tzinfo is None: return timestamp.replace(tzinfo=UTC) return timestamp.astimezone(UTC) class CortexDB: def __init__(self, db_path: Path, project_name: str): self.db_path = db_path self.project_name = project_name self._fading_write_count = 0 db_path.parent.mkdir(parents=True, exist_ok=True) self._init_schema() @contextmanager def _connect(self) -> Iterator[sqlite3.Connection]: conn = sqlite3.connect(str(self.db_path)) conn.row_factory = sqlite3.Row try: conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA foreign_keys=ON") yield conn conn.commit() except Exception: conn.rollback() raise finally: conn.close() def _init_schema(self): with self._connect() as conn: conn.executescript(""" CREATE TABLE IF NOT EXISTS permanent_memories ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL, content TEXT NOT NULL, project TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS fading_memories ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL, content TEXT NOT NULL, project TEXT NOT NULL, ttl_seconds INTEGER NOT NULL, access_count INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS reflection_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, project TEXT NOT NULL, trigger_count INTEGER NOT NULL, summary TEXT NOT NULL, promoted_ids TEXT NOT NULL DEFAULT '[]', discarded_count INTEGER NOT NULL DEFAULT 0, ran_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS session_stats ( id INTEGER PRIMARY KEY AUTOINCREMENT, project TEXT NOT NULL, prompt_tokens INTEGER NOT NULL DEFAULT 0, completion_tokens INTEGER NOT NULL DEFAULT 0, total_tokens INTEGER NOT NULL DEFAULT 0, cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_write_tokens INTEGER NOT NULL DEFAULT 0, reasoning_tokens INTEGER NOT NULL DEFAULT 0, api_calls INTEGER NOT NULL DEFAULT 0, total_turns INTEGER NOT NULL DEFAULT 0, copilot_prompts_submitted INTEGER NOT NULL DEFAULT 0, copilot_usage_available INTEGER NOT NULL DEFAULT 0, copilot_nano_aiu REAL NOT NULL DEFAULT 0, copilot_ai_credits REAL NOT NULL DEFAULT 0, copilot_metered_value_usd REAL NOT NULL DEFAULT 0, model_usage_json TEXT NOT NULL DEFAULT '[]', tasks_completed INTEGER NOT NULL DEFAULT 0, tasks_failed INTEGER NOT NULL DEFAULT 0, elapsed_seconds REAL NOT NULL DEFAULT 0, saved_at TEXT NOT NULL ); """) self._ensure_session_stats_columns(conn) @staticmethod def _ensure_session_stats_columns(conn: sqlite3.Connection) -> None: """Add session-stat columns for databases created by older AFK releases.""" existing = {row["name"] for row in conn.execute("PRAGMA table_info(session_stats)")} additions = { "cache_read_tokens": "INTEGER NOT NULL DEFAULT 0", "cache_write_tokens": "INTEGER NOT NULL DEFAULT 0", "reasoning_tokens": "INTEGER NOT NULL DEFAULT 0", "copilot_prompts_submitted": "INTEGER NOT NULL DEFAULT 0", "copilot_usage_available": "INTEGER NOT NULL DEFAULT 0", "copilot_nano_aiu": "REAL NOT NULL DEFAULT 0", "copilot_ai_credits": "REAL NOT NULL DEFAULT 0", "copilot_metered_value_usd": "REAL NOT NULL DEFAULT 0", "model_usage_json": "TEXT NOT NULL DEFAULT '[]'", } for name, definition in additions.items(): if name not in existing: conn.execute(f"ALTER TABLE session_stats ADD COLUMN {name} {definition}") def write_permanent(self, key: str, content: str) -> PermanentMemory: entry = PermanentMemory(key=key, content=content, project=self.project_name) with self._connect() as conn: cursor = conn.execute( "INSERT INTO permanent_memories (key, content, project, created_at) VALUES (?, ?, ?, ?)", (entry.key, entry.content, entry.project, entry.created_at.isoformat()), ) entry.id = cursor.lastrowid return entry def replace_permanent(self, key: str, content: str) -> PermanentMemory: """Replace a singleton permanent-memory key without accumulating duplicates.""" entry = PermanentMemory(key=key, content=content, project=self.project_name) with self._connect() as conn: conn.execute( "DELETE FROM permanent_memories WHERE key = ? AND project = ?", (entry.key, entry.project), ) cursor = conn.execute( "INSERT INTO permanent_memories (key, content, project, created_at) VALUES (?, ?, ?, ?)", (entry.key, entry.content, entry.project, entry.created_at.isoformat()), ) entry.id = cursor.lastrowid return entry def read_permanent(self, key: str) -> Optional[PermanentMemory]: with self._connect() as conn: row = conn.execute( "SELECT * FROM permanent_memories WHERE key = ? AND project = ? ORDER BY created_at DESC LIMIT 1", (key, self.project_name), ).fetchone() if row is None: return None return PermanentMemory( id=row["id"], key=row["key"], content=row["content"], project=row["project"], created_at=_parse_cortex_timestamp(row["created_at"]), ) def list_permanent(self) -> list[PermanentMemory]: with self._connect() as conn: rows = conn.execute( "SELECT * FROM permanent_memories WHERE project = ? ORDER BY created_at DESC", (self.project_name,), ).fetchall() return [ PermanentMemory( id=r["id"], key=r["key"], content=r["content"], project=r["project"], created_at=_parse_cortex_timestamp(r["created_at"]), ) for r in rows ] def write_fading( self, key: str, content: str, ttl: timedelta = timedelta(hours=24) ) -> FadingMemory: entry = FadingMemory(key=key, content=content, project=self.project_name, ttl=ttl) with self._connect() as conn: cursor = conn.execute( "INSERT INTO fading_memories (key, content, project, ttl_seconds, access_count, created_at) VALUES (?, ?, ?, ?, ?, ?)", ( entry.key, entry.content, entry.project, int(entry.ttl.total_seconds()), entry.access_count, entry.created_at.isoformat(), ), ) entry.id = cursor.lastrowid self._fading_write_count += 1 return entry def read_recent_fading(self, limit: int = 10) -> list[FadingMemory]: cutoff = (datetime.now(UTC) - timedelta(hours=24)).isoformat() with self._connect() as conn: rows = conn.execute( "SELECT * FROM fading_memories WHERE project = ? AND created_at > ? ORDER BY created_at DESC LIMIT ?", (self.project_name, cutoff, limit), ).fetchall() return [ FadingMemory( id=r["id"], key=r["key"], content=r["content"], project=r["project"], ttl=timedelta(seconds=r["ttl_seconds"]), access_count=r["access_count"], created_at=_parse_cortex_timestamp(r["created_at"]), ) for r in rows ] def record_reflection(self, summary: str, promoted_ids: list[int], discarded_count: int): trigger = self._fading_write_count log = ReflectionLog( project=self.project_name, trigger_count=trigger, summary=summary, promoted_ids=promoted_ids, discarded_count=discarded_count, ) with self._connect() as conn: conn.execute( "INSERT INTO reflection_log (project, trigger_count, summary, promoted_ids, discarded_count, ran_at) VALUES (?, ?, ?, ?, ?, ?)", ( log.project, log.trigger_count, log.summary, json.dumps(log.promoted_ids), log.discarded_count, log.ran_at.isoformat(), ), ) def delete_expired_fading(self) -> int: cutoff = (datetime.now(UTC) - timedelta(hours=24)).isoformat() with self._connect() as conn: cursor = conn.execute( "DELETE FROM fading_memories WHERE project = ? AND created_at < ?", (self.project_name, cutoff), ) return cursor.rowcount def delete_fading_by_ids(self, ids: list[int]) -> int: if not ids: return 0 placeholders = ",".join("?" * len(ids)) with self._connect() as conn: cursor = conn.execute( f"DELETE FROM fading_memories WHERE id IN ({placeholders})", ids, ) return cursor.rowcount def needs_reflection(self, interval: int = 5) -> bool: return self._fading_write_count > 0 and self._fading_write_count % interval == 0 def save_session(self, stats: dict) -> None: with self._connect() as conn: conn.execute( """INSERT INTO session_stats (project, prompt_tokens, completion_tokens, total_tokens, cache_read_tokens, cache_write_tokens, reasoning_tokens, api_calls, total_turns, copilot_prompts_submitted, copilot_usage_available, copilot_nano_aiu, copilot_ai_credits, copilot_metered_value_usd, model_usage_json, tasks_completed, tasks_failed, elapsed_seconds, saved_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", ( self.project_name, stats["prompt_tokens"], stats["completion_tokens"], stats["total_tokens"], stats.get("cache_read_tokens", 0), stats.get("cache_write_tokens", 0), stats.get("reasoning_tokens", 0), stats["api_calls"], stats["total_turns"], stats.get("copilot_prompts_submitted", 0), int(bool(stats.get("copilot_usage_available", False))), stats.get("copilot_nano_aiu", 0.0), stats.get("copilot_ai_credits", 0.0), stats.get("copilot_metered_value_usd", 0.0), json.dumps(stats.get("model_usage", [])), stats["tasks_completed"], stats["tasks_failed"], stats["elapsed_seconds"], datetime.now(UTC).isoformat(), ), ) def list_sessions(self, limit: int = 20) -> list[dict]: with self._connect() as conn: rows = conn.execute( "SELECT * FROM session_stats WHERE project = ? ORDER BY saved_at DESC LIMIT ?", (self.project_name, limit), ).fetchall() return [dict(r) for r in rows] def list_all_sessions(self, limit: int = 50) -> list[dict]: with self._connect() as conn: rows = conn.execute( "SELECT * FROM session_stats ORDER BY saved_at DESC LIMIT ?", (limit,), ).fetchall() return [dict(r) for r in rows] def compact_state(self, keep_session_stats: int = 100) -> dict[str, int]: """Prune only redundant runner state, then checkpoint and compact SQLite.""" if keep_session_stats < 1: raise ValueError("keep_session_stats must be at least 1.") # Move any outstanding WAL frames into the main database before measuring. # Otherwise the reported size can miss data that SQLite checkpoints while # opening the first maintenance connection. with self._connect() as checkpoint_connection: checkpoint_connection.execute("PRAGMA wal_checkpoint(TRUNCATE)") before_bytes = self.storage_size_bytes() with self._connect() as delete_connection: duplicate_last_plan = delete_connection.execute( """ DELETE FROM permanent_memories WHERE key = 'last-plan' AND project = ? AND id NOT IN ( SELECT id FROM permanent_memories WHERE key = 'last-plan' AND project = ? ORDER BY created_at DESC, id DESC LIMIT 1 ) """, (self.project_name, self.project_name), ).rowcount old_sessions = delete_connection.execute( """ DELETE FROM session_stats WHERE project = ? AND id NOT IN ( SELECT id FROM session_stats WHERE project = ? ORDER BY saved_at DESC, id DESC LIMIT ? ) """, (self.project_name, self.project_name, keep_session_stats), ).rowcount with self._connect() as checkpoint_connection: checkpoint_connection.execute("PRAGMA wal_checkpoint(TRUNCATE)") compact_path = self.db_path.with_name(f"{self.db_path.name}.compact") compact_path.unlink(missing_ok=True) connection = sqlite3.connect(str(self.db_path)) try: # VACUUM while WAL is enabled can leave the compacted image in a # new WAL file instead of reducing the on-disk database. Build a # standalone compact copy, then atomically replace the inactive # database after the connection releases all locks. connection.execute("VACUUM INTO ?", (str(compact_path),)) finally: connection.close() try: for sidecar in ( self.db_path.with_name(f"{self.db_path.name}-wal"), self.db_path.with_name(f"{self.db_path.name}-shm"), ): sidecar.unlink(missing_ok=True) os.replace(compact_path, self.db_path) finally: compact_path.unlink(missing_ok=True) after_bytes = self.storage_size_bytes() return { "duplicate_last_plan_rows": max(duplicate_last_plan, 0), "old_session_rows": max(old_sessions, 0), "before_bytes": before_bytes, "after_bytes": after_bytes, "reclaimed_bytes": max(before_bytes - after_bytes, 0), } def storage_size_bytes(self) -> int: sidecars = ( self.db_path, self.db_path.with_name(f"{self.db_path.name}-wal"), self.db_path.with_name(f"{self.db_path.name}-shm"), ) return sum(path.stat().st_size for path in sidecars if path.exists()) def get_context_for_worker(self, permanent_keys: Optional[list[str]] = None) -> str: parts = [] if permanent_keys: for key in permanent_keys: mem = self.read_permanent(key) if mem: parts.append(f"[Permanent: {key}]\n{mem.content}") else: for mem in self.list_permanent(): parts.append(f"[Permanent: {mem.key}]\n{mem.content}") fading = self.read_recent_fading() if fading: parts.append("--- Recent Context ---") for mem in fading: parts.append(f"[Fading: {mem.key}]\n{mem.content}") return "\n\n".join(parts)