#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
#[cfg(any(feature = "native", feature = "db"))]
use crate::error::Result;
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct CompactionReport {
pub execution_log_initial_bytes: u64,
pub execution_log_final_bytes: u64,
pub cards_pruned: usize,
pub handles_pruned: usize,
pub history_pruned: usize,
pub documents_optimized: bool,
pub vacuumed: bool,
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn prune_execution_logs(clm_root: &str, max_age_days: u64) -> Result<CompactionReport> {
let mut report = CompactionReport::default();
let db_path = crate::db::get_db_path("execution_log", clm_root);
if !db_path.exists() {
return Ok(report);
}
report.execution_log_initial_bytes = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);
let mut conn = Connection::open(&db_path)?;
conn.busy_timeout(std::time::Duration::from_secs(30))?;
let _ = conn.execute_batch("
DROP TRIGGER IF EXISTS card_delete;
DROP TRIGGER IF EXISTS card_update;
PRAGMA foreign_keys = OFF;
");
let tx = conn.transaction()?;
let handles_pruned = if max_age_days == 0 {
tx.execute(
"DELETE FROM handle_registry WHERE handle LIKE 'run:%' OR handle LIKE 'escalation:%' OR handle LIKE 'tests:%';",
[],
)?
} else {
tx.execute(
"DELETE FROM handle_registry WHERE (handle LIKE 'run:%' OR handle LIKE 'escalation:%' OR handle LIKE 'tests:%') AND created_at < datetime('now', '-' || ?1 || ' days');",
rusqlite::params![max_age_days],
)?
};
report.handles_pruned = handles_pruned;
let history_pruned = if max_age_days == 0 {
tx.execute(
"DELETE FROM handle_history WHERE handle NOT IN (SELECT handle FROM handle_registry);",
[],
)?
} else {
tx.execute(
"DELETE FROM handle_history WHERE handle NOT IN (SELECT handle FROM handle_registry) OR changed_at < datetime('now', '-' || ?1 || ' days');",
rusqlite::params![max_age_days],
)?
};
report.history_pruned = history_pruned;
let cards_pruned = tx.execute(
"DELETE FROM card WHERE hash NOT IN (SELECT current_hash FROM handle_registry);",
[],
)?;
report.cards_pruned = cards_pruned;
tx.commit()?;
let has_docs: bool = conn
.query_row(
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='documents';",
[],
|r| r.get(0),
)
.unwrap_or(0) > 0;
if has_docs {
let _ = conn.execute_batch("
DELETE FROM documents;
INSERT INTO documents(content) SELECT content FROM card;
INSERT INTO documents(documents) VALUES('optimize');
");
report.documents_optimized = true;
}
let _ = conn.execute_batch("
CREATE TRIGGER IF NOT EXISTS card_update AFTER UPDATE ON card
BEGIN
UPDATE documents SET content = new.content
WHERE rowid = (SELECT rowid FROM documents WHERE content = old.content LIMIT 1);
END;
CREATE TRIGGER IF NOT EXISTS card_delete AFTER DELETE ON card
BEGIN
DELETE FROM documents WHERE content = old.content;
END;
CREATE INDEX IF NOT EXISTS idx_handle_history_prev_hash ON handle_history(previous_hash);
PRAGMA foreign_keys = ON;
");
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
let _ = conn.execute_batch("VACUUM;");
report.vacuumed = true;
drop(conn);
report.execution_log_final_bytes = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0);
Ok(report)
}
#[cfg(any(feature = "native", feature = "db"))]
pub fn compact_all(clm_root: &str) -> Result<CompactionReport> {
let pillars = ["content_memory", "agent_identities", "execution_log"];
for pillar in &pillars {
let path = crate::db::get_db_path(pillar, clm_root);
if path.exists() {
if let Ok(conn) = Connection::open(&path) {
let _ = conn.busy_timeout(std::time::Duration::from_secs(30));
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
let _ = conn.execute_batch("VACUUM;");
}
}
}
prune_execution_logs(clm_root, 0)
}