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
25 .store_id
26 .ok_or_else(|| anyhow::anyhow!("task not found in store: {task_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 = task_ref::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 ndjson::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 let s = n.to_string();
450 let mut result = String::new();
451 for (i, c) in s.chars().rev().enumerate() {
452 if i > 0 && i % 3 == 0 {
453 result.push(',');
454 }
455 result.push(c);
456 }
457 result.chars().rev().collect()
458}
459
460fn format_duration(secs: f64) -> String {
461 if secs < 60.0 {
462 format!("{secs:.0}s")
463 } else if secs < 3600.0 {
464 let mins = secs / 60.0;
465 if mins < 10.0 {
466 format!("{mins:.1}m")
467 } else {
468 format!("{mins:.0}m")
469 }
470 } else {
471 let hours = secs / 3600.0;
472 format!("{hours:.1}h")
473 }
474}
475
476fn extract_claude_text(v: &serde_json::Value) -> Option<String> {
478 let content = v.get("message")?.get("content")?.as_array()?;
479 let text: String = content
480 .iter()
481 .filter_map(|item| {
482 if item.get("type").and_then(|t| t.as_str()) == Some("text") {
483 item.get("text")
484 .and_then(|t| t.as_str())
485 .map(str::to_string)
486 } else {
487 None
488 }
489 })
490 .collect::<String>();
491 if text.is_empty() { None } else { Some(text) }
492}
493
494fn str_field(v: &serde_json::Value, key: &str) -> Option<String> {
496 v.get(key).and_then(|s| s.as_str()).map(str::to_string)
497}
498
499fn first_sentence(s: &str, max: usize) -> String {
501 let sentence_end = s
503 .char_indices()
504 .find(|(_, c)| matches!(c, '.' | '!' | '?'))
505 .map_or(s.len(), |(i, _)| i + 1);
506 let candidate = &s[..sentence_end.min(s.len())];
507 ndjson::truncate(candidate.trim(), max)
508}
509
510#[derive(Debug, Clone, Copy, Default)]
511pub enum ExportFormat {
512 #[default]
513 Markdown,
514 Json,
515 Raw,
516}
517
518impl FromStr for ExportFormat {
519 type Err = String;
520
521 fn from_str(s: &str) -> Result<Self, Self::Err> {
522 match s.to_lowercase().as_str() {
523 "markdown" | "md" => Ok(Self::Markdown),
524 "json" | "js" => Ok(Self::Json),
525 "raw" | "ndjson" => Ok(Self::Raw),
526 _ => Err(format!("unknown format: {s}")),
527 }
528 }
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534
535 #[test]
536 fn parse_claude_write_edit() {
537 let content = r#"
538{"type":"tool_use","tool":{"name":"Write","input":{"file_path":"src/lib.rs","content":"..."}}}
539{"type":"tool_use","tool":{"name":"Edit","input":{"file_path":"src/main.rs","old_string":"foo","new_string":"bar"}}}
540{"type":"tool_use","tool":{"name":"Read","input":{"file_path":"Cargo.toml"}}}
541"#;
542 let p = parse_output(content);
543 assert_eq!(p.files_changed, vec!["src/lib.rs", "src/main.rs"]);
544 assert_eq!(p.files_read, vec!["Cargo.toml"]);
545 assert_eq!(p.tool_counts["Write"], 1);
546 assert_eq!(p.tool_counts["Edit"], 1);
547 assert_eq!(p.tool_counts["Read"], 1);
548 }
549
550 #[test]
551 fn parse_claude_git_bash() {
552 let content = r#"
553{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}
554{"type":"tool_use","tool":{"name":"Bash","input":{"command":"cargo build"}}}
555{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git commit -m \"fix\""}}}
556"#;
557 let p = parse_output(content);
558 assert_eq!(p.git_commands.len(), 2);
559 assert!(p.git_commands.contains(&"git status".to_string()));
560 assert!(
561 p.git_commands
562 .contains(&"git commit -m \"fix\"".to_string())
563 );
564 assert_eq!(p.tool_counts["Bash"], 3);
565 }
566
567 #[test]
568 fn parse_opencode_tool_use() {
569 let content = r#"
570{"type":"tool_use","part":{"tool":"write","state":{"input":{"file_path":"README.md"}}}}
571{"type":"tool_use","part":{"tool":"bash","state":{"input":{"command":"git diff"}}}}
572"#;
573 let p = parse_output(content);
574 assert_eq!(p.files_changed, vec!["README.md"]);
575 assert_eq!(p.git_commands, vec!["git diff"]);
576 }
577
578 #[test]
579 fn parse_codex_command_execution() {
580 let content = r#"
581{"type":"item.completed","item":{"type":"command_execution","command":"git log --oneline -5"}}
582{"type":"item.completed","item":{"type":"command_execution","command":"cargo test"}}
583"#;
584 let p = parse_output(content);
585 assert_eq!(p.git_commands, vec!["git log --oneline -5"]);
586 assert_eq!(p.tool_counts["bash"], 2);
587 }
588
589 #[test]
590 fn parse_key_messages_from_assistant() {
591 let content = r#"
592{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"This is a short msg."}]}}
593{"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."}]}}
594"#;
595 let p = parse_output(content);
596 assert_eq!(p.key_messages.len(), 1);
598 assert!(p.key_messages[0].contains("authentication"));
599 }
600
601 #[test]
602 fn parse_key_messages_from_opencode_and_codex() {
603 let long = "x".repeat(41);
604 let content = format!(
605 r#"{{"type":"text","part":{{"text":"{long}"}}}}
606{{"type":"text","text":"{long}"}}
607{{"type":"text","part":{{"text":"short"}}}}
608{{"type":"item.completed","item":{{"type":"agent_message","text":"{long}"}}}}
609{{"type":"item.completed","item":{{"type":"agent_message","text":"short"}}}}
610"#
611 );
612 let p = parse_output(&content);
613 assert_eq!(p.key_messages.len(), 3);
614 }
615
616 #[test]
617 fn parse_key_messages_capped_at_ten() {
618 let line = format!(r#"{{"type":"text","text":"{}"}}"#, "y".repeat(50));
619 let content = vec![line; 15].join("\n");
620 let p = parse_output(&content);
621 assert_eq!(p.key_messages.len(), 10);
622 }
623
624 #[test]
625 fn parse_codex_git_commands_capped_at_twenty() {
626 let line = r#"{"type":"item.completed","item":{"type":"command_execution","command":"git status"}}"#;
627 let content = vec![line; 25].join("\n");
628 let p = parse_output(&content);
629 assert_eq!(p.git_commands.len(), 20);
630 assert_eq!(p.tool_counts["bash"], 25);
631 }
632
633 #[test]
634 fn parse_claude_git_commands_capped_at_twenty() {
635 let line = r#"{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}"#;
636 let content = vec![line; 25].join("\n");
637 let p = parse_output(&content);
638 assert_eq!(p.git_commands.len(), 20);
639 assert_eq!(p.tool_counts["Bash"], 25);
640 }
641
642 #[test]
643 fn parse_git_commands_share_one_cap_across_claude_and_codex() {
644 let claude =
645 r#"{"type":"tool_use","tool":{"name":"Bash","input":{"command":"git status"}}}"#;
646 let codex =
647 r#"{"type":"item.completed","item":{"type":"command_execution","command":"git diff"}}"#;
648 let content = [vec![claude; 12], vec![codex; 12]].concat().join("\n");
649 let p = parse_output(&content);
650 assert_eq!(p.git_commands.len(), 20);
651 assert_eq!(
652 p.git_commands.iter().filter(|c| *c == "git status").count(),
653 12
654 );
655 assert_eq!(
656 p.git_commands.iter().filter(|c| *c == "git diff").count(),
657 8
658 );
659 }
660
661 #[test]
662 fn parse_git_commands_keep_bare_git_first_line_and_truncate() {
663 let long = format!("git {}", "a".repeat(200));
664 let content = format!(
665 r#"{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"git"}}}}}}
666{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":" git status "}}}}}}
667{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"git status\ngit log"}}}}}}
668{{"type":"tool_use","tool":{{"name":"Bash","input":{{"command":"gitk"}}}}}}
669{{"type":"item.completed","item":{{"type":"command_execution","command":"{long}"}}}}
670"#
671 );
672 let p = parse_output(&content);
673 assert_eq!(
674 p.git_commands,
675 vec![
676 "git".to_string(),
677 "git status".to_string(),
678 "git status".to_string(),
679 format!("git {}…", "a".repeat(116)),
680 ]
681 );
682 }
683
684 #[test]
685 fn parse_empty_content() {
686 let p = parse_output("");
687 assert!(p.is_empty());
688 }
689
690 #[test]
691 fn first_sentence_with_period() {
692 let s = "I will fix the bug. Then run tests.";
693 assert_eq!(first_sentence(s, 200), "I will fix the bug.");
694 }
695
696 #[test]
697 fn first_sentence_truncated() {
698 let long = "abcdefghijklmnopqrstuvwxyz".repeat(10);
699 let result = first_sentence(&long, 20);
700 assert!(result.ends_with('…'));
701 }
702
703 #[test]
704 fn first_sentence_cuts_on_char_count_not_bytes() {
705 assert_eq!(first_sentence("ééééé", 3), "ééé…");
706 assert_eq!(first_sentence("ééé", 3), "ééé");
707 }
708
709 #[test]
710 fn first_sentence_without_terminator_keeps_whole_text() {
711 assert_eq!(first_sentence(" no terminator ", 50), "no terminator");
712 assert_eq!(first_sentence("", 5), "");
713 }
714
715 #[test]
716 fn format_num_thousands() {
717 assert_eq!(format_num(1_234_567), "1,234,567");
718 assert_eq!(format_num(999), "999");
719 }
720
721 #[test]
722 fn format_duration_variants() {
723 assert_eq!(format_duration(45.0), "45s");
724 assert_eq!(format_duration(90.0), "1.5m");
725 assert_eq!(format_duration(600.0), "10m");
726 assert_eq!(format_duration(7200.0), "2.0h");
727 }
728}