Skip to content

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

feat(subagent_host): persist subagent lifecycle state

Steven Enamakelc4fb644c6610
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 3df4e33b30..0ff46a6958 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -7,14 +7,11 @@
use std::{
collections::HashMap,
- fs::OpenOptions,
path::PathBuf,
sync::{Arc, Mutex},
};
use async_trait::async_trait;
-use fs2::FileExt;
-use sha2::{Digest, Sha256};
use tinyagents_harness::context::{RunConfig, RunContext};
use tinyagents_orchestration::subagent::{
ArtifactReference, PreparedSubagent, SubagentCapabilities, SubagentDriver, SubagentError,
@@ -538,29 +535,19 @@ impl SubagentExecutor<crate::agent::tinyagents::host::OpenHumanRunContext> for O
}
/// Durable OpenHuman pause/terminal records scoped by the complete neutral
-/// task key. The key is encoded rather than using a task id as a filename, so
-/// equally named children of separate roots/parents can never resume or close
-/// one another's lifecycle.
+/// task key, on the storage port ([`store::LifecycleStore`]). The key is
+/// encoded rather than used raw, so equally named children of separate
+/// roots/parents can never resume or close one another's lifecycle.
pub(super) struct OpenHumanPersistence {
checkpoint_dir: std::path::PathBuf,
host_outcome: Arc<Mutex<Option<SubagentRunOutcome>>>,
}
-#[derive(serde::Serialize, serde::Deserialize)]
-struct TerminalRecord {
- outcome: SubagentOutcome,
- #[serde(default)]
- agent_id: String,
- #[serde(default)]
- elapsed_ms: u64,
-}
+use store::{LifecycleRecord, LifecycleStore, TerminalRecord};
-#[derive(serde::Deserialize)]
-#[serde(untagged)]
-enum CompatibleTerminalRecord {
- Current(TerminalRecord),
- Legacy(SubagentOutcome),
-}
+/// What a pause or terminal write decided, so the compare-and-swap closure
+/// can report an error without unwinding it.
+type Decision<T> = Result<T, String>;
impl OpenHumanPersistence {
pub(super) fn new(checkpoint_dir: std::path::PathBuf) -> Self {
@@ -575,240 +562,20 @@ impl OpenHumanPersistence {
self
}
- fn key_component(key: &SubagentTaskKey) -> String {
- fn hex(value: &str) -> String {
- value
- .as_bytes()
- .iter()
- .map(|byte| format!("{byte:02x}"))
- .collect()
- }
- let encoded = format!(
- "{}-{}-{}-{}",
- hex(&key.root_run_id),
- hex(&key.parent_run_id),
- hex(key.thread_id.as_deref().unwrap_or("")),
- hex(&key.task_id),
- );
- // A task key normally contains short UUID-like identifiers, for which
- // the reversible encoding preserves existing checkpoint paths. A
- // background child may inherit a rendered parent identifier, however;
- // hex-encoding that value can exceed the filesystem filename limit.
- // Hash only that exceptional form while keeping all key fields in the
- // digest input so distinct lifecycle scopes cannot alias.
- if encoded.len() <= 180 {
- encoded
- } else {
- format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
- }
- }
-
- fn pause_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.pause.json", Self::key_component(key)))
- }
-
- fn terminal_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.terminal.json", Self::key_component(key)))
- }
-
- fn index_path(&self, task_id: &str) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("task-{}.index.json", Self::task_component(task_id)))
- }
-
- fn lock_path(&self, key: &SubagentTaskKey) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("{}.lock", Self::key_component(key)))
- }
-
- fn index_lock_path(&self, task_id: &str) -> std::path::PathBuf {
- self.checkpoint_dir
- .join("lifecycle")
- .join(format!("task-{}.index.lock", Self::task_component(task_id)))
- }
-
- fn task_component(task_id: &str) -> String {
- let encoded = task_id
- .as_bytes()
- .iter()
- .map(|byte| format!("{byte:02x}"))
- .collect::<String>();
- if encoded.len() <= 180 {
- encoded
- } else {
- format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
- }
- }
-
- fn lock_file(path: &std::path::Path) -> Result<std::fs::File, SubagentError> {
- let parent = path.parent().expect("lifecycle lock path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let file = OpenOptions::new()
- .create(true)
- .truncate(false)
- .read(true)
- .write(true)
- .open(path)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- file.lock_exclusive()
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- Ok(file)
+ fn store(&self) -> Result<LifecycleStore, SubagentError> {
+ LifecycleStore::open(&self.checkpoint_dir)
}
- fn key_lock(&self, key: &SubagentTaskKey) -> Result<std::fs::File, SubagentError> {
- Self::lock_file(&self.lock_path(key))
- }
-
- fn index_lock(&self, task_id: &str) -> Result<std::fs::File, SubagentError> {
- Self::lock_file(&self.index_lock_path(task_id))
- }
-
- fn read_index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {
- let raw = match std::fs::read_to_string(self.index_path(task_id)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- let value: serde_json::Value = serde_json::from_str(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- // Accept the short-lived single-key format written by the first
- // lifecycle extraction, but immediately write the collision-safe
- // vector format on the next mutation.
- let keys = value
- .get("keys")
- .cloned()
- .map(serde_json::from_value)
- .transpose()
- .map_err(|error| SubagentError::Persistence(error.to_string()))?
- .or_else(|| {
- value
- .get("key")
- .cloned()
- .and_then(|key| serde_json::from_value(key).ok())
- .map(|key| vec![key])
- })
- .unwrap_or_default();
- Ok(keys)
- }
-
- fn write_index_keys(
- &self,
- task_id: &str,
- keys: &[SubagentTaskKey],
- ) -> Result<(), SubagentError> {
- let path = self.index_path(task_id);
- if keys.is_empty() {
- match std::fs::remove_file(path) {
- Ok(()) => return Ok(()),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- }
- }
- Self::replace_file(
- &path,
- serde_json::to_vec(&serde_json::json!({"keys": keys}))
- .map_err(|error| SubagentError::Persistence(error.to_string()))?,
- )
- }
-
- fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
- let _index_lock = self.index_lock(&key.task_id)?;
- let mut keys = self.read_index_keys(&key.task_id)?;
- if !keys.contains(key) {
- keys.push(key.clone());
- self.write_index_keys(&key.task_id, &keys)?;
- }
- Ok(())
- }
-
- fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
- let _index_lock = self.index_lock(&key.task_id)?;
- let mut keys = self.read_index_keys(&key.task_id)?;
- keys.retain(|candidate| candidate != key);
- self.write_index_keys(&key.task_id, &keys)
- }
-
- fn replace_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<(), SubagentError> {
- let parent = path.parent().expect("lifecycle state path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
- std::fs::write(&temporary, bytes)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match std::fs::rename(&temporary, path) {
- Ok(()) => Ok(()),
- Err(error) => {
- let _ = std::fs::remove_file(&temporary);
- Err(SubagentError::Persistence(error.to_string()))
- }
- }
- }
-
- fn insert_file(path: &std::path::Path, bytes: Vec<u8>) -> Result<bool, SubagentError> {
- let parent = path.parent().expect("lifecycle state path has a parent");
- std::fs::create_dir_all(parent)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
- std::fs::write(&temporary, bytes)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match std::fs::hard_link(&temporary, path) {
- Ok(()) => {
- let _ = std::fs::remove_file(&temporary);
- Ok(true)
- }
- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
- let _ = std::fs::remove_file(&temporary);
- Ok(false)
- }
- Err(error) => {
- let _ = std::fs::remove_file(&temporary);
- Err(SubagentError::Persistence(error.to_string()))
- }
- }
- }
-
- fn read_pause_checkpoint(
- &self,
+ /// The record's pause, refusing one stored under a different key.
+ fn pause_of(
+ record: &LifecycleRecord,
key: &SubagentTaskKey,
) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
- let raw = match std::fs::read_to_string(self.pause_path(key)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- let checkpoint = serde_json::from_str::<super::SubagentCheckpointData>(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- if checkpoint.task_key.as_ref() != Some(key) {
- return Err(SubagentError::Persistence("checkpoint key mismatch".into()));
- }
- Ok(Some(checkpoint))
- }
-
- fn read_terminal_record(
- &self,
- key: &SubagentTaskKey,
- ) -> Result<Option<TerminalRecord>, SubagentError> {
- let raw = match std::fs::read_to_string(self.terminal_path(key)) {
- Ok(raw) => raw,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(SubagentError::Persistence(error.to_string())),
- };
- match serde_json::from_str(&raw)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?
- {
- CompatibleTerminalRecord::Current(record) => Ok(Some(record)),
- CompatibleTerminalRecord::Legacy(outcome) => Ok(Some(TerminalRecord {
- outcome,
- agent_id: String::new(),
- elapsed_ms: 0,
- })),
+ match &record.pause {
+ Some(checkpoint) if checkpoint.task_key.as_ref() != Some(key) => {
+ Err(SubagentError::Persistence("checkpoint key mismatch".into()))
+ }
+ other => Ok(other.clone()),
}
}
@@ -816,13 +583,12 @@ impl OpenHumanPersistence {
&self,
key: &SubagentTaskKey,
) -> Result<Option<(String, u64)>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if let Some(record) = self.read_terminal_record(key)? {
- return Ok(
- (!record.agent_id.is_empty()).then_some((record.agent_id, record.elapsed_ms))
- );
+ let record = self.store()?.record(key)?;
+ if let Some(terminal) = record.terminal {
+ return Ok((!terminal.agent_id.is_empty())
+ .then_some((terminal.agent_id, terminal.elapsed_ms)));
}
- Ok(self.read_pause_checkpoint(key)?.and_then(|checkpoint| {
+ Ok(Self::pause_of(&record, key)?.and_then(|checkpoint| {
(!checkpoint.agent_id.is_empty())
.then_some((checkpoint.agent_id, checkpoint.elapsed_ms))
}))
@@ -889,11 +655,11 @@ impl OpenHumanPersistence {
&self,
key: &SubagentTaskKey,
) -> Result<Option<super::SubagentCheckpointData>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
+ let record = self.store()?.record(key)?;
+ if record.terminal.is_some() {
return Ok(None);
}
- self.read_pause_checkpoint(key)
+ Self::pause_of(&record, key)
}
fn checkpoint_for_task(
@@ -905,10 +671,10 @@ impl OpenHumanPersistence {
"unsafe task id"
)));
}
- let keys = {
- let _index_lock = self.index_lock(task_id).map_err(map_lifecycle_error)?;
- self.read_index_keys(task_id).map_err(map_lifecycle_error)?
- };
+ let keys = self
+ .store()
+ .and_then(|store| store.index_keys(task_id))
+ .map_err(map_lifecycle_error)?;
let mut live = Vec::new();
for key in keys {
if let Some(checkpoint) = self.live_checkpoint(&key).map_err(map_lifecycle_error)? {
@@ -944,16 +710,18 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
&self,
key: &SubagentTaskKey,
) -> Result<Option<SubagentOutcome>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- Ok(self.read_terminal_record(key)?.map(|record| record.outcome))
+ Ok(self
+ .store()?
+ .record(key)?
+ .terminal
+ .map(|record| record.outcome))
}
async fn load(&self, key: &SubagentTaskKey) -> Result<Option<SubagentResume>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
+ let record = self.store()?.record(key)?;
+ if record.terminal.is_some() {
return Ok(None);
}
- Ok(self
- .read_pause_checkpoint(key)?
+ Ok(Self::pause_of(&record, key)?
.as_ref()
.map(Self::checkpoint_resume))
}
@@ -962,23 +730,18 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
&self,
key: &SubagentTaskKey,
) -> Result<Option<SubagentOutcome>, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
+ let record = self.store()?.record(key)?;
+ if record.terminal.is_some() {
return Ok(None);
}
- Ok(self
- .read_pause_checkpoint(key)?
- .map(Self::checkpoint_outcome))
+ Ok(Self::pause_of(&record, key)?.map(Self::checkpoint_outcome))
}
async fn save_pause(
&self,
pause: tinyagents_orchestration::subagent::PersistedSubagentPause,
) -> Result<SubagentPausePersistenceDisposition, SubagentError> {
- let _key_lock = self.key_lock(&pause.key)?;
- if self.terminal_path(&pause.key).exists() {
- return Ok(SubagentPausePersistenceDisposition::TerminalExisting);
- }
+ let store = self.store()?;
let paused = match &pause.outcome.status {
SubagentOutcomeKind::AwaitingInput(paused) => paused,
_ => {
@@ -1041,29 +804,39 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
.map(|outcome| outcome.elapsed.as_millis() as u64)
.unwrap_or_default(),
};
- let json = serde_json::to_vec_pretty(&checkpoint)
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- let path = self.pause_path(&pause.key);
- let existing = self.read_pause_checkpoint(&pause.key)?;
- match (pause.replaces.as_ref(), existing) {
- (None, None) => {
- // Index first: a failed data write can leave a stale index,
- // which readers filter by the live pause record. A successful
- // pause can never be unresumable through a missing index.
- self.add_index_key(&pause.key)?;
- if Self::insert_file(&path, json)? {
- Ok(SubagentPausePersistenceDisposition::Inserted)
- } else {
- Ok(SubagentPausePersistenceDisposition::Existing)
+ // Index first: a failed data write can leave a stale index, which
+ // readers filter by the live pause record. A successful pause can
+ // never be unresumable through a missing index.
+ store.add_index_key(&pause.key)?;
+ let (key, replaces) = (pause.key.clone(), pause.replaces.clone());
+ let decided: Decision<SubagentPausePersistenceDisposition> = store.update(&pause.key, {
+ move |record| {
+ if record.terminal.is_some() {
+ return (
+ Ok(SubagentPausePersistenceDisposition::TerminalExisting),
+ false,
+ );
+ }
+ let current = match Self::pause_of(record, &key) {
+ Ok(current) => current,
+ Err(error) => return (Err(error.to_string()), false),
+ };
+ match (replaces.as_ref(), current) {
+ (None, None) => {
+ record.pause = Some(checkpoint.clone());
+ (Ok(SubagentPausePersistenceDisposition::Inserted), true)
+ }
+ (Some(expected), Some(current))
+ if Self::checkpoint_resume(&current) == *expected =>
+ {
+ record.pause = Some(checkpoint.clone());
+ (Ok(SubagentPausePersistenceDisposition::Replaced), true)
+ }
+ _ => (Ok(SubagentPausePersistenceDisposition::Existing), false),
}
}
- (Some(expected), Some(current)) if Self::checkpoint_resume(&current) == *expected => {
- self.add_index_key(&pause.key)?;
- Self::replace_file(&path, json)?;
- Ok(SubagentPausePersistenceDisposition::Replaced)
- }
- _ => Ok(SubagentPausePersistenceDisposition::Existing),
- }
+ })?;
+ decided.map_err(SubagentError::Persistence)
}
async fn record_terminal(
@@ -1072,28 +845,13 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
outcome: &SubagentOutcome,
replaces: Option<&SubagentResume>,
) -> Result<SubagentTerminalPersistenceDisposition, SubagentError> {
- let _key_lock = self.key_lock(key)?;
- if self.terminal_path(key).exists() {
- return Ok(SubagentTerminalPersistenceDisposition::Existing);
- }
- if let Some(current) = self.read_pause_checkpoint(key)? {
- let can_consume_pause =
- replaces.is_some_and(|expected| Self::checkpoint_resume(&current) == *expected);
- if !can_consume_pause {
- return Ok(SubagentTerminalPersistenceDisposition::PauseExisting);
- }
- } else if replaces.is_some() {
- return Err(SubagentError::Persistence(
- "terminal continuation lost its expected durable pause".into(),
- ));
- }
- let path = self.terminal_path(key);
+ let store = self.store()?;
let host = self
.host_outcome
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone();
- let record = serde_json::to_vec(&TerminalRecord {
+ let terminal = TerminalRecord {
outcome: outcome.clone(),
agent_id: host
.as_ref()
@@ -1103,27 +861,57 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
.as_ref()
.map(|outcome| outcome.elapsed.as_millis() as u64)
.unwrap_or_default(),
- })
- .map_err(|error| SubagentError::Persistence(error.to_string()))?;
- match Self::insert_file(&path, record)? {
- true => {
- // Terminal is the durable winner. Retiring a matching pause
- // afterwards cannot reopen the lifecycle because `load` first
- // observes this terminal marker.
- let _ = std::fs::remove_file(self.pause_path(key));
- // A stale task-id index is harmless because recovery filters
- // terminal keys. Never turn a durable terminal success into an
- // error merely because cleanup of a derived index failed.
- if let Err(error) = self.remove_index_key(key) {
- tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");
+ };
+ let (scoped, replaces) = (key.clone(), replaces.cloned());
+ let decided: Decision<SubagentTerminalPersistenceDisposition> = store.update(key, {
+ move |record| {
+ if record.terminal.is_some() {
+ return (Ok(SubagentTerminalPersistenceDisposition::Existing), false);
+ }
+ match Self::pause_of(record, &scoped) {
+ Err(error) => return (Err(error.to_string()), false),
+ Ok(Some(current)) => {
+ let can_consume_pause = replaces
+ .as_ref()
+ .is_some_and(|expected| Self::checkpoint_resume(&current) == *expected);
+ if !can_consume_pause {
+ return (
+ Ok(SubagentTerminalPersistenceDisposition::PauseExisting),
+ false,
+ );
+ }
+ }
+ Ok(None) if replaces.is_some() => {
+ return (
+ Err("terminal continuation lost its expected durable pause".into()),
+ false,
+ );
+ }
+ Ok(None) => {}
}
- Ok(SubagentTerminalPersistenceDisposition::Inserted)
+ // Terminal is the durable winner. Retiring a matching pause in
+ // the same write means it can never reopen the lifecycle.
+ record.terminal = Some(terminal.clone());
+ record.pause = None;
+ (Ok(SubagentTerminalPersistenceDisposition::Inserted), true)
+ }
+ })?;
+ let disposition = decided.map_err(SubagentError::Persistence)?;
+ if disposition == SubagentTerminalPersistenceDisposition::Inserted {
+ // A stale task-id index is harmless because recovery filters
+ // terminal keys. Never turn a durable terminal success into an
+ // error merely because cleanup of a derived index failed.
+ if let Err(error) = store.remove_index_key(key) {
+ tracing::warn!(task_id = %key.task_id, error = %error, "[subagent] terminal committed but task-id index cleanup failed");
}
- false => Ok(SubagentTerminalPersistenceDisposition::Existing),
}
+ Ok(disposition)
}
}
+#[path = "lifecycle_store.rs"]
+mod store;
+
#[path = "lifecycle_outcome.rs"]
mod outcome;
use outcome::{host_outcome_to_neutral, HostInFlightMap};
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rs
new file mode 100644
index 0000000000..b5d99aece6
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_store.rs
@@ -0,0 +1,315 @@
+//! The sub-agent lifecycle records on the storage port.
+//!
+//! One record per scoped task key (`record/<key component>` in `tsd.kv`, owner
+//! `subagents`, namespace `lifecycle`) holds the key's pause checkpoint and
+//! its terminal outcome together, so "a terminal closes the pause" is one
+//! compare-and-swap rather than two files under a lock. A second value per task id
+//! (`index/<task component>`) lists the scoped keys that share the id.
+//!
+//! Before schema v2 these were `<workspace>/.openhuman/subagent_checkpoints/
+//! lifecycle/<component>.{pause,terminal}.json` and `task-<component>.index.json`
+//! guarded by `flock` files. [`LifecycleStore::open`] imports them once per
+//! backend and scope (`tsd.migrations`) and leaves the files in place.
+
+use std::path::{Path, PathBuf};
+
+use sha2::{Digest, Sha256};
+use tinyagents_orchestration::subagent::{SubagentError, SubagentOutcome, SubagentTaskKey};
+
+use super::SubagentCheckpointData;
+use crate::storage::state_kv::StateKv;
+
+const OWNER: &str = "subagents";
+const NS: &str = "lifecycle";
+const IMPORT: &str = "lifecycle_dir";
+
+/// A task's terminal outcome with the host facts the neutral outcome lacks.
+#[derive(Clone, serde::Serialize, serde::Deserialize)]
+pub(super) struct TerminalRecord {
+ pub(super) outcome: SubagentOutcome,
+ #[serde(default)]
+ pub(super) agent_id: String,
+ #[serde(default)]
+ pub(super) elapsed_ms: u64,
+}
+
+/// A terminal file as older builds wrote it: the record, or the bare outcome.
+#[derive(serde::Deserialize)]
+#[serde(untagged)]
+enum CompatibleTerminalRecord {
+ Current(TerminalRecord),
+ Legacy(SubagentOutcome),
+}
+
+impl From<CompatibleTerminalRecord> for TerminalRecord {
+ fn from(record: CompatibleTerminalRecord) -> Self {
+ match record {
+ CompatibleTerminalRecord::Current(record) => record,
+ CompatibleTerminalRecord::Legacy(outcome) => Self {
+ outcome,
+ agent_id: String::new(),
+ elapsed_ms: 0,
+ },
+ }
+ }
+}
+
+/// Everything durable about one scoped task key.
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+pub(super) struct LifecycleRecord {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) pause: Option<SubagentCheckpointData>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub(super) terminal: Option<TerminalRecord>,
+}
+
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+struct TaskIndex {
+ #[serde(default)]
+ keys: Vec<SubagentTaskKey>,
+}
+
+fn failure(error: impl std::fmt::Display) -> SubagentError {
+ SubagentError::Persistence(format!("{error:#}"))
+}
+
+fn hex(value: &str) -> String {
+ value
+ .as_bytes()
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect()
+}
+
+/// A task key normally contains short UUID-like identifiers, for which the
+/// reversible encoding preserves the old file names. A background child may
+/// inherit a rendered parent identifier, however; that exceptional form is
+/// hashed while keeping every key field in the digest input so distinct
+/// lifecycle scopes cannot alias.
+fn bounded(encoded: String) -> String {
+ if encoded.len() <= 180 {
+ encoded
+ } else {
+ format!("sha256-{:x}", Sha256::digest(encoded.as_bytes()))
+ }
+}
+
+pub(super) fn key_component(key: &SubagentTaskKey) -> String {
+ bounded(format!(
+ "{}-{}-{}-{}",
+ hex(&key.root_run_id),
+ hex(&key.parent_run_id),
+ hex(key.thread_id.as_deref().unwrap_or("")),
+ hex(&key.task_id),
+ ))
+}
+
+pub(super) fn task_component(task_id: &str) -> String {
+ bounded(hex(task_id))
+}
+
+/// The workspace a checkpoint directory belongs to: the one above
+/// `.openhuman/subagent_checkpoints`, else the directory itself.
+fn workspace_of(checkpoint_dir: &Path) -> PathBuf {
+ let tail = checkpoint_dir.file_name().and_then(|name| name.to_str());
+ let parent = checkpoint_dir.parent();
+ if tail == Some("subagent_checkpoints")
+ && parent
+ .and_then(Path::file_name)
+ .and_then(|name| name.to_str())
+ == Some(".openhuman")
+ {
+ if let Some(workspace) = parent.and_then(Path::parent) {
+ return workspace.to_path_buf();
+ }
+ }
+ checkpoint_dir.to_path_buf()
+}
+
+/// The lifecycle store of one checkpoint directory's workspace.
+pub(super) struct LifecycleStore {
+ kv: StateKv,
+}
+
+impl LifecycleStore {
+ /// Opens the store for `checkpoint_dir`, importing its legacy lifecycle
+ /// files once.
+ pub(super) fn open(checkpoint_dir: &Path) -> Result<Self, SubagentError> {
+ let kv = StateKv::open(&workspace_of(checkpoint_dir), OWNER, NS).map_err(failure)?;
+ let legacy = checkpoint_dir.join("lifecycle");
+ kv.import_once(IMPORT, || import_legacy(&kv, &legacy))
+ .map_err(failure)?;
+ Ok(Self { kv })
+ }
+
+ fn record_name(key: &SubagentTaskKey) -> String {
+ format!("record/{}", key_component(key))
+ }
+
+ fn index_name(task_id: &str) -> String {
+ format!("index/{}", task_component(task_id))
+ }
+
+ /// The record of `key` (empty when nothing was written).
+ pub(super) fn record(&self, key: &SubagentTaskKey) -> Result<LifecycleRecord, SubagentError> {
+ Ok(self
+ .kv
+ .get(&Self::record_name(key))
+ .map_err(failure)?
+ .unwrap_or_default())
+ }
+
+ /// Changes the record of `key` under compare-and-swap; `change` may run
+ /// more than once, and returns its result and whether it changed the record.
+ pub(super) fn update<R: Send + 'static>(
+ &self,
+ key: &SubagentTaskKey,
+ change: impl Fn(&mut LifecycleRecord) -> (R, bool) + Send + Sync + 'static,
+ ) -> Result<R, SubagentError> {
+ self.kv
+ .update(&Self::record_name(key), change)
+ .map_err(failure)
+ }
+
+ /// The scoped keys that share `task_id`.
+ pub(super) fn index_keys(&self, task_id: &str) -> Result<Vec<SubagentTaskKey>, SubagentError> {
+ Ok(self
+ .kv
+ .get::<TaskIndex>(&Self::index_name(task_id))
+ .map_err(failure)?
+ .unwrap_or_default()
+ .keys)
+ }
+
+ pub(super) fn add_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let key = key.clone();
+ self.kv
+ .update::<TaskIndex, ()>(&Self::index_name(&key.task_id), {
+ let key = key.clone();
+ move |index| {
+ if index.keys.contains(&key) {
+ return ((), false);
+ }
+ index.keys.push(key.clone());
+ ((), true)
+ }
+ })
+ .map_err(failure)
+ }
+
+ pub(super) fn remove_index_key(&self, key: &SubagentTaskKey) -> Result<(), SubagentError> {
+ let key = key.clone();
+ self.kv
+ .update::<TaskIndex, ()>(&Self::index_name(&key.task_id), {
+ let key = key.clone();
+ move |index| {
+ let before = index.keys.len();
+ index.keys.retain(|candidate| candidate != &key);
+ ((), index.keys.len() != before)
+ }
+ })
+ .map_err(failure)
+ }
+}
+
+/// Copies the legacy lifecycle files of `dir`, never replacing a record that
+/// already holds the part a file carries.
+fn import_legacy(kv: &StateKv, dir: &Path) -> anyhow::Result<()> {
+ let entries = match std::fs::read_dir(dir) {
+ Ok(entries) => entries,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error.into()),
+ };
+ let mut imported = 0usize;
+ for entry in entries {
+ let path = entry?.path();
+ let Some(file) = path.file_name().and_then(|name| name.to_str()) else {
+ continue;
+ };
+ let bytes = match std::fs::read(&path) {
+ Ok(bytes) => bytes,
+ Err(error) => {
+ log::warn!("[subagent:lifecycle] legacy {file} unreadable ({error}); skipped");
+ continue;
+ }
+ };
+ if let Some(component) = file.strip_suffix(".pause.json") {
+ match serde_json::from_slice::<SubagentCheckpointData>(&bytes) {
+ Ok(pause) => {
+ kv.update::<LifecycleRecord, ()>(&format!("record/{component}"), move |r| {
+ if r.pause.is_none() {
+ r.pause = Some(pause.clone());
+ ((), true)
+ } else {
+ ((), false)
+ }
+ })?;
+ imported += 1;
+ }
+ Err(error) => log::warn!(
+ "[subagent:lifecycle] legacy pause {component} unparsable ({error}); skipped"
+ ),
+ }
+ } else if let Some(component) = file.strip_suffix(".terminal.json") {
+ match serde_json::from_slice::<CompatibleTerminalRecord>(&bytes) {
+ Ok(terminal) => {
+ let terminal = TerminalRecord::from(terminal);
+ kv.update::<LifecycleRecord, ()>(&format!("record/{component}"), move |r| {
+ if r.terminal.is_none() {
+ r.terminal = Some(terminal.clone());
+ ((), true)
+ } else {
+ ((), false)
+ }
+ })?;
+ imported += 1;
+ }
+ Err(error) => log::warn!(
+ "[subagent:lifecycle] legacy terminal {component} unparsable ({error}); skipped"
+ ),
+ }
+ } else if let Some(component) = file
+ .strip_prefix("task-")
+ .and_then(|rest| rest.strip_suffix(".index.json"))
+ {
+ let value: serde_json::Value = match serde_json::from_slice(&bytes) {
+ Ok(value) => value,
+ Err(error) => {
+ log::warn!("[subagent:lifecycle] legacy index {component} unparsable ({error})");
+ continue;
+ }
+ };
+ // The short-lived single-key format of the first lifecycle
+ // extraction is read as a one-key list.
+ let keys: Vec<SubagentTaskKey> = value
+ .get("keys")
+ .cloned()
+ .and_then(|keys| serde_json::from_value(keys).ok())
+ .or_else(|| {
+ value
+ .get("key")
+ .cloned()
+ .and_then(|key| serde_json::from_value(key).ok())
+ .map(|key| vec![key])
+ })
+ .unwrap_or_default();
+ kv.update::<TaskIndex, ()>(&format!("index/{component}"), move |index| {
+ let mut changed = false;
+ for key in &keys {
+ if !index.keys.contains(key) {
+ index.keys.push(key.clone());
+ changed = true;
+ }
+ }
+ ((), changed)
+ })?;
+ imported += 1;
+ }
+ }
+ log::debug!("[subagent:lifecycle] imported {imported} legacy lifecycle files");
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "lifecycle_store_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_store_tests.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_store_tests.rs
new file mode 100644
index 0000000000..bda2181c84
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_store_tests.rs
@@ -0,0 +1,108 @@
+use super::*;
+
+fn key(task: &str) -> SubagentTaskKey {
+ SubagentTaskKey {
+ root_run_id: "root".into(),
+ parent_run_id: "parent".into(),
+ thread_id: Some("thread".into()),
+ task_id: task.into(),
+ }
+}
+
+fn pause_json(key: &SubagentTaskKey) -> serde_json::Value {
+ serde_json::json!({
+ "task_key": key,
+ "task_id": key.task_id,
+ "agent_id": "researcher",
+ "history": [],
+ "question": "which one?",
+ "created_at": "2026-10-01T00:00:00Z",
+ "output": "partial",
+ "iterations": 2,
+ "usage": {},
+ "artifact_paths": [],
+ "elapsed_ms": 40
+ })
+}
+
+#[test]
+fn a_legacy_lifecycle_directory_is_imported_once_and_left_in_place() {
+ let dir = tempfile::tempdir().unwrap();
+ let lifecycle = dir.path().join("lifecycle");
+ std::fs::create_dir_all(&lifecycle).unwrap();
+ let paused = key("task-a");
+ let component = key_component(&paused);
+ std::fs::write(
+ lifecycle.join(format!("{component}.pause.json")),
+ serde_json::to_vec_pretty(&pause_json(&paused)).unwrap(),
+ )
+ .unwrap();
+ // The first lifecycle extraction wrote the index with a single `key`.
+ std::fs::write(
+ lifecycle.join(format!("task-{}.index.json", task_component("task-a"))),
+ serde_json::to_vec(&serde_json::json!({"key": paused})).unwrap(),
+ )
+ .unwrap();
+
+ let store = LifecycleStore::open(dir.path()).unwrap();
+ let record = store.record(&paused).unwrap();
+ assert_eq!(record.pause.unwrap().question, "which one?");
+ assert_eq!(store.index_keys("task-a").unwrap(), vec![paused.clone()]);
+ assert!(lifecycle
+ .join(format!("{component}.pause.json"))
+ .exists());
+
+ // A later change is not undone by reopening, which does not import again.
+ store
+ .update(&paused, |record| {
+ record.pause = None;
+ ((), true)
+ })
+ .unwrap();
+ let reopened = LifecycleStore::open(dir.path()).unwrap();
+ assert!(reopened.record(&paused).unwrap().pause.is_none());
+}
+
+#[test]
+fn a_legacy_bare_terminal_outcome_is_read_as_a_terminal_record() {
+ let dir = tempfile::tempdir().unwrap();
+ let lifecycle = dir.path().join("lifecycle");
+ std::fs::create_dir_all(&lifecycle).unwrap();
+ let done = key("task-b");
+ let mut outcome = SubagentOutcome::cancelled("task-b");
+ outcome.output = "finished".into();
+ std::fs::write(
+ lifecycle.join(format!("{}.terminal.json", key_component(&done))),
+ serde_json::to_vec(&outcome).unwrap(),
+ )
+ .unwrap();
+ std::fs::write(lifecycle.join("notes.txt"), "not a lifecycle file").unwrap();
+
+ let record = LifecycleStore::open(dir.path()).unwrap().record(&done).unwrap();
+ let terminal = record.terminal.unwrap();
+ assert_eq!(terminal.outcome.output, "finished");
+ assert!(terminal.agent_id.is_empty());
+}
+
+#[test]
+fn the_default_checkpoint_directory_belongs_to_its_workspace() {
+ let workspace = std::path::Path::new("/w/space");
+ assert_eq!(
+ workspace_of(&workspace.join(".openhuman/subagent_checkpoints")),
+ workspace
+ );
+ assert_eq!(workspace_of(std::path::Path::new("/x/y")), std::path::Path::new("/x/y"));
+}
+
+#[test]
+fn an_oversized_key_component_is_hashed_so_distinct_keys_do_not_alias() {
+ let long = |task: &str| SubagentTaskKey {
+ root_run_id: "root".repeat(100),
+ parent_run_id: "parent".repeat(100),
+ thread_id: None,
+ task_id: task.into(),
+ };
+ let (a, b) = (key_component(&long("a")), key_component(&long("b")));
+ assert!(a.starts_with("sha256-") && a.len() < 80);
+ assert_ne!(a, b);
+}