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