1use crate::cli::cost::format_cost;
2use crate::cli::init_store;
3use crate::cli::ndjson;
4use crate::cli::task_ref;
5use crate::store::Task;
6use crate::store::{TaskStatus, TaskStore};
7use anyhow::Context;
8use serde::Serialize;
9use std::collections::BTreeMap;
10use std::collections::BTreeSet;
11use std::collections::HashSet;
12use std::fs;
13use std::str::FromStr;
14use std::sync::Arc;
15
16pub async fn export(
17 task_id: &str,
18 attempt: Option<u32>,
19 format: ExportFormat,
20) -> anyhow::Result<()> {
21 let store = Arc::new(init_store().await?);
22
23 let resolved = task_ref::resolve(&store, task_id).await?;
24 let internal_id = resolved.require_store_id()?;
25 let repo = resolved.repo.clone();
26 let task = store.get(internal_id).await.context("task not found")?;
27
28 let attempt = if let Some(n) = attempt {
29 n
30 } else {
31 let runs = store.get_runs(internal_id).await?;
32 if runs.is_empty() {
33 anyhow::bail!("no attempts found for task");
34 }
35 let max_attempt = runs.iter().map(|r| r.attempt).max().unwrap_or(1);
36 u32::try_from(max_attempt).unwrap_or(1)
37 };
38
39 let output_path = task_ref::state_dir(&resolved)?
40 .join("attempts")
41 .join(attempt.to_string())
42 .join("output.json");
43
44 if !output_path.exists() {
45 anyhow::bail!(
46 "attempt {attempt} not found (no output file at {})",
47 output_path.display()
48 );
49 }
50
51 let content = fs::read_to_string(&output_path)?;
52
53 match format {
54 ExportFormat::Markdown => export_markdown(&task, attempt, &content, &store, &repo).await,
55 ExportFormat::Json => export_json(&task, attempt, &content),
56 ExportFormat::Raw => {
57 println!("{content}");
58 Ok(())
59 }
60 }
61}
62
63struct ParsedOutput {
65 files_changed: Vec<String>,
67 files_read: Vec<String>,
69 tool_counts: BTreeMap<String, usize>,
71 git_commands: Vec<String>,
73 key_messages: Vec<String>,
75}
76
77impl ParsedOutput {
78 fn is_empty(&self) -> bool {
79 self.files_changed.is_empty()
80 && self.files_read.is_empty()
81 && self.tool_counts.is_empty()
82 && self.git_commands.is_empty()
83 && self.key_messages.is_empty()
84 }
85}
86
87fn parse_output(content: &str) -> ParsedOutput {
94 let mut files_changed: BTreeSet<String> = BTreeSet::new();
95 let mut files_read: BTreeSet<String> = BTreeSet::new();
96 let mut tool_counts: BTreeMap<String, usize> = BTreeMap::default();
97 let mut git_commands: Vec<String> = Vec::new();
98 let mut key_messages: Vec<String> = Vec::new();
99
100 for line in content.lines() {
101 let trimmed = line.trim();
102 if trimmed.is_empty() {
103 continue;
104 }
105 let v: serde_json::Value = match serde_json::from_str(trimmed) {
106 Ok(v) => v,
107 Err(_) => continue,
108 };
109
110 let event_type = v.get("type").and_then(|t| t.as_str()).unwrap_or("");
111
112 match event_type {
113 "assistant" => {
115 if let Some(text) = extract_claude_text(&v) {
116 push_key_message(&mut key_messages, &text);
117 }
118 }
119
120 "tool_use" if v.get("tool").is_some() => {
121 if let Some(tool) = v.get("tool") {
123 let name = tool.get("name").and_then(|n| n.as_str()).unwrap_or("?");
124 *tool_counts.entry(name.to_string()).or_default() += 1;
125 let input = tool.get("input");
126 record_file_or_command(
127 name,
128 input,
129 &mut files_changed,
130 &mut files_read,
131 &mut git_commands,
132 );
133 }
134 }
135
136 "text" => {
138 let text = v
139 .get("part")
140 .and_then(|p| p.get("text"))
141 .and_then(|t| t.as_str())
142 .or_else(|| v.get("text").and_then(|t| t.as_str()))
143 .unwrap_or("");
144 push_key_message(&mut key_messages, text);
145 }
146
147 "tool_use" if v.get("part").is_some() => {
148 if let Some(part) = v.get("part") {
150 let name = part.get("tool").and_then(|t| t.as_str()).unwrap_or("?");
151 *tool_counts.entry(name.to_string()).or_default() += 1;
152 let input = part.get("state").and_then(|s| s.get("input"));
153 record_file_or_command(
154 name,
155 input,
156 &mut files_changed,
157 &mut files_read,
158 &mut git_commands,
159 );
160 }
161 }
162
163 "item.completed" => {
165 if let Some(item) = v.get("item") {
166 let item_type = item.get("type").and_then(|t| t.as_str()).unwrap_or("");
167 match item_type {
168 "agent_message" => {
169 let text = item.get("text").and_then(|t| t.as_str()).unwrap_or("");
170 push_key_message(&mut key_messages, text);
171 }
172 "command_execution" => {
173 let cmd = item.get("command").and_then(|c| c.as_str()).unwrap_or("");
174 *tool_counts.entry("bash".to_string()).or_default() += 1;
175 push_git_command(&mut git_commands, cmd);
176 }
177 _ => {}
178 }
179 }
180 }
181
182 _ => {}
183 }
184 }
185
186 ParsedOutput {
187 files_changed: files_changed
188 .into_iter()
189 .chain(ndjson::extract_files_changed(content))
190 .collect::<BTreeSet<_>>()
191 .into_iter()
192 .collect(),
193 files_read: files_read.into_iter().collect(),
194 tool_counts,
195 git_commands,
196 key_messages,
197 }
198}
199
200fn push_key_message(key_messages: &mut Vec<String>, text: &str) {
202 if text.len() > 40 && key_messages.len() < 10 {
203 key_messages.push(first_sentence(text, 160));
204 }
205}
206
207const MAX_GIT_COMMANDS: usize = 20;
208const GIT_COMMAND_MAX_CHARS: usize = 120;
209
210fn push_git_command(git_commands: &mut Vec<String>, cmd: &str) {
211 let first_line = cmd.lines().next().unwrap_or("").trim();
212 if (first_line.starts_with("git ") || first_line == "git")
213 && git_commands.len() < MAX_GIT_COMMANDS
214 {
215 git_commands.push(ndjson::truncate(first_line, GIT_COMMAND_MAX_CHARS));
216 }
217}
218
219fn record_file_or_command(
221 name: &str,
222 input: Option<&serde_json::Value>,
223 files_changed: &mut BTreeSet<String>,
224 files_read: &mut BTreeSet<String>,
225 git_commands: &mut Vec<String>,
226) {
227 let Some(input) = input else { return };
228 match name {
229 "Write" | "write" | "NotebookEdit" | "Edit" | "edit" | "MultiEdit" => {
230 if let Some(p) = str_field(input, "file_path") {
231 files_changed.insert(p);
232 }
233 }
234 "Read" | "read" => {
235 if let Some(p) = str_field(input, "file_path") {
236 files_read.insert(p);
237 }
238 }
239 "Bash" | "bash" => {
240 if let Some(cmd) = str_field(input, "command") {
241 push_git_command(git_commands, &cmd);
242 }
243 }
244 _ => {}
245 }
246}
247
248async fn export_markdown(
249 task: &Task,
250 attempt: u32,
251 content: &str,
252 store: &Arc<TaskStore>,
253 _repo: &str,
254) -> anyhow::Result<()> {
255 let runs = store.get_runs(task.id).await?;
256 let attempt_i32 = i32::try_from(attempt).ok();
257 let attempt_run = runs.iter().find(|r| Some(r.attempt) == attempt_i32);
258
259 let agent = task.agent.as_deref().unwrap_or("unknown");
260 let model = task.model.as_deref().unwrap_or("-");
261
262 let duration = attempt_run.map_or(0.0, |r| r.duration_secs);
263 let duration_str = format_duration(duration);
264
265 let input_tokens = task.input_tokens;
266 let output_tokens = task.output_tokens;
267
268 let cost = task.total_cost_usd;
269
270 println!(
271 "# Session: {} (Attempt {})",
272 task_id_display(task.id, task.external_id.as_ref()),
273 attempt
274 );
275 println!();
276 println!("**Agent**: {agent} ({model})");
277 println!("**Duration**: {duration_str}");
278 println!(
279 "**Tokens**: {} in / {} out",
280 format_num(input_tokens),
281 format_num(output_tokens)
282 );
283 if input_tokens > 0 || output_tokens > 0 || cost > 0.0 {
284 println!("**Cost**: {}", format_cost(cost));
285 }
286 println!("---");
287
288 if content.trim().is_empty() {
289 println!("(no output captured)");
290 return Ok(());
291 }
292
293 let parsed = parse_output(content);
295 if !parsed.is_empty() {
296 println!();
297 println!("## Summary");
298
299 if !parsed.files_changed.is_empty() {
300 println!();
301 println!("### Files Changed");
302 for f in &parsed.files_changed {
303 println!("- `{f}`");
304 }
305 }
306
307 if !parsed.tool_counts.is_empty() {
308 println!();
309 println!("### Tool Usage");
310 let mut counts: Vec<(&String, &usize)> = parsed.tool_counts.iter().collect();
312 counts.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
313 for (tool, count) in &counts {
314 println!("- **{tool}**: {count}");
315 }
316 }
317
318 if !parsed.git_commands.is_empty() {
319 println!();
320 println!("### Git Context");
321 let mut seen = HashSet::new();
323 for cmd in &parsed.git_commands {
324 if seen.insert(cmd.as_str()) {
325 println!("- `{cmd}`");
326 }
327 }
328 }
329
330 if !parsed.key_messages.is_empty() {
331 println!();
332 println!("### Key Decisions");
333 for msg in &parsed.key_messages {
334 println!("- {msg}");
335 }
336 }
337 }
338
339 println!();
341 println!("## Output");
342 println!();
343
344 let mut formatter = ndjson::Formatter::new(false);
345 for line in content.lines() {
346 ndjson::print(&formatter.format(line));
347 }
348
349 let summary = &task.summary;
351 if !summary.is_empty() {
352 println!();
353 println!("---");
354 println!();
355 println!("## Result");
356 println!();
357
358 let status = if task.status == TaskStatus::Done {
359 "success"
360 } else if task.status == TaskStatus::Blocked {
361 "blocked"
362 } else {
363 "incomplete"
364 };
365
366 println!("**Status**: {status}");
367 println!("**Summary**: {summary}");
368 }
369
370 let error = &task.last_error;
371 if !error.is_empty() {
372 println!();
373 println!("**Error**: {error}");
374 }
375
376 Ok(())
377}
378
379fn export_json(task: &Task, attempt: u32, content: &str) -> anyhow::Result<()> {
380 #[derive(Serialize)]
381 struct SessionExport {
382 task_id: i64,
383 external_id: Option<String>,
384 attempt: u32,
385 agent: Option<String>,
386 model: Option<String>,
387 input_tokens: i64,
388 output_tokens: i64,
389 total_cost_usd: f64,
390 summary: String,
391 last_error: String,
392 status: String,
393 files_changed: Vec<String>,
394 files_read: Vec<String>,
395 tool_counts: BTreeMap<String, usize>,
396 git_commands: Vec<String>,
397 key_messages: Vec<String>,
398 output: Vec<serde_json::Value>,
399 }
400
401 let output_lines: Vec<serde_json::Value> = content
402 .lines()
403 .filter_map(|line| {
404 let trimmed = line.trim();
405 if trimmed.is_empty() {
406 return None;
407 }
408 serde_json::from_str(trimmed).ok()
409 })
410 .collect();
411
412 let parsed = parse_output(content);
413
414 let export = SessionExport {
415 task_id: task.id,
416 external_id: task.external_id.clone(),
417 attempt,
418 agent: task.agent.clone(),
419 model: task.model.clone(),
420 input_tokens: task.input_tokens,
421 output_tokens: task.output_tokens,
422 total_cost_usd: task.total_cost_usd,
423 summary: task.summary.clone(),
424 last_error: task.last_error.clone(),
425 status: task.status.as_str().to_string(),
426 files_changed: parsed.files_changed,
427 files_read: parsed.files_read,
428 tool_counts: parsed.tool_counts,
429 git_commands: parsed.git_commands,
430 key_messages: parsed.key_messages,
431 output: output_lines,
432 };
433
434 println!("{}", serde_json::to_string_pretty(&export)?);
435
436 Ok(())
437}
438
439fn task_id_display(internal_id: i64, external_id: Option<&String>) -> String {
440 match external_id {
441 Some(ext) => format!("{ext}:{internal_id}"),
442 None => format!("internal:{internal_id}"),
443 }
444}
445
446fn format_num(n: i64) -> String {
447 let s = n.to_string();
448 let mut result = String::new();
449 for (i, c) in s.chars().rev().enumerate() {
450 if i > 0 && i % 3 == 0 {
451 result.push(',');
452 }
453 result.push(c);
454 }
455 result.chars().rev().collect()
456}
457
458fn format_duration(secs: f64) -> String {
459 if secs < 60.0 {
460 format!("{secs:.0}s")
461 } else if secs < 3600.0 {
462 let mins = secs / 60.0;
463 if mins < 10.0 {
464 format!("{mins:.1}m")
465 } else {
466 format!("{mins:.0}m")
467 }
468 } else {
469 let hours = secs / 3600.0;
470 format!("{hours:.1}h")
471 }
472}
473
474fn extract_claude_text(v: &serde_json::Value) -> Option<String> {
476 let content = v.get("message")?.get("content")?.as_array()?;
477 let text: String = content
478 .iter()
479 .filter_map(|item| {
480 if item.get("type").and_then(|t| t.as_str()) == Some("text") {
481 item.get("text")
482 .and_then(|t| t.as_str())
483 .map(str::to_string)
484 } else {
485 None
486 }
487 })
488 .collect::<String>();
489 if text.is_empty() { None } else { Some(text) }
490}
491
492fn str_field(v: &serde_json::Value, key: &str) -> Option<String> {
494 v.get(key).and_then(|s| s.as_str()).map(str::to_string)
495}
496
497fn first_sentence(s: &str, max: usize) -> String {
499 let sentence_end = s
501 .char_indices()
502 .find(|(_, c)| matches!(c, '.' | '!' | '?'))
503 .map_or(s.len(), |(i, _)| i + 1);
504 let candidate = &s[..sentence_end.min(s.len())];
505 ndjson::truncate(candidate.trim(), max)
506}
507
508#[derive(Debug, Clone, Copy, Default)]
509pub enum ExportFormat {
510 #[default]
511 Markdown,
512 Json,
513 Raw,
514}
515
516impl FromStr for ExportFormat {
517 type Err = String;
518
519 fn from_str(s: &str) -> Result<Self, Self::Err> {
520 match s.to_lowercase().as_str() {
521 "markdown" | "md" => Ok(Self::Markdown),
522 "json" | "js" => Ok(Self::Json),
523 "raw" | "ndjson" => Ok(Self::Raw),
524 _ => Err(format!("unknown format: {s}")),
525 }
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
532
533 #[test]
534 fn parse_claude_write_edit() {
535 let content = r#"
536{"type":"tool_use","tool":{"name":"Write","input":{"file_path":"src/lib.rs","content":"..."}}}
537{"type":"tool_use","tool":{"name":"Edit","input":{"file_path":"src/main.rs","old_string":"foo","new_string":"bar"}}}
538{"type":"tool_use","tool":{"name":"Read","input":{"file_path":"Cargo.toml"}}}
539"#;
540 let p = parse_output(content);
541 assert_eq!(p.files_changed, vec!["src/lib.rs", "src/main.rs"]);
542 assert_eq!(p.files_read, vec!["Cargo.toml"]);
543 assert_eq!(p.tool_counts["Write"], 1);
544 assert_eq!(p.tool_counts["Edit"], 1);
545 assert_eq!(p.tool_counts["Read"], 1);
546 }
547
548 #[test]
549 fn parse_claude_git_bash() {
550 let content = r#"
551{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}
552{"type":"tool_use","tool":{"name":"Bash","input":{"command":"cargo build"}}}
553{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git commit -m \"fix\""}}}
554"#;
555 let p = parse_output(content);
556 assert_eq!(p.git_commands.len(), 2);
557 assert!(p.git_commands.contains(&"git status".to_string()));
558 assert!(
559 p.git_commands
560 .contains(&"git commit -m \"fix\"".to_string())
561 );
562 assert_eq!(p.tool_counts["Bash"], 3);
563 }
564
565 #[test]
566 fn parse_opencode_tool_use() {
567 let content = r#"
568{"type":"tool_use","part":{"tool":"write","state":{"input":{"file_path":"README.md"}}}}
569{"type":"tool_use","part":{"tool":"bash","state":{"input":{"command":"git diff"}}}}
570"#;
571 let p = parse_output(content);
572 assert_eq!(p.files_changed, vec!["README.md"]);
573 assert_eq!(p.git_commands, vec!["git diff"]);
574 }
575
576 #[test]
577 fn parse_codex_command_execution() {
578 let content = r#"
579{"type":"item.completed","item":{"type":"command_execution","command":"git log --oneline -5"}}
580{"type":"item.completed","item":{"type":"command_execution","command":"cargo test"}}
581"#;
582 let p = parse_output(content);
583 assert_eq!(p.git_commands, vec!["git log --oneline -5"]);
584 assert_eq!(p.tool_counts["bash"], 2);
585 }
586
587 #[test]
588 fn parse_key_messages_from_assistant() {
589 let content = r#"
590{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"This is a short msg."}]}}
591{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"I have analyzed the codebase and found that the main issue is in the authentication module."}]}}
592"#;
593 let p = parse_output(content);
594 assert_eq!(p.key_messages.len(), 1);
596 assert!(p.key_messages[0].contains("authentication"));
597 }
598
599 #[test]
600 fn parse_key_messages_from_opencode_and_codex() {
601 let long = "x".repeat(41);
602 let content = format!(
603 r#"{{"type":"text","part":{{"text":"{long}"}}}}
604{{"type":"text","text":"{long}"}}
605{{"type":"text","part":{{"text":"short"}}}}
606{{"type":"item.completed","item":{{"type":"agent_message","text":"{long}"}}}}
607{{"type":"item.completed","item":{{"type":"agent_message","text":"short"}}}}
608"#
609 );
610 let p = parse_output(&content);
611 assert_eq!(p.key_messages.len(), 3);
612 }
613
614 #[test]
615 fn parse_key_messages_capped_at_ten() {
616 let line = format!(r#"{{"type":"text","text":"{}"}}"#, "y".repeat(50));
617 let content = vec![line; 15].join("\n");
618 let p = parse_output(&content);
619 assert_eq!(p.key_messages.len(), 10);
620 }
621
622 #[test]
623 fn parse_codex_git_commands_capped_at_twenty() {
624 let line = r#"{"type":"item.completed","item":{"type":"command_execution","command":"git status"}}"#;
625 let content = vec![line; 25].join("\n");
626 let p = parse_output(&content);
627 assert_eq!(p.git_commands.len(), 20);
628 assert_eq!(p.tool_counts["bash"], 25);
629 }
630
631 #[test]
632 fn parse_claude_git_commands_capped_at_twenty() {
633 let line = r#"{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}"#;
634 let content = vec![line; 25].join("\n");
635 let p = parse_output(&content);
636 assert_eq!(p.git_commands.len(), 20);
637 assert_eq!(p.tool_counts["Bash"], 25);
638 }
639
640 #[test]
641 fn parse_git_commands_share_one_cap_across_claude_and_codex() {
642 let claude =
643 r#"{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}"#;
644 let codex =
645 r#"{"type":"item.completed","item":{"type":"command_execution","command":"git diff"}}"#;
646 let content = [vec![claude; 12], vec![codex; 12]].concat().join("\n");
647 let p = parse_output(&content);
648 assert_eq!(p.git_commands.len(), 20);
649 assert_eq!(
650 p.git_commands.iter().filter(|c| *c == "git status").count(),
651 12
652 );
653 assert_eq!(
654 p.git_commands.iter().filter(|c| *c == "git diff").count(),
655 8
656 );
657 }
658
659 #[test]
660 fn parse_git_commands_keep_bare_git_first_line_and_truncate() {
661 let long = format!("git {}", "a".repeat(200));
662 let content = format!(
663 r#"{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"git"}}}}}}
664{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":" git status "}}}}}}
665{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"git status\ngit log"}}}}}}
666{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"gitk"}}}}}}
667{{"type":"item.completed","item":{{"type":"command_execution","command":"{long}"}}}}
668"#
669 );
670 let p = parse_output(&content);
671 assert_eq!(
672 p.git_commands,
673 vec![
674 "git".to_string(),
675 "git status".to_string(),
676 "git status".to_string(),
677 format!("git {}…", "a".repeat(116)),
678 ]
679 );
680 }
681
682 #[test]
683 fn parse_empty_content() {
684 let p = parse_output("");
685 assert!(p.is_empty());
686 }
687
688 #[test]
689 fn first_sentence_with_period() {
690 let s = "I will fix the bug. Then run tests.";
691 assert_eq!(first_sentence(s, 200), "I will fix the bug.");
692 }
693
694 #[test]
695 fn first_sentence_truncated() {
696 let long = "abcdefghijklmnopqrstuvwxyz".repeat(10);
697 let result = first_sentence(&long, 20);
698 assert!(result.ends_with('…'));
699 }
700
701 #[test]
702 fn first_sentence_cuts_on_char_count_not_bytes() {
703 assert_eq!(first_sentence("ééééé", 3), "ééé…");
704 assert_eq!(first_sentence("ééé", 3), "ééé");
705 }
706
707 #[test]
708 fn first_sentence_without_terminator_keeps_whole_text() {
709 assert_eq!(first_sentence(" no terminator ", 50), "no terminator");
710 assert_eq!(first_sentence("", 5), "");
711 }
712
713 #[test]
714 fn format_num_thousands() {
715 assert_eq!(format_num(1_234_567), "1,234,567");
716 assert_eq!(format_num(999), "999");
717 }
718
719 #[test]
720 fn format_duration_variants() {
721 assert_eq!(format_duration(45.0), "45s");
722 assert_eq!(format_duration(90.0), "1.5m");
723 assert_eq!(format_duration(600.0), "10m");
724 assert_eq!(format_duration(7200.0), "2.0h");
725 }
726}