The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(storage): add layout schema and status tracking
Steven Enamakela580278dc4e1
diff --git a/crates/openhuman-core/src/storage/layout/schemas.rs b/crates/openhuman-core/src/storage/layout/schemas.rsnew file mode 100644index 0000000000..01e72a504d--- /dev/null+++ b/crates/openhuman-core/src/storage/layout/schemas.rs@@ -0,0 +1,121 @@+//! Controllers `storage.migrate`, `storage.status` and `storage.restore`.+//!+//! Registered through `core/all.rs`; the CLI reaches them by the generic+//! namespace dispatch (`openhuman-core storage migrate --dry_run true`).++use serde_json::{Map, Value};++use super::{migrate, restore, status, Options, Target};+use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::runtime::DispatchCtx;+use crate::core::{ControllerSchema, FieldSchema, TypeSchema};++/// Schemas of the storage layout controllers.+pub fn all_controller_schemas() -> Vec<ControllerSchema> {+ vec![schemas("migrate"), schemas("status"), schemas("restore")]+}++/// The registered controllers.+pub fn all_registered_controllers() -> Vec<RegisteredController> {+ vec![+ RegisteredController { schema: schemas("migrate"), handler: handle_migrate },+ RegisteredController { schema: schemas("status"), handler: handle_status },+ RegisteredController { schema: schemas("restore"), handler: handle_restore },+ ]+}++fn field(name: &'static str, ty: TypeSchema, comment: &'static str, required: bool) -> FieldSchema {+ FieldSchema { name, ty, comment, required }+}++/// The schema of `function`.+pub fn schemas(function: &str) -> ControllerSchema {+ match function {+ "migrate" => ControllerSchema {+ namespace: "storage",+ function: "migrate",+ description: "Move the active profile from storage layout v1 (workspace/ files) to layout v2 (one storage.db plus files/). \+ Imports the legacy files, copies and verifies the database, moves user files, archives the originals to \+ <root>/backups/<user>-<timestamp>.tar.zst, then deletes only what was archived. Resumable. \+ dry_run returns the plan and writes nothing. Stop the core before running it for real.",+ inputs: vec![field("dry_run", TypeSchema::Option(Box::new(TypeSchema::Bool)), "Plan only: list what would be archived, moved, deleted and left alone, with byte totals.", false)],+ outputs: vec![field("result", TypeSchema::String, "noop, dry_run or migrated, with the plan or report alongside.", true)],+ },+ "status" => ControllerSchema {+ namespace: "storage",+ function: "status",+ description: "Layout version, schema version per owner, database size and last migration of the active profile. Read-only.",+ inputs: vec![],+ outputs: vec![field("layout_version", TypeSchema::U64, "1 or 2.", true)],+ },+ "restore" => ControllerSchema {+ namespace: "storage",+ function: "restore",+ description: "Put the active profile back to layout v1 from a migration archive: verifies the archive, restores its entries under workspace/, \+ sets the v2 storage.db aside and removes the layout marker.",+ inputs: vec![field("archive", TypeSchema::String, "Path of the .tar.zst archive.", true)],+ outputs: vec![field("entries", TypeSchema::U64, "Top-level entries restored.", true)],+ },+ _ => ControllerSchema {+ namespace: "storage",+ function: "unknown",+ description: "Unknown storage controller function.",+ inputs: vec![field("function", TypeSchema::String, "Unknown function requested for schema lookup.", true)],+ outputs: vec![field("error", TypeSchema::String, "Lookup error details.", true)],+ },+ }+}++async fn target_of(ctx: &DispatchCtx) -> Result<(Target, crate::config::Config), String> {+ let config = ctx.load_config().await?;+ let target = Target::from_config(&config).ok_or_else(|| {+ "this config is not a users/<id> profile, so it has no storage layout to migrate".to_owned()+ })?;+ Ok((target, config))+}++fn env_url() -> Option<String> {+ std::env::var(crate::storage::STORAGE_URL_VAR).ok()+}++fn to_value<T: serde::Serialize>(value: &T) -> Result<Value, String> {+ serde_json::to_value(value).map_err(|e| e.to_string())+}++fn handle_migrate(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let dry_run = match params.get("dry_run") {+ None | Some(Value::Null) => false,+ Some(Value::Bool(b)) => *b,+ Some(other) => return Err(format!("invalid 'dry_run': expected bool, got {other}")),+ };+ let (target, config) = target_of(&ctx).await?;+ let options = Options { dry_run, env_url: env_url(), ..Options::default() };+ let outcome = migrate(&target, &config, &options).await.map_err(|e| e.to_string())?;+ to_value(&outcome)+ })+}++fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let (target, config) = target_of(&ctx).await?;+ let report = status(&target, &config, env_url()).await.map_err(|e| e.to_string())?;+ to_value(&report)+ })+}++fn handle_restore(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let archive = params+ .get("archive")+ .and_then(Value::as_str)+ .ok_or_else(|| "missing required param 'archive'".to_owned())?;+ let (target, _config) = target_of(&ctx).await?;+ let report = restore(&target, std::path::Path::new(archive)).await.map_err(|e| e.to_string())?;+ to_value(&report)+ })+}++#[cfg(test)]+#[path = "schemas_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/storage/layout/status.rs b/crates/openhuman-core/src/storage/layout/status.rsnew file mode 100644index 0000000000..0bd11545ca--- /dev/null+++ b/crates/openhuman-core/src/storage/layout/status.rs@@ -0,0 +1,113 @@+//! `storage.status`: where a profile is in the layout move, read-only.++use std::collections::BTreeMap;++use serde::{Deserialize, Serialize};++use super::state::{LayoutError, LayoutState, Step};+use super::{legacy, Target};+use crate::config::schema::profile_layout::LayoutVersion;+use crate::config::Config;++/// The schema version one owner has reached in the profile's database.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct OwnerVersion {+ /// The schema owner (`threads`, `harness`, ...).+ pub owner: String,+ /// The highest version a finished step wrote.+ pub version: u32,+}++/// A profile's storage state.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct Status {+ /// `1` or `2`.+ pub layout_version: u8,+ /// `users/<id>`.+ pub profile_dir: String,+ /// The database file the profile uses under its layout.+ pub database: Option<String>,+ /// Its size in bytes, when it exists.+ pub database_bytes: Option<u64>,+ /// Schema version per owner, from `tsd.migrations`.+ pub schema_versions: Vec<OwnerVersion>,+ /// When the last migration step finished (ms since the epoch).+ pub last_migration_ms: Option<i64>,+ /// A layout migration was started and not finished.+ pub migration_in_progress: bool,+ /// The steps that finished, when one is in progress.+ pub migration_steps_done: Vec<Step>,+ /// An explicit storage URL names the backend, so the layout move does not+ /// apply (its credentials are not shown).+ pub explicit_url: bool,+}++/// Reads `target`'s status. Nothing is written: the database is opened raw+/// (no schema is prepared or migrated).+///+/// # Errors+///+/// An unreadable progress file. A database that cannot be read reports no+/// versions rather than failing.+pub async fn status(target: &Target, config: &Config, env_url: Option<String>) -> Result<Status, LayoutError> {+ let layout = LayoutVersion::detect(&target.profile_dir);+ let state = LayoutState::load(&target.profile_dir)?;+ let database = match layout {+ LayoutVersion::V2 => target.storage_db(),+ LayoutVersion::V1 => legacy::v1_db(target),+ };+ let meta = std::fs::metadata(&database).ok();+ let (schema_versions, last_migration_ms) = if meta.is_some() {+ read_versions(&database).await.unwrap_or_default()+ } else {+ (Vec::new(), None)+ };+ Ok(Status {+ layout_version: if layout == LayoutVersion::V2 { 2 } else { 1 },+ profile_dir: target.profile_dir.display().to_string(),+ database: meta.as_ref().map(|_| database.display().to_string()),+ database_bytes: meta.map(|m| m.len()),+ schema_versions,+ last_migration_ms,+ migration_in_progress: state.is_some(),+ migration_steps_done: state.map(|s| s.done).unwrap_or_default(),+ explicit_url: matches!(+ crate::storage::config::mode_from(env_url, config),+ crate::storage::config::StorageMode::Url(_)+ ),+ })+}++async fn read_versions(db: &std::path::Path) -> Result<(Vec<OwnerVersion>, Option<i64>), LayoutError> {+ use tinystoragedrivers::schema::Progress;+ use tinystoragedrivers::{DocumentStoreExt, Query, StorageBackend, MIGRATIONS_COLLECTION};+ let url = crate::storage::StorageUrl::parse(&format!("sqlite:{}", db.display()))+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("{e}")))?;+ let backend = tinystoragedrivers::open(&url)+ .await+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("{e}")))?;+ let scoped = backend+ .for_scope(&crate::storage::Scope::local())+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("{e}")))?;+ let rows = scoped+ .documents()+ .query_all(MIGRATIONS_COLLECTION, &Query::all())+ .await+ .map_err(|e| LayoutError::Other(anyhow::anyhow!("{e}")))?;+ let mut owners: BTreeMap<String, u32> = BTreeMap::new();+ let mut last = None::<i64>;+ for row in rows {+ let Ok(progress) = serde_json::from_value::<Progress>(row.doc) else {+ continue;+ };+ if progress.done && progress.to > 0 {+ let version = owners.entry(progress.owner).or_default();+ *version = (*version).max(progress.to);+ last = last.max(Some(row.meta.updated_ms).filter(|ms| *ms > 0));+ }+ }+ Ok((+ owners.into_iter().map(|(owner, version)| OwnerVersion { owner, version }).collect(),+ last,+ ))+}