Skip to content

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

feat(session_import): project live session events into runtime sessions

Steven Enamakele331e8115381
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index 65b0f496a8..9a7dbd06e6 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -580,51 +580,8 @@ impl OpenHumanTurnPrelude {
}
async fn finalize_after_durable_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
- self.mirror_transcript_after_commit(receipt);
self.memory_post_turn(receipt);
}
-
- fn mirror_transcript_after_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {
- let Some(path) = receipt
- .transcript
- .as_ref()
- .map(|commit| commit.path.clone())
- else {
- return;
- };
- if !crate::agent::session_import::live::dual_write_enabled(self.config.session_dual_write) {
- return;
- }
- let Some(stem) = path
- .file_stem()
- .and_then(|stem| stem.to_str())
- .map(str::to_owned)
- else {
- return;
- };
- let workspace = self.workspace_dir.clone();
- tokio::spawn(async move {
- let read_path = path.clone();
- let transcript = tokio::task::spawn_blocking(move || {
- tinyagents_session::transcript::read_transcript(&read_path)
- })
- .await;
- let Ok(Ok(transcript)) = transcript else {
- log::warn!("[session-store] dual-write transcript read-back failed");
- return;
- };
- if let Err(error) = tinyagents_session::transcript::import::live::write_live_turn(
- &workspace,
- &stem,
- &transcript,
- crate::agent::session_import::projector::journal_message_from_transcript,
- )
- .await
- {
- log::warn!("[session-store] dual-write failed stem={stem}: {error:#}");
- }
- });
- }
}
/// Reconcile visible delegate names without reopening a caller's explicit
diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rs
index de4e3cfb21..b9f5873748 100644
--- a/crates/openhuman-core/src/agent/session_import/live.rs
+++ b/crates/openhuman-core/src/agent/session_import/live.rs
@@ -1,99 +1,26 @@
-//! Host policy for the live session-store dual-write and the shadow read.
+//! The session key-value store a turn registers on its `RunContext`.
//!
-//! The work itself (`write_live_turn`, `shadow_read_compare`) lives in
-//! `tinyagents_session::transcript::import::live`; what stays here is the
-//! OpenHuman decision of *whether* it runs: the `AgentConfig` flags
-//! (`session_dual_write`, `session_shadow_reads`, both default ON), the
-//! `OPENHUMAN_SESSION_DUAL_WRITE` / `OPENHUMAN_SESSION_SHADOW_READS` kill
-//! switches (a falsey value forces the feature off, an env var can never force
-//! it on; this mirrors the `OPENHUMAN_APPROVAL_GATE` idiom), and the
-//! `RunContext.stores` registration of the session KV store.
+//! Sessions live in the storage backend (`DriverSessionStores`), one scope per
+//! agent. The file-era mirror of transcripts into a second layout, and the
+//! store-backed shadow read that compared against it, are gone: the backend is
+//! the only record. What remains is the harness-visible handle to the agent's
+//! key-value store, registered on each turn's `RunContext.stores` under
+//! [`TINYAGENTS_SESSION_KV_STORE`].
use std::sync::Arc;
use tinyagents_harness::store::Store;
-use tinyagents_session::transcript::import::ops::{open_session_stores, SessionStores};
-
-/// Kill-switch env var for the live session-store dual-write. The config flag
-/// (`AgentConfig::session_dual_write`) defaults ON; setting this env var to a
-/// falsey value forces the mirror OFF regardless of config. See
-/// [`dual_write_enabled`].
-const DUAL_WRITE_ENV: &str = "OPENHUMAN_SESSION_DUAL_WRITE";
-
-/// Kill-switch env var for the store-backed session shadow read. The config
-/// flag (`AgentConfig::session_shadow_reads`) defaults ON since the Phase 2
-/// parity soak; setting this env var to a falsey value forces the shadow read
-/// OFF even when the flag is ON. It can never force the shadow read ON. See
-/// [`shadow_reads_enabled`].
-const SHADOW_READ_ENV: &str = "OPENHUMAN_SESSION_SHADOW_READS";
-
-/// Whether `var` is set to a case-insensitive falsey value
-/// (`0`/`false`/`no`/`off`/`disable`/`disabled`). Unset — or any non-falsey
-/// value — is not a kill. Read live (not cached) so a config reload / env
-/// change is honored on the next turn/read.
-fn env_kill_switch_engaged(var: &str) -> bool {
- match std::env::var(var) {
- Ok(v) => matches!(
- v.trim().to_ascii_lowercase().as_str(),
- "0" | "false" | "no" | "off" | "disable" | "disabled"
- ),
- Err(_) => false,
- }
-}
-
-/// Whether the `OPENHUMAN_SESSION_DUAL_WRITE` kill switch is engaged (set to a
-/// falsey value). Unset — or any non-falsey value — leaves the mirror driven by
-/// the config flag. Read live (not cached) so a config reload / env change is
-/// honored on the next turn.
-fn kill_switch_engaged() -> bool {
- env_kill_switch_engaged(DUAL_WRITE_ENV)
-}
/// Store-registry name under which the session KV store is registered on each
-/// turn's `RunContext.stores` (issue #4249, 04.1). Slash-free so it round-trips
-/// the crate `FileStore` name sanitizer. This is a forward-looking,
-/// harness-visible handle to the same `tinyagents_store` KV tree the live
-/// dual-write mirrors into; readers stay legacy until 04.2.
+/// turn's `RunContext.stores`. Slash-free so it round-trips store-name
+/// sanitizers.
pub const TINYAGENTS_SESSION_KV_STORE: &str = "openhuman_sessions";
-/// Whether the live session-store dual-write is enabled for this turn.
-///
-/// `config_enabled` is the `AgentConfig::session_dual_write` flag, which
-/// **defaults ON**. The `OPENHUMAN_SESSION_DUAL_WRITE` env var is a pure kill
-/// switch: an explicit falsey value (case-insensitive
-/// `0`/`false`/`no`/`off`/`disable`/`disabled`) forces the mirror OFF regardless
-/// of config; otherwise the config flag wins. Read live (never cached) so a
-/// config reload / env change is honored on the next turn. This keeps a clean
-/// 04.2 seam (reads can flip independently) while making the mirror the default
-/// so new turns land in the store without opt-in.
-///
-/// Always off under a host session store that is not file-backed
-/// ([`crate::agent::session_store::replaces_files`]): it is already the only
-/// record, and there are no transcript files to mirror.
-pub fn dual_write_enabled(config_enabled: bool) -> bool {
- let killed = kill_switch_engaged();
- let replaced = crate::agent::session_store::replaces_files();
- let enabled = config_enabled && !killed && !replaced;
- log::debug!(
- "[session-store] dual-write decision config_enabled={config_enabled} kill_switch={killed} host_store={replaced} enabled={enabled}"
- );
- enabled
-}
-
-/// Open the session KV store as an `Arc<dyn Store>` for registration on the
-/// per-turn `RunContext.stores` under [`TINYAGENTS_SESSION_KV_STORE`], honoring
-/// the dual-write flag (config default ON + env kill switch).
+/// The calling agent's key-value store as an `Arc<dyn Store>` for registration
+/// on the per-turn `RunContext.stores` under [`TINYAGENTS_SESSION_KV_STORE`].
///
-/// Best-effort: `None` when the dual-write is disabled **or** the config (hence
-/// workspace) cannot be resolved. When present it is the exact same
-/// `{workspace}/tinyagents_store/kv` `FileStore` the importer and the live
-/// dual-write use, so a harness-side reader (04.2+) sees identical records. The
-/// journal (`JsonlAppendStore`, an `AppendStore` rather than a `Store`) is not
-/// registrable on the `StoreRegistry`; the dual-write opens it directly.
-///
-/// With a host session store that is not file-backed it is the current
-/// agent's key-value store, whatever the dual-write flag says: there are no
-/// files to mirror.
+/// Best-effort: `None` when the config (hence workspace) cannot be resolved and
+/// no store is installed.
pub async fn session_kv_store() -> Option<Arc<dyn Store>> {
if let Some(stores) = crate::agent::session_store::current() {
log::debug!("[session-store] registering the host session store's kv on RunContext.stores");
@@ -106,37 +33,10 @@ pub async fn session_kv_store() -> Option<Arc<dyn Store>> {
return None;
}
};
- if !dual_write_enabled(cfg.agent.session_dual_write) {
- log::debug!(
- "[session-store] dual-write disabled; skipping RunContext session-store registration"
- );
- return None;
- }
- let workspace = cfg.workspace_dir;
- let SessionStores { kv, .. } = open_session_stores(&workspace);
+ let stores = crate::agent::session_store::stores_for(&cfg.workspace_dir)?;
log::debug!(
"[session-store] opened session kv store for RunContext.stores workspace={}",
- workspace.display()
- );
- Some(Arc::new(kv))
-}
-
-/// Whether the store-backed session **shadow read** is enabled for this read.
-///
-/// `config_enabled` is the `AgentConfig::session_shadow_reads` flag, which
-/// **defaults ON** since the Phase 2 parity soak, as `session_dual_write`
-/// already did. The
-/// `OPENHUMAN_SESSION_SHADOW_READS` env var is a pure kill switch: an explicit
-/// falsey value (case-insensitive `0`/`false`/`no`/`off`/`disable`/`disabled`)
-/// forces the shadow read OFF regardless of config; it can never force it ON.
-/// Read live (never cached) so a config reload / env change is honored on the
-/// next read. Mirrors the [`dual_write_enabled`] flag/env idiom exactly: the
-/// env var can only ever force OFF, never ON.
-pub fn shadow_reads_enabled(config_enabled: bool) -> bool {
- let killed = env_kill_switch_engaged(SHADOW_READ_ENV);
- let enabled = config_enabled && !killed;
- log::debug!(
- "[session_shadow_read] decision config_enabled={config_enabled} kill_switch={killed} enabled={enabled}"
+ cfg.workspace_dir.display()
);
- enabled
+ Some(stores.kv)
}
diff --git a/crates/openhuman-core/src/agent/session_import/live_tests.rs b/crates/openhuman-core/src/agent/session_import/live_tests.rs
deleted file mode 100644
index 81e5c525ba..0000000000
--- a/crates/openhuman-core/src/agent/session_import/live_tests.rs
+++ /dev/null
@@ -1,341 +0,0 @@
-//! Write-side parity for the live session-store dual-write (issue #4249, 04.1).
-//!
-//! Drives the two persistence paths — the legacy authoritative JSONL writer
-//! (`transcript::write_transcript`) and the live store mirror
-//! ([`super::live::write_live_turn`]) — with the *same* completed turn, then
-//! asserts the store journal renders byte-for-byte the same
-//! [`JournalMessage`]s the importer's parity helper reads back off the legacy
-//! JSONL. This proves the two writers stay shape-identical for new turns
-//! without depending on the read path (04.2).
-
-use std::path::Path;
-
-use tempfile::TempDir;
-use tinyagents_harness::store::{AppendStore, JsonlAppendStore};
-
-use super::live::{dual_write_enabled, shadow_reads_enabled};
-use super::projector::journal_message_from_transcript as project;
-use crate::config::test_env::EnvVarGuard;
-use tinyagents_session::transcript::import::convert::journal_messages as journal_messages_with;
-use tinyagents_session::transcript::import::live::{
- shadow_read_compare as shadow_read_compare_with, write_live_turn as write_live_turn_with,
- ShadowReadOutcome,
-};
-use tinyagents_session::transcript::import::ops::store_root;
-use tinyagents_session::transcript::import::types::JournalMessage;
-use tinyagents_session::transcript::TranscriptMessage;
-use tinyagents_session::transcript::{
- read_transcript, write_transcript, MessageUsage, SessionTranscript, TranscriptMeta,
- TranscriptToolCall, TurnUsage,
-};
-
-fn journal_messages(t: &SessionTranscript) -> Vec<JournalMessage> {
- journal_messages_with(t, project)
-}
-
-async fn write_live_turn(workspace: &Path, key: &str, t: &SessionTranscript) -> anyhow::Result<()> {
- write_live_turn_with(workspace, key, t, project).await
-}
-
-async fn shadow_read_compare(
- workspace: &Path,
- key: &str,
- t: &SessionTranscript,
-) -> ShadowReadOutcome {
- shadow_read_compare_with(workspace, key, t, project).await
-}
-
-fn durable_messages(messages: &[TranscriptMessage]) -> Vec<TranscriptMessage> {
- messages.to_vec()
-}
-
-/// A transcript meta header matching the importer's `native` fixture shape.
-fn meta(thread_id: &str) -> TranscriptMeta {
- TranscriptMeta {
- session_id: None,
- parent_session_id: None,
- agent_name: "orchestrator".to_string(),
- agent_id: Some("orchestrator".to_string()),
- agent_type: Some("root".to_string()),
- dispatcher: "native".to_string(),
- provider: Some("anthropic".to_string()),
- model: Some("claude".to_string()),
- created: "2024-01-01T00:00:00Z".to_string(),
- updated: "2024-01-01T00:05:00Z".to_string(),
- turn_count: 1,
- prefix_message_count: None,
- input_tokens: 100,
- output_tokens: 50,
- cached_input_tokens: 20,
- charged_amount_usd: 0.05,
- thread_id: Some(thread_id.to_string()),
- task_id: None,
- }
-}
-
-/// Per-turn usage carrying a native tool call, so tool-call ids are exercised
-/// on the parity path (acceptance: "tool-call ids").
-fn turn_usage() -> TurnUsage {
- TurnUsage {
- provider: "anthropic".to_string(),
- model: "claude".to_string(),
- usage: MessageUsage {
- input: 100,
- output: 50,
- cached_input: 20,
- context_window: 200_000,
- cost_usd: 0.05,
- ..Default::default()
- },
- ts: "2024-01-01T00:00:01Z".to_string(),
- reasoning_content: None,
- tool_calls: vec![TranscriptToolCall {
- id: "tc1".to_string(),
- name: "read_file".to_string(),
- arguments: "{\"path\":\"x\"}".to_string(),
- extra_content: None,
- }],
- iteration: 1,
- }
-}
-
-/// A multi-turn session whose messages carry the sidecar `extra_metadata` the
-/// single-turn happy-path fixture cannot express: a system message, a failed
-/// `tool` message tagged with `openhuman_tool_failure`, two assistant turns, and
-/// the trailing assistant that this turn's usage attaches to. The writer lifts
-/// the tool-failure marker onto the line's top-level `failure`/`failure_detail`
-/// fields, and since #6282 the read-back restores it to `extra_metadata`, so the
-/// marker round-trips.
-fn rich_base_messages() -> Vec<TranscriptMessage> {
- let mut failed_tool = TranscriptMessage::tool("read_file failed: boom");
- failed_tool.tool_failure = Some(tinyagents_session::transcript::ToolFailure {
- failed: true,
- detail: Some("boom".into()),
- });
- vec![
- TranscriptMessage::system("you are the orchestrator"),
- TranscriptMessage::user("read the file"),
- TranscriptMessage::assistant("calling read_file"),
- failed_tool,
- TranscriptMessage::assistant("done"),
- ]
-}
-
-/// Read the store journal stream back into `JournalMessage`s, mirroring the
-/// importer's `journal_readback` helper.
-async fn journal_readback(ws: &Path, stream: &str) -> Vec<JournalMessage> {
- let journal = JsonlAppendStore::new(store_root(ws).join("journal"));
- journal
- .read_from(stream, 0)
- .await
- .expect("journal read")
- .into_iter()
- .map(|(_, v)| serde_json::from_value(v).expect("journal record shape"))
- .collect()
-}
-
-/// The dual-write is driven by the `AgentConfig::session_dual_write` config
-/// flag (default ON) with the `OPENHUMAN_SESSION_DUAL_WRITE` env var as a pure
-/// kill switch. This exercises the decision matrix directly. Env mutation is
-/// process-global, so all assertions live in one serial test and the var is
-/// restored on exit; no other test reads this var.
-#[test]
-fn config_flag_and_env_kill_switch() {
- const ENV: &str = "OPENHUMAN_SESSION_DUAL_WRITE";
- // Crate-wide env lock, held to the end; restores the prior value on drop
- // (also on unwind).
- let _env = EnvVarGuard::locked_unset(ENV);
-
- // Config OFF disables regardless of env.
- assert!(!dual_write_enabled(false), "config off disables");
-
- // Config ON (the default) enables when the env is unset.
- assert!(dual_write_enabled(true), "config on + no env enables");
-
- // A falsey env value is the kill switch: forces OFF even with config ON.
- for killed in ["0", "false", "no", "off", "disable", "disabled", "OFF"] {
- std::env::set_var(ENV, killed);
- assert!(
- !dual_write_enabled(true),
- "kill switch value {killed:?} must force off"
- );
- }
-
- // A non-falsey env value does not force on: config still governs.
- std::env::set_var(ENV, "1");
- assert!(
- dual_write_enabled(true),
- "non-falsey env leaves config ON on"
- );
- assert!(
- !dual_write_enabled(false),
- "non-falsey env does not force config-off on"
- );
-}
-
-// ── Store-backed shadow read (issue #4249, 04.2 phase 2) ────────────────────
-
-/// A session written by the dual-write and then read back through the shadow
-/// reader must render byte-for-byte the messages the legacy JSONL reader
-/// produces — no divergence. This is the read-path twin of
-/// [`live_dual_write_matches_legacy_jsonl_render`]: it drives the *same*
-/// writers, then compares via the actual `shadow_read_compare` path and asserts
-/// a clean [`ShadowReadOutcome::Match`].
-#[tokio::test]
-async fn shadow_read_roundtrip_matches_legacy() {
- let ws = TempDir::new().expect("tempdir");
- let stem = "1719_orchestrator";
- let jsonl_path = ws.path().join("session_raw").join(format!("{stem}.jsonl"));
-
- // A rich session (system + tool-failure + two assistant turns) so the fixture
- // can actually express the sidecar-metadata asymmetries; a two-message
- // happy-path turn cannot, which is why the pre-#6149 version passed vacuously.
- let base_messages = rich_base_messages();
- let meta = meta("t-root");
- let usage = turn_usage();
-
- // (1) Legacy authoritative write.
- write_transcript(
- &jsonl_path,
- &durable_messages(&base_messages),
- &meta,
- Some(&usage),
- )
- .expect("legacy write");
-
- // (2) Live dual-write, mirrored exactly as the fixed
- // `maybe_dual_write_session_store` does (#6149): the store record IS
- // `read_transcript(path)` — the legacy JSONL after its write→read round-trip,
- // the same value the shadow reader compares against — not a hand-rebuilt copy
- // of the in-memory turn.
- let mirrored = read_transcript(&jsonl_path).expect("read legacy transcript for mirror");
- write_live_turn(ws.path(), stem, &mirrored)
- .await
- .expect("live dual-write");
-
- // The legacy reader materializes this SessionTranscript for a resume; the
- // shadow reader compares it against the store stream.
- let legacy = read_transcript(&jsonl_path).expect("read legacy transcript");
- let outcome = shadow_read_compare(ws.path(), stem, &legacy).await;
- assert_eq!(
- outcome,
- ShadowReadOutcome::Match {
- messages: legacy.messages.len()
- },
- "round-tripped shadow read must match the legacy render with no divergence"
- );
-}
-
-/// An in-memory reconstruction remains observably distinct from the durable
-/// JSONL read-back even when replay metadata is not materialized explicitly.
-#[tokio::test]
-async fn in_memory_store_reconstruction_diverges_from_legacy_on_sidecar_metadata() {
- let ws = TempDir::new().expect("tempdir");
- let stem = "1719_orchestrator";
- let jsonl_path = ws.path().join("session_raw").join(format!("{stem}.jsonl"));
-
- let base_messages = rich_base_messages();
- let meta = meta("t-root");
- let usage = turn_usage();
-
- // Legacy write the way `persist_session_transcript` does it: append-only,
- // stamped with the turn's request id.
- tinyagents_session::transcript::append_transcript_turn(
- &jsonl_path,
- &[],
- &durable_messages(&base_messages),
- &meta,
- Some(&usage),
- Some("req-1"),
- )
- .expect("legacy write");
-
- // Pre-fix store construction: clone the in-memory turn, attach usage to the
- // last assistant, and mirror THAT — never round-tripping through the JSONL,
- // so the tool-failure marker the round-trip strips is still present.
- let mut live_messages = base_messages.clone();
- let last_assistant = live_messages
- .iter()
- .rposition(|m| m.role == "assistant")
- .expect("assistant message present");
- live_messages[last_assistant].turn_usage = Some(usage.clone());
- let reconstructed = SessionTranscript {
- tools: None,
- meta: meta.clone(),
- messages: durable_messages(&live_messages),
- };
- write_live_turn(ws.path(), stem, &reconstructed)
- .await
- .expect("live dual-write");
-
- let legacy = read_transcript(&jsonl_path).expect("read legacy transcript");
- let outcome = shadow_read_compare(ws.path(), stem, &legacy).await;
-
- let rendered = base_messages.len();
- assert_eq!(
- outcome,
- ShadowReadOutcome::Divergence {
- legacy: rendered,
- shadow: rendered,
- first_diff: Some(0),
- },
- "the in-memory reconstruction must diverge from the durable read-back at index zero"
- );
-}
-
-/// The shadow read is driven by the `AgentConfig::session_shadow_reads` config
-/// flag (default **ON** since the Phase 2 parity soak) with the
-/// `OPENHUMAN_SESSION_SHADOW_READS` env var as a
-/// pure kill switch (can only force OFF, never ON). This exercises the decision
-/// matrix directly — the gate `maybe_shadow_read_session_store` early-returns
-/// (never invoking the reader) whenever this returns `false`. Env mutation is
-/// process-global, so all assertions live in one serial test and the var is
-/// restored on exit.
-#[test]
-fn shadow_read_flag_and_env_kill_switch() {
- const ENV: &str = "OPENHUMAN_SESSION_SHADOW_READS";
- // Crate-wide env lock, held to the end; restores the prior value on drop
- // (also on unwind).
- let _env = EnvVarGuard::locked_unset(ENV);
-
- // Config OFF (the default) disables regardless of env — reader not invoked.
- assert!(
- !shadow_reads_enabled(false),
- "config off (default) disables the shadow read"
- );
-
- // Config ON enables when the env is unset.
- assert!(
- shadow_reads_enabled(true),
- "config on + no env enables the shadow read"
- );
-
- // A falsey env value is the kill switch: forces OFF even with config ON.
- for killed in ["0", "false", "no", "off", "disable", "disabled", "OFF"] {
- std::env::set_var(ENV, killed);
- assert!(
- !shadow_reads_enabled(true),
- "kill switch value {killed:?} must force off even with flag on"
- );
- }
-
- // A non-falsey env value does not force on: config still governs, and it
- // can never turn a default-off flag on.
- std::env::set_var(ENV, "1");
- assert!(
- shadow_reads_enabled(true),
- "non-falsey env leaves config ON on"
- );
- assert!(
- !shadow_reads_enabled(false),
- "non-falsey env cannot force a default-off flag on"
- );
-}
-
-// ── Legacy on-disk shapes (plan-agents.md Phase 2) ────────────────────────────
-//
-// Phase 2's exit criteria name two legacy layouts that must survive the
-// migration: the date-grouped `session_raw/DDMMYYYY/` directory and the
-// markdown transcripts `read_transcript_legacy_md` still parses. Both predate
-// the store, so both reach the shadow read by a different route than the happy
-// path above — and a real user upgrading has them on disk today.
diff --git a/crates/openhuman-core/src/agent/session_import/projector.rs b/crates/openhuman-core/src/agent/session_import/projector.rs
deleted file mode 100644
index dc8a940bbf..0000000000
--- a/crates/openhuman-core/src/agent/session_import/projector.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-//! Host projection of a durable transcript row into a session-store journal
-//! record.
-//!
-//! The importer, the live dual-write and the shadow read (all in
-//! `tinyagents_session::transcript::import`) take this as their
-//! `JournalProjector`. The journal record carries the row's typed sidecar
-//! (turn usage, tool-failure and replay markers) as `openhuman_*` keys inside
-//! `extra_metadata`; that key encoding is the journal's wire contract and is
-//! derived here, in one direction only, from the typed fields of the vendor row.
-
-use tinyagents_session::transcript::import::types::JournalMessage;
-use tinyagents_session::transcript::TranscriptMessage;
-
-const TURN_USAGE_METADATA_KEY: &str = "openhuman_turn_usage";
-const TOOL_FAILURE_METADATA_KEY: &str = "openhuman_tool_failure";
-const REPLAYED_METADATA_KEY: &str = "openhuman_replayed";
-const WRAPPED_VALUE_KEY: &str = "openhuman_wrapped_value";
-const WRAPPED_FLAG: &str = "wrapped";
-
-fn would_wrap(extra: &Option<serde_json::Value>) -> bool {
- matches!(extra, Some(value) if !value.is_object())
-}
-
-/// Insert a marker into the row's metadata. A non-object original is kept
-/// under [`WRAPPED_VALUE_KEY`] so no provider metadata is discarded.
-fn insert_host_metadata(
- extra: &mut Option<serde_json::Value>,
- key: &str,
- value: serde_json::Value,
-) {
- let mut map = match extra.take() {
- Some(serde_json::Value::Object(map)) => map,
- Some(existing) => {
- let mut map = serde_json::Map::new();
- map.insert(WRAPPED_VALUE_KEY.to_string(), existing);
- map
- }
- None => serde_json::Map::new(),
- };
- map.insert(key.to_string(), value);
- *extra = Some(serde_json::Value::Object(map));
-}
-
-/// The journal `extra_metadata` for one durable row.
-fn journal_extra_metadata(message: &TranscriptMessage) -> Option<serde_json::Value> {
- let mut extra = message.extra_metadata.clone();
- if let Some(usage) = message.turn_usage.as_ref() {
- if let Ok(mut payload) = serde_json::to_value(usage) {
- // Older journal rows omitted these unknown measurements. Preserve
- // that wire shape while retaining measured final-call counts.
- if let Some(counts) = payload
- .get_mut("usage")
- .and_then(serde_json::Value::as_object_mut)
- {
- for field in ["last_call_input", "last_call_output"] {
- if counts.get(field).and_then(serde_json::Value::as_u64) == Some(0) {
- counts.remove(field);
- }
- }
- }
- insert_host_metadata(&mut extra, TURN_USAGE_METADATA_KEY, payload);
- }
- }
- if let Some(failure) = message
- .tool_failure
- .as_ref()
- .filter(|failure| failure.failed)
- {
- let mut payload = serde_json::Map::new();
- payload.insert("failure".to_string(), serde_json::Value::Bool(true));
- if let Some(detail) = failure
- .detail
- .as_deref()
- .map(str::trim)
- .filter(|detail| !detail.is_empty())
- {
- payload.insert(
- "detail".to_string(),
- serde_json::Value::String(detail.to_string()),
- );
- }
- if would_wrap(&extra) {
- payload.insert(WRAPPED_FLAG.to_string(), serde_json::Value::Bool(true));
- }
- insert_host_metadata(
- &mut extra,
- TOOL_FAILURE_METADATA_KEY,
- serde_json::Value::Object(payload),
- );
- }
- if message.preserve_request_id {
- let mut payload = serde_json::Map::new();
- payload.insert(
- "request_id".to_string(),
- message
- .request_id
- .clone()
- .map(serde_json::Value::String)
- .unwrap_or(serde_json::Value::Null),
- );
- if would_wrap(&extra) {
- payload.insert(WRAPPED_FLAG.to_string(), serde_json::Value::Bool(true));
- }
- insert_host_metadata(
- &mut extra,
- REPLAYED_METADATA_KEY,
- serde_json::Value::Object(payload),
- );
- }
- extra
-}
-
-/// The journal's established string form of a row: the native envelope for a
-/// tool round, `[IMAGE:<url>]` markers for image parts, plain text otherwise.
-fn journal_content(message: &TranscriptMessage) -> String {
- if message.parts.is_some() {
- message.display_content()
- } else {
- message.legacy_content()
- }
-}
-
-/// The `JournalProjector` OpenHuman passes to the importer.
-pub fn journal_message_from_transcript(message: TranscriptMessage) -> JournalMessage {
- JournalMessage {
- id: message.id.clone(),
- role: message.role.clone(),
- content: journal_content(&message),
- extra_metadata: journal_extra_metadata(&message),
- }
-}
-
-#[cfg(test)]
-#[path = "projector_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/session_import/projector_tests.rs b/crates/openhuman-core/src/agent/session_import/projector_tests.rs
deleted file mode 100644
index fd99d2d7d9..0000000000
--- a/crates/openhuman-core/src/agent/session_import/projector_tests.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use super::*;
-
-#[test]
-fn journal_usage_omits_unknown_final_call_counts_and_preserves_measurements() {
- let mut row = TranscriptMessage::assistant("done");
- row.turn_usage = Some(tinyagents_session::transcript::TurnUsage {
- provider: "mock".into(),
- model: "model".into(),
- usage: tinyagents_session::transcript::MessageUsage {
- input: 120,
- output: 30,
- ..Default::default()
- },
- ts: String::new(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: 2,
- });
- let legacy = journal_extra_metadata(&row).unwrap();
- let counts = &legacy[TURN_USAGE_METADATA_KEY]["usage"];
- assert_eq!(counts["input"], 120);
- assert_eq!(counts["output"], 30);
- assert!(counts.get("last_call_input").is_none());
- assert!(counts.get("last_call_output").is_none());
- let usage = &mut row.turn_usage.as_mut().unwrap().usage;
- usage.last_call_input = 70;
- usage.last_call_output = 10;
- let measured = journal_extra_metadata(&row).unwrap();
- assert_eq!(
- measured[TURN_USAGE_METADATA_KEY]["usage"]["last_call_input"],
- 70
- );
- assert_eq!(
- measured[TURN_USAGE_METADATA_KEY]["usage"]["last_call_output"],
- 10
- );
-}