garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/import.rs

raw

//! `midas sessions import`: conversations Claude Code had outside midas — a
//! workstation's, the agent container's claude.ai/code sessions — brought to
//! the hub's Sessions, to read and search beside the ones midas ran.
//!
//! It reads Claude Code's transcripts (`~/.claude/projects/<dir>/<id>.jsonl`,
//! one line per message) where they are, and sends each as the log a session
//! midas runs would have: what the person said, the agent's text, its tool
//! calls with what they were given and what came of them (clipped), its plan.
//! Thinking, subagents' own conversations and Claude Code's bookkeeping stay
//! behind. The hub keeps it as an ended session (sessions.rs, Imported); run
//! again, only a conversation that is new or has grown is sent.

use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};
use serde_json::{json, Value};

/// A tool's input string or output kept, in characters: enough to see what it
/// did; a session midas runs keeps more (`TOOL_TEXT`), but hundreds of
/// imported ones would make the hub's disk the transcripts' size again.
const KEEP: usize = 2000;
/// The agent's text in one item, at most; longer is split.
const TEXT: usize = 32 * 1024;
/// A part of a log sent at once, under the hub's `IMPORT_BODY`.
const PART: usize = 2 << 20;

/// One conversation, read.
#[derive(Debug, Default)]
pub struct Conversation {
    pub key: String,
    pub cwd: String,
    pub branch: String,
    pub title: String,
    pub prompt: String,
    pub created: i64,
    pub updated: i64,
    pub items: Vec<Value>,
}

fn clip(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let head: String = s.chars().take(max).collect();
    format!("{head}\n… ({} more characters)", s.chars().count() - max)
}

fn clip_input(input: &Value) -> Value {
    let mut v = input.clone();
    for (_, x) in v.as_object_mut().into_iter().flatten() {
        if let Some(s) = x.as_str().filter(|s| s.chars().count() > KEEP) {
            *x = json!(clip(s, KEEP));
        }
    }
    v
}

/// Between two tags, if the text has them.
fn tag<'a>(s: &'a str, name: &str) -> Option<&'a str> {
    let open = format!("<{name}>");
    let start = s.find(&open)? + open.len();
    let end = s[start..].find(&format!("</{name}>"))? + start;
    Some(s[start..end].trim())
}

/// Text without Claude Code's `<system-reminder>` blocks, which the person never wrote.
fn unreminded(s: &str) -> String {
    let mut out = String::new();
    let mut rest = s;
    while let Some(a) = rest.find("<system-reminder>") {
        out.push_str(&rest[..a]);
        match rest[a..].find("</system-reminder>") {
            Some(b) => rest = &rest[a + b + "</system-reminder>".len()..],
            None => {
                rest = "";
                break;
            }
        }
    }
    out.push_str(rest);
    out.trim().to_string()
}

/// What a line of the person's text is in the log: what they said, a slash
/// command as they typed it, a note of what happened (an interruption, a
/// background task done), or nothing (Claude Code's own output and caveats).
fn user_text(s: &str) -> Option<Value> {
    let s = unreminded(s);
    if s.is_empty() || s.starts_with("<local-command-") || s.starts_with("Caveat: ") {
        return None;
    }
    if let Some(name) = tag(&s, "command-name") {
        let args = tag(&s, "command-args").unwrap_or("");
        return Some(json!({"kind": "user", "text": format!("{name} {args}").trim()}));
    }
    if s.starts_with("<task-notification>") {
        let what = tag(&s, "summary").unwrap_or("a background task ended");
        return Some(json!({"kind": "status", "text": what}));
    }
    if s.starts_with("[Request interrupted by user") {
        return Some(json!({"kind": "status", "text": "interrupted"}));
    }
    Some(json!({"kind": "user", "text": s}))
}

fn timestamp(v: &Value) -> Option<i64> {
    chrono::DateTime::parse_from_rfc3339(v["timestamp"].as_str()?).ok().map(|t| t.timestamp())
}

/// A transcript, read. `None` when nobody said anything in it.
pub fn read(path: &Path) -> Result<Option<Conversation>> {
    let f = File::open(path).with_context(|| format!("opening {}", path.display()))?;
    let mut lines = Vec::new();
    for line in BufReader::new(f).lines() {
        if let Ok(v) = serde_json::from_str::<Value>(&line?) {
            lines.push(v);
        }
    }
    let mut c = conversation(lines);
    if let Some(c) = c.as_mut().filter(|c| c.key.is_empty()) {
        c.key = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string();
    }
    Ok(c)
}

/// A transcript's lines as one conversation. `None` when nobody said anything in it.
fn conversation(lines: Vec<Value>) -> Option<Conversation> {
    let mut c = Conversation::default();
    let (mut custom, mut ai, mut summary) = (None, None, None);
    for v in lines {
        let kind = v["type"].as_str().unwrap_or("");
        match kind {
            "custom-title" => custom = v["customTitle"].as_str().map(str::to_string),
            "ai-title" => ai = v["aiTitle"].as_str().map(str::to_string),
            "summary" => summary = v["summary"].as_str().map(str::to_string),
            _ => {}
        }
        // A subagent's own conversation is its tool call's business.
        if !matches!(kind, "user" | "assistant") || v["isSidechain"] == true {
            continue;
        }
        if c.key.is_empty() {
            c.key = v["sessionId"].as_str().unwrap_or("").to_string();
        }
        if let Some(cwd) = v["cwd"].as_str().filter(|s| !s.is_empty()) {
            c.cwd = cwd.to_string();
        }
        if let Some(b) = v["gitBranch"].as_str().filter(|s| !s.is_empty() && *s != "HEAD") {
            c.branch = b.to_string();
        }
        let at = timestamp(&v);
        if let Some(t) = at {
            if c.created == 0 || t < c.created {
                c.created = t;
            }
            c.updated = c.updated.max(t);
        }
        let mut push = |mut it: Value| {
            if let Some(t) = at {
                it["at"] = json!(t);
            }
            c.items.push(it);
        };
        let content = &v["message"]["content"];
        if kind == "user" {
            if v["isCompactSummary"] == true {
                push(json!({"kind": "status", "text": "the conversation was compacted here"}));
                continue;
            }
            if v["isMeta"] == true {
                continue;
            }
            if let Some(s) = content.as_str() {
                if let Some(it) = user_text(s) {
                    push(it);
                }
                continue;
            }
            let mut pictures = 0;
            for b in content.as_array().into_iter().flatten() {
                match b["type"].as_str() {
                    Some("text") => {
                        if let Some(it) = b["text"].as_str().and_then(user_text) {
                            push(it);
                        }
                    }
                    Some("image") => pictures += 1,
                    Some("tool_result") => {
                        let text = match &b["content"] {
                            Value::String(s) => s.clone(),
                            Value::Array(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join("\n"),
                            _ => String::new(),
                        };
                        let failed = b["is_error"] == true;
                        push(json!({"kind": "tool_update", "id": b["tool_use_id"], "status": if failed { "failed" } else { "completed" },
                                    "output": (!text.trim().is_empty()).then(|| clip(&text, KEEP))}));
                    }
                    _ => {}
                }
            }
            if pictures > 0 {
                push(json!({"kind": "status", "text": format!("{pictures} picture{} sent, not imported", if pictures == 1 { "" } else { "s" })}));
            }
        } else {
            for b in content.as_array().into_iter().flatten() {
                match b["type"].as_str() {
                    Some("text") => {
                        let t = b["text"].as_str().unwrap_or("").trim();
                        if !t.is_empty() {
                            push(json!({"kind": "agent", "text": t}));
                        }
                    }
                    Some("tool_use") => {
                        let name = b["name"].as_str().unwrap_or("tool");
                        let input = &b["input"];
                        if name == "TodoWrite" {
                            push(json!({"kind": "plan", "entries": crate::acp::plan(input)["entries"]}));
                            continue;
                        }
                        push(json!({"kind": "tool", "id": b["id"], "title": crate::acp::title(name, input), "status": "completed",
                                    "input": input.as_object().filter(|o| !o.is_empty()).map(|_| clip_input(input))}));
                    }
                    _ => {}
                }
            }
        }
    }
    c.items = merge_text(std::mem::take(&mut c.items));
    let first = c.items.iter().find(|i| i["kind"] == "user")?;
    c.prompt = first["text"].as_str().unwrap_or("").to_string();
    // A plan's result is the plan: its tool call has no item of its own.
    let calls: std::collections::HashSet<String> = c.items.iter().filter(|i| i["kind"] == "tool")
        .filter_map(|i| i["id"].as_str().map(str::to_string)).collect();
    c.items.retain(|i| i["kind"] != "tool_update" || i["id"].as_str().is_some_and(|id| calls.contains(id)));
    let line = c.prompt.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("A conversation").to_string();
    c.title = custom.or(ai).or(summary).unwrap_or(line).chars().take(80).collect();
    Some(c)
}

/// The agent's text blocks in a row as one item, a paragraph apart (the page
/// joins items as they are: a live session's are chunks of one stream), and
/// none longer than `TEXT`.
fn merge_text(items: Vec<Value>) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::with_capacity(items.len());
    for it in items {
        let joinable = it["kind"] == "agent" && out.last().is_some_and(|l| {
            l["kind"] == "agent" && l["text"].as_str().map_or(0, str::len) + it["text"].as_str().map_or(0, str::len) < TEXT
        });
        if joinable {
            let last = out.last_mut().expect("joinable has a last");
            let t = format!("{}\n\n{}", last["text"].as_str().unwrap_or(""), it["text"].as_str().unwrap_or(""));
            last["text"] = json!(t);
        } else if it["kind"] == "agent" && it["text"].as_str().map_or(0, str::len) > TEXT {
            let text: Vec<char> = it["text"].as_str().unwrap_or("").chars().collect();
            for part in text.chunks(TEXT / 4) {
                let mut p = it.clone();
                p["text"] = json!(part.iter().collect::<String>());
                out.push(p);
            }
        } else {
            out.push(it);
        }
    }
    out
}

/// The transcripts a path names: itself, or a directory's `*.jsonl` (not its
/// subdirectories, where Claude Code keeps subagents' conversations).
fn transcripts(p: &Path) -> Result<Vec<PathBuf>> {
    if p.is_file() {
        return Ok(vec![p.to_path_buf()]);
    }
    let mut v: Vec<PathBuf> = fs::read_dir(p).with_context(|| format!("reading {}", p.display()))?.flatten()
        .map(|e| e.path()).filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "jsonl")).collect();
    v.sort();
    Ok(v)
}

/// A worktree's name is what the board knows the session by; a main checkout's is no one's.
fn owner_of(cwd: &str) -> String {
    match cwd.split_once("/worktrees/") {
        Some((_, rest)) => rest.split('/').next().unwrap_or("").to_string(),
        None => String::new(),
    }
}

/// The project a conversation was had in: its checkout's `origin`, or, when
/// the worktree is gone, the checkout it was made from.
fn repo_of(cwd: &str) -> Option<String> {
    if cwd.is_empty() {
        return None;
    }
    let main = cwd.split_once("/.claude/worktrees/").map_or(cwd, |(m, _)| m);
    [cwd, main].into_iter().map(Path::new).filter(|d| d.is_dir()).find_map(crate::cli::repo_in)
}

/// Send one conversation: begin it at the hub, then its log in parts.
fn send(c: &Conversation, from: &str, replace: bool) -> Result<Option<String>> {
    let begin = crate::client::post("/v1/hosted/import", &json!({
        "key": c.key, "from": from, "cwd": c.cwd, "title": c.title, "prompt": c.prompt, "branch": c.branch,
        "owner": owner_of(&c.cwd), "repo": repo_of(&c.cwd), "created": c.created, "updated": c.updated, "replace": replace,
    }))?;
    let id = begin["id"].as_str().ok_or_else(|| anyhow!("the hub gave no id"))?.to_string();
    if let Some(have) = begin["have"].as_str() {
        eprintln!("  {id}: here already ({have})");
        return Ok(None);
    }
    let mut part: Vec<&Value> = Vec::new();
    let mut size = 0;
    let path = format!("/v1/hosted/{id}/import");
    for it in &c.items {
        let n = it.to_string().len();
        if !part.is_empty() && size + n > PART {
            crate::client::post(&path, &json!({"items": part, "done": false}))?;
            part.clear();
            size = 0;
        }
        part.push(it);
        size += n + 1;
    }
    crate::client::post(&path, &json!({"items": part, "done": true}))?;
    Ok(Some(id))
}

// ── claude.ai/code: the sessions the account had there ──────────────────────
//
// claude.ai keeps every claude.ai/code session's conversation — a bridged one
// (run in a self-hosted environment, the agent container) as well as one in
// Anthropic's cloud — after the machine it ran on has dropped its transcript
// (Claude Code keeps 30 days). Claude Code's `--teleport` reads them back with
// the claude.ai login, as here: the session list, then each one's events,
// whose payloads are its transcript's lines.

const CLAUDE_API: &str = "https://api.anthropic.com";

/// The claude.ai login Claude Code keeps on this machine: its OAuth token
/// (the macOS keychain, else `.credentials.json`) and its organisation.
fn claude_login() -> Result<(String, String)> {
    let home = PathBuf::from(std::env::var("HOME").unwrap_or_default());
    let dir = std::env::var("CLAUDE_CONFIG_DIR").map(PathBuf::from).unwrap_or_else(|_| home.join(".claude"));
    let keychain = std::process::Command::new("security").args(["find-generic-password", "-s", "Claude Code-credentials", "-w"]).output()
        .ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).to_string());
    let creds = match keychain {
        Some(c) => c,
        None => fs::read_to_string(dir.join(".credentials.json")).context("no claude.ai login here: sign Claude Code in (/login) first")?,
    };
    let creds: Value = serde_json::from_str(&creds).context("reading Claude Code's login")?;
    let token = creds["claudeAiOauth"]["accessToken"].as_str().context("Claude Code is not signed in to claude.ai here")?.to_string();
    let account = [dir.join(".claude.json"), home.join(".claude.json")].iter()
        .find_map(|p| fs::read_to_string(p).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()))
        .context("no ~/.claude.json")?;
    let org = account["oauthAccount"]["organizationUuid"].as_str().context("no organisation in ~/.claude.json")?.to_string();
    Ok((token, org))
}

/// A GET of claude.ai's API through curl, the token in its config on stdin
/// (never in the process list), as `curl_forgejo` does.
fn claude_get(login: &(String, String), path: &str) -> Result<Value> {
    claude_get_with(login, path, "")
}

/// `claude_get` with a beta its endpoint asks for (`anthropic-beta`).
fn claude_get_with(login: &(String, String), path: &str, beta: &str) -> Result<Value> {
    let quote = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
    let mut cfg = format!(
        "silent\nshow-error\nurl = {}\nheader = {}\nheader = {}\nheader = \"anthropic-version: 2023-06-01\"\nwrite-out = \"\\n%{{http_code}}\"\n",
        quote(&format!("{CLAUDE_API}{path}")), quote(&format!("Authorization: Bearer {}", login.0)), quote(&format!("x-organization-uuid: {}", login.1)));
    if !beta.is_empty() {
        cfg.push_str(&format!("header = {}\n", quote(&format!("anthropic-beta: {beta}"))));
    }
    let mut child = std::process::Command::new("curl").args(["-K", "-", "--max-time", "120"])
        .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped())
        .spawn().context("starting curl")?;
    std::io::Write::write_all(&mut child.stdin.take().expect("piped"), cfg.as_bytes())?;
    let out = child.wait_with_output()?;
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    let (body, code) = text.rsplit_once('\n').unwrap_or(("", text.as_str()));
    match code.trim().parse::<u16>().unwrap_or(0) {
        200 => serde_json::from_str(body).context("claude.ai's answer"),
        0 => anyhow::bail!("curl failed: {}", String::from_utf8_lossy(&out.stderr).trim()),
        401 => anyhow::bail!("claude.ai refused the login: run Claude Code once here (it renews its token), or /login"),
        c => anyhow::bail!("claude.ai answered {c} for {path}: {}", body.chars().take(200).collect::<String>()),
    }
}

/// Every claude.ai/code session of the account, archived ones too, newest first.
fn claude_sessions(login: &(String, String)) -> Result<Vec<Value>> {
    let mut all = Vec::new();
    let mut cursor: Option<String> = None;
    loop {
        let page = claude_get(login, &format!("/v1/code/sessions?limit=100{}",
            cursor.as_deref().map(|c| format!("&cursor={}", escape(c))).unwrap_or_default()))?;
        all.extend(page["data"].as_array().cloned().unwrap_or_default());
        match page["next_cursor"].as_str().filter(|c| !c.is_empty()) {
            Some(c) => cursor = Some(c.to_string()),
            None => return Ok(all),
        }
    }
}

fn escape(s: &str) -> String {
    s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
}

/// One session's conversation, from its events: each event's payload is a
/// transcript line, which needs only its type and time put back.
///
/// A session's lines stopped naming their directory in September 2026; the
/// directory is then its environment's (`dirs`, asked once each): a bridged
/// one's `config.directory`. An environment since removed is not found, but
/// the sessions it ran are the older ones, whose lines name it.
fn claude_conversation(login: &(String, String), session: &Value, dirs: &mut BTreeMap<String, String>) -> Result<Option<Conversation>> {
    let id = session["id"].as_str().context("a session without an id")?;
    let mut lines = Vec::new();
    let mut cursor: Option<String> = None;
    loop {
        let page = claude_get(login, &format!("/v1/code/sessions/{}/teleport-events?limit=1000{}", escape(id),
            cursor.as_deref().map(|c| format!("&cursor={}", escape(c))).unwrap_or_default()))?;
        lines.extend(event_lines(&page));
        match page["next_cursor"].as_str().filter(|c| !c.is_empty()) {
            Some(c) => cursor = Some(c.to_string()),
            None => break,
        }
    }
    let mut c = conversation(lines);
    if let Some(c) = c.as_mut() {
        // claude.ai's own title, as its list shows it.
        if let Some(t) = session["title"].as_str().filter(|t| !t.trim().is_empty()) {
            c.title = t.chars().take(80).collect();
        }
        if c.key.is_empty() {
            c.key = id.to_string();
        }
        if c.cwd.is_empty() {
            if let Some(env) = session["environment_id"].as_str().filter(|e| !e.is_empty()) {
                let dir = dirs.entry(env.to_string()).or_insert_with(|| {
                    claude_get_with(login, &format!("/v1/environments/{}?beta=true", escape(env)), "environments-2025-11-01").ok()
                        .and_then(|e| e["config"]["directory"].as_str().map(str::to_string)).unwrap_or_default()
                });
                c.cwd = dir.clone();
            }
        }
    }
    Ok(c)
}

/// A page of a session's events as its transcript's lines: each event's
/// payload, with its type and time put back where the payload lacks them.
fn event_lines(page: &Value) -> Vec<Value> {
    page["data"].as_array().into_iter().flatten().filter(|e| e["payload"].is_object()).map(|e| {
        let mut v = e["payload"].clone();
        if v["type"].is_null() {
            v["type"] = e["event_type"].clone();
        }
        if v["timestamp"].is_null() {
            v["timestamp"] = e["created_at"].clone();
        }
        v
    }).collect()
}

/// What an import does with each conversation it has read.
struct Run<'a> {
    from: String,
    cwd: &'a [String],
    dry_run: bool,
    replace: bool,
    sent: u32,
    kept: u32,
    empty: u32,
    elsewhere: u32,
    failed: u32,
}

impl Run<'_> {
    fn take(&mut self, c: Result<Option<Conversation>>, what: &str) {
        let c = match c {
            Ok(Some(c)) => c,
            Ok(None) => {
                self.empty += 1;
                return;
            }
            Err(e) => {
                eprintln!("{what}: {e:#}");
                self.failed += 1;
                return;
            }
        };
        // Only the work asked for: had in a directory whose path says so.
        if !self.cwd.is_empty() && !self.cwd.iter().any(|w| c.cwd.contains(w.as_str())) {
            self.elsewhere += 1;
            return;
        }
        let when = chrono::DateTime::from_timestamp(c.created, 0).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default();
        eprintln!("{when} {} ({} items) — {}", c.key, c.items.len(), c.title);
        if self.dry_run {
            return;
        }
        match send(&c, &self.from, self.replace) {
            Ok(Some(id)) => {
                self.sent += 1;
                println!("{id}");
            }
            Ok(None) => self.kept += 1,
            Err(e) => {
                eprintln!("  not sent: {e:#}");
                self.failed += 1;
            }
        }
    }
}

/// `midas sessions import`: every transcript the paths name, and with
/// `claude_ai` every claude.ai/code session of this machine's login, to the hub.
pub fn import_cmd(paths: &[PathBuf], claude_ai: bool, cwd: &[String], from: Option<&str>, dry_run: bool, replace: bool) -> Result<i32> {
    if paths.is_empty() && !claude_ai {
        anyhow::bail!("say what to import: transcripts or their directories, or --claude-ai");
    }
    let host = from.map(str::to_string).unwrap_or_else(|| {
        std::process::Command::new("hostname").arg("-s").output().ok()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|h| !h.is_empty())
            .unwrap_or_else(|| "elsewhere".into())
    });
    let mut run = Run { from: host, cwd, dry_run, replace, sent: 0, kept: 0, empty: 0, elsewhere: 0, failed: 0 };
    for p in paths {
        for t in transcripts(p)? {
            run.take(read(&t), &t.display().to_string());
        }
    }
    if claude_ai {
        let login = claude_login()?;
        let sessions = claude_sessions(&login)?;
        eprintln!("claude.ai/code: {} sessions", sessions.len());
        run.from = from.unwrap_or("claude.ai/code").to_string();
        let mut dirs = BTreeMap::new();
        for s in &sessions {
            run.take(claude_conversation(&login, s, &mut dirs), s["id"].as_str().unwrap_or("?"));
        }
    }
    eprintln!("{} imported, {} here already, {} with nothing said, {} had elsewhere, {} failed",
              run.sent, run.kept, run.empty, run.elsewhere, run.failed);
    Ok(if run.failed > 0 { 1 } else { 0 })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn line(v: Value) -> String {
        v.to_string() + "\n"
    }

    #[test]
    fn a_transcript_reads_as_a_sessions_log() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("abc-123.jsonl");
        let at = |s: u32| format!("2026-10-01T10:00:{s:02}.000Z");
        let base = |t: &str, s: u32| json!({"type": t, "sessionId": "abc-123", "cwd": "/home/agent/work/.claude/worktrees/bridge-x",
                                            "gitBranch": "fix/sea", "timestamp": at(s), "isSidechain": false});
        let mut text = String::new();
        let mut u = base("user", 0);
        u["message"] = json!({"role": "user", "content": "<system-reminder>ignore</system-reminder>Fix the sea"});
        text += &line(u);
        let mut meta = base("user", 1);
        meta["isMeta"] = json!(true);
        meta["message"] = json!({"role": "user", "content": "Caveat: hidden"});
        text += &line(meta);
        let mut a = base("assistant", 2);
        a["message"] = json!({"role": "assistant", "content": [
            {"type": "thinking", "thinking": "hmm"},
            {"type": "text", "text": "Looking."},
            {"type": "tool_use", "id": "t1", "name": "Bash", "input": {"command": "ls -la", "description": "List"}},
            {"type": "tool_use", "id": "t2", "name": "TodoWrite", "input": {"todos": [{"content": "a", "status": "in_progress"}]}},
        ]});
        text += &line(a);
        let mut r = base("user", 3);
        r["message"] = json!({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": "t1", "content": "x".repeat(KEEP + 10), "is_error": true},
            {"type": "tool_result", "tool_use_id": "t2", "content": "ok"},
        ]});
        text += &line(r);
        let mut side = base("assistant", 4);
        side["isSidechain"] = json!(true);
        side["message"] = json!({"role": "assistant", "content": [{"type": "text", "text": "a subagent"}]});
        text += &line(side);
        let mut b = base("assistant", 5);
        b["message"] = json!({"role": "assistant", "content": [{"type": "text", "text": "Done."}]});
        text += &line(b);
        let mut b2 = base("assistant", 6);
        b2["message"] = json!({"role": "assistant", "content": [{"type": "text", "text": "Really."}]});
        text += &line(b2);
        let mut c = base("user", 7);
        c["message"] = json!({"role": "user", "content": "<command-name>/clear</command-name>\n<command-args></command-args>"});
        text += &line(c);
        text += &line(json!({"type": "ai-title", "aiTitle": "Sea fix", "sessionId": "abc-123"}));
        fs::write(&p, text).unwrap();

        let c = read(&p).unwrap().unwrap();
        assert_eq!((c.key.as_str(), c.title.as_str(), c.branch.as_str(), c.prompt.as_str()), ("abc-123", "Sea fix", "fix/sea", "Fix the sea"));
        assert_eq!(owner_of(&c.cwd), "bridge-x");
        let kinds: Vec<&str> = c.items.iter().map(|i| i["kind"].as_str().unwrap()).collect();
        assert_eq!(kinds, ["user", "agent", "tool", "plan", "tool_update", "agent", "user"]);
        assert_eq!(c.items[2]["title"], "Bash: ls -la");
        assert_eq!(c.items[3]["entries"][0]["status"], "in_progress");
        assert_eq!(c.items[4]["status"], "failed");
        assert!(c.items[4]["output"].as_str().unwrap().ends_with("(10 more characters)"));
        assert_eq!(c.items[5]["text"], "Done.\n\nReally.");
        assert_eq!(c.items[6]["text"], "/clear");
        assert_eq!((c.created, c.updated - c.created), (c.items[0]["at"].as_i64().unwrap(), 7));
    }

    #[test]
    fn a_claude_ai_session_reads_from_its_events() {
        let page = json!({"data": [
            {"event_type": "user", "created_at": "2026-07-26T21:40:48Z",
             "payload": {"sessionId": "u-1", "cwd": "/home/agent/work", "message": {"role": "user", "content": "Bus stops"}}},
            {"event_type": "attachment", "created_at": "2026-07-26T21:40:49Z", "payload": null},
            {"event_type": "assistant", "created_at": "2026-07-26T21:40:50Z",
             "payload": {"type": "assistant", "sessionId": "u-1", "timestamp": "2026-07-26T21:40:51Z",
                         "message": {"role": "assistant", "content": [{"type": "text", "text": "On it."}]}}},
        ]});
        let lines = event_lines(&page);
        assert_eq!(lines.len(), 2, "an event without a line is no line");
        assert_eq!((lines[0]["type"].as_str(), lines[0]["timestamp"].as_str()), (Some("user"), Some("2026-07-26T21:40:48Z")));
        assert_eq!(lines[1]["timestamp"], "2026-07-26T21:40:51Z", "its own time kept");
        let c = conversation(lines).unwrap();
        assert_eq!((c.key.as_str(), c.cwd.as_str(), c.items.len(), c.updated - c.created), ("u-1", "/home/agent/work", 2, 3));
    }

    #[test]
    fn nothing_said_is_nothing_to_import() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("x.jsonl");
        fs::write(&p, line(json!({"type": "summary", "summary": "s"}))).unwrap();
        assert!(read(&p).unwrap().is_none());
    }
}