返回 CodeWhale
session_export_regression_tests.rs
根目录 / crates / tui / src / commands / session_export_regression_tests.rs
1 //! FEAT-025 Phase 3: real-host regression coverage for the session-export
2 //! adapter.
3 //!
4 //! These tests deliberately stay outside `groups/session`, which FEAT-043
5 //! moves into `codewhale-commands`. They exercise the TUI-owned
6 //! `SessionExportAdapter` through the capability envelope and assert the
7 //! baseline host contracts: metadata derivation, data-minimized projections,
8 //! the shared turn-handoff renderer, read-only restore-point projection,
9 //! clipboard/recovery ordering inputs, and protected file resolution/writing.
10 //!
11 //! No test depends on a manual terminal, GUI, device, or live clipboard.
12
13 use std::path::{Path, PathBuf};
14
15 use tempfile::TempDir;
16
17 use codewhale_command_contract::facets::{
18 ConversationExportProjection, ExportBlock, HistoryEntry, RestorePointProjection,
19 RestoreSnapshot, TranscriptProjection, TurnHandoffProjection,
20 };
21 use codewhale_command_contract::handler::CommandCapabilities;
22
23 use crate::test_support::{EnvVarGuard, TestEnvLock};
24 use crate::tui::app::{App, TuiOptions};
25 use crate::tui::clipboard::ClipboardHandler;
26 use crate::tui::history::HistoryCell;
27 use codewhale_error_taxonomy::ErrorSeverity;
28 use codewhale_models::{ContentBlock, ImageUrlContent, Message, Role, ToolCaller};
29 use codewhale_runtime::config::Config;
30 use codewhale_snapshot::SnapshotRepo;
31
32 use crate::commands::session_export_test_support::{
33 assert_only_export_facet_exposed, normalize_export_time, normalize_recorded_export,
34 normalize_turn_generated_at,
35 };
36 use crate::commands::{CommandResult, execute};
37
38 struct ExportHarness {
39 app: App,
40 // Guards are declared before the lock and the temporary directory so the
41 // environment is restored before the lock is released and before the
42 // temporary files are removed (matches ControlHarness).
43 _home: EnvVarGuard,
44 _codewhale_home: EnvVarGuard,
45 _ssh: [EnvVarGuard; 3],
46 _env_lock: TestEnvLock,
47 temp: TempDir,
48 }
49
50 impl ExportHarness {
51 fn new() -> Self {
52 let env_lock = crate::test_support::lock_test_env();
53 let temp = TempDir::new().expect("tempdir");
54 let home = temp.path().join("home");
55 std::fs::create_dir_all(&home).expect("home dir");
56 let _home = EnvVarGuard::set("HOME", &home);
57 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &home);
58 let _ssh = ["SSH_CLIENT", "SSH_CONNECTION", "SSH_TTY"].map(EnvVarGuard::remove);
59 let options = TuiOptions {
60 skills_dir: temp.path().join("skills"),
61 memory_path: temp.path().join("memory.md"),
62 mcp_config_path: temp.path().join("mcp.json"),
63 ..crate::tui::test_support::test_tui_options(temp.path())
64 };
65 let app = App::new(options, &Config::default());
66 Self {
67 app,
68 _home,
69 _codewhale_home,
70 _ssh,
71 _env_lock: env_lock,
72 temp,
73 }
74 }
75 }
76
77 fn conversation_projection(app: &mut App) -> ConversationExportProjection {
78 let mut bundle = app.command_contexts();
79 let mut parts = bundle.parts();
80 parts
81 .export
82 .as_mut()
83 .expect("export facet")
84 .conversation_projection()
85 }
86
87 fn turn_handoff_projection(app: &mut App) -> TurnHandoffProjection {
88 let mut bundle = app.command_contexts();
89 let mut parts = bundle.parts();
90 parts
91 .export
92 .as_mut()
93 .expect("export facet")
94 .turn_handoff_projection()
95 }
96
97 fn text_message(role: Role, text: &str) -> Message {
98 Message {
99 role,
100 content: vec![ContentBlock::Text {
101 text: text.to_string(),
102 cache_control: None,
103 }],
104 }
105 }
106
107 #[test]
108 fn adapter_projects_authoritative_metadata_and_omits_hidden_payloads() {
109 let mut harness = ExportHarness::new();
110 harness.app.current_session_id = Some("session-123456789".to_string());
111 harness.app.api_messages = std::sync::Arc::new(vec![
112 text_message(Role::System, "hidden policy must never export"),
113 text_message(Role::User, "please inspect\nthe output"),
114 Message {
115 role: Role::Assistant,
116 content: vec![
117 ContentBlock::Thinking {
118 thinking: "private chain of thought".to_string(),
119 signature: Some("signature-secret".to_string()),
120 state: None,
121 redacted_data: None,
122 },
123 ContentBlock::ToolUse {
124 execution_id: None,
125 id: "call-1".to_string(),
126 name: "fetch_url".to_string(),
127 input: serde_json::json!({"url": "https://example.com/a"}),
128 caller: Some(ToolCaller {
129 caller_type: "code_execution_20250825".to_string(),
130 tool_id: Some("server-tool-1".to_string()),
131 }),
132 thought_signature: None,
133 },
134 ContentBlock::ImageUrl {
135 image_url: ImageUrlContent {
136 url: "data:image/png;base64,very-secret-image-data".to_string(),
137 },
138 },
139 ContentBlock::ImageUrl {
140 image_url: ImageUrlContent {
141 url: "https://example.com/remote.png".to_string(),
142 },
143 },
144 ],
145 },
146 ]);
147
148 let projection = conversation_projection(&mut harness.app);
149
150 assert_eq!(projection.metadata.session_label, "session-");
151 assert_eq!(
152 projection.metadata.provider,
153 harness.app.provider_identity_for_persistence()
154 );
155 assert_eq!(projection.metadata.model, harness.app.model_display_label());
156 assert_eq!(projection.metadata.mode, harness.app.mode.display_name());
157 assert_eq!(
158 projection.metadata.workspace_name,
159 harness
160 .temp
161 .path()
162 .file_name()
163 .and_then(|name| name.to_str())
164 .unwrap()
165 );
166 assert_eq!(projection.metadata.message_count, 3);
167 assert!(projection.metadata.exported_at_unix > 0);
168
169 let TranscriptProjection::Authoritative(messages) = &projection.transcript else {
170 panic!("authoritative transcript expected");
171 };
172 assert_eq!(messages.len(), 3);
173 assert_eq!(messages[1].role, "user");
174 assert_eq!(
175 messages[1].prompt_snippet.as_deref(),
176 Some("please inspect")
177 );
178 assert!(matches!(
179 messages[2].blocks[0],
180 ExportBlock::InternalReasoning
181 ));
182 assert!(matches!(messages[2].blocks[2], ExportBlock::ImageOmitted));
183 assert!(matches!(
184 &messages[2].blocks[3],
185 ExportBlock::ImageReference { url } if url == "https://example.com/remote.png"
186 ));
187 let ExportBlock::ToolCall { caller, .. } = &messages[2].blocks[1] else {
188 panic!("tool call expected");
189 };
190 let caller = caller.as_ref().expect("caller projection");
191 assert_eq!(caller.caller_type, "code_execution_20250825");
192 assert_eq!(caller.tool_id.as_deref(), Some("server-tool-1"));
193
194 let debug = format!("{projection:?}");
195 for forbidden in [
196 "private chain of thought",
197 "signature-secret",
198 "very-secret-image-data",
199 ] {
200 assert!(
201 !debug.contains(forbidden),
202 "hidden payload {forbidden:?} crossed the projection boundary"
203 );
204 }
205 }
206
207 #[test]
208 fn adapter_projects_visible_history_fallback_with_baseline_markers() {
209 let mut harness = ExportHarness::new();
210 harness.app.api_messages_mut().clear();
211 harness.app.history = vec![
212 HistoryCell::User {
213 content: "user text".to_string(),
214 },
215 HistoryCell::Assistant {
216 content: "assistant text".to_string(),
217 streaming: false,
218 },
219 HistoryCell::System {
220 content: "hidden system".to_string(),
221 },
222 HistoryCell::Thinking {
223 content: "hidden reasoning".to_string(),
224 streaming: false,
225 duration_secs: None,
226 },
227 HistoryCell::Error {
228 message: "boom".to_string(),
229 severity: ErrorSeverity::Warning,
230 code: None,
231 },
232 ];
233
234 let projection = conversation_projection(&mut harness.app);
235 let TranscriptProjection::HistoryFallback(entries) = &projection.transcript else {
236 panic!("history fallback expected");
237 };
238 assert_eq!(projection.metadata.message_count, 5);
239 assert_eq!(
240 entries[0],
241 HistoryEntry::Sanitized {
242 role: "user".to_string(),
243 body: "user text".to_string(),
244 }
245 );
246 assert_eq!(
247 entries[1],
248 HistoryEntry::Sanitized {
249 role: "assistant".to_string(),
250 body: "assistant text".to_string(),
251 }
252 );
253 assert_eq!(
254 entries[2],
255 HistoryEntry::Literal {
256 role: "system".to_string(),
257 body: "[internal context omitted]".to_string(),
258 }
259 );
260 assert_eq!(
261 entries[3],
262 HistoryEntry::Literal {
263 role: "internal reasoning".to_string(),
264 body: "[internal reasoning omitted]".to_string(),
265 }
266 );
267 assert_eq!(
268 entries[4],
269 HistoryEntry::Sanitized {
270 role: "warning".to_string(),
271 body: "boom".to_string(),
272 }
273 );
274 }
275
276 #[test]
277 fn adapter_reuses_turn_handoff_renderer_and_workspace_value() {
278 let mut harness = ExportHarness::new();
279 harness.app.history.push(HistoryCell::User {
280 content: "Fix the flaky login test".to_string(),
281 });
282 harness.app.history.push(HistoryCell::Assistant {
283 content: "Fixed the login test.".to_string(),
284 streaming: false,
285 });
286 harness.app.runtime_turn_status = Some("completed".to_string());
287
288 let direct = crate::tui::ui::turn_handoff_markdown(&harness.app);
289 let projection = turn_handoff_projection(&mut harness.app);
290
291 // The renderer stamps `generated <wall-clock second>` on every call, so two
292 // calls straddling a second boundary legitimately differ in that one field
293 // (seen on Windows CI: `10:35:58` vs `10:35:59`). Compare everything else
294 // byte-for-byte, and check both calls still carry the stamp.
295 assert!(direct.contains(" \u{b7} generated "));
296 assert!(projection.markdown.contains(" \u{b7} generated "));
297 assert_eq!(
298 normalize_turn_generated_at(&projection.markdown),
299 normalize_turn_generated_at(&direct),
300 "renderer output must not drift"
301 );
302 assert!(projection.markdown.contains("# Turn handoff"));
303 assert_eq!(
304 projection.workspace_path,
305 harness.app.workspace.to_string_lossy().into_owned()
306 );
307 }
308
309 #[test]
310 fn adapter_projects_absent_restore_points_without_creating_a_repo() {
311 let mut harness = ExportHarness::new();
312 let workspace = harness.temp.path().join("workspace");
313 std::fs::create_dir_all(&workspace).expect("workspace");
314 harness.app.workspace = workspace.clone();
315 let before = codewhale_snapshot::snapshot_git_dir(&workspace).expect("snapshot path");
316 assert!(!before.exists(), "precondition: no side repo yet");
317
318 let projection = conversation_projection(&mut harness.app);
319
320 assert!(matches!(
321 projection.restore_points,
322 RestorePointProjection::None
323 ));
324 assert!(
325 !codewhale_snapshot::snapshot_git_dir(&workspace)
326 .expect("snapshot path")
327 .exists(),
328 "projection must never create the snapshot repo"
329 );
330 }
331
332 #[test]
333 fn adapter_projects_recorded_restore_points_as_semantic_fields() {
334 let mut harness = ExportHarness::new();
335 let workspace = harness.temp.path().join("workspace");
336 std::fs::create_dir_all(&workspace).expect("workspace");
337 harness.app.workspace = workspace.clone();
338 let repo = SnapshotRepo::open_or_init(&workspace).expect("open side repo");
339 repo.snapshot("pre-turn:2: second prompt")
340 .expect("record snapshot");
341
342 let projection = conversation_projection(&mut harness.app);
343
344 let RestorePointProjection::Recorded { snapshots } = &projection.restore_points else {
345 panic!("recorded restore points expected");
346 };
347 assert_eq!(snapshots.len(), 1);
348 let snapshot: &RestoreSnapshot = &snapshots[0];
349 assert_eq!(snapshot.id.len(), 40, "full id crosses; portable truncates");
350 assert_eq!(snapshot.kind, "pre-turn");
351 assert_eq!(snapshot.sequence, Some(2));
352 assert_eq!(snapshot.prompt_snippet.as_deref(), Some("second prompt"));
353 assert_eq!(snapshot.label, "pre-turn:2: second prompt");
354 assert!(snapshot.timestamp_unix > 0);
355 }
356
357 #[test]
358 fn adapter_projects_user_identity_from_the_role_enum_not_the_string() {
359 // F6: the baseline compared `message.role != Role::User`. Projecting only
360 // the rendered role string would lose that distinction, because
361 // `Role::Unrecognized("user")` renders as "user" but is not `Role::User`.
362 let mut harness = ExportHarness::new();
363 harness.app.api_messages = std::sync::Arc::new(vec![
364 Message {
365 role: Role::Unrecognized("user".to_string()),
366 content: vec![ContentBlock::Text {
367 text: "looks like a user turn".to_string(),
368 cache_control: None,
369 }],
370 },
371 text_message(Role::User, "actually a user turn"),
372 ]);
373
374 let projection = conversation_projection(&mut harness.app);
375 let TranscriptProjection::Authoritative(messages) = &projection.transcript else {
376 panic!("authoritative transcript expected");
377 };
378 assert_eq!(
379 messages[0].role, "user",
380 "the rendered role string is unchanged"
381 );
382 assert!(
383 !messages[0].is_user_role,
384 "Role::Unrecognized(\"user\") must not be treated as a user turn"
385 );
386 assert!(messages[1].is_user_role, "Role::User is a user turn");
387 }
388
389 fn clipboard_facet(app: &mut App) -> bool {
390 let mut bundle = app.command_contexts();
391 let mut parts = bundle.parts();
392 parts
393 .export
394 .as_mut()
395 .expect("export facet")
396 .clipboard_requires_terminal_paste()
397 }
398
399 #[test]
400 fn adapter_exposes_clipboard_mode_recovery_and_delivery_separately() {
401 let mut harness = ExportHarness::new();
402
403 harness.app.clipboard = ClipboardHandler::for_test(true, true);
404 assert!(clipboard_facet(&mut harness.app));
405 harness.app.clipboard = ClipboardHandler::for_test(false, false);
406 assert!(!clipboard_facet(&mut harness.app));
407
408 // Recovery write is one operation and returns the shared path.
409 let recovery = {
410 let mut bundle = harness.app.command_contexts();
411 let mut parts = bundle.parts();
412 parts
413 .export
414 .as_mut()
415 .expect("export facet")
416 .write_recovery_copy("recover me")
417 };
418 let recovery = recovery.expect("recovery path");
419 assert!(recovery.ends_with("exports/last-copy.md"));
420 assert_eq!(
421 std::fs::read_to_string(&recovery).expect("recovery content"),
422 "recover me"
423 );
424
425 // Clipboard delivery is a separate operation and records the payload.
426 harness.app.clipboard = ClipboardHandler::for_test(false, false);
427 {
428 let mut bundle = harness.app.command_contexts();
429 let mut parts = bundle.parts();
430 parts
431 .export
432 .as_mut()
433 .expect("export facet")
434 .write_clipboard("deliver me")
435 .expect("clipboard write");
436 }
437 assert_eq!(
438 harness.app.clipboard.last_written_text(),
439 Some("deliver me")
440 );
441
442 // A failing clipboard still returns the raw host error text.
443 harness.app.clipboard = ClipboardHandler::unavailable_for_test(false);
444 let failure = {
445 let mut bundle = harness.app.command_contexts();
446 let mut parts = bundle.parts();
447 parts
448 .export
449 .as_mut()
450 .expect("export facet")
451 .write_clipboard("nope")
452 };
453 assert!(failure.is_err());
454 }
455
456 fn resolve(app: &mut App, raw: &str) -> Result<PathBuf, String> {
457 let mut bundle = app.command_contexts();
458 let mut parts = bundle.parts();
459 parts
460 .export
461 .as_mut()
462 .expect("export facet")
463 .resolve_export_path(raw)
464 }
465
466 /// Create a workspace directory whose path contains no symlink component.
467 ///
468 /// macOS places `TempDir` under `/var/folders/...`, and `/var` is a symlink to
469 /// `/private/var`. The protected export writer deliberately rejects any path
470 /// with a symlink component, so an adapter-level test that calls
471 /// `write_export_file` directly - bypassing `resolve_export_path`, which
472 /// canonicalizes the workspace for the real command - must hand it an already
473 /// resolved path. Linux temp dirs contain no symlink, so only macOS CI sees the
474 /// difference.
475 fn canonical_workspace(harness: &ExportHarness) -> PathBuf {
476 let root = std::fs::canonicalize(harness.temp.path()).expect("canonical temp root");
477 let workspace = root.join("workspace");
478 std::fs::create_dir_all(&workspace).expect("workspace");
479 workspace
480 }
481
482 fn write_file(
483 app: &mut App,
484 path: &std::path::Path,
485 contents: &[u8],
486 force: bool,
487 ) -> Result<(), String> {
488 let mut bundle = app.command_contexts();
489 let mut parts = bundle.parts();
490 parts
491 .export
492 .as_mut()
493 .expect("export facet")
494 .write_export_file(path, contents, force)
495 }
496
497 #[test]
498 fn adapter_resolves_export_paths_with_baseline_errors() {
499 let mut harness = ExportHarness::new();
500 let workspace = harness.temp.path().join("workspace");
501 std::fs::create_dir_all(&workspace).expect("workspace");
502 harness.app.workspace = workspace.clone();
503
504 assert_eq!(
505 resolve(&mut harness.app, "transcript.md").expect("workspace relative"),
506 std::fs::canonicalize(&workspace)
507 .unwrap()
508 .join("transcript.md")
509 );
510 assert_eq!(
511 resolve(&mut harness.app, "").unwrap_err(),
512 "export path is empty"
513 );
514 assert!(
515 resolve(&mut harness.app, "../outside.md")
516 .unwrap_err()
517 .contains("may not contain `..`")
518 );
519 assert!(
520 resolve(&mut harness.app, "/")
521 .unwrap_err()
522 .starts_with("export path must name a file:")
523 );
524 }
525
526 #[test]
527 fn adapter_preserves_protected_file_write_and_overwrite_refusal() {
528 let mut harness = ExportHarness::new();
529 let workspace = canonical_workspace(&harness);
530 harness.app.workspace = workspace.clone();
531 let target = workspace.join("transcript.md");
532
533 write_file(&mut harness.app, &target, b"first", false).expect("first write");
534 assert_eq!(std::fs::read_to_string(&target).unwrap(), "first");
535 #[cfg(unix)]
536 {
537 use std::os::unix::fs::PermissionsExt;
538 assert_eq!(
539 std::fs::metadata(&target).unwrap().permissions().mode() & 0o777,
540 0o600
541 );
542 }
543
544 let refused = write_file(&mut harness.app, &target, b"second", false).unwrap_err();
545 assert!(refused.contains("destination already exists"));
546 assert_eq!(std::fs::read_to_string(&target).unwrap(), "first");
547
548 write_file(&mut harness.app, &target, b"third", true).expect("forced write");
549 assert_eq!(std::fs::read_to_string(&target).unwrap(), "third");
550
551 let missing_parent =
552 write_file(&mut harness.app, &workspace.join("nope/x.md"), b"x", false).unwrap_err();
553 assert!(missing_parent.contains("parent directory"));
554 }
555
556 #[cfg(unix)]
557 #[test]
558 fn adapter_rejects_symlink_leaf_and_ancestor_exports() {
559 use std::os::unix::fs::symlink;
560
561 let mut harness = ExportHarness::new();
562 let workspace = canonical_workspace(&harness);
563 harness.app.workspace = workspace.clone();
564
565 let real_file = workspace.join("real.md");
566 std::fs::write(&real_file, "keep").expect("fixture file");
567 let leaf = workspace.join("leaf.md");
568 symlink(&real_file, &leaf).expect("leaf symlink");
569 let leaf_result = write_file(&mut harness.app, &leaf, b"replace", true).unwrap_err();
570 assert!(leaf_result.contains("symlink component"));
571 assert_eq!(std::fs::read_to_string(&real_file).unwrap(), "keep");
572
573 let real_dir = workspace.join("real-dir");
574 std::fs::create_dir(&real_dir).expect("real dir");
575 let linked_dir = workspace.join("linked-dir");
576 symlink(&real_dir, &linked_dir).expect("dir symlink");
577 let ancestor_result =
578 write_file(&mut harness.app, &linked_dir.join("out.md"), b"x", false).unwrap_err();
579 assert!(ancestor_result.contains("symlink component"));
580 assert!(!real_dir.join("out.md").exists());
581 }
582
583 /// The protected writer refuses any path whose ancestors include a symlink,
584 /// which on macOS is true of everything under `/var` (and therefore every
585 /// `TempDir`) because `/var` is a symlink to `/private/var`. An adapter-level
586 /// test that calls `write_export_file` directly must therefore hand it a
587 /// resolved path - `resolve_export_path` canonicalizes the workspace for the
588 /// real command, and `canonical_workspace` does the same for these tests.
589 ///
590 /// This test builds the symlink itself, so a Linux run catches the class of bug
591 /// that macOS CI caught in `adapter_preserves_protected_file_write_and_overwrite_refusal`
592 /// and `adapter_rejects_directory_destination_and_parent_not_a_directory`.
593 #[cfg(unix)]
594 #[test]
595 fn protected_writer_requires_a_path_free_of_symlink_ancestors() {
596 use std::os::unix::fs::symlink;
597
598 let harness = ExportHarness::new();
599 let real = harness.temp.path().join("real-root");
600 std::fs::create_dir_all(&real).expect("real root");
601 let link = harness.temp.path().join("link-root");
602 symlink(&real, &link).expect("root symlink");
603
604 // Reached through the symlinked root: refused, and nothing is written.
605 let refused =
606 crate::commands::session_export_host::write_export_file(&link.join("out.md"), b"x", false)
607 .expect_err("a symlinked ancestor must be refused");
608 assert!(refused.contains("symlink component"), "{refused}");
609 assert!(!real.join("out.md").exists());
610
611 // The same file through the resolved root is accepted, which is exactly what
612 // `canonical_workspace` supplies.
613 let resolved = std::fs::canonicalize(&link).expect("canonical root");
614 crate::commands::session_export_host::write_export_file(&resolved.join("out.md"), b"x", false)
615 .expect("a resolved path must be writable");
616 assert_eq!(
617 std::fs::read_to_string(resolved.join("out.md")).unwrap(),
618 "x"
619 );
620 }
621
622 #[test]
623 fn envelope_exposes_export_only_for_the_declared_capability() {
624 let mut harness = ExportHarness::new();
625
626 {
627 let mut bundle = harness.app.command_contexts();
628 let export_only = bundle
629 .contexts(CommandCapabilities::SESSION_EXPORT)
630 .into_parts();
631 // Exhaustive across all sixteen `ContextParts` slots (see the helper),
632 // so a newly added facet cannot silently join the export envelope.
633 assert_only_export_facet_exposed(export_only);
634 }
635
636 {
637 let mut bundle = harness.app.command_contexts();
638 let unrelated_only = bundle.contexts(CommandCapabilities::SESSION).into_parts();
639 assert!(
640 unrelated_only.export.is_none(),
641 "export must not be exposed without its declared capability"
642 );
643 }
644 }
645
646 // ---------------------------------------------------------------------------
647 // FEAT-025 Phase 4: full-command parity regressions relocated from the legacy
648 // `groups/session/export.rs` tests. They dispatch through the public command
649 // seam so the portable handler and the TUI export adapter are exercised
650 // together against real clipboard, filesystem, and snapshot fixtures.
651 // ---------------------------------------------------------------------------
652
653 fn dispatch(app: &mut App, arg: Option<&str>) -> CommandResult {
654 match arg {
655 Some(arg) => execute(&format!("/export {arg}"), app),
656 None => execute("/export", app),
657 }
658 }
659
660 // ---------------------------------------------------------------------------
661 // FEAT-025 audit hardening: full-document goldens captured from the
662 // pre-refactor implementation at `3f3aa9ed7` (see
663 // `fixtures/export_conversation_baseline.md` and `export_turn_baseline.md`).
664 //
665 // The goldens were produced by dispatching the same fixture through the
666 // *baseline* public `/export` seam in a scratch worktree (repository state
667 // `3f3aa9ed7`), not authored from the migrated implementation, so a
668 // divergence in the adapter projection or the portable renderer fails here
669 // with an exact byte offset. Only the two host-derived stamps (the export
670 // `- Exported:` line and the turn-handoff header) are normalised; every other
671 // byte, including redaction markers and omission text, is compared verbatim.
672 //
673 // To re-capture, reproduce the fixture below against a verified baseline and
674 // replace the fixture files - never regenerate them from the new code, which
675 // would turn this into a tautology.
676 // ---------------------------------------------------------------------------
677
678 /// Workspace pinned by the captured goldens (a path with no snapshot repo, so
679 /// the baseline restore-point state is `None`).
680 const BASELINE_WORKSPACE: &str = "/workspace/example";
681
682 /// Session id pinned by the captured goldens.
683 const BASELINE_SESSION: &str = "session-123456789";
684
685 /// The exact transcript fixture the baseline goldens were captured from.
686 fn baseline_golden_messages() -> Vec<Message> {
687 vec![
688 Message {
689 role: Role::System,
690 content: vec![ContentBlock::Text {
691 text: "hidden policy must never export".to_string(),
692 cache_control: None,
693 }],
694 },
695 Message {
696 role: Role::User,
697 content: vec![ContentBlock::Text {
698 text: "Please inspect this\u{1b}[31m output\u{1b}[0m".to_string(),
699 cache_control: None,
700 }],
701 },
702 Message {
703 role: Role::Assistant,
704 content: vec![
705 ContentBlock::Thinking {
706 thinking: "private chain of thought".to_string(),
707 signature: Some("signature-secret".to_string()),
708 state: None,
709 redacted_data: None,
710 },
711 ContentBlock::ToolUse {
712 execution_id: None,
713 id: "call-1".to_string(),
714 name: "fetch_url".to_string(),
715 input: serde_json::json!({
716 "url": "https://alice:password@example.com/path?token=very-secret&ok=1",
717 "api_key": "literal-api-secret",
718 "nested": {"authorization": "Bearer abcdefghijklmnop"},
719 }),
720 caller: Some(ToolCaller {
721 caller_type: "code_execution_20250825".to_string(),
722 tool_id: Some("server-tool-1".to_string()),
723 }),
724 thought_signature: None,
725 },
726 ],
727 },
728 Message {
729 role: Role::User,
730 content: vec![ContentBlock::ToolResult {
731 execution_id: None,
732 tool_use_id: "call-1".to_string(),
733 content: "Authorization: Bearer another-secret-token\nresult ok".to_string(),
734 is_error: Some(false),
735 content_blocks: Some(vec![
736 serde_json::json!({
737 "type": "image",
738 "mime_type": "image/png",
739 "data": "base64verysecretimagedata",
740 }),
741 serde_json::json!({"session_token": "session-secret", "note": "keep me"}),
742 ]),
743 }],
744 },
745 Message {
746 role: Role::Assistant,
747 content: vec![
748 ContentBlock::ImageUrl {
749 image_url: ImageUrlContent {
750 url: "https://example.com/visible.png?token=very-secret".to_string(),
751 },
752 },
753 ContentBlock::ImageUrl {
754 image_url: ImageUrlContent {
755 url: "data:image/png;base64,very-secret-image-data".to_string(),
756 },
757 },
758 ],
759 },
760 Message {
761 role: Role::Assistant,
762 content: vec![ContentBlock::ServerToolUse {
763 id: "srv-1".to_string(),
764 name: "web_search".to_string(),
765 input: serde_json::json!({"query": "secret token"}),
766 kind: None,
767 caller: None,
768 }],
769 },
770 Message {
771 role: Role::User,
772 content: vec![ContentBlock::ToolSearchToolResult {
773 tool_use_id: "srv-1".to_string(),
774 content: serde_json::json!({"results": []}),
775 }],
776 },
777 Message {
778 role: Role::Assistant,
779 content: vec![ContentBlock::CodeExecutionToolResult {
780 tool_use_id: "srv-2".to_string(),
781 content: serde_json::json!({"stdout": "ok"}),
782 }],
783 },
784 ]
785 }
786
787 #[test]
788 fn command_clipboard_export_matches_baseline_conversation_golden() {
789 let mut harness = ExportHarness::new();
790 harness.app.workspace = PathBuf::from(BASELINE_WORKSPACE);
791 harness.app.current_session_id = Some(BASELINE_SESSION.to_string());
792 harness.app.clipboard = ClipboardHandler::for_test(false, false);
793 harness.app.api_messages = std::sync::Arc::new(baseline_golden_messages());
794
795 let result = dispatch(&mut harness.app, None);
796 assert!(!result.is_error, "{:?}", result.message);
797 let markdown = harness
798 .app
799 .clipboard
800 .last_written_text()
801 .expect("clipboard payload")
802 .to_string();
803
804 let expected = normalize_export_time(include_str!("fixtures/export_conversation_baseline.md"));
805 crate::test_support::assert_byte_identical(
806 "baseline conversation export document",
807 &normalize_export_time(&markdown),
808 &expected,
809 );
810 }
811
812 #[test]
813 fn command_turn_export_matches_baseline_conversation_golden() {
814 let mut harness = ExportHarness::new();
815 harness.app.workspace = PathBuf::from(BASELINE_WORKSPACE);
816 harness.app.clipboard = ClipboardHandler::for_test(false, false);
817 harness.app.history.push(HistoryCell::User {
818 content: "Fix the flaky login test".to_string(),
819 });
820 harness.app.history.push(HistoryCell::Assistant {
821 content: "Fixed the login test.".to_string(),
822 streaming: false,
823 });
824 harness.app.runtime_turn_status = Some("completed".to_string());
825
826 let result = dispatch(&mut harness.app, Some("turn"));
827 assert!(!result.is_error, "{:?}", result.message);
828 let markdown = harness
829 .app
830 .clipboard
831 .last_written_text()
832 .expect("clipboard payload")
833 .to_string();
834
835 let expected = normalize_turn_generated_at(include_str!("fixtures/export_turn_baseline.md"));
836 crate::test_support::assert_byte_identical(
837 "baseline turn export document",
838 &normalize_turn_generated_at(&markdown),
839 &expected,
840 );
841 }
842
843 // ---------------------------------------------------------------------------
844 // FEAT-025 audit re-pass (finding G1): the first golden covered only the
845 // `RestorePointProjection::None` state and the authoritative transcript, so the
846 // `Recorded` restore table, the correlation lines, and the visible-history
847 // fallback were still asserted by hand-written expectations - the same class of
848 // weakness the first audit raised.
849 //
850 // These two goldens were captured the same way from baseline `3f3aa9ed7`:
851 // `fixtures/export_history_fallback_recorded_baseline.md` and
852 // `fixtures/export_correlation_recorded_baseline.md`. Snapshot commits carry a
853 // wall-clock author date, so the snapshot id and the `Recorded (UTC)` cell are
854 // normalised; the table structure, id truncation, correlation wording, the
855 // ambiguity warning, and the no-match line are compared verbatim.
856 // ---------------------------------------------------------------------------
857
858 /// Workspace **basename** pinned by the recorded-restore goldens. The export
859 /// header prints only the basename, so a per-test directory with this name
860 /// reproduces the captured document exactly while staying inside `TempDir`.
861 const BASELINE_RECORDED_WORKSPACE: &str = "f025-golden-workspace";
862
863 /// Seed the three snapshots the recorded goldens were captured with.
864 ///
865 /// Creation order matters: `SnapshotRepo::list` returns newest first, so this
866 /// yields `pre-turn:3`, `tool:call-1`, `pre-turn:2` in the table, and two
867 /// `pre-turn` entries sharing a prompt snippet - which is what makes the
868 /// correlation line ambiguous.
869 fn seed_baseline_restore_points(workspace: &Path) {
870 let repo = SnapshotRepo::open_or_init(workspace).expect("open side repo");
871 repo.snapshot("pre-turn:2: Fix the login test")
872 .expect("snapshot 1");
873 repo.snapshot("tool:call-1").expect("snapshot 2");
874 repo.snapshot("pre-turn:3: Fix the login test")
875 .expect("snapshot 3");
876 }
877
878 fn recorded_workspace(harness: &ExportHarness) -> PathBuf {
879 let workspace = harness.temp.path().join(BASELINE_RECORDED_WORKSPACE);
880 std::fs::create_dir_all(&workspace).expect("workspace");
881 seed_baseline_restore_points(&workspace);
882 workspace
883 }
884
885 #[test]
886 fn command_history_fallback_export_matches_baseline_recorded_golden() {
887 let mut harness = ExportHarness::new();
888 let workspace = recorded_workspace(&harness);
889 harness.app.workspace = workspace;
890 harness.app.current_session_id = Some("session-fallback".to_string());
891 harness.app.clipboard = ClipboardHandler::for_test(false, false);
892 harness.app.history.push(HistoryCell::User {
893 content: "Fix the login test".to_string(),
894 });
895 harness.app.history.push(HistoryCell::Assistant {
896 content: "Done.".to_string(),
897 streaming: false,
898 });
899
900 let result = dispatch(&mut harness.app, None);
901 assert!(!result.is_error, "{:?}", result.message);
902 let markdown = harness
903 .app
904 .clipboard
905 .last_written_text()
906 .expect("clipboard payload")
907 .to_string();
908
909 let expected = normalize_recorded_export(include_str!(
910 "fixtures/export_history_fallback_recorded_baseline.md"
911 ));
912 crate::test_support::assert_byte_identical(
913 "baseline history-fallback recorded export document",
914 &normalize_recorded_export(&markdown),
915 &expected,
916 );
917 }
918
919 #[test]
920 fn command_correlation_export_matches_baseline_recorded_golden() {
921 let mut harness = ExportHarness::new();
922 let workspace = recorded_workspace(&harness);
923 harness.app.workspace = workspace;
924 harness.app.current_session_id = Some("session-correlated".to_string());
925 harness.app.clipboard = ClipboardHandler::for_test(false, false);
926 harness.app.api_messages = std::sync::Arc::new(vec![
927 text_message(Role::User, "Fix the login test"),
928 text_message(Role::Assistant, "Working on it."),
929 text_message(Role::User, "unrelated question"),
930 ]);
931
932 let result = dispatch(&mut harness.app, None);
933 assert!(!result.is_error, "{:?}", result.message);
934 let markdown = harness
935 .app
936 .clipboard
937 .last_written_text()
938 .expect("clipboard payload")
939 .to_string();
940
941 let expected = normalize_recorded_export(include_str!(
942 "fixtures/export_correlation_recorded_baseline.md"
943 ));
944 crate::test_support::assert_byte_identical(
945 "baseline correlated recorded export document",
946 &normalize_recorded_export(&markdown),
947 &expected,
948 );
949 }
950
951 #[test]
952 fn export_entry_registers_through_portable_bridge_with_exact_metadata() {
953 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
954
955 let command = crate::commands::registry()
956 .get("export")
957 .expect("/export must be registered");
958 assert_eq!(command.info().name, "export");
959 assert_eq!(command.info().aliases, &["daochu"]);
960 assert_eq!(
961 command.info().usage,
962 "/export [clipboard|file [path]|turn [clipboard|file [path]]] [--format md|html|json] [--no-tools] [--force]"
963 );
964 assert!(
965 crate::commands::registry().get("daochu").is_some(),
966 "the /daochu alias must resolve to /export"
967 );
968 let handler = command
969 .contextual_handler()
970 .expect("/export must register through the portable bridge");
971 let CommandHandler::Contextual { capabilities, .. } = handler else {
972 panic!("/export must be contextual")
973 };
974 assert_eq!(
975 capabilities,
976 CommandCapabilities::SESSION_EXPORT,
977 "/export declares export authority only"
978 );
979 }
980
981 #[test]
982 fn command_clipboard_export_preserves_structure_and_redacts_secrets() {
983 let mut harness = ExportHarness::new();
984 let app = &mut harness.app;
985 app.current_session_id = Some("session-123456789".to_string());
986 app.api_messages = std::sync::Arc::new(vec![
987 Message {
988 role: Role::System,
989 content: vec![ContentBlock::Text {
990 text: "hidden policy must never export".to_string(),
991 cache_control: None,
992 }],
993 },
994 Message {
995 role: Role::User,
996 content: vec![ContentBlock::Text {
997 text: "Please inspect this\u{1b}[31m output\u{1b}[0m".to_string(),
998 cache_control: None,
999 }],
1000 },
1001 Message {
1002 role: Role::Assistant,
1003 content: vec![
1004 ContentBlock::Thinking {
1005 thinking: "private chain of thought".to_string(),
1006 signature: Some("signature-secret".to_string()),
1007 state: None,
1008 redacted_data: None,
1009 },
1010 ContentBlock::ToolUse {
1011 execution_id: None,
1012 id: "call-1".to_string(),
1013 name: "fetch_url".to_string(),
1014 input: serde_json::json!({
1015 "url": "https://alice:password@example.com/path?token=very-secret&ok=1",
1016 "api_key": "literal-api-secret",
1017 "nested": {"authorization": "Bearer abcdefghijklmnop"},
1018 }),
1019 caller: Some(ToolCaller {
1020 caller_type: "code_execution_20250825".to_string(),
1021 tool_id: Some("server-tool-1".to_string()),
1022 }),
1023 thought_signature: None,
1024 },
1025 ],
1026 },
1027 Message {
1028 role: Role::User,
1029 content: vec![ContentBlock::ToolResult {
1030 execution_id: None,
1031 tool_use_id: "call-1".to_string(),
1032 content: "Authorization: Bearer another-secret-token\nresult ok".to_string(),
1033 is_error: Some(false),
1034 content_blocks: Some(vec![serde_json::json!({
1035 "image": "https://example.com/a.png?api_key=hidden",
1036 "session_token": "session-secret",
1037 })]),
1038 }],
1039 },
1040 Message {
1041 role: Role::Assistant,
1042 content: vec![ContentBlock::ImageUrl {
1043 image_url: ImageUrlContent {
1044 url: "data:image/png;base64,very-secret-image-data".to_string(),
1045 },
1046 }],
1047 },
1048 ]);
1049 {
1050 let mut todos = app.todos.try_lock().expect("todos lock");
1051 todos.add(
1052 "export projection".to_string(),
1053 codewhale_engine::tools::todo::TodoStatus::InProgress,
1054 );
1055 }
1056 app.cycle_effort();
1057 let work_before = app.work_state_snapshot().expect("Work snapshot");
1058
1059 let result = dispatch(app, None);
1060
1061 assert!(!result.is_error, "{:?}", result.message);
1062 assert!(
1063 result
1064 .message
1065 .as_deref()
1066 .unwrap_or_default()
1067 .contains("local clipboard")
1068 );
1069 let markdown = app
1070 .clipboard
1071 .last_written_text()
1072 .expect("clipboard payload");
1073 let system = markdown.find("## 1. system").expect("system role");
1074 let user = markdown.find("## 2. user").expect("user role");
1075 let assistant = markdown.find("## 3. assistant").expect("assistant role");
1076 let tool_result = markdown.find("## 4. tool").expect("tool-result role");
1077 assert!(system < user && user < assistant && assistant < tool_result);
1078 assert!(markdown.contains("[internal context omitted]"));
1079 assert!(markdown.contains("call-1"));
1080 assert!(markdown.contains("fetch_url"));
1081 assert!(markdown.contains("server-tool-1"));
1082 assert!(markdown.contains("[internal reasoning and signature omitted]"));
1083 assert!(markdown.contains("[redacted]"));
1084 assert!(markdown.contains("https://***:***@example.com/path?token=***&ok=1"));
1085 assert!(markdown.contains("Reference omitted (inline or local image payload)"));
1086 let workspace_path = harness.temp.path().to_string_lossy().into_owned();
1087 for forbidden in [
1088 "hidden policy must never export",
1089 "private chain of thought",
1090 "signature-secret",
1091 "literal-api-secret",
1092 "very-secret",
1093 "another-secret-token",
1094 "session-secret",
1095 "very-secret-image-data",
1096 "\u{1b}[31m",
1097 workspace_path.as_str(),
1098 ] {
1099 assert!(
1100 !markdown.contains(forbidden),
1101 "leaked {forbidden:?}: {markdown}"
1102 );
1103 }
1104 assert_eq!(
1105 app.work_state_snapshot()
1106 .expect("Work snapshot after export"),
1107 work_before,
1108 "export must not mutate Work"
1109 );
1110 }
1111
1112 #[test]
1113 fn command_clipboard_reports_ssh_terminal_client_and_failure_honestly() {
1114 let mut harness = ExportHarness::new();
1115 let app = &mut harness.app;
1116 app.clipboard = ClipboardHandler::for_test(true, true);
1117 let ssh = dispatch(app, Some("clipboard"));
1118 assert!(!ssh.is_error, "{:?}", ssh.message);
1119 assert!(
1120 ssh.message
1121 .as_deref()
1122 .unwrap_or_default()
1123 .contains("terminal-client clipboard over SSH")
1124 );
1125 assert!(
1126 ssh.message
1127 .as_deref()
1128 .unwrap_or_default()
1129 .contains("last-copy.md"),
1130 "success must name the backup copy: {:?}",
1131 ssh.message
1132 );
1133
1134 app.clipboard = ClipboardHandler::unavailable_for_test(false);
1135 let failed = dispatch(app, Some("clipboard"));
1136 assert!(failed.is_error);
1137 let message = failed.message.as_deref().unwrap_or_default();
1138 assert!(
1139 message.contains("The full export was written to"),
1140 "{message}"
1141 );
1142 assert!(message.contains("last-copy.md"), "{message}");
1143 assert!(message.contains("/export file <path>"), "{message}");
1144 assert!(!harness.temp.path().join("chat_export.md").exists());
1145 assert!(
1146 harness
1147 .temp
1148 .path()
1149 .join("home/exports/last-copy.md")
1150 .exists()
1151 );
1152 }
1153
1154 #[test]
1155 fn command_file_export_is_workspace_relative_private_and_no_overwrite_by_default() {
1156 let mut harness = ExportHarness::new();
1157 let workspace = harness.temp.path().join("workspace");
1158 std::fs::create_dir_all(&workspace).expect("workspace");
1159 let app = &mut harness.app;
1160 app.workspace = workspace.clone();
1161 app.api_messages_mut().push(Message {
1162 role: Role::User,
1163 content: vec![ContentBlock::Text {
1164 text: "first export".to_string(),
1165 cache_control: None,
1166 }],
1167 });
1168
1169 let first = dispatch(app, Some("file transcript.md"));
1170 assert!(!first.is_error, "{:?}", first.message);
1171 let path = std::fs::canonicalize(&workspace)
1172 .unwrap()
1173 .join("transcript.md");
1174 let original = std::fs::read_to_string(&path).expect("first export");
1175 assert!(original.contains("first export"));
1176 #[cfg(unix)]
1177 {
1178 use std::os::unix::fs::PermissionsExt;
1179 assert_eq!(
1180 std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
1181 0o600
1182 );
1183 }
1184
1185 app.api_messages_mut()[0].content = vec![ContentBlock::Text {
1186 text: "replacement export".to_string(),
1187 cache_control: None,
1188 }];
1189 let refused = dispatch(app, Some("transcript.md"));
1190 assert!(refused.is_error);
1191 assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
1192
1193 let forced = dispatch(app, Some("file --force transcript.md"));
1194 assert!(!forced.is_error, "{:?}", forced.message);
1195 assert!(
1196 std::fs::read_to_string(&path)
1197 .unwrap()
1198 .contains("replacement export")
1199 );
1200 }
1201
1202 #[test]
1203 fn command_file_export_rejects_traversal_missing_parent_and_invalid_usage() {
1204 let mut harness = ExportHarness::new();
1205 let workspace = harness.temp.path().join("workspace");
1206 std::fs::create_dir_all(&workspace).expect("workspace");
1207 let app = &mut harness.app;
1208 app.workspace = workspace.clone();
1209
1210 for arg in [
1211 "file ../outside.md",
1212 "file missing/export.md",
1213 "clipboard extra.md",
1214 "turn clipboard extra.md",
1215 ] {
1216 let result = dispatch(app, Some(arg));
1217 assert!(result.is_error, "{arg}: {:?}", result.message);
1218 }
1219 assert!(!harness.temp.path().join("outside.md").exists());
1220 }
1221
1222 #[cfg(unix)]
1223 #[test]
1224 fn command_file_export_rejects_symlink_leaf_and_ancestor() {
1225 use std::os::unix::fs::symlink;
1226
1227 let mut harness = ExportHarness::new();
1228 let workspace = harness.temp.path().join("workspace");
1229 std::fs::create_dir_all(&workspace).expect("workspace");
1230 let app = &mut harness.app;
1231 app.workspace = workspace.clone();
1232
1233 let real_file = workspace.join("real.md");
1234 std::fs::write(&real_file, "keep").expect("fixture file");
1235 let leaf = workspace.join("leaf.md");
1236 symlink(&real_file, &leaf).expect("leaf symlink");
1237 let leaf_result = dispatch(app, Some(&format!("file --force {}", leaf.display())));
1238 assert!(leaf_result.is_error, "{:?}", leaf_result.message);
1239 assert_eq!(std::fs::read_to_string(&real_file).unwrap(), "keep");
1240
1241 let real_dir = workspace.join("real-dir");
1242 std::fs::create_dir(&real_dir).expect("real dir");
1243 let linked_dir = workspace.join("linked-dir");
1244 symlink(&real_dir, &linked_dir).expect("dir symlink");
1245 let ancestor_result = dispatch(
1246 app,
1247 Some(&format!("file {}", linked_dir.join("out.md").display())),
1248 );
1249 assert!(ancestor_result.is_error, "{:?}", ancestor_result.message);
1250 assert!(!real_dir.join("out.md").exists());
1251 }
1252
1253 #[test]
1254 fn command_turn_export_supports_clipboard_and_safe_legacy_file_destination() {
1255 let mut harness = ExportHarness::new();
1256 let app = &mut harness.app;
1257 app.history.push(HistoryCell::User {
1258 content: "Fix the flaky login test".to_string(),
1259 });
1260 app.history.push(HistoryCell::Assistant {
1261 content: "Fixed the login test.".to_string(),
1262 streaming: false,
1263 });
1264 app.runtime_turn_status = Some("completed".to_string());
1265
1266 let clipboard = dispatch(app, Some("turn"));
1267 assert!(!clipboard.is_error, "{:?}", clipboard.message);
1268 assert!(
1269 app.clipboard
1270 .last_written_text()
1271 .unwrap_or_default()
1272 .contains("# Turn handoff")
1273 );
1274
1275 let path = harness.temp.path().join("handoff.md");
1276 let file = dispatch(app, Some(&format!("turn {}", path.display())));
1277 assert!(!file.is_error, "{:?}", file.message);
1278 assert!(
1279 std::fs::read_to_string(&path)
1280 .unwrap()
1281 .contains("Fix the flaky login test")
1282 );
1283 let refused = dispatch(app, Some(&format!("turn {}", path.display())));
1284 assert!(refused.is_error);
1285 }
1286
1287 #[test]
1288 fn command_export_does_not_create_a_snapshot_repo_for_a_fresh_workspace() {
1289 let mut harness = ExportHarness::new();
1290 let workspace = harness.temp.path().join("workspace");
1291 std::fs::create_dir_all(&workspace).expect("workspace");
1292 let app = &mut harness.app;
1293 app.workspace = workspace.clone();
1294 let before = codewhale_snapshot::snapshot_git_dir(&workspace).expect("snapshot path");
1295 assert!(!before.exists(), "precondition: no side repo yet");
1296
1297 let result = dispatch(app, Some("clipboard"));
1298 assert!(!result.is_error, "{:?}", result.message);
1299
1300 assert!(
1301 !codewhale_snapshot::snapshot_git_dir(&workspace)
1302 .expect("snapshot path")
1303 .exists(),
1304 "export must never create the side repo"
1305 );
1306 }
1307
1308 #[test]
1309 fn adapter_projects_metadata_fallbacks_without_session_or_filename() {
1310 let mut harness = ExportHarness::new();
1311 // No session id: the baseline label is `unsaved`. A workspace whose final
1312 // component is `..` has no `file_name()`, so the label falls back too.
1313 harness.app.current_session_id = None;
1314 harness.app.workspace = harness.temp.path().join("..");
1315
1316 let projection = conversation_projection(&mut harness.app);
1317
1318 assert_eq!(projection.metadata.session_label, "unsaved");
1319 assert_eq!(projection.metadata.workspace_name, "workspace");
1320 assert_eq!(projection.metadata.message_count, 0);
1321 }
1322
1323 #[test]
1324 fn adapter_bounds_restore_points_to_the_latest_hundred_newest_first() {
1325 let mut harness = ExportHarness::new();
1326 let workspace = harness.temp.path().join("workspace");
1327 std::fs::create_dir_all(&workspace).expect("workspace");
1328 harness.app.workspace = workspace.clone();
1329 let repo = SnapshotRepo::open_or_init(&workspace).expect("open side repo");
1330
1331 // 101 recorded points prove the adapter's latest-100 window: exactly one
1332 // entry (the oldest) must be dropped.
1333 for sequence in 0..=100 {
1334 repo.snapshot(&format!("pre-turn:{sequence}: prompt {sequence}"))
1335 .expect("record snapshot");
1336 }
1337
1338 let projection = conversation_projection(&mut harness.app);
1339
1340 let RestorePointProjection::Recorded { snapshots } = &projection.restore_points else {
1341 panic!("recorded restore points expected");
1342 };
1343 assert_eq!(snapshots.len(), 100, "the adapter lists at most 100 points");
1344 assert_eq!(
1345 snapshots.first().map(|snapshot| snapshot.sequence),
1346 Some(Some(100)),
1347 "newest point is first"
1348 );
1349 assert_eq!(
1350 snapshots.last().map(|snapshot| snapshot.sequence),
1351 Some(Some(1)),
1352 "the window stops at the 100th newest point"
1353 );
1354 assert!(
1355 snapshots
1356 .iter()
1357 .all(|snapshot| snapshot.sequence != Some(0)),
1358 "the oldest (101st) point must not cross the window"
1359 );
1360 }
1361
1362 #[test]
1363 fn adapter_rejects_directory_destination_and_parent_not_a_directory() {
1364 let mut harness = ExportHarness::new();
1365 let workspace = canonical_workspace(&harness);
1366 harness.app.workspace = workspace.clone();
1367
1368 let directory = workspace.join("existing-dir");
1369 std::fs::create_dir(&directory).expect("directory target");
1370 let refused = write_file(&mut harness.app, &directory, b"x", true).unwrap_err();
1371 assert!(
1372 refused.contains("refusing to replace a non-regular file"),
1373 "{refused}"
1374 );
1375 assert!(directory.is_dir(), "the directory must be untouched");
1376
1377 let file_parent = workspace.join("not-a-dir");
1378 std::fs::write(&file_parent, "file").expect("file parent");
1379 let parent_error =
1380 write_file(&mut harness.app, &file_parent.join("out.md"), b"x", false).unwrap_err();
1381 assert!(
1382 parent_error.contains("parent is not a directory"),
1383 "{parent_error}"
1384 );
1385 assert!(!file_parent.join("out.md").exists());
1386 }
1387
1388 #[test]
1389 fn adapter_resolves_absolute_paths_and_keeps_the_lexical_fallback() {
1390 let mut harness = ExportHarness::new();
1391 let workspace = harness.temp.path().join("workspace");
1392 std::fs::create_dir_all(&workspace).expect("workspace");
1393 harness.app.workspace = workspace.clone();
1394 let canonical_workspace = std::fs::canonicalize(&workspace).expect("canonical workspace");
1395
1396 // A raw workspace-absolute path rebases onto the resolved workspace.
1397 assert_eq!(
1398 resolve(
1399 &mut harness.app,
1400 &workspace.join("abs.md").to_string_lossy()
1401 )
1402 .expect("raw absolute"),
1403 canonical_workspace.join("abs.md")
1404 );
1405 // A canonicalized workspace-absolute path rebases the same way.
1406 assert_eq!(
1407 resolve(
1408 &mut harness.app,
1409 &canonical_workspace.join("nested/abs.md").to_string_lossy()
1410 )
1411 .expect("canonical absolute"),
1412 canonical_workspace.join("nested/abs.md")
1413 );
1414 // A path outside the workspace stays absolute and is not rebased.
1415 let outside = harness.temp.path().join("outside.md");
1416 assert_eq!(
1417 resolve(&mut harness.app, &outside.to_string_lossy()).expect("outside absolute"),
1418 outside
1419 );
1420
1421 // A workspace that no longer exists falls back to the lexical path instead
1422 // of failing canonicalization.
1423 let missing = harness.temp.path().join("gone");
1424 harness.app.workspace = missing.clone();
1425 assert_eq!(
1426 resolve(&mut harness.app, "relative.md").expect("lexical fallback"),
1427 missing.join("relative.md")
1428 );
1429 }
1430
1431 #[test]
1432 fn command_clipboard_export_includes_session_turn_outcomes_in_last_copy() {
1433 let mut harness = ExportHarness::new();
1434 let app = &mut harness.app;
1435 app.clipboard = ClipboardHandler::for_test(false, false);
1436 app.api_messages = std::sync::Arc::new(vec![
1437 text_message(Role::User, "run the migration"),
1438 Message {
1439 role: Role::Assistant,
1440 content: vec![ContentBlock::ToolUse {
1441 execution_id: None,
1442 id: "call-todo".to_string(),
1443 name: "todo_write".to_string(),
1444 input: serde_json::json!({"items": []}),
1445 caller: None,
1446 thought_signature: None,
1447 }],
1448 },
1449 Message {
1450 role: Role::User,
1451 content: vec![ContentBlock::ToolResult {
1452 execution_id: None,
1453 tool_use_id: "call-todo".to_string(),
1454 content: "updated".to_string(),
1455 is_error: Some(false),
1456 content_blocks: None,
1457 }],
1458 },
1459 ]);
1460 app.session_turn_outcomes = vec![
1461 codewhale_engine::session_manager::SavedTurnOutcome::failed_with_code(
1462 "SSE stream request did not receive response headers after 45s (token sk-live1234567890abcdef)",
1463 Some("llm_network_error"),
1464 3,
1465 ),
1466 codewhale_engine::session_manager::SavedTurnOutcome::failed_with_code(
1467 "SSE stream request did not receive response headers after 45s",
1468 Some("llm_network_error"),
1469 3,
1470 ),
1471 ];
1472
1473 let result = dispatch(app, Some("clipboard"));
1474 assert!(!result.is_error, "{:?}", result.message);
1475
1476 let last_copy = std::fs::read_to_string(harness.temp.path().join("home/exports/last-copy.md"))
1477 .expect("last-copy.md");
1478 let tool_pos = last_copy.find("## 3. tool").expect("last tool message");
1479 let outcome_pos = last_copy
1480 .find("## Turn outcome (failed)")
1481 .expect("failed turn outcome in last-copy.md");
1482 assert!(tool_pos < outcome_pos, "{last_copy}");
1483 assert_eq!(
1484 last_copy.matches("## Turn outcome (failed)").count(),
1485 2,
1486 "{last_copy}"
1487 );
1488 assert!(
1489 last_copy.contains("- Code: `llm_network_error`"),
1490 "{last_copy}"
1491 );
1492 assert!(
1493 last_copy.contains("SSE stream request did not receive response headers after 45s"),
1494 "{last_copy}"
1495 );
1496 assert!(
1497 !last_copy.contains("sk-live1234567890abcdef"),
1498 "secret leaked in last-copy.md: {last_copy}"
1499 );
1500 }
1501
1501 lines RUST