Skip to content

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

feat(artifacts): keep versioned records in the storage backend

Sanil9da74f1cbe51
diff --git a/crates/openhuman-core/src/agent/artifacts/README.md b/crates/openhuman-core/src/agent/artifacts/README.md
index 763363fdab..6ddf5c2985 100644
--- a/crates/openhuman-core/src/agent/artifacts/README.md
+++ b/crates/openhuman-core/src/agent/artifacts/README.md
@@ -23,7 +23,7 @@ renders artifact content itself.
| [`store.rs`](./store.rs) | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; `create_artifact_regenerating` (explicit regenerate target); `sanitize_filename_stem`. |
| [`ops.rs`](./ops.rs) | RPC business logic returning `Outcome<Value>`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. |
| [`schemas.rs`](./schemas.rs) | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. |
-| [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (the crate's `FsArtifactStore` over `<workspace>/artifacts/versioned/`, one `<id>.json` per artifact), `LegacyUiBridge` (the crate's `ArtifactObserver`: shows each artifact's newest version through the legacy row + events and the files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). |
+| [`tiny_store.rs`](./tiny_store.rs) | OpenHuman's side of the versioned artifacts (`tiny-artifacts`): `versioned_store` (the records, in the configured storage backend: [`version_documents.rs`](./version_documents.rs); files from earlier builds under `<workspace>/artifacts/versioned/` are imported once), `version_files_dir` (each file version's own copy), `LegacyUiBridge` (the crate's `ArtifactObserver`: shows each artifact's newest version through the legacy row + events and the files folder), `artifacts_service`, the agent tools, and `save_operator_version` (the preview panel's autosave). |
| [`production.rs`](./production.rs) | `Production`: how producer tools (deck, document, generated media) file their output — reserve the file and the card, open the versioned record under the same id, then complete or fail it. |
| `*_tests.rs` | Sibling test files for each of the above (`#[path]`). |
diff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rs
index 42f2890595..b107865778 100644
--- a/crates/openhuman-core/src/agent/artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs
@@ -8,6 +8,7 @@ pub mod store;
mod store_documents;
pub mod tiny_store;
pub mod types;
+pub mod version_documents;
pub use files::{resolve_ready_file, FileRoots};
pub use migrate::{migrate_legacy_artifacts, MigrationReport};
diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store.rs
index 58329d80c4..c9baa6549d 100644
--- a/crates/openhuman-core/src/agent/artifacts/tiny_store.rs
+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store.rs
@@ -4,8 +4,8 @@
//! revision goes through its [`Artifacts`] service. OpenHuman supplies the
//! service's ports:
//!
-//! * [`versioned_store`] — the crate's [`FsArtifactStore`] over
-//! `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact);
+//! * [`versioned_store`] — the records, in the configured storage backend
+//! ([`super::version_documents::DocumentArtifactStore`]);
//! * [`LegacyUiBridge`] — the observer that shows each artifact in the
//! desktop UI;
//! * the folders file artifacts may point into: the agent's working folder
@@ -84,12 +84,16 @@ pub(crate) fn legacy_kind_for_extension(ext: &str) -> LegacyArtifactKind {
}
}
-pub use tiny_artifacts::FsArtifactStore;
+/// The versioned records of a workspace, in the configured storage backend
+/// under the acting scope (records an earlier build kept as files under
+/// [`legacy_versioned_dir`] are imported once).
+pub fn versioned_store(workspace_dir: &Path) -> super::version_documents::DocumentArtifactStore {
+ super::version_documents::DocumentArtifactStore::new(workspace_dir)
+}
-/// The versioned records of a workspace: `tiny-artifacts`' file-system store
-/// over `<workspace>/artifacts/versioned/` (one `<id>.json` per artifact).
-pub fn versioned_store(workspace_dir: &Path) -> FsArtifactStore {
- FsArtifactStore::new(workspace_dir.join("artifacts").join(VERSIONED_SUBDIR))
+/// Where an earlier build kept versioned records, one `<id>.json` each.
+pub fn legacy_versioned_dir(workspace_dir: &Path) -> PathBuf {
+ workspace_dir.join("artifacts").join(VERSIONED_SUBDIR)
}
/// Shows versioned artifacts in the desktop UI through the legacy pipeline.
diff --git a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
index d7dd2d0b57..95a4f89c6f 100644
--- a/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
+++ b/crates/openhuman-core/src/agent/artifacts/tiny_store_tests.rs
@@ -14,7 +14,10 @@ fn temp_dirs() -> (PathBuf, PathBuf) {
(workspace, files)
}
-async fn seeded(workspace: &PathBuf, _files: &PathBuf) -> FsArtifactStore {
+async fn seeded(
+ workspace: &PathBuf,
+ _files: &PathBuf,
+) -> crate::agent::artifacts::version_documents::DocumentArtifactStore {
let store = versioned_store(&workspace);
let record = ArtifactRecord::new(
"a-1",
diff --git a/crates/openhuman-core/src/agent/artifacts/version_documents.rs b/crates/openhuman-core/src/agent/artifacts/version_documents.rs
new file mode 100644
index 0000000000..93afb9efde
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/version_documents.rs
@@ -0,0 +1,234 @@
+//! Versioned artifact records on the `tinystoragedrivers` document port.
+//!
+//! [`DocumentArtifactStore`] is OpenHuman's `tiny-artifacts`
+//! [`ArtifactStore`]: each record lives in the installed storage backend (or
+//! the workspace default when none is installed), under the acting agent's
+//! scope, like the rest of the artifact domain (`store_documents.rs`). So a
+//! shared database shares the histories, and a core on another node or after
+//! a cloud restart reads the same versions.
+//!
+//! | Collection | Document id | Holds |
+//! | --- | --- | --- |
+//! | `artifact_versions` | artifact id | the whole `ArtifactRecord`, plus `updated_ms` for ordering |
+//!
+//! Only the records move. A file version's bytes stay in a file
+//! (`ArtifactVersion::file`), as the legacy card's do.
+//!
+//! The first call of a process imports the records an earlier build kept as
+//! `<workspace>/artifacts/versioned/<id>.json` (once per backend instance,
+//! scope and workspace). Only absent records are written, so the import never
+//! overwrites a newer one and is safe to repeat; deleting an artifact removes
+//! its legacy file first, so a restart does not bring it back.
+
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use async_trait::async_trait;
+use serde_json::Value;
+use tiny_artifacts::{ArtifactRecord, ArtifactStore};
+use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};
+
+use crate::storage::documents::Repo;
+use crate::storage::DocumentStoreExt;
+
+const VERSIONS: &str = "artifact_versions";
+const DOMAIN: &str = "artifacts::versions";
+
+fn collections() -> Vec<CollectionSpec> {
+ vec![CollectionSpec::new(VERSIONS)]
+}
+
+/// The versioned records of one workspace, in the configured storage backend.
+#[derive(Clone, Debug)]
+pub struct DocumentArtifactStore {
+ workspace_dir: PathBuf,
+}
+
+impl DocumentArtifactStore {
+ /// The store for `workspace_dir`'s records.
+ pub fn new(workspace_dir: impl Into<PathBuf>) -> Self {
+ Self {
+ workspace_dir: workspace_dir.into(),
+ }
+ }
+
+ /// Where an earlier build kept the records as JSON files.
+ fn legacy_dir(&self) -> PathBuf {
+ super::tiny_store::legacy_versioned_dir(&self.workspace_dir)
+ }
+
+ /// The repo for this call (resolved here, in the caller's context, for its
+ /// scope), after the one-time legacy import.
+ async fn repo(&self) -> Result<Repo> {
+ let repo = Repo::current_for(&self.workspace_dir, DOMAIN, collections)?;
+ let legacy = self.legacy_dir();
+ on_blocking(repo.clone(), move |repo| {
+ let key = legacy.display().to_string();
+ repo.once_per_backend(&key, || import_legacy(repo, &legacy).map(|_| ()))
+ })
+ .await?;
+ Ok(repo)
+ }
+}
+
+#[async_trait]
+impl ArtifactStore for DocumentArtifactStore {
+ async fn list(&self) -> Result<Vec<ArtifactRecord>> {
+ let repo = self.repo().await?;
+ let stored = on_blocking(repo, |repo| {
+ repo.run(|docs| async move {
+ docs.query_all(
+ VERSIONS,
+ &Query::all()
+ .sort(Sort::desc("updated_ms"))
+ .sort(Sort::asc("_id")),
+ )
+ .await
+ })
+ })
+ .await?;
+ Ok(stored
+ .into_iter()
+ .filter_map(|item| match record_of(item.doc) {
+ Ok(record) => Some(record),
+ Err(err) => {
+ tracing::warn!(
+ target: "tiny-artifacts",
+ id = %item.id,
+ err = %err,
+ "[artifacts] skipping an unreadable versioned record"
+ );
+ None
+ }
+ })
+ .collect())
+ }
+
+ async fn get(&self, id: &str) -> Result<Option<ArtifactRecord>> {
+ let repo = self.repo().await?;
+ let id = id.to_string();
+ let stored = on_blocking(repo, move |repo| {
+ repo.run(|docs| async move { docs.get(VERSIONS, &id).await })
+ })
+ .await?;
+ stored.map(|stored| record_of(stored.doc)).transpose()
+ }
+
+ async fn upsert(&self, artifact: &ArtifactRecord) -> Result<()> {
+ let repo = self.repo().await?;
+ let id = artifact.id.clone();
+ let doc = doc_of(artifact)?;
+ on_blocking(repo, move |repo| {
+ repo.run(|docs| async move {
+ docs.put(VERSIONS, &id, doc, Precondition::None)
+ .await
+ .map(|_| ())
+ })
+ })
+ .await
+ }
+
+ async fn delete(&self, id: &str) -> Result<bool> {
+ // The legacy file goes first: it is what a later import would bring
+ // back.
+ if !id.is_empty() && !id.contains(['/', '\\']) && !id.starts_with('.') {
+ let legacy = self.legacy_dir().join(format!("{id}.json"));
+ match tokio::fs::remove_file(&legacy).await {
+ Ok(()) => {}
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
+ Err(err) => {
+ return Err(err).with_context(|| format!("remove {}", legacy.display()))
+ }
+ }
+ }
+ let repo = self.repo().await?;
+ let id = id.to_string();
+ on_blocking(repo, move |repo| {
+ repo.run(|docs| async move { docs.delete(VERSIONS, &id, Precondition::None).await })
+ })
+ .await
+ }
+}
+
+fn doc_of(record: &ArtifactRecord) -> Result<Value> {
+ let mut doc = serde_json::to_value(record).context("serialize artifact record")?;
+ doc["updated_ms"] = Value::from(record.updated_at_millis);
+ Ok(doc)
+}
+
+fn record_of(mut doc: Value) -> Result<ArtifactRecord> {
+ if let Some(fields) = doc.as_object_mut() {
+ fields.remove("updated_ms");
+ }
+ serde_json::from_value(doc).context("parse artifact record")
+}
+
+/// Imports the legacy `<id>.json` records in `dir` that the store does not
+/// have; returns how many it created. A missing folder is nothing to import
+/// and an unreadable record is skipped; any other read error fails the import,
+/// so it is retried.
+fn import_legacy(repo: &Repo, dir: &Path) -> Result<usize> {
+ let entries = match std::fs::read_dir(dir) {
+ Ok(entries) => entries,
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(err) => return Err(err).with_context(|| format!("read {}", dir.display())),
+ };
+ let mut imported = 0;
+ for entry in entries {
+ let path = entry
+ .with_context(|| format!("read {}", dir.display()))?
+ .path();
+ if path.extension().and_then(|e| e.to_str()) != Some("json") {
+ continue;
+ }
+ let raw =
+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
+ let Ok(record) = serde_json::from_str::<ArtifactRecord>(&raw) else {
+ tracing::warn!(
+ target: "tiny-artifacts",
+ file = %path.display(),
+ "[artifacts] legacy import: skipping an unreadable record"
+ );
+ continue;
+ };
+ // A record is kept under its own id; a copy under another name is not
+ // the record.
+ if path.file_stem().and_then(|s| s.to_str()) != Some(record.id.as_str()) {
+ continue;
+ }
+ let id = record.id.clone();
+ let doc = doc_of(&record)?;
+ let created = repo.run(|docs| async move {
+ match docs.put(VERSIONS, &id, doc, Precondition::Absent).await {
+ Ok(_) => Ok(true),
+ Err(err) if err.kind() == tinystoragedrivers::ErrorKind::Conflict => Ok(false),
+ Err(err) => Err(err),
+ }
+ })?;
+ if created {
+ imported += 1;
+ }
+ }
+ tracing::debug!(
+ target: "tiny-artifacts",
+ imported,
+ "[artifacts] versioned records: legacy import done"
+ );
+ Ok(imported)
+}
+
+/// Runs a document-store call off the async worker (the port is reached
+/// through a blocking bridge).
+async fn on_blocking<T: Send + 'static>(
+ repo: Repo,
+ f: impl FnOnce(&Repo) -> Result<T> + Send + 'static,
+) -> Result<T> {
+ crate::core::runtime::DispatchCtx::ambient()
+ .spawn_blocking(move || f(&repo))
+ .await
+ .map_err(|e| anyhow::anyhow!("[artifacts] storage task failed: {e}"))?
+}
+
+#[cfg(test)]
+#[path = "version_documents_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/artifacts/version_documents_tests.rs b/crates/openhuman-core/src/agent/artifacts/version_documents_tests.rs
new file mode 100644
index 0000000000..e2f7c982c3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/artifacts/version_documents_tests.rs
@@ -0,0 +1,89 @@
+use tiny_artifacts::{ArtifactKind, ArtifactRecord, ArtifactStore};
+
+use super::*;
+
+fn workspace() -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("version-docs-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+}
+
+fn record(id: &str, body: &str, at: u64) -> ArtifactRecord {
+ ArtifactRecord::new(id, "Notes", ArtifactKind::Markdown, body, "agent", at)
+}
+
+#[tokio::test]
+async fn records_round_trip_through_the_document_store() {
+ let ws = workspace();
+ let store = DocumentArtifactStore::new(&ws);
+ store.upsert(&record("a-1", "# one", 1)).await.unwrap();
+ store.upsert(&record("a-2", "# two", 2)).await.unwrap();
+
+ let got = store.get("a-1").await.unwrap().unwrap();
+ assert_eq!(got, record("a-1", "# one", 1));
+ let listed: Vec<_> = store
+ .list()
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|r| r.id)
+ .collect();
+ // Most recently updated first.
+ assert_eq!(listed, vec!["a-2", "a-1"]);
+
+ assert!(store.delete("a-1").await.unwrap());
+ assert!(store.get("a-1").await.unwrap().is_none());
+ assert!(!store.delete("a-1").await.unwrap());
+ // Nothing is written as a file.
+ assert!(!super::super::tiny_store::legacy_versioned_dir(&ws)
+ .join("a-2.json")
+ .exists());
+}
+
+#[tokio::test]
+async fn records_from_an_earlier_build_are_imported_once_and_never_resurrected() {
+ let ws = workspace();
+ let legacy = super::super::tiny_store::legacy_versioned_dir(&ws);
+ std::fs::create_dir_all(&legacy).unwrap();
+ let old = record("old-1", "# kept as a file", 5);
+ std::fs::write(legacy.join("old-1.json"), serde_json::to_vec(&old).unwrap()).unwrap();
+ // A copy under another name is not the record; junk is skipped.
+ std::fs::write(legacy.join("other.json"), serde_json::to_vec(&old).unwrap()).unwrap();
+ std::fs::write(legacy.join("junk.json"), b"not json").unwrap();
+
+ let store = DocumentArtifactStore::new(&ws);
+ assert_eq!(store.get("old-1").await.unwrap(), Some(old.clone()));
+ assert!(store.get("other").await.unwrap().is_none());
+
+ // A newer write is not overwritten by a repeated import.
+ store.upsert(&record("old-1", "# newer", 9)).await.unwrap();
+ assert_eq!(
+ import_legacy(
+ &Repo::current_for(&ws, DOMAIN, collections).unwrap(),
+ &legacy
+ )
+ .unwrap(),
+ 0
+ );
+ assert_eq!(
+ store
+ .get("old-1")
+ .await
+ .unwrap()
+ .unwrap()
+ .latest()
+ .unwrap()
+ .body,
+ "# newer"
+ );
+
+ // Deleting removes the legacy file too, so the next import cannot bring it back.
+ assert!(store.delete("old-1").await.unwrap());
+ assert!(!legacy.join("old-1.json").exists());
+ import_legacy(
+ &Repo::current_for(&ws, DOMAIN, collections).unwrap(),
+ &legacy,
+ )
+ .unwrap();
+ assert!(store.get("old-1").await.unwrap().is_none());
+}