| 1 | //! Portable regression evidence for the expanded debug group. Fake facets |
| 2 | //! record authority and ordering; all handlers and renderers are production code. |
| 3 | |
| 4 | use super::{DebugAction, portable_handlers, receipts, undo}; |
| 5 | use codewhale_command_contract::facets::*; |
| 6 | use codewhale_command_contract::handler::{ |
| 7 | CommandCapabilities as Caps, CommandContexts, CommandHandler, |
| 8 | }; |
| 9 | use std::cell::RefCell; |
| 10 | use std::rc::Rc; |
| 11 | |
| 12 | struct UndoPresentation; |
| 13 | impl CommandPresentationContext for UndoPresentation { |
| 14 | fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> { |
| 15 | let catalog: serde_json::Value = |
| 16 | serde_json::from_str(include_str!("../../../localization/locales/en.json")).unwrap(); |
| 17 | let id: String = key |
| 18 | .split('_') |
| 19 | .map(|word| { |
| 20 | let mut chars = word.chars(); |
| 21 | chars |
| 22 | .next() |
| 23 | .unwrap() |
| 24 | .to_uppercase() |
| 25 | .chain(chars) |
| 26 | .collect::<String>() |
| 27 | }) |
| 28 | .collect(); |
| 29 | let mut text = catalog[&id] |
| 30 | .as_str() |
| 31 | .ok_or_else(|| format!("unknown test key {key}"))? |
| 32 | .to_string(); |
| 33 | for (name, value) in replacements { |
| 34 | text = text.replace(&format!("{{{name}}}"), value); |
| 35 | } |
| 36 | Ok(text) |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | #[test] |
| 41 | fn diff_formats_and_localizes_observations_without_host_state_or_actions() { |
| 42 | struct Diff(DebugDiffObservation); |
| 43 | impl CommandDebugDiffContext for Diff { |
| 44 | fn diff(&self) -> DebugDiffObservation { |
| 45 | self.0.clone() |
| 46 | } |
| 47 | } |
| 48 | struct Presentation(&'static str); |
| 49 | impl CommandPresentationContext for Presentation { |
| 50 | fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> { |
| 51 | let json = match self.0 { |
| 52 | "en" => include_str!("../../../localization/locales/en.json"), |
| 53 | "zh-Hans" => include_str!("../../../localization/locales/zh-Hans.json"), |
| 54 | _ => unreachable!(), |
| 55 | }; |
| 56 | let catalog: serde_json::Value = serde_json::from_str(json).unwrap(); |
| 57 | let id: String = key |
| 58 | .split('_') |
| 59 | .map(|word| { |
| 60 | let mut chars = word.chars(); |
| 61 | chars |
| 62 | .next() |
| 63 | .unwrap() |
| 64 | .to_uppercase() |
| 65 | .chain(chars) |
| 66 | .collect::<String>() |
| 67 | }) |
| 68 | .collect(); |
| 69 | let mut text = catalog[&id] |
| 70 | .as_str() |
| 71 | .ok_or_else(|| format!("unknown test key {key}"))? |
| 72 | .to_string(); |
| 73 | for (name, value) in replacements { |
| 74 | text = text.replace(&format!("{{{name}}}"), value); |
| 75 | } |
| 76 | Ok(text) |
| 77 | } |
| 78 | } |
| 79 | let output = |
| 80 | |names: &str, stat: &str, patch: &str, patch_truncated| DebugDiffObservation::Output { |
| 81 | names: names.into(), |
| 82 | stat: stat.into(), |
| 83 | patch: patch.into(), |
| 84 | patch_truncated, |
| 85 | }; |
| 86 | let patch = "diff --git a/c.rs b/c.rs\n@@ -1 +1 @@\n-old\n+new\n"; |
| 87 | for (observation, message, error, diff) in [ |
| 88 | ( |
| 89 | DebugDiffObservation::GitUnavailable, |
| 90 | "Error: git not found on PATH", |
| 91 | true, |
| 92 | None, |
| 93 | ), |
| 94 | ( |
| 95 | DebugDiffObservation::NoBaseline, |
| 96 | "Nothing to compare yet: this session has not saved a restore point here, and this folder is not a git repository.", |
| 97 | false, |
| 98 | None, |
| 99 | ), |
| 100 | ( |
| 101 | DebugDiffObservation::Failed("fixture I/O".into()), |
| 102 | "Git diff failed — is this a git repository?\nfixture I/O", |
| 103 | false, |
| 104 | None, |
| 105 | ), |
| 106 | ( |
| 107 | output(" \n", "ignored", "ignored", false), |
| 108 | "No changes since session start", |
| 109 | false, |
| 110 | None, |
| 111 | ), |
| 112 | ( |
| 113 | output("a.rs\n\nb.rs\n", "", "", false), |
| 114 | "Changed files (2):\na.rs\nb.rs", |
| 115 | false, |
| 116 | None, |
| 117 | ), |
| 118 | ( |
| 119 | output("a -> b\nc.rs\n", " 2 files changed\n", patch, false), |
| 120 | "Changed files (2, 1 renamed):\na -> b\nc.rs\n\n── Stat ──\n2 files changed", |
| 121 | false, |
| 122 | Some(patch), |
| 123 | ), |
| 124 | ( |
| 125 | output("c.rs\n", "", patch, true), |
| 126 | "Changed files (1):\nc.rs\n\nThe diff is too long to show in full. The file list above is complete.", |
| 127 | false, |
| 128 | Some(patch), |
| 129 | ), |
| 130 | ( |
| 131 | output("c.rs\n", "", "", true), |
| 132 | "Changed files (1):\nc.rs\n\nThe diff is too long to show in full. The file list above is complete.", |
| 133 | false, |
| 134 | None, |
| 135 | ), |
| 136 | ] { |
| 137 | let result = undo::diff( |
| 138 | CommandContexts::empty() |
| 139 | .with_debug_diff(&mut Diff(observation)) |
| 140 | .with_presentation(&mut Presentation("en")), |
| 141 | None, |
| 142 | ); |
| 143 | assert_eq!(result.message.as_deref(), Some(message)); |
| 144 | assert_eq!(result.is_error, error); |
| 145 | // The changed lines travel as a pager request, never as transcript |
| 146 | // text: a patch is not Markdown. |
| 147 | match (result.action, diff) { |
| 148 | (None, None) => {} |
| 149 | (Some(DebugAction::OpenDiffPager { title, diff }), Some(expected)) => { |
| 150 | assert_eq!(title, "Changes since session start"); |
| 151 | assert_eq!(diff, expected); |
| 152 | } |
| 153 | (action, expected) => panic!("{message}: {action:?} vs {expected:?}"), |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | let result = undo::diff( |
| 158 | CommandContexts::empty() |
| 159 | .with_debug_diff(&mut Diff(output( |
| 160 | "a -> b\nc.rs\n", |
| 161 | " 2 files changed\n", |
| 162 | patch, |
| 163 | false, |
| 164 | ))) |
| 165 | .with_presentation(&mut Presentation("zh-Hans")), |
| 166 | None, |
| 167 | ); |
| 168 | assert_eq!( |
| 169 | result.message.as_deref(), |
| 170 | Some("变更文件(2 个,其中 1 个已重命名):\na -> b\nc.rs\n\n── 统计 ──\n2 files changed") |
| 171 | ); |
| 172 | assert!(!result.is_error); |
| 173 | assert!(matches!( |
| 174 | result.action, |
| 175 | Some(DebugAction::OpenDiffPager { ref title, ref diff }) |
| 176 | if title == "会话开始以来的变更" && diff == patch |
| 177 | )); |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | fn change_checks_presentation_before_reading_the_host_projection() { |
| 182 | struct NoRead; |
| 183 | impl CommandDebugChangeContext for NoRead { |
| 184 | fn change_projection(&self) -> DebugChangeProjection { |
| 185 | panic!("missing capability must prevent host reads") |
| 186 | } |
| 187 | } |
| 188 | let result = super::change::change( |
| 189 | CommandContexts::empty().with_debug_change(&mut NoRead), |
| 190 | None, |
| 191 | ); |
| 192 | assert_eq!( |
| 193 | result.message.as_deref(), |
| 194 | Some("Error: Command capability unavailable: presentation") |
| 195 | ); |
| 196 | assert!(result.is_error); |
| 197 | assert!(result.action.is_none()); |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn whole_group_has_exact_authority_and_safe_missing_facets() { |
| 202 | let expected = [ |
| 203 | ("tokens", Caps::DEBUG_DIAGNOSTICS | Caps::PRESENTATION), |
| 204 | ("cost", Caps::DEBUG_DIAGNOSTICS | Caps::PRESENTATION), |
| 205 | ("receipts", Caps::DEBUG_RECEIPTS), |
| 206 | ("balance", Caps::DEBUG_DIAGNOSTICS), |
| 207 | ("cache", Caps::DEBUG_DIAGNOSTICS | Caps::PRESENTATION), |
| 208 | ("preview-request", Caps::NONE), |
| 209 | ("tools", Caps::DEBUG_DIAGNOSTICS), |
| 210 | ("change", Caps::DEBUG_CHANGE | Caps::PRESENTATION), |
| 211 | ("system", Caps::DEBUG_DIAGNOSTICS), |
| 212 | ("context", Caps::DEBUG_DIAGNOSTICS), |
| 213 | ("edit", Caps::DEBUG_HISTORY), |
| 214 | ("diff", Caps::DEBUG_DIFF | Caps::PRESENTATION), |
| 215 | ( |
| 216 | "undo", |
| 217 | Caps::DEBUG_UNDO | Caps::DEBUG_HISTORY | Caps::PRESENTATION, |
| 218 | ), |
| 219 | ("retry", Caps::DEBUG_HISTORY), |
| 220 | ]; |
| 221 | for ((info, handler), (name, expected)) in portable_handlers().into_iter().zip(expected) { |
| 222 | assert_eq!(info.name, name); |
| 223 | match handler { |
| 224 | CommandHandler::Pure(run) => { |
| 225 | assert_eq!(name, "preview-request"); |
| 226 | assert!(expected.is_empty()); |
| 227 | assert!(matches!( |
| 228 | run(Some("json")).action, |
| 229 | Some(DebugAction::PreviewOutboundRequest { json: true, .. }) |
| 230 | )); |
| 231 | } |
| 232 | CommandHandler::Contextual { |
| 233 | capabilities, |
| 234 | handler, |
| 235 | } => { |
| 236 | assert_eq!(capabilities, expected, "/{name}"); |
| 237 | let result = handler(CommandContexts::empty(), None); |
| 238 | assert!(result.is_error, "/{name}"); |
| 239 | assert!( |
| 240 | result |
| 241 | .message |
| 242 | .unwrap() |
| 243 | .starts_with("Error: Command capability unavailable:") |
| 244 | ); |
| 245 | assert!(result.action.is_none()); |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | fn empty_receipt() -> Receipt { |
| 252 | Receipt { |
| 253 | schema_id: RECEIPT_SCHEMA_ID, |
| 254 | source: ReceiptSource { |
| 255 | kind: SourceKind::Session, |
| 256 | id: "session-1".into(), |
| 257 | title: None, |
| 258 | workspace: None, |
| 259 | model: None, |
| 260 | started_at: None, |
| 261 | updated_at: None, |
| 262 | }, |
| 263 | turn: None, |
| 264 | postures: vec![], |
| 265 | totals: ReceiptTotals::default(), |
| 266 | usage: None, |
| 267 | actions: vec![], |
| 268 | omitted_actions: 0, |
| 269 | not_recorded: vec![], |
| 270 | claim_ceiling: [ |
| 271 | "local_record_only", |
| 272 | "not_safety_certification", |
| 273 | "not_provider_compatibility_certification", |
| 274 | ], |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | struct ReceiptFacet { |
| 279 | calls: RefCell<Vec<Option<String>>>, |
| 280 | result: Result<Receipt, DebugReceiptError>, |
| 281 | } |
| 282 | impl CommandDebugReceiptsContext for ReceiptFacet { |
| 283 | fn receipt(&self, turn: Option<&str>) -> Result<Receipt, DebugReceiptError> { |
| 284 | self.calls.borrow_mut().push(turn.map(str::to_owned)); |
| 285 | self.result.clone() |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn receipts_validate_before_host_reads_and_preserve_last_turn_selector() { |
| 291 | let mut facet = ReceiptFacet { |
| 292 | calls: RefCell::new(vec![]), |
| 293 | result: Ok(empty_receipt()), |
| 294 | }; |
| 295 | for argument in [ |
| 296 | "bad", |
| 297 | "json -1", |
| 298 | "999999999999999999999999999999999999999999", |
| 299 | ] { |
| 300 | let result = receipts::receipts( |
| 301 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 302 | Some(argument), |
| 303 | ); |
| 304 | assert!(result.is_error); |
| 305 | assert!( |
| 306 | result |
| 307 | .message |
| 308 | .unwrap() |
| 309 | .contains("Use /receipts [json] [<turn>].") |
| 310 | ); |
| 311 | } |
| 312 | assert!(facet.calls.borrow().is_empty()); |
| 313 | let result = receipts::receipts( |
| 314 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 315 | Some("json 2 03"), |
| 316 | ); |
| 317 | assert!(!result.is_error); |
| 318 | assert_eq!(&*facet.calls.borrow(), &[Some("03".into())]); |
| 319 | let result = receipts::receipts( |
| 320 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 321 | None, |
| 322 | ); |
| 323 | assert_eq!( |
| 324 | result.message.as_deref(), |
| 325 | Some("# Receipt: session session-1\n\nsession session-1\n\nNo actions recorded.") |
| 326 | ); |
| 327 | assert!(result.action.is_none()); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn receipt_failures_keep_the_approval_and_builder_error_contracts() { |
| 332 | for (error, message) in [ |
| 333 | ( |
| 334 | DebugReceiptError::ApprovalLog("broken record".into()), |
| 335 | "Error: Could not read this session's approval log: broken record", |
| 336 | ), |
| 337 | ( |
| 338 | DebugReceiptError::Build("turn 9 not found".into()), |
| 339 | "Error: turn 9 not found", |
| 340 | ), |
| 341 | ] { |
| 342 | let mut facet = ReceiptFacet { |
| 343 | calls: RefCell::new(vec![]), |
| 344 | result: Err(error), |
| 345 | }; |
| 346 | let result = receipts::receipts( |
| 347 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 348 | None, |
| 349 | ); |
| 350 | assert!(result.is_error); |
| 351 | assert_eq!(result.message.as_deref(), Some(message)); |
| 352 | assert!(result.action.is_none()); |
| 353 | assert_eq!(facet.calls.borrow().len(), 1); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn receipt_rendering_preserves_json_fences_and_prevents_forged_terminal_lines() { |
| 359 | let mut receipt = empty_receipt(); |
| 360 | receipt.source.title = Some("````\nforged\u{1b}[31m".into()); |
| 361 | let mut facet = ReceiptFacet { |
| 362 | calls: RefCell::new(vec![]), |
| 363 | result: Ok(receipt), |
| 364 | }; |
| 365 | let result = receipts::receipts( |
| 366 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 367 | Some("json"), |
| 368 | ); |
| 369 | let output = result.message.unwrap(); |
| 370 | let json = output |
| 371 | .strip_prefix("`````json\n") |
| 372 | .unwrap() |
| 373 | .strip_suffix("\n`````") |
| 374 | .unwrap(); |
| 375 | let value: serde_json::Value = serde_json::from_str(json).unwrap(); |
| 376 | assert_eq!(value["schema_id"], RECEIPT_SCHEMA_ID); |
| 377 | assert_eq!(value["source"]["title"], "````\nforged\u{1b}[31m"); |
| 378 | let result = receipts::receipts( |
| 379 | CommandContexts::empty().with_debug_receipts(&mut facet), |
| 380 | None, |
| 381 | ); |
| 382 | let output = result.message.unwrap(); |
| 383 | assert!(!output.contains("\nforged")); |
| 384 | assert!(!output.contains('\u{1b}')); |
| 385 | assert!(output.contains("\\nforged\\u{1b}")); |
| 386 | } |
| 387 | |
| 388 | #[derive(Default)] |
| 389 | struct HistoryFacet { |
| 390 | events: Rc<RefCell<Vec<&'static str>>>, |
| 391 | input: Option<String>, |
| 392 | composer: Option<String>, |
| 393 | removed: usize, |
| 394 | } |
| 395 | impl CommandDebugHistoryContext for HistoryFacet { |
| 396 | fn last_user_input(&self) -> Option<String> { |
| 397 | self.events.borrow_mut().push("last_user"); |
| 398 | self.input.clone() |
| 399 | } |
| 400 | fn load_composer(&mut self, input: String) { |
| 401 | self.events.borrow_mut().push("composer"); |
| 402 | self.composer = Some(input); |
| 403 | } |
| 404 | fn undo_conversation(&mut self) -> DebugConversationUndo { |
| 405 | self.events.borrow_mut().push("undo_chat"); |
| 406 | DebugConversationUndo { |
| 407 | removed: self.removed, |
| 408 | sync: synced_conversation(), |
| 409 | } |
| 410 | } |
| 411 | } |
| 412 | fn synced_conversation() -> SessionSyncPayload { |
| 413 | SessionSyncPayload { |
| 414 | session_id: Some("undo-session".to_string()), |
| 415 | messages: Vec::new(), |
| 416 | system_prompt: None, |
| 417 | model: "model".to_string(), |
| 418 | workspace: std::path::PathBuf::from("/tmp/undo-workspace"), |
| 419 | mode: codewhale_command_contract::CommandMode::Agent, |
| 420 | agent_preset: None, |
| 421 | } |
| 422 | } |
| 423 | struct UndoFacet; |
| 424 | impl CommandDebugUndoContext for UndoFacet {} |
| 425 | |
| 426 | /// `/undo` defers mutation to the admitted host action; invalid options |
| 427 | /// are reported before a file or message is touched. |
| 428 | #[test] |
| 429 | fn undo_defers_latest_and_force_and_rejects_unknown_options() { |
| 430 | let events = Rc::new(RefCell::new(vec![])); |
| 431 | let mut history = HistoryFacet { |
| 432 | events: events.clone(), |
| 433 | removed: 2, |
| 434 | ..Default::default() |
| 435 | }; |
| 436 | let mut facet = UndoFacet; |
| 437 | for (arg, force) in [ |
| 438 | (None, false), |
| 439 | (Some(" "), false), |
| 440 | (Some("force"), true), |
| 441 | (Some(" FORCE "), true), |
| 442 | ] { |
| 443 | let result = undo::undo( |
| 444 | CommandContexts::empty() |
| 445 | .with_debug_undo(&mut facet) |
| 446 | .with_debug_history(&mut history) |
| 447 | .with_presentation(&mut UndoPresentation), |
| 448 | arg, |
| 449 | ); |
| 450 | assert!( |
| 451 | events.borrow().is_empty(), |
| 452 | "mutation precedes host admission: {arg:?}" |
| 453 | ); |
| 454 | assert_eq!( |
| 455 | result.action, |
| 456 | Some(DebugAction::UndoLatestRequest { force }) |
| 457 | ); |
| 458 | assert!(result.message.is_none()); |
| 459 | } |
| 460 | let result = undo::undo( |
| 461 | CommandContexts::empty() |
| 462 | .with_debug_undo(&mut facet) |
| 463 | .with_debug_history(&mut history) |
| 464 | .with_presentation(&mut UndoPresentation), |
| 465 | Some("everything"), |
| 466 | ); |
| 467 | assert!(result.is_error); |
| 468 | assert!( |
| 469 | result.message.as_deref().is_some_and( |
| 470 | |message| message.contains("`everything`") && message.contains("/undo force") |
| 471 | ), |
| 472 | "{:?}", |
| 473 | result.message |
| 474 | ); |
| 475 | assert!(events.borrow().is_empty(), "nothing ran"); |
| 476 | } |
| 477 | |
| 478 | #[test] |
| 479 | fn undo_requires_both_facets_and_defers_without_mutating_history() { |
| 480 | let events = Rc::new(RefCell::new(vec![])); |
| 481 | let mut facet = UndoFacet; |
| 482 | let result = undo::undo(CommandContexts::empty().with_debug_undo(&mut facet), None); |
| 483 | assert_eq!( |
| 484 | result.message.as_deref(), |
| 485 | Some("Error: Command capability unavailable: debug_history") |
| 486 | ); |
| 487 | assert!(events.borrow().is_empty()); |
| 488 | let mut history = HistoryFacet { |
| 489 | events: events.clone(), |
| 490 | removed: 2, |
| 491 | ..Default::default() |
| 492 | }; |
| 493 | let result = undo::undo( |
| 494 | CommandContexts::empty() |
| 495 | .with_debug_undo(&mut facet) |
| 496 | .with_debug_history(&mut history) |
| 497 | .with_presentation(&mut UndoPresentation), |
| 498 | None, |
| 499 | ); |
| 500 | assert_eq!( |
| 501 | result.action, |
| 502 | Some(DebugAction::UndoLatestRequest { force: false }) |
| 503 | ); |
| 504 | assert!(result.message.is_none()); |
| 505 | assert!( |
| 506 | events.borrow().is_empty(), |
| 507 | "an old facet cannot bypass asynchronous admission or discard history" |
| 508 | ); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn retry_truncates_history_before_emitting_the_exact_original_input() { |
| 513 | let input = "漢字".repeat(20); |
| 514 | let mut history = HistoryFacet { |
| 515 | input: Some(input.clone()), |
| 516 | removed: 2, |
| 517 | ..Default::default() |
| 518 | }; |
| 519 | let result = undo::retry( |
| 520 | CommandContexts::empty().with_debug_history(&mut history), |
| 521 | None, |
| 522 | ); |
| 523 | assert_eq!( |
| 524 | result.action, |
| 525 | Some(DebugAction::ConversationUndo { |
| 526 | sync: synced_conversation(), |
| 527 | restored_files: 0, |
| 528 | retry_input: Some(input.clone()), |
| 529 | }) |
| 530 | ); |
| 531 | assert_eq!( |
| 532 | result.message, |
| 533 | Some(format!("Retrying: {}...", "漢字".repeat(8))) |
| 534 | ); |
| 535 | assert_eq!(&*history.events.borrow(), &["last_user", "undo_chat"]); |
| 536 | history.events.borrow_mut().clear(); |
| 537 | let result = undo::edit( |
| 538 | CommandContexts::empty().with_debug_history(&mut history), |
| 539 | None, |
| 540 | ); |
| 541 | assert!(!result.is_error); |
| 542 | assert_eq!(history.composer, Some(input)); |
| 543 | assert_eq!(&*history.events.borrow(), &["last_user", "composer"]); |
| 544 | } |
| 545 |