import sqlite3 from datetime import UTC, datetime, timedelta from pathlib import Path from afk_developer.cortex.db import CortexDB from afk_developer.cortex.models import FadingMemory def _stats() -> dict: return { "prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "api_calls": 0, "total_turns": 0, "tasks_completed": 0, "tasks_failed": 0, "elapsed_seconds": 1.0, } def test_replace_permanent_keeps_singleton_memory(tmp_path: Path) -> None: db = CortexDB(tmp_path / "cortex.db", "example") db.write_permanent("last-plan", "old") db.replace_permanent("last-plan", "current") memories = [memory for memory in db.list_permanent() if memory.key == "last-plan"] assert len(memories) == 1 assert memories[0].content == "current" def test_compact_state_prunes_only_redundant_runner_rows(tmp_path: Path) -> None: db = CortexDB(tmp_path / "cortex.db", "example") db.write_permanent("last-plan", "old" + ("x" * 100_000)) db.write_permanent("last-plan", "new") db.write_permanent("important", "retain") for _ in range(3): db.save_session(_stats()) result = db.compact_state(keep_session_stats=1) assert result["duplicate_last_plan_rows"] == 1 assert result["old_session_rows"] == 2 assert result["reclaimed_bytes"] > 0 assert len(db.list_sessions()) == 1 assert db.read_permanent("important").content == "retain" assert db.read_permanent("last-plan").content == "new" def test_session_stats_persists_copilot_usage_and_model_breakdown(tmp_path: Path) -> None: db = CortexDB(tmp_path / "cortex.db", "example") stats = _stats() | { "copilot_prompts_submitted": 1, "copilot_usage_available": True, "copilot_nano_aiu": 1_250_000_000.0, "copilot_ai_credits": 1.25, "copilot_metered_value_usd": 0.0125, "model_usage": [{"endpoint": "copilot", "model": "gpt-5.6-luna"}], } db.save_session(stats) stored = db.list_sessions(limit=1)[0] assert stored["copilot_prompts_submitted"] == 1 assert stored["copilot_usage_available"] == 1 assert stored["copilot_ai_credits"] == 1.25 assert stored["model_usage_json"] == '[{"endpoint": "copilot", "model": "gpt-5.6-luna"}]' def test_existing_cortex_database_migrates_session_stats_columns(tmp_path: Path) -> None: db_path = tmp_path / "cortex.db" connection = sqlite3.connect(db_path) connection.execute( """CREATE TABLE 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, api_calls INTEGER NOT NULL DEFAULT 0, total_turns INTEGER NOT NULL DEFAULT 0, 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 )""" ) connection.commit() connection.close() db = CortexDB(db_path, "example") with db._connect() as connection: columns = {row["name"] for row in connection.execute("PRAGMA table_info(session_stats)")} assert {"copilot_ai_credits", "copilot_metered_value_usd", "model_usage_json"} <= columns def test_cortex_uses_aware_utc_timestamps_and_reads_legacy_records(tmp_path: Path) -> None: db = CortexDB(tmp_path / "cortex.db", "example") memory = db.write_permanent("project-context", "current") db.save_session(_stats()) with db._connect() as connection: saved_at = connection.execute("SELECT saved_at FROM session_stats").fetchone()[0] connection.execute( "INSERT INTO fading_memories " "(key, content, project, ttl_seconds, access_count, created_at) " "VALUES (?, ?, ?, ?, ?, ?)", ( "legacy", "legacy timestamp", "example", 3600, 0, datetime.now(UTC).replace(tzinfo=None).isoformat(), ), ) legacy = next(item for item in db.read_recent_fading() if item.key == "legacy") assert memory.created_at.tzinfo is UTC assert saved_at.endswith("+00:00") assert legacy.created_at.tzinfo is UTC assert FadingMemory( key="legacy-expiry", content="legacy timestamp", project="example", created_at=datetime.now(UTC).replace(tzinfo=None) - timedelta(hours=25), ).is_expired