Skip to content

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

refactor(agent): import transcript sessions directly

Steven Enamakelcee6b7523a44
diff --git a/.sdd-progress.md b/.sdd-progress.md
index 5c4cf2df4e..7f18977140 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -12,18 +12,21 @@ in progress. They require direct imports with no compatibility shims and preserv
OpenHuman policy/security, persistence-root wiring, BUS/progress/RPC projection,
and concrete execution adapters.
-Session extraction S1: complete in the TinyAgents submodule (uncommitted at
-this checkpoint): `tinyagents-session::transcript` now owns the neutral
-append-only JSONL codec, file paths, display/model readers, metadata helpers,
-and history/locator interfaces. `TranscriptMessage` and `TranscriptToolCall`
-preserve raw tool argument strings and opaque provider `extra_content` without
-passing through a lossy inference type. Focused evidence: `cargo test
---manifest-path vendor/tinyagents/Cargo.toml -p tinyagents-session transcript`
-passes (2 tests, including malformed raw arguments and provider extension
-round-trip); `cargo check -p tinyagents-session` passes. OpenHuman direct
-consumer cutover is deliberately pending S4; the attempted mechanical cutover
-was reverted before handoff so the host remains on its currently compiling
-implementation until a dedicated slice ports the host conversion tests.
+Session extraction S1-S4: in progress. `tinyagents-session::transcript` owns
+the neutral append-only JSONL codec, paths, display/model readers, metadata,
+history and locator interfaces. Its public history API now stays entirely on
+lossless `TranscriptMessage`; the prior `FileTranscriptHistory -> Message` /
+`ChatHistory` conversion was removed because it dropped native tool calls,
+usage, thinking and provider metadata. OpenHuman production consumers import
+`tinyagents_session::transcript` directly and the local transcript/history
+implementation plus test modules are deleted. The only retained host seam is
+an explicit field-for-field `ChatMessage <-> TranscriptMessage` conversion at
+the persistence/replay boundary. TinyAgents focused transcript tests pass
+(6 tests: raw malformed arguments/provider extensions, malformed records,
+append/compaction/request-id/partials, lossless history, discovery and legacy
+read); root `cargo check -p openhuman` passed. Remaining: compile the
+OpenHuman test targets after their test doubles are moved to the direct trait,
+clean residual stale docs and finish review/commit gates.
Wave 2: complete (direct canonical imports, explicit recursive context, execution-scoped graph bindings including durable resume/retry, registry/definition split, integration fixtures, and full workspace gate; independent Terra reviews resolved).
Wave 3: complete in TinyAgents (all ten host capabilities, truthful unary/stream terminal lifecycle, parent-authority-preserving recursion, budget compression/accounting, and upstream Claude provider merge; independent Terra Gate 3 and merge reviews PASS).
Wave 4 Phase A: complete at OpenHuman commit 9baad52086 (canonical direct imports, behavior-free facade deletion, host-only conversion/tracing seams retained; independent Terra review PASS).
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs b/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
index 17ddc2d0eb..10557af5c1 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
@@ -313,12 +313,12 @@ impl AgentBuilder {
/// session's write handle (`open_stem`), so a fake supplied here takes the
/// whole turn path off the filesystem. Leave unset in production — `None`
/// resolves lazily to a
- /// [`FileTranscriptLocator`][super::super::transcript_history::FileTranscriptLocator]
+ /// [`FileTranscriptLocator`][tinyagents_session::transcript::FileTranscriptLocator]
/// over the agent's current workspace, which is behaviourally identical to
/// the pre-S4 free-function calls.
pub(crate) fn with_session_history_locator(
mut self,
- locator: std::sync::Arc<dyn super::super::transcript_history::SessionHistoryLocator>,
+ locator: std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>,
) -> Self {
self.session_history_locator = Some(locator);
self
diff --git a/crates/openhuman-core/src/agent/harness/session/mod.rs b/crates/openhuman-core/src/agent/harness/session/mod.rs
index e79f76b0be..39e28bdc3e 100644
--- a/crates/openhuman-core/src/agent/harness/session/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/session/mod.rs
@@ -13,7 +13,7 @@
//! [`crate::agent::tinyagents::run_turn_via_tinyagents_shared`], the
//! shared TinyAgents harness assembly. What this module keeps is the
//! OpenHuman product shell around that loop — transcript persistence and
-//! legacy-format compatibility ([`transcript`], [`migration`]), prompt
+//! legacy-format compatibility ([`migration`]), prompt
//! section assembly and KV-cache prefix stability, memory/context injection
//! policy, post-turn hooks, and the persisted history shape. The migration
//! plan for moving the durable parts onto TinyAgents store/cache primitives
@@ -40,8 +40,6 @@ mod migration;
mod runtime;
#[cfg(test)]
mod tool_progress;
-pub(crate) mod transcript;
-pub(crate) mod transcript_history;
mod turn;
// `pub(crate)` since issue #6014: the tool-call-cap instruction is now appended
// inside the loop by `tinyagents::middleware::FinalCallWrapUpMiddleware`, so the
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
index 2c427317bb..7b5df7131b 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
+++ b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
@@ -198,7 +198,12 @@ impl Agent {
// Count the tool-role results carried into the resumed prefix —
// the fidelity the prose fallback would have silently dropped.
let tool_result_msgs = session.messages.iter().filter(|m| m.role == "tool").count();
- let bounded = self.bound_cached_transcript_messages(session.messages);
+ let replay = session
+ .messages
+ .into_iter()
+ .map(crate::agent::messages::chat_message_from_transcript)
+ .collect();
+ let bounded = self.bound_cached_transcript_messages(replay);
if bounded.len() < loaded_count {
log::warn!(
"[web-channel] resume prefix trimmed from {} to {} messages \
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript.rs b/crates/openhuman-core/src/agent/harness/session/transcript.rs
deleted file mode 100644
index 0f5f86e317..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript.rs
+++ /dev/null
@@ -1,149 +0,0 @@
-//! Session transcript persistence for KV cache stability.
-//!
-//! **Source of truth**: `session_raw/{stem}.jsonl` — a *flat* directory.
-//!
-//! Each JSONL file starts with a single metadata line (identified by an
-//! `_meta` key) followed by one JSON object per record. On every
-//! write the companion `.md` file is re-rendered for human readability
-//! under `sessions/{YYYY_MM_DD}/{stem}.md`; it is **never** read back —
-//! all round-trip / resume logic uses the JSONL.
-//!
-//! ## Append-only log (Phase A — transcript-derived view)
-//!
-//! The JSONL is an **append-only event log**. [`write_transcript`] still
-//! full-rewrites (used by one-shot writers: migrations, sub-agent runners,
-//! tests), but the incremental session persistence path
-//! (`persist_session_transcript`) uses [`append_transcript_turn`], which
-//! never rewrites existing lines. It classifies the incoming logical
-//! message set against what was last persisted:
-//!
-//! - **Pure extension** (previously-persisted messages are a prefix of the
-//! new set): only the new tail message lines are appended.
-//! - **Reduction / rewrite** (context reduction dropped or replaced earlier
-//! turns — the previously-persisted set is *not* a prefix): a single
-//! `{"kind":"compaction","replacement":[…]}` record is appended carrying
-//! the full reduced message set. Earlier turns stay on disk untouched.
-//!
-//! Cumulative `_meta` totals are kept fresh without rewriting the file by
-//! appending a fresh `{"_meta":{…}}` line each turn; readers take the **last**
-//! `_meta` line as authoritative (line 1 remains a valid fallback for old
-//! cores that only read the header).
-//!
-//! ### Two read paths
-//!
-//! - **Model context** ([`read_transcript`] / `read_transcript_jsonl`) replays
-//! the log: message lines accumulate, a `compaction` record **replaces** the
-//! accumulator with its `replacement`, and `interrupted:true` partial lines
-//! are **skipped** (they never entered the model's context). The result is
-//! byte-identical to what the old full-rewrite approach produced.
-//! - **Display** ([`read_transcript_display`]) returns **every** record in file
-//! order — pre-compaction history, compaction markers, and interrupted
-//! partials — so the UI projection (Phase B) can render the full timeline.
-//!
-//! ### Compatibility
-//!
-//! Existing files (zero compaction records, no `version`) read identically.
-//! New record kinds and fields are additive: `MessageLine` carries a
-//! `#[serde(flatten)] _extra` catch-all and `MetaPayload` does not set
-//! `deny_unknown_fields`, so an **old** core reading a **new** file skips
-//! unknown-kind lines (a compaction record fails the `role`/`content`
-//! requirement and is logged+skipped) rather than crashing. The `_meta`
-//! carries a `version` field (`TRANSCRIPT_SCHEMA_VERSION`) for future readers.
-//!
-//! ## Storage layout
-//!
-//! ```text
-//! {workspace}/session_raw/{stem}.jsonl ← source of truth (flat)
-//! {workspace}/sessions/YYYY_MM_DD/{stem}.md ← human-readable view
-//! ```
-//!
-//! `stem` is `{unix_ts}_{agent_id}` for a root session, or
-//! `{parent_chain}__{unix_ts}_{agent_id}` for a sub-agent. Because the
-//! stem starts with the unix timestamp at agent-build time, a directory
-//! listing of `session_raw/` is naturally sorted by creation time and
-//! `find_latest_transcript` becomes O(scan one dir, filter by suffix)
-//! — it does not depend on the calendar date, so a session that's been
-//! idle for weeks resumes the same way as one from yesterday.
-//!
-//! ## Backward compatibility
-//!
-//! Older releases wrote into `session_raw/DDMMYYYY/{stem}.jsonl` (and
-//! the legacy `sessions/DDMMYYYY/{stem}.md`). [`find_latest_transcript`]
-//! falls back to scanning those date-grouped dirs when the flat
-//! directory yields nothing, so users upgrading don't lose resume.
-//!
-//! ## JSONL schema
-//!
-//! **Line 1 (meta):**
-//! ```json
-//! {"_meta":{"agent":"code_executor","dispatcher":"native","created":"...","updated":"...","turn_count":3,"input_tokens":5000,"output_tokens":1200,"cached_input_tokens":3500,"charged_amount_usd":0.0045,"thread_id":"thr_abc123"}}
-//! ```
-//!
-//! **Message lines:**
-//! ```json
-//! {"role":"system","content":"..."}
-//! {"role":"user","content":"..."}
-//! {"role":"assistant","content":"...","model":"claude-...","usage":{"input":1234,"output":567,"cached_input":1000,"cost_usd":0.0012},"ts":"2026-04-17T..."}
-//! {"role":"tool","content":"..."}
-//! ```
-//!
-//! Only `role` and `content` are required. All other fields are optional.
-//! UI-visible rows may also carry a stable `id` and `extra_metadata` so
-//! the session transcript can eventually replace the separate thread
-//! message log without losing message-level addressing.
-//!
-//! ## Module layout
-//!
-//! | File | Role |
-//! |-----------------|-------------------------------------------------------------|
-//! | `types` | Public domain types (`TranscriptMeta`, projections, usage). |
-//! | `metadata` | `extra_metadata` side-channel keys (turn usage, failures). |
-//! | `jsonl` | Line shapes and line ⇄ message conversions. |
-//! | `writer` | Full rewrite, append-only turn delta, interrupted partials. |
-//! | `reader` | Model-context replay, display projection, meta-only scans. |
-//! | `thread_lookup` | Thread → root transcript lookup and usage summaries. |
-//! | `paths` | `session_raw` / `sessions` path resolution and resume scan. |
-//! | `markdown` | Human-readable `.md` companion rendering. |
-//! | `legacy_md` | Legacy HTML-comment `.md` reader. |
-
-mod jsonl;
-mod legacy_md;
-mod markdown;
-mod metadata;
-mod paths;
-mod reader;
-mod thread_lookup;
-mod types;
-mod writer;
-
-pub use legacy_md::read_transcript_legacy_md;
-pub(crate) use metadata::attach_tool_failure_metadata;
-#[cfg(test)]
-pub(crate) use metadata::attach_turn_usage_metadata;
-pub(crate) use metadata::mark_replayed_if_unmarked;
-pub use paths::{find_latest_transcript, resolve_keyed_transcript_path};
-pub use reader::{read_transcript, read_transcript_display};
-pub use thread_lookup::{
- find_root_transcript_for_thread, find_root_transcript_for_thread_scoped,
- find_root_transcripts_for_thread, read_thread_usage_summary,
-};
-pub use types::{
- CompactionMarker, DisplayMessage, DisplayRecord, MessageUsage, SessionTranscript,
- TranscriptMeta, TurnUsage,
-};
-pub use writer::{append_interrupted_partial, append_transcript_turn, write_transcript};
-
-// Private helpers the colocated tests exercise directly.
-#[cfg(test)]
-use jsonl::build_message_line;
-#[cfg(test)]
-use paths::{
- latest_in_dir, md_companion_path, next_index, raw_session_dir, resolve_new_transcript_path,
- sanitize_agent_name,
-};
-
-// ── Tests ─────────────────────────────────────────────────────────────
-
-#[cfg(test)]
-#[path = "transcript_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs b/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
deleted file mode 100644
index 0ef25ea1e5..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
+++ /dev/null
@@ -1,402 +0,0 @@
-//! JSONL line shapes (`_meta`, message, and compaction records) and the
-//! conversions between them and the public [`ChatMessage`] /
-//! [`TranscriptMeta`] / [`DisplayMessage`] types.
-
-use super::metadata::{
- attach_replayed_metadata, attach_tool_failure_metadata, attach_turn_usage_metadata,
- take_replayed_request_id, take_tool_failure,
-};
-use super::types::{
- DisplayMessage, MessageUsage, TranscriptMeta, TurnUsage, TRANSCRIPT_SCHEMA_VERSION,
-};
-use crate::agent::harness::session::transcript::metadata::turn_usage_from_metadata;
-use crate::agent::messages::ChatMessage;
-use crate::inference::provider::ToolCall;
-use anyhow::{Context, Result};
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-
-/// Discriminator value for a compaction record's `kind` field.
-pub(super) const COMPACTION_KIND: &str = "compaction";
-
-#[allow(clippy::trivially_copy_pass_by_ref)]
-fn is_false(b: &bool) -> bool {
- !*b
-}
-
-// ── Internal JSONL types ─────────────────────────────────────────────
-
-/// The `_meta` line serialisation shape.
-#[derive(Serialize, Deserialize)]
-pub(super) struct MetaLine {
- #[serde(rename = "_meta")]
- pub(super) meta: MetaPayload,
-}
-
-#[derive(Serialize, Deserialize)]
-pub(super) struct MetaPayload {
- /// Schema version of the transcript record format (see
- /// [`TRANSCRIPT_SCHEMA_VERSION`]). Absent (deserialises to `0`) on files
- /// written before the append-only migration.
- #[serde(default)]
- pub(super) version: u32,
- pub(super) agent: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) agent_id: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) agent_type: Option<String>,
- pub(super) dispatcher: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) provider: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) model: Option<String>,
- pub(super) created: String,
- pub(super) updated: String,
- pub(super) turn_count: usize,
- pub(super) input_tokens: u64,
- pub(super) output_tokens: u64,
- pub(super) cached_input_tokens: u64,
- pub(super) charged_amount_usd: f64,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) thread_id: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) task_id: Option<String>,
-}
-
-/// One message line in the JSONL — only `role` and `content` are required.
-/// All other fields are optional; unknown fields are flattened to preserve
-/// forward-compatibility.
-#[derive(Serialize, Deserialize)]
-pub(super) struct MessageLine {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) id: Option<String>,
- pub(super) role: String,
- pub(super) content: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) extra_metadata: Option<serde_json::Value>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) provider: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) model: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) usage: Option<MessageUsage>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) reasoning_content: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) tool_calls: Option<Vec<ToolCall>>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) iteration: Option<u32>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(super) ts: Option<String>,
- /// Turn boundary marker: the web-chat `request_id` this message belongs to,
- /// when available. Stamped on every line of a turn so the display projection
- /// can group a turn's messages. Absent for CLI / non-request-scoped runs.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) request_id: Option<String>,
- /// `true` when this line is a *partial* assistant answer captured because
- /// the turn was interrupted/cancelled mid-stream. Present for **display
- /// only** — the model-context reader skips these so a resumed context never
- /// carries a truncated answer.
- #[serde(default, skip_serializing_if = "is_false")]
- pub(super) interrupted: bool,
- /// `true` when this tool-result line's tool call **failed**
- /// (`ToolResult::is_error`). Additive + optional: legacy lines and every
- /// non-tool line omit it and default to success. Lifted from the tool
- /// message's failure metadata by [`build_message_line`]; consumed by the
- /// display projection to render an error tool row instead of success.
- #[serde(default, skip_serializing_if = "is_false")]
- pub(super) failure: bool,
- /// Optional short, single-line reason for a failed tool call (the head of
- /// the error output). Present only alongside `failure: true`.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) failure_detail: Option<String>,
- /// Absorb any unknown fields so forward-compat reads don't error.
- #[serde(flatten)]
- pub(super) _extra: HashMap<String, serde_json::Value>,
-}
-
-/// A compaction record: `{"kind":"compaction","replacement":[…]}`.
-///
-/// Appended when the harness reduces context (post-compaction / trim) so the
-/// model-context reader can reconstruct the reduced set without the file being
-/// destructively rewritten. `replacement` is the **full** logical message set
-/// that supersedes everything before it — an explicit replacement list
-/// (mirroring Codex's `Compacted { replacement_history }`) rather than
-/// surviving-message ids, because our writer already holds the reduced
-/// `messages` slice on each persist call and message ids are optional, so an
-/// id-reference scheme would be less robust for no gain.
-#[derive(Serialize, Deserialize)]
-pub(super) struct CompactionLine {
- pub(super) kind: String,
- pub(super) replacement: Vec<MessageLine>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) ts: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub(super) request_id: Option<String>,
- #[serde(flatten)]
- pub(super) _extra: HashMap<String, serde_json::Value>,
-}
-
-/// Build the serialised `_meta` header line for `meta`, stamping the current
-/// [`TRANSCRIPT_SCHEMA_VERSION`].
-fn meta_payload_from(meta: &TranscriptMeta) -> MetaPayload {
- MetaPayload {
- version: TRANSCRIPT_SCHEMA_VERSION,
- agent: meta.agent_name.clone(),
- agent_id: meta.agent_id.clone(),
- agent_type: meta.agent_type.clone(),
- dispatcher: meta.dispatcher.clone(),
- provider: meta.provider.clone(),
- model: meta.model.clone(),
- created: meta.created.clone(),
- updated: meta.updated.clone(),
- turn_count: meta.turn_count,
- input_tokens: meta.input_tokens,
- output_tokens: meta.output_tokens,
- cached_input_tokens: meta.cached_input_tokens,
- charged_amount_usd: meta.charged_amount_usd,
- thread_id: meta.thread_id.clone(),
- task_id: meta.task_id.clone(),
- }
-}
-
-pub(super) fn meta_line_json(meta: &TranscriptMeta) -> Result<String> {
- let meta_line = MetaLine {
- meta: meta_payload_from(meta),
- };
- serde_json::to_string(&meta_line).context("serialise transcript meta header")
-}
-
-/// Build a [`MessageLine`] for `msg`, folding in `turn_usage` (assistant rows)
-/// and stamping the `request_id` turn boundary when supplied.
-pub(super) fn build_message_line(
- msg: &ChatMessage,
- turn_usage: Option<&TurnUsage>,
- request_id: Option<&str>,
- interrupted: bool,
-) -> MessageLine {
- let assistant_usage = if msg.role == "assistant" {
- turn_usage
- } else {
- None
- };
- // Lift any tool-failure marker off a cloned `extra_metadata` onto the
- // additive top-level `failure` / `failure_detail` line fields, stripping it
- // so it is not persisted twice.
- let mut extra_metadata = msg.extra_metadata.clone();
- let (failure, failure_detail) = match take_tool_failure(&mut extra_metadata) {
- Some((failed, detail)) => (failed, detail),
- None => (false, None),
- };
- // A row replayed from an earlier turn keeps the request it was first
- // written under; only this turn's own rows take `request_id` (#6282).
- let request_id = match take_replayed_request_id(&mut extra_metadata) {
- Some(original) => original,
- None => request_id.map(str::to_string),
- };
- let message_reasoning = (msg.role == "assistant")
- .then(|| {
- extra_metadata
- .as_ref()
- .and_then(|meta| meta.get(crate::agent::message_convert::REASONING_EXT_KEY))
- .and_then(serde_json::Value::as_str)
- .map(str::to_string)
- })
- .flatten();
- let native_envelope = (msg.role == "assistant")
- .then(|| serde_json::from_str::<serde_json::Value>(&msg.content).ok())
- .flatten();
- let envelope_reasoning = native_envelope
- .as_ref()
- .and_then(|value| value.get("reasoning_content"))
- .and_then(serde_json::Value::as_str)
- .map(str::to_string);
- let envelope_tool_calls = native_envelope
- .as_ref()
- .and_then(|value| value.get("tool_calls"))
- .and_then(|value| serde_json::from_value::<Vec<ToolCall>>(value.clone()).ok())
- .filter(|calls| !calls.is_empty());
- MessageLine {
- id: msg.id.clone(),
- role: msg.role.clone(),
- content: msg.content.clone(),
- extra_metadata,
- provider: assistant_usage.map(|tu| tu.provider.clone()),
- model: assistant_usage.map(|tu| tu.model.clone()),
- usage: assistant_usage.map(|tu| tu.usage.clone()),
- reasoning_content: message_reasoning
- .or(envelope_reasoning)
- .or_else(|| assistant_usage.and_then(|tu| tu.reasoning_content.clone())),
- tool_calls: envelope_tool_calls.or_else(|| {
- assistant_usage.and_then(|tu| {
- if tu.tool_calls.is_empty() {
- None
- } else {
- Some(tu.tool_calls.clone())
- }
- })
- }),
- iteration: assistant_usage.map(|tu| tu.iteration),
- ts: assistant_usage.map(|tu| tu.ts.clone()),
- request_id,
- interrupted,
- failure,
- failure_detail,
- _extra: HashMap::new(),
- }
-}
-
-/// Serialise `messages` into JSONL message lines, attributing
-/// `last_assistant_turn_usage` (or per-message embedded usage) to the last
-/// assistant row and stamping `request_id` on every line.
-pub(super) fn serialise_message_lines(
- messages: &[ChatMessage],
- last_assistant_turn_usage: Option<&TurnUsage>,
- request_id: Option<&str>,
- buf: &mut String,
-) -> Result<()> {
- let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
- for (i, msg) in messages.iter().enumerate() {
- let turn_usage = if Some(i) == last_assistant_idx {
- last_assistant_turn_usage
- .cloned()
- .or_else(|| turn_usage_from_metadata(msg))
- } else {
- turn_usage_from_metadata(msg)
- };
- let line = build_message_line(msg, turn_usage.as_ref(), request_id, false);
- let line_json =
- serde_json::to_string(&line).with_context(|| format!("serialise message line {i}"))?;
- buf.push_str(&line_json);
- buf.push('\n');
- }
- Ok(())
-}
-
-/// Convert a parsed `MetaPayload` into the public [`TranscriptMeta`].
-pub(super) fn meta_from_payload(mp: MetaPayload) -> TranscriptMeta {
- TranscriptMeta {
- agent_name: mp.agent,
- agent_id: mp.agent_id,
- agent_type: mp.agent_type,
- dispatcher: mp.dispatcher,
- provider: mp.provider,
- model: mp.model,
- created: mp.created,
- updated: mp.updated,
- turn_count: mp.turn_count,
- input_tokens: mp.input_tokens,
- output_tokens: mp.output_tokens,
- cached_input_tokens: mp.cached_input_tokens,
- charged_amount_usd: mp.charged_amount_usd,
- thread_id: mp.thread_id,
- task_id: mp.task_id,
- }
-}
-
-/// Recover the [`TurnUsage`] a message line carried (assistant rows only).
-fn turn_usage_from_line(ml: &MessageLine) -> Option<TurnUsage> {
- match (
- ml.provider.clone(),
- ml.model.clone(),
- ml.usage.clone(),
- ml.ts.clone(),
- ) {
- (Some(provider), Some(model), Some(usage), Some(ts)) if ml.role == "assistant" => {
- Some(TurnUsage {
- provider,
- model,
- usage,
- ts,
- reasoning_content: ml.reasoning_content.clone(),
- tool_calls: ml.tool_calls.clone().unwrap_or_default(),
- iteration: ml.iteration.unwrap_or_default(),
- })
- }
- _ => None,
- }
-}
-
-/// Reconstruct a [`ChatMessage`] from a message line, re-attaching turn-usage
-/// metadata so the round-trip is lossless for the model-context path.
-pub(super) fn message_from_line(ml: MessageLine) -> ChatMessage {
- let turn_usage = turn_usage_from_line(&ml);
- let failure_detail = ml.failure.then(|| ml.failure_detail.clone());
- let request_id = ml.request_id.clone();
- let mut message = ChatMessage {
- id: ml.id,
- role: ml.role,
- content: ml.content,
- extra_metadata: ml.extra_metadata,
- cache_breakpoints: Vec::new(),
- };
- if let Some(turn_usage) = turn_usage.as_ref() {
- attach_turn_usage_metadata(&mut message, turn_usage);
- }
- // Carry what the line recorded about the turn that wrote it back onto the
- // message, so re-persisting it (a resume into a fresh transcript) writes the
- // same `failure` flag and `request_id` instead of losing the flag and
- // restamping the row with the resuming request (#6282). A line with neither
- // reads back exactly as it was written.
- if let Some(detail) = failure_detail {
- attach_tool_failure_metadata(&mut message, detail.as_deref());
- }
- if let Some(request_id) = request_id.as_deref() {
- attach_replayed_metadata(&mut message, Some(request_id));
- }
- message
-}
-
-/// Classification of one non-empty JSONL line.
-pub(super) enum LineKind {
- Meta(MetaLine),
- Compaction(CompactionLine),
- Message(MessageLine),
-}
-
-/// Classify a raw line: a `_meta` header/update, a `compaction` record, or a
-/// message line. Returns `Err` only when the line is malformed for its
-/// apparent kind; the caller decides whether that is fatal (first line) or a
-/// skippable warning (later lines).
-pub(super) fn classify_line(line: &str) -> Result<LineKind, serde_json::Error> {
- // Cheap structural peek. Unknown/other shapes fall through to MessageLine,
- // whose required `role`/`content` gate rejects genuinely foreign lines.
- let value: serde_json::Value = serde_json::from_str(line)?;
- if value.get("_meta").is_some() {
- return serde_json::from_str::<MetaLine>(line).map(LineKind::Meta);
- }
- if value.get("kind").and_then(|k| k.as_str()) == Some(COMPACTION_KIND) {
- return serde_json::from_str::<CompactionLine>(line).map(LineKind::Compaction);
- }
- serde_json::from_str::<MessageLine>(line).map(LineKind::Message)
-}
-
-// ── Display read ──────────────────────────────────────────────────────
-
-/// Reconstruct a [`DisplayMessage`] from a message line, preserving the
-/// turn-boundary + partial flags the model-context path discards.
-pub(super) fn display_message_from_line(ml: MessageLine) -> DisplayMessage {
- let turn_usage = turn_usage_from_line(&ml);
- let reasoning_content = ml.reasoning_content.clone().or_else(|| {
- turn_usage
- .as_ref()
- .and_then(|tu| tu.reasoning_content.clone())
- });
- DisplayMessage {
- interrupted: ml.interrupted,
- request_id: ml.request_id.clone(),
- iteration: ml.iteration,
- ts: ml.ts.clone(),
- turn_usage,
- reasoning_content,
- failure: ml.failure,
- failure_detail: ml.failure_detail.clone(),
- message: ChatMessage {
- id: ml.id,
- role: ml.role,
- content: ml.content,
- extra_metadata: ml.extra_metadata,
- cache_breakpoints: Vec::new(),
- },
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs b/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs
deleted file mode 100644
index 5428461fa9..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/legacy_md.rs
+++ /dev/null
@@ -1,139 +0,0 @@
-//! Legacy HTML-comment `.md` transcript reader (one-release migration
-//! compat for sessions written before the JSONL source of truth).
-
-use super::types::{SessionTranscript, TranscriptMeta};
-use crate::agent::messages::ChatMessage;
-use anyhow::{Context, Result};
-use std::fs;
-use std::path::Path;
-
-/// Read a legacy HTML-comment `.md` transcript. Used as a fallback when
-/// only a `.md` exists (no `.jsonl` sibling).
-///
-/// Returns a `SessionTranscript` with whatever fields the `.md` tracked;
-/// fields the old format didn't carry are defaulted.
-pub fn read_transcript_legacy_md(path: &Path) -> Result<SessionTranscript> {
- let raw = fs::read_to_string(path)
- .with_context(|| format!("read legacy transcript {}", path.display()))?;
-
- let meta = parse_legacy_meta(&raw)
- .with_context(|| format!("parse legacy transcript meta in {}", path.display()))?;
-
- let messages = parse_legacy_messages(&raw)
- .with_context(|| format!("parse legacy transcript messages in {}", path.display()))?;
-
- log::debug!(
- "[transcript] loaded {} messages (legacy md) from {}",
- messages.len(),
- path.display()
- );
-
- Ok(SessionTranscript { meta, messages })
-}
-
-const LEGACY_MSG_OPEN_PREFIX: &str = "<!--MSG role=\"";
-const LEGACY_MSG_OPEN_SUFFIX: &str = "\"-->";
-const LEGACY_MSG_CLOSE: &str = "<!--/MSG-->";
-const LEGACY_MSG_CLOSE_ESCAPED: &str = "<!--\\/MSG-->";
-
-fn parse_legacy_meta(raw: &str) -> Result<TranscriptMeta> {
- let header_start = raw
- .find("<!-- session_transcript")
- .context("missing session_transcript header")?;
- let header_end = raw[header_start..]
- .find("-->")
- .context("unclosed session_transcript header")?;
- let header = &raw[header_start..header_start + header_end + 3];
-
- let get = |key: &str| -> Option<String> {
- header.lines().find_map(|line| {
- let line = line.trim();
- if line.starts_with(&format!("{key}:")) {
- Some(line[key.len() + 1..].trim().to_string())
- } else {
- None
- }
- })
- };
-
- Ok(TranscriptMeta {
- agent_name: get("agent").unwrap_or_else(|| "unknown".into()),
- dispatcher: get("dispatcher").unwrap_or_else(|| "native".into()),
- agent_id: None,
- agent_type: None,
- provider: None,
- model: None,
- created: get("created").unwrap_or_default(),
- updated: get("updated").unwrap_or_default(),
- turn_count: get("turn_count").and_then(|s| s.parse().ok()).unwrap_or(0),
- input_tokens: get("input_tokens")
- .and_then(|s| s.parse().ok())
- .unwrap_or(0),
- output_tokens: get("output_tokens")
- .and_then(|s| s.parse().ok())
- .unwrap_or(0),
- cached_input_tokens: get("cached_input_tokens")
- .and_then(|s| s.parse().ok())
- .unwrap_or(0),
- charged_amount_usd: get("charged_usd")
- .and_then(|s| s.trim_start_matches('$').parse().ok())
- .unwrap_or(0.0),
- thread_id: get("thread_id").filter(|s| !s.is_empty()),
- task_id: None,
- })
-}
-
-fn parse_legacy_messages(raw: &str) -> Result<Vec<ChatMessage>> {
- let mut messages = Vec::new();
- let mut search_from = 0;
-
- loop {
- let Some(open_start) = raw[search_from..].find(LEGACY_MSG_OPEN_PREFIX) else {
- break;
- };
- let open_start = search_from + open_start;
- let after_prefix = open_start + LEGACY_MSG_OPEN_PREFIX.len();
-
- let Some(role_end) = raw[after_prefix..].find(LEGACY_MSG_OPEN_SUFFIX) else {
- break;
- };
- let role = raw[after_prefix..after_prefix + role_end].to_string();
-
- let content_start = after_prefix + role_end + LEGACY_MSG_OPEN_SUFFIX.len();
- let content_start = if raw[content_start..].starts_with('\n') {
- content_start + 1
- } else {
- content_start
- };
-
- let close_tag = format!("\n{LEGACY_MSG_CLOSE}");
- let Some(content_end_rel) = raw[content_start..].find(&close_tag) else {
- let Some(content_end_rel) = raw[content_start..].find(LEGACY_MSG_CLOSE) else {
- break;
- };
- let content = &raw[content_start..content_start + content_end_rel];
- messages.push(ChatMessage {
- id: None,
- role,
- content: content.replace(LEGACY_MSG_CLOSE_ESCAPED, LEGACY_MSG_CLOSE),
- extra_metadata: None,
- cache_breakpoints: Vec::new(),
- });
- search_from = content_start + content_end_rel + LEGACY_MSG_CLOSE.len();
- continue;
- };
-
- let content = &raw[content_start..content_start + content_end_rel];
- messages.push(ChatMessage {
- id: None,
- role,
- content: content.replace(LEGACY_MSG_CLOSE_ESCAPED, LEGACY_MSG_CLOSE),
- extra_metadata: None,
- cache_breakpoints: Vec::new(),
- });
-
- search_from = content_start + content_end_rel + close_tag.len();
- }
-
- Ok(messages)
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs b/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs
deleted file mode 100644
index 5be99cecd6..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/markdown.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-//! Human-readable markdown rendering of a transcript (the `.md` companion).
-
-use super::types::{TranscriptMeta, TurnUsage};
-use crate::agent::messages::ChatMessage;
-use std::collections::HashMap;
-use std::fmt::Write as FmtWrite;
-
-/// Render a human-readable markdown representation of the transcript.
-///
-/// This output is **for humans only** — it is never read back by the
-/// application. All resume / round-trip logic uses the JSONL source of truth.
-pub(super) fn render_markdown(
- messages: &[ChatMessage],
- meta: &TranscriptMeta,
- per_message_usage: &HashMap<usize, &TurnUsage>,
-) -> String {
- let mut buf = String::new();
-
- let _ = writeln!(buf, "# Session transcript — {}", meta.agent_name);
- buf.push('\n');
- let _ = writeln!(buf, "- Dispatcher: {}", meta.dispatcher);
- if let Some(agent_id) = meta.agent_id.as_deref() {
- let _ = writeln!(buf, "- Agent ID: `{agent_id}`");
- }
- if let Some(agent_type) = meta.agent_type.as_deref() {
- let _ = writeln!(buf, "- Agent type: `{agent_type}`");
- }
- if let Some(provider) = meta.provider.as_deref() {
- let _ = writeln!(buf, "- Provider: `{provider}`");
- }
- if let Some(model) = meta.model.as_deref() {
- let _ = writeln!(buf, "- Model: `{model}`");
- }
- if let Some(task_id) = meta.task_id.as_deref() {
- let _ = writeln!(buf, "- Task: `{task_id}`");
- }
- if let Some(tid) = meta.thread_id.as_deref() {
- let _ = writeln!(buf, "- Thread: `{tid}`");
- }
- let _ = writeln!(buf, "- Turns: {}", meta.turn_count);
- if meta.input_tokens > 0 || meta.output_tokens > 0 {
- let cache_pct = if meta.input_tokens > 0 {
- (meta.cached_input_tokens as f64 / meta.input_tokens as f64) * 100.0
- } else {
- 0.0
- };
- let _ = writeln!(
- buf,
- "- Tokens: {} in / {} out / {} cached ({:.1}% hit)",
- meta.input_tokens, meta.output_tokens, meta.cached_input_tokens, cache_pct
- );
- }
- if meta.charged_amount_usd > 0.0 {
- let _ = writeln!(buf, "- Charged: ${:.6}", meta.charged_amount_usd);
- }
- let _ = writeln!(buf, "- Updated: {}", meta.updated);
-
- for (i, msg) in messages.iter().enumerate() {
- buf.push_str("\n---\n\n");
-
- if let Some(tu) = per_message_usage.get(&i) {
- let _ = writeln!(
- buf,
- "## [{}] · {} · {} in / {} out / {} cached · ${:.6}",
- msg.role,
- tu.model,
- tu.usage.input,
- tu.usage.output,
- tu.usage.cached_input,
- tu.usage.cost_usd
- );
- if !tu.provider.is_empty() || tu.usage.context_window > 0 {
- let _ = writeln!(
- buf,
- "_provider: `{}` · iteration: {} · context window: {}_",
- tu.provider, tu.iteration, tu.usage.context_window
- );
- }
- if let Some(reasoning) = tu.reasoning_content.as_deref().filter(|s| !s.is_empty()) {
- let _ = writeln!(buf, "\n### Thoughts\n\n{reasoning}\n");
- }
- } else {
- let _ = writeln!(buf, "## [{}]", msg.role);
- }
-
- buf.push('\n');
- buf.push_str(&msg.content);
- buf.push('\n');
- }
-
- buf
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs b/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
deleted file mode 100644
index bfe02ccfa4..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-//! `extra_metadata` side-channel keys on [`ChatMessage`]: turn usage /
-//! provenance and tool-failure markers that the turn loop stamps before
-//! persistence and the transcript writer lifts onto line fields.
-//!
-//! **The `openhuman_*` key namespace inside `extra_metadata` is reserved for
-//! these host markers.** They travel in-band next to caller metadata, so the
-//! writer strips a `openhuman_tool_failure` / `openhuman_replayed` key it finds
-//! there whoever wrote it. A caller value stored under
-//! [`WRAPPED_VALUE_KEY`] is safe, though: a wrap is recorded in the marker's own
-//! payload rather than inferred from that key.
-
-use super::types::TurnUsage;
-use crate::agent::messages::ChatMessage;
-
-const TURN_USAGE_METADATA_KEY: &str = "openhuman_turn_usage";
-
-/// `extra_metadata` key carrying a tool-result message's failure marker. The
-/// harness folds a tool result into a `role:"tool"` message that drops the
-/// per-call failure flag (`ToolResult::is_error`), so the turn loop re-attaches
-/// the outcome here — from the captured `ToolCallOutcome` side-channel — before
-/// persistence. `extra_metadata` is `#[serde(skip_serializing)]` on
-/// [`ChatMessage`], so this never reaches the provider; the transcript writer
-/// lifts it onto the additive [`MessageLine::failure`] / `failure_detail` line
-/// fields and strips it from the persisted `extra_metadata`.
-const TOOL_FAILURE_METADATA_KEY: &str = "openhuman_tool_failure";
-
-/// `extra_metadata` key marking a message **replayed from an earlier turn**: a
-/// row read back from a transcript, or a message seeded from the conversation
-/// log on cold boot. It carries the `request_id` the row was first written with
-/// (`null` when it had none). The writer stamps a replayed row with that
-/// original id instead of the current turn's, so resuming a thread into a fresh
-/// transcript file does not re-attribute every earlier turn's rows to the
-/// resuming request (#6282). Stripped from the persisted `extra_metadata`, like
-/// the failure marker.
-const REPLAYED_METADATA_KEY: &str = "openhuman_replayed";
-
-/// Key a non-object `extra_metadata` value is moved under when a side-channel
-/// marker has to be added next to it. The wrap is recorded in the marker's own
-/// payload (`"wrapped": true`), never inferred from this key being present, so
-/// caller metadata that happens to use the same key is left alone.
-const WRAPPED_VALUE_KEY: &str = "openhuman_wrapped_value";
-
-/// Field a marker payload carries when adding it wrapped a non-object
-/// `extra_metadata` value that [`take_metadata`] must restore.
-const WRAPPED_FLAG: &str = "wrapped";
-
-/// Whether adding a marker to `message` would have to wrap its existing
-/// `extra_metadata` (i.e. it is present and not an object).
-fn would_wrap(message: &ChatMessage) -> bool {
- matches!(&message.extra_metadata, Some(value) if !value.is_object())
-}
-
-/// Insert `value` under `key` in `message.extra_metadata`, moving a non-object
-/// value under [`WRAPPED_VALUE_KEY`] so nothing already there is lost. Callers
-/// that need the value restored on removal record the wrap in their own payload
-/// (see [`would_wrap`]).
-fn insert_metadata(message: &mut ChatMessage, key: &str, value: serde_json::Value) {
- let mut map = match message.extra_metadata.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);
- message.extra_metadata = Some(serde_json::Value::Object(map));
-}
-
-/// Pop `key` out of a cloned `extra_metadata` map, then undo what adding it
-/// did: an object left empty becomes no `extra_metadata` (a legacy-identical
-/// line stays legacy-identical), and a value this marker wrapped (its payload
-/// says so) is restored, so a replayed or failed row persists its original
-/// metadata exactly — including a caller object that itself uses
-/// [`WRAPPED_VALUE_KEY`], which is never treated as a wrap.
-fn take_metadata(extra: &mut Option<serde_json::Value>, key: &str) -> Option<serde_json::Value> {
- let serde_json::Value::Object(map) = extra.as_mut()? else {
- return None;
- };
- let value = map.remove(key)?;
- let wrapped = value
- .get(WRAPPED_FLAG)
- .and_then(serde_json::Value::as_bool)
- .unwrap_or(false);
- if map.is_empty() {
- *extra = None;
- } else if wrapped {
- // Another marker may still sit beside the wrapped value (a replayed row
- // that also failed carries both). Restoring now would drop it, so hand
- // the wrap on and let whichever host marker is removed last restore.
- match [TOOL_FAILURE_METADATA_KEY, REPLAYED_METADATA_KEY]
- .into_iter()
- .find(|remaining| map.contains_key(*remaining))
- {
- Some(carrier) => {
- if let Some(serde_json::Value::Object(marker)) = map.get_mut(carrier) {
- marker.insert(WRAPPED_FLAG.to_string(), serde_json::Value::Bool(true));
- }
- }
- // Only the wrapped value is left: restore it. Anything else still
- // there (turn usage) is not ours to strip, so the wrap stays.
- None if map.len() == 1 => {
- if let Some(original) = map.remove(WRAPPED_VALUE_KEY) {
- *extra = Some(original);
- }
- }
- None => {}
- }
- }
- Some(value)
-}
-
-/// Stamp a tool-result [`ChatMessage`] with its failure outcome so the
-/// transcript writer can persist an explicit failure flag. `detail` is an
-/// optional short, single-line reason (e.g. the head of the error output).
-/// No-op semantics: pass this only for genuinely failed tool calls.
-pub(crate) fn attach_tool_failure_metadata(message: &mut ChatMessage, detail: Option<&str>) {
- let mut payload = serde_json::Map::new();
- payload.insert("failure".to_string(), serde_json::Value::Bool(true));
- if let Some(detail) = detail.map(str::trim).filter(|s| !s.is_empty()) {
- payload.insert(
- "detail".to_string(),
- serde_json::Value::String(detail.to_string()),
- );
- }
- if would_wrap(message) {
- payload.insert(WRAPPED_FLAG.to_string(), serde_json::Value::Bool(true));
- }
- insert_metadata(
- message,
- TOOL_FAILURE_METADATA_KEY,
- serde_json::Value::Object(payload),
- );
-}
-
-/// Pop the tool-failure marker out of a cloned `extra_metadata` map, returning
-/// `Some((true, detail))` when it was present. Strips the key so it is not
-/// duplicated into the persisted `extra_metadata` alongside the top-level
-/// `failure` line field. Legacy lines without the marker return `None`.
-pub(super) fn take_tool_failure(
- extra: &mut Option<serde_json::Value>,
-) -> Option<(bool, Option<String>)> {
- let marker = take_metadata(extra, TOOL_FAILURE_METADATA_KEY)?;
- let detail = marker
- .get("detail")
- .and_then(|d| d.as_str())
- .map(str::to_string);
- Some((true, detail))
-}
-
-/// Mark `message` as replayed from an earlier turn whose request was
-/// `request_id` (`None` when that turn recorded none). See
-/// [`REPLAYED_METADATA_KEY`].
-pub(crate) fn attach_replayed_metadata(message: &mut ChatMessage, request_id: Option<&str>) {
- let mut payload = serde_json::Map::new();
- payload.insert(
- "request_id".to_string(),
- match request_id {
- Some(id) => serde_json::Value::String(id.to_string()),
- None => serde_json::Value::Null,
- },
- );
- if would_wrap(message) {
- payload.insert(WRAPPED_FLAG.to_string(), serde_json::Value::Bool(true));
- }
- insert_metadata(
- message,
- REPLAYED_METADATA_KEY,
- serde_json::Value::Object(payload),
- );
-}
-
-/// Mark `message` as replayed with no recorded request id, unless it already
-/// carries a replayed marker. A transcript row read back with its own
-/// `request_id` keeps that id; every other resumed row (a request-less line, a
-/// conversation-log seed) must not take the resuming turn's id either (#6282).
-pub(crate) fn mark_replayed_if_unmarked(message: &mut ChatMessage) {
- let marked = message
- .extra_metadata
- .as_ref()
- .and_then(|meta| meta.get(REPLAYED_METADATA_KEY))
- .is_some();
- if !marked {
- attach_replayed_metadata(message, None);
- }
-}
-
-/// Pop the replayed marker out of a cloned `extra_metadata` map, returning
-/// `Some(original_request_id)` when the message was replayed and `None` when it
-/// belongs to the turn being written.
-pub(super) fn take_replayed_request_id(
- extra: &mut Option<serde_json::Value>,
-) -> Option<Option<String>> {
- let marker = take_metadata(extra, REPLAYED_METADATA_KEY)?;
- Some(
- marker
- .get("request_id")
- .and_then(|id| id.as_str())
- .map(str::to_string),
- )
-}
-
-pub(crate) fn attach_turn_usage_metadata(message: &mut ChatMessage, turn_usage: &TurnUsage) {
- let Ok(payload) = serde_json::to_value(turn_usage) else {
- log::warn!("[transcript] failed to serialize turn usage metadata");
- return;
- };
- insert_metadata(message, TURN_USAGE_METADATA_KEY, payload);
-}
-
-pub(crate) fn turn_usage_extra_metadata(turn_usage: &TurnUsage) -> Option<serde_json::Value> {
- let mut message = ChatMessage::assistant("");
- attach_turn_usage_metadata(&mut message, turn_usage);
- message.extra_metadata
-}
-
-pub(super) fn turn_usage_from_metadata(message: &ChatMessage) -> Option<TurnUsage> {
- let payload = message
- .extra_metadata
- .as_ref()?
- .get(TURN_USAGE_METADATA_KEY)?;
- serde_json::from_value(payload.clone()).ok()
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs b/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs
deleted file mode 100644
index 4a5b5d2413..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/paths.rs
+++ /dev/null
@@ -1,308 +0,0 @@
-//! Transcript path resolution: the flat `session_raw/{stem}.jsonl` layout,
-//! the dated `.md` companion, legacy date-grouped fallbacks, and the
-//! newest-transcript scan used for resume.
-
-use anyhow::{Context, Result};
-use std::fs;
-use std::path::{Path, PathBuf};
-
-/// Resolve a transcript path under `session_raw/{stem}.jsonl` — a
-/// *flat* directory keyed only by stem. Used by the session-key flow:
-/// the stem is `"{unix_ts}_{agent_id}"` for a root session, or
-/// `"{parent_chain}__{session_key}"` for a sub-agent, so nested
-/// delegations still produce a single flat filename that encodes the
-/// parent → child path.
-///
-/// Creates the directory if needed. Overwrites are intentional: the
-/// `Agent` persists the same transcript file across every turn of a
-/// session, and every sub-agent spawn gets a unique timestamp in its
-/// own key so collisions are effectively impossible.
-pub fn resolve_keyed_transcript_path(workspace_dir: &Path, stem: &str) -> Result<PathBuf> {
- let raw_dir = raw_session_dir(workspace_dir);
- resolve_keyed_transcript_path_in_dir(&raw_dir, stem)
-}
-
-pub fn resolve_keyed_transcript_path_in_dir(raw_dir: &Path, stem: &str) -> Result<PathBuf> {
- fs::create_dir_all(raw_dir)
- .with_context(|| format!("create session_raw dir {}", raw_dir.display()))?;
- let sanitized = sanitize_stem(stem);
- Ok(raw_dir.join(format!("{sanitized}.jsonl")))
-}
-
-/// Sanitize a user-supplied transcript stem so it never escapes the
-/// `session_raw/` directory. Allows ASCII alphanumerics plus a small
-/// punctuation set (`_`, `-`, `.`); every other byte is replaced with
-/// `_`. Empty inputs fall back to `"session"`.
-fn sanitize_stem(stem: &str) -> String {
- let cleaned: String = stem
- .chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' {
- c
- } else {
- '_'
- }
- })
- .collect();
- if cleaned.is_empty() {
- "session".to_string()
- } else {
- cleaned
- }
-}
-
-pub fn resolve_new_transcript_path(workspace_dir: &Path, agent_name: &str) -> Result<PathBuf> {
- let raw_dir = raw_session_dir(workspace_dir);
- fs::create_dir_all(&raw_dir)
- .with_context(|| format!("create session_raw dir {}", raw_dir.display()))?;
-
- let sanitized = sanitize_agent_name(agent_name);
- let idx_raw = next_index(&raw_dir, &sanitized)?;
- // Also consider today's md companion dir so a stale .md from this
- // session doesn't cause an index collision when only .md exists.
- let md_dir = today_md_session_dir(workspace_dir);
- let idx_md = next_index(&md_dir, &sanitized)?;
- let next_idx = idx_raw.max(idx_md);
- let filename = format!("{}_{}.jsonl", sanitized, next_idx);
-
- Ok(raw_dir.join(filename))
-}
-
-/// Find the most recent transcript for `agent_name`.
-///
-/// **Primary**: scan the flat `session_raw/` directory and pick the
-/// newest matching stem (root sessions only — sub-agents are skipped).
-/// **Fallback**: scan the legacy `session_raw/DDMMYYYY/` dirs (today
-/// and yesterday) and the legacy `sessions/DDMMYYYY/` markdown dirs so
-/// users upgrading from the date-grouped layout don't lose resume.
-/// The fallback is one-release transitional and can be removed once
-/// existing transcripts have rolled forward.
-pub fn find_latest_transcript(workspace_dir: &Path, agent_name: &str) -> Option<PathBuf> {
- let sanitized = sanitize_agent_name(agent_name);
- let raw_root = raw_session_dir(workspace_dir);
- let sessions_root = workspace_dir.join("sessions");
-
- // Primary path: flat session_raw/ directory. The stem-suffix scan
- // is naturally date-independent, so an idle thread resumes the same
- // way today as it did weeks ago.
- if raw_root.is_dir() {
- if let Some(path) = latest_in_dir(&raw_root, &sanitized) {
- return Some(path);
- }
- }
-
- // Fallback: legacy date-grouped layout (one-release migration
- // window). Today first, then yesterday — matches the previous
- // behaviour so we don't regress while users still have files in
- // the old structure.
- let today = chrono::Local::now().format("%d%m%Y").to_string();
- let yesterday = (chrono::Local::now() - chrono::Duration::days(1))
- .format("%d%m%Y")
- .to_string();
-
- for date_str in [&today, &yesterday] {
- let raw_dir = raw_root.join(date_str);
- if raw_dir.is_dir() {
- if let Some(path) = latest_in_dir(&raw_dir, &sanitized) {
- return Some(path);
- }
- }
- let legacy_dir = sessions_root.join(date_str);
- if legacy_dir.is_dir() {
- if let Some(path) = latest_in_dir(&legacy_dir, &sanitized) {
- return Some(path);
- }
- }
- }
-
- None
-}
-
-/// Date-grouped directory for human-readable `.md` companions, e.g.
-/// `{workspace}/sessions/2026_05_02`. ISO-style `YYYY_MM_DD` so the
-/// listing sorts lexicographically by date.
-pub(super) fn today_md_session_dir(workspace_dir: &Path) -> PathBuf {
- let date = chrono::Local::now().format("%Y_%m_%d").to_string();
- workspace_dir.join("sessions").join(date)
-}
-
-/// Flat directory for the JSONL source of truth, e.g.
-/// `{workspace}/session_raw`. Stems start with `{unix_ts}` so the
-/// listing is naturally time-ordered without a date subdirectory.
-pub(super) fn raw_session_dir(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("session_raw")
-}
-
-/// Given a `session_raw/{stem}.jsonl` path, derive the companion
-/// `sessions/YYYY_MM_DD/{stem}.md` path. The date is taken from the
-/// local clock at write time — fine for browsing because the source
-/// of truth lives in the flat raw dir; the `.md` is purely a view.
-///
-/// Legacy `session_raw/DDMMYYYY/{stem}.jsonl` paths (still on disk
-/// from older releases until they roll forward) keep their date
-/// component when generating the companion so we don't accidentally
-/// stamp old transcripts with today's date.
-///
-/// If no `session_raw` component is present (tests using a flat
-/// tempdir), the companion sits alongside as a sibling `.md`.
-pub(super) fn md_companion_path(jsonl_path: &Path) -> PathBuf {
- let components: Vec<_> = jsonl_path.components().collect();
-
- let raw_idx = components
- .iter()
- .position(|comp| matches!(comp, std::path::Component::Normal(s) if *s == "session_raw"));
-
- let Some(raw_idx) = raw_idx else {
- return jsonl_path.with_extension("md");
- };
-
- let mut out = PathBuf::new();
- for comp in &components[..raw_idx] {
- out.push(comp.as_os_str());
- }
- out.push("sessions");
-
- // Tail after `session_raw`:
- // * Flat: ["{stem}.jsonl"] — prepend today's YYYY_MM_DD.
- // * Legacy: ["DDMMYYYY", "{stem}.jsonl"] — keep the existing
- // date dir so we don't relabel old transcripts.
- let tail = &components[raw_idx + 1..];
- if tail.len() <= 1 {
- out.push(chrono::Local::now().format("%Y_%m_%d").to_string());
- }
- for comp in tail {
- out.push(comp.as_os_str());
- }
-
- out.with_extension("md")
-}
-
-pub(super) fn sanitize_agent_name(name: &str) -> String {
- name.chars()
- .map(|c| {
- if c.is_alphanumeric() || c == '-' || c == '_' {
- c
- } else {
- '_'
- }
- })
- .collect()
-}
-
-/// Compute the next free index for `agent_prefix` in `dir`.
-///
-/// Considers both `.jsonl` and `.md` files so that indices stay unique
-/// during the one-release migration window when both extensions may exist.
-pub(super) fn next_index(dir: &Path, agent_prefix: &str) -> Result<usize> {
- let prefix = format!("{}_", agent_prefix);
- let mut max_idx: Option<usize> = None;
-
- if let Ok(entries) = fs::read_dir(dir) {
- for entry in entries.flatten() {
- let name = entry.file_name();
- let name = name.to_string_lossy();
- if !name.starts_with(&prefix) {
- continue;
- }
- // Accept both extensions.
- let stem_end = if name.ends_with(".jsonl") {
- name.len() - 6
- } else if name.ends_with(".md") {
- name.len() - 3
- } else {
- continue;
- };
- let idx_str = &name[prefix.len()..stem_end];
- if let Ok(idx) = idx_str.parse::<usize>() {
- max_idx = Some(max_idx.map_or(idx, |m: usize| m.max(idx)));
- }
- }
- }
-
- Ok(max_idx.map_or(0, |m| m + 1))
-}
-
-/// Find the latest transcript file for `agent_prefix` in `dir`.
-///
-/// Prefers `.jsonl` files; falls back to `.md` if no `.jsonl` exists
-/// (legacy sessions). When both exist for the same index the `.jsonl`
-/// wins.
-pub(super) fn latest_in_dir(dir: &Path, agent_prefix: &str) -> Option<PathBuf> {
- // Two transcript-naming schemes coexist on disk:
- // * Legacy: `{agent}_{index}.jsonl|.md` — strictly increasing
- // index, used by the now-removed `resolve_new_transcript_path`.
- // * Keyed: `{unix_ts}_{agent}.jsonl` (root session) or
- // `{parent_chain}__{unix_ts}_{agent}.jsonl` (sub-agent). The
- // root stem starts with `{unix_ts}_{agent}` and has no `__`
- // prefix segment.
- //
- // For resume we only care about root sessions (sub-agents rebuild
- // from scratch), so we scan for filenames matching either scheme
- // and pick the newest. "Newest" is the largest sort key — indices
- // and unix timestamps both order naturally as integers.
- let legacy_prefix = format!("{}_", agent_prefix);
- let keyed_suffix = format!("_{}", agent_prefix);
- let mut best_jsonl: Option<(u64, PathBuf)> = None;
- let mut best_md: Option<(u64, PathBuf)> = None;
-
- let entries = fs::read_dir(dir).ok()?;
- for entry in entries.flatten() {
- let name = entry.file_name();
- let name_str = name.to_string_lossy();
- // Extract the stem minus extension.
- let (stem, is_jsonl) = if let Some(s) = name_str.strip_suffix(".jsonl") {
- (s, true)
- } else if let Some(s) = name_str.strip_suffix(".md") {
- (s, false)
- } else {
- continue;
- };
- // Skip sub-agent transcripts — they carry at least one `__`
- // separator in their stem (e.g.
- // `{orch_key}__{planner_key}`). Root resume never targets a
- // sub-agent's transcript directly.
- if stem.contains("__") {
- continue;
- }
- // Determine sort key. Keyed filenames end with
- // `_{agent_prefix}`: everything before that is the unix
- // timestamp. Legacy filenames start with `{agent_prefix}_`:
- // everything after is the numeric index.
- let sort_key: u64 = if let Some(ts_part) = stem.strip_suffix(&keyed_suffix) {
- match ts_part.parse::<u64>() {
- Ok(ts) => ts,
- Err(_) => continue,
- }
- } else if let Some(idx_part) = stem.strip_prefix(&legacy_prefix) {
- match idx_part.parse::<u64>() {
- Ok(idx) => idx,
- Err(_) => continue,
- }
- } else {
- continue;
- };
- let slot = if is_jsonl {
- &mut best_jsonl
- } else {
- &mut best_md
- };
- if slot.as_ref().is_none_or(|(best, _)| sort_key > *best) {
- *slot = Some((sort_key, entry.path()));
- }
- }
-
- // Prefer the best .jsonl; fall back to .md if no .jsonl exists.
- match (best_jsonl, best_md) {
- (Some(jsonl), Some(md)) => {
- // Take the one with the higher index; on a tie prefer .jsonl.
- if md.0 > jsonl.0 {
- Some(md.1)
- } else {
- Some(jsonl.1)
- }
- }
- (Some(jsonl), None) => Some(jsonl.1),
- (None, Some(md)) => Some(md.1),
- (None, None) => None,
- }
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs b/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs
deleted file mode 100644
index f5c868288a..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/reader.rs
+++ /dev/null
@@ -1,287 +0,0 @@
-//! Transcript readers: the model-context replay ([`read_transcript`]), the
-//! display projection ([`read_transcript_display`]), and the cheap
-//! meta-only / last-usage scans used by thread summaries.
-
-use super::jsonl::{
- classify_line, display_message_from_line, message_from_line, meta_from_payload, LineKind,
- MetaLine,
-};
-use super::legacy_md::read_transcript_legacy_md;
-use super::types::{
- CompactionMarker, DisplayRecord, DisplaySessionTranscript, MessageUsage, SessionTranscript,
- TranscriptMeta,
-};
-use crate::agent::messages::ChatMessage;
-use anyhow::{Context, Result};
-use std::fs;
-use std::path::Path;
-
-/// Read a session transcript.
-///
-/// **Primary path**: reads the `.jsonl` source of truth.
-/// **Fallback**: if the `.jsonl` does not exist but the legacy `.md` does
-/// (migration path — old sessions), reads it via the legacy HTML-comment
-/// parser and returns a `SessionTranscript` with default meta where the
-/// `.md` format didn't track a field.
-pub fn read_transcript(path: &Path) -> Result<SessionTranscript> {
- // Route by extension first: a legacy `.md` path (returned by
- // `find_latest_transcript` when only legacy files exist) must go to
- // the legacy parser, never to the JSONL parser.
- if path.extension().and_then(|s| s.to_str()) == Some("md") {
- log::debug!(
- "[transcript] reading legacy .md transcript: {}",
- path.display()
- );
- return read_transcript_legacy_md(path);
- }
-
- if path.exists() {
- read_transcript_jsonl(path)
- } else {
- // Fallback: try the .md sibling (legacy one-release compat).
- let md_path = path.with_extension("md");
- if md_path.exists() {
- log::debug!(
- "[transcript] .jsonl not found, falling back to legacy .md: {}",
- md_path.display()
- );
- read_transcript_legacy_md(&md_path)
- } else {
- // Neither exists — propagate the original jsonl error.
- read_transcript_jsonl(path)
- }
- }
-}
-
-fn read_transcript_jsonl(path: &Path) -> Result<SessionTranscript> {
- let raw = fs::read_to_string(path)
- .with_context(|| format!("read transcript jsonl {}", path.display()))?;
-
- let mut meta: Option<TranscriptMeta> = None;
- let mut messages: Vec<ChatMessage> = Vec::new();
- let mut compactions_replayed = 0usize;
- let mut interrupted_skipped = 0usize;
-
- // Append-only log replay (Phase A): the first non-empty line MUST be the
- // `_meta` header; subsequent lines are messages, `compaction` records
- // (which *replace* the accumulated context), interrupted partials (skipped
- // for the model-context path), or refreshed `_meta` lines (last wins).
- let mut seen_first = false;
- for (line_no, line) in raw.lines().enumerate() {
- let line = line.trim();
- if line.is_empty() {
- continue;
- }
-
- if !seen_first {
- seen_first = true;
- let ml: MetaLine = serde_json::from_str(line).map_err(|err| {
- anyhow::anyhow!(
- "first non-empty line of {} (line {}) is not a valid _meta object: {err}",
- path.display(),
- line_no + 1,
- )
- })?;
- meta = Some(meta_from_payload(ml.meta));
- continue;
- }
-
- match classify_line(line) {
- Ok(LineKind::Meta(ml)) => {
- // Refreshed cumulative meta — last one wins.
- meta = Some(meta_from_payload(ml.meta));
- }
- Ok(LineKind::Compaction(cl)) => {
- // Reduction record: the reduced context REPLACES everything
- // accumulated so far, exactly reproducing the old full-rewrite.
- let replacement: Vec<ChatMessage> =
- cl.replacement.into_iter().map(message_from_line).collect();
- log::debug!(
- "[transcript] replay: compaction at line {} replaces {} accumulated message(s) with {} (request_id={:?}) in {}",
- line_no + 1,
- messages.len(),
- replacement.len(),
- cl.request_id,
- path.display()
- );
- messages = replacement;
- compactions_replayed += 1;
- }
- Ok(LineKind::Message(ml)) => {
- if ml.interrupted {
- // Display-only partial — never part of the model context.
- interrupted_skipped += 1;
- log::debug!(
- "[transcript] replay: skipping interrupted partial line {} (display only) in {}",
- line_no + 1,
- path.display()
- );
- continue;
- }
- messages.push(message_from_line(ml));
- }
- Err(err) => {
- log::warn!(
- "[transcript] skipping malformed/unknown record line {} in {}: {err}",
- line_no + 1,
- path.display()
- );
- }
- }
- }
-
- let meta = meta.with_context(|| {
- format!(
- "missing _meta header line in jsonl transcript {}",
- path.display()
- )
- })?;
-
- log::debug!(
- "[transcript] loaded {} messages (jsonl, {} compaction(s) replayed, {} interrupted skipped) from {}",
- messages.len(),
- compactions_replayed,
- interrupted_skipped,
- path.display()
- );
-
- Ok(SessionTranscript { meta, messages })
-}
-
-/// Read a transcript for **display**: returns *every* record in file order,
-/// including pre-compaction history, compaction markers, and interrupted
-/// partials — the counterpart to the model-context [`read_transcript`], which
-/// collapses the log into the reduced context.
-///
-/// `meta` reflects the newest `_meta` line (cumulative totals stay current).
-pub fn read_transcript_display(path: &Path) -> Result<DisplaySessionTranscript> {
- let raw = fs::read_to_string(path)
- .with_context(|| format!("read transcript jsonl (display) {}", path.display()))?;
-
- let mut meta: Option<TranscriptMeta> = None;
- let mut records: Vec<DisplayRecord> = Vec::new();
- let mut seen_first = false;
-
- for (line_no, line) in raw.lines().enumerate() {
- let line = line.trim();
- if line.is_empty() {
- continue;
- }
- if !seen_first {
- seen_first = true;
- let ml: MetaLine = serde_json::from_str(line).map_err(|err| {
- anyhow::anyhow!(
- "first non-empty line of {} (line {}) is not a valid _meta object: {err}",
- path.display(),
- line_no + 1,
- )
- })?;
- meta = Some(meta_from_payload(ml.meta));
- continue;
- }
- match classify_line(line) {
- Ok(LineKind::Meta(ml)) => meta = Some(meta_from_payload(ml.meta)),
- Ok(LineKind::Compaction(cl)) => {
- let replacement = cl
- .replacement
- .into_iter()
- .map(display_message_from_line)
- .collect();
- records.push(DisplayRecord::Compaction(CompactionMarker {
- replacement,
- ts: cl.ts,
- request_id: cl.request_id,
- }));
- }
- Ok(LineKind::Message(ml)) => {
- records.push(DisplayRecord::Message(display_message_from_line(ml)));
- }
- Err(err) => {
- log::warn!(
- "[transcript] display: skipping malformed/unknown record line {} in {}: {err}",
- line_no + 1,
- path.display()
- );
- }
- }
- }
-
- let meta = meta.with_context(|| {
- format!(
- "missing _meta header line in jsonl transcript {}",
- path.display()
- )
- })?;
-
- log::debug!(
- "[transcript] display-loaded {} record(s) from {}",
- records.len(),
- path.display()
- );
-
- Ok(DisplaySessionTranscript { meta, records })
-}
-
-/// Parse the authoritative `_meta` of a root transcript JSONL.
-///
-/// Append-only files carry the immutable header on line 1 plus a refreshed
-/// `_meta` line per turn (cumulative totals). The **last** `_meta` line wins,
-/// so a multi-turn session reports its running totals — not just the first
-/// turn's. Falls back to line 1 for legacy single-header files.
-pub(super) fn read_transcript_meta_only(path: &Path) -> Option<TranscriptMeta> {
- let raw = fs::read_to_string(path).ok()?;
- let mut latest: Option<TranscriptMeta> = None;
- for line in raw.lines() {
- let line = line.trim();
- if line.is_empty() {
- continue;
- }
- if let Ok(ml) = serde_json::from_str::<MetaLine>(line) {
- latest = Some(meta_from_payload(ml.meta));
- } else if latest.is_none() {
- // The first non-empty line must be a valid meta header.
- return None;
- }
- }
- latest
-}
-
-/// Extract the last assistant message's usage + model from a transcript JSONL.
-/// Only the final assistant message of a turn carries these (see the JSONL
-/// format docs at the top of this module). Compaction records and refreshed
-/// `_meta` lines are skipped; a `compaction` record's `replacement` assistant
-/// rows are considered so a compacted transcript still surfaces its latest
-/// usage.
-pub(super) fn read_last_assistant_usage(path: &Path) -> Option<(MessageUsage, Option<String>)> {
- let raw = fs::read_to_string(path).ok()?;
- let mut result = None;
- let mut seen_first = false;
- for line in raw.lines() {
- let line = line.trim();
- if line.is_empty() {
- continue;
- }
- if !seen_first {
- seen_first = true; // first non-empty line is the `_meta` header
- continue;
- }
- match classify_line(line) {
- Ok(LineKind::Message(ml)) if ml.role == "assistant" && !ml.interrupted => {
- if let Some(usage) = ml.usage {
- result = Some((usage, ml.model));
- }
- }
- Ok(LineKind::Compaction(cl)) => {
- for ml in &cl.replacement {
- if ml.role == "assistant" {
- if let Some(usage) = ml.usage.clone() {
- result = Some((usage, ml.model.clone()));
- }
- }
- }
- }
- _ => {}
- }
- }
- result
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs b/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs
deleted file mode 100644
index dc8e9a4b62..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/thread_lookup.rs
+++ /dev/null
@@ -1,222 +0,0 @@
-//! Thread-keyed lookups over the canonical `session_raw` store: locating a thread's
-//! root transcripts and summing its token / cost usage.
-
-use super::paths::raw_session_dir;
-use super::reader::{read_last_assistant_usage, read_transcript, read_transcript_meta_only};
-use super::types::{SubagentArchetypeUsage, ThreadUsageSummary};
-use std::collections::BTreeMap;
-use std::fs;
-use std::path::{Path, PathBuf};
-
-/// Find the newest root transcript whose metadata declares `thread_id`.
-///
-/// Root transcripts live directly under `session_raw/` and do not carry
-/// the `__` separator used for sub-agent siblings. This helper is the
-/// bridge PR-2 can use to route UI thread reads to the canonical root
-/// transcript without accidentally folding delegated worker transcripts
-/// into the main chat timeline.
-pub fn find_root_transcript_for_thread(workspace_dir: &Path, thread_id: &str) -> Option<PathBuf> {
- find_root_transcripts_for_thread(workspace_dir, thread_id).pop()
-}
-
-/// [`find_root_transcript_for_thread`], additionally scoped to `agent_id`
-/// when given.
-///
-/// Plain thread-id matching is ambiguous when several distinct agents can be
-/// given the same caller-supplied `thread_id` — every runtime agent on one
-/// [`Runtime`](openhuman_embed's library host) shares the same
-/// `session_raw/` store, keyed only by thread id in `_meta.thread_id`. Two
-/// agents handed the same id would otherwise resolve to whichever one wrote
-/// the newest matching transcript, splicing agent B's history (and its
-/// caller's data) into agent A's turn. `agent_id` filters on
-/// `_meta.agent_id`, the agent definition id written at turn time, so the
-/// resume this seeds only ever pulls from the calling agent's own history.
-///
-/// `agent_id: None` is the pre-existing unscoped behaviour — used for the
-/// desktop orchestrator, where a `thread_id` is only ever driven by one
-/// logical agent (#5351).
-pub fn find_root_transcript_for_thread_scoped(
- workspace_dir: &Path,
- thread_id: &str,
- agent_id: Option<&str>,
-) -> Option<PathBuf> {
- let mut matches = find_root_transcripts_for_thread(workspace_dir, thread_id);
- if let Some(agent_id) = agent_id {
- matches.retain(|path| {
- read_transcript(path)
- .ok()
- .and_then(|transcript| transcript.meta.agent_id)
- .as_deref()
- == Some(agent_id)
- });
- }
- matches.pop()
-}
-
-pub fn find_root_transcripts_for_thread(workspace_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
- let mut matches = Vec::new();
- matches.extend(root_transcripts_for_thread_in_dir(
- &raw_session_dir(workspace_dir),
- thread_id,
- ));
- matches.sort_by_cached_key(|path| {
- let created = read_transcript(path)
- .ok()
- .map(|transcript| transcript.meta.created)
- .unwrap_or_default();
- (created, path.clone())
- });
- matches
-}
-
-pub fn find_root_transcript_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Option<PathBuf> {
- root_transcripts_for_thread_in_dir(raw_dir, thread_id).pop()
-}
-
-fn root_transcripts_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
- let thread_id = thread_id.trim();
- if thread_id.is_empty() {
- return Vec::new();
- }
-
- let Ok(entries) = fs::read_dir(raw_dir) else {
- return Vec::new();
- };
- // Keyed by `meta.created` so the order is chronological rather than
- // lexicographic. Modern stems are `{unix_ts}_{agent_id}` and sort the same
- // either way, but a legacy `{agent}_{index}` root encodes no time at all —
- // and because digits sort before letters, every legacy root sorted *after*
- // every modern one regardless of when it was written. `project_from_files`
- // concatenates these in order, so that reordered the rendered view and
- // could attach a sub-agent trail to the wrong turn.
- let mut matches: Vec<(String, PathBuf)> = entries
- .flatten()
- .map(|entry| entry.path())
- .filter(|path| {
- path.extension().and_then(|s| s.to_str()) == Some("jsonl")
- && path
- .file_stem()
- .and_then(|s| s.to_str())
- .is_some_and(|stem| !stem.contains("__"))
- })
- .filter_map(|path| match read_transcript(&path) {
- Ok(transcript) if transcript.meta.thread_id.as_deref() == Some(thread_id) => {
- Some((transcript.meta.created.clone(), path))
- }
- Ok(_) => None,
- Err(err) => {
- log::warn!(
- "[transcript] skipping unreadable root transcript candidate {}: {err}",
- path.display()
- );
- None
- }
- })
- .collect();
-
- // Path is the tiebreak so the order stays total and deterministic when two
- // transcripts share a `created` stamp.
- matches.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
- matches.into_iter().map(|(_, path)| path).collect()
-}
-
-/// Summed token/cost usage for `thread_id` across its root transcripts, or
-/// `None` when the thread has no persisted turns yet.
-pub fn read_thread_usage_summary(
- workspace_dir: &Path,
- thread_id: &str,
-) -> Option<ThreadUsageSummary> {
- let thread_id = thread_id.trim();
- if thread_id.is_empty() {
- return None;
- }
-
- // Single scan: split the thread's transcripts into root (orchestrator) and
- // `__` sub-agent files. Root totals stay the parent's; sub-agent files are
- // grouped by archetype for the per-agent breakdown.
- let mut root_matches: Vec<PathBuf> = Vec::new();
- let mut sub_matches: Vec<PathBuf> = Vec::new();
- let raw_dir = raw_session_dir(workspace_dir);
- let Ok(entries) = fs::read_dir(&raw_dir) else {
- return None;
- };
- for path in entries.flatten().map(|entry| entry.path()) {
- if path.extension().and_then(|s| s.to_str()) != Some("jsonl") {
- continue;
- }
- let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
- continue;
- };
- let is_subagent = stem.contains("__");
- let matches_thread = read_transcript_meta_only(&path)
- .map(|m| m.thread_id.as_deref() == Some(thread_id))
- .unwrap_or(false);
- if !matches_thread {
- continue;
- }
- if is_subagent {
- sub_matches.push(path);
- } else {
- root_matches.push(path);
- }
- }
-
- if root_matches.is_empty() && sub_matches.is_empty() {
- return None;
- }
- root_matches.sort_by(|left, right| left.file_name().cmp(&right.file_name()));
-
- let mut summary = ThreadUsageSummary::default();
- for path in &root_matches {
- if let Some(meta) = read_transcript_meta_only(path) {
- summary.input_tokens = summary.input_tokens.saturating_add(meta.input_tokens);
- summary.output_tokens = summary.output_tokens.saturating_add(meta.output_tokens);
- summary.cached_input_tokens = summary
- .cached_input_tokens
- .saturating_add(meta.cached_input_tokens);
- summary.cost_usd += meta.charged_amount_usd;
- summary.turn_count = summary.turn_count.saturating_add(meta.turn_count);
- }
- }
-
- // Newest root transcript drives the last-turn gauge + model + updated stamp.
- if let Some(newest) = root_matches.last() {
- if let Some(meta) = read_transcript_meta_only(newest) {
- summary.updated = meta.updated;
- }
- if let Some((usage, model)) = read_last_assistant_usage(newest) {
- summary.last_turn_input_tokens = usage.input;
- summary.last_turn_output_tokens = usage.output;
- summary.model = model;
- }
- }
-
- // Group sub-agent transcripts by archetype (`agent_name`).
- let mut groups: BTreeMap<String, SubagentArchetypeUsage> = BTreeMap::new();
- for path in &sub_matches {
- let Some(meta) = read_transcript_meta_only(path) else {
- continue;
- };
- let group =
- groups
- .entry(meta.agent_name.clone())
- .or_insert_with(|| SubagentArchetypeUsage {
- agent_id: meta.agent_name.clone(),
- ..Default::default()
- });
- group.input_tokens = group.input_tokens.saturating_add(meta.input_tokens);
- group.output_tokens = group.output_tokens.saturating_add(meta.output_tokens);
- group.cached_input_tokens = group
- .cached_input_tokens
- .saturating_add(meta.cached_input_tokens);
- group.runs = group.runs.saturating_add(1);
- if group.model.is_none() {
- if let Some((_, model)) = read_last_assistant_usage(path) {
- group.model = model;
- }
- }
- }
- summary.subagents = groups.into_values().collect();
-
- Some(summary)
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/types.rs b/crates/openhuman-core/src/agent/harness/session/transcript/types.rs
deleted file mode 100644
index 7f91b8d462..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/types.rs
+++ /dev/null
@@ -1,192 +0,0 @@
-//! Public transcript domain types: per-message usage, the `_meta` header,
-//! the model-context and display projections, and thread usage summaries.
-
-use crate::agent::messages::ChatMessage;
-use crate::inference::provider::ToolCall;
-use serde::{Deserialize, Serialize};
-
-/// Per-message usage figures attributed to the last assistant turn.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct MessageUsage {
- pub input: u64,
- pub output: u64,
- pub cached_input: u64,
- #[serde(default)]
- pub context_window: u64,
- pub cost_usd: f64,
-}
-
-/// Usage + provenance for one provider response, attached to the last
-/// assistant message in a turn.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TurnUsage {
- #[serde(default)]
- pub provider: String,
- #[serde(default)]
- pub model: String,
- pub usage: MessageUsage,
- /// RFC-3339 timestamp of the response.
- #[serde(default)]
- pub ts: String,
- /// Raw reasoning/thinking content returned by thinking models. This is
- /// persisted as metadata so the later transcript view can show the model's
- /// thoughts without depending on the live stream still being open.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub reasoning_content: Option<String>,
- /// Native tool calls emitted in this provider response, if any. Text-mode
- /// calls remain present in `content` as the raw markup the model emitted.
- #[serde(default)]
- pub tool_calls: Vec<ToolCall>,
- /// One-based engine iteration for this provider response.
- #[serde(default)]
- pub iteration: u32,
-}
-
-/// Schema version stamped on the `_meta` header line. Bumped when the JSONL
-/// record shape changes in a way future readers may need to branch on. `0`
-/// (absent) denotes pre-append-only files written before this field existed.
-pub const TRANSCRIPT_SCHEMA_VERSION: u32 = 1;
-
-/// Metadata header for a session transcript file.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct TranscriptMeta {
- pub agent_name: String,
- /// Canonical registry id for the agent that produced this transcript.
- /// `agent_name` may be per-thread renamed for file names; this remains the
- /// stable archetype id when available.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub agent_id: Option<String>,
- /// Coarse runtime kind (`root`, `subagent`, `extractor`, ...).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub agent_type: Option<String>,
- pub dispatcher: String,
- /// Provider label used for the most recent recorded response.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub provider: Option<String>,
- /// Model id used for the most recent recorded response.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- pub created: String,
- pub updated: String,
- pub turn_count: usize,
- /// Cumulative input tokens across all provider calls this session.
- pub input_tokens: u64,
- /// Cumulative output tokens across all provider calls this session.
- pub output_tokens: u64,
- /// Cumulative input tokens served from the KV cache.
- pub cached_input_tokens: u64,
- /// Cumulative amount charged in USD.
- pub charged_amount_usd: f64,
- /// Backend-side LLM thread identifier (the `thread_id` forwarded on
- /// `/openai/v1/chat/completions` so the OpenHuman backend can group
- /// `InferenceLog` entries and align KV-cache keys with the same logical
- /// chat thread the user sees in the UI). `None` for runs that don't
- /// originate from a thread-scoped channel (e.g. CLI-only sessions).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub thread_id: Option<String>,
- /// Sub-agent task id, when this transcript belongs to a spawned worker.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub task_id: Option<String>,
-}
-
-/// A parsed session transcript: metadata + exact message array.
-#[derive(Debug, Clone)]
-pub struct SessionTranscript {
- pub meta: TranscriptMeta,
- pub messages: Vec<ChatMessage>,
-}
-
-// ── Display read types ───────────────────────────────────────────────
-
-/// One message in a display projection, carrying the turn-boundary + partial
-/// flags the model-context [`SessionTranscript`] discards.
-#[derive(Debug, Clone)]
-pub struct DisplayMessage {
- pub message: ChatMessage,
- /// `true` when this is an interrupted partial answer (display only).
- pub interrupted: bool,
- /// Turn boundary marker (`request_id`), when stamped.
- pub request_id: Option<String>,
- pub iteration: Option<u32>,
- pub ts: Option<String>,
- /// Usage/provenance for assistant messages that carried it.
- pub turn_usage: Option<TurnUsage>,
- /// Raw reasoning/thinking captured for this line, when present. Mirrors the
- /// line's `reasoning_content` directly so it survives even on lines without
- /// full turn-usage provenance (e.g. an interrupted partial, which carries no
- /// provider/model/usage). Prefer this over digging into [`Self::turn_usage`]
- /// for display: it is populated from `turn_usage.reasoning_content` too.
- pub reasoning_content: Option<String>,
- /// `true` when this is a **failed** tool-result line (`ToolResult::is_error`
- /// at execution time). The display projection renders an error tool row
- /// instead of success. Always `false` for non-tool lines and legacy files.
- pub failure: bool,
- /// Optional short reason for a failed tool call (present only with
- /// `failure: true`).
- pub failure_detail: Option<String>,
-}
-
-/// A compaction marker in a display projection.
-#[derive(Debug, Clone)]
-pub struct CompactionMarker {
- /// The reduced message set this compaction installed as the new context.
- pub replacement: Vec<DisplayMessage>,
- pub ts: Option<String>,
- pub request_id: Option<String>,
-}
-
-/// One record in a display projection, in file order.
-#[derive(Debug, Clone)]
-pub enum DisplayRecord {
- Message(DisplayMessage),
- Compaction(CompactionMarker),
-}
-
-/// A display projection of a transcript: **all** records, including
-/// pre-compaction history, compaction markers, and interrupted partials.
-#[derive(Debug, Clone)]
-pub struct DisplaySessionTranscript {
- pub meta: TranscriptMeta,
- pub records: Vec<DisplayRecord>,
-}
-
-/// Aggregated token/cost usage for a chat thread, summed across **all** of the
-/// thread's root session transcripts (a thread reopened across days/restarts
-/// produces several files). `last_turn_*`, `model`, and `updated` come from the
-/// newest transcript so the UI can render a context-window gauge for the most
-/// recent turn. Returns `None` when no transcript exists yet (a brand-new
-/// thread with no completed turns).
-#[derive(Debug, Clone, Default, PartialEq)]
-pub struct ThreadUsageSummary {
- /// Orchestrator (parent) token totals — the root transcript(s) only. Root
- /// transcripts never include sub-agent calls (those go to a separate
- /// observer + their own `__` transcript files); see [`Self::subagents`].
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cached_input_tokens: u64,
- pub cost_usd: f64,
- pub turn_count: usize,
- /// Input/output tokens of the most recent assistant turn (context gauge).
- pub last_turn_input_tokens: u64,
- pub last_turn_output_tokens: u64,
- /// Model that served the most recent turn, if recorded.
- pub model: Option<String>,
- /// RFC-3339 `updated` of the newest transcript.
- pub updated: String,
- /// Per-archetype sub-agent spend, reconstructed from the thread's `__`
- /// sub-agent transcripts (grouped by `agent_name`).
- pub subagents: Vec<SubagentArchetypeUsage>,
-}
-
-/// One sub-agent archetype's summed spend within a thread (e.g. all `coder`
-/// runs). `model` is the model that served one of its runs, used to price it.
-#[derive(Debug, Clone, Default, PartialEq)]
-pub struct SubagentArchetypeUsage {
- pub agent_id: String,
- pub input_tokens: u64,
- pub output_tokens: u64,
- pub cached_input_tokens: u64,
- /// How many sub-agent runs of this archetype contributed.
- pub runs: usize,
- pub model: Option<String>,
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs b/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs
deleted file mode 100644
index 57c54cc036..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript/writer.rs
+++ /dev/null
@@ -1,292 +0,0 @@
-//! Transcript writers: the one-shot full rewrite, the append-only per-turn
-//! delta (message tail or compaction record), interrupted partials, and the
-//! derived `.md` companion.
-
-use super::jsonl::{
- build_message_line, meta_line_json, serialise_message_lines, CompactionLine, MessageLine,
- COMPACTION_KIND,
-};
-use super::markdown::render_markdown;
-use super::metadata::turn_usage_from_metadata;
-use super::paths::md_companion_path;
-use super::types::{TranscriptMeta, TurnUsage};
-use crate::agent::messages::ChatMessage;
-use anyhow::{Context, Result};
-use std::collections::HashMap;
-use std::fs;
-use std::path::Path;
-
-/// Write JSONL as source of truth **and** re-render the companion `.md`.
-///
-/// `jsonl_path` must end in `.jsonl`; the `.md` companion is derived by
-/// swapping the extension. **Full rewrite** on every call — this is the
-/// one-shot writer used by migrations, the sub-agent runners, and tests.
-/// The incremental session-persistence path uses [`append_transcript_turn`]
-/// instead, which never rewrites existing lines.
-pub fn write_transcript(
- jsonl_path: &Path,
- messages: &[ChatMessage],
- meta: &TranscriptMeta,
- last_assistant_turn_usage: Option<&TurnUsage>,
-) -> Result<()> {
- if let Some(parent) = jsonl_path.parent() {
- fs::create_dir_all(parent)
- .with_context(|| format!("create transcript dir {}", parent.display()))?;
- }
-
- // ── JSONL ────────────────────────────────────────────────────────
- let mut jsonl_buf = String::new();
- jsonl_buf.push_str(&meta_line_json(meta)?);
- jsonl_buf.push('\n');
- serialise_message_lines(messages, last_assistant_turn_usage, None, &mut jsonl_buf)?;
-
- fs::write(jsonl_path, jsonl_buf.as_bytes())
- .with_context(|| format!("write transcript {}", jsonl_path.display()))?;
-
- log::debug!(
- "[transcript] wrote {} messages (jsonl, full rewrite) to {}",
- messages.len(),
- jsonl_path.display()
- );
-
- render_md_companion(jsonl_path, messages, meta, last_assistant_turn_usage);
- Ok(())
-}
-
-/// Append this turn's delta to an **append-only** transcript, never rewriting
-/// existing lines.
-///
-/// `prev_persisted` is the logical message set the previous call left on disk
-/// (empty on the first call for a fresh file). The incoming `messages` is the
-/// current full logical set for this turn:
-///
-/// - **Pure extension** (`prev_persisted` is a prefix of `messages`): only the
-/// new tail is appended as message lines.
-/// - **Reduction / rewrite** (context reduction changed or dropped earlier
-/// turns): a single `compaction` record carrying the full reduced
-/// `messages` is appended; earlier lines are left untouched on disk.
-///
-/// A fresh `_meta` line is appended so cumulative totals stay current without a
-/// full rewrite. The `.md` companion is re-rendered from `messages` (derived
-/// view — always the reduced/current set). Returns nothing; the caller updates
-/// its tracked `prev_persisted` to `messages` on success.
-///
-/// `request_id` (when available from the web-chat path) is stamped on every
-/// appended line as a turn boundary marker.
-pub fn append_transcript_turn(
- jsonl_path: &Path,
- prev_persisted: &[ChatMessage],
- messages: &[ChatMessage],
- meta: &TranscriptMeta,
- turn_usage: Option<&TurnUsage>,
- request_id: Option<&str>,
-) -> Result<()> {
- if let Some(parent) = jsonl_path.parent() {
- fs::create_dir_all(parent)
- .with_context(|| format!("create transcript dir {}", parent.display()))?;
- }
-
- let file_exists = jsonl_path.exists();
-
- // First write for this file: create it with meta + all message lines.
- if !file_exists {
- let mut buf = String::new();
- buf.push_str(&meta_line_json(meta)?);
- buf.push('\n');
- serialise_message_lines(messages, turn_usage, request_id, &mut buf)?;
- fs::write(jsonl_path, buf.as_bytes())
- .with_context(|| format!("create transcript {}", jsonl_path.display()))?;
- log::debug!(
- "[transcript] created append-only transcript with {} message(s) at {}",
- messages.len(),
- jsonl_path.display()
- );
- render_md_companion(jsonl_path, messages, meta, turn_usage);
- return Ok(());
- }
-
- // Subsequent writes: diff against the previously-persisted logical set.
- let common = common_prefix_len(prev_persisted, messages);
- let mut buf = String::new();
-
- if common == prev_persisted.len() {
- // Pure extension — append only the new tail.
- let tail = &messages[common..];
- log::debug!(
- "[transcript] append: extending on-disk set (prev={}, new={}, appending {} tail line(s)) {}",
- prev_persisted.len(),
- messages.len(),
- tail.len(),
- jsonl_path.display()
- );
- serialise_message_lines(tail, turn_usage, request_id, &mut buf)?;
- } else {
- // Reduction / rewrite — the on-disk set is no longer a prefix. Append a
- // compaction record carrying the full reduced context so the
- // model-context reader can replay it, without destroying earlier lines.
- log::debug!(
- "[transcript] append: context reduced (prev={}, new={}, common_prefix={}) — writing compaction record {}",
- prev_persisted.len(),
- messages.len(),
- common,
- jsonl_path.display()
- );
- let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
- let replacement: Vec<MessageLine> = messages
- .iter()
- .enumerate()
- .map(|(i, msg)| {
- let tu = if Some(i) == last_assistant_idx {
- turn_usage
- .cloned()
- .or_else(|| turn_usage_from_metadata(msg))
- } else {
- turn_usage_from_metadata(msg)
- };
- build_message_line(msg, tu.as_ref(), request_id, false)
- })
- .collect();
- let compaction = CompactionLine {
- kind: COMPACTION_KIND.to_string(),
- replacement,
- ts: Some(chrono::Utc::now().to_rfc3339()),
- request_id: request_id.map(str::to_string),
- _extra: HashMap::new(),
- };
- let line = serde_json::to_string(&compaction).context("serialise compaction record")?;
- buf.push_str(&line);
- buf.push('\n');
- }
-
- // Refresh cumulative meta by appending a new `_meta` line (readers take the
- // last one). Keeps append-only + O(1)-per-turn (no full-file rewrite).
- buf.push_str(&meta_line_json(meta)?);
- buf.push('\n');
-
- append_bytes(jsonl_path, buf.as_bytes())?;
- render_md_companion(jsonl_path, messages, meta, turn_usage);
- Ok(())
-}
-
-/// Append a partial assistant answer, flagged `interrupted: true`, captured
-/// when a streaming turn was cancelled/interrupted before completion.
-///
-/// **Display only**: the model-context reader skips interrupted lines, so a
-/// resumed context never carries a truncated answer. Does not affect the
-/// caller's tracked `prev_persisted` (nothing about the logical model context
-/// changed). No-op when `partial_content` is empty.
-pub fn append_interrupted_partial(
- jsonl_path: &Path,
- partial_content: &str,
- request_id: Option<&str>,
- iteration: Option<u32>,
- reasoning_content: Option<&str>,
-) -> Result<()> {
- if partial_content.is_empty() {
- return Ok(());
- }
- if let Some(parent) = jsonl_path.parent() {
- fs::create_dir_all(parent)
- .with_context(|| format!("create transcript dir {}", parent.display()))?;
- }
- let mut line = build_message_line(
- &ChatMessage::assistant(partial_content),
- None,
- request_id,
- true,
- );
- line.iteration = iteration;
- line.reasoning_content = reasoning_content
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- line.ts = Some(chrono::Utc::now().to_rfc3339());
- let mut buf = serde_json::to_string(&line).context("serialise interrupted partial line")?;
- buf.push('\n');
- append_bytes(jsonl_path, buf.as_bytes())?;
- log::debug!(
- "[transcript] appended interrupted partial ({} chars, request_id={:?}) to {}",
- partial_content.len(),
- request_id,
- jsonl_path.display()
- );
- Ok(())
-}
-
-/// Longest common prefix length between two message slices, comparing on the
-/// stable, serialised fields (`role`, `content`, `id`). `ChatMessage` does not
-/// derive `PartialEq`, and `extra_metadata` is intentionally excluded because
-/// it is enriched (turn usage) between the in-memory history and the persisted
-/// line, which must not count as a divergence.
-fn common_prefix_len(a: &[ChatMessage], b: &[ChatMessage]) -> usize {
- a.iter()
- .zip(b.iter())
- .take_while(|(x, y)| x.role == y.role && x.content == y.content && x.id == y.id)
- .count()
-}
-
-/// Append raw bytes to a file, opening in append mode (O(1), no read-back).
-fn append_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
- use std::io::Write;
- let mut file = fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(path)
- .with_context(|| format!("open transcript for append {}", path.display()))?;
- file.write_all(bytes)
- .with_context(|| format!("append transcript {}", path.display()))?;
- Ok(())
-}
-
-/// Re-render the derived `.md` companion from the current (reduced) message set.
-///
-/// Best-effort — the JSONL is the source of truth; a companion write failure is
-/// logged and swallowed so it can never take down state persistence.
-fn render_md_companion(
- jsonl_path: &Path,
- messages: &[ChatMessage],
- meta: &TranscriptMeta,
- last_assistant_turn_usage: Option<&TurnUsage>,
-) {
- let last_assistant_idx = messages.iter().rposition(|m| m.role == "assistant");
- let mut owned_usage: Vec<(usize, TurnUsage)> = Vec::new();
- for (idx, msg) in messages.iter().enumerate() {
- let usage = if Some(idx) == last_assistant_idx {
- last_assistant_turn_usage
- .cloned()
- .or_else(|| turn_usage_from_metadata(msg))
- } else {
- turn_usage_from_metadata(msg)
- };
- if let Some(usage) = usage {
- owned_usage.push((idx, usage));
- }
- }
- let per_msg_usage: HashMap<usize, &TurnUsage> = owned_usage
- .iter()
- .map(|(idx, usage)| (*idx, usage))
- .collect();
-
- let md_path = md_companion_path(jsonl_path);
- if let Some(parent) = md_path.parent() {
- if let Err(err) = fs::create_dir_all(parent) {
- log::warn!(
- "[transcript] failed to create md companion dir {}: {err}",
- parent.display()
- );
- return;
- }
- }
- let md = render_markdown(messages, meta, &per_msg_usage);
- if let Err(err) = fs::write(&md_path, md.as_bytes()) {
- log::warn!(
- "[transcript] failed to write markdown companion {}: {err}",
- md_path.display()
- );
- return;
- }
- log::debug!(
- "[transcript] wrote markdown companion to {}",
- md_path.display()
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_forward_compat_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_forward_compat_tests.rs
deleted file mode 100644
index 96f80b02a6..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_forward_compat_tests.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-use super::*;
-
-/// A file carrying an unknown record kind (as a future core might write) is
-/// skipped by the reader rather than crashing it.
-#[test]
-fn unknown_record_kind_is_skipped_not_fatal() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("unknown_kind.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
- h.turn(
- &[ChatMessage::system("sys"), ChatMessage::user("q1")],
- &meta,
- None,
- None,
- );
- // Simulate a future kind by appending a foreign record line.
- {
- use std::io::Write;
- let mut f = std::fs::OpenOptions::new()
- .append(true)
- .open(&path)
- .unwrap();
- writeln!(f, "{{\"kind\":\"future_thing\",\"payload\":42}}").unwrap();
- }
- // Append a normal turn after the unknown line to prove reading continues.
- let mut msgs = vec![ChatMessage::system("sys"), ChatMessage::user("q1")];
- msgs.push(ChatMessage::assistant("a1"));
- h.prev = vec![ChatMessage::system("sys"), ChatMessage::user("q1")];
- h.turn(&msgs, &meta, None, None);
-
- let model = read_transcript(&path).unwrap();
- // The unknown record is skipped; the real messages survive.
- assert!(model.messages.iter().any(|m| m.content == "a1"));
- assert!(!model
- .messages
- .iter()
- .any(|m| m.content.contains("future_thing")));
-}
-
-/// The `_meta` version field is stamped by the append writer and absent (0) on
-/// legacy files — but both remain readable.
-#[test]
-fn meta_version_stamped_and_optional() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("version.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
- h.turn(&[ChatMessage::user("q")], &meta, None, None);
- let raw = std::fs::read_to_string(&path).unwrap();
- assert!(
- raw.lines().next().unwrap().contains("\"version\":1"),
- "append writer must stamp the schema version on the meta header"
- );
-}
-
-/// Root transcripts must come back in the order they were written, not in
-/// filename order.
-///
-/// Modern stems are `{unix_ts}_{agent}` and sort identically either way, but a
-/// legacy `{agent}_{index}` root encodes no time at all — and because digits
-/// sort before letters, every legacy root sorted *after* every modern one no
-/// matter when it was written. `project_from_files` concatenates these in
-/// order, so a mis-ordered list reorders the rendered view and can attach a
-/// sub-agent trail to the wrong turn.
-#[test]
-fn root_transcripts_are_ordered_by_creation_not_file_name() {
- let dir = TempDir::new().unwrap();
- let raw = dir.path().join("session_raw");
- std::fs::create_dir_all(&raw).unwrap();
-
- let write_root = |stem: &str, created: &str| {
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-order".into());
- meta.created = created.into();
- write_transcript(
- &raw.join(format!("{stem}.jsonl")),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
- };
-
- // The legacy root is the OLDEST, but `orchestrator_1` sorts after any
- // digit-led stem, so a filename sort puts it last.
- write_root("orchestrator_1", "2026-04-10T09:00:00Z");
- write_root("1776211200_orchestrator", "2026-04-11T09:00:00Z");
- write_root("1776297600_orchestrator", "2026-04-12T09:00:00Z");
-
- let ordered: Vec<String> = find_root_transcripts_for_thread(dir.path(), "thread-order")
- .into_iter()
- .map(|path| {
- path.file_stem()
- .and_then(|stem| stem.to_str())
- .unwrap_or_default()
- .to_string()
- })
- .collect();
-
- assert_eq!(
- ordered,
- vec![
- "orchestrator_1".to_string(),
- "1776211200_orchestrator".to_string(),
- "1776297600_orchestrator".to_string(),
- ],
- "roots must be chronological; a filename sort would put the legacy root last"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_history.rs b/crates/openhuman-core/src/agent/harness/session/transcript_history.rs
deleted file mode 100644
index 2b5cd0fd05..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_history.rs
+++ /dev/null
@@ -1,633 +0,0 @@
-//! [`ChatHistory`] over OpenHuman's durable `session_raw` transcript.
-//!
-//! This is the seam chosen in `docs/specs/2026-07-28-agent-session-transcript-to-tinyagents-design.md`
-//! §4 Option A: the harness talks to the crate's
-//! [`tinyagents_harness::memory::ChatHistory`] trait, while OpenHuman keeps
-//! ownership of the on-disk format. Nothing about `session_raw` moves, so
-//! there is no on-disk change and no migration risk — the previous parallel
-//! abstraction is what goes away.
-//!
-//! [`SessionTranscriptHistory`] is a thin handle over the free functions in
-//! [`super::transcript`]. It holds no state beyond the transcript's identity,
-//! so it is cheap to construct per turn and safe to share.
-//!
-//! # Why the trait's `thread_id` is not used for path resolution
-//!
-//! `ChatHistory` is keyed by `thread_id`, but a `session_raw` transcript is
-//! keyed by its **stem** (`{unix_ts}_{agent_id}`, or `{parent_chain}__…` for a
-//! sub-agent). These are deliberately different: several transcripts can share
-//! one `_meta.thread_id` — every sub-agent spawned within a thread does — so
-//! resolving a path from `thread_id` would be ambiguous and could interleave
-//! two agents' histories into one file.
-//!
-//! The handle is therefore bound to one transcript at construction, and the
-//! `thread_id` argument is accepted for trait conformance only. Callers that
-//! genuinely want thread-level lookup use
-//! [`super::transcript::find_root_transcript_for_thread`].
-//!
-//! # Append-only, including `clear`
-//!
-//! Every mutation routes through
-//! [`append_transcript_turn`][super::transcript::append_transcript_turn], which
-//! never rewrites existing lines. A reduction in the logical message set
-//! becomes a `{"kind":"compaction","replacement":[…]}` record rather than a
-//! file rewrite. That includes [`SessionTranscriptHistory::clear`] — see its
-//! doc comment for the semantics that were chosen and why.
-//!
-//! # Why the metadata-bearing write does not cross the crate trait
-//!
-//! S4 of the design doc is worded as "the turn path takes `Arc<dyn
-//! ChatHistory>`", but that wording conflicts with S4's own exit criterion
-//! ("`threads/transcript_view` projection output unchanged"). The crate trait
-//! (`vendor/tinyagents/src/harness/memory/types.rs`) has exactly four methods,
-//! and every one of them carries only a `thread_id: &str` plus `Message` /
-//! `Vec<Message>`. Three things the turn path persists therefore have **no
-//! channel**:
-//!
-//! - **`request_id`** — stamped on every line of a turn. It drives
-//! `DisplayItem::TurnBoundary` (`threads/transcript_view/project.rs`,
-//! `maybe_emit_turn_boundary`) and the `(request_id, ts)` root-turn segments
-//! that anchor every `DisplayItem::Subagent`. Lose it and the transcript view
-//! silently stops showing turn structure.
-//! - **`turn_usage`** — attributed to the last assistant row. It carries
-//! `model`, `iteration`, `ts`, `reasoning_content` and the native
-//! `tool_calls`. The projection reads **every** `DisplayItem::ToolCall` off
-//! `turn_usage.tool_calls`, so losing it does not degrade the tool rows, it
-//! deletes them — after which each following `role:"tool"` line falls through
-//! to the orphan branch. `Reasoning` items vanish with it, and
-//! `AssistantMessage.{model,iteration}` / `interim` collapse.
-//! - **`TranscriptMeta`'s cumulative fields** — `turn_count` and the four
-//! token/cost rollups that `read_thread_usage_summary` (`threads/ops.rs`)
-//! reports. The turn path computes these fresh each turn;
-//! [`SessionTranscriptHistory::meta_for_write`] deliberately re-reads the
-//! file's existing `_meta` instead, which is right for the generic trait path
-//! but would freeze the rollups at the previous turn's values if the turn
-//! path used it.
-//!
-//! So the turn path goes through [`SessionHistory::append_turn`] — an
-//! OpenHuman-side supertrait of `ChatHistory` whose one method forwards the
-//! same six arguments `append_transcript_turn` already takes. The indirection
-//! is real (`Arc<dyn SessionHistory>`), the on-disk bytes are unchanged by
-//! construction, and `ChatHistory` stays in the bound so the handle is still a
-//! genuine crate-side history for any future consumer.
-//!
-//! ## Two alternatives, rejected — recorded so they are not re-litigated
-//!
-//! 1. **Per-message `ChatHistory::append`.** One `append_transcript_turn` per
-//! message means one `_meta` line and one full-file re-read per message:
-//! an on-disk change *and* O(n²) I/O on a file that grows without bound.
-//! 2. **Widening `ChatHistory` upstream.** It does not close the gap either.
-//! The crate's `Usage` has no `cost_usd` / `context_window`;
-//! `TranscriptMeta` is a cumulative *file header*, not turn provenance; and
-//! the per-message tool-failure `extra_metadata` that
-//! `message_to_chat_message` drops is untouchable by any turn-level record.
-//! You would pay a tinyagents release and still need a
-//! `serde_json::Value` escape hatch, for a trait that has no consumer inside
-//! the vendored crate outside `harness/memory/`.
-//!
-//! # Why the READ half is [`SessionTranscriptRead`], not `ChatHistory::messages`
-//!
-//! Same shape of argument as the write, and equally settled — measured with a
-//! round-trip probe, not assumed. `ChatHistory::messages` returns
-//! `Vec<Message>`, and the turn path needs `Vec<ChatMessage>` back, so a
-//! trait-mediated read has to pass through
-//! [`message_to_chat_message`][crate::agent::message_convert::message_to_chat_message].
-//! That converter maps `Message::Assistant` to `ChatMessage::assistant(msg.text())`
-//! and **drops `a.tool_calls` entirely**. A persisted native tool round is
-//! deliberately stored as the `{content, tool_calls}` / `{tool_call_id, content}`
-//! envelope so the next turn re-parses it; flattening it orphans every following
-//! `role:"tool"` row and produces the provider `400 An assistant message with
-//! 'tool_calls' must be followed by tool messages`. It also blinds the
-//! TAURI-RUST-7 trailing strip in
-//! [`bound_cached_transcript_messages`][super::types::Agent::bound_cached_transcript_messages],
-//! which sniffs that envelope out of `ChatMessage.content`. Two lesser losses
-//! ride along and are inert on this path: the `openhuman_turn_usage`
-//! `extra_metadata` (re-attached by `read_transcript`, never re-serialised from
-//! the cached prefix) and `AssistantMessage.id` (no reader anywhere).
-//!
-//! So the read goes through [`SessionTranscriptRead::read_session`], which
-//! returns the very [`SessionTranscript`] the free function returns, produced by
-//! the same [`read_transcript`] call. Losslessness is **structural**: nothing
-//! crosses `Message`, so `tool_calls`, `tool_call_id`, `failure`,
-//! `reasoning_content` and the `_meta` header all survive by construction, and
-//! compaction replay + `interrupted: true` partial skipping stay exactly where
-//! the format owner performs them.
-//!
-//! # Why discovery is a separate object ([`SessionHistoryLocator`])
-//!
-//! A handle is bound to one *file*. The turn path's two reads are *lookups*:
-//! `(workspace, agent name)` → newest match, and
-//! `_meta.thread_id` → newest **root** transcript. `ChatHistory` has no
-//! discovery concept at all (it is `thread_id`-keyed and returns messages, never
-//! a location), so leaving discovery as free functions would keep the read half
-//! hitting the filesystem no matter what handle was injected — i.e. the
-//! `Arc<dyn …>` would stay decorative. The locator is therefore the single
-//! injected object covering *both* reads and the session's own write handle.
-//!
-//! # Deliberately NOT done here — recorded with reasons
-//!
-//! - **The `impl ChatHistory` block below still has no production caller.**
-//! Reads go through `read_session`, writes through `append_turn`. It is kept,
-//! not deleted, because it is the crate-side seam Option A exists to
-//! establish, and because it supplies the `Send + Sync + 'static` bounds the
-//! shared `Arc<dyn SessionHistory>` needs. The trigger that would delete it is
-//! an explicit decision to drop `ChatHistory` from the [`SessionHistory`]
-//! bound; that frees this file's `read`/`persisted`/`meta_for_write`/
-//! `write_logical_set`/`impl ChatHistory` (~150 lines) plus most of the test
-//! module (~570 lines together). Decide it, don't rediscover it.
-//! - **The spec's "Removes: ~400 LOC of parallel abstraction" is not delivered
-//! and cannot be.** See the design doc's "Where '~400 LOC' came from"
-//! subsection: the figure is §2.1's residual after Option B, i.e. exactly
-//! `migration.rs` (373 LOC), which §5 S1 and the deletion ledger both keep
-//! host-owned. Option A's measured ledger is ≈ −15 / +90 LOC here.
-//! - **The #4249 JSONL↔store mirror is the one genuine parallel session
-//! persistence** (`session_import/live.rs`, `maybe_shadow_read_session_store`
-//! / `maybe_dual_write_session_store`, the `StoreRegistry` registration, two
-//! `AgentConfig` flags, one config migration — ~565 prod LOC). It is not
-//! touched here: it is gated on #4249's own Phase-2 parity soak and its
-//! terminus (reads served from the store) points the opposite way from this
-//! branch's non-negotiable zero-on-disk-change constraint.
-
-use std::path::{Path, PathBuf};
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use tinyagents_harness::memory::ChatHistory;
-use tinyagents_harness::{Result as TaResult, TinyAgentsError};
-use tinyinference_llm::message::Message;
-
-use crate::agent::message_convert::{history_to_messages, message_to_chat_message};
-use crate::agent::messages::ChatMessage;
-
-use super::transcript::{
- append_transcript_turn, find_latest_transcript, find_root_transcript_for_thread,
- find_root_transcript_for_thread_scoped, read_transcript, resolve_keyed_transcript_path,
- SessionTranscript, TranscriptMeta, TurnUsage,
-};
-
-/// One turn's worth of transcript write, borrowed.
-///
-/// The fields mirror [`append_transcript_turn`]'s argument list one-for-one and
-/// in order, so [`SessionHistory::append_turn`]'s forwarding is visually
-/// checkable against the format's own signature. Nothing is transformed on the
-/// way through; that is the entire correctness claim of this seam and
-/// `append_turn_is_byte_identical_to_the_free_function` in the tests pins it.
-///
-/// `prev` is a field rather than handle state on purpose: the turn path tracks
-/// the previously-persisted logical set in memory on `Agent`
-/// (`persisted_transcript_messages`) precisely so it never has to re-read a
-/// growing file, and a disk re-read is not a faithful substitute — see
-/// [`SessionTranscriptHistory::write_logical_set`].
-pub struct TranscriptTurn<'a> {
- /// Logical message set already persisted, for the extension-vs-compaction diff.
- pub prev: &'a [ChatMessage],
- /// Logical message set after this turn.
- pub next: &'a [ChatMessage],
- /// `_meta` header to append after this turn's lines.
- pub meta: &'a TranscriptMeta,
- /// Usage + provenance attributed to the turn's last assistant row.
- pub turn_usage: Option<&'a TurnUsage>,
- /// Web-chat request id, stamped on every line of the turn.
- pub request_id: Option<&'a str>,
-}
-
-/// The seam the live turn path holds as `Arc<dyn SessionHistory>`.
-///
-/// `ChatHistory` is a supertrait rather than a sibling for two reasons: it
-/// supplies the `Send + Sync + 'static` bounds the shared handle needs, and it
-/// keeps the crate-side surface (S2/S3) live rather than orphaned. See this
-/// module's header for why the turn write cannot simply *be* a `ChatHistory`
-/// call.
-///
-/// `append_turn` is deliberately **sync**: `persist_session_transcript` is a
-/// sync `&mut self` method and the whole write chain under it is sync, so an
-/// async method here would ripple `.await` through the turn loop for no gain.
-pub(crate) trait SessionHistory: ChatHistory + SessionTranscriptRead {
- /// Appends one turn, forwarding every argument to the format owner.
- fn append_turn(&self, turn: TranscriptTurn<'_>) -> anyhow::Result<()>;
-}
-
-/// The read half of a bound transcript — the seam the turn path's two resume
-/// reads hold.
-///
-/// Split out of [`SessionHistory`] rather than added as one more method on it,
-/// for a reason that is not stylistic: a *discovered* transcript can still be a
-/// legacy `.md` file (see [`SessionTranscriptHistory::opened_at`]), and
-/// `append_transcript_turn` writes JSONL. Handing discovery results out as
-/// `Arc<dyn SessionTranscriptRead>` makes it impossible to `append_turn` into
-/// one by construction, instead of by convention.
-///
-/// Sync for the same reason [`SessionHistory::append_turn`] is: both callers are
-/// sync `&mut self` methods on `Agent`.
-pub(crate) trait SessionTranscriptRead: Send + Sync {
- /// The transcript file this handle is bound to.
- ///
- /// The turn path still needs the concrete path after the read:
- /// `maybe_shadow_read_session_store` takes `&Path`, and the dual-write
- /// mirror derives its record key from `file_stem()`.
- fn path(&self) -> &Path;
-
- /// The model-context replay of this transcript, `_meta` included, or
- /// `Ok(None)` when the file does not exist.
- ///
- /// Exactly [`read_transcript`], so compaction records have already replaced
- /// the accumulator and `interrupted: true` partials are already skipped —
- /// §3.1's "single most important constraint". Returning the whole
- /// [`SessionTranscript`] rather than messages alone is what lets the shadow
- /// read keep working through this seam.
- fn read_session(&self) -> anyhow::Result<Option<SessionTranscript>>;
-}
-
-/// Resolves transcripts by the two keys the turn path actually has, and binds
-/// this session's own write handle.
-///
-/// One injected object covers the whole turn path: both resume reads and the
-/// first-write bind. `Agent` holds it as `Option<Arc<dyn SessionHistoryLocator>>`
-/// and falls back to [`FileTranscriptLocator`] built from the *current*
-/// `workspace_dir` — lazily, never frozen at build time,
-/// because tests reassign `agent.workspace_dir` after `build()` and a
-/// build-time locator would silently keep pointing at the old directory.
-pub(crate) trait SessionHistoryLocator: Send + Sync {
- /// Newest transcript for `agent_name` in this session's raw subtree,
- /// including the legacy `session_raw/DDMMYYYY/` + `.md` fallback.
- fn latest_for_agent(&self, agent_name: &str) -> Option<Arc<dyn SessionTranscriptRead>>;
-
- /// Newest **root** transcript whose `_meta.thread_id` matches.
- ///
- /// Root-only on purpose: several transcripts share one thread id (every
- /// sub-agent spawned within it does), so a stem-keyed lookup would be
- /// ambiguous.
- fn root_for_thread(&self, thread_id: &str) -> Option<Arc<dyn SessionTranscriptRead>>;
-
- /// [`Self::root_for_thread`], additionally scoped to `agent_id` when
- /// given — see
- /// [`transcript::find_root_transcript_for_thread_scoped`](super::transcript::find_root_transcript_for_thread_scoped)
- /// for why. Defaults to the unscoped lookup so an implementor that never
- /// serves several distinct agents over the same `thread_id` (this test
- /// double, notably) does not have to know about agent scoping at all.
- fn root_for_thread_scoped(
- &self,
- thread_id: &str,
- agent_id: Option<&str>,
- ) -> Option<Arc<dyn SessionTranscriptRead>> {
- let _ = agent_id;
- self.root_for_thread(thread_id)
- }
-
- /// Binds (creating on first write) this session's own write handle for
- /// `stem`, with `seed` used only when no file exists yet.
- fn open_stem(
- &self,
- stem: &str,
- seed: TranscriptMeta,
- ) -> anyhow::Result<Arc<dyn SessionHistory>>;
-}
-
-/// The default [`SessionHistoryLocator`]: real files under
-/// `{workspace_dir}/session_raw`.
-///
-/// Thin by design — each method wraps exactly one `transcript::` free function
-/// and changes nothing about it, so swapping the turn path onto the locator is
-/// behaviour-preserving.
-pub(crate) struct FileTranscriptLocator {
- workspace_dir: PathBuf,
-}
-
-impl FileTranscriptLocator {
- pub(crate) fn new(workspace_dir: impl Into<PathBuf>) -> Self {
- Self {
- workspace_dir: workspace_dir.into(),
- }
- }
-}
-
-impl SessionHistoryLocator for FileTranscriptLocator {
- fn latest_for_agent(&self, agent_name: &str) -> Option<Arc<dyn SessionTranscriptRead>> {
- let path = find_latest_transcript(&self.workspace_dir, agent_name)?;
- log::debug!(
- "[transcript-history] locator latest_for_agent agent={agent_name} path={}",
- path.display()
- );
- Some(Arc::new(SessionTranscriptHistory::opened_at(
- path,
- seed_meta_for_discovered(agent_name),
- )))
- }
-
- fn root_for_thread(&self, thread_id: &str) -> Option<Arc<dyn SessionTranscriptRead>> {
- let path = find_root_transcript_for_thread(&self.workspace_dir, thread_id)?;
- log::debug!(
- "[transcript-history] locator root_for_thread thread={thread_id} path={}",
- path.display()
- );
- Some(Arc::new(SessionTranscriptHistory::opened_at(
- path,
- seed_meta_for_discovered(thread_id),
- )))
- }
-
- fn root_for_thread_scoped(
- &self,
- thread_id: &str,
- agent_id: Option<&str>,
- ) -> Option<Arc<dyn SessionTranscriptRead>> {
- // Same cross-dir, newest-wins scan as `root_for_thread`, additionally
- // filtered on `_meta.agent_id` so one runtime agent's resume cannot
- // pick up a different agent's transcript for a caller-reused
- // `thread_id` — see `find_root_transcript_for_thread_scoped`.
- let path =
- find_root_transcript_for_thread_scoped(&self.workspace_dir, thread_id, agent_id)?;
- log::debug!(
- "[transcript-history] locator root_for_thread_scoped thread={thread_id} \
- agent_id={agent_id:?} path={}",
- path.display()
- );
- Some(Arc::new(SessionTranscriptHistory::opened_at(
- path,
- seed_meta_for_discovered(thread_id),
- )))
- }
-
- fn open_stem(
- &self,
- stem: &str,
- seed: TranscriptMeta,
- ) -> anyhow::Result<Arc<dyn SessionHistory>> {
- Ok(Arc::new(SessionTranscriptHistory::new(
- &self.workspace_dir,
- stem,
- seed,
- )?))
- }
-}
-
-/// A placeholder `_meta` for a handle bound to an already-existing transcript.
-///
-/// `seed_meta` is consulted only when the file is **absent**, and a discovered
-/// path exists by definition, so this value is never written. It exists because
-/// [`SessionTranscriptHistory`] is one type serving both roles; giving read-only
-/// handles a `None` meta would mean an `Option` field every write path then has
-/// to unwrap for no benefit.
-fn seed_meta_for_discovered(agent_name: &str) -> TranscriptMeta {
- TranscriptMeta {
- agent_name: agent_name.to_string(),
- agent_id: None,
- agent_type: None,
- dispatcher: String::new(),
- provider: None,
- model: None,
- created: String::new(),
- updated: String::new(),
- turn_count: 0,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: None,
- task_id: None,
- }
-}
-
-/// A [`ChatHistory`] backed by one `session_raw/{stem}.jsonl` transcript.
-///
-/// Construct with [`SessionTranscriptHistory::new`] (workspace-rooted, i.e.
-/// `{workspace}/session_raw/`). The `seed_meta` is used only when the
-/// transcript file does not exist yet; for an existing file the authoritative
-/// cumulative `_meta` is read back from disk so turn counts and token rollups
-/// keep accumulating rather than resetting.
-pub struct SessionTranscriptHistory {
- /// Fully-resolved transcript file, fixed at construction.
- ///
- /// Resolved eagerly rather than derived per call from a `(workspace, stem)`
- /// pair: the old shape hardcoded `{workspace}/session_raw/`, which is the
- /// **wrong directory** for a canonical session and would have silently
- /// cross-written into the canonical session's transcripts the moment this
- /// handle was wired into the turn path.
- path: PathBuf,
- /// `_meta` used for the very first write, before a file exists.
- seed_meta: TranscriptMeta,
-}
-
-impl SessionTranscriptHistory {
- /// Binds a history handle to `{workspace_dir}/session_raw/{stem}.jsonl`.
- ///
- pub fn new(
- workspace_dir: impl AsRef<Path>,
- stem: &str,
- seed_meta: TranscriptMeta,
- ) -> anyhow::Result<Self> {
- let path = resolve_keyed_transcript_path(workspace_dir.as_ref(), stem)?;
- log::debug!(
- "[transcript-history] bound stem={stem} path={}",
- path.display()
- );
- Ok(Self { path, seed_meta })
- }
-
- /// Binds a handle to an **already-discovered** transcript file, verbatim.
- ///
- /// Deliberately does **not** go through `resolve_keyed_transcript_path*`,
- /// which the two stem constructors above use. That helper `create_dir_all`s
- /// its parent and forces a `.jsonl` extension — both wrong for a discovered
- /// path: `find_latest_transcript` can still return a legacy `.md`
- /// file (`read_transcript` routes by extension), and re-resolving would
- /// mangle it into a sibling `.jsonl` that does not exist while creating
- /// stray directories on a pure read.
- ///
- /// Hand the result out as `Arc<dyn SessionTranscriptRead>`, not
- /// `Arc<dyn SessionHistory>` — see [`SessionTranscriptRead`]'s doc.
- pub fn opened_at(path: PathBuf, seed_meta: TranscriptMeta) -> Self {
- log::debug!(
- "[transcript-history] opened discovered path={}",
- path.display()
- );
- Self { path, seed_meta }
- }
-
- /// This handle's transcript file.
- pub fn path(&self) -> &Path {
- &self.path
- }
-
- /// Reads the current transcript, or `None` when no file exists yet.
- ///
- /// A missing transcript is the normal first-turn state, not an error.
- fn read(&self) -> TaResult<Option<SessionTranscript>> {
- if !self.path.exists() {
- return Ok(None);
- }
- read_transcript(&self.path).map(Some).map_err(memory_err)
- }
-
- /// The logical (model-context) message set currently on disk.
- ///
- /// Routes through [`read_transcript`], so compaction records have already
- /// replaced the accumulator and `interrupted: true` partials are skipped.
- fn persisted(&self) -> TaResult<Vec<ChatMessage>> {
- Ok(self.read()?.map(|t| t.messages).unwrap_or_default())
- }
-
- /// The `_meta` to write: the file's own cumulative meta when it exists,
- /// otherwise this handle's seed.
- ///
- /// Correct for the generic `ChatHistory` path, which has no channel for a
- /// caller-computed meta. The **turn path must never route through here** —
- /// it computes `turn_count` and the four token/cost rollups fresh each turn,
- /// and re-reading the file's `_meta` would freeze them at the previous
- /// turn's values, silently breaking `read_thread_usage_summary`.
- fn meta_for_write(&self) -> TaResult<TranscriptMeta> {
- Ok(self
- .read()?
- .map(|t| t.meta)
- .unwrap_or_else(|| self.seed_meta.clone()))
- }
-
- /// Writes `next` as the new logical set, diffing against what is persisted.
- ///
- /// Routes through [`SessionHistory::append_turn`] so every write in this
- /// module — trait-driven and turn-path alike — funnels through one call to
- /// [`append_transcript_turn`], and the extension-vs-compaction decision
- /// stays with the format owner rather than drifting here.
- ///
- /// The `self.persisted()` disk re-read is what the generic trait path has
- /// to do, and is deliberately **not** what the turn path does.
- /// [`read_transcript`] reconstructs `ChatMessage`s from line records: the
- /// `failure` / `failure_detail` fields have been lifted out of
- /// `extra_metadata` and turn-usage fields hoisted to top-level line fields.
- /// Feeding that back in as `prev` would make `common_prefix_len` mismatch
- /// at the first such message, so the writer would emit a full compaction
- /// record — re-appending the entire message set — on every single turn.
- fn write_logical_set(&self, next: &[ChatMessage]) -> TaResult<()> {
- let prev = self.persisted()?;
- let meta = self.meta_for_write()?;
- self.append_turn(TranscriptTurn {
- prev: &prev,
- next,
- meta: &meta,
- turn_usage: None,
- request_id: None,
- })
- .map_err(memory_err)
- }
-}
-
-impl SessionTranscriptRead for SessionTranscriptHistory {
- fn path(&self) -> &Path {
- &self.path
- }
-
- /// Same call the free-function readers make, on the same path, with the
- /// same return type — so there is nothing left for the round trip to lose.
- fn read_session(&self) -> anyhow::Result<Option<SessionTranscript>> {
- if !self.path.exists() {
- log::debug!(
- "[transcript-history] read_session absent path={}",
- self.path.display()
- );
- return Ok(None);
- }
- let session = read_transcript(&self.path)?;
- log::debug!(
- "[transcript-history] read_session messages={} path={}",
- session.messages.len(),
- self.path.display()
- );
- Ok(Some(session))
- }
-}
-
-impl SessionHistory for SessionTranscriptHistory {
- /// Pure forwarder: every argument reaches [`append_transcript_turn`]
- /// untouched, so the bytes this writes are identical to what the free
- /// function would have written at the call site.
- fn append_turn(&self, turn: TranscriptTurn<'_>) -> anyhow::Result<()> {
- log::debug!(
- "[transcript-history] append_turn prev={} next={} usage={} request_id={:?} path={}",
- turn.prev.len(),
- turn.next.len(),
- turn.turn_usage.is_some(),
- turn.request_id,
- self.path.display()
- );
- append_transcript_turn(
- &self.path,
- turn.prev,
- turn.next,
- turn.meta,
- turn.turn_usage,
- turn.request_id,
- )
- }
-}
-
-#[async_trait]
-impl ChatHistory for SessionTranscriptHistory {
- /// Returns the **model-context** replay of this transcript.
- ///
- /// This is deliberately the same path the resume flow uses, not the raw
- /// line set: compaction records replace the accumulator and interrupted
- /// partials are dropped, so a resumed context never carries a truncated
- /// answer. Use
- /// [`read_transcript_display`][super::transcript::read_transcript_display]
- /// when rendering history for a human instead.
- ///
- /// An absent transcript yields an empty `Vec`, per the trait contract.
- async fn messages(&self, _thread_id: &str) -> TaResult<Vec<Message>> {
- Ok(history_to_messages(&self.persisted()?))
- }
-
- /// Appends one message to the end of the transcript.
- ///
- /// Extending the persisted set writes only the new tail line.
- async fn append(&self, _thread_id: &str, message: Message) -> TaResult<()> {
- let mut next = self.persisted()?;
- next.push(message_to_chat_message(&message));
- self.write_logical_set(&next)
- }
-
- /// Replaces the logical message set with `messages`.
- ///
- /// This maps onto the compaction-record path, **not** a file rewrite: when
- /// `messages` is no longer an extension of what is on disk,
- /// [`append_transcript_turn`] appends a single
- /// `{"kind":"compaction","replacement":[…]}` record carrying the full
- /// reduced set and leaves every earlier line in place. The trait's default
- /// implementation (clear-then-append) would destroy that history, which is
- /// why this override exists.
- async fn replace(&self, _thread_id: &str, messages: Vec<Message>) -> TaResult<()> {
- let next: Vec<ChatMessage> = messages.iter().map(message_to_chat_message).collect();
- self.write_logical_set(&next)
- }
-
- /// Empties the **model context** while preserving the transcript on disk.
- ///
- /// Semantics chosen (S3 requires this be explicit): `clear` appends a
- /// compaction record with an empty `replacement`. Afterwards
- /// [`messages`][Self::messages] returns empty, but every prior line — and
- /// so the display read, usage rollups, and audit trail — survives.
- ///
- /// The two rejected alternatives, recorded so this is not re-litigated:
- /// truncating the file breaks the append-only invariant that the whole
- /// format rests on, and starting a fresh stem would silently orphan the
- /// session's history from its thread. A no-op on an absent transcript, per
- /// the trait contract.
- async fn clear(&self, _thread_id: &str) -> TaResult<()> {
- if !self.path.exists() {
- return Ok(());
- }
- self.write_logical_set(&[])
- }
-}
-
-/// Maps a transcript I/O failure into the crate's error type.
-///
-/// `ChatHistory` is a `harness::memory` surface, so its failures classify as
-/// [`TinyAgentsError::Memory`]. The `anyhow` context chain is flattened into
-/// the message via `{:#}` so the underlying cause is not lost.
-fn memory_err(err: anyhow::Error) -> TinyAgentsError {
- TinyAgentsError::Memory(format!("session transcript: {err:#}"))
-}
-
-#[cfg(test)]
-#[path = "transcript_history_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs
deleted file mode 100644
index ea0992c637..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs
+++ /dev/null
@@ -1,641 +0,0 @@
-//! Tests for the [`ChatHistory`] seam over the durable transcript.
-//!
-//! These pin the three properties S3 of the design doc calls out as hard
-//! requirements, because each one is a place where a plausible-looking
-//! implementation would silently corrupt a user's transcript:
-//!
-//! 1. `messages()` reads the **model-context** replay, not the raw line set.
-//! 2. `replace()` compacts rather than rewriting, so history survives.
-//! 3. `clear()` empties the context without destroying the file.
-
-use tempfile::TempDir;
-
-use super::*;
-use crate::agent::harness::session::transcript::read_transcript_display;
-
-/// Stem every test writes under; the file lands at
-/// `{workspace}/session_raw/{STEM}.jsonl`.
-const STEM: &str = "1760000000_tester";
-
-fn meta() -> TranscriptMeta {
- TranscriptMeta {
- agent_name: "tester".into(),
- agent_id: Some("tester".into()),
- agent_type: Some("root".into()),
- dispatcher: "native".into(),
- provider: None,
- model: None,
- created: "2026-08-07T10:00:00Z".into(),
- updated: "2026-08-07T10:00:00Z".into(),
- turn_count: 0,
- input_tokens: 0,
- output_tokens: 0,
- cached_input_tokens: 0,
- charged_amount_usd: 0.0,
- thread_id: Some("thread-1".into()),
- task_id: None,
- }
-}
-
-fn history(dir: &TempDir) -> SessionTranscriptHistory {
- SessionTranscriptHistory::new(dir.path(), STEM, meta()).unwrap()
-}
-
-fn user(text: &str) -> Message {
- Message::User(tinyinference_llm::message::UserMessage {
- content: vec![tinyinference_llm::message::ContentBlock::Text(
- text.to_string(),
- )],
- })
-}
-
-/// Visible text of each message, for order-sensitive assertions.
-fn texts(messages: &[Message]) -> Vec<String> {
- messages.iter().map(Message::text).collect()
-}
-
-#[tokio::test]
-async fn messages_on_absent_transcript_is_empty_not_an_error() {
- let dir = TempDir::new().unwrap();
- assert!(history(&dir).messages("thread-1").await.unwrap().is_empty());
-}
-
-#[tokio::test]
-async fn append_extends_and_reads_back_in_order() {
- let dir = TempDir::new().unwrap();
- let h = history(&dir);
-
- h.append("thread-1", user("one")).await.unwrap();
- h.append("thread-1", user("two")).await.unwrap();
-
- let got = h.messages("thread-1").await.unwrap();
- assert_eq!(texts(&got), vec!["one", "two"]);
-}
-
-/// S3 requirement 1: `messages()` must be the model-context replay.
-///
-/// After a reduction, the raw file still holds the pre-compaction lines. A
-/// reader that returned the raw line set would hand the model a context that
-/// includes text the compaction was meant to drop.
-#[tokio::test]
-async fn messages_replays_compaction_rather_than_returning_raw_lines() {
- let dir = TempDir::new().unwrap();
- let h = history(&dir);
-
- h.append("thread-1", user("first")).await.unwrap();
- h.append("thread-1", user("second")).await.unwrap();
- h.append("thread-1", user("third")).await.unwrap();
-
- // Reduce to a set that is not a prefix extension → compaction record.
- h.replace("thread-1", vec![user("summary")]).await.unwrap();
-
- // The model-context read sees only the replacement.
- assert_eq!(
- texts(&h.messages("thread-1").await.unwrap()),
- vec!["summary"]
- );
-
- // ...while the file itself still carries the superseded lines, proving the
- // reduction was a compaction record and not a rewrite.
- let path = h.path();
- let display = read_transcript_display(path).unwrap();
- let rendered = format!("{display:?}");
- assert!(
- rendered.contains("first") && rendered.contains("second"),
- "pre-compaction lines must survive on disk; display read was: {rendered}"
- );
-
- // And the seam agrees with the format's own model-context reader.
- assert_eq!(
- texts(&h.messages("thread-1").await.unwrap()),
- read_transcript(path)
- .unwrap()
- .messages
- .iter()
- .map(|m| m.content.clone())
- .collect::<Vec<_>>()
- );
-}
-
-/// S3 requirement 2: `replace()` must not rewrite the file.
-///
-/// The trait's default `replace` is clear-then-append; if that default were
-/// ever inherited here it would destroy the append-only history. This asserts
-/// the file only ever grows.
-#[tokio::test]
-async fn replace_appends_a_compaction_record_and_never_shrinks_the_file() {
- let dir = TempDir::new().unwrap();
- let h = history(&dir);
-
- h.append("thread-1", user("alpha")).await.unwrap();
- h.append("thread-1", user("beta")).await.unwrap();
-
- let path = h.path();
- let before = std::fs::read_to_string(path).unwrap();
-
- h.replace("thread-1", vec![user("condensed")])
- .await
- .unwrap();
-
- let after = std::fs::read_to_string(path).unwrap();
- assert!(
- after.starts_with(&before),
- "replace must append; earlier bytes were modified"
- );
- assert!(
- after.contains("\"kind\":\"compaction\""),
- "replace must write a compaction record, got: {after}"
- );
-}
-
-/// S3 requirement 3: `clear()` semantics are explicit and non-destructive.
-#[tokio::test]
-async fn clear_empties_the_context_but_preserves_the_file() {
- let dir = TempDir::new().unwrap();
- let h = history(&dir);
-
- h.append("thread-1", user("kept on disk")).await.unwrap();
- let path = h.path();
- let before = std::fs::read_to_string(path).unwrap();
-
- h.clear("thread-1").await.unwrap();
-
- assert!(h.messages("thread-1").await.unwrap().is_empty());
- assert!(path.exists(), "clear must not delete the transcript");
-
- let after = std::fs::read_to_string(path).unwrap();
- assert!(
- after.starts_with(&before),
- "clear must append, not truncate"
- );
- assert!(
- after.contains("kept on disk"),
- "clear must preserve prior lines for the display read"
- );
-}
-
-#[tokio::test]
-async fn clear_on_absent_transcript_is_a_noop_not_an_error() {
- let dir = TempDir::new().unwrap();
- history(&dir).clear("thread-1").await.unwrap();
-}
-
-/// Appending after a compaction continues from the replacement set, not from
-/// the superseded lines — otherwise dropped context would resurrect itself.
-#[tokio::test]
-async fn append_after_compaction_extends_the_replacement_set() {
- let dir = TempDir::new().unwrap();
- let h = history(&dir);
-
- h.append("thread-1", user("old")).await.unwrap();
- h.replace("thread-1", vec![user("summary")]).await.unwrap();
- h.append("thread-1", user("new")).await.unwrap();
-
- assert_eq!(
- texts(&h.messages("thread-1").await.unwrap()),
- vec!["summary", "new"]
- );
-}
-
-/// An existing transcript's cumulative `_meta` wins over the handle's seed, so
-/// reopening a session does not reset its turn/token rollups to zero.
-#[tokio::test]
-async fn existing_meta_is_preferred_over_the_seed() {
- let dir = TempDir::new().unwrap();
- history(&dir).append("thread-1", user("one")).await.unwrap();
-
- let mut stale_seed = meta();
- stale_seed.turn_count = 999;
- stale_seed.agent_name = "wrong".into();
- let reopened = SessionTranscriptHistory::new(dir.path(), STEM, stale_seed).unwrap();
- reopened.append("thread-1", user("two")).await.unwrap();
-
- let persisted = read_transcript(reopened.path()).unwrap();
- assert_eq!(persisted.meta.agent_name, "tester");
- assert_ne!(persisted.meta.turn_count, 999);
-}
-
-// ── S4: the `SessionHistory` write seam ──────────────────────────────
-
-fn chat(role: &str, content: &str) -> ChatMessage {
- ChatMessage {
- id: None,
- role: role.into(),
- content: content.into(),
- extra_metadata: None,
- cache_breakpoints: Vec::new(),
- }
-}
-
-/// A turn's worth of provenance, with fixed timestamps so byte comparison is
-/// not clock-dependent.
-fn turn_usage() -> TurnUsage {
- TurnUsage {
- provider: "anthropic".into(),
- model: "claude-x".into(),
- usage: crate::agent::harness::session::transcript::MessageUsage {
- input: 20,
- output: 8,
- cached_input: 0,
- context_window: 200_000,
- cost_usd: 0.002,
- },
- ts: "2026-08-07T10:00:05Z".into(),
- reasoning_content: Some("thinking".into()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "call-1".into(),
- name: "get_weather".into(),
- arguments: r#"{"city":"NYC"}"#.into(),
- extra_content: None,
- }],
- iteration: 2,
- }
-}
-
-/// The core S4 correctness claim: `append_turn` is a **pure forwarder**.
-///
-/// The turn path stopped calling `append_transcript_turn` directly and now goes
-/// through the handle. That is only safe if the handle changes nothing, so this
-/// writes the same turn twice — once each way — and compares the files byte for
-/// byte. Cheaper and stricter than re-projecting the result: it fails on any
-/// transformation at all, not just ones the projection happens to notice.
-#[test]
-fn append_turn_is_byte_identical_to_the_free_function() {
- let direct_dir = TempDir::new().unwrap();
- let seam_dir = TempDir::new().unwrap();
-
- let messages = vec![
- chat("user", "what's the weather?"),
- chat("assistant", "72F and sunny."),
- ];
- let usage = turn_usage();
-
- let direct_path = resolve_keyed_transcript_path(direct_dir.path(), STEM).unwrap();
- append_transcript_turn(
- &direct_path,
- &[],
- &messages,
- &meta(),
- Some(&usage),
- Some("req-1"),
- )
- .unwrap();
-
- let seam = SessionTranscriptHistory::new(seam_dir.path(), STEM, meta()).unwrap();
- seam.append_turn(TranscriptTurn {
- prev: &[],
- next: &messages,
- meta: &meta(),
- turn_usage: Some(&usage),
- request_id: Some("req-1"),
- })
- .unwrap();
-
- assert_eq!(
- std::fs::read(&direct_path).unwrap(),
- std::fs::read(seam.path()).unwrap(),
- "append_turn must forward every argument unchanged"
- );
-}
-
-/// The executable form of this module's "why the write does not cross the crate
-/// trait" note: the same logical message set, written through `append_turn`
-/// versus through `ChatHistory::replace`, produces display lines that differ in
-/// exactly the three fields the trait cannot carry.
-///
-/// The trait-path assertions are not a bug being pinned — `replace` genuinely
-/// has nowhere to put this data. They are here so that anyone tempted to route
-/// the turn path through `ChatHistory` sees the cost first.
-#[tokio::test]
-async fn trait_path_loses_the_provenance_that_append_turn_preserves() {
- let usage = turn_usage();
- let messages = vec![chat("assistant", "72F and sunny.")];
-
- // Seam path: request_id + turn_usage reach the line.
- let seam_dir = TempDir::new().unwrap();
- let seam = history(&seam_dir);
- seam.append_turn(TranscriptTurn {
- prev: &[],
- next: &messages,
- meta: &meta(),
- turn_usage: Some(&usage),
- request_id: Some("req-1"),
- })
- .unwrap();
- let seam_line = first_display_message(seam.path());
- assert_eq!(seam_line.request_id.as_deref(), Some("req-1"));
- let seam_usage = seam_line.turn_usage.expect("turn_usage persisted");
- assert_eq!(seam_usage.model, "claude-x");
- assert_eq!(seam_usage.iteration, 2);
- assert_eq!(seam_usage.tool_calls.len(), 1);
-
- // Trait path: the same messages, none of the provenance.
- let trait_dir = TempDir::new().unwrap();
- let trait_history = history(&trait_dir);
- trait_history
- .replace(
- "thread-1",
- vec![Message::Assistant(
- tinyinference_llm::message::AssistantMessage {
- id: None,
- content: vec![tinyinference_llm::message::ContentBlock::Text(
- "72F and sunny.".into(),
- )],
- tool_calls: vec![],
- usage: None,
- },
- )],
- )
- .await
- .unwrap();
- let trait_line = first_display_message(trait_history.path());
- assert!(
- trait_line.request_id.is_none(),
- "ChatHistory has no channel for request_id — no turn boundary"
- );
- assert!(
- trait_line.turn_usage.is_none(),
- "ChatHistory has no channel for turn_usage — no model/iteration/tool calls"
- );
-}
-
-/// First `role != "system"` display message line of a transcript.
-fn first_display_message(
- path: &Path,
-) -> crate::agent::harness::session::transcript::DisplayMessage {
- read_transcript_display(path)
- .unwrap()
- .records
- .into_iter()
- .find_map(|r| match r {
- crate::agent::harness::session::transcript::DisplayRecord::Message(m)
- if m.message.role != "system" =>
- {
- Some(m)
- }
- _ => None,
- })
- .expect("a display message line")
-}
-
-// ─────────────────────────────────────────────────────────────────────
-// S4 read half: the locator + `read_session`
-// ─────────────────────────────────────────────────────────────────────
-
-/// The `_meta`/`messages` pair rendered exhaustively.
-///
-/// `SessionTranscript` cannot derive `PartialEq` here — that would mean editing
-/// `transcript.rs`, and this branch's zero-on-disk-change rule keeps that file
-/// untouched. `ChatMessage`'s `id` and `extra_metadata` are `skip_serializing`,
-/// so a JSON comparison would silently ignore exactly the fields most at risk;
-/// `Debug` prints every field, so it is the stricter check.
-fn transcript_fingerprint(t: &SessionTranscript) -> String {
- format!("{:?}|{:?}", t.meta, t.messages)
-}
-
-fn locator(dir: &TempDir) -> FileTranscriptLocator {
- FileTranscriptLocator::new(dir.path())
-}
-
-/// A tool round persisted the way the turn path persists it: the assistant
-/// carries the native `{content, tool_calls}` envelope and the tool row carries
-/// the matching `tool_call_id`.
-fn native_tool_round() -> Vec<ChatMessage> {
- vec![
- ChatMessage::system("system prompt"),
- ChatMessage::user("what is the weather"),
- ChatMessage::assistant(
- serde_json::json!({
- "content": "calling get_weather",
- // The flat `{id, name, arguments}` shape
- // `NativeDialect::to_provider_messages` persists — the
- // one `parse_native_assistant_envelope` accepts.
- "tool_calls": [{
- "id": "call-1",
- "name": "get_weather",
- "arguments": "{\"city\":\"SF\"}"
- }]
- })
- .to_string(),
- ),
- ChatMessage::tool(
- serde_json::json!({"tool_call_id": "call-1", "content": "72F and sunny"}).to_string(),
- ),
- ChatMessage::assistant("It is 72F and sunny."),
- ]
-}
-
-/// Writes a transcript exercising every replay rule the read must preserve: a
-/// plain extension turn, a **compaction** (a reduction, not a prefix), an
-/// `interrupted: true` partial, and a failure-annotated tool row.
-fn write_torture_transcript(dir: &TempDir) -> PathBuf {
- let path = resolve_keyed_transcript_path(dir.path(), STEM).unwrap();
-
- let first = native_tool_round();
- append_transcript_turn(&path, &[], &first, &meta(), None, Some("req-1")).unwrap();
-
- // A reduction, so the writer must emit a compaction record rather than a
- // tail append. Replaying it wrongly is the corruption §3.1 calls the single
- // most important constraint in the design.
- let mut failed_tool = ChatMessage::tool(
- serde_json::json!({"tool_call_id": "call-2", "content": "boom"}).to_string(),
- );
- crate::agent::harness::session::transcript::attach_tool_failure_metadata(
- &mut failed_tool,
- Some("exit status 1"),
- );
- let reduced = vec![
- ChatMessage::system("system prompt"),
- ChatMessage::assistant("[summary] asked about weather"),
- failed_tool,
- ChatMessage::assistant("Sorry, that failed."),
- ];
- append_transcript_turn(&path, &first, &reduced, &meta(), None, Some("req-2")).unwrap();
-
- // Display-only line the model-context replay must skip.
- crate::agent::harness::session::transcript::append_interrupted_partial(
- &path,
- "half a sent",
- Some("req-3"),
- Some(1),
- None,
- )
- .unwrap();
-
- path
-}
-
-/// The locator's read must be the free function's read — same struct, same
-/// call, no `Message` round trip. Compaction replay and interrupted-partial
-/// skipping therefore come along for free rather than being re-implemented.
-#[test]
-fn locator_read_is_equivalent_to_the_free_function() {
- let dir = TempDir::new().unwrap();
- let path = write_torture_transcript(&dir);
-
- let direct = read_transcript(&path).unwrap();
- let through_seam = locator(&dir)
- .latest_for_agent("tester")
- .expect("locator discovers the transcript")
- .read_session()
- .unwrap()
- .expect("file exists");
-
- assert_eq!(
- transcript_fingerprint(&through_seam),
- transcript_fingerprint(&direct),
- "read_session must return exactly what read_transcript returns"
- );
- // Guard the fixture itself: an equivalence that compared two empty replays
- // would pass for the wrong reason.
- let roles_and_text: Vec<(&str, String)> = direct
- .messages
- .iter()
- .map(|m| {
- // The tool row is JSON, and a serde round trip may reorder its
- // keys; compare it parsed so the assertion pins content, not
- // serialisation order.
- let text = serde_json::from_str::<serde_json::Value>(&m.content)
- .map(|v| v["content"].as_str().unwrap_or_default().to_string())
- .unwrap_or_else(|_| m.content.clone());
- (m.role.as_str(), text)
- })
- .collect();
- assert_eq!(
- roles_and_text,
- vec![
- ("system", "system prompt".to_string()),
- ("assistant", "[summary] asked about weather".to_string()),
- ("tool", "boom".to_string()),
- ("assistant", "Sorry, that failed.".to_string()),
- ],
- "the fixture must actually exercise the compaction + interrupted skip"
- );
-}
-
-/// The cold-boot lookup keyed on `_meta.thread_id` goes through the same seam.
-#[test]
-fn locator_root_for_thread_reads_the_matching_transcript() {
- let dir = TempDir::new().unwrap();
- let path = write_torture_transcript(&dir);
-
- let through_seam = locator(&dir)
- .root_for_thread("thread-1")
- .expect("locator resolves by _meta.thread_id")
- .read_session()
- .unwrap()
- .expect("file exists");
-
- assert_eq!(
- transcript_fingerprint(&through_seam),
- transcript_fingerprint(&read_transcript(&path).unwrap())
- );
- assert!(locator(&dir).root_for_thread("thread-absent").is_none());
-}
-
-/// `opened_at` binds a discovered path verbatim, so a legacy `.md` transcript
-/// still resolves. Re-resolving through `resolve_keyed_transcript_path*` — the
-/// obvious-looking alternative — would rewrite the extension to `.jsonl` and
-/// hand back a path that does not exist.
-#[test]
-fn md_legacy_path_resolves_through_the_locator() {
- let dir = TempDir::new().unwrap();
- let raw = dir.path().join("session_raw");
- std::fs::create_dir_all(&raw).unwrap();
- let md = raw.join(format!("{STEM}.md"));
- std::fs::write(
- &md,
- "<!-- session_transcript\nagent: tester\ndispatcher: native\n-->\n\n\
- <!--MSG role=\"user\"-->\nlegacy question\n<!--/MSG-->\n",
- )
- .unwrap();
-
- let handle = locator(&dir)
- .latest_for_agent("tester")
- .expect("locator finds the legacy .md");
- assert_eq!(
- handle.path(),
- md,
- "the discovered path must be used verbatim"
- );
-
- let session = handle.read_session().unwrap().expect("legacy file exists");
- assert_eq!(
- session
- .messages
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["legacy question"]
- );
-}
-
-/// A read handle bound to a file that vanished is `Ok(None)`, not an error —
-/// the callers fold it into their existing "nothing to resume from" branch.
-#[test]
-fn read_session_on_absent_file_is_none_not_an_error() {
- let dir = TempDir::new().unwrap();
- let handle = SessionTranscriptHistory::opened_at(
- dir.path().join("session_raw").join("nope.jsonl"),
- meta(),
- );
- assert!(handle.read_session().unwrap().is_none());
-}
-
-/// **The mutation gate for the read half.**
-///
-/// Routing the read through `ChatHistory::messages()` and converting back with
-/// `message_to_chat_message` flattens the assistant's native `tool_calls`
-/// envelope into prose, orphaning the following `role:"tool"` row — the
-/// provider `400 An assistant message with 'tool_calls' must be followed by
-/// tool messages`. This test asserts both halves: what the seam preserves, and
-/// that the rejected route really does lose it. Swap `read_session` for
-/// `messages()` in `try_load_session_transcript` and this fails.
-#[tokio::test]
-async fn resumed_native_tool_round_keeps_tool_calls() {
- let dir = TempDir::new().unwrap();
- let path = resolve_keyed_transcript_path(dir.path(), STEM).unwrap();
- let round = native_tool_round();
- append_transcript_turn(&path, &[], &round, &meta(), None, None).unwrap();
-
- let through_seam = locator(&dir)
- .latest_for_agent("tester")
- .unwrap()
- .read_session()
- .unwrap()
- .unwrap()
- .messages;
-
- let assistant = through_seam
- .iter()
- .find(|m| m.role == "assistant" && m.content.contains("tool_calls"))
- .expect("the assistant envelope survived the seam");
- let envelope: serde_json::Value = serde_json::from_str(&assistant.content).unwrap();
- assert_eq!(envelope["tool_calls"][0]["id"], "call-1");
- let tool_row = through_seam
- .iter()
- .find(|m| m.role == "tool")
- .expect("the tool result survived");
- let tool_json: serde_json::Value = serde_json::from_str(&tool_row.content).unwrap();
- assert_eq!(
- tool_json["tool_call_id"], "call-1",
- "the tool result must still correlate to the assistant's call"
- );
-
- // The rejected route, run for real so the rejection stays evidence-backed.
- let lossy: Vec<ChatMessage> = SessionTranscriptHistory::new(dir.path(), STEM, meta())
- .unwrap()
- .messages("thread-1")
- .await
- .unwrap()
- .iter()
- .map(message_to_chat_message)
- .collect();
- assert!(
- !lossy
- .iter()
- .any(|m| m.role == "assistant" && m.content.contains("tool_calls")),
- "ChatHistory::messages() is expected to drop the tool_calls envelope — \
- if this ever stops being true, revisit the read seam's rationale"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_roundtrip_and_paths_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_roundtrip_and_paths_tests.rs
deleted file mode 100644
index 251c49e65d..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_roundtrip_and_paths_tests.rs
+++ /dev/null
@@ -1,637 +0,0 @@
-use super::*;
-
-use std::fs;
-use std::path::PathBuf;
-#[test]
-fn intermediate_assistant_reasoning_is_lifted_without_turn_usage() {
- let mut message = ChatMessage::assistant("I will inspect the repository.");
- message.extra_metadata = Some(serde_json::json!({
- crate::agent::message_convert::REASONING_EXT_KEY:
- "First identify the relevant files."
- }));
-
- let line = build_message_line(&message, None, Some("request-1"), false);
- assert_eq!(
- line.reasoning_content.as_deref(),
- Some("First identify the relevant files.")
- );
-}
-
-#[test]
-fn round_trip_produces_byte_identical_messages() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("test.jsonl");
- let messages = sample_messages();
- let meta = sample_meta();
-
- write_transcript(&path, &messages, &meta, None).unwrap();
- let loaded = read_transcript(&path).unwrap();
-
- assert_eq!(loaded.messages.len(), messages.len());
- for (original, loaded) in messages.iter().zip(loaded.messages.iter()) {
- assert_eq!(original.id, loaded.id, "id mismatch");
- assert_eq!(original.role, loaded.role, "role mismatch");
- assert_eq!(
- original.content, loaded.content,
- "content mismatch for role={}",
- original.role
- );
- assert_eq!(
- original.extra_metadata, loaded.extra_metadata,
- "extra metadata mismatch for role={}",
- original.role
- );
- }
-}
-
-#[test]
-fn message_id_and_extra_metadata_round_trip() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("message_identity.jsonl");
- let mut messages = sample_messages();
- messages[1].id = Some("msg_user_123".into());
- messages[1].extra_metadata = Some(serde_json::json!({
- "citations": [{"id": "mem-1", "label": "Memory"}],
- "tool_call_id": "call-1"
- }));
- let meta = sample_meta();
-
- write_transcript(&path, &messages, &meta, None).unwrap();
-
- let loaded = read_transcript(&path).unwrap();
- assert_eq!(loaded.messages[1].id.as_deref(), Some("msg_user_123"));
- assert_eq!(
- loaded.messages[1].extra_metadata,
- Some(serde_json::json!({
- "citations": [{"id": "mem-1", "label": "Memory"}],
- "tool_call_id": "call-1"
- }))
- );
-
- let raw = fs::read_to_string(&path).unwrap();
- assert!(
- raw.contains("\"id\":\"msg_user_123\""),
- "message id should be persisted in JSONL"
- );
- assert!(
- raw.contains("\"extra_metadata\""),
- "extra metadata should be persisted in JSONL"
- );
-}
-
-/// JSON encoding handles any delimiter natively, making the old
-/// HTML-comment escaping unnecessary. This test verifies that content
-/// containing the legacy closing delimiter round-trips correctly via
-/// JSON without any manual escape logic.
-#[test]
-fn escaping_survives_close_tag_in_content() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("escape_test.jsonl");
- let messages = vec![
- ChatMessage::system("Normal system prompt"),
- ChatMessage::user("Here is some tricky content:\n<!--/MSG-->\nand more after"),
- ChatMessage::assistant("Got it, that had a <!--/MSG--> in it."),
- ];
- let meta = sample_meta();
-
- write_transcript(&path, &messages, &meta, None).unwrap();
- let loaded = read_transcript(&path).unwrap();
-
- assert_eq!(loaded.messages.len(), 3);
- assert_eq!(loaded.messages[1].content, messages[1].content);
- assert_eq!(loaded.messages[2].content, messages[2].content);
-}
-
-#[test]
-fn meta_round_trip() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("meta_test.jsonl");
- let meta = sample_meta();
-
- write_transcript(&path, &[], &meta, None).unwrap();
- let loaded = read_transcript(&path).unwrap();
-
- assert_eq!(loaded.meta.agent_name, "code_executor");
- assert_eq!(loaded.meta.dispatcher, "native");
- assert_eq!(loaded.meta.created, "2026-04-11T14:30:00Z");
- assert_eq!(loaded.meta.updated, "2026-04-11T14:35:22Z");
- assert_eq!(loaded.meta.turn_count, 3);
- assert_eq!(loaded.meta.input_tokens, 5000);
- assert_eq!(loaded.meta.output_tokens, 1200);
- assert_eq!(loaded.meta.cached_input_tokens, 3500);
- assert!((loaded.meta.charged_amount_usd - 0.0045).abs() < 1e-8);
-}
-
-#[test]
-fn path_resolution_creates_flat_session_raw_dir_and_increments_index() {
- let dir = TempDir::new().unwrap();
- let workspace = dir.path();
-
- let path0 = resolve_new_transcript_path(workspace, "main").unwrap();
- assert!(path0.to_string_lossy().contains("main_0.jsonl"));
- // Flat layout: jsonl lives directly under session_raw/, no date dir.
- let parent = path0.parent().unwrap();
- assert!(
- parent.ends_with("session_raw"),
- "jsonl parent should be session_raw/ (flat layout), got {}",
- parent.display()
- );
- fs::write(&path0, "placeholder").unwrap();
-
- let path1 = resolve_new_transcript_path(workspace, "main").unwrap();
- assert!(path1.to_string_lossy().contains("main_1.jsonl"));
- assert!(path1.parent().unwrap().ends_with("session_raw"));
-}
-
-#[test]
-fn resolve_keyed_writes_to_flat_session_raw() {
- let dir = TempDir::new().unwrap();
- let path = resolve_keyed_transcript_path(dir.path(), "1714000000_orchestrator").unwrap();
- assert_eq!(path.parent().unwrap(), dir.path().join("session_raw"));
- assert!(path
- .to_string_lossy()
- .ends_with("1714000000_orchestrator.jsonl"));
-}
-
-#[test]
-fn md_companion_path_for_flat_jsonl_uses_iso_date_dir() {
- let jsonl = PathBuf::from("/tmp/ws/session_raw/1714000000_main.jsonl");
- let md = md_companion_path(&jsonl);
- let today = chrono::Local::now().format("%Y_%m_%d").to_string();
- assert_eq!(
- md,
- PathBuf::from(format!("/tmp/ws/sessions/{today}/1714000000_main.md")),
- "flat session_raw should map to sessions/YYYY_MM_DD/ on the md side"
- );
-}
-
-#[test]
-fn md_companion_path_preserves_legacy_ddmmyyyy_dir() {
- // A pre-migration jsonl at session_raw/DDMMYYYY/{stem}.jsonl should
- // keep its date component so old transcripts aren't relabeled with
- // today's date.
- let jsonl = PathBuf::from("/tmp/ws/session_raw/17042026/main_0.jsonl");
- let md = md_companion_path(&jsonl);
- assert_eq!(
- md,
- PathBuf::from("/tmp/ws/sessions/17042026/main_0.md"),
- "legacy date-grouped raw paths must keep their original date dir"
- );
-}
-
-#[test]
-fn md_companion_path_falls_back_to_sibling_when_no_session_raw_component() {
- let jsonl = PathBuf::from("/tmp/flat/main_0.jsonl");
- let md = md_companion_path(&jsonl);
- assert_eq!(md, PathBuf::from("/tmp/flat/main_0.md"));
-}
-
-#[test]
-fn resolve_avoids_index_collision_with_md_in_iso_date_dir() {
- let dir = TempDir::new().unwrap();
- let workspace = dir.path();
- let date = chrono::Local::now().format("%Y_%m_%d").to_string();
- let md_dir = workspace.join("sessions").join(&date);
- fs::create_dir_all(&md_dir).unwrap();
- fs::write(md_dir.join("main_0.md"), "x").unwrap();
- fs::write(md_dir.join("main_1.md"), "x").unwrap();
-
- let path = resolve_new_transcript_path(workspace, "main").unwrap();
- assert!(
- path.to_string_lossy().contains("main_2.jsonl"),
- "should advance past md indices in today's YYYY_MM_DD dir, got {}",
- path.display()
- );
-}
-
-#[test]
-fn sanitize_agent_name_strips_special_chars() {
- assert_eq!(sanitize_agent_name("code_executor"), "code_executor");
- assert_eq!(sanitize_agent_name("my agent!"), "my_agent_");
- assert_eq!(sanitize_agent_name("agent-v2"), "agent-v2");
-}
-
-#[test]
-fn find_latest_scans_flat_session_raw_dir() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- fs::write(raw_dir.join("main_0.jsonl"), "a").unwrap();
- fs::write(raw_dir.join("main_2.jsonl"), "c").unwrap();
- fs::write(raw_dir.join("main_1.jsonl"), "b").unwrap();
- fs::write(raw_dir.join("other_0.jsonl"), "x").unwrap();
-
- let latest = find_latest_transcript(dir.path(), "main").unwrap();
- assert!(latest.to_string_lossy().ends_with("main_2.jsonl"));
- assert_eq!(latest.parent().unwrap(), raw_dir);
-}
-
-#[test]
-fn find_latest_picks_newest_keyed_stem_in_flat_dir() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- // Keyed stem layout: `{unix_ts}_{agent_id}.jsonl`.
- fs::write(raw_dir.join("1714000000_main.jsonl"), "old").unwrap();
- fs::write(raw_dir.join("1714999999_main.jsonl"), "new").unwrap();
- // Sub-agent transcripts (contain `__`) must be skipped.
- fs::write(
- raw_dir.join("1714000000_orchestrator__1714500000_planner.jsonl"),
- "sub",
- )
- .unwrap();
-
- let latest = find_latest_transcript(dir.path(), "main").unwrap();
- assert!(latest.to_string_lossy().ends_with("1714999999_main.jsonl"));
-}
-
-#[test]
-fn find_root_transcript_for_thread_skips_subagent_siblings() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- let mut root_meta = sample_meta();
- root_meta.thread_id = Some("thread-abc".into());
- write_transcript(
- &raw_dir.join("1714000000_orchestrator_thread-abc.jsonl"),
- &sample_messages(),
- &root_meta,
- None,
- )
- .unwrap();
-
- let mut newer_other_meta = sample_meta();
- newer_other_meta.thread_id = Some("thread-other".into());
- write_transcript(
- &raw_dir.join("1714999999_orchestrator_thread-other.jsonl"),
- &sample_messages(),
- &newer_other_meta,
- None,
- )
- .unwrap();
-
- let mut subagent_meta = sample_meta();
- subagent_meta.thread_id = Some("thread-abc".into());
- write_transcript(
- &raw_dir.join("1715000000_orchestrator_thread-abc__1715000100_worker.jsonl"),
- &sample_messages(),
- &subagent_meta,
- None,
- )
- .unwrap();
-
- let found = find_root_transcript_for_thread(dir.path(), "thread-abc").unwrap();
- assert!(found
- .to_string_lossy()
- .ends_with("1714000000_orchestrator_thread-abc.jsonl"));
-}
-
-#[test]
-fn find_root_transcript_for_thread_scans_canonical_raw_dir() {
- let dir = TempDir::new().unwrap();
- let scoped_raw = raw_session_dir(dir.path());
- fs::create_dir_all(&scoped_raw).unwrap();
-
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-canonical".into());
- let expected = scoped_raw.join("1714000000_orchestrator_thread-canonical.jsonl");
- write_transcript(&expected, &sample_messages(), &meta, None).unwrap();
-
- assert_eq!(
- find_root_transcript_for_thread(dir.path(), "thread-canonical"),
- Some(expected)
- );
-}
-
-#[test]
-fn find_latest_falls_back_to_legacy_ddmmyyyy_raw_dir() {
- // Pre-migration transcript at session_raw/DDMMYYYY/main_*.jsonl
- // must still resolve via the legacy fallback when the flat dir is
- // empty.
- let dir = TempDir::new().unwrap();
- let date = chrono::Local::now().format("%d%m%Y").to_string();
- let legacy_raw = dir.path().join("session_raw").join(&date);
- fs::create_dir_all(&legacy_raw).unwrap();
- fs::write(legacy_raw.join("main_5.jsonl"), "legacy").unwrap();
-
- let latest = find_latest_transcript(dir.path(), "main").unwrap();
- assert!(latest.to_string_lossy().ends_with("main_5.jsonl"));
- assert!(latest.to_string_lossy().contains(&date));
-}
-
-#[test]
-fn find_latest_prefers_flat_over_legacy_ddmmyyyy() {
- let dir = TempDir::new().unwrap();
- let raw_root = dir.path().join("session_raw");
- fs::create_dir_all(&raw_root).unwrap();
- fs::write(raw_root.join("main_9.jsonl"), "flat").unwrap();
-
- let date = chrono::Local::now().format("%d%m%Y").to_string();
- let legacy_raw = raw_root.join(&date);
- fs::create_dir_all(&legacy_raw).unwrap();
- fs::write(legacy_raw.join("main_99.jsonl"), "legacy").unwrap();
-
- let latest = find_latest_transcript(dir.path(), "main").unwrap();
- // Flat dir takes precedence so newly-created sessions always win
- // over stale legacy files — even when a legacy file has a higher
- // numeric index. The flat dir is the canonical layout going
- // forward.
- assert_eq!(latest.parent().unwrap(), raw_root);
- assert!(latest.to_string_lossy().ends_with("main_9.jsonl"));
-}
-
-#[test]
-fn find_latest_falls_back_to_legacy_sessions_md() {
- let dir = TempDir::new().unwrap();
- let date = chrono::Local::now().format("%d%m%Y").to_string();
- let legacy = dir.path().join("sessions").join(&date);
- fs::create_dir_all(&legacy).unwrap();
- fs::write(legacy.join("main_0.md"), "legacy").unwrap();
-
- let latest = find_latest_transcript(dir.path(), "main");
- assert!(latest.is_some());
- let latest = latest.unwrap();
- assert!(latest.to_string_lossy().ends_with("main_0.md"));
-}
-
-#[test]
-fn find_latest_returns_none_when_no_sessions() {
- let dir = TempDir::new().unwrap();
- assert!(find_latest_transcript(dir.path(), "main").is_none());
-}
-
-#[test]
-fn empty_content_message_round_trips() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("empty.jsonl");
- let messages = vec![
- ChatMessage::system("prompt"),
- ChatMessage::assistant(""),
- ChatMessage::user("hi"),
- ];
- let meta = sample_meta();
-
- write_transcript(&path, &messages, &meta, None).unwrap();
- let loaded = read_transcript(&path).unwrap();
-
- assert_eq!(loaded.messages.len(), 3);
- assert_eq!(loaded.messages[1].content, "");
-}
-
-#[test]
-fn multiline_content_preserves_exact_whitespace() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("whitespace.jsonl");
- let content = " leading spaces\n\n\nmultiple blanks\n trailing ";
- let messages = vec![ChatMessage::user(content)];
- let meta = sample_meta();
-
- write_transcript(&path, &messages, &meta, None).unwrap();
- let loaded = read_transcript(&path).unwrap();
-
- assert_eq!(loaded.messages[0].content, content);
-}
-
-#[test]
-fn usage_round_trips_on_last_assistant_message() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("usage.jsonl");
- let messages = sample_messages();
- let meta = sample_meta();
- let tu = sample_turn_usage();
-
- write_transcript(&path, &messages, &meta, Some(&tu)).unwrap();
-
- // Verify by reading raw JSONL lines: the last assistant line should
- // carry model + usage + ts fields.
- let raw = fs::read_to_string(&path).unwrap();
- let last_assistant_line = raw
- .lines()
- .filter(|l| l.contains("\"role\":\"assistant\""))
- .last()
- .expect("should have an assistant line");
-
- assert!(
- last_assistant_line.contains("claude-sonnet-4-6"),
- "model missing from last assistant line"
- );
- assert!(
- last_assistant_line.contains("openhuman-backend"),
- "provider missing from last assistant line"
- );
- assert!(
- last_assistant_line.contains("\"context_window\":200000"),
- "context window missing from usage"
- );
- assert!(
- last_assistant_line.contains("private reasoning trace"),
- "reasoning content missing from assistant metadata"
- );
- assert!(
- last_assistant_line.contains("\"tool_calls\""),
- "native tool calls missing from assistant metadata"
- );
- assert!(
- last_assistant_line.contains("\"cost_usd\""),
- "cost_usd missing"
- );
-
- // Messages themselves still round-trip byte-identically.
- let loaded = read_transcript(&path).unwrap();
- assert_eq!(loaded.messages.len(), messages.len());
- for (orig, got) in messages.iter().zip(loaded.messages.iter()) {
- assert_eq!(orig.role, got.role);
- assert_eq!(orig.content, got.content);
- }
-}
-
-#[test]
-fn embedded_usage_preserves_earlier_assistant_messages_on_rewrite() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("multi_usage.jsonl");
- let mut messages = vec![
- ChatMessage::user("start"),
- ChatMessage::assistant("first"),
- ChatMessage::user("continue"),
- ChatMessage::assistant("second"),
- ];
- let first_usage = TurnUsage {
- provider: "provider-a".into(),
- model: "model-a".into(),
- iteration: 1,
- ..sample_turn_usage()
- };
- let second_usage = TurnUsage {
- provider: "provider-b".into(),
- model: "model-b".into(),
- iteration: 2,
- ..sample_turn_usage()
- };
- attach_turn_usage_metadata(&mut messages[1], &first_usage);
-
- write_transcript(&path, &messages, &sample_meta(), Some(&second_usage)).unwrap();
-
- let raw = fs::read_to_string(&path).unwrap();
- let assistant_lines: Vec<&str> = raw
- .lines()
- .filter(|line| line.contains("\"role\":\"assistant\""))
- .collect();
- assert_eq!(assistant_lines.len(), 2);
- assert!(assistant_lines[0].contains("provider-a"));
- assert!(assistant_lines[0].contains("model-a"));
- assert!(assistant_lines[1].contains("provider-b"));
- assert!(assistant_lines[1].contains("model-b"));
-
- let loaded = read_transcript(&path).unwrap();
- write_transcript(&path, &loaded.messages, &loaded.meta, None).unwrap();
- let rewritten = fs::read_to_string(&path).unwrap();
- assert!(rewritten.contains("provider-a"));
- assert!(rewritten.contains("model-a"));
- assert!(rewritten.contains("provider-b"));
- assert!(rewritten.contains("model-b"));
-}
-
-#[test]
-fn md_companion_file_is_written() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("companion.jsonl");
- let messages = sample_messages();
- let meta = sample_meta();
- let tu = sample_turn_usage();
-
- write_transcript(&path, &messages, &meta, Some(&tu)).unwrap();
-
- let md_path = path.with_extension("md");
- assert!(md_path.exists(), ".md companion should be written");
- let md = fs::read_to_string(&md_path).unwrap();
- assert!(md.contains("# Session transcript — code_executor"));
- assert!(md.contains("Agent ID: `code_executor`"));
- assert!(md.contains("Agent type: `subagent`"));
- assert!(md.contains("Provider: `openhuman-backend`"));
- assert!(md.contains("Task: `task-123`"));
- assert!(
- md.contains("claude-sonnet-4-6"),
- "model should appear in md"
- );
- assert!(md.contains("private reasoning trace"));
- assert!(md.contains("## [system]"), "system section missing");
- assert!(md.contains("## [user]"), "user section missing");
-}
-
-#[test]
-fn legacy_md_fallback_reads_old_session() {
- let dir = TempDir::new().unwrap();
- // Write a legacy .md file directly (old format).
- let md_path = dir.path().join("legacy.md");
- let legacy_content = "<!-- session_transcript\nagent: test_agent\ndispatcher: native\ncreated: 2026-01-01T00:00:00Z\nupdated: 2026-01-01T00:01:00Z\nturn_count: 1\ninput_tokens: 10\noutput_tokens: 5\ncached_input_tokens: 3\n-->\n\n<!--MSG role=\"system\"-->\nhello\n<!--/MSG-->\n";
- fs::write(&md_path, legacy_content).unwrap();
-
- // read_transcript called with a .jsonl path that doesn't exist
- // should fall back to the .md sibling.
- let jsonl_path = dir.path().join("legacy.jsonl");
- let loaded = read_transcript(&jsonl_path).unwrap();
- assert_eq!(loaded.meta.agent_name, "test_agent");
- assert_eq!(loaded.messages.len(), 1);
- assert_eq!(loaded.messages[0].role, "system");
- assert_eq!(loaded.messages[0].content, "hello");
-}
-
-#[test]
-fn unknown_fields_on_jsonl_lines_are_ignored() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("forward_compat.jsonl");
-
- // Write a JSONL with future unknown fields.
- let content = concat!(
- r#"{"_meta":{"agent":"a","dispatcher":"native","created":"t","updated":"t","turn_count":0,"input_tokens":0,"output_tokens":0,"cached_input_tokens":0,"charged_amount_usd":0.0}}"#,
- "\n",
- r#"{"role":"user","content":"hello","future_field":"ignored","another":42}"#,
- "\n"
- );
- fs::write(&path, content).unwrap();
-
- let loaded = read_transcript(&path).unwrap();
- assert_eq!(loaded.messages.len(), 1);
- assert_eq!(loaded.messages[0].role, "user");
- assert_eq!(loaded.messages[0].content, "hello");
-}
-
-#[test]
-fn next_index_counts_both_jsonl_and_md_files() {
- let dir = TempDir::new().unwrap();
- // Mix of legacy .md and new .jsonl for the same agent.
- fs::write(dir.path().join("main_0.md"), "legacy").unwrap();
- fs::write(dir.path().join("main_1.jsonl"), "new").unwrap();
-
- let next = next_index(dir.path(), "main").unwrap();
- assert_eq!(
- next, 2,
- "should account for both .md and .jsonl when computing next index"
- );
-}
-
-#[test]
-fn latest_in_dir_prefers_jsonl_over_md() {
- let dir = TempDir::new().unwrap();
- // Same index: both .jsonl and .md exist — .jsonl should win.
- fs::write(dir.path().join("main_0.md"), "legacy").unwrap();
- fs::write(dir.path().join("main_0.jsonl"), "new").unwrap();
-
- let latest = latest_in_dir(dir.path(), "main").unwrap();
- assert!(
- latest.to_string_lossy().ends_with(".jsonl"),
- "should prefer .jsonl when both exist at same index"
- );
-}
-
-/// `thread_id` (the backend-side LLM thread identifier) must be both
-/// emitted in the JSONL `_meta` header and surfaced in the `.md`
-/// companion so a human reading the transcript can correlate it with
-/// `InferenceLog` rows on the backend. Sessions without an ambient
-/// thread (CLI, tests) keep `thread_id = None` and neither field
-/// appears — the absence is intentional, not a missing feature.
-#[test]
-fn thread_id_round_trips_and_appears_in_md_when_present() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("thread.jsonl");
- let messages = sample_messages();
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-xyz-42".into());
-
- write_transcript(&path, &messages, &meta, None).unwrap();
-
- // JSONL round-trip preserves the field.
- let loaded = read_transcript(&path).unwrap();
- assert_eq!(loaded.meta.thread_id.as_deref(), Some("thread-xyz-42"));
-
- // Markdown companion exposes it under the header.
- let md = fs::read_to_string(path.with_extension("md")).unwrap();
- assert!(
- md.contains("- Thread: `thread-xyz-42`"),
- "thread id should be rendered in md header, got:\n{md}"
- );
-}
-
-#[test]
-fn thread_id_absent_omits_md_line_and_jsonl_field() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("no_thread.jsonl");
- let messages = sample_messages();
- let meta = sample_meta(); // thread_id = None
-
- write_transcript(&path, &messages, &meta, None).unwrap();
-
- let raw_jsonl = fs::read_to_string(&path).unwrap();
- assert!(
- !raw_jsonl.contains("\"thread_id\""),
- "absent thread_id must be skipped in JSONL so the field doesn't show up as `null`"
- );
- let md = fs::read_to_string(path.with_extension("md")).unwrap();
- assert!(
- !md.contains("- Thread:"),
- "no `- Thread:` line should appear when thread_id is None, got:\n{md}"
- );
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_tests.rs
deleted file mode 100644
index efe8be7a00..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_tests.rs
+++ /dev/null
@@ -1,100 +0,0 @@
-use super::*;
-use crate::agent::messages::ChatMessage;
-use crate::inference::provider::ToolCall;
-use tempfile::TempDir;
-
-fn sample_messages() -> Vec<ChatMessage> {
- vec![
- ChatMessage::system(
- "You are a helpful assistant.\n\n## Tools\n\n- **shell**: Run commands",
- ),
- ChatMessage::user("What files are in /tmp?"),
- ChatMessage::assistant("Let me check that for you."),
- ChatMessage::tool("{\"tool_call_id\":\"tc1\",\"content\":\"file1.txt\\nfile2.txt\"}"),
- ChatMessage::assistant("There are two files: file1.txt and file2.txt."),
- ]
-}
-
-fn sample_meta() -> TranscriptMeta {
- TranscriptMeta {
- agent_name: "code_executor".into(),
- agent_id: Some("code_executor".into()),
- agent_type: Some("subagent".into()),
- dispatcher: "native".into(),
- provider: Some("openhuman-backend".into()),
- model: Some("claude-sonnet-4-6".into()),
- created: "2026-04-11T14:30:00Z".into(),
- updated: "2026-04-11T14:35:22Z".into(),
- turn_count: 3,
- input_tokens: 5000,
- output_tokens: 1200,
- cached_input_tokens: 3500,
- charged_amount_usd: 0.0045,
- thread_id: None,
- task_id: Some("task-123".into()),
- }
-}
-
-fn sample_turn_usage() -> TurnUsage {
- TurnUsage {
- provider: "openhuman-backend".into(),
- model: "claude-sonnet-4-6".into(),
- usage: MessageUsage {
- input: 1234,
- output: 567,
- cached_input: 1000,
- context_window: 200_000,
- cost_usd: 0.0012,
- },
- ts: "2026-04-17T10:00:00Z".into(),
- reasoning_content: Some("private reasoning trace".into()),
- tool_calls: vec![ToolCall {
- id: "call-1".into(),
- name: "shell".into(),
- arguments: "{\"cmd\":\"ls\"}".into(),
- extra_content: None,
- }],
- iteration: 1,
- }
-}
-
-// ── Phase A: append-only + compaction + display + interrupted ─────────
-
-/// A helper mirroring the in-process persist loop: track the previously
-/// persisted logical set and feed each turn through `append_transcript_turn`.
-struct AppendHarness {
- path: std::path::PathBuf,
- prev: Vec<ChatMessage>,
-}
-
-impl AppendHarness {
- fn new(path: std::path::PathBuf) -> Self {
- Self {
- path,
- prev: Vec::new(),
- }
- }
-
- fn turn(
- &mut self,
- messages: &[ChatMessage],
- meta: &TranscriptMeta,
- usage: Option<&TurnUsage>,
- request_id: Option<&str>,
- ) {
- append_transcript_turn(&self.path, &self.prev, messages, meta, usage, request_id)
- .expect("append turn");
- self.prev = messages.to_vec();
- }
-}
-
-fn roles(messages: &[ChatMessage]) -> Vec<&str> {
- messages.iter().map(|m| m.role.as_str()).collect()
-}
-
-#[path = "transcript_forward_compat_tests.rs"]
-mod transcript_forward_compat_tests;
-#[path = "transcript_roundtrip_and_paths_tests.rs"]
-mod transcript_roundtrip_and_paths_tests;
-#[path = "transcript_thread_and_append_tests.rs"]
-mod transcript_thread_and_append_tests;
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs
deleted file mode 100644
index eb551b8846..0000000000
--- a/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs
+++ /dev/null
@@ -1,685 +0,0 @@
-use super::*;
-
-use crate::agent::messages::ChatMessage;
-use std::fs;
-// ── find_root_transcript_for_thread: scope isolation ────────────────────────
-
-/// An empty or blank `thread_id` must not match any transcript — the
-/// function should return `None` immediately rather than scan every JSONL
-/// file looking for an empty `thread_id`.
-#[test]
-fn find_root_transcript_for_thread_returns_none_for_empty_thread_id() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- // Write a transcript that has a non-empty thread_id.
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-abc".into());
- write_transcript(
- &raw_dir.join("1714000000_main.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- assert!(
- find_root_transcript_for_thread(dir.path(), "").is_none(),
- "empty thread_id should return None"
- );
- assert!(
- find_root_transcript_for_thread(dir.path(), " ").is_none(),
- "blank thread_id should return None"
- );
-}
-
-/// When two threads have transcripts in the same workspace, each call
-/// must return **only** the file belonging to that thread — cross-thread
-/// bleed must not occur.
-#[test]
-fn find_root_transcript_for_thread_isolates_by_thread_id() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- let mut meta_a = sample_meta();
- meta_a.thread_id = Some("thread-aaa".into());
- write_transcript(
- &raw_dir.join("1714000000_agent_thread-aaa.jsonl"),
- &sample_messages(),
- &meta_a,
- None,
- )
- .unwrap();
-
- let mut meta_b = sample_meta();
- meta_b.thread_id = Some("thread-bbb".into());
- write_transcript(
- &raw_dir.join("1714001000_agent_thread-bbb.jsonl"),
- &sample_messages(),
- &meta_b,
- None,
- )
- .unwrap();
-
- let found_a = find_root_transcript_for_thread(dir.path(), "thread-aaa")
- .expect("should find transcript for thread-aaa");
- let found_b = find_root_transcript_for_thread(dir.path(), "thread-bbb")
- .expect("should find transcript for thread-bbb");
-
- assert!(
- found_a
- .to_string_lossy()
- .contains("1714000000_agent_thread-aaa"),
- "wrong transcript returned for thread-aaa: {}",
- found_a.display()
- );
- assert!(
- found_b
- .to_string_lossy()
- .contains("1714001000_agent_thread-bbb"),
- "wrong transcript returned for thread-bbb: {}",
- found_b.display()
- );
-}
-
-/// `find_root_transcript_for_thread` returns the **newest** transcript
-/// (highest stem, alphabetically) when multiple root files share the
-/// same `thread_id`. This covers the agent restart scenario where a
-/// session accumulates more than one transcript for the same thread.
-#[test]
-fn find_root_transcript_for_thread_returns_newest_when_multiple_match() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-multi".into());
-
- // Older file — lower timestamp.
- write_transcript(
- &raw_dir.join("1714000000_orchestrator_thread-multi.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- // Newer file — higher timestamp; should be the one returned.
- write_transcript(
- &raw_dir.join("1715000000_orchestrator_thread-multi.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- let found = find_root_transcript_for_thread(dir.path(), "thread-multi")
- .expect("should find newest transcript");
- assert!(
- found
- .to_string_lossy()
- .contains("1715000000_orchestrator_thread-multi"),
- "should return the newest transcript, got: {}",
- found.display()
- );
-}
-
-/// A subagent transcript (stem contains `__`) must be skipped even if
-/// its `thread_id` matches — only root transcripts are eligible.
-#[test]
-fn find_root_transcript_for_thread_excludes_subagent_files() {
- let dir = TempDir::new().unwrap();
- let raw_dir = dir.path().join("session_raw");
- fs::create_dir_all(&raw_dir).unwrap();
-
- let mut meta = sample_meta();
- meta.thread_id = Some("thread-xyz".into());
-
- // Root transcript — should be found.
- write_transcript(
- &raw_dir.join("1714000000_orch_thread-xyz.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- // Sub-agent transcript for the same thread — must be skipped.
- write_transcript(
- &raw_dir.join("1714000000_orch_thread-xyz__1714500000_worker.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- let found = find_root_transcript_for_thread(dir.path(), "thread-xyz")
- .expect("should find the root transcript");
- let stem = found.file_stem().unwrap().to_string_lossy();
- assert!(
- !stem.contains("__"),
- "returned path must not be a subagent file (contains __): {}",
- found.display()
- );
-}
-
-#[test]
-fn read_thread_usage_summary_totals_last_turn_and_model() {
- let ws = TempDir::new().unwrap();
- let raw = raw_session_dir(ws.path());
- std::fs::create_dir_all(&raw).unwrap();
-
- let mut meta = sample_meta();
- meta.thread_id = Some("thr-xyz".into());
- meta.input_tokens = 5000;
- meta.output_tokens = 1200;
- meta.cached_input_tokens = 800;
- meta.charged_amount_usd = 0.0045;
- meta.turn_count = 3;
-
- let tu = TurnUsage {
- provider: "openhuman-backend".into(),
- model: "reasoning-v1".into(),
- usage: MessageUsage {
- input: 400,
- output: 120,
- cached_input: 50,
- context_window: 1_000_000,
- cost_usd: 0.0009,
- },
- ts: "2026-04-11T14:35:22Z".into(),
- reasoning_content: None,
- tool_calls: Vec::new(),
- iteration: 0,
- };
- let path = raw.join("1700000000_main.jsonl");
- write_transcript(&path, &sample_messages(), &meta, Some(&tu)).unwrap();
-
- let summary = read_thread_usage_summary(ws.path(), "thr-xyz").expect("summary present");
- assert_eq!(summary.input_tokens, 5000);
- assert_eq!(summary.output_tokens, 1200);
- assert_eq!(summary.cached_input_tokens, 800);
- assert!((summary.cost_usd - 0.0045).abs() < 1e-9);
- assert_eq!(summary.turn_count, 3);
- assert_eq!(summary.last_turn_input_tokens, 400);
- assert_eq!(summary.last_turn_output_tokens, 120);
- assert_eq!(summary.model.as_deref(), Some("reasoning-v1"));
-}
-
-#[test]
-fn read_thread_usage_summary_sums_multiple_transcripts() {
- let ws = TempDir::new().unwrap();
- let raw = raw_session_dir(ws.path());
- std::fs::create_dir_all(&raw).unwrap();
-
- let mk = |stem: &str, input: u64, cost: f64| {
- let mut meta = sample_meta();
- meta.thread_id = Some("thr-multi".into());
- meta.input_tokens = input;
- meta.output_tokens = 0;
- meta.cached_input_tokens = 0;
- meta.charged_amount_usd = cost;
- meta.turn_count = 1;
- write_transcript(
- &raw.join(format!("{stem}.jsonl")),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
- };
- mk("1700000000_main", 100, 0.01);
- mk("1700000100_main", 250, 0.02);
-
- let s = read_thread_usage_summary(ws.path(), "thr-multi").expect("summary present");
- assert_eq!(s.input_tokens, 350);
- assert!((s.cost_usd - 0.03).abs() < 1e-9);
- assert_eq!(s.turn_count, 2);
-}
-
-#[test]
-fn read_thread_usage_summary_scans_canonical_raw_dir() {
- let ws = TempDir::new().unwrap();
- let raw = raw_session_dir(ws.path());
- std::fs::create_dir_all(&raw).unwrap();
- let mut meta = sample_meta();
- meta.thread_id = Some("thr-scoped-usage".into());
- meta.input_tokens = 321;
- meta.output_tokens = 45;
- meta.turn_count = 2;
- write_transcript(
- &raw.join("1700000000_main.jsonl"),
- &sample_messages(),
- &meta,
- None,
- )
- .unwrap();
-
- let summary = read_thread_usage_summary(ws.path(), "thr-scoped-usage")
- .expect("canonical usage summary present");
- assert_eq!(summary.input_tokens, 321);
- assert_eq!(summary.output_tokens, 45);
- assert_eq!(summary.turn_count, 2);
-}
-
-#[test]
-fn read_thread_usage_summary_none_for_unknown_thread() {
- let ws = TempDir::new().unwrap();
- assert!(read_thread_usage_summary(ws.path(), "no-such-thread").is_none());
- // Empty thread id is rejected too.
- assert!(read_thread_usage_summary(ws.path(), " ").is_none());
-}
-
-#[test]
-fn read_thread_usage_summary_groups_subagents_by_archetype() {
- let ws = TempDir::new().unwrap();
- let raw = raw_session_dir(ws.path());
- std::fs::create_dir_all(&raw).unwrap();
-
- // Root (orchestrator) transcript — never includes sub-agent calls.
- let mut root = sample_meta();
- root.thread_id = Some("thr-sub".into());
- root.agent_name = "main".into();
- root.input_tokens = 1000;
- root.output_tokens = 200;
- root.cached_input_tokens = 0;
- root.charged_amount_usd = 0.0;
- root.turn_count = 2;
- write_transcript(
- &raw.join("1700000000_main.jsonl"),
- &sample_messages(),
- &root,
- None,
- )
- .unwrap();
-
- // Sub-agent transcripts (stems contain `__`): coder x2 + researcher x1.
- let sub = |stem: &str, agent: &str, input: u64, output: u64| {
- let mut m = sample_meta();
- m.thread_id = Some("thr-sub".into());
- m.agent_name = agent.into();
- m.input_tokens = input;
- m.output_tokens = output;
- m.cached_input_tokens = 0;
- m.charged_amount_usd = 0.0;
- m.turn_count = 1;
- write_transcript(
- &raw.join(format!("{stem}.jsonl")),
- &sample_messages(),
- &m,
- None,
- )
- .unwrap();
- };
- sub("1700000000_main__1700000001_coder", "coder", 300, 60);
- sub("1700000000_main__1700000002_coder", "coder", 100, 20);
- sub(
- "1700000000_main__1700000003_researcher",
- "researcher",
- 500,
- 90,
- );
-
- let s = read_thread_usage_summary(ws.path(), "thr-sub").expect("summary present");
- // Root totals are orchestrator-only (sub-agents are separate).
- assert_eq!(s.input_tokens, 1000);
- assert_eq!(s.output_tokens, 200);
- // Grouped by archetype.
- assert_eq!(s.subagents.len(), 2);
- let coder = s
- .subagents
- .iter()
- .find(|g| g.agent_id == "coder")
- .expect("coder group");
- assert_eq!(coder.input_tokens, 400);
- assert_eq!(coder.output_tokens, 80);
- assert_eq!(coder.runs, 2);
- let researcher = s
- .subagents
- .iter()
- .find(|g| g.agent_id == "researcher")
- .expect("researcher group");
- assert_eq!(researcher.input_tokens, 500);
- assert_eq!(researcher.runs, 1);
-}
-
-/// Pure extension across turns: the model-context read reflects the final
-/// (growing) message set and never rewrites earlier lines.
-#[test]
-fn append_pure_extension_grows_context() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("append.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
-
- let turn1 = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("hi"),
- ChatMessage::assistant("hello"),
- ];
- h.turn(&turn1, &meta, None, None);
-
- let mut turn2 = turn1.clone();
- turn2.push(ChatMessage::user("again"));
- turn2.push(ChatMessage::assistant("hello again"));
- h.turn(&turn2, &meta, None, None);
-
- let loaded = read_transcript(&path).unwrap();
- assert_eq!(
- roles(&loaded.messages),
- vec!["system", "user", "assistant", "user", "assistant"]
- );
- assert_eq!(loaded.messages[4].content, "hello again");
-}
-
-/// Compaction round-trip: after a reduction, the model-context read returns the
-/// REDUCED context, while the display read returns the FULL pre-compaction
-/// history plus the compaction marker.
-#[test]
-fn compaction_round_trip_model_vs_display() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("compact.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
-
- // Three growing turns.
- let base = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("q1"),
- ChatMessage::assistant("a1"),
- ChatMessage::user("q2"),
- ChatMessage::assistant("a2"),
- ];
- h.turn(&base, &meta, None, None);
-
- // A reduction: the harness drops the earliest exchange and keeps a summary
- // + the recent tail. This is NOT a prefix of `base`, so it must land as a
- // compaction record.
- let reduced = vec![
- ChatMessage::system("sys"),
- ChatMessage::assistant("[summary] earlier discussion about q1/q2"),
- ChatMessage::user("q3"),
- ChatMessage::assistant("a3"),
- ];
- h.turn(&reduced, &meta, None, None);
-
- // Model-context read == the reduced set only.
- let model = read_transcript(&path).unwrap();
- assert_eq!(
- model
- .messages
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec![
- "sys",
- "[summary] earlier discussion about q1/q2",
- "q3",
- "a3"
- ],
- "model context must reflect the reduced set after compaction"
- );
-
- // Display read == full history: the 5 pre-compaction messages, then a
- // compaction marker carrying the 4-message replacement.
- let display = read_transcript_display(&path).unwrap();
- let pre: Vec<&str> = display
- .records
- .iter()
- .take_while(|r| matches!(r, DisplayRecord::Message(_)))
- .filter_map(|r| match r {
- DisplayRecord::Message(m) => Some(m.message.content.as_str()),
- _ => None,
- })
- .collect();
- assert_eq!(pre, vec!["sys", "q1", "a1", "q2", "a2"]);
- let marker = display
- .records
- .iter()
- .find_map(|r| match r {
- DisplayRecord::Compaction(c) => Some(c),
- _ => None,
- })
- .expect("display must retain the compaction marker");
- assert_eq!(marker.replacement.len(), 4);
- assert_eq!(
- marker.replacement[1].message.content,
- "[summary] earlier discussion about q1/q2"
- );
-}
-
-/// After a compaction, a subsequent pure extension appends normally and the
-/// model-context read replays reset-then-extend to the correct final set.
-#[test]
-fn append_after_compaction_extends_reduced_set() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("compact_then_extend.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
-
- h.turn(
- &[
- ChatMessage::system("sys"),
- ChatMessage::user("q1"),
- ChatMessage::assistant("a1"),
- ],
- &meta,
- None,
- None,
- );
- let reduced = vec![
- ChatMessage::system("sys"),
- ChatMessage::assistant("[summary]"),
- ];
- h.turn(&reduced, &meta, None, None);
- let mut extended = reduced.clone();
- extended.push(ChatMessage::user("q2"));
- extended.push(ChatMessage::assistant("a2"));
- h.turn(&extended, &meta, None, None);
-
- let model = read_transcript(&path).unwrap();
- assert_eq!(
- model
- .messages
- .iter()
- .map(|m| m.content.as_str())
- .collect::<Vec<_>>(),
- vec!["sys", "[summary]", "q2", "a2"]
- );
-}
-
-/// request_id turn-boundary stamping round-trips into the display projection on
-/// every appended line of a turn.
-#[test]
-fn request_id_stamped_on_every_line() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("reqid.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
-
- let turn1 = vec![ChatMessage::system("sys"), ChatMessage::user("q1")];
- h.turn(&turn1, &meta, None, Some("req-1"));
-
- let mut turn2 = turn1.clone();
- turn2.push(ChatMessage::assistant("a2"));
- h.turn(&turn2, &meta, None, Some("req-2"));
-
- let display = read_transcript_display(&path).unwrap();
- let msgs: Vec<&DisplayMessage> = display
- .records
- .iter()
- .filter_map(|r| match r {
- DisplayRecord::Message(m) => Some(m),
- _ => None,
- })
- .collect();
- // turn1 wrote sys + user with req-1; turn2 appended only the assistant tail
- // with req-2.
- assert_eq!(msgs[0].request_id.as_deref(), Some("req-1"));
- assert_eq!(msgs[1].request_id.as_deref(), Some("req-1"));
- assert_eq!(msgs[2].request_id.as_deref(), Some("req-2"));
- assert_eq!(msgs[2].message.content, "a2");
-}
-
-/// #6282: rows read back from a transcript and persisted into a fresh file (a
-/// resume into a rebuilt agent) keep the request they were first written under
-/// and their tool-failure flag; only the resuming turn's own rows take its
-/// request id.
-#[test]
-fn resumed_rows_keep_their_request_id_and_failure_flag() {
- let dir = TempDir::new().unwrap();
- let meta = sample_meta();
-
- let mut failed_tool =
- ChatMessage::tool(r#"{"tool_call_id":"call-1","content":"install failed"}"#);
- attach_tool_failure_metadata(&mut failed_tool, Some("install failed"));
- let first = dir.path().join("first.jsonl");
- let turn1 = vec![
- ChatMessage::system("sys"),
- ChatMessage::user("install it"),
- failed_tool,
- ChatMessage::assistant("it failed"),
- ];
- AppendHarness::new(first.clone()).turn(&turn1, &meta, None, Some("req-1"));
-
- // Resume into a rebuilt agent: the prior rows come back through the
- // model-context reader and are persisted into a new file with the next turn.
- let mut resumed = read_transcript(&first).unwrap().messages;
- resumed.push(ChatMessage::user("what happened?"));
- let second = dir.path().join("second.jsonl");
- AppendHarness::new(second.clone()).turn(&resumed, &meta, None, Some("req-2"));
-
- let msgs: Vec<DisplayMessage> = read_transcript_display(&second)
- .unwrap()
- .records
- .into_iter()
- .filter_map(|r| match r {
- DisplayRecord::Message(m) => Some(m),
- _ => None,
- })
- .collect();
- let ids: Vec<Option<&str>> = msgs.iter().map(|m| m.request_id.as_deref()).collect();
- assert_eq!(
- ids,
- vec![
- Some("req-1"),
- Some("req-1"),
- Some("req-1"),
- Some("req-1"),
- Some("req-2")
- ],
- "replayed rows keep the request that wrote them"
- );
- let tool = msgs
- .iter()
- .find(|m| m.message.role == "tool")
- .expect("replayed tool row");
- assert!(tool.failure, "a replayed failed tool row stays failed");
- assert_eq!(tool.failure_detail.as_deref(), Some("install failed"));
- // The markers are an in-memory side-channel: neither reaches the file.
- let raw = fs::read_to_string(&second).unwrap();
- assert!(
- !raw.contains("openhuman_replayed") && !raw.contains("openhuman_tool_failure"),
- "side-channel markers must not be persisted: {raw}"
- );
-}
-
-/// An interrupted partial is appended to the file, is visible in the display
-/// read flagged `interrupted`, and is SKIPPED by the model-context read (a
-/// resumed context never carries a truncated answer).
-#[test]
-fn interrupted_partial_display_only() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("interrupted.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
- h.turn(
- &[ChatMessage::system("sys"), ChatMessage::user("q1")],
- &meta,
- None,
- Some("req-1"),
- );
-
- append_interrupted_partial(
- &path,
- "partial answer that was cut off",
- Some("req-1"),
- Some(3),
- Some("thinking that was cut off"),
- )
- .expect("append interrupted");
-
- // Model context: the partial is skipped.
- let model = read_transcript(&path).unwrap();
- assert_eq!(roles(&model.messages), vec!["system", "user"]);
- assert!(
- !model.messages.iter().any(|m| m.content.contains("cut off")),
- "interrupted partial must NOT enter the model context"
- );
-
- // Display: the partial is present and flagged.
- let display = read_transcript_display(&path).unwrap();
- let partial = display
- .records
- .iter()
- .find_map(|r| match r {
- DisplayRecord::Message(m) if m.interrupted => Some(m),
- _ => None,
- })
- .expect("display must include the interrupted partial");
- assert_eq!(partial.message.content, "partial answer that was cut off");
- assert_eq!(partial.request_id.as_deref(), Some("req-1"));
- assert_eq!(partial.iteration, Some(3));
- assert_eq!(
- partial.reasoning_content.as_deref(),
- Some("thinking that was cut off"),
- "interrupted partial must carry its reasoning_content"
- );
-}
-
-/// Empty partial content is a no-op — no line is written.
-#[test]
-fn interrupted_partial_empty_is_noop() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("empty_interrupt.jsonl");
- let meta = sample_meta();
- let mut h = AppendHarness::new(path.clone());
- h.turn(&[ChatMessage::user("q")], &meta, None, None);
- append_interrupted_partial(&path, "", None, None, None).expect("noop");
- let display = read_transcript_display(&path).unwrap();
- assert!(display
- .records
- .iter()
- .all(|r| matches!(r, DisplayRecord::Message(m) if !m.interrupted)));
-}
-
-/// A legacy file — one produced by the full-rewrite `write_transcript` with no
-/// compaction records and no `version` — reads identically under both the
-/// model-context and display readers.
-#[test]
-fn legacy_file_reads_identically() {
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("legacy.jsonl");
- let messages = sample_messages();
- let meta = sample_meta();
- // Full-rewrite writer == the legacy shape (append-only readers must tolerate
- // it: zero compaction records, last `_meta` == the only `_meta`).
- write_transcript(&path, &messages, &meta, None).unwrap();
-
- let model = read_transcript(&path).unwrap();
- assert_eq!(model.messages.len(), messages.len());
- assert_eq!(roles(&model.messages), roles(&messages));
-
- let display = read_transcript_display(&path).unwrap();
- let display_roles: Vec<&str> = display
- .records
- .iter()
- .filter_map(|r| match r {
- DisplayRecord::Message(m) => Some(m.message.role.as_str()),
- _ => None,
- })
- .collect();
- assert_eq!(display_roles, roles(&messages));
-}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core.rs b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
index dcbdbc1cee..f597586608 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
@@ -143,7 +143,7 @@ fn stamp_tool_failures(
messages: &mut [ChatMessage],
tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
) {
- use crate::agent::harness::session::transcript;
+ use tinyagents_session::transcript;
if tool_outcomes.is_empty() {
return;
}
@@ -165,7 +165,9 @@ fn stamp_tool_failures(
"[transcript] stamping tool failure call_id={call_id} name={}",
outcome.name
);
- transcript::attach_tool_failure_metadata(msg, detail.as_deref());
+ let mut durable = crate::agent::messages::transcript_message_from_chat(msg);
+ transcript::attach_tool_failure_metadata(&mut durable, detail.as_deref());
+ *msg = crate::agent::messages::chat_message_from_transcript(durable);
}
}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
index c88d9c7390..5b516f7d50 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
@@ -1,6 +1,5 @@
//! Keeping what a failed chat turn did (#6281).
-use crate::agent::harness::session::transcript::{MessageUsage, TurnUsage};
use crate::agent::harness::session::turn_checkpoint::{truncate_chars, CHECKPOINT_RESULT_CHARS};
use crate::agent::harness::session::types::Agent;
use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
@@ -9,6 +8,7 @@ use crate::agent::tinyagents::{
render_unanswered_steps, TranscriptSnapshot, TranscriptSnapshotSink,
};
use anyhow::Result;
+use tinyagents_session::transcript::{MessageUsage, TurnUsage};
use tinyinference_llm::message::Message;
/// Leads the note a failed turn leaves in history, so the model (and a reader
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
index 552c0d174e..507edc2600 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
@@ -475,12 +475,12 @@ impl Agent {
// `provider`/`model` from every transcript (they are `TranscriptMeta`
// fields sourced from the turn usage) — parity with the legacy engine,
// which handed `self.last_turn_usage.as_ref()` to this call.
- let turn_usage = crate::agent::harness::session::transcript::TurnUsage {
+ let turn_usage = tinyagents_session::transcript::TurnUsage {
provider: self.event_channel().to_string(),
// The model that actually ran this turn (a per-turn override can
// diverge from `self.model_name`); attribute usage to it.
model: effective_model.to_string(),
- usage: crate::agent::harness::session::transcript::MessageUsage {
+ usage: tinyagents_session::transcript::MessageUsage {
input: input_tokens,
output: output_tokens,
cached_input: cached_input_tokens,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs
index 35999d03fc..f73d4fa643 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/resumed_prefix.rs
@@ -80,8 +80,11 @@ impl Agent {
self.history = cached
.into_iter()
.map(|mut message| {
- crate::agent::harness::session::transcript::mark_replayed_if_unmarked(&mut message);
- ConversationMessage::Chat(message)
+ let mut durable = crate::agent::messages::transcript_message_from_chat(&message);
+ tinyagents_session::transcript::mark_replayed_if_unmarked(&mut durable);
+ ConversationMessage::Chat(crate::agent::messages::chat_message_from_transcript(
+ durable,
+ ))
})
.chain(tail)
.collect();
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs b/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
index 324c30ee5f..8d108d9967 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
@@ -246,8 +246,6 @@ pub(super) fn sanitize_learned_entry(content: &str) -> String {
sanitized
}
-#[cfg(test)]
-pub(crate) use super::transcript;
#[cfg(test)]
pub(crate) use super::turn_checkpoint::assistant_message_has_tool_calls;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs
index 4fd046b6b9..8b2b70e76b 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_load.rs
@@ -1,10 +1,9 @@
//! Loading a prior session transcript for KV-cache resume, and the locator
//! that finds it.
-use crate::agent::harness::session::transcript_history::{
- FileTranscriptLocator, SessionHistoryLocator,
-};
use crate::agent::harness::session::types::Agent;
+use crate::agent::messages::chat_message_from_transcript;
+use tinyagents_session::transcript::{FileTranscriptLocator, TranscriptLocator};
impl Agent {
// ─────────────────────────────────────────────────────────────────
@@ -18,10 +17,10 @@ impl Agent {
/// # How this reaches the transcript (S4)
///
/// Both halves of the turn path now go through the seam: writes through
- /// [`SessionHistory::append_turn`][crate::agent::harness::session::transcript_history::SessionHistory::append_turn],
+ /// [`TranscriptHistory::append_turn`][tinyagents_session::transcript::TranscriptHistory::append_turn],
/// reads through
- /// [`SessionHistoryLocator`][crate::agent::harness::session::transcript_history::SessionHistoryLocator]
- /// + [`SessionTranscriptRead::read_session`][crate::agent::harness::session::transcript_history::SessionTranscriptRead::read_session].
+ /// [`TranscriptLocator`][tinyagents_session::transcript::TranscriptLocator]
+ /// + [`TranscriptRead::read_session`][tinyagents_session::transcript::TranscriptRead::read_session].
///
/// The read is **not** `ChatHistory::messages()`, and that is settled, not
/// pending: `messages()` returns `Vec<Message>`, and converting back with
@@ -31,7 +30,7 @@ impl Agent {
/// TAURI-RUST-7 trailing strip inspects, and re-sending a flattened prefix
/// to a native provider is the `400 assistant message with 'tool_calls'
/// must be followed by tool messages` failure that strip exists to prevent.
- /// `read_session` returns the whole [`SessionTranscript`][crate::agent::harness::session::transcript::SessionTranscript]
+ /// `read_session` returns the whole [`SessionTranscript`][tinyagents_session::transcript::SessionTranscript]
/// instead — the same struct the free function returns, from the same
/// `read_transcript` call — so compaction replay, `interrupted: true`
/// partial skipping and the `_meta` header
@@ -80,7 +79,12 @@ impl Agent {
// legacy transcript just loaded stays authoritative and
// is what feeds the resume below. Gated OFF by default.
self.maybe_shadow_read_session_store(&path, &session);
- let bounded = self.bound_cached_transcript_messages(session.messages);
+ let replay = session
+ .messages
+ .into_iter()
+ .map(chat_message_from_transcript)
+ .collect();
+ let bounded = self.bound_cached_transcript_messages(replay);
if bounded.len() < loaded_count {
log::warn!(
"[transcript] resume prefix trimmed from {} to {} messages (max_history_messages={})",
@@ -107,7 +111,7 @@ impl Agent {
/// `build()` (tests do exactly that), and a locator frozen at build time
/// would silently keep resolving against the directory the agent no longer
/// uses.
- pub(crate) fn session_locator(&self) -> std::sync::Arc<dyn SessionHistoryLocator> {
+ pub(crate) fn session_locator(&self) -> std::sync::Arc<dyn TranscriptLocator> {
match &self.session_history_locator {
Some(locator) => locator.clone(),
None => std::sync::Arc::new(FileTranscriptLocator::new(self.workspace_dir.clone())),
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs
index dc52316e3d..947d6069b5 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs
@@ -1,10 +1,9 @@
//! Persisting the turn's provider messages as the session transcript, plus the
//! session-store dual-write / shadow-read mirrors.
-use crate::agent::harness::session::transcript;
-use crate::agent::harness::session::transcript_history::TranscriptTurn;
use crate::agent::harness::session::types::Agent;
-use crate::agent::messages::ChatMessage;
+use crate::agent::messages::{transcript_message_from_chat, ChatMessage};
+use tinyagents_session::transcript::{self, TranscriptTurn};
impl Agent {
/// Persist the exact provider messages as a session transcript.
@@ -108,25 +107,26 @@ impl Agent {
// so pre-compaction history survives on disk for the display projection.
// `request_id` (web-chat only) stamps a turn boundary on each line.
//
- // This goes through `SessionHistory::append_turn` rather than
+ // This goes through `TranscriptHistory::append_turn` rather than
// `transcript::append_transcript_turn` directly (S4). The handle is a
// pure forwarder of exactly these six values — it must be, because the
// crate's `ChatHistory` methods carry no channel for `request_id`,
// `turn_usage` or a caller-computed `TranscriptMeta`, and dropping any
// of them silently guts the transcript-view projection. See the header
- // of `transcript_history.rs` for the full argument.
+ // of `tinyagents_session::transcript::TranscriptHistory` for the full argument.
let prev = std::mem::take(&mut self.persisted_transcript_messages);
+ let next: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();
let request_id = crate::agent::turn_origin::current_request_id();
match history.append_turn(TranscriptTurn {
prev: &prev,
- next: messages,
+ next: &next,
meta: &meta,
turn_usage,
request_id: request_id.as_deref(),
}) {
Ok(()) => {
// Track the new persisted logical set for the next turn's diff.
- self.persisted_transcript_messages = messages.to_vec();
+ self.persisted_transcript_messages = next;
// Best-effort, non-fatal dual-write into the TinyAgents store.
// Gated by the default-ON session dual-write flag
// (`OPENHUMAN_SESSION_DUAL_WRITE` is a kill switch). Only runs
diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rs
index 86a22395e3..e881639f7a 100644
--- a/crates/openhuman-core/src/agent/harness/session/types.rs
+++ b/crates/openhuman-core/src/agent/harness/session/types.rs
@@ -254,13 +254,13 @@ pub struct Agent {
/// `session_transcript_path` on first write.
///
/// This is the S4 indirection: the turn path appends through
- /// [`SessionHistory::append_turn`][super::transcript_history::SessionHistory::append_turn]
+ /// [`TranscriptHistory::append_turn`][tinyagents_session::transcript::TranscriptHistory::append_turn]
/// rather than calling the format's free function directly.
///
/// It is `Arc<dyn …>` rather than the concrete handle so the turn loop is
/// written against the seam instead of the implementation. It is now
/// genuinely substitutable: the handle is produced by
- /// [`SessionHistoryLocator::open_stem`][super::transcript_history::SessionHistoryLocator::open_stem]
+ /// [`TranscriptLocator::open_stem`][tinyagents_session::transcript::TranscriptLocator::open_stem]
/// on the locator in `session_history_locator`, so injecting a locator
/// replaces this session's writes as well as both of its resume reads.
///
@@ -268,7 +268,7 @@ pub struct Agent {
/// into the handle: the dual-write mirror needs the concrete `&Path` for
/// `file_stem()`, and several tests assert on it directly.
pub(super) session_history:
- Option<std::sync::Arc<dyn super::transcript_history::SessionHistory>>,
+ Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptHistory>>,
/// Injected transcript locator, or `None` to use real files.
///
/// The single injection point for the whole transcript seam: it resolves
@@ -276,20 +276,21 @@ pub struct Agent {
/// session's write handle (`open_stem`). `None` is the production default
/// and is resolved *lazily* by
/// [`Agent::session_locator`][Self::session_locator] into a
- /// [`FileTranscriptLocator`][super::transcript_history::FileTranscriptLocator]
+ /// [`FileTranscriptLocator`][tinyagents_session::transcript::FileTranscriptLocator]
/// over the **current** `workspace_dir` — never
/// captured at build time, because callers (tests especially) reassign
/// `workspace_dir` after `build()` and a frozen locator would silently keep
/// reading the old directory.
pub(super) session_history_locator:
- Option<std::sync::Arc<dyn super::transcript_history::SessionHistoryLocator>>,
+ Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
/// The logical message set most recently persisted to
/// `session_transcript_path`, tracked in memory so the append-only writer
/// can diff each turn's messages against it (pure extension → append tail;
/// reduction → compaction record) without re-reading the growing file.
/// Empty until the first persist. Each process writes its own transcript
/// file, so this in-memory state is always aligned with the file it owns.
- pub(super) persisted_transcript_messages: Vec<ChatMessage>,
+ pub(super) persisted_transcript_messages:
+ Vec<tinyagents_session::transcript::TranscriptMessage>,
/// Unique transcript key for this session, formatted as
/// `"{unix_ts}_{agent_id}"`. Generated once at agent-build time so
/// every transcript write in this session uses the same filename
@@ -543,7 +544,7 @@ pub struct AgentBuilder {
/// [`with_session_history_locator`][super::builder::AgentBuilder::with_session_history_locator]
/// to substitute the transcript backing store for the whole turn path.
pub(super) session_history_locator:
- Option<std::sync::Arc<dyn super::transcript_history::SessionHistoryLocator>>,
+ Option<std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
/// Forwarded to [`Agent::omit_profile`] at `build()` time. Mirrors the
/// target definition's `omit_profile` flag; `None` means "fall back
/// to the safe default" (omit).
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
index b59af41085..37e36e4476 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/extract_tool.rs
@@ -29,11 +29,11 @@ use serde_json::{json, Value};
use tinyagents_graph::parallel::{map_reduce, FailurePolicy, ParallelOptions};
use super::handoff::{chunk_content, ResultHandoffCache, HANDOFF_MAX_ENTRIES};
-use crate::agent::harness::session::transcript::{
+use crate::agent::messages::{transcript_message_from_chat, ChatMessage};
+use crate::agent::tinyagents::TurnModelSource;
+use tinyagents_session::transcript::{
resolve_keyed_transcript_path, write_transcript, MessageUsage, TranscriptMeta, TurnUsage,
};
-use crate::agent::messages::ChatMessage;
-use crate::agent::tinyagents::TurnModelSource;
use tinyinference_llm::message::Message;
use tinyinference_llm::model::ModelRequest;
use tinytools::{Tool, ToolCallOptions, ToolCategory, ToolResult, ToolRunContext};
@@ -621,7 +621,8 @@ fn write_extract_transcript(
task_id: None,
};
- if let Err(e) = write_transcript(&path, &messages, &meta, Some(&turn_usage)) {
+ let durable_messages: Vec<_> = messages.iter().map(transcript_message_from_chat).collect();
+ if let Err(e) = write_transcript(&path, &durable_messages, &meta, Some(&turn_usage)) {
tracing::warn!(
error = %e,
path = %path.display(),
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
index 3beb31a4ae..117ddd605a 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
@@ -54,7 +54,7 @@ pub(super) fn persist_subagent_transcript(
dispatcher: &str,
iteration: u32,
) {
- use crate::agent::harness::session::transcript;
+ use tinyagents_session::transcript;
let path = match transcript::resolve_keyed_transcript_path(workspace_dir, transcript_stem) {
Ok(p) => p,
@@ -100,7 +100,13 @@ pub(super) fn persist_subagent_transcript(
thread_id: thread_id.map(str::to_owned),
task_id: Some(task_id.to_string()),
};
- if let Err(err) = transcript::write_transcript(&path, history, &meta, Some(&turn_usage)) {
+ let durable_history: Vec<_> = history
+ .iter()
+ .map(crate::agent::messages::transcript_message_from_chat)
+ .collect();
+ if let Err(err) =
+ transcript::write_transcript(&path, &durable_history, &meta, Some(&turn_usage))
+ {
tracing::debug!(
agent_id,
error = %err,
diff --git a/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs b/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
index 15d5d568df..0cbbac4a44 100644
--- a/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
+++ b/crates/openhuman-core/src/agent/learning/transcript_ingest/mod.rs
@@ -43,10 +43,10 @@ pub use types::{
CONVERSATION_REFLECTIONS_NAMESPACE,
};
-use crate::agent::harness::session::transcript::{self, SessionTranscript};
use crate::memory::Memory;
use futures::stream::StreamExt;
use std::path::Path;
+use tinyagents_session::transcript::{self, SessionTranscript};
/// Max number of persist round-trips (markdown write + SQLite tx + embedding)
/// kept in flight at once during ingestion. Bounds provider load so a
diff --git a/crates/openhuman-core/src/agent/messages.rs b/crates/openhuman-core/src/agent/messages.rs
index c04545e8ca..e9d262dafa 100644
--- a/crates/openhuman-core/src/agent/messages.rs
+++ b/crates/openhuman-core/src/agent/messages.rs
@@ -28,6 +28,37 @@ pub struct ChatMessage {
pub cache_breakpoints: Vec<usize>,
}
+/// Convert the host's provider-facing record into the neutral durable
+/// transcript record. This is intentionally a field-for-field conversion at
+/// the host boundary: `tinyagents-session` must not know OpenHuman's runtime
+/// message type, while no provider metadata may be discarded before durable
+/// persistence.
+pub(crate) fn transcript_message_from_chat(
+ message: &ChatMessage,
+) -> tinyagents_session::transcript::TranscriptMessage {
+ tinyagents_session::transcript::TranscriptMessage {
+ id: message.id.clone(),
+ role: message.role.clone(),
+ content: message.content.clone(),
+ extra_metadata: message.extra_metadata.clone(),
+ cache_breakpoints: message.cache_breakpoints.clone(),
+ }
+}
+
+/// Convert a neutral durable transcript row back into the host's provider
+/// message shape after the lossless transcript reader has completed replay.
+pub(crate) fn chat_message_from_transcript(
+ message: tinyagents_session::transcript::TranscriptMessage,
+) -> ChatMessage {
+ ChatMessage {
+ id: message.id,
+ role: message.role,
+ content: message.content,
+ extra_metadata: message.extra_metadata,
+ cache_breakpoints: message.cache_breakpoints,
+ }
+}
+
impl ChatMessage {
pub fn system(content: impl Into<String>) -> Self {
Self {
diff --git a/crates/openhuman-core/src/agent/session_import/convert.rs b/crates/openhuman-core/src/agent/session_import/convert.rs
index f1d08f1833..681fd14cd4 100644
--- a/crates/openhuman-core/src/agent/session_import/convert.rs
+++ b/crates/openhuman-core/src/agent/session_import/convert.rs
@@ -1,7 +1,7 @@
//! Pure conversion helpers: stem lineage, stream naming, descriptor
//! assembly, and message-record projection.
-use crate::agent::harness::session::transcript::SessionTranscript;
+use tinyagents_session::transcript::SessionTranscript;
use super::types::{
DescriptorImport, DescriptorSource, DescriptorUsage, JournalMessage, SessionDescriptor,
diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rs
index edd4f380c7..727bc27837 100644
--- a/crates/openhuman-core/src/agent/session_import/live.rs
+++ b/crates/openhuman-core/src/agent/session_import/live.rs
@@ -24,7 +24,7 @@ use std::sync::Arc;
use anyhow::{Context, Result};
use tinyagents_harness::store::{AppendStore, Store};
-use crate::agent::harness::session::transcript::SessionTranscript;
+use tinyagents_session::transcript::SessionTranscript;
use super::convert::{
build_descriptor, effective_thread_id, journal_messages, sanitize_store_name, stream_name,
diff --git a/crates/openhuman-core/src/agent/session_import/ops.rs b/crates/openhuman-core/src/agent/session_import/ops.rs
index 276f17b4c8..abfdd47b65 100644
--- a/crates/openhuman-core/src/agent/session_import/ops.rs
+++ b/crates/openhuman-core/src/agent/session_import/ops.rs
@@ -17,7 +17,7 @@ use serde_json::json;
use sha2::{Digest, Sha256};
use tinyagents_harness::store::{AppendStore, FileStore, JsonlAppendStore, Store};
-use crate::agent::harness::session::transcript::{
+use tinyagents_session::transcript::{
read_transcript, read_transcript_legacy_md, SessionTranscript,
};
diff --git a/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs b/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
index 8e40221fac..59e40c1bce 100644
--- a/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
+++ b/crates/openhuman-core/src/config/migrations/phase_out_profile_md.rs
@@ -4,7 +4,7 @@
//! `PROFILE.md` is being retired as a system-prompt injection. Earlier
//! builds wrote the file into the system prompt of every session and
//! froze those bytes inside `session_raw/{stem}.jsonl` (see
-//! [`crate::agent::harness::session::transcript`]). Without
+//! [`tinyagents_session::transcript`]). Without
//! this migration, an upgrade leaves the leaked content replaying
//! inside every resumed thread forever — the runtime loader reuses the
//! persisted system message verbatim for KV-cache stability.
@@ -46,10 +46,10 @@
//! migration short-circuits without scanning. The caller still bumps
//! `schema_version` so future launches don't re-check.
-use crate::agent::harness::session::transcript::{self, SessionTranscript};
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
+use tinyagents_session::transcript::{self, SessionTranscript};
/// Line that opens a `PROFILE.md` block in a system prompt. Matches the
/// output of `inject_workspace_file_capped` in `agent/prompts/mod.rs`.
@@ -155,7 +155,7 @@ pub fn run(workspace_dir: &Path) -> Result<PhaseOutStats> {
///
/// **Layout assumption (one level deep).** The walk descends exactly one
/// level — into `sessions/<date>/*.md` — matching the layout produced
-/// by [`crate::agent::harness::session::transcript`]
+/// by [`tinyagents_session::transcript`]
/// (`sessions/YYYY_MM_DD/{stem}.md` for the new format, legacy
/// `sessions/DDMMYYYY/{stem}.md` for the date-grouped fallback). The
/// JSONL walk in [`collect_jsonl_transcripts`] makes the same
diff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rs
index 169fb1169a..6ed1106ae9 100644
--- a/crates/openhuman-core/src/threads/ops/usage.rs
+++ b/crates/openhuman-core/src/threads/ops/usage.rs
@@ -51,10 +51,8 @@ pub async fn token_usage(
request: ThreadTokenUsageRequest,
) -> Result<RpcOutcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {
let dir = workspace_dir().await?;
- let summary = crate::agent::harness::session::transcript::read_thread_usage_summary(
- &dir,
- &request.thread_id,
- );
+ let summary =
+ tinyagents_session::transcript::read_thread_usage_summary(&dir, &request.thread_id);
// Re-audit cost at CURRENT pricing rather than trusting the
// `charged_amount_usd` persisted in the transcript: those values were
diff --git a/crates/openhuman-core/src/threads/transcript_view/project.rs b/crates/openhuman-core/src/threads/transcript_view/project.rs
index 8a3aa1eebf..912dc54fe1 100644
--- a/crates/openhuman-core/src/threads/transcript_view/project.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/project.rs
@@ -9,9 +9,7 @@ use std::collections::VecDeque;
use std::fs;
use std::path::{Path, PathBuf};
-use crate::agent::harness::session::transcript::{
- self, CompactionMarker, DisplayMessage, DisplayRecord,
-};
+use tinyagents_session::transcript::{self, CompactionMarker, DisplayMessage, DisplayRecord};
use super::types::{DisplayItem, ProjectedTranscript, ToolCallFailure, ToolCallStatus};
diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs b/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
index 4ad8ba0e07..7bca9f5d48 100644
--- a/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
+++ b/crates/openhuman-core/src/threads/turn_state/mirror/lifecycle.rs
@@ -41,12 +41,10 @@ impl TurnStateMirror {
return;
}
let workspace_dir = self.store.workspace_dir();
- let Some(path) =
- crate::agent::harness::session::transcript::find_root_transcript_for_thread(
- workspace_dir,
- thread_id,
- )
- else {
+ let Some(path) = tinyagents_session::transcript::find_root_transcript_for_thread(
+ workspace_dir,
+ thread_id,
+ ) else {
log::debug!(
"{MIRROR_LOG_PREFIX} no root transcript for thread={thread_id} yet — leaving interrupted partial ({} chars) in turn_state snapshot only",
partial.len()
@@ -64,7 +62,7 @@ impl TurnStateMirror {
} else {
Some(thinking)
};
- match crate::agent::harness::session::transcript::append_interrupted_partial(
+ match tinyagents_session::transcript::append_interrupted_partial(
&path,
partial,
request_id,
diff --git a/docs/plans/migrate-agent-sessions-to-tinyagents-session.md b/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
index 077b29302b..5b69a59f15 100644
--- a/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
+++ b/docs/plans/migrate-agent-sessions-to-tinyagents-session.md
@@ -30,8 +30,8 @@ Add these public modules to `tinyagents-session`:
```text
transcript::{
- TranscriptMeta, SessionTranscript, DisplaySessionTranscript,
- TranscriptRecord, TurnUsage, MessageUsage, ChatHistory,
+ TranscriptMeta, TranscriptMessage, TranscriptToolCall, SessionTranscript,
+ DisplaySessionTranscript, TranscriptRecord, TurnUsage, MessageUsage,
TranscriptHistory, TranscriptRead, TranscriptLocator,
read_transcript, read_transcript_display, write_transcript,
append_turn, compact_context, transcript_path, latest_for_agent,
@@ -39,15 +39,16 @@ transcript::{
}
```
-Use `tinyinference_llm::message::Message` and its tool-call representation for
-the persisted model transcript. If an OpenHuman-only field is needed, expose a
-small caller-owned metadata JSON value rather than naming `ChatMessage` or an
-OpenHuman type. Keep stable JSONL `kind` tags forward-compatible: unknown
-records are skipped, not fatal. `tinyagents-session` may depend on
-`tinyinference-llm`, `tinyagents-harness` only for its error/`ChatHistory`
-contract (or relocate that contract to session to avoid an upward dependency),
-serde, serde_json, chrono and std I/O. It must not depend on graph or the new
-orchestration crate.
+Use the neutral `TranscriptMessage`/`TranscriptToolCall` durable model, not a
+`tinyinference_llm::message::Message` or `ChatHistory` conversion. The durable
+model preserves raw tool argument strings (including malformed streamed JSON),
+opaque provider `extra_content`, tool-result correlation ids, usage, thinking,
+trusted/verbatim metadata and caller-owned JSON metadata. Runtime-message
+conversion is an explicit host-boundary operation after read / before write.
+Keep stable JSONL `kind` tags forward-compatible: unknown records are skipped,
+not fatal. `tinyagents-session` may depend on serde, serde_json, chrono and
+std I/O (and its existing shared error substrate), but must not depend on graph,
+the new orchestration crate, or a provider dialect for transcript persistence.
OpenHuman replaces its local types and helpers with direct imports, then
implements only an adapter at the existing host boundary where conversion from
@@ -80,8 +81,10 @@ ignored; malformed required records fail; append writes only deltas; and path
derivation is deterministic.
**GREEN:** Add `transcript/{types,jsonl,metadata,paths,reader,writer}.rs` and
-the public API above. Use crate-native message types. Do not change established
-OpenHuman file bytes in this slice.
+the public API above. `TranscriptMessage` is deliberately neutral and
+lossless; do not add a public convenience conversion through a narrower
+provider/harness message. Do not change established OpenHuman file bytes in
+this slice.
### S2 — history, compaction, and discovery
diff --git a/vendor/tinyagents b/vendor/tinyagents
index a495ecdf8f..47b6cc1cae 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit a495ecdf8f3903304c45dbac21d0417dfa100330
+Subproject commit 47b6cc1caecc6779aef22174118a53afa78fb215