Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(storage): move store import helpers into storage module

Steven Enamakelaa38493a3786
diff --git a/crates/openhuman-core/src/desktop/notifications/store_import.rs b/crates/openhuman-core/src/desktop/notifications/store_import.rs
index d229afd3f5..51e73dfdb1 100644
--- a/crates/openhuman-core/src/desktop/notifications/store_import.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store_import.rs
@@ -106,3 +106,7 @@ fn read_rows(conn: &Connection, workspace: &str) -> Result<Vec<ImportDoc>> {
}
Ok(docs)
}
+
+#[cfg(all(test, feature = "storage-sqlite"))]
+#[path = "store_import_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/desktop/notifications/store_import_tests.rs b/crates/openhuman-core/src/desktop/notifications/store_import_tests.rs
new file mode 100644
index 0000000000..a2a72a65d3
--- /dev/null
+++ b/crates/openhuman-core/src/desktop/notifications/store_import_tests.rs
@@ -0,0 +1,115 @@
+use super::*;
+use crate::desktop::notifications::store as live;
+use crate::desktop::notifications::types::{
+ CoreNotificationCategory, CoreNotificationEvent, IntegrationNotification, NotificationSettings,
+ NotificationStatus,
+};
+use crate::storage::local::{forget, table_names};
+use chrono::{Duration, Utc};
+use tempfile::TempDir;
+
+fn workspace() -> (TempDir, Config, Config) {
+ let dir = TempDir::new().unwrap();
+ let mut classic = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ classic.storage.url = Some("classic".into());
+ let default = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ (dir, classic, default)
+}
+
+fn note(id: &str, provider: &str, secs_ago: i64) -> IntegrationNotification {
+ IntegrationNotification {
+ id: id.to_string(),
+ provider: provider.to_string(),
+ account_id: Some("acct".into()),
+ title: format!("title {id}"),
+ body: format!("body {id}"),
+ raw_payload: serde_json::json!({ "k": id }),
+ importance_score: None,
+ triage_action: None,
+ triage_reason: None,
+ status: NotificationStatus::Unread,
+ received_at: Utc::now() - Duration::seconds(secs_ago),
+ scored_at: None,
+ }
+}
+
+fn event(id: &str, ts: u64) -> CoreNotificationEvent {
+ CoreNotificationEvent {
+ id: id.to_string(),
+ category: CoreNotificationCategory::Agents,
+ title: "Cron job completed".into(),
+ body: "done".into(),
+ deep_link: None,
+ timestamp_ms: ts,
+ actions: None,
+ workspace: None,
+ workspace_revision: None,
+ }
+}
+
+#[test]
+fn legacy_notifications_are_imported_once_through_the_public_api() {
+ let (_dir, classic, default) = workspace();
+ live::insert(&classic, &note("n-old", "slack", 60)).unwrap();
+ live::insert(&classic, &note("n-new", "gmail", 0)).unwrap();
+ live::insert(&classic, &note("n-read", "gmail", 30)).unwrap();
+ live::update_triage(&classic, "n-new", 0.8, "react", "important").unwrap();
+ live::mark_read(&classic, "n-read").unwrap();
+ live::upsert_settings(
+ &classic,
+ &NotificationSettings {
+ provider: "slack".into(),
+ enabled: false,
+ importance_threshold: 0.5,
+ route_to_orchestrator: false,
+ },
+ )
+ .unwrap();
+ live::insert_core_notification(&classic, &event("e1", 1_000)).unwrap();
+ live::insert_core_notification(&classic, &event("e2", 2_000)).unwrap();
+ live::mark_core_notification_read(&classic, "e1").unwrap();
+ let db = live::db_path(&classic);
+
+ let listed = live::list(&default, 10, 0, None, None).unwrap();
+ let ids: Vec<_> = listed.iter().map(|n| n.id.as_str()).collect();
+ assert_eq!(ids, ["n-new", "n-read", "n-old"]);
+ let scored = &listed[0];
+ assert_eq!(scored.importance_score, Some(0.8));
+ assert_eq!(scored.triage_action.as_deref(), Some("react"));
+ assert_eq!(scored.raw_payload["k"], "n-new");
+ assert_eq!(scored.account_id.as_deref(), Some("acct"));
+ assert_eq!(listed[1].status, NotificationStatus::Read);
+ assert_eq!(live::unread_count(&default).unwrap(), 2);
+ let settings = live::get_settings(&default, "slack").unwrap();
+ assert!(!settings.enabled);
+ assert!(!settings.route_to_orchestrator);
+ assert!((settings.importance_threshold - 0.5).abs() < f32::EPSILON);
+ let core = live::list_core_notifications(&default, false, 10).unwrap();
+ let core_ids: Vec<_> = core.iter().map(|e| e.id.as_str()).collect();
+ assert_eq!(core_ids, ["e2", "e1"]);
+ assert_eq!(live::unread_core_notification_count(&default).unwrap(), 1);
+
+ let tables = table_names(&db);
+ for name in [
+ "integration_notifications",
+ "notification_settings",
+ "core_notifications",
+ ] {
+ assert!(tables.contains(&format!("_legacy_{name}")), "{name}");
+ assert!(!tables.contains(&name.to_string()), "{name} was renamed");
+ }
+
+ // A restart does not import again.
+ live::mark_dismissed(&default, "n-old").unwrap();
+ forget(&db);
+ let after = live::list(&default, 10, 0, None, None).unwrap();
+ let old = after.iter().find(|n| n.id == "n-old").unwrap();
+ assert_eq!(old.status, NotificationStatus::Dismissed);
+ assert_eq!(after.len(), 3);
+}
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import.rs b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
index 9c4d86affe..e1b691c588 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store_import.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
@@ -90,3 +90,7 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
}
Ok(docs)
}
+
+#[cfg(all(test, feature = "storage-sqlite"))]
+#[path = "store_import_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs b/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs
new file mode 100644
index 0000000000..f0351e0724
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs
@@ -0,0 +1,112 @@
+use super::*;
+use crate::integrations::composio::providers::NormalizedTask;
+use crate::integrations::task_sources::store as live;
+use crate::integrations::task_sources::types::{FilterSpec, ProviderSlug, SourceTarget};
+use crate::storage::local::{forget, table_names};
+use serde_json::json;
+use tempfile::TempDir;
+
+fn workspace() -> (TempDir, Config, Config) {
+ let dir = TempDir::new().unwrap();
+ let mut classic = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ classic.storage.url = Some("classic".into());
+ let default = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ (dir, classic, default)
+}
+
+fn filter() -> FilterSpec {
+ FilterSpec::Github {
+ repo: Some("tinyhumansai/openhuman".into()),
+ labels: vec!["bug".into()],
+ assignee_is_me: true,
+ state: Some("open".into()),
+ fetch_mode: Default::default(),
+ extra: json!({}),
+ }
+}
+
+fn task(external_id: &str, title: &str) -> NormalizedTask {
+ NormalizedTask {
+ external_id: external_id.into(),
+ provider: "github".into(),
+ title: title.into(),
+ ..Default::default()
+ }
+}
+
+#[test]
+fn legacy_sources_and_ledger_are_imported_once_through_the_public_api() {
+ let (_dir, classic, default) = workspace();
+ let first = live::add_source(
+ &classic,
+ ProviderSlug::Github,
+ Some("conn-1".into()),
+ Some("My issues".into()),
+ filter(),
+ 1800,
+ SourceTarget::AgentTodoProactive,
+ 25,
+ )
+ .unwrap();
+ let second = live::add_source(
+ &classic,
+ ProviderSlug::Github,
+ None,
+ None,
+ filter(),
+ 600,
+ SourceTarget::AgentTodoProactive,
+ 10,
+ )
+ .unwrap();
+ live::mark_ingested(&classic, &first.id, &task("t-1", "First")).unwrap();
+ live::mark_ingested(&classic, &first.id, &task("t-2", "Second")).unwrap();
+ live::mark_ingested(&classic, &second.id, &task("t-1", "Other")).unwrap();
+ live::record_fetch(
+ &classic,
+ &first.id,
+ chrono::Utc::now(),
+ super::super::types::FetchReason::Periodic,
+ "ok",
+ )
+ .unwrap();
+ let db = live::db_path(&classic);
+
+ let sources = live::list_sources(&default).unwrap();
+ assert_eq!(sources.len(), 2);
+ let got = live::get_source(&default, &first.id).unwrap();
+ assert_eq!(got.name.as_deref(), Some("My issues"));
+ assert_eq!(got.connection_id.as_deref(), Some("conn-1"));
+ assert_eq!(got.interval_secs, 1800);
+ assert_eq!(got.max_tasks_per_fetch, 25);
+ assert_eq!(got.filter, filter());
+ assert!(got.last_fetch_at.is_some());
+ assert_eq!(got.last_status.as_deref(), Some("periodic: ok"));
+ assert!(live::was_ingested(&default, &first.id, "t-1").unwrap());
+ assert!(live::was_ingested(&default, &second.id, "t-1").unwrap());
+ assert!(live::is_ingested(&default, &first.id, "t-1", &live::content_hash(&task("t-1", "First"))).unwrap());
+ let titles: Vec<_> = live::list_ingested(&default, &first.id, 10)
+ .unwrap()
+ .into_iter()
+ .map(|t| t.title)
+ .collect();
+ assert_eq!(titles.len(), 2);
+ assert!(titles.contains(&"First".to_string()));
+ assert_eq!(live::list_ingested_refs(&default, &first.id).unwrap().len(), 2);
+
+ let tables = table_names(&db);
+ assert!(tables.contains(&"_legacy_task_sources".to_string()));
+ assert!(tables.contains(&"_legacy_ingested_tasks".to_string()));
+ assert!(!tables.contains(&"task_sources".to_string()));
+
+ // A restart does not import again.
+ live::remove_source(&default, &second.id).unwrap();
+ forget(&db);
+ assert_eq!(live::list_sources(&default).unwrap().len(), 1);
+}
diff --git a/crates/openhuman-core/src/security/approval/store_import.rs b/crates/openhuman-core/src/security/approval/store_import.rs
index b514c04b88..86a5d2f3d4 100644
--- a/crates/openhuman-core/src/security/approval/store_import.rs
+++ b/crates/openhuman-core/src/security/approval/store_import.rs
@@ -123,3 +123,7 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
}
Ok(docs)
}
+
+#[cfg(all(test, feature = "storage-sqlite"))]
+#[path = "store_import_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/security/approval/store_import_tests.rs b/crates/openhuman-core/src/security/approval/store_import_tests.rs
new file mode 100644
index 0000000000..da79507e49
--- /dev/null
+++ b/crates/openhuman-core/src/security/approval/store_import_tests.rs
@@ -0,0 +1,132 @@
+use super::*;
+use crate::security::approval::store as live;
+use crate::security::approval::types::{
+ ApprovalDecision, ApprovalSourceContext, ExecutionOutcome, PendingApproval,
+};
+use crate::storage::local::{forget, table_names};
+use chrono::{Duration, Utc};
+use serde_json::json;
+use tempfile::TempDir;
+
+fn workspace() -> (TempDir, Config, Config) {
+ let dir = TempDir::new().unwrap();
+ let mut classic = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ classic.storage.url = Some("classic".into());
+ let default = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ (dir, classic, default)
+}
+
+fn request(id: &str, expires_in: i64) -> PendingApproval {
+ PendingApproval {
+ request_id: id.to_string(),
+ tool_name: "composio".to_string(),
+ action_summary: format!("summary {id}"),
+ args_redacted: json!({ "action": "execute", "id": id }),
+ created_at: Utc::now(),
+ expires_at: Some(Utc::now() + Duration::minutes(expires_in)),
+ source_context: Some(ApprovalSourceContext::Flow {
+ flow_id: "flow-1".into(),
+ run_id: "run-1".into(),
+ node_id: None,
+ }),
+ tool_call_id: Some(format!("call-{id}")),
+ agent_id: Some("agent-7".into()),
+ }
+}
+
+#[test]
+fn legacy_rows_are_imported_once_through_the_public_api() {
+ let (_dir, classic, default) = workspace();
+ // Build the legacy database with the legacy code.
+ live::insert_pending(&classic, &request("pending-1", 10), "sess").unwrap();
+ live::insert_pending(&classic, &request("approved-1", 10), "sess").unwrap();
+ live::insert_pending(&classic, &request("denied-1", 10), "sess").unwrap();
+ live::insert_pending(&classic, &request("stale-1", -5), "sess").unwrap();
+ live::decide(&classic, "approved-1", ApprovalDecision::Approve).unwrap();
+ live::record_execution(&classic, "approved-1", ExecutionOutcome::Success, None).unwrap();
+ live::decide(&classic, "denied-1", ApprovalDecision::Deny).unwrap();
+ live::insert_flow_trust(&classic, "flow-1", "shell").unwrap();
+ live::insert_flow_trust(&classic, "flow-1", "http").unwrap();
+ live::record_flow_preauthorization(&classic, "flow-2", "shell", "sess").unwrap();
+ let db = live::db_path(&classic);
+ assert!(table_names(&db).contains(&"pending_approvals".to_string()));
+
+ // The default opens the same file and sees every row.
+ let pending = live::list_pending(&default).unwrap();
+ let mut ids: Vec<_> = pending.iter().map(|p| p.request_id.as_str()).collect();
+ ids.sort_unstable();
+ assert_eq!(ids, ["pending-1", "stale-1"]);
+ let first = pending.iter().find(|p| p.request_id == "pending-1").unwrap();
+ assert_eq!(first.tool_name, "composio");
+ assert_eq!(first.action_summary, "summary pending-1");
+ assert_eq!(first.args_redacted["id"], "pending-1");
+ assert_eq!(first.tool_call_id.as_deref(), Some("call-pending-1"));
+ assert_eq!(first.agent_id.as_deref(), Some("agent-7"));
+ assert!(matches!(
+ first.source_context,
+ Some(ApprovalSourceContext::Flow { ref flow_id, .. }) if flow_id == "flow-1"
+ ));
+ assert_eq!(
+ live::get_decision(&default, "approved-1").unwrap(),
+ Some(ApprovalDecision::Approve)
+ );
+ assert_eq!(
+ live::get_decision(&default, "denied-1").unwrap(),
+ Some(ApprovalDecision::Deny)
+ );
+ let audit = live::list_recent_decisions(&default, 10).unwrap();
+ let mut audited: Vec<_> = audit.iter().map(|a| a.decision).collect();
+ audited.sort_by_key(|d| d.as_str());
+ assert_eq!(audit.len(), 3, "approve, deny and the flow pre-authorization");
+ assert!(audited.contains(&ApprovalDecision::ApproveAlwaysForFlow));
+ assert!(live::is_flow_tool_trusted(&default, "flow-1", "shell").unwrap());
+ assert!(live::is_flow_tool_trusted(&default, "flow-1", "http").unwrap());
+ assert!(!live::is_flow_tool_trusted(&default, "flow-2", "http").unwrap());
+ // The expiry key was imported: the stale request expires.
+ assert_eq!(live::expire_stale(&default).unwrap(), 1);
+
+ // The old tables are kept under their retired names.
+ let tables = table_names(&db);
+ assert!(tables.contains(&"_legacy_pending_approvals".to_string()));
+ assert!(tables.contains(&"_legacy_flow_tool_trust".to_string()));
+ assert!(!tables.contains(&"pending_approvals".to_string()));
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ let kept: i64 = conn
+ .query_row("SELECT COUNT(*) FROM _legacy_pending_approvals", [], |r| {
+ r.get(0)
+ })
+ .unwrap();
+ assert_eq!(kept, 5);
+
+ // A restart does not import again: a change made since stays made.
+ live::decide(&default, "pending-1", ApprovalDecision::Deny).unwrap();
+ forget(&db);
+ assert_eq!(
+ live::get_decision(&default, "pending-1").unwrap(),
+ Some(ApprovalDecision::Deny)
+ );
+ assert!(live::list_pending(&default).unwrap().is_empty());
+}
+
+#[test]
+fn a_workspace_with_no_legacy_file_starts_empty() {
+ let (_dir, _classic, default) = workspace();
+ assert!(live::list_pending(&default).unwrap().is_empty());
+ assert!(!table_names(&live::db_path(&default))
+ .iter()
+ .any(|t| t.starts_with("_legacy_")));
+}
+
+#[test]
+fn the_classic_opt_out_keeps_the_legacy_tables() {
+ let (_dir, classic, _default) = workspace();
+ live::insert_pending(&classic, &request("a", 10), "sess").unwrap();
+ assert_eq!(live::list_pending(&classic).unwrap().len(), 1);
+ assert!(table_names(&live::db_path(&classic)).contains(&"pending_approvals".to_string()));
+}
diff --git a/crates/openhuman-core/src/security/devices/store_import.rs b/crates/openhuman-core/src/security/devices/store_import.rs
index f695e26a25..9ea46fb69d 100644
--- a/crates/openhuman-core/src/security/devices/store_import.rs
+++ b/crates/openhuman-core/src/security/devices/store_import.rs
@@ -53,3 +53,7 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
rows.map(|row| row.context("[devices::import] decode a paired_devices row"))
.collect()
}
+
+#[cfg(all(test, feature = "storage-sqlite"))]
+#[path = "store_import_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/security/devices/store_import_tests.rs b/crates/openhuman-core/src/security/devices/store_import_tests.rs
new file mode 100644
index 0000000000..87d6f5c995
--- /dev/null
+++ b/crates/openhuman-core/src/security/devices/store_import_tests.rs
@@ -0,0 +1,55 @@
+use super::*;
+use crate::security::devices::store as live;
+use crate::storage::local::{forget, table_names};
+use tempfile::TempDir;
+
+fn workspace() -> (TempDir, Config, Config) {
+ let dir = TempDir::new().unwrap();
+ let mut classic = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ classic.storage.url = Some("classic".into());
+ let default = Config {
+ workspace_dir: dir.path().to_path_buf(),
+ ..Config::default()
+ };
+ (dir, classic, default)
+}
+
+#[test]
+fn legacy_devices_are_imported_once_through_the_public_api() {
+ let (_dir, classic, default) = workspace();
+ live::insert_device(&classic, "chan-a", "Phone", "pk-a", "hash-a").unwrap();
+ live::insert_device(&classic, "chan-b", "Tablet", "pk-b", "hash-b").unwrap();
+ live::insert_device(&classic, "chan-c", "Old laptop", "pk-c", "hash-c").unwrap();
+ live::touch_device(&classic, "chan-a").unwrap();
+ live::revoke_device(&classic, "chan-c").unwrap();
+ let db = live::db_path(&classic);
+
+ let listed = live::list_devices(&default).unwrap();
+ let labels: Vec<_> = listed.iter().map(|d| d.label.as_str()).collect();
+ assert_eq!(labels, ["Phone", "Tablet"]);
+ let phone = live::get_device(&default, "chan-a").unwrap().unwrap();
+ assert_eq!(phone.device_pubkey, "pk-a");
+ assert!(phone.last_seen_at.is_some(), "last_seen_at survives");
+ assert!(!phone.revoked);
+ let tablet = live::get_device(&default, "chan-b").unwrap().unwrap();
+ assert!(tablet.last_seen_at.is_none());
+ let old = live::get_device(&default, "chan-c").unwrap().unwrap();
+ assert!(old.revoked, "a revoked device stays revoked");
+
+ let tables = table_names(&db);
+ assert!(tables.contains(&"_legacy_paired_devices".to_string()));
+ assert!(!tables.contains(&"paired_devices".to_string()));
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ let kept: i64 = conn
+ .query_row("SELECT COUNT(*) FROM _legacy_paired_devices", [], |r| r.get(0))
+ .unwrap();
+ assert_eq!(kept, 3);
+
+ // A restart does not import again.
+ live::revoke_device(&default, "chan-b").unwrap();
+ forget(&db);
+ assert_eq!(live::list_devices(&default).unwrap().len(), 1);
+}
diff --git a/crates/openhuman-core/src/storage/README.md b/crates/openhuman-core/src/storage/README.md
index 165916b360..02ba278909 100644
--- a/crates/openhuman-core/src/storage/README.md
+++ b/crates/openhuman-core/src/storage/README.md
@@ -5,9 +5,21 @@ The process's storage backend on the
ports, vendored through `vendor/tinyagents/vendor/tinystoragedrivers`.
One URL picks it: `OPENHUMAN_STORAGE_URL`, else `[storage] url` in
-`config.toml` (`config::StorageConfig`). With neither set, the desktop
-default, nothing is opened and every domain keeps the classic on-disk layout
-under the workspace.
+`config.toml` (`config::StorageConfig`), else the default,
+`sqlite:<workspace_dir>` (`storage::config`).
+
+The default installs no process-wide backend. The large relational stores
+(`sessions.db`, `flows.db`, `jobs.db`, `graph_checkpoints.db`) keep serving
+their own SQLite files as they always have, so nothing is migrated or
+duplicated. The small stores (approvals, devices, notifications, task
+sources) keep their rows as document tables inside their existing `.db` file
+(`approval/approval.db`, `devices/devices.db`, `notifications/notifications.db`,
+`task_sources/sources.db`): the first call in a process opens it with the
+SQLite driver and `storage::local` imports the rows of the old tables, then
+renames them to `_legacy_<name>` and keeps them for one release. The legacy
+code paths stay for reading old data during that import, for builds without
+`storage-sqlite`, for SaaS, and for the opt-out: `OPENHUMAN_STORAGE_URL=classic`
+(or `[storage] url = "classic"`) keeps the pure legacy tables untouched.
| URL | Driver | Cargo feature |
| --- | --- | --- |
@@ -16,9 +28,10 @@ under the workspace.
| `mongodb://…/<db>`, `mongodb+srv://…/<db>` | MongoDB, one database shared by every scope | `storage-mongodb` |
| `file:<dir>` | JSON and JSONL files | `storage-file` |
-A URL for a driver the build lacks fails at `open`, naming the feature. None
-of the features are in the shipped desktop product yet; a cloud build turns
-on `storage-mongodb`.
+A URL for a driver the build lacks fails at `open`, naming the feature.
+`storage-sqlite` is a default feature and in the shipped product; `file` is
+always compiled in; `storage-mongodb` is in neither, a cloud build turns it
+on.
## Entry points
diff --git a/crates/openhuman-core/src/storage/local.rs b/crates/openhuman-core/src/storage/local.rs
index 7f73d7bd6c..b5f4a8fc9c 100644
--- a/crates/openhuman-core/src/storage/local.rs
+++ b/crates/openhuman-core/src/storage/local.rs
@@ -254,6 +254,29 @@ fn import(
Ok(written)
}
+/// Forgets that `db_path` was opened, so the next call opens (and imports)
+/// it afresh: how a test models a restart.
+#[cfg(all(test, feature = "storage-sqlite"))]
+pub(crate) fn forget(db_path: &Path) {
+ OPENED
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .remove(db_path);
+}
+
+/// The names of `db_path`'s tables, sorted (test inspection).
+#[cfg(test)]
+pub(crate) fn table_names(db_path: &Path) -> Vec<String> {
+ let conn = Connection::open(db_path).unwrap();
+ let mut stmt = conn
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
+ .unwrap();
+ stmt.query_map([], |row| row.get(0))
+ .unwrap()
+ .map(Result::unwrap)
+ .collect()
+}
+
/// Whether `table` exists on `conn`.
pub fn table_exists(conn: &Connection, table: &str) -> rusqlite::Result<bool> {
conn.query_row(
diff --git a/crates/openhuman-core/src/storage/local_tests.rs b/crates/openhuman-core/src/storage/local_tests.rs
new file mode 100644
index 0000000000..cea56e8d3a
--- /dev/null
+++ b/crates/openhuman-core/src/storage/local_tests.rs
@@ -0,0 +1,122 @@
+use super::*;
+use crate::storage::documents::Repo;
+use serde_json::json;
+use tempfile::TempDir;
+
+const TABLES: &[&str] = &["old_things"];
+
+fn collections() -> Vec<CollectionSpec> {
+ vec![CollectionSpec::new("things")]
+}
+
+fn legacy_file(dir: &TempDir) -> std::path::PathBuf {
+ let path = dir.path().join("things.db");
+ let conn = Connection::open(&path).unwrap();
+ conn.execute_batch(
+ "CREATE TABLE old_things (id TEXT PRIMARY KEY, n INTEGER);
+ INSERT INTO old_things VALUES ('a', 1), ('b', 2);",
+ )
+ .unwrap();
+ path
+}
+
+fn config(url: Option<&str>) -> Config {
+ let mut config = Config::default();
+ config.storage.url = url.map(str::to_string);
+ config
+}
+
+fn plan(path: &std::path::Path) -> Vec<ImportDoc> {
+ let conn = Connection::open(path).unwrap();
+ let mut stmt = conn.prepare("SELECT id, n FROM old_things ORDER BY id").unwrap();
+ stmt.query_map([], |row| {
+ Ok(ImportDoc {
+ collection: "things",
+ id: row.get(0)?,
+ doc: json!({ "n": row.get::<_, i64>(1)? }),
+ })
+ })
+ .unwrap()
+ .map(Result::unwrap)
+ .collect()
+}
+
+fn open_things(config: &Config, path: &std::path::Path) -> Option<Opened> {
+ let read = || Ok(plan(path));
+ open(
+ config,
+ path,
+ collections,
+ &ImportPlan {
+ domain: "things",
+ tables: TABLES,
+ read: &read,
+ },
+ )
+ .unwrap()
+}
+
+#[test]
+fn the_default_imports_then_retires_the_old_table() {
+ let dir = TempDir::new().unwrap();
+ let path = legacy_file(&dir);
+ let opened = open_things(&config(None), &path).expect("default mode opens the file");
+ assert_eq!(opened.scope, Scope::local());
+ let repo = Repo::on(&opened.backend, &opened.scope, "things", collections).unwrap();
+ let got = repo
+ .run(|docs| async move { docs.get("things", "b").await })
+ .unwrap()
+ .unwrap();
+ assert_eq!(got.doc, json!({ "n": 2 }));
+ let tables = table_names(&path);
+ assert!(tables.contains(&"_legacy_old_things".to_string()));
+ assert!(!tables.contains(&"old_things".to_string()));
+}
+
+#[test]
+fn a_retired_name_already_taken_gets_a_numeric_suffix() {
+ let dir = TempDir::new().unwrap();
+ let path = legacy_file(&dir);
+ Connection::open(&path)
+ .unwrap()
+ .execute_batch("CREATE TABLE _legacy_old_things (x)")
+ .unwrap();
+ open_things(&config(None), &path).unwrap();
+ let tables = table_names(&path);
+ assert!(tables.contains(&"_legacy_old_things".to_string()));
+ assert!(tables.contains(&"_legacy_old_things_2".to_string()));
+}
+
+#[test]
+fn classic_and_the_empty_file_do_not_import() {
+ let dir = TempDir::new().unwrap();
+ let path = legacy_file(&dir);
+ assert!(open_things(&config(Some("classic")), &path).is_none());
+ assert!(table_names(&path).contains(&"old_things".to_string()));
+ // An explicit URL that nothing installed keeps the legacy tables too.
+ assert!(open_things(&config(Some("memory")), &path).is_none());
+
+ let empty = dir.path().join("empty.db");
+ assert!(open_things(&config(None), &empty).is_some());
+}
+
+#[test]
+fn an_import_that_cannot_read_is_retried_not_remembered() {
+ let dir = TempDir::new().unwrap();
+ let path = legacy_file(&dir);
+ let fails = || -> Result<Vec<ImportDoc>> { Err(anyhow!("boom")) };
+ let failing = ImportPlan {
+ domain: "things",
+ tables: TABLES,
+ read: &fails,
+ };
+ let opened = open(&config(None), &path, collections, &failing).unwrap();
+ assert!(opened.is_some(), "the store stays usable");
+ assert!(
+ table_names(&path).contains(&"old_things".to_string()),
+ "the old table is untouched"
+ );
+ // The next call imports properly.
+ open_things(&config(None), &path).unwrap();
+ assert!(table_names(&path).contains(&"_legacy_old_things".to_string()));
+}
diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rs
index 8b12888862..a3b5b5b556 100644
--- a/crates/openhuman-core/src/storage/mod.rs
+++ b/crates/openhuman-core/src/storage/mod.rs
@@ -2,9 +2,12 @@
//!
//! One URL picks where durable state that has moved onto the storage ports
//! lives: `OPENHUMAN_STORAGE_URL`, else `[storage] url` in `config.toml`
-//! ([`crate::config::StorageConfig`]). With neither set — the desktop default —
-//! nothing here is opened and every domain keeps the classic on-disk layout
-//! under the workspace.
+//! ([`crate::config::StorageConfig`]), else the default
+//! ([`config::StorageMode`]). The default installs no backend: the large
+//! stores keep their SQLite files, and the small ones (approvals, devices,
+//! notifications, task sources) keep document tables inside their own `.db`
+//! files, importing their old tables on first open ([`local`]). The value
+//! `classic` opts out to the pure legacy layout.
//!
//! When a URL is set, the host opens it once at startup ([`open`]) and
//! installs it ([`install`]); domains reach it through [`installed`] and bind