The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge remote-tracking branch 'upstream/main' into agent-turn-transcript
Steven Enamakeldf9a7566ceed
diff --cc src/openhuman/agent/harness/session/transcript_part_01.rsindex 0000000000,41e1e8e3a2..0dddcefa4dmode 000000,100644..100644--- a/src/openhuman/agent/harness/session/transcript_part_01.rs+++ b/src/openhuman/agent/harness/session/transcript_part_01.rs@@@ -1,0 -1,640 +1,668 @@@+ use crate::openhuman::agent::messages::ChatMessage;+ use crate::openhuman::inference::provider::ToolCall;+ use anyhow::{Context, Result};+ use serde::{Deserialize, Serialize};+ use std::collections::{BTreeMap, HashMap};+ use std::fmt::Write as FmtWrite;+ use std::fs;+ use std::path::{Path, PathBuf};++ // ── Types ────────────────────────────────────────────────────────────++ /// 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,+ }++ 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";++ /// 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()),+ );+ }+ let marker = serde_json::Value::Object(payload);++ match message.extra_metadata.take() {+ Some(serde_json::Value::Object(mut map)) => {+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ Some(existing) => {+ let mut map = serde_json::Map::new();+ map.insert("value".to_string(), existing);+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ None => {+ let mut map = serde_json::Map::new();+ map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ }+ }++ /// 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`.+ fn take_tool_failure(extra: &mut Option<serde_json::Value>) -> Option<(bool, Option<String>)> {+ let serde_json::Value::Object(map) = extra.as_mut()? else {+ return None;+ };+ let marker = map.remove(TOOL_FAILURE_METADATA_KEY)?;+ // If removing the marker emptied the object, drop `extra_metadata` entirely+ // so a legacy-identical line stays legacy-identical.+ if map.is_empty() {+ *extra = None;+ }+ let detail = marker+ .get("detail")+ .and_then(|d| d.as_str())+ .map(str::to_string);+ Some((true, detail))+ }++ /// 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;++ /// Discriminator value for a compaction record's `kind` field.+ const COMPACTION_KIND: &str = "compaction";++ #[allow(clippy::trivially_copy_pass_by_ref)]+ fn is_false(b: &bool) -> bool {+ !*b+ }++ 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;+ };++ match message.extra_metadata.take() {+ Some(serde_json::Value::Object(mut map)) => {+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ Some(existing) => {+ let mut map = serde_json::Map::new();+ map.insert("value".to_string(), existing);+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ None => {+ let mut map = serde_json::Map::new();+ map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);+ message.extra_metadata = Some(serde_json::Value::Object(map));+ }+ }+ }++ 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+ }++ 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()+ }++ /// 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>,+ }++ // ── Internal JSONL types ─────────────────────────────────────────────++ /// The `_meta` line serialisation shape.+ #[derive(Serialize, Deserialize)]+ struct MetaLine {+ #[serde(rename = "_meta")]+ meta: MetaPayload,+ }++ #[derive(Serialize, Deserialize)]+ 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)]+ version: u32,+ agent: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ agent_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ agent_type: Option<String>,+ dispatcher: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ provider: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ model: Option<String>,+ created: String,+ updated: String,+ turn_count: usize,+ input_tokens: u64,+ output_tokens: u64,+ cached_input_tokens: u64,+ charged_amount_usd: f64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ thread_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ 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)]+ struct MessageLine {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ id: Option<String>,+ role: String,+ content: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ extra_metadata: Option<serde_json::Value>,+ #[serde(skip_serializing_if = "Option::is_none")]+ provider: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ model: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ usage: Option<MessageUsage>,+ #[serde(skip_serializing_if = "Option::is_none")]+ reasoning_content: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tool_calls: Option<Vec<ToolCall>>,+ #[serde(skip_serializing_if = "Option::is_none")]+ iteration: Option<u32>,+ #[serde(skip_serializing_if = "Option::is_none")]+ 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")]+ 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")]+ 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")]+ 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")]+ failure_detail: Option<String>,+ /// Absorb any unknown fields so forward-compat reads don't error.+ #[serde(flatten)]+ _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)]+ struct CompactionLine {+ kind: String,+ replacement: Vec<MessageLine>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ ts: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ request_id: Option<String>,+ #[serde(flatten)]+ _extra: HashMap<String, serde_json::Value>,+ }++ // ── 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>,+ }++ // ── Write ─────────────────────────────────────────────────────────────++ /// 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(),+ }+ }++ 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.+ 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),+ };++ let message_reasoning = (msg.role == "assistant")++ .then(|| {++ extra_metadata++ .as_ref()++ .and_then(|meta| {++ meta.get(crate::openhuman::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: assistant_usage.and_then(|tu| tu.reasoning_content.clone()),- tool_calls: assistant_usage.and_then(|tu| {- if tu.tool_calls.is_empty() {- None- } else {- Some(tu.tool_calls.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: request_id.map(str::to_string),+ 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.+ 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(())+ }++ /// 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(())+ }diff --cc src/openhuman/agent/harness/session/transcript_part_02.rsindex 0000000000,66c84d2e9e..2066c4c278mode 000000,100644..100644--- a/src/openhuman/agent/harness/session/transcript_part_02.rs+++ b/src/openhuman/agent/harness/session/transcript_part_02.rs@@@ -1,0 -1,616 +1,631 @@@++ /// 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()+ );+ }++ // ── Read ─────────────────────────────────────────────────────────────++ /// 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)+ }+ }+ }++ /// Convert a parsed `MetaPayload` into the public [`TranscriptMeta`].+ 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.+ fn message_from_line(ml: MessageLine) -> ChatMessage {+ let turn_usage = turn_usage_from_line(&ml);+ let mut message = ChatMessage {+ id: ml.id,+ role: ml.role,+ content: ml.content,+ extra_metadata: ml.extra_metadata,+ };+ if let Some(turn_usage) = turn_usage.as_ref() {+ attach_turn_usage_metadata(&mut message, turn_usage);+ }+ message+ }++ /// Classification of one non-empty JSONL line.+ 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).+ 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)+ }++ 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 })+ }++ // ── Display read ──────────────────────────────────────────────────────++ /// Reconstruct a [`DisplayMessage`] from a message line, preserving the+ /// turn-boundary + partial flags the model-context path discards.+ 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,+ },+ }+ }++ /// 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 })+ }++ /// Find the newest root transcript whose metadata declares `thread_id`, across+ /// the shared `session_raw/` store and every profile-scoped+ /// `session_raw-<id>/` store.+ ///+ /// 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> {- raw_session_dirs(workspace_dir)- .into_iter()- .filter_map(|raw_dir| find_root_transcript_for_thread_in_dir(&raw_dir, thread_id))- .max_by(|left, right| left.file_name().cmp(&right.file_name()))++ find_root_transcripts_for_thread(workspace_dir, thread_id).pop()++}++++pub fn find_root_transcripts_for_thread(++ workspace_dir: &Path,++ thread_id: &str,++) -> Vec<PathBuf> {++ let mut matches = Vec::new();++ for raw_dir in raw_session_dirs(workspace_dir) {++ matches.extend(root_transcripts_for_thread_in_dir(&raw_dir, thread_id));++ }++ matches.sort_by(|left, right| left.file_name().cmp(&right.file_name()));++ matches+ }++ fn raw_session_dirs(workspace_dir: &Path) -> Vec<PathBuf> {+ let mut raw_dirs = vec![raw_session_dir(workspace_dir)];+ if let Ok(entries) = fs::read_dir(workspace_dir) {+ raw_dirs.extend(entries.flatten().map(|entry| entry.path()).filter(|path| {+ path.is_dir()+ && path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| {+ name.strip_prefix("session_raw-")+ .is_some_and(|suffix| !suffix.is_empty())+ })+ }));+ }+ raw_dirs.sort();+ raw_dirs+ }++ 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 None;++ return Vec::new();+ }+- let entries = fs::read_dir(raw_dir).ok()?;++ let Ok(entries) = fs::read_dir(raw_dir) else {++ return Vec::new();++ };+ let mut matches: Vec<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(|path| match read_transcript(path) {+ Ok(transcript) => transcript.meta.thread_id.as_deref() == Some(thread_id),+ Err(err) => {+ log::warn!(+ "[transcript] skipping unreadable root transcript candidate {}: {err}",+ path.display()+ );+ false+ }+ })+ .collect();++ matches.sort();- matches.pop()++ matches+ }++ /// 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>,+ }++ /// 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.+ 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.+ 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 --cc src/openhuman/agent/harness/session/transcript_tests_part_01_tests.rsindex 0000000000,828b62caa3..5882e4f9a7mode 000000,100644..100644--- a/src/openhuman/agent/harness/session/transcript_tests_part_01_tests.rs+++ b/src/openhuman/agent/harness/session/transcript_tests_part_01_tests.rs@@@ -1,0 -1,620 +1,635 @@@+ use super::*;+++#[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::openhuman::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_profile_scoped_raw_dirs() {+ let dir = TempDir::new().unwrap();+ let scoped_raw = dir.path().join("session_raw-alice");+ fs::create_dir_all(&scoped_raw).unwrap();++ let mut meta = sample_meta();+ meta.thread_id = Some("thread-scoped".into());+ let expected = scoped_raw.join("1714000000_orchestrator_thread-scoped.jsonl");+ write_transcript(&expected, &sample_messages(), &meta, None).unwrap();++ assert_eq!(+ find_root_transcript_for_thread(dir.path(), "thread-scoped"),+ 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 --cc vendor/tinyagentsindex 1284a93f21,a53888802e..d44f18843b--- a/vendor/tinyagents+++ b/vendor/tinyagents@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 1284a93f21876a5363ed14bc0554edba6a5ce917-Subproject commit a53888802e83544c24e973f358862fc58c5f1da6++Subproject commit d44f18843b88982e792fc8c9a4e056f6358831b6