Skip to content

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

feat(session_import): add session import module with conversion and projection support

Steven Enamakel2afdf92bcf5c
diff --git a/crates/openhuman-core/src/agent/session_import/convert.rs b/crates/openhuman-core/src/agent/session_import/convert.rs
deleted file mode 100644
index cfc1d7a3fb..0000000000
--- a/crates/openhuman-core/src/agent/session_import/convert.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-//! Pure conversion helpers: stem lineage, stream naming, descriptor
-//! assembly, and message-record projection.
-
-use tinyagents_session::transcript::SessionTranscript;
-
-use super::types::{
- DescriptorImport, DescriptorSource, DescriptorUsage, JournalMessage, SessionDescriptor,
- IMPORT_VERSION,
-};
-
-/// Parent session key from the `__` stem chain.
-///
-/// Stems are `{parent_chain}__{unix_ts}_{agent_id}`; the parent key is
-/// everything before the **last** `__`. Roots (no `__`) have no parent.
-pub fn parent_session_key(stem: &str) -> Option<String> {
- stem.rfind("__").map(|idx| stem[..idx].to_string())
-}
-
-/// Sanitize a string into the TinyAgents store-name alphabet (ASCII
-/// alphanumerics, `-`, `_`, `.`); anything else becomes `_`. Empty input
-/// becomes `"session"` to match the transcript layer's fallback.
-pub fn sanitize_store_name(name: &str) -> String {
- let cleaned: String = name
- .chars()
- .map(|c| {
- if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
- c
- } else {
- '_'
- }
- })
- .collect();
- if cleaned.is_empty() || cleaned.bytes().all(|b| b == b'.') {
- "session".to_string()
- } else {
- cleaned
- }
-}
-
-/// Journal stream name for a session.
-///
-/// Per-session streams (`session.{stem}.messages`) rather than per-thread:
-/// multiple transcript files can share one `_meta.thread_id`, and appending
-/// them into a shared stream would interleave sessions. The descriptor
-/// carries `thread_id` so thread-level views can still be projected.
-pub fn stream_name(session_key: &str) -> String {
- format!("session.{}.messages", sanitize_store_name(session_key))
-}
-
-/// Effective thread id for a transcript: `_meta.thread_id` when present,
-/// otherwise a synthesized stable id. Returns `(thread_id, synthesized)`.
-pub fn effective_thread_id(session_key: &str, meta_thread_id: Option<&str>) -> (String, bool) {
- match meta_thread_id {
- Some(t) if !t.is_empty() => (t.to_string(), false),
- _ => (
- format!("imported-{}", sanitize_store_name(session_key)),
- true,
- ),
- }
-}
-
-/// Build the `sessions/{session_key}` descriptor from a parsed transcript.
-#[allow(clippy::too_many_arguments)]
-pub fn build_descriptor(
- session_key: &str,
- transcript: &SessionTranscript,
- thread_id: String,
- thread_id_synthesized: bool,
- run_ids: Vec<String>,
- source: DescriptorSource,
- imported_at: String,
- warnings: usize,
-) -> SessionDescriptor {
- let meta = &transcript.meta;
- SessionDescriptor {
- session_key: session_key.to_string(),
- parent_session_key: parent_session_key(session_key),
- thread_id,
- thread_id_synthesized,
- task_id: meta.task_id.clone(),
- run_ids,
- stream: stream_name(session_key),
- dispatcher: meta.dispatcher.clone(),
- agent_name: meta.agent_name.clone(),
- agent_id: meta.agent_id.clone(),
- agent_type: meta.agent_type.clone(),
- provider: meta.provider.clone(),
- model: meta.model.clone(),
- created: meta.created.clone(),
- updated: meta.updated.clone(),
- turn_count: meta.turn_count,
- usage: DescriptorUsage {
- input: meta.input_tokens,
- output: meta.output_tokens,
- cached_input: meta.cached_input_tokens,
- cost_usd: meta.charged_amount_usd,
- },
- source,
- import: DescriptorImport {
- version: IMPORT_VERSION,
- imported_at,
- warnings,
- },
- }
-}
-
-/// Project a transcript's messages into journal records.
-pub fn journal_messages(transcript: &SessionTranscript) -> Vec<JournalMessage> {
- transcript
- .messages
- .iter()
- .cloned()
- .map(crate::agent::messages::chat_message_from_transcript)
- .map(|message| JournalMessage::from(&message))
- .collect()
-}
-
-#[cfg(test)]
-#[path = "convert_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/session_import/convert_tests.rs b/crates/openhuman-core/src/agent/session_import/convert_tests.rs
deleted file mode 100644
index a9cfa6a2dc..0000000000
--- a/crates/openhuman-core/src/agent/session_import/convert_tests.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use super::*;
-
-#[test]
-fn parent_key_follows_last_double_underscore() {
- assert_eq!(parent_session_key("1719_orchestrator"), None);
- assert_eq!(
- parent_session_key("1719_orchestrator__1720_researcher"),
- Some("1719_orchestrator".to_string())
- );
- assert_eq!(
- parent_session_key("a__b__c"),
- Some("a__b".to_string()),
- "two-level chains keep the full parent chain as the parent key"
- );
-}
-
-#[test]
-fn sanitize_maps_unsafe_bytes_and_guards_dots() {
- assert_eq!(sanitize_store_name("1719_agent"), "1719_agent");
- assert_eq!(sanitize_store_name("a/b:c d"), "a_b_c_d");
- assert_eq!(sanitize_store_name(""), "session");
- assert_eq!(sanitize_store_name(".."), "session");
-}
-
-#[test]
-fn thread_id_synthesized_only_when_absent() {
- assert_eq!(
- effective_thread_id("s1", Some("t-1")),
- ("t-1".to_string(), false)
- );
- assert_eq!(
- effective_thread_id("s1", None),
- ("imported-s1".to_string(), true)
- );
- assert_eq!(
- effective_thread_id("s1", Some("")),
- ("imported-s1".to_string(), true)
- );
-}
-
-#[test]
-fn stream_name_is_store_safe() {
- assert_eq!(
- stream_name("1719_a__1720_b"),
- "session.1719_a__1720_b.messages"
- );
-}
diff --git a/crates/openhuman-core/src/agent/session_import/mod.rs b/crates/openhuman-core/src/agent/session_import/mod.rs
index 7b3779b0bb..e0792257a2 100644
--- a/crates/openhuman-core/src/agent/session_import/mod.rs
+++ b/crates/openhuman-core/src/agent/session_import/mod.rs
@@ -9,19 +9,13 @@
//! `openhuman.session_import_run` (`openhuman-core session_import run`). It
//! is an explicit command, never a boot hook.
-mod convert;
pub mod live;
-pub mod ops;
-mod scan;
+pub mod projector;
mod schemas;
-pub mod types;
pub use schemas::{
all_session_import_controller_schemas, all_session_import_registered_controllers,
};
-pub use types::{ImportOptions, ImportSummary};
#[cfg(test)]
mod live_tests;
-#[cfg(test)]
-mod ops_tests;
diff --git a/crates/openhuman-core/src/agent/session_import/ops.rs b/crates/openhuman-core/src/agent/session_import/ops.rs
deleted file mode 100644
index abfdd47b65..0000000000
--- a/crates/openhuman-core/src/agent/session_import/ops.rs
+++ /dev/null
@@ -1,503 +0,0 @@
-//! The importer: scan → plan → (optionally) write TinyAgents store records.
-//!
-//! Sources are never mutated or deleted. All writes land under
-//! `{workspace}/tinyagents_store/`:
-//!
-//! - `kv/sessions/{session_key}.json` — compatibility descriptor;
-//! - `kv/migration_items/{sha256(source)}.json` — per-item idempotency ledger;
-//! - `kv/migrations/session_import_v1.json` — global run marker;
-//! - `journal/session.{stem}.messages.jsonl` — message journal
-//! (`StoreRecord` per line via TinyAgents `JsonlAppendStore`).
-
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-
-use anyhow::{Context, Result};
-use serde_json::json;
-use sha2::{Digest, Sha256};
-use tinyagents_harness::store::{AppendStore, FileStore, JsonlAppendStore, Store};
-
-use tinyagents_session::transcript::{
- read_transcript, read_transcript_legacy_md, SessionTranscript,
-};
-
-use super::convert::{
- build_descriptor, effective_thread_id, journal_messages, parent_session_key, stream_name,
-};
-use super::scan::{discover_sources, SourceItem};
-use super::types::{
- DescriptorSource, ImportOptions, ImportSummary, ItemAction, ItemLedgerRecord, ItemReport,
- SourceKind, IMPORT_VERSION, JOURNAL_SUBDIR, KV_SUBDIR, MARKER_KEY, NS_MIGRATIONS,
- NS_MIGRATION_ITEMS, NS_SESSIONS,
-};
-
-/// Root of the TinyAgents store tree inside a workspace.
-pub fn store_root(workspace: &Path) -> PathBuf {
- workspace.join("tinyagents_store")
-}
-
-/// The KV + journal store handles opened over a workspace's TinyAgents store
-/// tree (`{workspace}/tinyagents_store/{kv,journal}`), plus the journal root
-/// for stream-file layout math.
-pub(crate) struct SessionStores {
- pub kv: FileStore,
- pub journal: JsonlAppendStore,
- pub journal_root: PathBuf,
-}
-
-/// Open the KV + journal stores under `{workspace}/tinyagents_store/{kv,journal}`.
-///
-/// Shared by the one-time importer ([`run_import`]) and the live dual-write
-/// ([`super::live::write_live_turn`]) so both use the exact same store layout and
-/// records land in the same place regardless of who wrote them.
-pub(crate) fn open_session_stores(workspace: &Path) -> SessionStores {
- let root = store_root(workspace);
- let journal_root = root.join(JOURNAL_SUBDIR);
- SessionStores {
- kv: FileStore::new(root.join(KV_SUBDIR)),
- journal: JsonlAppendStore::new(&journal_root),
- journal_root,
- }
-}
-
-/// Best-effort run-ledger links read from `session_db/sessions.db`
-/// (read-only; missing DB or table is not an error).
-#[derive(Debug, Default)]
-struct RunLedgerLinks {
- /// thread id → sorted, deduped `agent_runs.id`s touching it.
- runs_by_thread: HashMap<String, Vec<String>>,
- /// worker thread id → `agent_runs.parent_thread_id` (for lineage checks).
- parent_thread_by_worker: HashMap<String, String>,
-}
-
-/// Run the import. Never mutates sources; per-item failures become warnings.
-pub async fn run_import(workspace: &Path, opts: &ImportOptions) -> Result<ImportSummary> {
- let SessionStores {
- kv,
- journal,
- journal_root,
- } = open_session_stores(workspace);
-
- log::info!(
- "[session-import] start workspace={} dry_run={} only={:?} force={}",
- workspace.display(),
- opts.dry_run,
- opts.only,
- opts.force
- );
-
- // Global marker fast path: a completed full import skips the scan
- // entirely, unless targeted (--only), forced, or a dry-run plan.
- let full_scan = opts.only.is_none();
- if full_scan && !opts.force && !opts.dry_run {
- if let Ok(Some(marker)) = kv.get(NS_MIGRATIONS, MARKER_KEY).await {
- log::info!("[session-import] marker present, nothing to do: {marker}");
- return Ok(ImportSummary {
- already_done: true,
- ..Default::default()
- });
- }
- }
-
- let only_pattern = match opts.only.as_deref() {
- Some(raw) => {
- Some(glob::Pattern::new(raw).with_context(|| format!("invalid --only glob: {raw:?}"))?)
- }
- None => None,
- };
-
- let (sources, scan_warnings) = discover_sources(workspace);
- let mut summary = ImportSummary {
- dry_run: opts.dry_run,
- warnings: scan_warnings,
- ..Default::default()
- };
- for w in &summary.warnings {
- log::warn!("[session-import] scan: {w}");
- }
-
- let sources: Vec<SourceItem> = sources
- .into_iter()
- .filter(|s| only_pattern.as_ref().is_none_or(|p| p.matches(&s.stem)))
- .collect();
- summary.scanned = sources.len();
- log::info!("[session-import] scanned {} source(s)", summary.scanned);
-
- // Pass 1: read every transcript so lineage cross-checks can see sibling
- // metadata. Read failures are recorded and retried as Markdown when a
- // companion exists.
- let mut parsed: HashMap<String, SessionTranscript> = HashMap::new();
- let mut read_failures: HashMap<String, String> = HashMap::new();
- for item in &sources {
- match read_source(item) {
- Ok(t) => {
- parsed.insert(item.stem.clone(), t);
- }
- Err(err) => {
- read_failures.insert(item.stem.clone(), format!("{err:#}"));
- }
- }
- }
-
- let links = read_run_ledger_links(workspace, &mut summary.warnings);
- let imported_at = chrono::Utc::now().to_rfc3339();
-
- // Pass 2: plan + write per item.
- for item in &sources {
- let report = process_item(
- item,
- &parsed,
- &read_failures,
- &links,
- &kv,
- &journal,
- &journal_root,
- &imported_at,
- opts,
- )
- .await;
-
- match report.action {
- ItemAction::Imported => {
- summary.imported += 1;
- summary.messages_written += report.messages;
- }
- ItemAction::WouldImport => summary.imported += 1,
- ItemAction::SkippedUnchanged => summary.skipped += 1,
- ItemAction::Failed => summary.failed += 1,
- }
- if opts.verbose {
- log::info!(
- "[session-import] {:?} stem={} source={} messages={} warnings={}",
- report.action,
- report.session_key,
- report.source,
- report.messages,
- report.warnings.len()
- );
- } else {
- log::debug!(
- "[session-import] {:?} stem={} source={}",
- report.action,
- report.session_key,
- report.source
- );
- }
- summary.items.push(report);
- }
-
- // Global marker only after a full, non-dry scan.
- if full_scan && !opts.dry_run {
- let marker = json!({
- "version": IMPORT_VERSION,
- "imported_at": imported_at,
- "scanned": summary.scanned,
- "imported": summary.imported,
- "skipped": summary.skipped,
- "failed": summary.failed,
- "messages_written": summary.messages_written,
- "warnings": summary.warnings.len(),
- });
- if let Err(err) = kv.put(NS_MIGRATIONS, MARKER_KEY, marker).await {
- summary
- .warnings
- .push(format!("failed to write global marker: {err}"));
- }
- }
-
- log::info!(
- "[session-import] done scanned={} imported={} skipped={} failed={} messages={} dry_run={}",
- summary.scanned,
- summary.imported,
- summary.skipped,
- summary.failed,
- summary.messages_written,
- summary.dry_run
- );
- Ok(summary)
-}
-
-/// Read one source with the appropriate reader.
-fn read_source(item: &SourceItem) -> Result<SessionTranscript> {
- match item.kind {
- SourceKind::Jsonl | SourceKind::JsonlLegacyDir => read_transcript(&item.path)
- .with_context(|| format!("read_transcript({})", item.relative)),
- SourceKind::Markdown => read_transcript_legacy_md(&item.path)
- .with_context(|| format!("read_transcript_legacy_md({})", item.relative)),
- }
-}
-
-#[allow(clippy::too_many_arguments)]
-async fn process_item(
- item: &SourceItem,
- parsed: &HashMap<String, SessionTranscript>,
- read_failures: &HashMap<String, String>,
- links: &RunLedgerLinks,
- kv: &FileStore,
- journal: &JsonlAppendStore,
- journal_root: &Path,
- imported_at: &str,
- opts: &ImportOptions,
-) -> ItemReport {
- let mut report = ItemReport {
- session_key: item.stem.clone(),
- source: item.relative.clone(),
- kind: item.kind,
- action: ItemAction::Failed,
- stream: None,
- thread_id: None,
- messages: 0,
- warnings: Vec::new(),
- };
-
- if let Some(err) = read_failures.get(&item.stem) {
- report.warnings.push(format!("unreadable source: {err}"));
- log::warn!(
- "[session-import] failed stem={} source={}: {err}",
- item.stem,
- item.relative
- );
- return report;
- }
- let Some(transcript) = parsed.get(&item.stem) else {
- report
- .warnings
- .push("internal: parsed transcript missing".into());
- return report;
- };
-
- let stream = stream_name(&item.stem);
- let (thread_id, synthesized) =
- effective_thread_id(&item.stem, transcript.meta.thread_id.as_deref());
- if synthesized {
- report
- .warnings
- .push(format!("no thread_id in _meta; synthesized {thread_id}"));
- }
- report.stream = Some(stream.clone());
- report.thread_id = Some(thread_id.clone());
- report.messages = transcript.messages.len();
-
- // Lineage cross-check: stem chain is the write-time truth; a
- // disagreeing run-ledger parent is only a warning.
- if let Some(parent_stem) = parent_session_key(&item.stem) {
- if let (Some(ledger_parent), Some(parent_transcript)) = (
- links.parent_thread_by_worker.get(&thread_id),
- parsed.get(&parent_stem),
- ) {
- if let Some(parent_thread) = parent_transcript.meta.thread_id.as_deref() {
- if ledger_parent != parent_thread {
- report.warnings.push(format!(
- "run-ledger parent thread {ledger_parent} disagrees with stem-chain \
- parent thread {parent_thread}; keeping the stem chain"
- ));
- }
- }
- }
- }
-
- // Idempotency: skip unchanged sources unless forced.
- let item_key = ledger_key(&item.relative);
- let (size, mtime_ms) = file_fingerprint(&item.path);
- if !opts.force {
- if let Ok(Some(prior)) = kv.get(NS_MIGRATION_ITEMS, &item_key).await {
- if let Ok(prior) = serde_json::from_value::<ItemLedgerRecord>(prior) {
- if prior.version == IMPORT_VERSION
- && prior.size == size
- && prior.mtime_ms == mtime_ms
- {
- report.action = ItemAction::SkippedUnchanged;
- return report;
- }
- }
- }
- }
-
- if opts.dry_run {
- report.action = ItemAction::WouldImport;
- return report;
- }
-
- // Re-import overwrites: the append store has no truncate, so drop the
- // stream file (layout: `{journal_root}/{stream}.jsonl`) before writing.
- let stream_file = journal_root.join(format!("{stream}.jsonl"));
- if stream_file.exists() {
- if let Err(err) = std::fs::remove_file(&stream_file) {
- report
- .warnings
- .push(format!("cannot reset journal stream {stream}: {err}"));
- return report;
- }
- }
-
- for (idx, record) in journal_messages(transcript).iter().enumerate() {
- let value = match serde_json::to_value(record) {
- Ok(v) => v,
- Err(err) => {
- report
- .warnings
- .push(format!("message {idx} not serializable: {err}"));
- return report;
- }
- };
- if let Err(err) = journal.append(&stream, value).await {
- report
- .warnings
- .push(format!("journal append failed at message {idx}: {err}"));
- return report;
- }
- }
-
- let run_ids = links
- .runs_by_thread
- .get(&thread_id)
- .cloned()
- .unwrap_or_default();
- let descriptor = build_descriptor(
- &item.stem,
- transcript,
- thread_id,
- synthesized,
- run_ids,
- DescriptorSource {
- jsonl: matches!(item.kind, SourceKind::Jsonl | SourceKind::JsonlLegacyDir)
- .then(|| item.relative.clone()),
- md: match item.kind {
- SourceKind::Markdown => Some(item.relative.clone()),
- _ => item.md_companion.clone(),
- },
- },
- imported_at.to_string(),
- report.warnings.len(),
- );
- let descriptor_key = super::convert::sanitize_store_name(&item.stem);
- let descriptor_value = match serde_json::to_value(&descriptor) {
- Ok(v) => v,
- Err(err) => {
- report
- .warnings
- .push(format!("descriptor not serializable: {err}"));
- return report;
- }
- };
- if let Err(err) = kv.put(NS_SESSIONS, &descriptor_key, descriptor_value).await {
- report
- .warnings
- .push(format!("descriptor write failed: {err}"));
- return report;
- }
-
- let ledger = ItemLedgerRecord {
- version: IMPORT_VERSION,
- session_key: item.stem.clone(),
- source: item.relative.clone(),
- size,
- mtime_ms,
- stream,
- messages: report.messages,
- imported_at: imported_at.to_string(),
- };
- match serde_json::to_value(&ledger) {
- Ok(v) => {
- if let Err(err) = kv.put(NS_MIGRATION_ITEMS, &item_key, v).await {
- report
- .warnings
- .push(format!("item ledger write failed: {err}"));
- return report;
- }
- }
- Err(err) => {
- report
- .warnings
- .push(format!("item ledger not serializable: {err}"));
- return report;
- }
- }
-
- report.action = ItemAction::Imported;
- report
-}
-
-/// Item-ledger key: hex sha256 of the workspace-relative source path.
-fn ledger_key(relative: &str) -> String {
- let mut hasher = Sha256::new();
- hasher.update(relative.as_bytes());
- format!("{:x}", hasher.finalize())
-}
-
-/// `(size, mtime_ms)` fingerprint; `(0, 0)` when unreadable.
-fn file_fingerprint(path: &Path) -> (u64, u64) {
- let Ok(meta) = std::fs::metadata(path) else {
- return (0, 0);
- };
- let mtime_ms = meta
- .modified()
- .ok()
- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0);
- (meta.len(), mtime_ms)
-}
-
-/// Read run-ledger links from `session_db/sessions.db`, read-only.
-///
-/// Missing file/table → empty links, no warning (fresh workspaces are
-/// normal). Query errors are warnings, never failures.
-fn read_run_ledger_links(workspace: &Path, warnings: &mut Vec<String>) -> RunLedgerLinks {
- let db_path = workspace.join("session_db").join("sessions.db");
- if !db_path.exists() {
- return RunLedgerLinks::default();
- }
- let conn = match rusqlite::Connection::open_with_flags(
- &db_path,
- rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
- ) {
- Ok(c) => c,
- Err(err) => {
- warnings.push(format!("run ledger unreadable ({err}); skipping run links"));
- return RunLedgerLinks::default();
- }
- };
-
- let mut links = RunLedgerLinks::default();
- let mut stmt =
- match conn.prepare("SELECT id, parent_thread_id, worker_thread_id FROM agent_runs") {
- Ok(s) => s,
- Err(_) => return RunLedgerLinks::default(), // table absent: nothing to link
- };
- let rows = stmt.query_map([], |row| {
- Ok((
- row.get::<_, String>(0)?,
- row.get::<_, Option<String>>(1)?,
- row.get::<_, Option<String>>(2)?,
- ))
- });
- let rows = match rows {
- Ok(r) => r,
- Err(err) => {
- warnings.push(format!(
- "run ledger query failed ({err}); skipping run links"
- ));
- return RunLedgerLinks::default();
- }
- };
- for row in rows.flatten() {
- let (id, parent_thread, worker_thread) = row;
- for thread in [parent_thread.as_deref(), worker_thread.as_deref()]
- .into_iter()
- .flatten()
- {
- let entry = links.runs_by_thread.entry(thread.to_string()).or_default();
- if !entry.contains(&id) {
- entry.push(id.clone());
- }
- }
- if let (Some(worker), Some(parent)) = (worker_thread, parent_thread) {
- links.parent_thread_by_worker.insert(worker, parent);
- }
- }
- for ids in links.runs_by_thread.values_mut() {
- ids.sort();
- }
- links
-}
diff --git a/crates/openhuman-core/src/agent/session_import/ops_tests.rs b/crates/openhuman-core/src/agent/session_import/ops_tests.rs
deleted file mode 100644
index 3748e3e16c..0000000000
--- a/crates/openhuman-core/src/agent/session_import/ops_tests.rs
+++ /dev/null
@@ -1,475 +0,0 @@
-//! Fixture-matrix tests for the session importer — one test per row of the
-//! matrix in `docs/tinyagents-session-migration-design.md`.
-
-use std::fs;
-use std::path::{Path, PathBuf};
-
-use tempfile::TempDir;
-use tinyagents_harness::store::{AppendStore, FileStore, JsonlAppendStore, Store};
-
-use super::convert::{journal_messages, sanitize_store_name};
-use super::ops::{run_import, store_root};
-use super::types::{
- ImportOptions, ImportSummary, ItemAction, JournalMessage, SessionDescriptor, MARKER_KEY,
- NS_MIGRATIONS, NS_SESSIONS,
-};
-use tinyagents_session::transcript::{read_transcript, read_transcript_legacy_md};
-
-fn ws() -> TempDir {
- TempDir::new().expect("tempdir")
-}
-
-fn write_file(path: &Path, contents: &str) {
- fs::create_dir_all(path.parent().unwrap()).unwrap();
- fs::write(path, contents).unwrap();
-}
-
-fn flat_jsonl(ws: &Path, stem: &str) -> PathBuf {
- ws.join("session_raw").join(format!("{stem}.jsonl"))
-}
-
-fn meta_line(thread_id: Option<&str>, dispatcher: &str) -> String {
- let thread = thread_id
- .map(|t| format!(",\"thread_id\":\"{t}\""))
- .unwrap_or_default();
- format!(
- "{{\"_meta\":{{\"agent\":\"orchestrator\",\"agent_id\":\"orchestrator\",\
- \"dispatcher\":\"{dispatcher}\",\"provider\":\"anthropic\",\"model\":\"claude\",\
- \"created\":\"2024-01-01T00:00:00Z\",\"updated\":\"2024-01-01T00:05:00Z\",\
- \"turn_count\":1,\"input_tokens\":100,\"output_tokens\":50,\
- \"cached_input_tokens\":20,\"charged_amount_usd\":0.05{thread}}}}}\n"
- )
-}
-
-/// A native transcript: user turn + assistant turn carrying usage and a
-/// tool call with Gemini-style `extra_content` passthrough.
-fn native_body() -> &'static str {
- concat!(
- "{\"role\":\"user\",\"content\":\"hi\"}\n",
- "{\"role\":\"assistant\",\"content\":\"done\",\"provider\":\"anthropic\",",
- "\"model\":\"claude\",\"usage\":{\"input\":100,\"output\":50,\"cached_input\":20,",
- "\"context_window\":200000,\"cost_usd\":0.05},\"ts\":\"2024-01-01T00:00:01Z\",",
- "\"iteration\":1,\"tool_calls\":[{\"id\":\"tc1\",\"name\":\"read_file\",",
- "\"arguments\":\"{\\\"path\\\":\\\"x\\\"}\",",
- "\"extra_content\":{\"google\":{\"thought_signature\":\"sig\"}}}]}\n",
- )
-}
-
-async fn run(ws: &Path, opts: ImportOptions) -> ImportSummary {
- run_import(ws, &opts).await.expect("run_import")
-}
-
-async fn descriptor(ws: &Path, stem: &str) -> SessionDescriptor {
- let kv = FileStore::new(store_root(ws).join("kv"));
- let value = kv
- .get(NS_SESSIONS, &sanitize_store_name(stem))
- .await
- .expect("kv get")
- .unwrap_or_else(|| panic!("descriptor missing for {stem}"));
- serde_json::from_value(value).expect("descriptor shape")
-}
-
-async fn journal_readback(ws: &Path, stream: &str) -> Vec<JournalMessage> {
- let journal = JsonlAppendStore::new(store_root(ws).join("journal"));
- journal
- .read_from(stream, 0)
- .await
- .expect("journal read")
- .into_iter()
- .map(|(_, v)| serde_json::from_value(v).expect("journal record shape"))
- .collect()
-}
-
-/// Parity: the journal read-back must equal what `read_transcript` returns
-/// for the source, field for field (including reattached turn-usage
-/// metadata).
-async fn assert_parity_jsonl(ws: &Path, stem: &str, source: &Path) {
- let expected = journal_messages(&read_transcript(source).expect("read_transcript"));
- let actual = journal_readback(ws, &format!("session.{stem}.messages")).await;
- assert_eq!(actual, expected, "journal read-back diverges for {stem}");
-}
-
-// Fixture 1 + 7: current flat layout, native dispatcher, tool_calls with
-// extra_content — full parity + descriptor mapping.
-#[tokio::test]
-async fn imports_flat_native_jsonl_with_parity() {
- let ws = ws();
- let stem = "1719000000_orchestrator";
- let source = flat_jsonl(ws.path(), stem);
- write_file(
- &source,
- &(meta_line(Some("t-root"), "native") + native_body()),
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.scanned, 1);
- assert_eq!(summary.imported, 1);
- assert_eq!(summary.failed, 0);
- assert_eq!(summary.messages_written, 2);
-
- let desc = descriptor(ws.path(), stem).await;
- assert_eq!(desc.session_key, stem);
- assert_eq!(desc.thread_id, "t-root");
- assert!(!desc.thread_id_synthesized);
- assert_eq!(desc.parent_session_key, None);
- assert_eq!(desc.dispatcher, "native");
- assert_eq!(desc.usage.input, 100);
- assert_eq!(desc.usage.cost_usd, 0.05);
- assert_eq!(
- desc.source.jsonl.as_deref(),
- Some("session_raw/1719000000_orchestrator.jsonl")
- );
-
- assert_parity_jsonl(ws.path(), stem, &source).await;
-
- // Turn-usage metadata (incl. the tool call's extra_content) survived.
- let messages = journal_readback(ws.path(), &format!("session.{stem}.messages")).await;
- let assistant = &messages[1];
- let usage = assistant
- .extra_metadata
- .as_ref()
- .and_then(|m| m.get("openhuman_turn_usage"))
- .expect("turn usage metadata");
- assert_eq!(usage["tool_calls"][0]["id"], "tc1");
- assert_eq!(
- usage["tool_calls"][0]["extra_content"]["google"]["thought_signature"],
- "sig"
- );
-
- // Global marker written after a full non-dry run.
- let kv = FileStore::new(store_root(ws.path()).join("kv"));
- assert!(kv.get(NS_MIGRATIONS, MARKER_KEY).await.unwrap().is_some());
-}
-
-// Fixture 2: legacy date-folder layout.
-#[tokio::test]
-async fn imports_legacy_date_folder_jsonl() {
- let ws = ws();
- let stem = "1718000000_researcher";
- let source = ws
- .path()
- .join("session_raw")
- .join("01062024")
- .join(format!("{stem}.jsonl"));
- write_file(
- &source,
- &(meta_line(Some("t-legacy"), "native") + native_body()),
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.imported, 1, "warnings: {:?}", summary.warnings);
- let desc = descriptor(ws.path(), stem).await;
- assert_eq!(
- desc.source.jsonl.as_deref(),
- Some("session_raw/01062024/1718000000_researcher.jsonl")
- );
- assert_parity_jsonl(ws.path(), stem, &source).await;
-}
-
-// Fixture 3: Markdown-only session via the legacy `<!--MSG-->` reader.
-#[tokio::test]
-async fn imports_markdown_only_session() {
- let ws = ws();
- let stem = "1717000000_helper";
- let md = ws
- .path()
- .join("sessions")
- .join("2024_06_01")
- .join(format!("{stem}.md"));
- write_file(
- &md,
- "<!-- session_transcript\nagent: helper\ndispatcher: native\n\
- created: 2024-06-01T00:00:00Z\nupdated: 2024-06-01T00:05:00Z\n\
- turn_count: 1\ninput_tokens: 10\noutput_tokens: 5\ncached_input_tokens: 0\n\
- charged_usd: $0.01\nthread_id: t-md\n-->\n\
- <!--MSG role=\"user\"-->\nhello\n<!--/MSG-->\n\
- <!--MSG role=\"assistant\"-->\nhi there\n<!--/MSG-->\n",
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.imported, 1, "warnings: {:?}", summary.warnings);
-
- let desc = descriptor(ws.path(), stem).await;
- assert_eq!(desc.thread_id, "t-md");
- assert_eq!(desc.source.jsonl, None);
- assert!(desc.source.md.as_deref().unwrap().ends_with(".md"));
-
- let expected = journal_messages(&read_transcript_legacy_md(&md).unwrap());
- let actual = journal_readback(ws.path(), &format!("session.{stem}.messages")).await;
- assert_eq!(actual, expected);
-}
-
-// Fixture 4: sub-agent stems, two-level chain → parent keys from the stem.
-#[tokio::test]
-async fn subagent_stem_chain_sets_parent_lineage() {
- let ws = ws();
- let root = "100_a";
- let child = "100_a__200_b";
- let grandchild = "100_a__200_b__300_c";
- for (stem, thread) in [(root, "t-a"), (child, "t-b"), (grandchild, "t-c")] {
- write_file(
- &flat_jsonl(ws.path(), stem),
- &(meta_line(Some(thread), "native") + native_body()),
- );
- }
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.imported, 3);
- assert_eq!(descriptor(ws.path(), root).await.parent_session_key, None);
- assert_eq!(
- descriptor(ws.path(), child)
- .await
- .parent_session_key
- .as_deref(),
- Some("100_a")
- );
- assert_eq!(
- descriptor(ws.path(), grandchild)
- .await
- .parent_session_key
- .as_deref(),
- Some("100_a__200_b")
- );
-}
-
-// Fixtures 5 + 6: XML and P-format tool markup stays verbatim in content.
-#[tokio::test]
-async fn xml_and_pformat_markup_preserved_verbatim() {
- let ws = ws();
- let xml_stem = "1716000000_xmlagent";
- let xml_markup =
- "calling now <tool_call>{\"name\":\"shell\",\"arguments\":{\"cmd\":\"ls\"}}</tool_call>";
- write_file(
- &flat_jsonl(ws.path(), xml_stem),
- &format!(
- "{}{{\"role\":\"assistant\",\"content\":\"{}\"}}\n",
- meta_line(Some("t-xml"), "xml"),
- xml_markup.replace('"', "\\\"")
- ),
- );
- let p_stem = "1716000001_pfagent";
- let p_markup = "<tool_call>read_file[notes.txt|10]</tool_call>";
- write_file(
- &flat_jsonl(ws.path(), p_stem),
- &format!(
- "{}{{\"role\":\"assistant\",\"content\":\"{}\"}}\n",
- meta_line(Some("t-pf"), "pformat"),
- p_markup.replace('"', "\\\"")
- ),
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.imported, 2);
-
- let xml_msgs = journal_readback(ws.path(), &format!("session.{xml_stem}.messages")).await;
- assert_eq!(xml_msgs[0].content, xml_markup);
- assert_eq!(descriptor(ws.path(), xml_stem).await.dispatcher, "xml");
-
- let p_msgs = journal_readback(ws.path(), &format!("session.{p_stem}.messages")).await;
- assert_eq!(p_msgs[0].content, p_markup);
- assert_eq!(descriptor(ws.path(), p_stem).await.dispatcher, "pformat");
-}
-
-// Fixture 8: malformed sources fail per-item without aborting the batch;
-// a truncated trailing line is tolerated by the reader (skip + warning).
-#[tokio::test]
-async fn malformed_sources_fail_without_aborting_batch() {
- let ws = ws();
- write_file(
- &flat_jsonl(ws.path(), "1715000000_good"),
- &(meta_line(Some("t-good"), "native") + native_body()),
- );
- // Missing `_meta` first line.
- write_file(
- &flat_jsonl(ws.path(), "1715000001_nometa"),
- "{\"role\":\"user\",\"content\":\"hi\"}\n",
- );
- // Empty file.
- write_file(&flat_jsonl(ws.path(), "1715000002_empty"), "");
- // Truncated last line after one valid message.
- write_file(
- &flat_jsonl(ws.path(), "1715000003_truncated"),
- &format!(
- "{}{{\"role\":\"user\",\"content\":\"ok\"}}\n{{\"role\":\"assistant\",\"conte",
- meta_line(Some("t-trunc"), "native")
- ),
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.scanned, 4);
- assert_eq!(summary.imported, 2, "good + truncated-but-tolerated");
- assert_eq!(summary.failed, 2, "no-meta + empty fail per-item");
-
- let truncated = journal_readback(ws.path(), "session.1715000003_truncated.messages").await;
- assert_eq!(truncated.len(), 1, "malformed trailing line skipped");
-
- // The batch still completed and the marker landed.
- let kv = FileStore::new(store_root(ws.path()).join("kv"));
- assert!(kv.get(NS_MIGRATIONS, MARKER_KEY).await.unwrap().is_some());
-}
-
-// Fixture 9: `_meta` without thread_id → synthesized stable id + warning.
-#[tokio::test]
-async fn synthesizes_thread_id_when_meta_lacks_one() {
- let ws = ws();
- let stem = "1714000000_nothread";
- write_file(
- &flat_jsonl(ws.path(), stem),
- &(meta_line(None, "native") + native_body()),
- );
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- let desc = descriptor(ws.path(), stem).await;
- assert_eq!(desc.thread_id, format!("imported-{stem}"));
- assert!(desc.thread_id_synthesized);
- let item = &summary.items[0];
- assert!(
- item.warnings.iter().any(|w| w.contains("synthesized")),
- "warnings: {:?}",
- item.warnings
- );
-}
-
-// Fixture 10: run-ledger rows join run_ids; a disagreeing ledger parent
-// thread is a warning, and the stem chain wins.
-#[tokio::test]
-async fn run_ledger_links_join_and_disagreement_warns() {
- let ws = ws();
- let root = "100_root";
- let child = "100_root__200_child";
- write_file(
- &flat_jsonl(ws.path(), root),
- &(meta_line(Some("t-root"), "native") + native_body()),
- );
- write_file(
- &flat_jsonl(ws.path(), child),
- &(meta_line(Some("t-child"), "native") + native_body()),
- );
-
- let db_dir = ws.path().join("session_db");
- fs::create_dir_all(&db_dir).unwrap();
- let conn = rusqlite::Connection::open(db_dir.join("sessions.db")).unwrap();
- conn.execute_batch(
- "CREATE TABLE agent_runs (id TEXT PRIMARY KEY, parent_thread_id TEXT, worker_thread_id TEXT);
- INSERT INTO agent_runs VALUES ('run-1', 't-DIFFERENT', 't-child');",
- )
- .unwrap();
- drop(conn);
-
- let summary = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(summary.imported, 2, "warnings: {:?}", summary.warnings);
-
- let child_desc = descriptor(ws.path(), child).await;
- assert_eq!(child_desc.run_ids, vec!["run-1".to_string()]);
- assert_eq!(
- child_desc.parent_session_key.as_deref(),
- Some("100_root"),
- "stem chain wins"
- );
- let child_item = summary
- .items
- .iter()
- .find(|i| i.session_key == child)
- .unwrap();
- assert!(
- child_item.warnings.iter().any(|w| w.contains("disagrees")),
- "warnings: {:?}",
- child_item.warnings
- );
-}
-
-// Fixture 11: full rerun short-circuits on the marker; a targeted rerun
-// skips unchanged items and re-imports only the touched one.
-#[tokio::test]
-async fn idempotent_rerun_skips_then_touch_reimports() {
- let ws = ws();
- let a = "1713000000_a";
- let b = "1713000001_b";
- for stem in [a, b] {
- write_file(
- &flat_jsonl(ws.path(), stem),
- &(meta_line(Some(&format!("t-{stem}")), "native") + native_body()),
- );
- }
-
- let first = run(ws.path(), ImportOptions::default()).await;
- assert_eq!(first.imported, 2);
-
- // Full rerun: global marker short-circuits.
- let second = run(ws.path(), ImportOptions::default()).await;
- assert!(second.already_done);
- assert_eq!(second.scanned, 0);
-
- // Targeted rerun: everything unchanged → skipped.
- let targeted = run(
- ws.path(),
- ImportOptions {
- only: Some("*".into()),
- ..Default::default()
- },
- )
- .await;
- assert_eq!(targeted.skipped, 2);
- assert_eq!(targeted.imported, 0);
-
- // Touch one source (size changes) → only it re-imports.
- let path = flat_jsonl(ws.path(), a);
- let mut contents = fs::read_to_string(&path).unwrap();
- contents.push_str("{\"role\":\"user\",\"content\":\"follow-up\"}\n");
- fs::write(&path, contents).unwrap();
-
- let after_touch = run(
- ws.path(),
- ImportOptions {
- only: Some("*".into()),
- ..Default::default()
- },
- )
- .await;
- assert_eq!(after_touch.imported, 1);
- assert_eq!(after_touch.skipped, 1);
-
- // The re-imported stream was reset, not appended twice.
- let msgs = journal_readback(ws.path(), &format!("session.{a}.messages")).await;
- assert_eq!(msgs.len(), 3);
-}
-
-// Dry-run: reports the plan, writes nothing.
-#[tokio::test]
-async fn dry_run_writes_nothing() {
- let ws = ws();
- write_file(
- &flat_jsonl(ws.path(), "1712000000_plan"),
- &(meta_line(Some("t-plan"), "native") + native_body()),
- );
-
- let summary = run(
- ws.path(),
- ImportOptions {
- dry_run: true,
- ..Default::default()
- },
- )
- .await;
- assert!(summary.dry_run);
- assert_eq!(summary.imported, 1);
- assert_eq!(summary.messages_written, 0);
- assert_eq!(summary.items[0].action, ItemAction::WouldImport);
- assert!(
- !store_root(ws.path()).join("kv").exists()
- && !store_root(ws.path()).join("journal").exists(),
- "dry run must not create store dirs"
- );
-}
-
-// Sources are never mutated: byte-identical after import.
-#[tokio::test]
-async fn sources_untouched_after_import() {
- let ws = ws();
- let source = flat_jsonl(ws.path(), "1711000000_untouched");
- let contents = meta_line(Some("t-u"), "native") + native_body();
- write_file(&source, &contents);
-
- run(ws.path(), ImportOptions::default()).await;
- assert_eq!(fs::read_to_string(&source).unwrap(), contents);
-}
diff --git a/crates/openhuman-core/src/agent/session_import/projector.rs b/crates/openhuman-core/src/agent/session_import/projector.rs
new file mode 100644
index 0000000000..2c5b8b17cc
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_import/projector.rs
@@ -0,0 +1,29 @@
+//! Host projection of a durable transcript row into a session-store journal
+//! record.
+//!
+//! The importer, the live dual-write and the shadow read (all in
+//! `tinyagents_session::transcript::import`) take this as their
+//! `JournalProjector`. It goes through the host's `ChatMessage` shape so the
+//! journal carries the reconstructed sidecar metadata (`openhuman_turn_usage`,
+//! tool-failure and replay markers) exactly as a transcript read-back does.
+
+use tinyagents_session::transcript::import::types::JournalMessage;
+use tinyagents_session::transcript::TranscriptMessage;
+
+use crate::agent::messages::{chat_message_from_transcript, ChatMessage};
+
+impl From<&ChatMessage> for JournalMessage {
+ fn from(msg: &ChatMessage) -> Self {
+ Self {
+ id: msg.id.clone(),
+ role: msg.role.clone(),
+ content: msg.content.clone(),
+ extra_metadata: msg.extra_metadata.clone(),
+ }
+ }
+}
+
+/// The `JournalProjector` OpenHuman passes to the importer.
+pub fn journal_message_from_transcript(message: TranscriptMessage) -> JournalMessage {
+ JournalMessage::from(&chat_message_from_transcript(message))
+}
diff --git a/crates/openhuman-core/src/agent/session_import/scan.rs b/crates/openhuman-core/src/agent/session_import/scan.rs
deleted file mode 100644
index 67a14553c2..0000000000
--- a/crates/openhuman-core/src/agent/session_import/scan.rs
+++ /dev/null
@@ -1,178 +0,0 @@
-//! Source discovery: which legacy session files exist in a workspace.
-
-use std::collections::BTreeMap;
-use std::path::{Path, PathBuf};
-
-use super::types::SourceKind;
-
-/// One discovered source, keyed by session stem.
-#[derive(Debug, Clone)]
-pub struct SourceItem {
- pub stem: String,
- pub kind: SourceKind,
- /// Absolute path of the file the messages will be read from.
- pub path: PathBuf,
- /// Workspace-relative path of `path`, for descriptors and the ledger.
- pub relative: String,
- /// Workspace-relative Markdown companion, when one exists next to a
- /// JSONL source (informational only — never read when JSONL exists).
- pub md_companion: Option<String>,
-}
-
-/// Scan `session_raw/` (flat + legacy `DDMMYYYY` folders) and `sessions/`
-/// Markdown directories. Returns items sorted by stem, plus scan warnings.
-///
-/// Precedence per stem: flat JSONL > legacy-dir JSONL > Markdown-only. The
-/// same stem never yields two items.
-pub fn discover_sources(workspace: &Path) -> (Vec<SourceItem>, Vec<String>) {
- let mut warnings = Vec::new();
- // stem → item, first writer wins per the precedence order below.
- let mut by_stem: BTreeMap<String, SourceItem> = BTreeMap::new();
-
- let raw_dir = workspace.join("session_raw");
-
- // 1. Flat JSONL (current layout).
- for path in list_files(&raw_dir, "jsonl", &mut warnings) {
- insert_stem(
- &mut by_stem,
- workspace,
- path,
- SourceKind::Jsonl,
- &mut warnings,
- );
- }
-
- // 2. Legacy date-folder JSONL.
- for sub in list_dirs(&raw_dir, &mut warnings) {
- let name = sub
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string();
- if !is_ddmmyyyy(&name) {
- continue;
- }
- for path in list_files(&sub, "jsonl", &mut warnings) {
- insert_stem(
- &mut by_stem,
- workspace,
- path,
- SourceKind::JsonlLegacyDir,
- &mut warnings,
- );
- }
- }
-
- // 3. Markdown sessions: only stems with no JSONL anywhere. Also record
- // companions for stems that do have JSONL.
- let sessions_dir = workspace.join("sessions");
- for sub in list_dirs(&sessions_dir, &mut warnings) {
- for path in list_files(&sub, "md", &mut warnings) {
- let Some(stem) = file_stem(&path) else {
- continue;
- };
- let relative = relative_to(workspace, &path);
- match by_stem.get_mut(&stem) {
- Some(item) => {
- if item.md_companion.is_none() {
- item.md_companion = Some(relative);
- }
- }
- None => {
- by_stem.insert(
- stem.clone(),
- SourceItem {
- stem,
- kind: SourceKind::Markdown,
- relative,
- path,
- md_companion: None,
- },
- );
- }
- }
- }
- }
-
- (by_stem.into_values().collect(), warnings)
-}
-
-fn insert_stem(
- by_stem: &mut BTreeMap<String, SourceItem>,
- workspace: &Path,
- path: PathBuf,
- kind: SourceKind,
- warnings: &mut Vec<String>,
-) {
- let Some(stem) = file_stem(&path) else {
- warnings.push(format!("unreadable file name, skipped: {}", path.display()));
- return;
- };
- let relative = relative_to(workspace, &path);
- if let Some(existing) = by_stem.get(&stem) {
- warnings.push(format!(
- "duplicate stem '{stem}': keeping {}, ignoring {relative}",
- existing.relative
- ));
- return;
- }
- by_stem.insert(
- stem.clone(),
- SourceItem {
- stem,
- kind,
- relative,
- path,
- md_companion: None,
- },
- );
-}
-
-fn file_stem(path: &Path) -> Option<String> {
- path.file_stem().map(|s| s.to_string_lossy().to_string())
-}
-
-fn relative_to(workspace: &Path, path: &Path) -> String {
- path.strip_prefix(workspace)
- .unwrap_or(path)
- .to_string_lossy()
- .to_string()
-}
-
-fn list_files(dir: &Path, ext: &str, warnings: &mut Vec<String>) -> Vec<PathBuf> {
- list_entries(dir, warnings)
- .into_iter()
- .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == ext))
- .collect()
-}
-
-fn list_dirs(dir: &Path, warnings: &mut Vec<String>) -> Vec<PathBuf> {
- list_entries(dir, warnings)
- .into_iter()
- .filter(|p| p.is_dir())
- .collect()
-}
-
-fn list_entries(dir: &Path, warnings: &mut Vec<String>) -> Vec<PathBuf> {
- if !dir.exists() {
- return Vec::new();
- }
- match std::fs::read_dir(dir) {
- Ok(entries) => {
- let mut paths: Vec<PathBuf> =
- entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
- paths.sort();
- paths
- }
- Err(err) => {
- warnings.push(format!("cannot read {}: {err}", dir.display()));
- Vec::new()
- }
- }
-}
-
-/// Exactly 8 ASCII digits — the legacy `DDMMYYYY` folder convention (matches
-/// `session::migration::is_ddmmyyyy`).
-fn is_ddmmyyyy(name: &str) -> bool {
- name.len() == 8 && name.bytes().all(|b| b.is_ascii_digit())
-}
diff --git a/crates/openhuman-core/src/agent/session_import/schemas.rs b/crates/openhuman-core/src/agent/session_import/schemas.rs
index 856aff71bd..7e7dc5e64d 100644
--- a/crates/openhuman-core/src/agent/session_import/schemas.rs
+++ b/crates/openhuman-core/src/agent/session_import/schemas.rs
@@ -7,8 +7,9 @@ use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::Outcome;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use super::ops::run_import;
-use super::types::ImportOptions;
+use super::projector::journal_message_from_transcript;
+use tinyagents_session::transcript::import::ops::run_import;
+use tinyagents_session::transcript::import::types::ImportOptions;
#[derive(Debug, Deserialize, Default)]
struct SessionImportRunParams {
@@ -112,7 +113,7 @@ fn handle_session_import_run(params: Map<String, Value>) -> ControllerFuture {
dry_run = opts.dry_run,
"[session-import] rpc run"
);
- let summary = run_import(&workspace, &opts)
+ let summary = run_import(&workspace, &opts, journal_message_from_transcript)
.await
.map_err(|e| format!("session import failed: {e:#}"))?;
let logs = summary.warnings.clone();
diff --git a/crates/openhuman-core/src/agent/session_import/types.rs b/crates/openhuman-core/src/agent/session_import/types.rs
deleted file mode 100644
index 614da5c403..0000000000
--- a/crates/openhuman-core/src/agent/session_import/types.rs
+++ /dev/null
@@ -1,217 +0,0 @@
-//! Serde types for the one-time session import into TinyAgents stores.
-
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-
-use crate::agent::messages::ChatMessage;
-
-/// Schema version of the importer. Bump when the record shapes change and a
-/// re-import should be forced.
-pub const IMPORT_VERSION: u32 = 1;
-
-/// Store namespaces / stream layout under `{workspace}/tinyagents_store/`.
-///
-/// TinyAgents store names are slash-free (ASCII alphanumerics plus `-_.`
-/// only — the crate's path-traversal guard), so streams use dot-separated
-/// names rather than the `thread/{id}/messages` shape sketched in the design
-/// doc.
-pub const KV_SUBDIR: &str = "kv";
-pub const JOURNAL_SUBDIR: &str = "journal";
-pub const NS_SESSIONS: &str = "sessions";
-pub const NS_MIGRATIONS: &str = "migrations";
-pub const NS_MIGRATION_ITEMS: &str = "migration_items";
-pub const MARKER_KEY: &str = "session_import_v1";
-
-/// Options accepted by `session_import.run`.
-#[derive(Debug, Clone, Default, Deserialize)]
-pub struct ImportOptions {
- /// Plan only: read and report, write nothing.
- #[serde(default)]
- pub dry_run: bool,
- /// Optional glob over session stems (e.g. `1719*_orchestrator`); when
- /// set, only matching sources are considered and the global marker is
- /// neither honoured as a skip nor written.
- #[serde(default)]
- pub only: Option<String>,
- /// Re-import even when the global marker or an unchanged item ledger
- /// entry would normally skip the work.
- #[serde(default)]
- pub force: bool,
- /// Per-item info logging instead of debug.
- #[serde(default)]
- pub verbose: bool,
-}
-
-/// What kind of source a scanned item came from.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum SourceKind {
- /// Current flat `session_raw/{stem}.jsonl`.
- Jsonl,
- /// Legacy date-folder `session_raw/{DDMMYYYY}/{stem}.jsonl`.
- JsonlLegacyDir,
- /// Markdown-only session (no JSONL twin anywhere).
- Markdown,
-}
-
-/// Per-item action taken (or planned, in dry-run).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ItemAction {
- Imported,
- WouldImport,
- SkippedUnchanged,
- Failed,
-}
-
-/// Per-source report line in the summary.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ItemReport {
- pub session_key: String,
- /// Source path relative to the workspace root.
- pub source: String,
- pub kind: SourceKind,
- pub action: ItemAction,
- /// Journal stream the messages went to (absent for failures).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub stream: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub thread_id: Option<String>,
- pub messages: usize,
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub warnings: Vec<String>,
-}
-
-/// Whole-run summary returned by `session_import.run`.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct ImportSummary {
- pub dry_run: bool,
- /// True when the global marker short-circuited the scan.
- pub already_done: bool,
- pub scanned: usize,
- pub imported: usize,
- pub skipped: usize,
- pub failed: usize,
- pub messages_written: usize,
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub warnings: Vec<String>,
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub items: Vec<ItemReport>,
-}
-
-/// Usage roll-up carried on the session descriptor.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct DescriptorUsage {
- pub input: u64,
- pub output: u64,
- pub cached_input: u64,
- pub cost_usd: f64,
-}
-
-/// Source pointers preserved on the descriptor (workspace-relative).
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct DescriptorSource {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub jsonl: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub md: Option<String>,
-}
-
-/// Import provenance block on the descriptor.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct DescriptorImport {
- pub version: u32,
- pub imported_at: String,
- pub warnings: usize,
-}
-
-/// The `sessions/{session_key}` compatibility descriptor: maps the OpenHuman
-/// session key to TinyAgents-side identifiers and back.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct SessionDescriptor {
- pub session_key: String,
- /// Parent session key derived from the `__` stem chain (`None` = root).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub parent_session_key: Option<String>,
- /// From `_meta.thread_id`, or synthesized `imported-{session_key}`.
- pub thread_id: String,
- /// True when `thread_id` was synthesized because the source had none.
- #[serde(default)]
- pub thread_id_synthesized: bool,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub task_id: Option<String>,
- /// Run-ledger `agent_runs.id`s joined via `thread_id` (best-effort).
- #[serde(default, skip_serializing_if = "Vec::is_empty")]
- pub run_ids: Vec<String>,
- /// Journal stream holding this session's messages.
- pub stream: String,
- pub dispatcher: String,
- pub agent_name: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub agent_id: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub agent_type: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub provider: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub model: Option<String>,
- pub created: String,
- pub updated: String,
- pub turn_count: usize,
- pub usage: DescriptorUsage,
- pub source: DescriptorSource,
- pub import: DescriptorImport,
-}
-
-/// One message journal entry.
-///
-/// `ChatMessage` marks `id`/`extra_metadata` `skip_serializing` (they must
-/// not reach providers), so the journal carries its own full-fidelity record
-/// of what `read_transcript()` returns — including the reconstructed
-/// `openhuman_turn_usage` metadata.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct JournalMessage {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub id: Option<String>,
- pub role: String,
- pub content: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub extra_metadata: Option<Value>,
-}
-
-impl From<&ChatMessage> for JournalMessage {
- fn from(msg: &ChatMessage) -> Self {
- Self {
- id: msg.id.clone(),
- role: msg.role.clone(),
- content: msg.content.clone(),
- extra_metadata: msg.extra_metadata.clone(),
- }
- }
-}
-
-impl From<JournalMessage> for ChatMessage {
- fn from(rec: JournalMessage) -> Self {
- ChatMessage {
- id: rec.id,
- role: rec.role,
- content: rec.content,
- extra_metadata: rec.extra_metadata,
- cache_breakpoints: Vec::new(),
- }
- }
-}
-
-/// Item-ledger record under `migration_items/{sha256(relative source path)}`.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ItemLedgerRecord {
- pub version: u32,
- pub session_key: String,
- /// Workspace-relative source path.
- pub source: String,
- pub size: u64,
- pub mtime_ms: u64,
- pub stream: String,
- pub messages: usize,
- pub imported_at: String,
-}