| 1 | //! `/export` command — portable handler over the session-export facet |
| 2 | //! (FEAT-025 D1-D9). |
| 3 | //! |
| 4 | //! Parsing, document rendering, redaction, operation sequencing, and result |
| 5 | //! composition are portable: this module depends only on the external command |
| 6 | //! contract, `chrono`, the shared pure sanitizer in |
| 7 | //! [`codewhale_sanitize::sanitize`], and the shared session `CommandResult`. |
| 8 | //! Concrete `App`, clipboard, filesystem, snapshot, history, and turn-handoff |
| 9 | //! access stays behind `CommandSessionExportContext` (D1). Helpers, tests, and |
| 10 | //! this handler therefore carry no TUI, client, configuration, or filesystem |
| 11 | //! dependency, so the slice can move to `codewhale-commands` unchanged (D8/D10). |
| 12 | //! |
| 13 | //! A conversation renders to Markdown here, or to a self-contained HTML page |
| 14 | //! or a structured JSON document in the sibling `export_html` and |
| 15 | //! `export_json` modules, all from the same sanitized projection. |
| 16 | //! |
| 17 | //! Known limitations: HTML and JSON omit the workspace restore-point table, |
| 18 | //! which is local state with no meaning outside this machine; HTML shows |
| 19 | //! message text verbatim instead of rendering its Markdown; `--no-tools` |
| 20 | //! cannot filter the visible-history fallback, which carries no structured |
| 21 | //! tool blocks; turn handoffs and clipboard exports are Markdown only. |
| 22 | |
| 23 | use std::collections::HashMap; |
| 24 | use std::fmt::Write as FmtWrite; |
| 25 | use std::path::{Path, PathBuf}; |
| 26 | |
| 27 | use codewhale_command_contract::facets::{ |
| 28 | CommandSessionExportContext, ConversationExportProjection, ExportBlock, ExportMessage, |
| 29 | ExportMetadata, ExportTurnOutcome, HistoryEntry, RestorePointProjection, RestoreSnapshot, |
| 30 | TranscriptProjection, TurnHandoffProjection, |
| 31 | }; |
| 32 | use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler}; |
| 33 | use codewhale_command_contract::metadata::{ |
| 34 | CommandInfo as ContractInfo, RegisterCommand as ContractRegisterCommand, |
| 35 | }; |
| 36 | use codewhale_sanitize::sanitize::{ |
| 37 | inline_text, is_internal_role, redact_json, redact_url_for_display, sanitize_text, |
| 38 | }; |
| 39 | use serde_json::Value; |
| 40 | |
| 41 | use super::CommandResult; |
| 42 | |
| 43 | pub(in crate::commands) struct ExportCmd; |
| 44 | |
| 45 | pub(in crate::commands) const CONTRACT_INFO: ContractInfo = ContractInfo { |
| 46 | name: "export", |
| 47 | aliases: &["daochu"], |
| 48 | usage: "/export [clipboard|file [path]|turn [clipboard|file [path]]] [--format md|html|json] [--no-tools] [--force]", |
| 49 | description_key: "cmd_export_description", |
| 50 | }; |
| 51 | |
| 52 | impl ContractRegisterCommand<CommandResult> for ExportCmd { |
| 53 | fn info() -> &'static ContractInfo { |
| 54 | &CONTRACT_INFO |
| 55 | } |
| 56 | |
| 57 | fn handler() -> CommandHandler<CommandResult> { |
| 58 | CommandHandler::Contextual { |
| 59 | capabilities: CommandCapabilities::SESSION_EXPORT, |
| 60 | handler: export_contextual, |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | pub(in crate::commands) fn export_contextual( |
| 66 | contexts: CommandContexts<'_>, |
| 67 | arg: Option<&str>, |
| 68 | ) -> CommandResult { |
| 69 | let parts = contexts.into_parts(); |
| 70 | let Some(export) = parts.export.as_deref() else { |
| 71 | return CommandResult::error("Command capability unavailable: session_export".to_string()); |
| 72 | }; |
| 73 | export_portable(export, arg) |
| 74 | } |
| 75 | |
| 76 | /// Portable `/export` composed entirely from contract-owned data and facet |
| 77 | /// operations. Parse first, render the selected scope second, then run the |
| 78 | /// destination-specific sequence (D6/D7). |
| 79 | pub(in crate::commands) fn export_portable( |
| 80 | export: &dyn CommandSessionExportContext, |
| 81 | arg: Option<&str>, |
| 82 | ) -> CommandResult { |
| 83 | let request = match parse_request(arg) { |
| 84 | Ok(request) => request, |
| 85 | Err(err) => return CommandResult::error(err), |
| 86 | }; |
| 87 | let (label, stem, document) = match request.scope { |
| 88 | ExportScope::Conversation => { |
| 89 | let projection = export.conversation_projection(); |
| 90 | let stem = export_file_stem(&projection.metadata); |
| 91 | let document = render_export(projection, request.format, request.include_tools); |
| 92 | ("Conversation", stem, document) |
| 93 | } |
| 94 | ExportScope::Turn => ( |
| 95 | "Turn handoff", |
| 96 | format!( |
| 97 | "codewhale-turn-{}", |
| 98 | file_timestamp(chrono::Utc::now().timestamp()) |
| 99 | ), |
| 100 | sanitize_turn_handoff(&export.turn_handoff_projection()), |
| 101 | ), |
| 102 | }; |
| 103 | |
| 104 | match request.destination { |
| 105 | ExportDestination::Clipboard => copy_to_clipboard(export, label, &document), |
| 106 | ExportDestination::File { path, force } => { |
| 107 | let path = match path { |
| 108 | Some(path) => export.resolve_export_path(&path), |
| 109 | None => { |
| 110 | export.default_export_path(&format!("{stem}.{}", request.format.extension())) |
| 111 | } |
| 112 | }; |
| 113 | let path = match path { |
| 114 | Ok(path) => path, |
| 115 | Err(err) => return CommandResult::error(err), |
| 116 | }; |
| 117 | match export.write_export_file(&path, document.as_bytes(), force) { |
| 118 | Ok(()) => CommandResult::message(format!( |
| 119 | "{label} exported to {} ({}, {} lines{}){}", |
| 120 | path.display(), |
| 121 | request.format.name(), |
| 122 | document.lines().count(), |
| 123 | redaction_note(count_redactions(&document)), |
| 124 | if force { |
| 125 | " (overwrite explicitly allowed)" |
| 126 | } else { |
| 127 | "" |
| 128 | } |
| 129 | )), |
| 130 | Err(err) => CommandResult::error(format!( |
| 131 | "Failed to export {label} to {}: {err}", |
| 132 | path.display() |
| 133 | )), |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | fn render_export( |
| 140 | projection: ConversationExportProjection, |
| 141 | format: ExportFormat, |
| 142 | include_tools: bool, |
| 143 | ) -> String { |
| 144 | let projection = if include_tools { |
| 145 | projection |
| 146 | } else { |
| 147 | without_tool_blocks(projection) |
| 148 | }; |
| 149 | match format { |
| 150 | ExportFormat::Markdown => render_conversation(projection), |
| 151 | ExportFormat::Html => super::export_html::render(projection), |
| 152 | ExportFormat::Json => super::export_json::render(projection), |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | fn is_tool_block(block: &ExportBlock) -> bool { |
| 157 | matches!( |
| 158 | block, |
| 159 | ExportBlock::ToolCall { .. } |
| 160 | | ExportBlock::ToolResult { .. } |
| 161 | | ExportBlock::ServerToolCall { .. } |
| 162 | | ExportBlock::ToolSearchResult { .. } |
| 163 | | ExportBlock::CodeExecutionResult { .. } |
| 164 | ) |
| 165 | } |
| 166 | |
| 167 | fn without_tool_blocks( |
| 168 | mut projection: ConversationExportProjection, |
| 169 | ) -> ConversationExportProjection { |
| 170 | if let TranscriptProjection::Authoritative(messages) = &mut projection.transcript { |
| 171 | let mut kept_prefix = Vec::with_capacity(messages.len() + 1); |
| 172 | kept_prefix.push(0usize); |
| 173 | let mut kept = 0usize; |
| 174 | messages.retain_mut(|message| { |
| 175 | let before = message.blocks.len(); |
| 176 | message.blocks.retain(|block| !is_tool_block(block)); |
| 177 | let keep = before == message.blocks.len() |
| 178 | || message |
| 179 | .blocks |
| 180 | .iter() |
| 181 | .any(|block| !matches!(block, ExportBlock::InternalReasoning)); |
| 182 | if keep { |
| 183 | kept += 1; |
| 184 | } |
| 185 | kept_prefix.push(kept); |
| 186 | keep |
| 187 | }); |
| 188 | let max_index = kept_prefix.len().saturating_sub(1); |
| 189 | for outcome in &mut projection.turn_outcomes { |
| 190 | let clamped = outcome.after_message_count.min(max_index); |
| 191 | outcome.after_message_count = kept_prefix.get(clamped).copied().unwrap_or(kept); |
| 192 | } |
| 193 | projection.metadata.message_count = messages.len(); |
| 194 | } |
| 195 | projection |
| 196 | } |
| 197 | |
| 198 | fn redaction_note(count: usize) -> String { |
| 199 | match count { |
| 200 | 0 => String::new(), |
| 201 | 1 => ", 1 redaction".to_string(), |
| 202 | count => format!(", {count} redactions"), |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// Count the redaction markers the shared sanitizer leaves behind: `[redacted…]` |
| 207 | /// for secrets and keys, `***:***@` for URL credentials, and an encoded `***` |
| 208 | /// for sensitive URL query values. |
| 209 | pub(in crate::commands) fn count_redactions(document: &str) -> usize { |
| 210 | ["[redacted", "***:***@", "=%2A%2A%2A"] |
| 211 | .iter() |
| 212 | .map(|marker| document.matches(marker).count()) |
| 213 | .sum() |
| 214 | } |
| 215 | |
| 216 | const EXPORT_SLUG_MAX_LEN: usize = 40; |
| 217 | |
| 218 | fn export_file_stem(metadata: &ExportMetadata) -> String { |
| 219 | let slug = [ |
| 220 | metadata.title.as_deref(), |
| 221 | Some(metadata.session_label.as_str()), |
| 222 | ] |
| 223 | .into_iter() |
| 224 | .flatten() |
| 225 | .map(|text| slugify(&sanitize_text(text))) |
| 226 | .find(|slug| !slug.is_empty()) |
| 227 | .unwrap_or_else(|| "session".to_string()); |
| 228 | format!( |
| 229 | "codewhale-{slug}-{}", |
| 230 | file_timestamp(metadata.exported_at_unix) |
| 231 | ) |
| 232 | } |
| 233 | |
| 234 | fn slugify(text: &str) -> String { |
| 235 | let mut slug = String::new(); |
| 236 | for ch in text.chars() { |
| 237 | if slug.len() >= EXPORT_SLUG_MAX_LEN { |
| 238 | break; |
| 239 | } |
| 240 | if ch.is_ascii_alphanumeric() { |
| 241 | slug.push(ch.to_ascii_lowercase()); |
| 242 | } else if !slug.is_empty() && !slug.ends_with('-') { |
| 243 | slug.push('-'); |
| 244 | } |
| 245 | } |
| 246 | slug.truncate(slug.trim_end_matches('-').len()); |
| 247 | slug |
| 248 | } |
| 249 | |
| 250 | fn file_timestamp(timestamp: i64) -> String { |
| 251 | chrono::DateTime::from_timestamp(timestamp, 0) |
| 252 | .map(|time| time.format("%Y%m%d-%H%M%S").to_string()) |
| 253 | .unwrap_or_else(|| "unknown".to_string()) |
| 254 | } |
| 255 | |
| 256 | pub(super) fn tool_names(transcript: &TranscriptProjection) -> HashMap<String, String> { |
| 257 | let mut names = HashMap::new(); |
| 258 | if let TranscriptProjection::Authoritative(messages) = transcript { |
| 259 | for block in messages.iter().flat_map(|message| &message.blocks) { |
| 260 | if let ExportBlock::ToolCall { id, name, .. } |
| 261 | | ExportBlock::ServerToolCall { id, name, .. } = block |
| 262 | { |
| 263 | names.insert(id.clone(), name.clone()); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | names |
| 268 | } |
| 269 | |
| 270 | pub(super) fn role_label(message: &ExportMessage) -> String { |
| 271 | let carries_only_tool_results = message.is_user_role |
| 272 | && !message.blocks.is_empty() |
| 273 | && message.blocks.iter().all(|block| { |
| 274 | matches!( |
| 275 | block, |
| 276 | ExportBlock::ToolResult { .. } |
| 277 | | ExportBlock::ToolSearchResult { .. } |
| 278 | | ExportBlock::CodeExecutionResult { .. } |
| 279 | ) |
| 280 | }); |
| 281 | if carries_only_tool_results { |
| 282 | "tool".to_string() |
| 283 | } else { |
| 284 | inline_text(&message.role) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 289 | enum ExportScope { |
| 290 | Conversation, |
| 291 | Turn, |
| 292 | } |
| 293 | |
| 294 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 295 | enum ExportFormat { |
| 296 | Markdown, |
| 297 | Html, |
| 298 | Json, |
| 299 | } |
| 300 | |
| 301 | impl ExportFormat { |
| 302 | fn parse(value: &str) -> Option<Self> { |
| 303 | match value.to_ascii_lowercase().as_str() { |
| 304 | "md" | "markdown" => Some(Self::Markdown), |
| 305 | "html" => Some(Self::Html), |
| 306 | "json" => Some(Self::Json), |
| 307 | _ => None, |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | fn from_path(path: &str) -> Self { |
| 312 | match Path::new(path).extension().and_then(|ext| ext.to_str()) { |
| 313 | Some(ext) if ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm") => { |
| 314 | Self::Html |
| 315 | } |
| 316 | Some(ext) if ext.eq_ignore_ascii_case("json") => Self::Json, |
| 317 | _ => Self::Markdown, |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | fn extension(self) -> &'static str { |
| 322 | match self { |
| 323 | Self::Markdown => "md", |
| 324 | Self::Html => "html", |
| 325 | Self::Json => "json", |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | fn name(self) -> &'static str { |
| 330 | match self { |
| 331 | Self::Markdown => "Markdown", |
| 332 | Self::Html => "HTML", |
| 333 | Self::Json => "JSON", |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 339 | enum ExportDestination { |
| 340 | Clipboard, |
| 341 | File { path: Option<String>, force: bool }, |
| 342 | } |
| 343 | |
| 344 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 345 | struct ExportRequest { |
| 346 | scope: ExportScope, |
| 347 | destination: ExportDestination, |
| 348 | format: ExportFormat, |
| 349 | include_tools: bool, |
| 350 | } |
| 351 | |
| 352 | struct Token { |
| 353 | text: String, |
| 354 | quoted: bool, |
| 355 | } |
| 356 | |
| 357 | impl Token { |
| 358 | fn is_word(&self, word: &str) -> bool { |
| 359 | !self.quoted && self.text.eq_ignore_ascii_case(word) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | fn tokenize(raw: &str) -> Result<Vec<Token>, String> { |
| 364 | let mut tokens = Vec::new(); |
| 365 | let mut chars = raw.chars().peekable(); |
| 366 | while let Some(&first) = chars.peek() { |
| 367 | if first.is_whitespace() { |
| 368 | chars.next(); |
| 369 | continue; |
| 370 | } |
| 371 | let mut text = String::new(); |
| 372 | if first == '"' || first == '\'' { |
| 373 | chars.next(); |
| 374 | let mut closed = false; |
| 375 | for ch in chars.by_ref() { |
| 376 | if ch == first { |
| 377 | closed = true; |
| 378 | break; |
| 379 | } |
| 380 | text.push(ch); |
| 381 | } |
| 382 | if !closed { |
| 383 | return Err(export_usage("unterminated quote")); |
| 384 | } |
| 385 | if chars.peek().is_some_and(|next| !next.is_whitespace()) { |
| 386 | return Err(export_usage("unexpected text after a closing quote")); |
| 387 | } |
| 388 | tokens.push(Token { text, quoted: true }); |
| 389 | } else { |
| 390 | while let Some(&ch) = chars.peek() { |
| 391 | if ch.is_whitespace() { |
| 392 | break; |
| 393 | } |
| 394 | text.push(ch); |
| 395 | chars.next(); |
| 396 | } |
| 397 | tokens.push(Token { |
| 398 | text, |
| 399 | quoted: false, |
| 400 | }); |
| 401 | } |
| 402 | } |
| 403 | Ok(tokens) |
| 404 | } |
| 405 | |
| 406 | fn parse_request(arg: Option<&str>) -> Result<ExportRequest, String> { |
| 407 | let mut tokens = tokenize(arg.unwrap_or(""))?.into_iter(); |
| 408 | let mut positionals: Vec<Token> = Vec::new(); |
| 409 | let mut force = false; |
| 410 | let mut include_tools = true; |
| 411 | let mut format: Option<ExportFormat> = None; |
| 412 | while let Some(token) = tokens.next() { |
| 413 | if token.quoted || !token.text.starts_with("--") { |
| 414 | positionals.push(token); |
| 415 | continue; |
| 416 | } |
| 417 | let option = token.text.to_ascii_lowercase(); |
| 418 | let value = match option.as_str() { |
| 419 | "--force" => { |
| 420 | force = true; |
| 421 | continue; |
| 422 | } |
| 423 | "--no-tools" => { |
| 424 | include_tools = false; |
| 425 | continue; |
| 426 | } |
| 427 | "--format" => match tokens.next() { |
| 428 | Some(next) if next.quoted || !next.text.starts_with("--") => next.text, |
| 429 | _ => return Err(export_usage("--format needs a value: md, html, or json")), |
| 430 | }, |
| 431 | _ if option.starts_with("--format=") => token.text["--format=".len()..].to_string(), |
| 432 | _ => { |
| 433 | return Err(export_usage(&format!( |
| 434 | "unknown option `{}`", |
| 435 | inline_text(&token.text) |
| 436 | ))); |
| 437 | } |
| 438 | }; |
| 439 | let parsed = ExportFormat::parse(&value).ok_or_else(|| { |
| 440 | export_usage(&format!( |
| 441 | "unknown format `{}`; use md, html, or json", |
| 442 | inline_text(&value) |
| 443 | )) |
| 444 | })?; |
| 445 | if format.replace(parsed).is_some() { |
| 446 | return Err(export_usage("--format was given more than once")); |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | let scope = if positionals |
| 451 | .first() |
| 452 | .is_some_and(|token| token.is_word("turn")) |
| 453 | { |
| 454 | positionals.remove(0); |
| 455 | ExportScope::Turn |
| 456 | } else { |
| 457 | ExportScope::Conversation |
| 458 | }; |
| 459 | |
| 460 | let wants_file = scope == ExportScope::Conversation |
| 461 | && format.is_some_and(|format| format != ExportFormat::Markdown); |
| 462 | let destination = if positionals.is_empty() { |
| 463 | if wants_file { |
| 464 | ExportDestination::File { path: None, force } |
| 465 | } else { |
| 466 | ExportDestination::Clipboard |
| 467 | } |
| 468 | } else if positionals[0].is_word("clipboard") { |
| 469 | if positionals.len() > 1 { |
| 470 | return Err(export_usage("clipboard does not accept a path")); |
| 471 | } |
| 472 | ExportDestination::Clipboard |
| 473 | } else { |
| 474 | let path_tokens = if positionals[0].is_word("file") { |
| 475 | &positionals[1..] |
| 476 | } else { |
| 477 | &positionals[..] |
| 478 | }; |
| 479 | let path = (!path_tokens.is_empty()).then(|| { |
| 480 | path_tokens |
| 481 | .iter() |
| 482 | .map(|token| token.text.as_str()) |
| 483 | .collect::<Vec<_>>() |
| 484 | .join(" ") |
| 485 | }); |
| 486 | ExportDestination::File { path, force } |
| 487 | }; |
| 488 | if force && destination == ExportDestination::Clipboard { |
| 489 | return Err(export_usage("--force only applies to file exports")); |
| 490 | } |
| 491 | |
| 492 | let format = match scope { |
| 493 | ExportScope::Turn => { |
| 494 | if format.is_some_and(|format| format != ExportFormat::Markdown) { |
| 495 | return Err(export_usage("turn handoffs are Markdown only")); |
| 496 | } |
| 497 | if !include_tools { |
| 498 | return Err(export_usage( |
| 499 | "--no-tools applies to conversation exports, not turn handoffs", |
| 500 | )); |
| 501 | } |
| 502 | ExportFormat::Markdown |
| 503 | } |
| 504 | ExportScope::Conversation => match (&destination, format) { |
| 505 | (ExportDestination::Clipboard, Some(format)) if format != ExportFormat::Markdown => { |
| 506 | return Err(export_usage( |
| 507 | "HTML and JSON exports need a file destination", |
| 508 | )); |
| 509 | } |
| 510 | ( |
| 511 | ExportDestination::File { |
| 512 | path: Some(path), .. |
| 513 | }, |
| 514 | None, |
| 515 | ) => ExportFormat::from_path(path), |
| 516 | (_, format) => format.unwrap_or(ExportFormat::Markdown), |
| 517 | }, |
| 518 | }; |
| 519 | |
| 520 | Ok(ExportRequest { |
| 521 | scope, |
| 522 | destination, |
| 523 | format, |
| 524 | include_tools, |
| 525 | }) |
| 526 | } |
| 527 | |
| 528 | fn export_usage(reason: &str) -> String { |
| 529 | format!("{reason}. Usage: {}", CONTRACT_INFO.usage) |
| 530 | } |
| 531 | |
| 532 | fn copy_to_clipboard( |
| 533 | export: &dyn CommandSessionExportContext, |
| 534 | label: &str, |
| 535 | markdown: &str, |
| 536 | ) -> CommandResult { |
| 537 | let terminal_client = export.clipboard_requires_terminal_paste(); |
| 538 | let last_copy = export.write_recovery_copy(markdown); |
| 539 | let copy_hint = |path: Option<PathBuf>| match path { |
| 540 | Some(path) => { |
| 541 | format!("; a copy is at {}", path.display()) |
| 542 | } |
| 543 | None => String::new(), |
| 544 | }; |
| 545 | match export.write_clipboard(markdown) { |
| 546 | Ok(()) if terminal_client => CommandResult::message(format!( |
| 547 | "{label} sent to the terminal-client clipboard over SSH via tmux/OSC 52 ({} lines){}; terminal support and settings determine whether the client accepts it", |
| 548 | markdown.lines().count(), |
| 549 | copy_hint(last_copy) |
| 550 | )), |
| 551 | Ok(()) => CommandResult::message(format!( |
| 552 | "{label} copied to the local clipboard ({} lines; a terminal clipboard fallback may have been used){}", |
| 553 | markdown.lines().count(), |
| 554 | copy_hint(last_copy) |
| 555 | )), |
| 556 | Err(err) => match last_copy { |
| 557 | Some(path) => CommandResult::error(format!( |
| 558 | "Clipboard export failed: {err}. The full export was written to {}; /export file <path> writes it where you choose", |
| 559 | path.display() |
| 560 | )), |
| 561 | None => CommandResult::error(format!( |
| 562 | "Clipboard export failed: {err}. No file was written; use `/export file <path>` to choose an explicit destination" |
| 563 | )), |
| 564 | }, |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | /// Render the full-conversation export document from portable projection data. |
| 569 | /// |
| 570 | /// Takes the projection by value so the render path can move each block's JSON |
| 571 | /// payload into `push_json` instead of cloning it a second time. The projection |
| 572 | /// itself was already copied once at the facet boundary (F3); cloning the |
| 573 | /// payloads again here would be an avoidable extra copy of every tool input and |
| 574 | /// structured result. |
| 575 | pub(in crate::commands) fn render_conversation(projection: ConversationExportProjection) -> String { |
| 576 | let ConversationExportProjection { |
| 577 | metadata, |
| 578 | transcript, |
| 579 | restore_points, |
| 580 | turn_outcomes, |
| 581 | } = projection; |
| 582 | let names = tool_names(&transcript); |
| 583 | let mut out = String::new(); |
| 584 | out.push_str("# Codewhale conversation export\n\n"); |
| 585 | let _ = writeln!( |
| 586 | out, |
| 587 | "- Exported: {}", |
| 588 | format_export_time(metadata.exported_at_unix) |
| 589 | ); |
| 590 | if let Some(title) = metadata.title.as_deref() { |
| 591 | let _ = writeln!(out, "- Title: {}", inline_text(title)); |
| 592 | } |
| 593 | let _ = writeln!(out, "- Session: {}", inline_text(&metadata.session_label)); |
| 594 | let _ = writeln!(out, "- Provider: {}", inline_text(&metadata.provider)); |
| 595 | let _ = writeln!(out, "- Model: {}", inline_text(&metadata.model)); |
| 596 | let _ = writeln!(out, "- Mode: {}", metadata.mode); |
| 597 | let _ = writeln!( |
| 598 | out, |
| 599 | "- Workspace: {}", |
| 600 | inline_text(&metadata.workspace_name) |
| 601 | ); |
| 602 | let _ = writeln!(out, "- Messages: {}", metadata.message_count); |
| 603 | let _ = write!(out, "\n> {OMISSION_NOTE}\n\n"); |
| 604 | |
| 605 | render_restore_summary(&mut out, &restore_points); |
| 606 | |
| 607 | match transcript { |
| 608 | TranscriptProjection::HistoryFallback(entries) => { |
| 609 | if entries.is_empty() && !turn_outcomes.is_empty() { |
| 610 | for outcome in &turn_outcomes { |
| 611 | render_turn_outcome(&mut out, outcome); |
| 612 | } |
| 613 | } else { |
| 614 | render_history_fallback(&mut out, &entries); |
| 615 | } |
| 616 | } |
| 617 | TranscriptProjection::Authoritative(messages) => { |
| 618 | let mut outcomes = turn_outcomes.iter().peekable(); |
| 619 | let message_count = messages.len(); |
| 620 | render_turn_outcomes_through(&mut out, &mut outcomes, 0, message_count == 0); |
| 621 | for (index, message) in messages.into_iter().enumerate() { |
| 622 | // Correlation is derived before `message` is consumed by the |
| 623 | // renderer so the render path can take ownership of its payloads. |
| 624 | let correlation = correlation_markdown(&restore_points, &message); |
| 625 | render_message(&mut out, index + 1, message, &names); |
| 626 | out.push_str(&correlation); |
| 627 | render_turn_outcomes_through( |
| 628 | &mut out, |
| 629 | &mut outcomes, |
| 630 | index + 1, |
| 631 | index + 1 == message_count, |
| 632 | ); |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | out |
| 637 | } |
| 638 | |
| 639 | fn render_turn_outcomes_through<'a, I>( |
| 640 | out: &mut String, |
| 641 | outcomes: &mut std::iter::Peekable<I>, |
| 642 | message_count: usize, |
| 643 | last: bool, |
| 644 | ) where |
| 645 | I: Iterator<Item = &'a ExportTurnOutcome>, |
| 646 | { |
| 647 | while let Some(outcome) = |
| 648 | outcomes.next_if(|outcome| last || outcome.after_message_count <= message_count) |
| 649 | { |
| 650 | render_turn_outcome(out, outcome); |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | fn render_turn_outcome(out: &mut String, outcome: &ExportTurnOutcome) { |
| 655 | let status = inline_text(&outcome.status); |
| 656 | let status = if status.is_empty() { |
| 657 | "failed" |
| 658 | } else { |
| 659 | status.as_str() |
| 660 | }; |
| 661 | let _ = writeln!(out, "## Turn outcome ({status})\n"); |
| 662 | let _ = writeln!(out, "- Status: {status}"); |
| 663 | let _ = writeln!( |
| 664 | out, |
| 665 | "- Ended: {}", |
| 666 | format_export_time(outcome.ended_at_unix) |
| 667 | ); |
| 668 | if let Some(code) = outcome |
| 669 | .code |
| 670 | .as_deref() |
| 671 | .map(inline_text) |
| 672 | .filter(|code| !code.is_empty()) |
| 673 | { |
| 674 | let _ = writeln!(out, "- Code: `{code}`"); |
| 675 | } |
| 676 | out.push('\n'); |
| 677 | push_sanitized_text(out, &outcome.error); |
| 678 | } |
| 679 | |
| 680 | pub(super) const OMISSION_NOTE: &str = "Hidden instructions, internal reasoning, and reasoning signatures are omitted. Secret-like values and credential-bearing URLs are redacted as a defense in depth; review the export before sharing it."; |
| 681 | |
| 682 | pub(super) fn format_export_time(timestamp: i64) -> String { |
| 683 | chrono::DateTime::from_timestamp(timestamp, 0) |
| 684 | .map(|time| time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) |
| 685 | .unwrap_or_else(|| "unknown".to_string()) |
| 686 | } |
| 687 | |
| 688 | /// Characters of the snapshot SHA shown as a restore-point id. |
| 689 | const RESTORE_POINT_ID_LEN: usize = 12; |
| 690 | |
| 691 | fn render_restore_summary(out: &mut String, projection: &RestorePointProjection) { |
| 692 | out.push_str("## Restore points\n\n"); |
| 693 | match projection { |
| 694 | RestorePointProjection::None => { |
| 695 | out.push_str( |
| 696 | "No workspace restore points are recorded for this workspace, so nothing in this export can be correlated to a restorable workspace state. Snapshots may be disabled, or no turn has taken one yet.\n\n", |
| 697 | ); |
| 698 | } |
| 699 | RestorePointProjection::Unreadable { reason } => { |
| 700 | let _ = writeln!( |
| 701 | out, |
| 702 | "Workspace restore points could not be read ({}). Treat the correlation below as unavailable rather than empty.\n", |
| 703 | inline_text(reason) |
| 704 | ); |
| 705 | } |
| 706 | RestorePointProjection::Recorded { snapshots } if snapshots.is_empty() => { |
| 707 | out.push_str( |
| 708 | "A snapshot repository exists for this workspace but records no restore points yet.\n\n", |
| 709 | ); |
| 710 | } |
| 711 | RestorePointProjection::Recorded { snapshots } => { |
| 712 | let _ = writeln!( |
| 713 | out, |
| 714 | "The {} most recent workspace restore points, newest first. `/restore <N>` restores by the index in this table and `/restore list` shows the live list.\n", |
| 715 | snapshots.len() |
| 716 | ); |
| 717 | out.push_str( |
| 718 | "> The index is the position at export time. Every new turn records another restore point and shifts it, so re-check `/restore list` before restoring from an older export. The snapshot id does not shift.\n\n", |
| 719 | ); |
| 720 | out.push_str("| N | Restore point | Recorded (UTC) | Label |\n"); |
| 721 | out.push_str("| --- | --- | --- | --- |\n"); |
| 722 | for (index, snapshot) in snapshots.iter().enumerate() { |
| 723 | let _ = writeln!( |
| 724 | out, |
| 725 | "| {} | `{}` | {} | {} |", |
| 726 | index + 1, |
| 727 | short_restore_id(&snapshot.id), |
| 728 | format_export_time(snapshot.timestamp_unix), |
| 729 | inline_text(&snapshot.label) |
| 730 | ); |
| 731 | } |
| 732 | out.push('\n'); |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | /// Append the restore points correlated to a single user message. |
| 738 | /// |
| 739 | /// Correlation is by the prompt snippet the host embedded in the snapshot |
| 740 | /// label, produced by the same function the snapshot writer uses. No |
| 741 | /// message-index-to-turn-sequence mapping is invented: a turn sequence and an |
| 742 | /// export message index are different counters, and asserting they line up |
| 743 | /// would be a guess presented as provenance. |
| 744 | fn correlation_markdown(projection: &RestorePointProjection, message: &ExportMessage) -> String { |
| 745 | let mut out = String::new(); |
| 746 | // F6: exact `Role::User` identity, not the rendered role string. Comparing |
| 747 | // textually against "user" would also match `Role::Unrecognized("user")`, |
| 748 | // which the baseline deliberately did not correlate. |
| 749 | if !message.is_user_role { |
| 750 | return out; |
| 751 | } |
| 752 | let RestorePointProjection::Recorded { snapshots } = projection else { |
| 753 | return out; |
| 754 | }; |
| 755 | let Some(snippet) = message.prompt_snippet.as_deref() else { |
| 756 | return out; |
| 757 | }; |
| 758 | |
| 759 | let matches: Vec<(usize, &RestoreSnapshot)> = snapshots |
| 760 | .iter() |
| 761 | .enumerate() |
| 762 | .filter(|(_, snapshot)| { |
| 763 | matches!(snapshot.kind.as_str(), "pre-turn" | "post-turn") |
| 764 | && snapshot.prompt_snippet.as_deref() == Some(snippet) |
| 765 | }) |
| 766 | .collect(); |
| 767 | |
| 768 | if matches.is_empty() { |
| 769 | out.push_str( |
| 770 | "- Restore points: none recorded for this message within the listed window.\n\n", |
| 771 | ); |
| 772 | return out; |
| 773 | } |
| 774 | |
| 775 | let ambiguous = matches.len() > 1; |
| 776 | let rendered: Vec<String> = matches |
| 777 | .iter() |
| 778 | .map(|(index, snapshot)| { |
| 779 | let seq = snapshot |
| 780 | .sequence |
| 781 | .map(|seq| format!(" turn {seq}")) |
| 782 | .unwrap_or_default(); |
| 783 | format!( |
| 784 | "N{} `{}` ({}{})", |
| 785 | index + 1, |
| 786 | short_restore_id(&snapshot.id), |
| 787 | snapshot.kind, |
| 788 | seq |
| 789 | ) |
| 790 | }) |
| 791 | .collect(); |
| 792 | let _ = writeln!(out, "- Restore points: {}", rendered.join(", ")); |
| 793 | if ambiguous { |
| 794 | out.push_str( |
| 795 | " - More than one restore point carries this prompt snippet, so the match is ambiguous; compare the recorded times above before restoring.\n", |
| 796 | ); |
| 797 | } |
| 798 | out.push('\n'); |
| 799 | out |
| 800 | } |
| 801 | |
| 802 | fn short_restore_id(id: &str) -> String { |
| 803 | id.chars().take(RESTORE_POINT_ID_LEN).collect() |
| 804 | } |
| 805 | |
| 806 | fn render_message( |
| 807 | out: &mut String, |
| 808 | index: usize, |
| 809 | message: ExportMessage, |
| 810 | names: &HashMap<String, String>, |
| 811 | ) { |
| 812 | let role = role_label(&message); |
| 813 | let _ = writeln!(out, "## {index}. {role}\n"); |
| 814 | if is_internal_role(&message.role) { |
| 815 | out.push_str("[internal context omitted]\n\n"); |
| 816 | return; |
| 817 | } |
| 818 | if message.blocks.is_empty() { |
| 819 | out.push_str("[no content]\n\n"); |
| 820 | return; |
| 821 | } |
| 822 | let mut after_heading = false; |
| 823 | for block in message.blocks { |
| 824 | render_content_block(out, block, names, &mut after_heading); |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | fn render_content_block( |
| 829 | out: &mut String, |
| 830 | block: ExportBlock, |
| 831 | names: &HashMap<String, String>, |
| 832 | after_heading: &mut bool, |
| 833 | ) { |
| 834 | let headed = !matches!( |
| 835 | block, |
| 836 | ExportBlock::Text { .. } | ExportBlock::InternalReasoning |
| 837 | ); |
| 838 | match block { |
| 839 | ExportBlock::Text { text } => { |
| 840 | if std::mem::take(after_heading) { |
| 841 | out.push_str("### Text\n\n"); |
| 842 | } |
| 843 | push_sanitized_text(out, &text); |
| 844 | } |
| 845 | ExportBlock::ImageReference { url } => { |
| 846 | out.push_str("### Image attachment\n\n"); |
| 847 | let _ = writeln!( |
| 848 | out, |
| 849 | "- Reference: {}\n", |
| 850 | inline_text(&redact_url_for_display(&url)) |
| 851 | ); |
| 852 | } |
| 853 | ExportBlock::ImageOmitted => { |
| 854 | out.push_str("### Image attachment\n\n"); |
| 855 | out.push_str("- Reference omitted (inline or local image payload)\n\n"); |
| 856 | } |
| 857 | ExportBlock::InternalReasoning => { |
| 858 | out.push_str("[internal reasoning and signature omitted]\n\n"); |
| 859 | } |
| 860 | ExportBlock::ToolCall { |
| 861 | id, |
| 862 | name, |
| 863 | caller, |
| 864 | input, |
| 865 | } => { |
| 866 | let _ = writeln!(out, "### Tool call: {}\n", inline_text(&name)); |
| 867 | let _ = writeln!(out, "- ID: {}", inline_text(&id)); |
| 868 | if let Some(caller) = caller { |
| 869 | let _ = writeln!(out, "- Caller type: {}", inline_text(&caller.caller_type)); |
| 870 | if let Some(tool_id) = caller.tool_id.as_deref() { |
| 871 | let _ = writeln!(out, "- Caller tool ID: {}", inline_text(tool_id)); |
| 872 | } |
| 873 | } |
| 874 | out.push('\n'); |
| 875 | push_json(out, input); |
| 876 | } |
| 877 | ExportBlock::ToolResult { |
| 878 | tool_use_id, |
| 879 | content, |
| 880 | is_error, |
| 881 | structured, |
| 882 | } => { |
| 883 | match names.get(&tool_use_id) { |
| 884 | Some(name) => { |
| 885 | let _ = writeln!(out, "### Tool result: {}\n", inline_text(name)); |
| 886 | } |
| 887 | None => out.push_str("### Tool result\n\n"), |
| 888 | } |
| 889 | let _ = writeln!(out, "- Tool call ID: {}", inline_text(&tool_use_id)); |
| 890 | if is_error { |
| 891 | out.push_str("- Error: true\n"); |
| 892 | } |
| 893 | out.push('\n'); |
| 894 | push_fenced_text(out, &sanitize_text(&content)); |
| 895 | if let Some(blocks) = structured { |
| 896 | out.push_str("Structured result blocks:\n\n"); |
| 897 | push_json(out, blocks); |
| 898 | } |
| 899 | } |
| 900 | ExportBlock::ServerToolCall { id, name, input } => { |
| 901 | let _ = writeln!(out, "### Server tool call: {}\n", inline_text(&name)); |
| 902 | let _ = writeln!(out, "- ID: {}\n", inline_text(&id)); |
| 903 | push_json(out, input); |
| 904 | } |
| 905 | ExportBlock::ToolSearchResult { |
| 906 | tool_use_id, |
| 907 | content, |
| 908 | } => { |
| 909 | out.push_str("### Tool-search result\n\n"); |
| 910 | let _ = writeln!(out, "- Tool call ID: {}\n", inline_text(&tool_use_id)); |
| 911 | push_json(out, content); |
| 912 | } |
| 913 | ExportBlock::CodeExecutionResult { |
| 914 | tool_use_id, |
| 915 | content, |
| 916 | } => { |
| 917 | out.push_str("### Code-execution result\n\n"); |
| 918 | let _ = writeln!(out, "- Tool call ID: {}\n", inline_text(&tool_use_id)); |
| 919 | push_json(out, content); |
| 920 | } |
| 921 | } |
| 922 | if headed { |
| 923 | *after_heading = true; |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | fn render_history_fallback(out: &mut String, entries: &[HistoryEntry]) { |
| 928 | if entries.is_empty() { |
| 929 | out.push_str("## Conversation\n\n[empty conversation]\n"); |
| 930 | return; |
| 931 | } |
| 932 | out.push_str( |
| 933 | "> Structured API messages were unavailable; the entries below are a sanitized visible-history fallback.\n\n", |
| 934 | ); |
| 935 | for (index, entry) in entries.iter().enumerate() { |
| 936 | let (role, body) = match entry { |
| 937 | HistoryEntry::Sanitized { role, body } => (role.as_str(), sanitize_text(body)), |
| 938 | HistoryEntry::Literal { role, body } => (role.as_str(), body.clone()), |
| 939 | }; |
| 940 | let _ = writeln!(out, "## {}. {}\n", index + 1, inline_text(role)); |
| 941 | push_pre_sanitized_text(out, &body); |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | fn push_sanitized_text(out: &mut String, text: &str) { |
| 946 | push_pre_sanitized_text(out, &sanitize_text(text)); |
| 947 | } |
| 948 | |
| 949 | fn push_pre_sanitized_text(out: &mut String, text: &str) { |
| 950 | if text.trim().is_empty() { |
| 951 | out.push_str("[empty text]\n\n"); |
| 952 | } else { |
| 953 | out.push_str(text.trim_end()); |
| 954 | out.push_str("\n\n"); |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | fn push_fenced_text(out: &mut String, text: &str) { |
| 959 | let body = text.trim_end(); |
| 960 | if body.trim().is_empty() { |
| 961 | out.push_str("[empty text]\n\n"); |
| 962 | return; |
| 963 | } |
| 964 | let fence = markdown_fence(body); |
| 965 | let _ = writeln!(out, "{fence}text\n{body}\n{fence}\n"); |
| 966 | } |
| 967 | |
| 968 | pub(super) fn redacted_json_text(mut value: Value) -> String { |
| 969 | // Redact in place: the caller hands over ownership, so there is no need to |
| 970 | // clone the whole payload just to redact it (F3 follow-up). |
| 971 | redact_json(&mut value, None); |
| 972 | serde_json::to_string_pretty(&value) |
| 973 | .unwrap_or_else(|_| "\"[structured content unavailable]\"".to_string()) |
| 974 | } |
| 975 | |
| 976 | fn push_json(out: &mut String, value: Value) { |
| 977 | let json = redacted_json_text(value); |
| 978 | let fence = markdown_fence(&json); |
| 979 | let _ = writeln!(out, "{fence}json\n{json}\n{fence}\n"); |
| 980 | } |
| 981 | |
| 982 | fn markdown_fence(content: &str) -> String { |
| 983 | let longest = content |
| 984 | .split(|ch| ch != '`') |
| 985 | .map(str::len) |
| 986 | .max() |
| 987 | .unwrap_or(0); |
| 988 | "`".repeat(longest.saturating_add(1).max(3)) |
| 989 | } |
| 990 | |
| 991 | fn sanitize_turn_handoff(projection: &TurnHandoffProjection) -> String { |
| 992 | let sanitized = sanitize_text(&projection.markdown); |
| 993 | if projection.workspace_path.is_empty() { |
| 994 | sanitized |
| 995 | } else { |
| 996 | sanitized.replace(&projection.workspace_path, ".") |
| 997 | } |
| 998 | } |
| 999 | |
| 1000 | #[cfg(test)] |
| 1001 | mod tests { |
| 1002 | use super::*; |
| 1003 | use std::cell::RefCell; |
| 1004 | |
| 1005 | /// Minimal fake facet: every delegate is deterministic and records calls. |
| 1006 | struct FakeExport { |
| 1007 | conversation: ConversationExportProjection, |
| 1008 | turn: TurnHandoffProjection, |
| 1009 | terminal_paste: bool, |
| 1010 | recovery: Option<PathBuf>, |
| 1011 | clipboard: Result<(), String>, |
| 1012 | resolve: Result<PathBuf, String>, |
| 1013 | write: Result<(), String>, |
| 1014 | calls: RefCell<Vec<String>>, |
| 1015 | } |
| 1016 | |
| 1017 | impl Default for FakeExport { |
| 1018 | fn default() -> Self { |
| 1019 | Self { |
| 1020 | conversation: conversation_projection(vec![]), |
| 1021 | turn: TurnHandoffProjection { |
| 1022 | markdown: String::new(), |
| 1023 | workspace_path: String::new(), |
| 1024 | }, |
| 1025 | terminal_paste: false, |
| 1026 | recovery: None, |
| 1027 | clipboard: Ok(()), |
| 1028 | resolve: Ok(PathBuf::from("/resolved/out.md")), |
| 1029 | write: Ok(()), |
| 1030 | calls: RefCell::new(Vec::new()), |
| 1031 | } |
| 1032 | } |
| 1033 | } |
| 1034 | |
| 1035 | impl CommandSessionExportContext for FakeExport { |
| 1036 | fn conversation_projection(&self) -> ConversationExportProjection { |
| 1037 | self.calls |
| 1038 | .borrow_mut() |
| 1039 | .push("conversation_projection".to_string()); |
| 1040 | self.conversation.clone() |
| 1041 | } |
| 1042 | |
| 1043 | fn turn_handoff_projection(&self) -> TurnHandoffProjection { |
| 1044 | self.calls |
| 1045 | .borrow_mut() |
| 1046 | .push("turn_handoff_projection".to_string()); |
| 1047 | self.turn.clone() |
| 1048 | } |
| 1049 | |
| 1050 | fn clipboard_requires_terminal_paste(&self) -> bool { |
| 1051 | self.calls |
| 1052 | .borrow_mut() |
| 1053 | .push("clipboard_requires_terminal_paste".to_string()); |
| 1054 | self.terminal_paste |
| 1055 | } |
| 1056 | |
| 1057 | fn write_recovery_copy(&self, markdown: &str) -> Option<PathBuf> { |
| 1058 | self.calls |
| 1059 | .borrow_mut() |
| 1060 | .push(format!("write_recovery_copy({markdown})")); |
| 1061 | self.recovery.clone() |
| 1062 | } |
| 1063 | |
| 1064 | fn write_clipboard(&self, markdown: &str) -> Result<(), String> { |
| 1065 | self.calls |
| 1066 | .borrow_mut() |
| 1067 | .push(format!("write_clipboard({markdown})")); |
| 1068 | self.clipboard.clone() |
| 1069 | } |
| 1070 | |
| 1071 | fn resolve_export_path(&self, raw: &str) -> Result<PathBuf, String> { |
| 1072 | self.calls |
| 1073 | .borrow_mut() |
| 1074 | .push(format!("resolve_export_path({raw})")); |
| 1075 | self.resolve.clone() |
| 1076 | } |
| 1077 | |
| 1078 | fn default_export_path(&self, file_name: &str) -> Result<PathBuf, String> { |
| 1079 | self.calls |
| 1080 | .borrow_mut() |
| 1081 | .push(format!("default_export_path({file_name})")); |
| 1082 | self.resolve.clone() |
| 1083 | } |
| 1084 | |
| 1085 | fn write_export_file( |
| 1086 | &self, |
| 1087 | path: &Path, |
| 1088 | contents: &[u8], |
| 1089 | force: bool, |
| 1090 | ) -> Result<(), String> { |
| 1091 | self.calls.borrow_mut().push(format!( |
| 1092 | "write_export_file({}, {}, {force})", |
| 1093 | path.display(), |
| 1094 | String::from_utf8_lossy(contents) |
| 1095 | )); |
| 1096 | self.write.clone() |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | fn conversation_projection(messages: Vec<ExportMessage>) -> ConversationExportProjection { |
| 1101 | ConversationExportProjection { |
| 1102 | metadata: codewhale_command_contract::facets::ExportMetadata { |
| 1103 | session_label: "sess12345678".to_string(), |
| 1104 | title: None, |
| 1105 | provider: "deepseek".to_string(), |
| 1106 | model: "deepseek-v4".to_string(), |
| 1107 | mode: "agent".to_string(), |
| 1108 | workspace_name: "workspace".to_string(), |
| 1109 | message_count: messages.len(), |
| 1110 | exported_at_unix: 1_700_000_000, |
| 1111 | }, |
| 1112 | transcript: TranscriptProjection::Authoritative(messages), |
| 1113 | restore_points: RestorePointProjection::None, |
| 1114 | turn_outcomes: Vec::new(), |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | fn user_message(text: &str) -> ExportMessage { |
| 1119 | ExportMessage { |
| 1120 | is_user_role: true, |
| 1121 | role: "user".to_string(), |
| 1122 | blocks: vec![ExportBlock::Text { |
| 1123 | text: text.to_string(), |
| 1124 | }], |
| 1125 | prompt_snippet: Some(text.to_string()), |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | fn snapshot( |
| 1130 | id: &str, |
| 1131 | label: &str, |
| 1132 | timestamp: i64, |
| 1133 | kind: &str, |
| 1134 | sequence: Option<u64>, |
| 1135 | ) -> RestoreSnapshot { |
| 1136 | RestoreSnapshot { |
| 1137 | id: id.to_string(), |
| 1138 | label: label.to_string(), |
| 1139 | timestamp_unix: timestamp, |
| 1140 | kind: kind.to_string(), |
| 1141 | sequence, |
| 1142 | prompt_snippet: label |
| 1143 | .split_once(": ") |
| 1144 | .map(|(_, snippet)| snippet.to_string()), |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | fn request(scope: ExportScope, destination: ExportDestination) -> ExportRequest { |
| 1149 | ExportRequest { |
| 1150 | scope, |
| 1151 | destination, |
| 1152 | format: ExportFormat::Markdown, |
| 1153 | include_tools: true, |
| 1154 | } |
| 1155 | } |
| 1156 | |
| 1157 | fn file_destination(path: Option<&str>, force: bool) -> ExportDestination { |
| 1158 | ExportDestination::File { |
| 1159 | path: path.map(str::to_string), |
| 1160 | force, |
| 1161 | } |
| 1162 | } |
| 1163 | |
| 1164 | #[test] |
| 1165 | fn parser_matrix_is_exact() { |
| 1166 | assert_eq!( |
| 1167 | parse_request(None).unwrap(), |
| 1168 | request(ExportScope::Conversation, ExportDestination::Clipboard) |
| 1169 | ); |
| 1170 | assert_eq!( |
| 1171 | parse_request(Some("clipboard")).unwrap().scope, |
| 1172 | ExportScope::Conversation |
| 1173 | ); |
| 1174 | assert_eq!( |
| 1175 | parse_request(Some("TURN")).unwrap().scope, |
| 1176 | ExportScope::Turn |
| 1177 | ); |
| 1178 | assert_eq!( |
| 1179 | parse_request(Some("file --force reports/chat export.md")).unwrap(), |
| 1180 | request( |
| 1181 | ExportScope::Conversation, |
| 1182 | file_destination(Some("reports/chat export.md"), true) |
| 1183 | ) |
| 1184 | ); |
| 1185 | assert_eq!( |
| 1186 | parse_request(Some("legacy export.md")).unwrap(), |
| 1187 | request( |
| 1188 | ExportScope::Conversation, |
| 1189 | file_destination(Some("legacy export.md"), false) |
| 1190 | ) |
| 1191 | ); |
| 1192 | assert_eq!( |
| 1193 | parse_request(Some("turn file --force handoff.md")).unwrap(), |
| 1194 | request( |
| 1195 | ExportScope::Turn, |
| 1196 | file_destination(Some("handoff.md"), true) |
| 1197 | ) |
| 1198 | ); |
| 1199 | assert_eq!( |
| 1200 | parse_request(Some("turn legacy.md")).unwrap(), |
| 1201 | request( |
| 1202 | ExportScope::Turn, |
| 1203 | file_destination(Some("legacy.md"), false) |
| 1204 | ) |
| 1205 | ); |
| 1206 | assert_eq!( |
| 1207 | parse_request(Some("turn clipboard")).unwrap().destination, |
| 1208 | ExportDestination::Clipboard |
| 1209 | ); |
| 1210 | assert_eq!( |
| 1211 | parse_request(Some("file")).unwrap().destination, |
| 1212 | file_destination(None, false) |
| 1213 | ); |
| 1214 | |
| 1215 | for arg in ["clipboard extra.md", "turn clipboard extra.md"] { |
| 1216 | assert!(parse_request(Some(arg)).is_err(), "{arg}"); |
| 1217 | } |
| 1218 | assert_eq!( |
| 1219 | parse_request(Some("clipboard extra.md")).unwrap_err(), |
| 1220 | export_usage("clipboard does not accept a path") |
| 1221 | ); |
| 1222 | } |
| 1223 | |
| 1224 | #[test] |
| 1225 | fn missing_authority_fails_safely_without_effects() { |
| 1226 | let result = export_contextual(CommandContexts::empty(), Some("clipboard")); |
| 1227 | assert!(result.is_error); |
| 1228 | assert_eq!( |
| 1229 | result.message.as_deref(), |
| 1230 | Some("Error: Command capability unavailable: session_export") |
| 1231 | ); |
| 1232 | } |
| 1233 | |
| 1234 | #[test] |
| 1235 | fn conversation_clipboard_renders_full_document_and_sequences_operations() { |
| 1236 | let fake = FakeExport { |
| 1237 | conversation: conversation_projection(vec![ |
| 1238 | ExportMessage { |
| 1239 | is_user_role: false, |
| 1240 | role: "system".to_string(), |
| 1241 | blocks: vec![ExportBlock::Text { |
| 1242 | text: "hidden policy must never export".to_string(), |
| 1243 | }], |
| 1244 | prompt_snippet: None, |
| 1245 | }, |
| 1246 | user_message("Please inspect this"), |
| 1247 | ]), |
| 1248 | recovery: Some(PathBuf::from("/home/.codewhale/exports/last-copy.md")), |
| 1249 | ..FakeExport::default() |
| 1250 | }; |
| 1251 | |
| 1252 | let result = export_portable(&fake, Some("clipboard")); |
| 1253 | |
| 1254 | assert!(!result.is_error, "{:?}", result.message); |
| 1255 | let message = result.message.as_deref().unwrap_or_default(); |
| 1256 | assert!( |
| 1257 | message.starts_with("Conversation copied to the local clipboard ("), |
| 1258 | "{message}" |
| 1259 | ); |
| 1260 | assert!( |
| 1261 | message.contains(" lines; a terminal clipboard fallback may have been used)"), |
| 1262 | "{message}" |
| 1263 | ); |
| 1264 | assert!( |
| 1265 | message.ends_with("; a copy is at /home/.codewhale/exports/last-copy.md"), |
| 1266 | "{message}" |
| 1267 | ); |
| 1268 | let read = fake.calls.borrow(); |
| 1269 | assert_eq!(read[0], "conversation_projection"); |
| 1270 | assert_eq!(read[1], "clipboard_requires_terminal_paste"); |
| 1271 | assert!(read[2].starts_with("write_recovery_copy("), "{read:?}"); |
| 1272 | assert!(read[3].starts_with("write_clipboard("), "{read:?}"); |
| 1273 | assert_eq!(read.len(), 4, "exactly one recovery and one clipboard call"); |
| 1274 | let recovery_payload = read[2] |
| 1275 | .trim_start_matches("write_recovery_copy(") |
| 1276 | .trim_end_matches(')'); |
| 1277 | let markdown = read[3] |
| 1278 | .trim_start_matches("write_clipboard(") |
| 1279 | .trim_end_matches(')'); |
| 1280 | assert_eq!( |
| 1281 | recovery_payload, markdown, |
| 1282 | "both writes receive identical Markdown" |
| 1283 | ); |
| 1284 | assert!(markdown.starts_with("# Codewhale conversation export\n\n")); |
| 1285 | assert!(markdown.contains("## 1. system\n\n[internal context omitted]\n\n")); |
| 1286 | assert!(markdown.contains("## 2. user\n\nPlease inspect this\n\n")); |
| 1287 | assert!(!markdown.contains("hidden policy must never export")); |
| 1288 | } |
| 1289 | |
| 1290 | #[test] |
| 1291 | fn conversation_document_matches_full_golden_equality() { |
| 1292 | let projection = conversation_projection(vec![ |
| 1293 | ExportMessage { |
| 1294 | is_user_role: false, |
| 1295 | role: "system".to_string(), |
| 1296 | blocks: vec![ExportBlock::Text { |
| 1297 | text: "hidden policy must never export".to_string(), |
| 1298 | }], |
| 1299 | prompt_snippet: None, |
| 1300 | }, |
| 1301 | user_message("Please inspect this"), |
| 1302 | ]); |
| 1303 | |
| 1304 | let expected = "# Codewhale conversation export\n\n\ |
| 1305 | - Exported: 2023-11-14T22:13:20Z\n\ |
| 1306 | - Session: sess12345678\n\ |
| 1307 | - Provider: deepseek\n\ |
| 1308 | - Model: deepseek-v4\n\ |
| 1309 | - Mode: agent\n\ |
| 1310 | - Workspace: workspace\n\ |
| 1311 | - Messages: 2\n\n\ |
| 1312 | > Hidden instructions, internal reasoning, and reasoning signatures are omitted. Secret-like values and credential-bearing URLs are redacted as a defense in depth; review the export before sharing it.\n\n\ |
| 1313 | ## Restore points\n\n\ |
| 1314 | No workspace restore points are recorded for this workspace, so nothing in this export can be correlated to a restorable workspace state. Snapshots may be disabled, or no turn has taken one yet.\n\n\ |
| 1315 | ## 1. system\n\n[internal context omitted]\n\n\ |
| 1316 | ## 2. user\n\nPlease inspect this\n\n"; |
| 1317 | |
| 1318 | assert_eq!(render_conversation(projection), expected); |
| 1319 | } |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn ssh_clipboard_uses_terminal_client_wording() { |
| 1323 | let fake = FakeExport { |
| 1324 | terminal_paste: true, |
| 1325 | conversation: conversation_projection(vec![user_message("hi")]), |
| 1326 | ..FakeExport::default() |
| 1327 | }; |
| 1328 | |
| 1329 | let result = export_portable(&fake, Some("clipboard")); |
| 1330 | |
| 1331 | assert!(!result.is_error); |
| 1332 | let message = result.message.as_deref().unwrap_or_default(); |
| 1333 | assert!( |
| 1334 | message.contains("terminal-client clipboard over SSH via tmux/OSC 52"), |
| 1335 | "{message}" |
| 1336 | ); |
| 1337 | assert!( |
| 1338 | !message.contains("a copy is at"), |
| 1339 | "no recovery path present: {message}" |
| 1340 | ); |
| 1341 | } |
| 1342 | |
| 1343 | #[test] |
| 1344 | fn recovery_failure_still_attempts_clipboard() { |
| 1345 | let fake = FakeExport { |
| 1346 | conversation: conversation_projection(vec![user_message("hi")]), |
| 1347 | recovery: None, |
| 1348 | clipboard: Err("no clipboard".to_string()), |
| 1349 | ..FakeExport::default() |
| 1350 | }; |
| 1351 | |
| 1352 | let result = export_portable(&fake, Some("clipboard")); |
| 1353 | |
| 1354 | assert!(result.is_error); |
| 1355 | assert_eq!( |
| 1356 | result.message.as_deref(), |
| 1357 | Some( |
| 1358 | "Error: Clipboard export failed: no clipboard. No file was written; use `/export file <path>` to choose an explicit destination" |
| 1359 | ) |
| 1360 | ); |
| 1361 | let read = fake.calls.borrow(); |
| 1362 | assert!( |
| 1363 | read.iter() |
| 1364 | .any(|call| call.starts_with("write_recovery_copy(")) |
| 1365 | ); |
| 1366 | assert!(read.iter().any(|call| call.starts_with("write_clipboard("))); |
| 1367 | } |
| 1368 | |
| 1369 | #[test] |
| 1370 | fn file_export_renders_resolves_then_writes_once() { |
| 1371 | let fake = FakeExport { |
| 1372 | conversation: conversation_projection(vec![user_message("first export")]), |
| 1373 | resolve: Ok(PathBuf::from("/workspace/transcript.md")), |
| 1374 | write: Ok(()), |
| 1375 | ..FakeExport::default() |
| 1376 | }; |
| 1377 | |
| 1378 | let lines = render_conversation(fake.conversation.clone()) |
| 1379 | .lines() |
| 1380 | .count(); |
| 1381 | |
| 1382 | let result = export_portable(&fake, Some("file transcript.md")); |
| 1383 | |
| 1384 | assert!(!result.is_error, "{:?}", result.message); |
| 1385 | assert_eq!( |
| 1386 | result.message.as_deref(), |
| 1387 | Some( |
| 1388 | format!( |
| 1389 | "Conversation exported to /workspace/transcript.md (Markdown, {lines} lines)" |
| 1390 | ) |
| 1391 | .as_str() |
| 1392 | ) |
| 1393 | ); |
| 1394 | let read = fake.calls.borrow(); |
| 1395 | assert_eq!(read.len(), 3, "{read:?}"); |
| 1396 | assert_eq!(read[0], "conversation_projection"); |
| 1397 | assert_eq!(read[1], "resolve_export_path(transcript.md)"); |
| 1398 | assert!(read[2].starts_with("write_export_file(/workspace/transcript.md,")); |
| 1399 | assert!( |
| 1400 | !read |
| 1401 | .iter() |
| 1402 | .any(|call| call.contains("clipboard") || call.contains("recovery")), |
| 1403 | "file export must not touch clipboard or recovery: {read:?}" |
| 1404 | ); |
| 1405 | } |
| 1406 | |
| 1407 | #[test] |
| 1408 | fn resolution_failure_prevents_writing() { |
| 1409 | let fake = FakeExport { |
| 1410 | conversation: conversation_projection(vec![user_message("x")]), |
| 1411 | resolve: Err("export paths may not contain `..`".to_string()), |
| 1412 | ..FakeExport::default() |
| 1413 | }; |
| 1414 | |
| 1415 | let result = export_portable(&fake, Some("file ../escape.md")); |
| 1416 | |
| 1417 | assert!(result.is_error); |
| 1418 | assert_eq!( |
| 1419 | result.message.as_deref(), |
| 1420 | Some("Error: export paths may not contain `..`") |
| 1421 | ); |
| 1422 | let read = fake.calls.borrow(); |
| 1423 | assert!( |
| 1424 | !read |
| 1425 | .iter() |
| 1426 | .any(|call| call.starts_with("write_export_file(")), |
| 1427 | "no write after resolution failure: {read:?}" |
| 1428 | ); |
| 1429 | } |
| 1430 | |
| 1431 | #[test] |
| 1432 | fn write_failure_wraps_exact_baseline_text() { |
| 1433 | let fake = FakeExport { |
| 1434 | conversation: conversation_projection(vec![user_message("x")]), |
| 1435 | resolve: Ok(PathBuf::from("/workspace/out.md")), |
| 1436 | write: Err("destination already exists: /workspace/out.md".to_string()), |
| 1437 | ..FakeExport::default() |
| 1438 | }; |
| 1439 | |
| 1440 | let result = export_portable(&fake, Some("file out.md")); |
| 1441 | |
| 1442 | assert!(result.is_error); |
| 1443 | assert_eq!( |
| 1444 | result.message.as_deref(), |
| 1445 | Some( |
| 1446 | "Error: Failed to export Conversation to /workspace/out.md: destination already exists: /workspace/out.md" |
| 1447 | ) |
| 1448 | ); |
| 1449 | } |
| 1450 | |
| 1451 | #[test] |
| 1452 | fn forced_file_export_reports_overwrite_suffix() { |
| 1453 | let fake = FakeExport { |
| 1454 | conversation: conversation_projection(vec![user_message("x")]), |
| 1455 | resolve: Ok(PathBuf::from("/workspace/out.md")), |
| 1456 | ..FakeExport::default() |
| 1457 | }; |
| 1458 | |
| 1459 | let lines = render_conversation(fake.conversation.clone()) |
| 1460 | .lines() |
| 1461 | .count(); |
| 1462 | |
| 1463 | let result = export_portable(&fake, Some("file --force out.md")); |
| 1464 | |
| 1465 | assert_eq!( |
| 1466 | result.message.as_deref(), |
| 1467 | Some( |
| 1468 | format!( |
| 1469 | "Conversation exported to /workspace/out.md (Markdown, {lines} lines) (overwrite explicitly allowed)" |
| 1470 | ) |
| 1471 | .as_str() |
| 1472 | ) |
| 1473 | ); |
| 1474 | let read = fake.calls.borrow(); |
| 1475 | assert!(read[2].ends_with(", true)"), "{:?}", read[2]); |
| 1476 | } |
| 1477 | |
| 1478 | #[test] |
| 1479 | fn turn_export_sanitizes_then_replaces_nonempty_workspace() { |
| 1480 | let fake = FakeExport { |
| 1481 | turn: TurnHandoffProjection { |
| 1482 | markdown: "# Turn handoff\n\n\u{1b}[31m/Users/me/repo\u{1b}[0m done".to_string(), |
| 1483 | workspace_path: "/Users/me/repo".to_string(), |
| 1484 | }, |
| 1485 | ..FakeExport::default() |
| 1486 | }; |
| 1487 | |
| 1488 | let result = export_portable(&fake, Some("turn")); |
| 1489 | |
| 1490 | assert!(!result.is_error); |
| 1491 | let read = fake.calls.borrow(); |
| 1492 | let markdown = read |
| 1493 | .iter() |
| 1494 | .find_map(|call| { |
| 1495 | call.strip_prefix("write_clipboard(") |
| 1496 | .map(|c| c.trim_end_matches(')')) |
| 1497 | }) |
| 1498 | .expect("clipboard payload"); |
| 1499 | assert_eq!(markdown, "# Turn handoff\n\n. done"); |
| 1500 | assert!( |
| 1501 | !read |
| 1502 | .iter() |
| 1503 | .any(|call| call.starts_with("conversation_projection")), |
| 1504 | "turn-only export must not read conversation snapshots: {read:?}" |
| 1505 | ); |
| 1506 | } |
| 1507 | |
| 1508 | #[test] |
| 1509 | fn turn_export_with_empty_workspace_path_skips_replacement() { |
| 1510 | let fake = FakeExport { |
| 1511 | turn: TurnHandoffProjection { |
| 1512 | markdown: "path stays".to_string(), |
| 1513 | workspace_path: String::new(), |
| 1514 | }, |
| 1515 | ..FakeExport::default() |
| 1516 | }; |
| 1517 | assert_eq!(sanitize_turn_handoff(&fake.turn), "path stays"); |
| 1518 | } |
| 1519 | |
| 1520 | #[test] |
| 1521 | fn restore_summary_distinguishes_every_state() { |
| 1522 | let mut none = String::new(); |
| 1523 | render_restore_summary(&mut none, &RestorePointProjection::None); |
| 1524 | assert!( |
| 1525 | none.contains("No workspace restore points are recorded"), |
| 1526 | "{none}" |
| 1527 | ); |
| 1528 | |
| 1529 | let mut unreadable = String::new(); |
| 1530 | render_restore_summary( |
| 1531 | &mut unreadable, |
| 1532 | &RestorePointProjection::Unreadable { |
| 1533 | reason: "permission denied".to_string(), |
| 1534 | }, |
| 1535 | ); |
| 1536 | assert!(unreadable.contains("could not be read"), "{unreadable}"); |
| 1537 | assert!( |
| 1538 | unreadable.contains("unavailable rather than empty"), |
| 1539 | "{unreadable}" |
| 1540 | ); |
| 1541 | |
| 1542 | let mut empty = String::new(); |
| 1543 | render_restore_summary( |
| 1544 | &mut empty, |
| 1545 | &RestorePointProjection::Recorded { |
| 1546 | snapshots: Vec::new(), |
| 1547 | }, |
| 1548 | ); |
| 1549 | assert!(empty.contains("records no restore points yet"), "{empty}"); |
| 1550 | |
| 1551 | let mut recorded = String::new(); |
| 1552 | render_restore_summary( |
| 1553 | &mut recorded, |
| 1554 | &RestorePointProjection::Recorded { |
| 1555 | snapshots: vec![ |
| 1556 | snapshot( |
| 1557 | &"a".repeat(40), |
| 1558 | "pre-turn:2: second prompt", |
| 1559 | 1_700_000_100, |
| 1560 | "pre-turn", |
| 1561 | Some(2), |
| 1562 | ), |
| 1563 | snapshot( |
| 1564 | &"b".repeat(40), |
| 1565 | "pre-turn:1: first prompt", |
| 1566 | 1_700_000_000, |
| 1567 | "pre-turn", |
| 1568 | Some(1), |
| 1569 | ), |
| 1570 | ], |
| 1571 | }, |
| 1572 | ); |
| 1573 | assert!( |
| 1574 | recorded.contains( |
| 1575 | "| 1 | `aaaaaaaaaaaa` | 2023-11-14T22:15:00Z | pre-turn:2: second prompt |" |
| 1576 | ), |
| 1577 | "{recorded}" |
| 1578 | ); |
| 1579 | assert!( |
| 1580 | recorded.contains( |
| 1581 | "| 2 | `bbbbbbbbbbbb` | 2023-11-14T22:13:20Z | pre-turn:1: first prompt |" |
| 1582 | ), |
| 1583 | "{recorded}" |
| 1584 | ); |
| 1585 | } |
| 1586 | |
| 1587 | #[test] |
| 1588 | fn correlation_matches_ambiguity_absence_and_role_rules() { |
| 1589 | let recorded = RestorePointProjection::Recorded { |
| 1590 | snapshots: vec![ |
| 1591 | snapshot( |
| 1592 | &"e".repeat(40), |
| 1593 | "pre-turn:9: run the tests", |
| 1594 | 1_700_000_300, |
| 1595 | "pre-turn", |
| 1596 | Some(9), |
| 1597 | ), |
| 1598 | snapshot( |
| 1599 | &"f".repeat(40), |
| 1600 | "pre-turn:5: run the tests", |
| 1601 | 1_700_000_100, |
| 1602 | "pre-turn", |
| 1603 | Some(5), |
| 1604 | ), |
| 1605 | snapshot( |
| 1606 | &"2".repeat(40), |
| 1607 | "tool:call_abc: rename the widget", |
| 1608 | 1_700_000_000, |
| 1609 | "tool", |
| 1610 | None, |
| 1611 | ), |
| 1612 | ], |
| 1613 | }; |
| 1614 | |
| 1615 | let ambiguous = correlation_markdown(&recorded, &user_message("run the tests")); |
| 1616 | assert!( |
| 1617 | ambiguous.contains("N1 `eeeeeeeeeeee` (pre-turn turn 9)"), |
| 1618 | "{ambiguous}" |
| 1619 | ); |
| 1620 | assert!( |
| 1621 | ambiguous.contains("N2 `ffffffffffff` (pre-turn turn 5)"), |
| 1622 | "{ambiguous}" |
| 1623 | ); |
| 1624 | assert!(ambiguous.contains("ambiguous"), "{ambiguous}"); |
| 1625 | |
| 1626 | let none = correlation_markdown(&recorded, &user_message("never snapshotted")); |
| 1627 | assert!(none.contains("none recorded for this message"), "{none}"); |
| 1628 | |
| 1629 | let tool_only = correlation_markdown(&recorded, &user_message("rename the widget")); |
| 1630 | assert!( |
| 1631 | tool_only.contains("none recorded for this message"), |
| 1632 | "{tool_only}" |
| 1633 | ); |
| 1634 | |
| 1635 | let assistant = correlation_markdown( |
| 1636 | &recorded, |
| 1637 | &ExportMessage { |
| 1638 | is_user_role: false, |
| 1639 | role: "assistant".to_string(), |
| 1640 | blocks: vec![ExportBlock::Text { |
| 1641 | text: "run the tests".to_string(), |
| 1642 | }], |
| 1643 | prompt_snippet: Some("run the tests".to_string()), |
| 1644 | }, |
| 1645 | ); |
| 1646 | assert!(assistant.is_empty(), "{assistant}"); |
| 1647 | } |
| 1648 | |
| 1649 | #[test] |
| 1650 | fn correlation_requires_exact_user_identity_not_the_role_string() { |
| 1651 | let recorded = RestorePointProjection::Recorded { |
| 1652 | snapshots: vec![snapshot( |
| 1653 | "aaaaaaaaaaaa", |
| 1654 | "pre-turn:4: run the tests", |
| 1655 | 5, |
| 1656 | "pre-turn", |
| 1657 | Some(4), |
| 1658 | )], |
| 1659 | }; |
| 1660 | // Same rendered role string as a real user turn, but not `Role::User`. |
| 1661 | let unrecognized = ExportMessage { |
| 1662 | role: "user".to_string(), |
| 1663 | is_user_role: false, |
| 1664 | blocks: vec![ExportBlock::Text { |
| 1665 | text: "run the tests".to_string(), |
| 1666 | }], |
| 1667 | prompt_snippet: Some("run the tests".to_string()), |
| 1668 | }; |
| 1669 | assert!( |
| 1670 | correlation_markdown(&recorded, &unrecognized).is_empty(), |
| 1671 | "a role that only renders as \"user\" must not correlate" |
| 1672 | ); |
| 1673 | |
| 1674 | let real_user = ExportMessage { |
| 1675 | is_user_role: true, |
| 1676 | ..unrecognized |
| 1677 | }; |
| 1678 | assert!( |
| 1679 | correlation_markdown(&recorded, &real_user).contains("N1 `aaaaaaaaaaaa`"), |
| 1680 | "an exact user turn still correlates" |
| 1681 | ); |
| 1682 | } |
| 1683 | |
| 1684 | #[test] |
| 1685 | fn history_fallback_marks_literals_and_sanitizes_visible_bodies() { |
| 1686 | let mut out = String::new(); |
| 1687 | render_history_fallback( |
| 1688 | &mut out, |
| 1689 | &[ |
| 1690 | HistoryEntry::Sanitized { |
| 1691 | role: "user".to_string(), |
| 1692 | body: "hello\u{1b}[31m world".to_string(), |
| 1693 | }, |
| 1694 | HistoryEntry::Literal { |
| 1695 | role: "system".to_string(), |
| 1696 | body: "[internal context omitted]".to_string(), |
| 1697 | }, |
| 1698 | ], |
| 1699 | ); |
| 1700 | assert!(out.contains("## 1. user\n\nhello world\n\n"), "{out}"); |
| 1701 | assert!( |
| 1702 | out.contains("## 2. system\n\n[internal context omitted]\n\n"), |
| 1703 | "{out}" |
| 1704 | ); |
| 1705 | |
| 1706 | let mut empty = String::new(); |
| 1707 | render_history_fallback(&mut empty, &[]); |
| 1708 | assert_eq!(empty, "## Conversation\n\n[empty conversation]\n"); |
| 1709 | } |
| 1710 | |
| 1711 | #[test] |
| 1712 | fn json_fence_tracks_longest_backtick_run_and_redacts_secrets() { |
| 1713 | let mut out = String::new(); |
| 1714 | push_json( |
| 1715 | &mut out, |
| 1716 | serde_json::json!({"api_key": "literal-secret", "note": "``` inner"}), |
| 1717 | ); |
| 1718 | assert!(!out.contains("literal-secret"), "{out}"); |
| 1719 | assert!(out.starts_with("````json\n"), "{out}"); |
| 1720 | assert!(out.contains("\"api_key\": \"[redacted]\""), "{out}"); |
| 1721 | } |
| 1722 | |
| 1723 | #[test] |
| 1724 | fn empty_content_and_missing_blocks_use_baseline_markers() { |
| 1725 | let names = HashMap::new(); |
| 1726 | let mut out = String::new(); |
| 1727 | render_message( |
| 1728 | &mut out, |
| 1729 | 1, |
| 1730 | ExportMessage { |
| 1731 | is_user_role: false, |
| 1732 | role: "assistant".to_string(), |
| 1733 | blocks: Vec::new(), |
| 1734 | prompt_snippet: None, |
| 1735 | }, |
| 1736 | &names, |
| 1737 | ); |
| 1738 | assert!(out.contains("## 1. assistant\n\n[no content]\n\n"), "{out}"); |
| 1739 | |
| 1740 | let mut empty_text = String::new(); |
| 1741 | render_content_block( |
| 1742 | &mut empty_text, |
| 1743 | ExportBlock::Text { |
| 1744 | text: " ".to_string(), |
| 1745 | }, |
| 1746 | &names, |
| 1747 | &mut false, |
| 1748 | ); |
| 1749 | assert!(empty_text.ends_with("[empty text]\n\n"), "{empty_text}"); |
| 1750 | } |
| 1751 | |
| 1752 | #[test] |
| 1753 | fn parser_handles_whitespace_case_and_flag_positions() { |
| 1754 | assert_eq!( |
| 1755 | parse_request(Some(" clipboard ")).unwrap(), |
| 1756 | request(ExportScope::Conversation, ExportDestination::Clipboard) |
| 1757 | ); |
| 1758 | assert_eq!( |
| 1759 | parse_request(Some(" TURN ")).unwrap(), |
| 1760 | request(ExportScope::Turn, ExportDestination::Clipboard) |
| 1761 | ); |
| 1762 | assert_eq!( |
| 1763 | parse_request(Some(" File Report One.md ")).unwrap(), |
| 1764 | request( |
| 1765 | ExportScope::Conversation, |
| 1766 | file_destination(Some("Report One.md"), false) |
| 1767 | ) |
| 1768 | ); |
| 1769 | assert_eq!( |
| 1770 | parse_request(Some("turn FILE --Force handoff.md")).unwrap(), |
| 1771 | request( |
| 1772 | ExportScope::Turn, |
| 1773 | file_destination(Some("handoff.md"), true) |
| 1774 | ) |
| 1775 | ); |
| 1776 | assert_eq!( |
| 1777 | parse_request(Some("file out.md --force")).unwrap(), |
| 1778 | request( |
| 1779 | ExportScope::Conversation, |
| 1780 | file_destination(Some("out.md"), true) |
| 1781 | ) |
| 1782 | ); |
| 1783 | assert_eq!( |
| 1784 | parse_request(Some("turn file")).unwrap().destination, |
| 1785 | file_destination(None, false) |
| 1786 | ); |
| 1787 | assert_eq!( |
| 1788 | parse_request(Some("turn file --force")) |
| 1789 | .unwrap() |
| 1790 | .destination, |
| 1791 | file_destination(None, true) |
| 1792 | ); |
| 1793 | assert_eq!( |
| 1794 | parse_request(Some("turn clipboard extra.md")).unwrap_err(), |
| 1795 | export_usage("clipboard does not accept a path") |
| 1796 | ); |
| 1797 | } |
| 1798 | |
| 1799 | #[test] |
| 1800 | fn header_metadata_keeps_unsaved_and_workspace_fallbacks() { |
| 1801 | let projection = ConversationExportProjection { |
| 1802 | metadata: codewhale_command_contract::facets::ExportMetadata { |
| 1803 | session_label: "unsaved".to_string(), |
| 1804 | title: None, |
| 1805 | provider: "unknown".to_string(), |
| 1806 | model: "unknown".to_string(), |
| 1807 | mode: "agent".to_string(), |
| 1808 | workspace_name: "workspace".to_string(), |
| 1809 | message_count: 0, |
| 1810 | exported_at_unix: 0, |
| 1811 | }, |
| 1812 | transcript: TranscriptProjection::Authoritative(Vec::new()), |
| 1813 | restore_points: RestorePointProjection::None, |
| 1814 | turn_outcomes: Vec::new(), |
| 1815 | }; |
| 1816 | |
| 1817 | let rendered = render_conversation(projection); |
| 1818 | |
| 1819 | assert!( |
| 1820 | rendered.contains("- Exported: 1970-01-01T00:00:00Z\n"), |
| 1821 | "{rendered}" |
| 1822 | ); |
| 1823 | assert!(rendered.contains("- Session: unsaved\n"), "{rendered}"); |
| 1824 | assert!(rendered.contains("- Provider: unknown\n"), "{rendered}"); |
| 1825 | assert!(rendered.contains("- Model: unknown\n"), "{rendered}"); |
| 1826 | assert!(rendered.contains("- Workspace: workspace\n"), "{rendered}"); |
| 1827 | assert!(rendered.contains("- Messages: 0\n"), "{rendered}"); |
| 1828 | } |
| 1829 | |
| 1830 | #[test] |
| 1831 | fn every_content_block_variant_renders_exactly() { |
| 1832 | let names = HashMap::from([("call-1".to_string(), "fetch_url".to_string())]); |
| 1833 | |
| 1834 | // Image reference: URL credentials and sensitive query values are masked. |
| 1835 | let mut image = String::new(); |
| 1836 | render_content_block( |
| 1837 | &mut image, |
| 1838 | ExportBlock::ImageReference { |
| 1839 | url: "https://alice:pw@example.com/a.png?api_key=hidden&ok=1".to_string(), |
| 1840 | }, |
| 1841 | &names, |
| 1842 | &mut false, |
| 1843 | ); |
| 1844 | assert_eq!( |
| 1845 | image, |
| 1846 | "### Image attachment\n\n- Reference: https://***:***@example.com/a.png?api_key=***&ok=1\n\n" |
| 1847 | ); |
| 1848 | |
| 1849 | // Inline/local image payloads became an omission marker at projection. |
| 1850 | let mut omitted = String::new(); |
| 1851 | render_content_block(&mut omitted, ExportBlock::ImageOmitted, &names, &mut false); |
| 1852 | assert_eq!( |
| 1853 | omitted, |
| 1854 | "### Image attachment\n\n- Reference omitted (inline or local image payload)\n\n" |
| 1855 | ); |
| 1856 | |
| 1857 | // Reasoning bodies and signatures are replaced by the baseline marker. |
| 1858 | let mut reasoning = String::new(); |
| 1859 | render_content_block( |
| 1860 | &mut reasoning, |
| 1861 | ExportBlock::InternalReasoning, |
| 1862 | &names, |
| 1863 | &mut false, |
| 1864 | ); |
| 1865 | assert_eq!(reasoning, "[internal reasoning and signature omitted]\n\n"); |
| 1866 | |
| 1867 | // Tool call with caller metadata and redacted JSON input. |
| 1868 | let mut tool_call = String::new(); |
| 1869 | render_content_block( |
| 1870 | &mut tool_call, |
| 1871 | ExportBlock::ToolCall { |
| 1872 | id: "call-1".to_string(), |
| 1873 | name: "fetch_url".to_string(), |
| 1874 | caller: Some(codewhale_command_contract::facets::ToolCallerProjection { |
| 1875 | caller_type: "code_execution_20250825".to_string(), |
| 1876 | tool_id: Some("server-tool-1".to_string()), |
| 1877 | }), |
| 1878 | input: serde_json::json!({"api_key": "literal-secret"}), |
| 1879 | }, |
| 1880 | &names, |
| 1881 | &mut false, |
| 1882 | ); |
| 1883 | assert_eq!( |
| 1884 | tool_call, |
| 1885 | "### Tool call: fetch_url\n\n- ID: call-1\n- Caller type: code_execution_20250825\n- Caller tool ID: server-tool-1\n\n```json\n{\n \"api_key\": \"[redacted]\"\n}\n```\n\n" |
| 1886 | ); |
| 1887 | |
| 1888 | // Tool call without caller metadata omits only the caller lines. |
| 1889 | let mut bare_tool_call = String::new(); |
| 1890 | render_content_block( |
| 1891 | &mut bare_tool_call, |
| 1892 | ExportBlock::ToolCall { |
| 1893 | id: "call-2".to_string(), |
| 1894 | name: "read_file".to_string(), |
| 1895 | caller: None, |
| 1896 | input: serde_json::json!({}), |
| 1897 | }, |
| 1898 | &names, |
| 1899 | &mut false, |
| 1900 | ); |
| 1901 | assert_eq!( |
| 1902 | bare_tool_call, |
| 1903 | "### Tool call: read_file\n\n- ID: call-2\n\n```json\n{}\n```\n\n" |
| 1904 | ); |
| 1905 | |
| 1906 | // Tool result with structured blocks: both the sanitized result text |
| 1907 | // and the redacted structured payload are rendered. |
| 1908 | let mut structured_result = String::new(); |
| 1909 | render_content_block( |
| 1910 | &mut structured_result, |
| 1911 | ExportBlock::ToolResult { |
| 1912 | tool_use_id: "call-1".to_string(), |
| 1913 | content: "tool output line".to_string(), |
| 1914 | is_error: false, |
| 1915 | structured: Some(serde_json::json!([{"session_token": "session-secret"}])), |
| 1916 | }, |
| 1917 | &names, |
| 1918 | &mut false, |
| 1919 | ); |
| 1920 | assert_eq!( |
| 1921 | structured_result, |
| 1922 | "### Tool result: fetch_url\n\n- Tool call ID: call-1\n\n```text\ntool output line\n```\n\nStructured result blocks:\n\n```json\n[\n {\n \"session_token\": \"[redacted]\"\n }\n]\n```\n\n" |
| 1923 | ); |
| 1924 | |
| 1925 | // Tool result without structured blocks ends after the result text, and |
| 1926 | // an empty body keeps the baseline empty marker. |
| 1927 | let mut plain_result = String::new(); |
| 1928 | render_content_block( |
| 1929 | &mut plain_result, |
| 1930 | ExportBlock::ToolResult { |
| 1931 | tool_use_id: "call-2".to_string(), |
| 1932 | content: String::new(), |
| 1933 | is_error: true, |
| 1934 | structured: None, |
| 1935 | }, |
| 1936 | &names, |
| 1937 | &mut false, |
| 1938 | ); |
| 1939 | assert_eq!( |
| 1940 | plain_result, |
| 1941 | "### Tool result\n\n- Tool call ID: call-2\n- Error: true\n\n[empty text]\n\n" |
| 1942 | ); |
| 1943 | |
| 1944 | let mut server_call = String::new(); |
| 1945 | render_content_block( |
| 1946 | &mut server_call, |
| 1947 | ExportBlock::ServerToolCall { |
| 1948 | id: "srv-1".to_string(), |
| 1949 | name: "web_search".to_string(), |
| 1950 | input: serde_json::json!({"query": "rust"}), |
| 1951 | }, |
| 1952 | &names, |
| 1953 | &mut false, |
| 1954 | ); |
| 1955 | assert_eq!( |
| 1956 | server_call, |
| 1957 | "### Server tool call: web_search\n\n- ID: srv-1\n\n```json\n{\n \"query\": \"rust\"\n}\n```\n\n" |
| 1958 | ); |
| 1959 | |
| 1960 | let mut search_result = String::new(); |
| 1961 | render_content_block( |
| 1962 | &mut search_result, |
| 1963 | ExportBlock::ToolSearchResult { |
| 1964 | tool_use_id: "search-1".to_string(), |
| 1965 | content: serde_json::json!({"results": []}), |
| 1966 | }, |
| 1967 | &names, |
| 1968 | &mut false, |
| 1969 | ); |
| 1970 | assert_eq!( |
| 1971 | search_result, |
| 1972 | "### Tool-search result\n\n- Tool call ID: search-1\n\n```json\n{\n \"results\": []\n}\n```\n\n" |
| 1973 | ); |
| 1974 | |
| 1975 | let mut execution_result = String::new(); |
| 1976 | render_content_block( |
| 1977 | &mut execution_result, |
| 1978 | ExportBlock::CodeExecutionResult { |
| 1979 | tool_use_id: "exec-1".to_string(), |
| 1980 | content: serde_json::json!({"stdout": "ok"}), |
| 1981 | }, |
| 1982 | &names, |
| 1983 | &mut false, |
| 1984 | ); |
| 1985 | assert_eq!( |
| 1986 | execution_result, |
| 1987 | "### Code-execution result\n\n- Tool call ID: exec-1\n\n```json\n{\n \"stdout\": \"ok\"\n}\n```\n\n" |
| 1988 | ); |
| 1989 | } |
| 1990 | |
| 1991 | #[test] |
| 1992 | fn conversation_export_interleaves_redacted_turn_outcomes_at_message_positions() { |
| 1993 | let mut projection = conversation_projection(vec![ |
| 1994 | user_message("first turn"), |
| 1995 | ExportMessage { |
| 1996 | is_user_role: false, |
| 1997 | role: "assistant".to_string(), |
| 1998 | blocks: vec![ExportBlock::ToolCall { |
| 1999 | id: "call-1".to_string(), |
| 2000 | name: "todo_write".to_string(), |
| 2001 | caller: None, |
| 2002 | input: serde_json::json!({}), |
| 2003 | }], |
| 2004 | prompt_snippet: None, |
| 2005 | }, |
| 2006 | ExportMessage { |
| 2007 | is_user_role: true, |
| 2008 | role: "user".to_string(), |
| 2009 | blocks: vec![ExportBlock::ToolResult { |
| 2010 | tool_use_id: "call-1".to_string(), |
| 2011 | content: "ok".to_string(), |
| 2012 | is_error: false, |
| 2013 | structured: None, |
| 2014 | }], |
| 2015 | prompt_snippet: None, |
| 2016 | }, |
| 2017 | user_message("second turn"), |
| 2018 | ]); |
| 2019 | projection.turn_outcomes = vec![ |
| 2020 | ExportTurnOutcome { |
| 2021 | status: "failed".to_string(), |
| 2022 | error: "SSE stream request failed with Authorization: Bearer super-secret-token" |
| 2023 | .to_string(), |
| 2024 | code: Some("llm_network_error".to_string()), |
| 2025 | ended_at_unix: 1_700_000_060, |
| 2026 | after_message_count: 3, |
| 2027 | }, |
| 2028 | ExportTurnOutcome { |
| 2029 | status: "interrupted".to_string(), |
| 2030 | error: "Turn stopped by operator".to_string(), |
| 2031 | code: None, |
| 2032 | ended_at_unix: 1_700_000_120, |
| 2033 | after_message_count: 99, |
| 2034 | }, |
| 2035 | ]; |
| 2036 | |
| 2037 | let markdown = render_conversation(projection.clone()); |
| 2038 | let tool_pos = markdown.find("## 3. tool").expect("tool message"); |
| 2039 | let first_outcome_pos = markdown |
| 2040 | .find("## Turn outcome (failed)") |
| 2041 | .expect("first turn outcome"); |
| 2042 | let second_user_pos = markdown.find("## 4. user").expect("second user message"); |
| 2043 | let trailing_outcome_pos = markdown |
| 2044 | .find("## Turn outcome (interrupted)") |
| 2045 | .expect("trailing turn outcome"); |
| 2046 | assert!( |
| 2047 | tool_pos < first_outcome_pos |
| 2048 | && first_outcome_pos < second_user_pos |
| 2049 | && second_user_pos < trailing_outcome_pos, |
| 2050 | "{markdown}" |
| 2051 | ); |
| 2052 | assert!(markdown.contains("- Status: failed\n"), "{markdown}"); |
| 2053 | assert!( |
| 2054 | markdown.contains("- Ended: 2023-11-14T22:14:20Z\n"), |
| 2055 | "{markdown}" |
| 2056 | ); |
| 2057 | assert!( |
| 2058 | markdown.contains("- Code: `llm_network_error`\n"), |
| 2059 | "{markdown}" |
| 2060 | ); |
| 2061 | assert!( |
| 2062 | markdown.contains("Authorization: [redacted]"), |
| 2063 | "turn outcome secrets must be redacted: {markdown}" |
| 2064 | ); |
| 2065 | assert!( |
| 2066 | !markdown.contains("super-secret-token"), |
| 2067 | "turn outcome leaked secret: {markdown}" |
| 2068 | ); |
| 2069 | assert!(markdown.contains("Turn stopped by operator"), "{markdown}"); |
| 2070 | |
| 2071 | let no_tools = render_export(projection.clone(), ExportFormat::Markdown, false); |
| 2072 | let nt_first_user = no_tools.find("## 1. user").expect("first user"); |
| 2073 | let nt_first_outcome = no_tools |
| 2074 | .find("## Turn outcome (failed)") |
| 2075 | .expect("outcome after dropped tool messages"); |
| 2076 | let nt_second_user = no_tools.find("## 2. user").expect("second user"); |
| 2077 | assert!( |
| 2078 | nt_first_user < nt_first_outcome && nt_first_outcome < nt_second_user, |
| 2079 | "--no-tools must keep turn outcomes at their chronological boundary: {no_tools}" |
| 2080 | ); |
| 2081 | |
| 2082 | let html = render_export(projection.clone(), ExportFormat::Html, true); |
| 2083 | assert!(html.contains("Turn outcome · failed"), "{html}"); |
| 2084 | assert!(html.contains("Code llm_network_error"), "{html}"); |
| 2085 | assert!(!html.contains("super-secret-token"), "{html}"); |
| 2086 | |
| 2087 | let json_raw = render_export(projection, ExportFormat::Json, true); |
| 2088 | let parsed: serde_json::Value = serde_json::from_str(&json_raw).expect("valid json"); |
| 2089 | let outcomes = parsed["turn_outcomes"] |
| 2090 | .as_array() |
| 2091 | .expect("json turn_outcomes"); |
| 2092 | assert_eq!(outcomes.len(), 2); |
| 2093 | assert_eq!(outcomes[0]["status"], "failed"); |
| 2094 | assert_eq!(outcomes[0]["code"], "llm_network_error"); |
| 2095 | assert_eq!(outcomes[0]["after_message_count"], 3); |
| 2096 | assert!(!json_raw.contains("super-secret-token"), "{json_raw}"); |
| 2097 | } |
| 2098 | } |
| 2099 |