use agentstategraph_core::{Commit, Epoch, Namespace, Object, ObjectId, Session, SessionStatus};
use agentstategraph_reminders::ReminderStore;
use chrono::{DateTime, Utc};
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
#[error("object not found: {0}")]
ObjectNotFound(String),
#[error("commit not found: {0}")]
CommitNotFound(String),
#[error("ref not found: {0}")]
RefNotFound(String),
#[error("namespace not found: '{0}' (create it with create_namespace before writing refs)")]
NamespaceNotFound(String),
#[error("namespace already exists: '{0}'")]
NamespaceAlreadyExists(String),
#[error("CAS conflict: ref '{name}' expected {expected}, found {actual}")]
CasConflict {
name: String,
expected: String,
actual: String,
},
#[error("duplicate ref: {0}")]
DuplicateRef(String),
#[error("storage backend error: {0}")]
Backend(String),
#[error("serialization error: {0}")]
Serialization(String),
#[error("epoch '{id}' is already sealed")]
EpochAlreadySealed { id: String },
#[error("session '{id}' has already ended")]
SessionEnded { id: String },
#[error("invalid operation: {0}")]
InvalidOperation(String),
}
impl StorageError {
pub fn code(&self) -> &'static str {
match self {
StorageError::ObjectNotFound(_) => "object_not_found",
StorageError::CommitNotFound(_) => "commit_not_found",
StorageError::RefNotFound(_) => "ref_not_found",
StorageError::NamespaceNotFound(_) => "namespace_not_found",
StorageError::NamespaceAlreadyExists(_) => "namespace_already_exists",
StorageError::CasConflict { .. } => "write_conflict",
StorageError::DuplicateRef(_) => "ref_already_exists",
StorageError::Backend(_) => "storage_error",
StorageError::Serialization(_) => "serialization_error",
StorageError::EpochAlreadySealed { .. } => "epoch_sealed",
StorageError::SessionEnded { .. } => "session_ended",
StorageError::InvalidOperation(_) => "invalid_operation",
}
}
}
pub trait ObjectStore: Send + Sync {
fn get_object(&self, id: &ObjectId) -> Result<Option<Object>, StorageError>;
fn put_object(&self, obj: &Object) -> Result<ObjectId, StorageError>;
fn has_object(&self, id: &ObjectId) -> Result<bool, StorageError>;
fn batch_get_objects(&self, ids: &[ObjectId]) -> Result<Vec<Option<Object>>, StorageError> {
ids.iter().map(|id| self.get_object(id)).collect()
}
fn batch_put_objects(&self, objs: &[Object]) -> Result<Vec<ObjectId>, StorageError> {
objs.iter().map(|obj| self.put_object(obj)).collect()
}
fn leaf_index_is_built(&self, _namespace: &str, _ref_name: &str) -> Result<bool, StorageError> {
Ok(false)
}
fn leaf_index_build(
&self,
_namespace: &str,
_ref_name: &str,
_entries: &[(String, String)],
) -> Result<(), StorageError> {
Ok(())
}
fn leaf_index_apply(
&self,
_namespace: &str,
_ref_name: &str,
_removed_paths: &[String],
_added: &[(String, String)],
) -> Result<(), StorageError> {
Ok(())
}
fn leaf_index_search(
&self,
_namespace: &str,
_ref_name: &str,
_query_lower: &str,
_limit: usize,
) -> Result<Option<Vec<(String, String)>>, StorageError> {
Ok(None)
}
fn leaf_index_tracks_roots(&self) -> bool {
false
}
fn leaf_index_root(
&self,
_namespace: &str,
_ref_name: &str,
) -> Result<Option<ObjectId>, StorageError> {
Ok(None)
}
fn leaf_index_build_at(
&self,
namespace: &str,
ref_name: &str,
_root: &ObjectId,
entries: &[(String, String)],
) -> Result<(), StorageError> {
self.leaf_index_build(namespace, ref_name, entries)
}
fn leaf_index_advance(
&self,
namespace: &str,
ref_name: &str,
_from: &ObjectId,
_to: &ObjectId,
removed_paths: &[String],
added: &[(String, String)],
) -> Result<bool, StorageError> {
self.leaf_index_apply(namespace, ref_name, removed_paths, added)?;
Ok(true)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HistoryRollupRow {
pub day: String,
pub namespace: String,
pub agent_id: String,
pub intent_category: String,
pub commit_count: i64,
pub first_ts: String,
pub last_ts: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HistoryMilestoneRow {
pub commit_id: ObjectId,
pub kind: String,
pub timestamp: String,
pub day: String,
pub namespace: String,
pub agent_id: String,
pub description: String,
pub state_root: Option<ObjectId>,
pub git_sha: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TableBytes {
pub name: String,
pub bytes: i64,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StoreShape {
pub objects: i64,
pub commits: i64,
pub total_bytes: i64,
pub tables: Vec<TableBytes>,
pub dbstat_available: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitTrace {
pub trace_id: String,
pub span_id: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StoreTotals {
pub objects: i64,
pub commits: i64,
pub bytes: Option<i64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GcReachability {
pub total_objects: i64,
pub live_objects: i64,
pub reclaimable_objects: i64,
pub roots_walked: usize,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VacuumStats {
pub bytes_before: i64,
pub bytes_after: i64,
pub bytes_reclaimed: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GcSweep {
pub objects_before: i64,
pub objects_deleted: i64,
pub objects_after: i64,
pub deleted_target: i64,
}
pub const DEFAULT_GC_GRACE: std::time::Duration = std::time::Duration::from_secs(10 * 60);
pub const GC_FRESHEN_AFTER: std::time::Duration = std::time::Duration::from_secs(60);
pub const HISTORY_NAMESPACE_UNKNOWN: &str = "unattributed";
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CommitWalk {
pub commits: Vec<Commit>,
pub truncated: bool,
}
pub trait CommitStore: Send + Sync {
fn get_commit(&self, id: &ObjectId) -> Result<Option<Commit>, StorageError>;
fn put_commit(&self, commit: &Commit) -> Result<(), StorageError>;
fn has_commit(&self, id: &ObjectId) -> Result<bool, StorageError>;
fn list_commits(&self, from: &ObjectId, limit: usize) -> Result<Vec<Commit>, StorageError>;
fn list_commits_dag(&self, from: &ObjectId, limit: usize) -> Result<CommitWalk, StorageError> {
let mut seen: std::collections::HashSet<ObjectId> = std::collections::HashSet::new();
let mut frontier: std::collections::VecDeque<ObjectId> =
std::collections::VecDeque::from([*from]);
let mut commits = Vec::new();
let mut truncated = false;
while let Some(id) = frontier.pop_front() {
if commits.len() >= limit {
truncated = true;
break;
}
if !seen.insert(id) {
continue;
}
match self.get_commit(&id)? {
Some(commit) => {
for p in &commit.parents {
if !seen.contains(p) {
frontier.push_back(*p);
}
}
commits.push(commit);
}
None => continue,
}
}
Ok(CommitWalk { commits, truncated })
}
fn all_commit_ids(&self) -> Result<Vec<ObjectId>, StorageError>;
fn history_extract_batch(&self, _batch_size: usize) -> Result<usize, StorageError> {
Ok(0)
}
fn history_cursor(&self) -> Result<i64, StorageError> {
Ok(0)
}
fn history_rollup(&self) -> Result<Vec<HistoryRollupRow>, StorageError> {
Ok(Vec::new())
}
fn history_milestones(&self, _limit: usize) -> Result<Vec<HistoryMilestoneRow>, StorageError> {
Ok(Vec::new())
}
fn history_store_shape(&self) -> Result<StoreShape, StorageError> {
Ok(StoreShape::default())
}
fn store_totals(&self) -> Result<Option<StoreTotals>, StorageError> {
Ok(None)
}
fn put_commit_traced(
&self,
commit: &Commit,
trace: Option<&CommitTrace>,
) -> Result<(), StorageError> {
self.put_commit(commit)?;
match trace {
Some(trace) => self.set_commit_trace(&commit.id, trace),
None => Ok(()),
}
}
fn set_commit_trace(
&self,
_commit_id: &ObjectId,
_trace: &CommitTrace,
) -> Result<(), StorageError> {
Ok(())
}
fn get_commit_trace(&self, _commit_id: &ObjectId) -> Result<Option<CommitTrace>, StorageError> {
Ok(None)
}
fn history_is_commit_distilled(&self, _id: &ObjectId) -> Result<bool, StorageError> {
Ok(false)
}
fn history_retained_state_roots(&self) -> Result<Vec<ObjectId>, StorageError> {
Ok(Vec::new())
}
fn history_undistilled_commit_count(&self) -> Result<i64, StorageError> {
Ok(0)
}
fn history_gc_reachability(
&self,
_roots: &[ObjectId],
_batch: usize,
) -> Result<GcReachability, StorageError> {
Ok(GcReachability::default())
}
fn history_gc_sweep(
&self,
_roots: &[ObjectId],
_batch: usize,
) -> Result<GcSweep, StorageError> {
Ok(GcSweep::default())
}
fn history_gc_lock_writers(&self) -> Result<(), StorageError> {
Ok(())
}
fn history_gc_unlock_writers(&self, _commit: bool) -> Result<(), StorageError> {
Ok(())
}
fn gc_pin_root(&self, _key: &str, _root: &ObjectId) -> Result<(), StorageError> {
Ok(())
}
fn gc_unpin_root(&self, _key: &str) -> Result<(), StorageError> {
Ok(())
}
fn gc_pinned_roots(
&self,
_max_age: std::time::Duration,
) -> Result<Vec<ObjectId>, StorageError> {
Ok(Vec::new())
}
fn history_unpin_legacy_milestones(&self) -> Result<usize, StorageError> {
Ok(0)
}
fn commit_state_roots_recent_first(&self) -> Result<Vec<ObjectId>, StorageError> {
Ok(Vec::new())
}
fn history_vacuum(&self) -> Result<VacuumStats, StorageError> {
Ok(VacuumStats::default())
}
}
pub trait RefStore: Send + Sync {
fn create_namespace(&self, namespace: &Namespace) -> Result<(), StorageError>;
fn list_namespaces(&self) -> Result<Vec<Namespace>, StorageError>;
fn get_ref(&self, namespace: &Namespace, name: &str) -> Result<Option<ObjectId>, StorageError>;
fn set_ref(
&self,
namespace: &Namespace,
name: &str,
target: ObjectId,
) -> Result<(), StorageError>;
fn cas_ref(
&self,
namespace: &Namespace,
name: &str,
expected: ObjectId,
new: ObjectId,
) -> Result<bool, StorageError>;
fn create_ref(
&self,
namespace: &Namespace,
name: &str,
target: ObjectId,
) -> Result<bool, StorageError> {
if self.get_ref(namespace, name)?.is_some() {
return Ok(false);
}
self.set_ref(namespace, name, target)?;
Ok(true)
}
fn cas_delete_ref(
&self,
namespace: &Namespace,
name: &str,
expected: ObjectId,
) -> Result<bool, StorageError> {
if self.get_ref(namespace, name)? != Some(expected) {
return Ok(false);
}
self.delete_ref(namespace, name)
}
fn list_refs(
&self,
namespace: &Namespace,
prefix: &str,
) -> Result<Vec<(String, ObjectId)>, StorageError>;
fn delete_ref(&self, namespace: &Namespace, name: &str) -> Result<bool, StorageError>;
fn delete_namespace(&self, namespace: &Namespace) -> Result<bool, StorageError>;
}
pub trait EpochStore: Send + Sync {
fn create_epoch(&self, epoch: &Epoch) -> Result<(), StorageError>;
fn seal_epoch(
&self,
id: &str,
summary: &str,
sealed_at: DateTime<Utc>,
sealed_commits: &[ObjectId],
seal_hash: &ObjectId,
) -> Result<(), StorageError>;
fn assign_epoch_namespace(&self, id: &str, namespace: &str) -> Result<bool, StorageError>;
fn list_epochs(&self) -> Result<Vec<Epoch>, StorageError>;
fn get_epoch(&self, id: &str) -> Result<Option<Epoch>, StorageError>;
fn set_commit_epoch(&self, commit_id: &ObjectId, epoch_id: &str) -> Result<(), StorageError>;
fn archive_epoch(&self, id: &str) -> Result<(), StorageError>;
}
pub trait SessionStore: Send + Sync {
fn create_session(&self, session: &Session) -> Result<(), StorageError>;
fn end_session(
&self,
id: &str,
status: SessionStatus,
ended_at: DateTime<Utc>,
) -> Result<(), StorageError>;
fn list_sessions(&self, agent_filter: Option<&str>) -> Result<Vec<Session>, StorageError>;
fn get_session(&self, id: &str) -> Result<Option<Session>, StorageError>;
fn set_commit_session(
&self,
commit_id: &ObjectId,
session_id: &str,
) -> Result<(), StorageError>;
}
pub trait TaintStore: Send + Sync {
fn create_taint(&self, _taint: &agentstategraph_taint::Taint) -> Result<(), StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
fn resolve_taint(
&self,
_id: &str,
_resolved_by: &str,
_reason: &str,
_proof: Option<&str>,
_resolved_at: DateTime<Utc>,
) -> Result<(), StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
fn list_taints(
&self,
_path_prefix: Option<&str>,
_kind: Option<agentstategraph_taint::TaintKind>,
_include_resolved: bool,
) -> Result<Vec<agentstategraph_taint::Taint>, StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
fn check_taint(
&self,
_request_path: &str,
) -> Result<Vec<agentstategraph_taint::Taint>, StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
fn get_taint(&self, _id: &str) -> Result<Option<agentstategraph_taint::Taint>, StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
fn set_taint_commit_id(&self, _id: &str, _commit_id: &str) -> Result<(), StorageError> {
Err(StorageError::Backend("taint storage not supported".into()))
}
}
pub trait Storage:
ObjectStore + CommitStore + RefStore + EpochStore + SessionStore + TaintStore + ReminderStore
{
}
impl<
T: ObjectStore + CommitStore + RefStore + EpochStore + SessionStore + TaintStore + ReminderStore,
> Storage for T
{
}