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
refactor(session): use TinyAgents layout migration directly
Steven Enamakela83a99c5052c
diff --git a/crates/openhuman-core/src/agent/harness/session/migration.rs b/crates/openhuman-core/src/agent/harness/session/migration.rsdeleted file mode 100644index ac416d4f38..0000000000--- a/crates/openhuman-core/src/agent/harness/session/migration.rs+++ /dev/null@@ -1,373 +0,0 @@-//! Session storage layout migration: date-grouped → flat `session_raw/`.-//!-//! Older releases (≤ 0.53.4) wrote transcripts to:-//!-//! ```text-//! {workspace}/session_raw/{DDMMYYYY}/{stem}.jsonl-//! {workspace}/sessions/{DDMMYYYY}/{stem}.md-//! ```-//!-//! From 0.53.5 onwards the source of truth is the *flat*-//! `session_raw/{stem}.jsonl` and the human-readable companion is-//! `sessions/{YYYY_MM_DD}/{stem}.md` — see-//! [`tinyagents_session::transcript`] for the shared transcript format and-//! date-independent resume discovery.-//!-//! `find_latest_transcript` ships a fallback that reads the legacy-//! layout when the flat dir is empty, so users upgrading don't lose-//! resume even before this migration runs. This module performs the-//! one-shot move so files end up in their canonical location and the-//! transitional fallback can eventually be removed.-//!-//! ## Idempotency-//!-//! After a successful migration we write a marker at-//! `{workspace}/state/migrations/session_layout_v1.done`. Subsequent-//! starts read the marker and skip the scan entirely. If the workspace-//! has no legacy layout (fresh install or already migrated by an-//! external sync) we still write the marker so the scan stays-//! single-cost.-//!-//! ## Version gate-//!-//! The marker doubles as the "have we already migrated past 0.53.4?"-//! flag. A bare workspace with no legacy dirs and no marker is treated-//! as "fresh — nothing to do, write the marker." A workspace with-//! legacy dirs is treated as "upgrading from ≤ 0.53.4 — migrate then-//! write the marker."-//!-//! Failures are surfaced as warnings (logged) and **never panic**:-//! transcript files are valuable but not strictly required for-//! continued operation, and an uncatchable migration error would brick-//! every startup.--use anyhow::{Context, Result};-use std::fs;-use std::path::{Path, PathBuf};--/// Marker file that signals "the v1 session-layout migration ran-/// successfully on this workspace at least once". Written under-/// `state/migrations/` to keep the workspace root tidy.-const MIGRATION_MARKER: &str = "state/migrations/session_layout_v1.done";--#[derive(Debug, Default, Clone)]-pub struct MigrationOutcome {- pub jsonl_moved: usize,- pub jsonl_skipped: usize,- pub md_moved: usize,- pub md_skipped: usize,- pub legacy_dirs_pruned: usize,- pub already_done: bool,- pub warnings: Vec<String>,-}--/// Migrate the session storage layout for `workspace_dir` if needed.-///-/// * Detects legacy `session_raw/{DDMMYYYY}/...jsonl` and-/// `sessions/{DDMMYYYY}/...md` layouts (i.e. an upgrade from-/// ≤ 0.53.4).-/// * Moves jsonl files to flat `session_raw/{stem}.jsonl`.-/// * Renames `DDMMYYYY` md dirs to ISO-style `YYYY_MM_DD` so the-/// listing sorts lexicographically.-/// * Writes the migration marker on success.-///-/// Idempotent: returns immediately with `already_done = true` if the-/// marker already exists. Best-effort on individual file moves —-/// failures are logged and surfaced via `warnings`, not propagated, so-/// one bad rename can't brick startup.-pub fn migrate_session_layout_if_needed(workspace_dir: &Path) -> Result<MigrationOutcome> {- let marker_path = workspace_dir.join(MIGRATION_MARKER);- if marker_path.exists() {- log::debug!(- "[session-migration] marker present at {} — skipping",- marker_path.display()- );- return Ok(MigrationOutcome {- already_done: true,- ..Default::default()- });- }-- let mut outcome = MigrationOutcome::default();-- let raw_root = workspace_dir.join("session_raw");- if raw_root.is_dir() {- migrate_raw_jsonl(&raw_root, &mut outcome)?;- }-- let sessions_root = workspace_dir.join("sessions");- if sessions_root.is_dir() {- migrate_md_directories(&sessions_root, &mut outcome)?;- }-- write_marker(&marker_path, &outcome).context("write session-migration marker")?;-- log::info!(- "[session-migration] complete: jsonl moved={} skipped={}, md moved={} skipped={}, legacy dirs pruned={}, warnings={}",- outcome.jsonl_moved,- outcome.jsonl_skipped,- outcome.md_moved,- outcome.md_skipped,- outcome.legacy_dirs_pruned,- outcome.warnings.len(),- );-- Ok(outcome)-}--/// Walk `session_raw/`, find direct subdirectories whose names look-/// like `DDMMYYYY` (8 ascii digits), and move every `*.jsonl` file-/// inside up to the flat `session_raw/` parent. Empty legacy dirs-/// are removed; non-empty ones are left in place with a warning so a-/// human can decide what to do.-fn migrate_raw_jsonl(raw_root: &Path, outcome: &mut MigrationOutcome) -> Result<()> {- let entries = match fs::read_dir(raw_root) {- Ok(it) => it,- Err(err) => {- outcome- .warnings- .push(format!("read_dir({}) failed: {err}", raw_root.display()));- return Ok(());- }- };-- for entry in entries.flatten() {- let path = entry.path();- if !path.is_dir() {- continue;- }- let Some(name) = path.file_name().and_then(|s| s.to_str()) else {- continue;- };- if !is_ddmmyyyy(name) {- // Not a legacy date dir — leave alone (could be the new- // flat layout's own files which would never be a dir, or- // a user-created subdirectory we shouldn't touch).- continue;- }- move_jsonl_files_up(&path, raw_root, outcome);- prune_if_empty(&path, outcome);- }-- Ok(())-}--fn move_jsonl_files_up(legacy_dir: &Path, flat_dir: &Path, outcome: &mut MigrationOutcome) {- let entries = match fs::read_dir(legacy_dir) {- Ok(it) => it,- Err(err) => {- outcome- .warnings- .push(format!("read_dir({}) failed: {err}", legacy_dir.display()));- return;- }- };-- for entry in entries.flatten() {- let path = entry.path();- if !path.is_file() {- continue;- }- if path.extension().and_then(|s| s.to_str()) != Some("jsonl") {- continue;- }- let Some(file_name) = path.file_name() else {- continue;- };- let dest = flat_dir.join(file_name);- if dest.exists() {- // Same stem already lives in the flat dir — the new layout- // is authoritative for current sessions, so leave the- // legacy copy in place and surface a warning instead of- // overwriting newer data.- outcome.jsonl_skipped += 1;- outcome.warnings.push(format!(- "skip move: destination already exists at {} (legacy file kept at {})",- dest.display(),- path.display()- ));- continue;- }- match fs::rename(&path, &dest) {- Ok(()) => {- outcome.jsonl_moved += 1;- log::debug!(- "[session-migration] moved {} → {}",- path.display(),- dest.display()- );- }- Err(err) => {- outcome.warnings.push(format!(- "rename({} → {}) failed: {err}",- path.display(),- dest.display()- ));- }- }- }-}--/// Walk `sessions/`, rename each `DDMMYYYY` subdirectory to its-/// `YYYY_MM_DD` equivalent. We rename the dir wholesale rather than-/// copying file-by-file: the contents are human-readable companions-/// and don't need re-indexing.-fn migrate_md_directories(sessions_root: &Path, outcome: &mut MigrationOutcome) -> Result<()> {- let entries = match fs::read_dir(sessions_root) {- Ok(it) => it,- Err(err) => {- outcome.warnings.push(format!(- "read_dir({}) failed: {err}",- sessions_root.display()- ));- return Ok(());- }- };-- for entry in entries.flatten() {- let path = entry.path();- if !path.is_dir() {- continue;- }- let Some(name) = path.file_name().and_then(|s| s.to_str()) else {- continue;- };- let Some(iso) = ddmmyyyy_to_yyyy_mm_dd(name) else {- continue;- };- let dest = sessions_root.join(&iso);- if dest.exists() {- // ISO dir already exists — merge file-by-file, never- // overwrite. A user could have legitimately produced both- // names (e.g. by manual workflow) so we don't blindly- // discard either side.- merge_md_dirs(&path, &dest, outcome);- prune_if_empty(&path, outcome);- continue;- }- match fs::rename(&path, &dest) {- Ok(()) => {- outcome.md_moved += 1;- log::debug!(- "[session-migration] renamed md dir {} → {}",- path.display(),- dest.display()- );- }- Err(err) => {- outcome.warnings.push(format!(- "rename({} → {}) failed: {err}",- path.display(),- dest.display()- ));- }- }- }-- Ok(())-}--fn merge_md_dirs(legacy: &Path, dest: &Path, outcome: &mut MigrationOutcome) {- let entries = match fs::read_dir(legacy) {- Ok(it) => it,- Err(err) => {- outcome- .warnings- .push(format!("read_dir({}) failed: {err}", legacy.display()));- return;- }- };- for entry in entries.flatten() {- let src = entry.path();- if !src.is_file() {- continue;- }- let Some(file_name) = src.file_name() else {- continue;- };- let target = dest.join(file_name);- if target.exists() {- outcome.md_skipped += 1;- outcome.warnings.push(format!(- "skip md merge: {} already exists (legacy at {} kept)",- target.display(),- src.display()- ));- continue;- }- match fs::rename(&src, &target) {- Ok(()) => outcome.md_moved += 1,- Err(err) => outcome.warnings.push(format!(- "rename({} → {}) failed: {err}",- src.display(),- target.display()- )),- }- }-}--fn prune_if_empty(dir: &Path, outcome: &mut MigrationOutcome) {- match fs::read_dir(dir) {- Ok(mut it) => {- if it.next().is_some() {- // Non-empty — leave for human inspection.- return;- }- }- Err(_) => return,- }- if fs::remove_dir(dir).is_ok() {- outcome.legacy_dirs_pruned += 1;- }-}--fn write_marker(marker_path: &Path, outcome: &MigrationOutcome) -> Result<()> {- if let Some(parent) = marker_path.parent() {- fs::create_dir_all(parent)- .with_context(|| format!("create marker dir {}", parent.display()))?;- }- let body = format!(- "openhuman session_layout migration v1\nrun_at: {}\njsonl_moved: {}\nmd_moved: {}\nlegacy_dirs_pruned: {}\nwarnings: {}\n",- chrono::Utc::now().to_rfc3339(),- outcome.jsonl_moved,- outcome.md_moved,- outcome.legacy_dirs_pruned,- outcome.warnings.len(),- );- fs::write(marker_path, body)- .with_context(|| format!("write marker {}", marker_path.display()))?;- Ok(())-}--/// Returns true iff `name` is exactly 8 ASCII digits — the legacy-/// `DDMMYYYY` shape. We don't validate the date range (1–31, 1–12,-/// 1900–2100) because chrono printed the value originally, so any-/// real on-disk dir is well-formed; the digit shape is a sufficient-/// fingerprint to distinguish from user-created subdirectories.-fn is_ddmmyyyy(name: &str) -> bool {- name.len() == 8 && name.chars().all(|c| c.is_ascii_digit())-}--/// Convert `DDMMYYYY` → `YYYY_MM_DD`. Returns `None` if the input-/// isn't 8 digits.-fn ddmmyyyy_to_yyyy_mm_dd(name: &str) -> Option<String> {- if !is_ddmmyyyy(name) {- return None;- }- let dd = &name[0..2];- let mm = &name[2..4];- let yyyy = &name[4..8];- Some(format!("{yyyy}_{mm}_{dd}"))-}--/// Returns the path of the migration marker for `workspace_dir`.-/// Exposed for tests and CLI tooling that wants to manually re-run-/// the migration (delete the marker, then call-/// [`migrate_session_layout_if_needed`] again).-pub fn marker_path_for(workspace_dir: &Path) -> PathBuf {- workspace_dir.join(MIGRATION_MARKER)-}--#[cfg(test)]-#[path = "migration_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/harness/session/migration_tests.rs b/crates/openhuman-core/src/agent/harness/session/migration_tests.rsdeleted file mode 100644index e1b5c41513..0000000000--- a/crates/openhuman-core/src/agent/harness/session/migration_tests.rs+++ /dev/null@@ -1,170 +0,0 @@-use super::*;-use std::fs;-use tempfile::TempDir;--fn write_file(path: &std::path::Path, body: &str) {- fs::create_dir_all(path.parent().unwrap()).unwrap();- fs::write(path, body).unwrap();-}--#[test]-fn fresh_workspace_writes_marker_with_no_moves() {- let dir = TempDir::new().unwrap();- let outcome = migrate_session_layout_if_needed(dir.path()).unwrap();- assert!(!outcome.already_done);- assert_eq!(outcome.jsonl_moved, 0);- assert_eq!(outcome.md_moved, 0);- assert!(marker_path_for(dir.path()).exists());-}--#[test]-fn second_run_is_a_noop() {- let dir = TempDir::new().unwrap();- let _first = migrate_session_layout_if_needed(dir.path()).unwrap();- let second = migrate_session_layout_if_needed(dir.path()).unwrap();- assert!(second.already_done);- assert_eq!(second.jsonl_moved, 0);- assert_eq!(second.warnings.len(), 0);-}--#[test]-fn moves_legacy_jsonl_files_up_to_flat_session_raw() {- let dir = TempDir::new().unwrap();- let ws = dir.path();- let legacy_a = ws.join("session_raw").join("01052026");- let legacy_b = ws.join("session_raw").join("02052026");- write_file(&legacy_a.join("1714000000_main.jsonl"), "a");- write_file(&legacy_a.join("1714000001_welcome.jsonl"), "b");- write_file(&legacy_b.join("1714999999_orchestrator.jsonl"), "c");-- let outcome = migrate_session_layout_if_needed(ws).unwrap();- assert_eq!(outcome.jsonl_moved, 3);- assert_eq!(outcome.legacy_dirs_pruned, 2);-- let raw_root = ws.join("session_raw");- assert!(raw_root.join("1714000000_main.jsonl").exists());- assert!(raw_root.join("1714000001_welcome.jsonl").exists());- assert!(raw_root.join("1714999999_orchestrator.jsonl").exists());- // Empty legacy date dirs should have been pruned.- assert!(!legacy_a.exists(), "legacy date dir should be removed");- assert!(!legacy_b.exists(), "legacy date dir should be removed");-}--#[test]-fn jsonl_destination_collision_is_skipped_with_warning() {- // If a flat `session_raw/{stem}.jsonl` already exists for the- // same stem we don't overwrite — the flat copy is authoritative- // (the user may have already started a fresh session with the- // same key after a clock reset). Surface a warning instead.- let dir = TempDir::new().unwrap();- let ws = dir.path();- let raw_root = ws.join("session_raw");- write_file(&raw_root.join("1714000000_main.jsonl"), "new");- write_file(- &raw_root.join("01052026").join("1714000000_main.jsonl"),- "old",- );-- let outcome = migrate_session_layout_if_needed(ws).unwrap();- assert_eq!(outcome.jsonl_moved, 0);- assert_eq!(outcome.jsonl_skipped, 1);- assert!(outcome- .warnings- .iter()- .any(|w| w.contains("already exists")));- // Both files still exist — nothing was overwritten.- assert_eq!(- fs::read_to_string(raw_root.join("1714000000_main.jsonl")).unwrap(),- "new"- );- assert_eq!(- fs::read_to_string(raw_root.join("01052026").join("1714000000_main.jsonl")).unwrap(),- "old"- );-}--#[test]-fn renames_md_ddmmyyyy_dirs_to_iso() {- let dir = TempDir::new().unwrap();- let ws = dir.path();- let legacy_md = ws.join("sessions").join("01052026");- write_file(&legacy_md.join("main_0.md"), "x");- write_file(&legacy_md.join("main_1.md"), "y");-- let outcome = migrate_session_layout_if_needed(ws).unwrap();- assert_eq!(outcome.md_moved, 1, "one rename of the dir as a whole");- let iso = ws.join("sessions").join("2026_05_01");- assert!(iso.is_dir());- assert!(iso.join("main_0.md").exists());- assert!(iso.join("main_1.md").exists());- assert!(- !legacy_md.exists(),- "DDMMYYYY md dir should be gone after rename"- );-}--#[test]-fn merges_md_when_iso_dir_already_exists() {- let dir = TempDir::new().unwrap();- let ws = dir.path();- // Both layouts coexist for the same calendar date — e.g. user- // ran a hand-edited build that produced ISO dirs alongside the- // legacy DDMMYYYY ones.- let legacy = ws.join("sessions").join("01052026");- let iso = ws.join("sessions").join("2026_05_01");- write_file(&legacy.join("main_0.md"), "legacy");- write_file(&legacy.join("main_1.md"), "legacy");- write_file(&iso.join("main_1.md"), "newer");-- let outcome = migrate_session_layout_if_needed(ws).unwrap();- // main_0.md moves over (no collision); main_1.md collides and is- // skipped without overwriting the newer copy.- assert_eq!(outcome.md_moved, 1);- assert_eq!(outcome.md_skipped, 1);- assert_eq!(fs::read_to_string(iso.join("main_0.md")).unwrap(), "legacy");- assert_eq!(fs::read_to_string(iso.join("main_1.md")).unwrap(), "newer");-}--#[test]-fn ignores_non_date_subdirectories_in_session_raw() {- // Defensive: a user (or some other tool) might have created a- // sibling dir under session_raw/. We must not touch it — only- // 8-digit names are recognised as legacy date dirs.- let dir = TempDir::new().unwrap();- let ws = dir.path();- let weird = ws.join("session_raw").join("my_notes");- write_file(&weird.join("random.jsonl"), "keep me");-- let outcome = migrate_session_layout_if_needed(ws).unwrap();- assert_eq!(outcome.jsonl_moved, 0);- assert!(weird.is_dir(), "non-date subdir must be left alone");- assert!(weird.join("random.jsonl").exists());-}--#[test]-fn ddmmyyyy_to_iso_handles_boundary_dates() {- assert_eq!(- ddmmyyyy_to_yyyy_mm_dd("01012026").as_deref(),- Some("2026_01_01")- );- assert_eq!(- ddmmyyyy_to_yyyy_mm_dd("31122099").as_deref(),- Some("2099_12_31")- );- assert!(ddmmyyyy_to_yyyy_mm_dd("abc12345").is_none());- assert!(ddmmyyyy_to_yyyy_mm_dd("1234567").is_none(), "7 digits");- assert!(ddmmyyyy_to_yyyy_mm_dd("123456789").is_none(), "9 digits");-}--#[test]-fn marker_persists_run_metadata() {- let dir = TempDir::new().unwrap();- let ws = dir.path();- let legacy = ws.join("session_raw").join("01052026");- write_file(&legacy.join("1714000000_main.jsonl"), "a");-- migrate_session_layout_if_needed(ws).unwrap();- let marker = fs::read_to_string(marker_path_for(ws)).unwrap();- assert!(marker.contains("jsonl_moved: 1"));- assert!(marker.contains("openhuman session_layout migration v1"));-}diff --git a/crates/openhuman-core/src/agent/harness/session/mod.rs b/crates/openhuman-core/src/agent/harness/session/mod.rsindex 39e28bdc3e..a04d1228e4 100644--- a/crates/openhuman-core/src/agent/harness/session/mod.rs+++ b/crates/openhuman-core/src/agent/harness/session/mod.rs@@ -13,7 +13,7 @@//! [`crate::agent::tinyagents::run_turn_via_tinyagents_shared`], the//! shared TinyAgents harness assembly. What this module keeps is the//! OpenHuman product shell around that loop — transcript persistence and-//! legacy-format compatibility ([`migration`]), prompt+//! legacy-format compatibility from `tinyagents_session::transcript`, prompt//! section assembly and KV-cache prefix stability, memory/context injection//! policy, post-turn hooks, and the persisted history shape. The migration//! plan for moving the durable parts onto TinyAgents store/cache primitives@@ -36,7 +36,6 @@pub(crate) use builder::provider_role_for_definition;mod builder;-mod migration;mod runtime;#[cfg(test)]mod tool_progress;@@ -49,8 +48,6 @@ mod turn;pub(crate) mod turn_checkpoint;mod types;-pub use migration::{migrate_session_layout_if_needed, MigrationOutcome};-#[cfg(test)]#[path = "session_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/platform/startup/ops.rs b/crates/openhuman-core/src/platform/startup/ops.rsindex 8cd784e1ed..f3bde57d40 100644--- a/crates/openhuman-core/src/platform/startup/ops.rs+++ b/crates/openhuman-core/src/platform/startup/ops.rs@@ -1,11 +1,14 @@use std::path::Path;+use tinyagents_session::transcript::{migrate_layout_if_needed, TranscriptLayoutMigration};/// Run one-shot workspace migrations needed at process startup.////// Failures are logged and do not abort startup. Individual migration helpers/// remain responsible for their own idempotency markers.pub fn run_workspace_migrations(workspace_dir: &Path) {- match crate::agent::harness::session::migrate_session_layout_if_needed(workspace_dir) {+ let layout_migration: anyhow::Result<TranscriptLayoutMigration> =+ migrate_layout_if_needed(workspace_dir);+ match layout_migration {Ok(outcome) if outcome.already_done => {log::debug!("[runtime] session_layout migration already applied");}@@ -55,3 +58,7 @@ pub fn run_workspace_migrations(workspace_dir: &Path) {}}}++#[cfg(test)]+#[path = "ops_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/platform/startup/ops_tests.rs b/crates/openhuman-core/src/platform/startup/ops_tests.rsnew file mode 100644index 0000000000..1a7635d136--- /dev/null+++ b/crates/openhuman-core/src/platform/startup/ops_tests.rs@@ -0,0 +1,35 @@+use super::run_workspace_migrations;+use std::fs;+use tempfile::TempDir;++#[test]+fn workspace_startup_migrates_transcripts_once() {+ let tempdir = TempDir::new().unwrap();+ let workspace = tempdir.path();+ let legacy = workspace+ .join("session_raw")+ .join("01052026")+ .join("1714000000_main.jsonl");+ fs::create_dir_all(legacy.parent().unwrap()).unwrap();+ fs::write(&legacy, "legacy transcript").unwrap();++ run_workspace_migrations(workspace);++ let canonical = workspace.join("session_raw/1714000000_main.jsonl");+ let marker = workspace.join("state/migrations/session_layout_v1.done");+ assert_eq!(fs::read_to_string(&canonical).unwrap(), "legacy transcript");+ let first_marker = fs::read_to_string(&marker).unwrap();++ // A newly-arrived legacy artifact proves startup observes the marker rather+ // than re-running the migration on every process launch.+ fs::create_dir_all(legacy.parent().unwrap()).unwrap();+ fs::write(&legacy, "must remain legacy after marker").unwrap();+ run_workspace_migrations(workspace);++ assert_eq!(fs::read_to_string(&canonical).unwrap(), "legacy transcript");+ assert_eq!(+ fs::read_to_string(&legacy).unwrap(),+ "must remain legacy after marker"+ );+ assert_eq!(fs::read_to_string(marker).unwrap(), first_marker);+}diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 6c3105e67f..420cab0fc9 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 6c3105e67fcca56e62a9a29b45b192726523a78a+Subproject commit 420cab0fc99ce91222aec1ab8b7b99abfbba0325