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