Skip to content

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

refactor(tinyagents): extract dispatch control into its own module

Steven Enamakelefdb9632c5f5
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control.rs b/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control.rs
new file mode 100644
index 0000000000..73a5036fcd
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control.rs
@@ -0,0 +1,118 @@
+//! Host-owned pre-dispatch policy and per-turn evidence used to decide whether a child may start.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::time::{Duration, Instant};
+
+/// Immutable inputs to the host's pre-dispatch policy.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DispatchInputs {
+ pub pause_requested: bool,
+ pub pause_completed_calls: u64,
+ pub pause_cap: u64,
+ pub remaining: Option<Duration>,
+ pub observed_max: Option<Duration>,
+ pub observed_samples: u64,
+}
+
+/// Outcome of the host's pre-dispatch policy.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DispatchDecision {
+ Allow,
+ RefusePaused {
+ completed_model_calls: u64,
+ cap: u64,
+ },
+ RefuseBudget {
+ remaining_ms: u64,
+ observed_max_ms: u64,
+ observed_samples: u64,
+ },
+}
+
+/// Decide whether a child can be started using only evidence recorded on this
+/// turn. This stays host policy: TinyAgents owns the loop, not OpenHuman's
+/// pause and wall-clock refusal rules.
+pub fn decide_dispatch(inputs: DispatchInputs) -> DispatchDecision {
+ if inputs.pause_requested {
+ return DispatchDecision::RefusePaused {
+ completed_model_calls: inputs.pause_completed_calls,
+ cap: inputs.pause_cap,
+ };
+ }
+ let (Some(remaining), Some(observed_max)) = (inputs.remaining, inputs.observed_max) else {
+ return DispatchDecision::Allow;
+ };
+ if remaining < observed_max {
+ return DispatchDecision::RefuseBudget {
+ remaining_ms: remaining.as_millis().min(u128::from(u64::MAX)) as u64,
+ observed_max_ms: observed_max.as_millis().min(u128::from(u64::MAX)) as u64,
+ observed_samples: inputs.observed_samples,
+ };
+ }
+ DispatchDecision::Allow
+}
+
+/// Shared root-turn state used by all synchronous descendants and siblings to
+/// decide whether starting another delegate is still safe.
+#[derive(Debug)]
+pub struct TurnDispatchState {
+ pause_requested: AtomicBool,
+ pause_completed_calls: AtomicU64,
+ pause_cap: AtomicU64,
+ started: Instant,
+ budget: Option<Duration>,
+ observed_max_ms: AtomicU64,
+ observed_samples: AtomicU64,
+}
+
+impl TurnDispatchState {
+ pub fn new(budget: Option<Duration>) -> Self {
+ Self {
+ pause_requested: AtomicBool::new(false),
+ pause_completed_calls: AtomicU64::new(0),
+ pause_cap: AtomicU64::new(0),
+ started: Instant::now(),
+ budget,
+ observed_max_ms: AtomicU64::new(0),
+ observed_samples: AtomicU64::new(0),
+ }
+ }
+
+ pub fn record_pause_requested(&self, completed_model_calls: u64, cap: u64) {
+ self.pause_completed_calls
+ .store(completed_model_calls, Ordering::SeqCst);
+ self.pause_cap.store(cap, Ordering::SeqCst);
+ self.pause_requested.store(true, Ordering::SeqCst);
+ }
+
+ pub fn record_subagent_elapsed(&self, elapsed: Duration) {
+ let ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64;
+ self.observed_samples.fetch_add(1, Ordering::SeqCst);
+ self.observed_max_ms.fetch_max(ms, Ordering::SeqCst);
+ }
+
+ pub fn snapshot(&self) -> DispatchInputs {
+ let observed_max = match self.observed_max_ms.load(Ordering::SeqCst) {
+ 0 => None,
+ ms => Some(Duration::from_millis(ms)),
+ };
+ DispatchInputs {
+ pause_requested: self.pause_requested.load(Ordering::SeqCst),
+ pause_completed_calls: self.pause_completed_calls.load(Ordering::SeqCst),
+ pause_cap: self.pause_cap.load(Ordering::SeqCst),
+ remaining: self
+ .budget
+ .map(|budget| budget.saturating_sub(self.started.elapsed())),
+ observed_max,
+ observed_samples: self.observed_samples.load(Ordering::SeqCst),
+ }
+ }
+
+ pub fn check(&self) -> DispatchDecision {
+ decide_dispatch(self.snapshot())
+ }
+}
+
+#[cfg(test)]
+#[path = "dispatch_control_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control_tests.rs
new file mode 100644
index 0000000000..2fb886cde9
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/host/dispatch_control_tests.rs
@@ -0,0 +1,126 @@
+use super::*;
+use super::super::{OpenHumanRunContext, SubagentUsageEntry};
+use std::sync::Arc;
+
+#[test]
+fn dispatch_guard_refuses_pause_and_budget_without_a_task_scope() {
+ let paused = TurnDispatchState::new(Some(std::time::Duration::from_secs(60)));
+ paused.record_pause_requested(15, 15);
+ assert_eq!(
+ paused.check(),
+ DispatchDecision::RefusePaused {
+ completed_model_calls: 15,
+ cap: 15,
+ }
+ );
+
+ // A zero budget makes the time relationship deterministic: after an
+ // observed child, any check is strictly short of that child's duration.
+ let exhausted = TurnDispatchState::new(Some(std::time::Duration::ZERO));
+ exhausted.record_subagent_elapsed(std::time::Duration::from_secs(1));
+ assert!(matches!(
+ exhausted.check(),
+ DispatchDecision::RefuseBudget {
+ observed_max_ms: 1_000,
+ observed_samples: 1,
+ ..
+ }
+ ));
+}
+
+#[test]
+fn detached_children_reset_turn_accounting_and_cancellation() {
+ let mut root = OpenHumanRunContext::new();
+ root.thread_id = Some("thread-a".into());
+ let dispatch = Arc::new(TurnDispatchState::new(Some(std::time::Duration::ZERO)));
+ dispatch.record_subagent_elapsed(std::time::Duration::from_secs(1));
+ root.dispatch = Some(dispatch);
+ let detached = root.detached_child();
+
+ assert_eq!(detached.thread_id.as_deref(), Some("thread-a"));
+ assert!(detached.dispatch.is_none());
+ root.cancellation.cancel();
+ assert!(!detached.cancellation.is_cancelled());
+ detached.record_completed_subagent_usage(SubagentUsageEntry {
+ task_id: "background".into(),
+ agent_id: "archivist".into(),
+ usage: Default::default(),
+ });
+ assert!(root.subagent_usage_entries().is_empty());
+ assert_eq!(detached.subagent_usage_entries().len(), 1);
+}
+
+#[test]
+fn child_inherits_the_same_physical_dispatch_admission() {
+ let admission: Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchAdmission> =
+ Arc::new(TestAdmission);
+ let env = crate::agent::turn_env::HostTurnEnv {
+ dispatch_admission: Some(admission.clone()),
+ ..Default::default()
+ };
+
+ let parent = OpenHumanRunContext::new().with_host_env(&env);
+ let child = parent.child();
+
+ assert!(Arc::ptr_eq(
+ parent.dispatch_admission.as_ref().unwrap(),
+ child.dispatch_admission.as_ref().unwrap()
+ ));
+ assert!(Arc::ptr_eq(&parent.session_sidecar, &child.session_sidecar));
+}
+
+#[test]
+fn detached_child_inherits_the_parent_dispatch_admission() {
+ let admission: Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchAdmission> =
+ Arc::new(TestAdmission);
+ let parent = OpenHumanRunContext {
+ dispatch_admission: Some(admission),
+ ..OpenHumanRunContext::new()
+ };
+
+ assert!(Arc::ptr_eq(
+ parent.dispatch_admission.as_ref().unwrap(),
+ parent.detached_child().dispatch_admission.as_ref().unwrap()
+ ));
+ assert!(!Arc::ptr_eq(
+ &parent.session_sidecar,
+ &parent.detached_child().session_sidecar
+ ));
+}
+
+#[test]
+fn independently_created_root_turns_have_isolated_dispatch_refusal_sidecars() {
+ let first = OpenHumanRunContext::new();
+ let second = OpenHumanRunContext::new();
+ let refusal = crate::agent::tinyagents::budget::DispatchRefusal::new(
+ crate::agent::tinyagents::budget::DispatchRefusalReason::CallLimit,
+ );
+
+ assert!(!Arc::ptr_eq(
+ &first.session_sidecar,
+ &second.session_sidecar
+ ));
+ first.session_sidecar.lock().unwrap().dispatch_refusal = Some(refusal);
+ assert!(second
+ .session_sidecar
+ .lock()
+ .unwrap()
+ .dispatch_refusal
+ .is_none());
+}
+
+struct TestAdmission;
+
+#[async_trait::async_trait]
+impl crate::agent::tinyagents::budget::PhysicalDispatchAdmission for TestAdmission {
+ async fn acquire(
+ &self,
+ ) -> Result<
+ Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchPermit>,
+ crate::agent::tinyagents::budget::DispatchRefusal,
+ > {
+ Err(crate::agent::tinyagents::budget::DispatchRefusal::new(
+ crate::agent::tinyagents::budget::DispatchRefusalReason::CallLimit,
+ ))
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index edb2b955db..9227d96e61 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -9,10 +9,8 @@
//! so every host seam receives the same explicit carrier rather than recovering
//! product state from a task-local.
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
-use std::time::Instant;
use tokio::sync::mpsc::Sender;
@@ -152,115 +150,8 @@ pub(crate) struct SessionTurnSidecar {
pub deferred_terminal: Option<crate::agent::tinyagents::turn_outcome::DeferredTurnTerminal>,
}
-/// Immutable inputs to the host's pre-dispatch policy.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct DispatchInputs {
- pub pause_requested: bool,
- pub pause_completed_calls: u64,
- pub pause_cap: u64,
- pub remaining: Option<Duration>,
- pub observed_max: Option<Duration>,
- pub observed_samples: u64,
-}
-
-/// Outcome of the host's pre-dispatch policy.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum DispatchDecision {
- Allow,
- RefusePaused {
- completed_model_calls: u64,
- cap: u64,
- },
- RefuseBudget {
- remaining_ms: u64,
- observed_max_ms: u64,
- observed_samples: u64,
- },
-}
-
-/// Decide whether a child can be started using only evidence recorded on this
-/// turn. This stays host policy: TinyAgents owns the loop, not OpenHuman's
-/// pause and wall-clock refusal rules.
-pub fn decide_dispatch(inputs: DispatchInputs) -> DispatchDecision {
- if inputs.pause_requested {
- return DispatchDecision::RefusePaused {
- completed_model_calls: inputs.pause_completed_calls,
- cap: inputs.pause_cap,
- };
- }
- let (Some(remaining), Some(observed_max)) = (inputs.remaining, inputs.observed_max) else {
- return DispatchDecision::Allow;
- };
- if remaining < observed_max {
- return DispatchDecision::RefuseBudget {
- remaining_ms: remaining.as_millis().min(u128::from(u64::MAX)) as u64,
- observed_max_ms: observed_max.as_millis().min(u128::from(u64::MAX)) as u64,
- observed_samples: inputs.observed_samples,
- };
- }
- DispatchDecision::Allow
-}
-
-/// Shared root-turn state used by all synchronous descendants and siblings to
-/// decide whether starting another delegate is still safe.
-#[derive(Debug)]
-pub struct TurnDispatchState {
- pause_requested: AtomicBool,
- pause_completed_calls: AtomicU64,
- pause_cap: AtomicU64,
- started: Instant,
- budget: Option<Duration>,
- observed_max_ms: AtomicU64,
- observed_samples: AtomicU64,
-}
-
-impl TurnDispatchState {
- pub fn new(budget: Option<Duration>) -> Self {
- Self {
- pause_requested: AtomicBool::new(false),
- pause_completed_calls: AtomicU64::new(0),
- pause_cap: AtomicU64::new(0),
- started: Instant::now(),
- budget,
- observed_max_ms: AtomicU64::new(0),
- observed_samples: AtomicU64::new(0),
- }
- }
-
- pub fn record_pause_requested(&self, completed_model_calls: u64, cap: u64) {
- self.pause_completed_calls
- .store(completed_model_calls, Ordering::SeqCst);
- self.pause_cap.store(cap, Ordering::SeqCst);
- self.pause_requested.store(true, Ordering::SeqCst);
- }
-
- pub fn record_subagent_elapsed(&self, elapsed: Duration) {
- let ms = elapsed.as_millis().min(u128::from(u64::MAX)) as u64;
- self.observed_samples.fetch_add(1, Ordering::SeqCst);
- self.observed_max_ms.fetch_max(ms, Ordering::SeqCst);
- }
-
- pub fn snapshot(&self) -> DispatchInputs {
- let observed_max = match self.observed_max_ms.load(Ordering::SeqCst) {
- 0 => None,
- ms => Some(Duration::from_millis(ms)),
- };
- DispatchInputs {
- pause_requested: self.pause_requested.load(Ordering::SeqCst),
- pause_completed_calls: self.pause_completed_calls.load(Ordering::SeqCst),
- pause_cap: self.pause_cap.load(Ordering::SeqCst),
- remaining: self
- .budget
- .map(|budget| budget.saturating_sub(self.started.elapsed())),
- observed_max,
- observed_samples: self.observed_samples.load(Ordering::SeqCst),
- }
- }
-
- pub fn check(&self) -> DispatchDecision {
- decide_dispatch(self.snapshot())
- }
-}
+mod dispatch_control;
+pub use dispatch_control::{decide_dispatch, DispatchDecision, DispatchInputs, TurnDispatchState};
/// Explicit OpenHuman data carried by a top-level or child agent run.
///
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index ca5549bce9..c668ed1260 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -131,32 +131,6 @@ fn root_context_is_owned_and_children_inherit_thread() {
assert_eq!(root.child().thread_id.as_deref(), Some("thread-a"));
}
-#[test]
-fn dispatch_guard_refuses_pause_and_budget_without_a_task_scope() {
- let paused = TurnDispatchState::new(Some(std::time::Duration::from_secs(60)));
- paused.record_pause_requested(15, 15);
- assert_eq!(
- paused.check(),
- DispatchDecision::RefusePaused {
- completed_model_calls: 15,
- cap: 15,
- }
- );
-
- // A zero budget makes the time relationship deterministic: after an
- // observed child, any check is strictly short of that child's duration.
- let exhausted = TurnDispatchState::new(Some(std::time::Duration::ZERO));
- exhausted.record_subagent_elapsed(std::time::Duration::from_secs(1));
- assert!(matches!(
- exhausted.check(),
- DispatchDecision::RefuseBudget {
- observed_max_ms: 1_000,
- observed_samples: 1,
- ..
- }
- ));
-}
-
#[test]
fn child_ledgers_are_isolated_and_parent_keeps_completed_child_totals() {
let root = OpenHumanRunContext::new();
@@ -205,28 +179,6 @@ fn failed_outer_run_promotes_completed_nested_usage_once() {
assert_eq!(root.subagent_usage_entries()[0].task_id, "nested");
}
-#[test]
-fn detached_children_reset_turn_accounting_and_cancellation() {
- let mut root = OpenHumanRunContext::new();
- root.thread_id = Some("thread-a".into());
- let dispatch = Arc::new(TurnDispatchState::new(Some(std::time::Duration::ZERO)));
- dispatch.record_subagent_elapsed(std::time::Duration::from_secs(1));
- root.dispatch = Some(dispatch);
- let detached = root.detached_child();
-
- assert_eq!(detached.thread_id.as_deref(), Some("thread-a"));
- assert!(detached.dispatch.is_none());
- root.cancellation.cancel();
- assert!(!detached.cancellation.is_cancelled());
- detached.record_completed_subagent_usage(SubagentUsageEntry {
- task_id: "background".into(),
- agent_id: "archivist".into(),
- usage: Default::default(),
- });
- assert!(root.subagent_usage_entries().is_empty());
- assert_eq!(detached.subagent_usage_entries().len(), 1);
-}
-
#[test]
fn children_inherit_attachment_placeholders() {
let mut root = OpenHumanRunContext::new();
@@ -428,81 +380,6 @@ fn child_inherits_shared_model_budget_and_narrowed_depth_limit() {
);
}
-#[test]
-fn child_inherits_the_same_physical_dispatch_admission() {
- let admission: Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchAdmission> =
- Arc::new(TestAdmission);
- let env = crate::agent::turn_env::HostTurnEnv {
- dispatch_admission: Some(admission.clone()),
- ..Default::default()
- };
-
- let parent = OpenHumanRunContext::new().with_host_env(&env);
- let child = parent.child();
-
- assert!(Arc::ptr_eq(
- parent.dispatch_admission.as_ref().unwrap(),
- child.dispatch_admission.as_ref().unwrap()
- ));
- assert!(Arc::ptr_eq(&parent.session_sidecar, &child.session_sidecar));
-}
-
-#[test]
-fn detached_child_inherits_the_parent_dispatch_admission() {
- let admission: Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchAdmission> =
- Arc::new(TestAdmission);
- let parent = OpenHumanRunContext {
- dispatch_admission: Some(admission),
- ..OpenHumanRunContext::new()
- };
-
- assert!(Arc::ptr_eq(
- parent.dispatch_admission.as_ref().unwrap(),
- parent.detached_child().dispatch_admission.as_ref().unwrap()
- ));
- assert!(!Arc::ptr_eq(
- &parent.session_sidecar,
- &parent.detached_child().session_sidecar
- ));
-}
-
-#[test]
-fn independently_created_root_turns_have_isolated_dispatch_refusal_sidecars() {
- let first = OpenHumanRunContext::new();
- let second = OpenHumanRunContext::new();
- let refusal = crate::agent::tinyagents::budget::DispatchRefusal::new(
- crate::agent::tinyagents::budget::DispatchRefusalReason::CallLimit,
- );
-
- assert!(!Arc::ptr_eq(
- &first.session_sidecar,
- &second.session_sidecar
- ));
- first.session_sidecar.lock().unwrap().dispatch_refusal = Some(refusal);
- assert!(second
- .session_sidecar
- .lock()
- .unwrap()
- .dispatch_refusal
- .is_none());
-}
-
-struct TestAdmission;
-
-#[async_trait::async_trait]
-impl crate::agent::tinyagents::budget::PhysicalDispatchAdmission for TestAdmission {
- async fn acquire(
- &self,
- ) -> Result<
- Arc<dyn crate::agent::tinyagents::budget::PhysicalDispatchPermit>,
- crate::agent::tinyagents::budget::DispatchRefusal,
- > {
- Err(crate::agent::tinyagents::budget::DispatchRefusal::new(
- crate::agent::tinyagents::budget::DispatchRefusalReason::CallLimit,
- ))
- }
-}
-
#[test]
fn task_recency_window_reaches_tools_as_a_host_extension_not_a_task_local() {
let mut host = OpenHumanRunContext::new();
diff --git a/crates/openhuman-core/src/threads/welcome_migration_tests.rs b/crates/openhuman-core/src/threads/welcome_migration_tests.rs
deleted file mode 100644
index d83cee7236..0000000000
--- a/crates/openhuman-core/src/threads/welcome_migration_tests.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-use super::*;
-use crate::threads::store::{ensure_thread, list_threads, CreateConversationThread};
-use tempfile::TempDir;
-
-fn make_thread(id: &str, labels: Vec<String>) -> CreateConversationThread {
- CreateConversationThread {
- id: id.to_string(),
- title: format!("Test thread {id}"),
- created_at: "2024-01-01T00:00:00Z".to_string(),
- parent_thread_id: None,
- labels: Some(labels),
- personality_id: None,
- working_dir: None,
- }
-}
-
-fn write_transcript(path: &Path, agent: &str, thread_id: &str) {
- let body = format!(
- "{{\"_meta\":{{\"agent\":\"{agent}\",\"dispatcher\":\"native\",\"created\":\"2026-05-01T00:00:00Z\",\"updated\":\"2026-05-01T00:00:00Z\",\"turn_count\":1,\"input_tokens\":0,\"output_tokens\":0,\"cached_input_tokens\":0,\"charged_amount_usd\":0.0,\"thread_id\":\"{thread_id}\"}}}}\n{{\"role\":\"user\",\"content\":\"hi\"}}\n"
- );
- fs::create_dir_all(path.parent().unwrap()).unwrap();
- fs::write(path, body).unwrap();
-}
-
-#[test]
-fn migration_updates_thread_labels_and_transcripts() {
- let tmp = TempDir::new().unwrap();
- let workspace = tmp.path();
-
- ensure_thread(
- &crate::core::runtime::DispatchCtx::ambient(),
- workspace.to_path_buf(),
- make_thread(
- "welcome-thread",
- vec!["onboarding".into(), "personal".into()],
- ),
- )
- .unwrap();
-
- let raw = workspace.join("session_raw/1715000000_welcome_thread-abc.jsonl");
- write_transcript(&raw, "welcome_thread-abc", "thread-abc");
- let md = workspace.join("sessions/2026_05_01/1715000000_welcome_thread-abc.md");
- fs::create_dir_all(md.parent().unwrap()).unwrap();
- fs::write(&md, "# Session transcript — welcome_thread-abc\n").unwrap();
-
- let result =
- migrate_welcome_agent_artifacts(&crate::core::runtime::DispatchCtx::ambient(), workspace)
- .unwrap();
-
- assert_eq!(result.threads_updated, 1);
- assert_eq!(result.transcripts_updated, 1);
- assert_eq!(result.transcript_files_renamed, 1);
- assert_eq!(result.markdown_files_renamed, 1);
-
- let threads = list_threads(
- &crate::core::runtime::DispatchCtx::ambient(),
- workspace.to_path_buf(),
- )
- .unwrap();
- let thread = threads
- .iter()
- .find(|thread| thread.id == "welcome-thread")
- .unwrap();
- assert_eq!(thread.labels, vec!["personal"]);
-
- let renamed = workspace.join("session_raw/1715000000_orchestrator_thread-abc.jsonl");
- assert!(renamed.exists(), "renamed transcript should exist");
- let contents = fs::read_to_string(&renamed).unwrap();
- assert!(
- contents.contains("\"agent\":\"orchestrator_thread-abc\""),
- "transcript metadata should be rewritten: {contents}"
- );
- assert!(
- workspace
- .join("sessions/2026_05_01/1715000000_orchestrator_thread-abc.md")
- .exists(),
- "markdown companion should be renamed"
- );
- assert!(workspace.join(MIGRATION_MARKER).exists());
-}
-
-#[test]
-fn migration_is_idempotent_after_marker() {
- let tmp = TempDir::new().unwrap();
- let workspace = tmp.path();
- fs::create_dir_all(workspace.join("state/migrations")).unwrap();
- fs::write(workspace.join(MIGRATION_MARKER), b"done\n").unwrap();
-
- let result =
- migrate_welcome_agent_artifacts(&crate::core::runtime::DispatchCtx::ambient(), workspace)
- .unwrap();
- assert!(result.already_done);
- assert_eq!(result.threads_updated, 0);
- assert_eq!(result.transcripts_updated, 0);
-}
-
-#[test]
-fn migration_returns_error_without_marker_when_destination_exists() {
- let tmp = TempDir::new().unwrap();
- let workspace = tmp.path();
-
- let raw = workspace.join("session_raw/1715000000_welcome_thread-abc.jsonl");
- write_transcript(&raw, "welcome_thread-abc", "thread-abc");
- let dest = workspace.join("session_raw/1715000000_orchestrator_thread-abc.jsonl");
- write_transcript(&dest, "orchestrator_thread-abc", "thread-abc");
-
- let err =
- migrate_welcome_agent_artifacts(&crate::core::runtime::DispatchCtx::ambient(), workspace)
- .unwrap_err();
-
- assert!(
- err.contains("partial migration"),
- "expected partial-migration error, got: {err}"
- );
- let contents = fs::read_to_string(&raw).unwrap();
- assert!(
- contents.contains("\"agent\":\"welcome_thread-abc\""),
- "blocked rename should leave legacy metadata untouched: {contents}"
- );
- assert!(
- !workspace.join(MIGRATION_MARKER).exists(),
- "partial migration must not write marker"
- );
-}