Skip to content

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

fix(agent): correct journal entry ordering in reaper

Steven Enamakel59b8cf4e0d6e
diff --git a/crates/openhuman-core/src/agent/tinyagents/journal.rs b/crates/openhuman-core/src/agent/tinyagents/journal.rs
index a299ef481e..286b01053e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs
@@ -74,21 +74,6 @@ const STATUS_NS: &str = "run_status";
static REQUEST_JOURNAL_RUNS: Lazy<Mutex<HashMap<String, String>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
-/// Mints a fresh, slash-free, process-unique run id (`run.<32-hex>`), used three
-/// ways for one turn: the [`EventSink::with_stream_id`] prefix (so persisted
-/// `event_id`s are the restart-stable `{run_id}-evt-{offset}`), the journal
-/// stream key, and the status-store key. The `simple()` uuid form (no hyphens)
-/// keeps the id inside the crate store's allowed-character set.
-///
-/// The caller mints this *before* creating the run [`EventSink`] so the same id
-/// seeds the sink stream prefix and the durable journal/status — see
-/// [`attach_turn_journal`].
-///
-/// [`EventSink::with_stream_id`]: tinyagents_harness::events::EventSink::with_stream_id
-pub(crate) fn mint_run_id() -> RunId {
- RunId::new(format!("run.{}", uuid::Uuid::new_v4().simple()))
-}
-
pub(crate) fn register_request_journal_run(request_id: &str, run_id: &str) {
match REQUEST_JOURNAL_RUNS.lock() {
Ok(mut runs) => {
@@ -125,139 +110,6 @@ async fn resolve_workspace() -> anyhow::Result<PathBuf> {
Ok(config.workspace_dir)
}
-/// The OpenHuman journal redaction policy (issue #4249, 05.1).
-///
-/// The crate [`RedactingSink`] masks configured secret substrings anywhere they
-/// appear in a serialized event before the observation is persisted. This policy
-/// seeds it with the process's credential material — the values of environment
-/// variables whose name looks like a secret (contains `KEY` / `TOKEN` / `SECRET`
-/// / `PASSWORD` / `PASSWD` / `CREDENTIAL` / `BEARER`) — so an API key or bearer
-/// token echoed into model text, a tool argument fragment, or an error string is
-/// never written to the durable journal in the clear. Only reasonably long
-/// values (>= 8 chars) are masked, so unrelated short config values are left
-/// alone. Minimal but real: it does not persist raw secrets, and structural
-/// prompt/PII stripping is a follow-up if the event vocabulary grows to carry
-/// full prompts.
-fn openhuman_redaction_secrets() -> Vec<String> {
- const MARKERS: [&str; 7] = [
- "KEY",
- "TOKEN",
- "SECRET",
- "PASSWORD",
- "PASSWD",
- "CREDENTIAL",
- "BEARER",
- ];
- let mut secrets = Vec::new();
- for (name, value) in std::env::vars() {
- let upper = name.to_ascii_uppercase();
- if MARKERS.iter().any(|m| upper.contains(m)) && value.trim().len() >= 8 {
- secrets.push(value);
- }
- }
- log::debug!(
- "[journal] redaction policy seeded with {} secret value(s)",
- secrets.len()
- );
- secrets
-}
-
-/// A durable [`HarnessStatusStore`] backed by a crate [`FileStore`] KV
-/// namespace.
-///
-/// The crate ships only an in-memory [`HarnessStatusStore`]
-/// (`InMemoryStatusStore`), which does not survive a process restart — useless
-/// for the "reattach after the UI died and see what is still running" use case
-/// this slice targets. This small `Store`-backed impl overwrites one
-/// `run_status/<run_id>.json` file per run (compact snapshot: ids, phase,
-/// counters, timestamps, error — never prompts or payloads) and answers the
-/// lineage/liveness queries by enumerating the namespace via
-/// [`Store::list`]. `list_by_root` is what lets a supervisor find "every active
-/// descendant of this root run".
-pub(crate) struct FileStatusStore {
- kv: FileStore,
-}
-
-impl FileStatusStore {
- /// Wrap the workspace kv store as a durable status store.
- pub(crate) fn new(kv: FileStore) -> Self {
- Self { kv }
- }
-
- /// Enumerate every persisted status snapshot (best-effort per-record decode:
- /// a corrupt/legacy record is skipped, never fatal).
- async fn all(&self) -> TaResult<Vec<HarnessRunStatus>> {
- let keys = self.kv.list(STATUS_NS).await?;
- let mut out = Vec::with_capacity(keys.len());
- for key in keys {
- if let Some(value) = self.kv.get(STATUS_NS, &key).await? {
- match serde_json::from_value::<HarnessRunStatus>(value) {
- Ok(status) => out.push(status),
- Err(err) => {
- log::debug!("[journal] skipping undecodable run status key={key} err={err}")
- }
- }
- }
- }
- Ok(out)
- }
-}
-
-#[async_trait]
-impl HarnessStatusStore for FileStatusStore {
- async fn put_status(&self, status: HarnessRunStatus) -> TaResult<()> {
- let key = status.run_id.as_str().to_string();
- let value = serde_json::to_value(&status)?;
- self.kv.put(STATUS_NS, &key, value).await
- }
-
- async fn get_status(&self, run_id: &str) -> TaResult<Option<HarnessRunStatus>> {
- match self.kv.get(STATUS_NS, run_id).await? {
- Some(value) => Ok(Some(serde_json::from_value(value)?)),
- None => Ok(None),
- }
- }
-
- async fn list_by_thread(&self, thread_id: &str) -> TaResult<Vec<HarnessRunStatus>> {
- Ok(self
- .all()
- .await?
- .into_iter()
- .filter(|s| {
- s.thread_id
- .as_ref()
- .is_some_and(|t| t.as_str() == thread_id)
- })
- .collect())
- }
-
- async fn list_by_root(&self, root_run_id: &str) -> TaResult<Vec<HarnessRunStatus>> {
- Ok(self
- .all()
- .await?
- .into_iter()
- .filter(|s| s.root_run_id.as_str() == root_run_id)
- .collect())
- }
-
- async fn list_active(&self) -> TaResult<Vec<HarnessRunStatus>> {
- use tinyagents_harness::ids::ExecutionStatus;
- Ok(self
- .all()
- .await?
- .into_iter()
- .filter(|s| {
- matches!(
- s.status,
- ExecutionStatus::Pending
- | ExecutionStatus::Running
- | ExecutionStatus::Interrupted
- )
- })
- .collect())
- }
-}
-
/// A live handle to a turn's durable journal + status snapshot.
///
/// Held by the turn loop for the duration of the run so it can stamp a terminal
@@ -274,14 +126,6 @@ pub(crate) struct TurnJournal {
}
impl TurnJournal {
- /// The durable run id — the journal stream key + status key a future replay
- /// RPC reads back via [`read_run_events`] / [`read_run_status`].
- // Part of the replay seam surfaced to the (follow-up) replay RPC.
- #[allow(dead_code)]
- pub(crate) fn run_id(&self) -> String {
- self.run_id.as_str().to_string()
- }
-
/// Best-effort terminal write: mark the run completed and persist. Non-fatal.
pub(crate) async fn finish_completed(&self) {
self.event_sink.flush();
@@ -361,7 +205,7 @@ pub(crate) async fn attach_turn_journal(
// observation's `event_id` is the stable `{run_id}-evt-{offset}`.
let journal: Arc<dyn HarnessEventJournal> = Arc::new(StoreEventJournal::new(stores.journal));
let journal_sink = Arc::new(JournalSink::new(journal, run_id.clone()));
- let redacting = RedactingSink::new(journal_sink.clone(), openhuman_redaction_secrets());
+ let redacting = RedactingSink::new(journal_sink.clone(), process_env_secrets());
// FanOutSink is the durable-observer composition seam (05.2 adds graph sinks
// here). Subscribing it as its own listener leaves the bridge subscription
@@ -405,9 +249,6 @@ pub(crate) async fn attach_turn_journal(
/// reconnect mid-run and backfill the timeline from durable state instead of
/// relying on transient `AgentProgress` buffering. Best-effort: a missing store
/// or unknown run yields an empty `Vec`, not an error.
-// Replay-RPC seam (05.x): no in-tree caller yet — the persisted journal is
-// provably replayable through this reader.
-#[allow(dead_code)]
pub(crate) async fn read_run_events(
run_id: &str,
from_offset: u64,
@@ -420,21 +261,3 @@ pub(crate) async fn read_run_events(
.await
.map_err(|e| anyhow::anyhow!("[journal] read_run_events failed run_id={run_id}: {e}"))
}
-
-/// Late-attach replay reader: the latest durable [`HarnessRunStatus`] for
-/// `run_id`, or `None` if unknown. Companion to [`read_run_events`] for the
-/// future replay RPC.
-#[allow(dead_code)]
-pub(crate) async fn read_run_status(run_id: &str) -> anyhow::Result<Option<HarnessRunStatus>> {
- let workspace = resolve_workspace().await?;
- let stores = open_session_stores(&workspace);
- let status = FileStatusStore::new(stores.kv);
- status
- .get_status(run_id)
- .await
- .map_err(|e| anyhow::anyhow!("[journal] read_run_status failed run_id={run_id}: {e}"))
-}
-
-#[cfg(test)]
-#[path = "journal_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/journal_tests.rs b/crates/openhuman-core/src/agent/tinyagents/journal_tests.rs
deleted file mode 100644
index b11e8867ab..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/journal_tests.rs
+++ /dev/null
@@ -1,235 +0,0 @@
-use super::*;
-use tinyagents_harness::events::AgentEvent;
-use tinyagents_harness::ids::ExecutionStatus;
-
-/// The full 05.1 acceptance in miniature: emit events through a sink with a
-/// durable journal attached, then reconstruct the timeline + terminal status
-/// from the store alone — the "kill the UI mid-turn, reattach, replay" path.
-#[tokio::test]
-async fn journal_persists_and_replays_run() {
- let tmp = std::env::temp_dir().join(format!("oh-journal-test-{}", uuid::Uuid::new_v4()));
- let stores = open_session_stores(&tmp);
- let run_id = mint_run_id();
-
- // Attach a journal sink directly (bypassing config resolution) and emit.
- // Seed the sink with the run id so persisted `event_id`s are the
- // restart-stable `{run_id}-evt-{offset}` — mirrors the caller in
- // `run_turn_via_tinyagents_shared`.
- let journal: Arc<dyn HarnessEventJournal> = Arc::new(StoreEventJournal::new(stores.journal));
- let sink = EventSink::with_stream_id(run_id.as_str());
- // Keep a handle to the JournalSink: persistence became asynchronous
- // (background `AppendWorker` drain, tinyagents v1.5 audit remediation),
- // so the test must `flush()` before reading the journal back — exactly
- // the contract the crate documents for read-after-write.
- let journal_sink = Arc::new(JournalSink::new(journal, run_id.clone()));
- let redacting = RedactingSink::new(journal_sink.clone(), vec!["sk-super-secret".into()]);
- sink.subscribe(Arc::new(FanOutSink::new().with(Arc::new(redacting))));
-
- sink.emit(AgentEvent::ModelStarted {
- call_id: "c1".into(),
- model: "sk-super-secret leaked here".to_string(),
- });
- sink.emit(AgentEvent::ToolStarted {
- call_id: "c1".into(),
- tool_name: "echo".to_string(),
- input: None,
- });
- // Drain the async persistence worker so the durable log has caught up
- // (flush blocks on the drain thread's ack, not on this runtime).
- journal_sink.flush();
-
- // Reconstruct from the durable store alone.
- let replayed = read_run_events_at(&tmp, run_id.as_str(), 0).await;
- assert_eq!(replayed.len(), 2);
- // Records come back fully ordered with restart-stable ids of the form
- // `{run_id}-evt-{offset}`.
- for (offset, obs) in replayed.iter().enumerate() {
- assert_eq!(obs.offset, offset as u64, "offset should be monotonic");
- assert_eq!(
- obs.event_id.as_str(),
- format!("{}-evt-{offset}", run_id.as_str()),
- "event id should be the stable {{stream_id}}-evt-{{offset}}"
- );
- }
- // The seeded secret was masked before persistence.
- if let AgentEvent::ModelStarted { model, .. } = &replayed[0].event {
- assert!(
- !model.contains("sk-super-secret"),
- "secret should be redacted"
- );
- assert!(model.contains("[REDACTED]"));
- } else {
- panic!("expected ModelStarted first");
- }
-
- // Late attach at a non-zero offset: a reader that reconnects after the
- // first event reconstructs only the tail (offset >= 1), still ordered and
- // still with stable ids — the mid-run reconnect/backfill path.
- let tail = read_run_events_at(&tmp, run_id.as_str(), 1).await;
- assert_eq!(tail.len(), 1);
- assert_eq!(tail[0].offset, 1);
- assert_eq!(
- tail[0].event_id.as_str(),
- format!("{}-evt-1", run_id.as_str())
- );
- assert!(matches!(tail[0].event, AgentEvent::ToolStarted { .. }));
-
- // Status store round-trips a running → completed transition and answers
- // list_active / list_by_root / list_by_thread.
- let status_store = FileStatusStore::new(open_session_stores(&tmp).kv);
- let mut status =
- HarnessRunStatus::new(run_id.clone(), ComponentId::new("mock-model".to_string()))
- .with_thread(ThreadId::new("thread-42"));
- status.mark_running(HarnessPhase::Model);
- status_store.put_status(status.clone()).await.unwrap();
- let active = status_store.list_active().await.unwrap();
- assert_eq!(active.len(), 1);
- assert_eq!(active[0].status, ExecutionStatus::Running);
- assert_eq!(
- status_store
- .list_by_thread("thread-42")
- .await
- .unwrap()
- .len(),
- 1
- );
- assert!(status_store
- .list_by_thread("nope")
- .await
- .unwrap()
- .is_empty());
-
- status.mark_completed();
- status_store.put_status(status).await.unwrap();
- let by_root = status_store.list_by_root(run_id.as_str()).await.unwrap();
- assert_eq!(by_root.len(), 1);
- assert_eq!(by_root[0].status, ExecutionStatus::Completed);
- assert!(status_store.list_active().await.unwrap().is_empty());
-
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// Workspace-parameterized twin of [`read_run_events`] for tests that supply
-/// an explicit store root instead of resolving one from config.
-async fn read_run_events_at(
- workspace: &std::path::Path,
- run_id: &str,
- from_offset: u64,
-) -> Vec<AgentObservation> {
- let stores = open_session_stores(workspace);
- StoreEventJournal::new(stores.journal)
- .read_from(run_id, from_offset)
- .await
- .unwrap()
-}
-
-/// Asserts that the durable journal sink and underlying append store handle
-/// multi-byte UTF-8 sequences straddling the 4096-byte lookback window boundary
-/// without failing validation or dropping observations (#5599).
-///
-/// `JsonlAppendStore::next_offset` seeks to `len - 4096`. When that byte offset lands
-/// mid-character, older implementations using `read_to_string` failed with "stream did
-/// not contain valid UTF-8". This test asserts that such boundary straddles are genuinely
-/// induced (`assert!(!torn.is_empty())`) and that subsequent appends and late-attach
-/// replays succeed contiguously.
-#[tokio::test]
-async fn journal_sink_handles_multibyte_utf8_spanning_window_boundary() {
- const WINDOW: usize = 4096;
- let mut torn = Vec::new();
-
- // Walk a padding range to sweep the (len - 4096) lookback boundary across
- // the continuation bytes of a multi-byte UTF-8 sequence.
- for pad in 0..20usize {
- let tmp = std::env::temp_dir().join(format!(
- "oh-journal-utf8-test-{pad}-{}",
- uuid::Uuid::new_v4()
- ));
- let run_id = mint_run_id();
-
- let stores = open_session_stores(&tmp);
- let journal: Arc<dyn HarnessEventJournal> =
- Arc::new(StoreEventJournal::new(stores.journal));
- let sink = EventSink::with_stream_id(run_id.as_str());
- let journal_sink = Arc::new(JournalSink::new(journal, run_id.clone()));
- sink.subscribe(Arc::new(FanOutSink::new().with(journal_sink.clone())));
-
- // 10 base events with multi-byte emoji payloads to approach and exceed WINDOW (4096 bytes).
- for i in 0..10 {
- sink.emit(AgentEvent::ModelStarted {
- call_id: format!("call-{i}").into(),
- model: "🦀".repeat(50),
- });
- }
-
- // An 11th event whose model string is padded byte-by-byte to sweep the window boundary.
- sink.emit(AgentEvent::ModelStarted {
- call_id: "call-10".into(),
- model: "x".repeat(pad),
- });
- journal_sink.flush();
-
- // Inspect the underlying stream file to verify whether this pad placed the
- // 4096-byte lookback window start inside a multi-byte UTF-8 character.
- let stream_path = tmp
- .join("tinyagents_store")
- .join("journal")
- .join(format!("{}.jsonl", run_id.as_str()));
- let raw = std::fs::read(&stream_path).expect("read stream file");
- if raw.len() > WINDOW {
- let start = raw.len() - WINDOW;
- let text = String::from_utf8_lossy(&raw);
- if !text.is_char_boundary(start) {
- torn.push(pad);
- }
- }
-
- // Emit a subsequent tool event across the boundary: this forces next_offset
- // to resolve the stream tail and assign the next sequential offset.
- sink.emit(AgentEvent::ToolStarted {
- call_id: "call-11".into(),
- tool_name: "test_tool".to_string(),
- input: None,
- });
- journal_sink.flush();
-
- // Verify replay: all 12 events must be present and contiguous from offset 0.
- let replayed = read_run_events_at(&tmp, run_id.as_str(), 0).await;
- assert_eq!(
- replayed.len(),
- 12,
- "pad {pad}: all observations must be retained"
- );
- for (i, obs) in replayed.iter().enumerate() {
- assert_eq!(
- obs.offset, i as u64,
- "pad {pad}: observation {i} offset must be contiguous"
- );
- assert_eq!(
- obs.event_id.as_str(),
- format!("{}-evt-{i}", run_id.as_str()),
- "pad {pad}: event id should follow stable prefix pattern"
- );
- }
-
- // Verify model contents on the first and 11th observations match exactly.
- if let AgentEvent::ModelStarted { model, .. } = &replayed[0].event {
- assert_eq!(model, &"🦀".repeat(50));
- } else {
- panic!("pad {pad}: expected ModelStarted at offset 0");
- }
- if let AgentEvent::ModelStarted { model, .. } = &replayed[10].event {
- assert_eq!(model, &"x".repeat(pad));
- } else {
- panic!("pad {pad}: expected ModelStarted at offset 10");
- }
- assert!(matches!(replayed[11].event, AgentEvent::ToolStarted { .. }));
-
- let _ = std::fs::remove_dir_all(&tmp);
- }
-
- assert!(
- !torn.is_empty(),
- "no pad put the 4096-byte window start inside a multi-byte character; \
- adjust padding range so the test proves boundary recovery"
- );
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs b/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
deleted file mode 100644
index e6b7987caf..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
+++ /dev/null
@@ -1,189 +0,0 @@
-use super::*;
-
-use tinyagents_harness::ids::ComponentId;
-
-use crate::agent::tinyagents::journal::mint_run_id;
-
-/// Build a fresh status in the given non-terminal state and persist it.
-async fn seed_status(store: &FileStatusStore, status_kind: ExecutionStatus) -> String {
- let run_id = mint_run_id();
- let mut status =
- HarnessRunStatus::new(run_id.clone(), ComponentId::new("mock-model".to_string()));
- match status_kind {
- ExecutionStatus::Pending => { /* fresh status is already Pending */ }
- ExecutionStatus::Running => status.mark_running(HarnessPhase::Model),
- ExecutionStatus::Interrupted => status.mark_interrupted(),
- other => panic!("seed_status only seeds non-terminal states, got {other:?}"),
- }
- store.put_status(status).await.unwrap();
- run_id.as_str().to_string()
-}
-
-/// The sweep reaps every non-terminal run to `Cancelled` with the reason,
-/// leaves terminal runs untouched, and empties the active listing.
-#[tokio::test]
-async fn reap_cancels_every_active_run_and_spares_terminal_ones() {
- let tmp = std::env::temp_dir().join(format!("oh-reaper-{}", uuid::Uuid::new_v4()));
- let store = FileStatusStore::new(open_session_stores(&tmp).kv);
-
- let pending = seed_status(&store, ExecutionStatus::Pending).await;
- let running = seed_status(&store, ExecutionStatus::Running).await;
- let interrupted = seed_status(&store, ExecutionStatus::Interrupted).await;
-
- // A run that already finished must survive the sweep unchanged.
- let done = mint_run_id();
- let mut done_status =
- HarnessRunStatus::new(done.clone(), ComponentId::new("mock-model".to_string()));
- done_status.mark_running(HarnessPhase::Model);
- done_status.mark_completed();
- store.put_status(done_status).await.unwrap();
-
- let reaped = reap_orphaned_runs(&tmp).await;
- assert_eq!(reaped, 3, "the three non-terminal runs were reaped");
-
- // Every orphan is now terminal-cancelled with the stable reason.
- for run_id in [&pending, &running, &interrupted] {
- let status = store
- .get_status(run_id)
- .await
- .unwrap()
- .expect("status present");
- assert_eq!(status.status, ExecutionStatus::Cancelled);
- assert_eq!(status.current_phase, HarnessPhase::Done);
- assert_eq!(status.error.as_deref(), Some(ORPHAN_REAP_REASON));
- assert!(status.ended_at.is_some(), "reaped run has an end time");
- }
-
- // The completed run is left exactly as it was.
- let done_after = store
- .get_status(done.as_str())
- .await
- .unwrap()
- .expect("done present");
- assert_eq!(done_after.status, ExecutionStatus::Completed);
- assert!(done_after.error.is_none());
-
- // The active listing is now empty — a second sweep is a no-op.
- assert!(store.list_active().await.unwrap().is_empty());
- assert_eq!(
- reap_orphaned_runs(&tmp).await,
- 0,
- "idempotent: nothing left to reap"
- );
-
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// A workspace that never hosted a run reaps nothing and does not error.
-#[tokio::test]
-async fn reap_on_empty_workspace_is_a_noop() {
- let tmp = std::env::temp_dir().join(format!("oh-reaper-empty-{}", uuid::Uuid::new_v4()));
- assert_eq!(reap_orphaned_runs(&tmp).await, 0);
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// The sweep has to happen on the path a **build-only** embedder takes.
-///
-/// `CoreRuntime::invoke` dispatches `openhuman.agent_runs_active` the moment
-/// `build()` returns, with no transport and no background services in
-/// between, so a sweep that lived with the other boot-once jobs (which run
-/// from `serve()`) would leave that caller reading the previous process's
-/// graveyard. This pins the sweep to the build path with every optional
-/// service off.
-///
-/// The build itself runs in a **child process** (this same test binary,
-/// re-invoked with `--exact` on this test and `REAPER_BOOT_CHILD` set).
-/// `CoreBuilder::build` → `CoreContext::init` → `bootstrap_core_runtime`
-/// installs process-wide `OnceLock` singletons that can never be unset — the
-/// default `CoreContext` (here with `DomainSet::harness()` and a throw-away
-/// workspace), the global `ApprovalGate`, the socket manager, native-bus
-/// handlers. Booting in the lib test binary leaked all of them into every
-/// test that ran afterwards under `--test-threads=1`: `all_tools` lost its
-/// acting tool groups, the tinyflows HTTP adapter hit the origin-label gate
-/// instead of the SSRF guard, memory-binding tests saw a workspace they never
-/// set up. The parent seeds the store and verifies the sweep; only the child
-/// touches the singletons, and it exits with them.
-#[tokio::test]
-async fn a_build_only_runtime_is_swept_before_it_can_be_invoked() {
- if std::env::var_os(REAPER_BOOT_CHILD_ENV).is_some() {
- boot_child().await;
- return;
- }
-
- let tmp = std::env::temp_dir().join(format!("oh-reaper-boot-{}", uuid::Uuid::new_v4()));
- // `OPENHUMAN_WORKSPACE` names the root; the resolved workspace is the
- // `workspace` directory under it, which is what the sweep will read.
- let workspace = tmp.join("workspace");
- let store = FileStatusStore::new(open_session_stores(&workspace).kv);
- let orphan = seed_status(&store, ExecutionStatus::Running).await;
- assert_eq!(store.list_active().await.unwrap().len(), 1);
-
- let exe = std::env::current_exe().expect("test binary path");
- let output = std::process::Command::new(exe)
- .args([
- "--exact",
- "agent::tinyagents::reaper::tests::\
- a_build_only_runtime_is_swept_before_it_can_be_invoked",
- "--test-threads=1",
- "--nocapture",
- ])
- .env(REAPER_BOOT_CHILD_ENV, "1")
- .env("OPENHUMAN_WORKSPACE", &tmp)
- .output()
- .expect("spawn the boot child");
- assert!(
- output.status.success(),
- "the boot child must build a core and pass its own assertions\n\
- --- stdout ---\n{}\n--- stderr ---\n{}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
-
- // The child writes the durable store in a separate process. Reopen it for
- // verification instead of reading through the parent's handle, whose
- // refactored KV layer may still serve the status it cached while seeding.
- let after_store = FileStatusStore::new(open_session_stores(&workspace).kv);
- let after = after_store
- .get_status(&orphan)
- .await
- .unwrap()
- .expect("the seeded run is still readable");
- assert_eq!(
- after.status,
- ExecutionStatus::Cancelled,
- "build() must reap before any RPC can be dispatched"
- );
- assert_eq!(after.error.as_deref(), Some(ORPHAN_REAP_REASON));
- assert!(after_store.list_active().await.unwrap().is_empty());
-
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// Set on the re-invoked test binary so the test body knows it is the boot
-/// child rather than the seeding/verifying parent.
-const REAPER_BOOT_CHILD_ENV: &str = "OPENHUMAN_TEST_REAPER_BOOT_CHILD";
-
-/// The child half of `a_build_only_runtime_is_swept_before_it_can_be_invoked`:
-/// build a runtime with no transport and no services — the shape
-/// `examples/embed_headless.rs` documents — against the `OPENHUMAN_WORKSPACE`
-/// the parent exported, and check the build resolved that workspace. The
-/// parent reads the sweep's effect out of the store afterwards.
-async fn boot_child() {
- use crate::core::runtime::{CoreBuilder, DomainSet, ServiceSet};
- use crate::core::types::HostKind;
-
- let root = std::path::PathBuf::from(
- std::env::var_os("OPENHUMAN_WORKSPACE").expect("parent exports OPENHUMAN_WORKSPACE"),
- );
- let built = CoreBuilder::new(HostKind::Cli)
- .services(ServiceSet::none())
- .domains(DomainSet::harness())
- .build()
- .await
- .expect("a headless build succeeds");
- assert_eq!(
- built.context().workspace_dir().ok(),
- Some(root.join("workspace")),
- "the build must have resolved the workspace the parent seeded"
- );
-}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index b61fefa9a7..5a954aae1b 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit b61fefa9a7061bba7d22a818150e433fc631d8c7
+Subproject commit 5a954aae1b84e7cef6de8fcdc1cf11913c93c9c5