返回 CodeWhale
session_export.rs
根目录 / crates / engine / src / session_export.rs
1 //! Full-fidelity session archive export (`tar.xz`).
2 //!
3 //! The interactive `/export` command renders a sanitized, lossy Markdown
4 //! transcript for humans. This module is the machine-facing counterpart: it
5 //! packs the durable session record into a compressed tar archive so a
6 //! complete session log — system prompt, every user and assistant message
7 //! including thinking blocks, tool calls and tool results, the branch
8 //! journal, approval receipts, and the session's artifacts — can be saved
9 //! with one command and restored later or attached to a bug report.
10 //!
11 //! Archive layout (format version 1):
12 //!
13 //! - `session.json` — the full [`SavedSession`] serialization, the same shape
14 //! as the on-disk session record. Extract it and open it with `/load` in
15 //! the TUI for a full-fidelity restore (system prompt included); note that
16 //! `/resume <file>` imports the conversation transcript only.
17 //! - `container.json` — the portable [`SessionImportContainer`] for
18 //! version-tolerant resume across schema changes.
19 //! - `artifacts/<...>` — the session-owned artifact directory, when present
20 //! and not excluded. Only regular files are archived; symlinks are skipped
21 //! and opened through the existing confined-file reader. Extracted files
22 //! remain separate; `/load` does not install them into the artifact store.
23 //! - `manifest.json` — archive format version, generator version, export
24 //! timestamp, session metadata, and the index of the preceding members.
25 //! Written last so its index covers everything above it.
26 //!
27 //! Contents are intentionally **not sanitized**: this is a full-fidelity log
28 //! for the session owner, unlike `/export`, which redacts secrets for
29 //! sharing. xz compression keeps verbose tool-heavy sessions small enough to
30 //! archive or attach.
31
32 use std::fs;
33 use std::io::{self, Read, Write};
34 use std::path::{Path, PathBuf};
35
36 use chrono::Utc;
37 use liblzma::write::XzEncoder;
38 use serde::Serialize;
39 use tar::Builder;
40
41 use crate::session_manager::{SavedSession, SessionMetadata};
42 use codewhale_runtime::artifacts::{ARTIFACTS_DIR_NAME, is_valid_session_id};
43 use codewhale_runtime::session_tree::SessionImportContainer;
44 use codewhale_util::files::WorkspaceFile;
45
46 /// Layout version of the exported archive. Bump when members change.
47 pub const SESSION_ARCHIVE_FORMAT_VERSION: u32 = 1;
48
49 /// Default xz compression preset (0–9), mirroring `xz -6`.
50 pub const DEFAULT_XZ_COMPRESSION_LEVEL: u32 = 6;
51
52 const SESSION_RECORD_MEMBER: &str = "session.json";
53 const SESSION_CONTAINER_MEMBER: &str = "container.json";
54 const ARCHIVE_MANIFEST_MEMBER: &str = "manifest.json";
55 const MAX_ARTIFACT_DEPTH: usize = 64;
56 const MAX_ARTIFACT_ENTRIES: usize = 100_000;
57
58 /// Options for [`write_session_archive`].
59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
60 pub struct SessionArchiveOptions {
61 /// Include the session-owned `artifacts/` directory when it exists.
62 pub include_artifacts: bool,
63 /// xz compression preset, 0 (fastest) through 9 (smallest).
64 pub compression_level: u32,
65 /// Replace the destination directory entry. Otherwise fail if it exists.
66 pub overwrite: bool,
67 }
68
69 impl Default for SessionArchiveOptions {
70 fn default() -> Self {
71 Self {
72 include_artifacts: true,
73 compression_level: DEFAULT_XZ_COMPRESSION_LEVEL,
74 overwrite: false,
75 }
76 }
77 }
78
79 /// One archive member reported in the manifest and [`SessionArchiveSummary`].
80 #[derive(Debug, Clone, Serialize, PartialEq, Eq)]
81 pub struct SessionArchiveMember {
82 /// Member path inside the archive, `/`-separated.
83 pub name: String,
84 /// Uncompressed member size in bytes.
85 pub bytes: u64,
86 }
87
88 /// Outcome of a successful [`write_session_archive`] call.
89 #[derive(Debug, Clone, Serialize)]
90 pub struct SessionArchiveSummary {
91 /// Path the `.tar.xz` archive was written to.
92 pub output: PathBuf,
93 /// Exported session id.
94 pub session_id: String,
95 /// [`SESSION_ARCHIVE_FORMAT_VERSION`] used for this archive.
96 pub archive_format_version: u32,
97 /// xz preset the archive was written with.
98 pub compression_level: u32,
99 /// Whether `artifacts/` members were included.
100 pub includes_artifacts: bool,
101 /// Member index in write order. `manifest.json` itself is excluded: it
102 /// is written last and indexes everything before it.
103 pub members: Vec<SessionArchiveMember>,
104 }
105
106 impl SessionArchiveSummary {
107 /// Sum of uncompressed member sizes.
108 pub fn total_member_bytes(&self) -> u64 {
109 self.members.iter().map(|member| member.bytes).sum()
110 }
111
112 /// Compressed archive size in bytes, or 0 if the file is unreadable.
113 pub fn compressed_bytes(&self) -> u64 {
114 fs::metadata(&self.output).map_or(0, |meta| meta.len())
115 }
116 }
117
118 #[derive(Serialize)]
119 struct ArchiveManifest {
120 archive_format_version: u32,
121 generator: &'static str,
122 generator_version: &'static str,
123 exported_at: String,
124 session: SessionMetadata,
125 members: Vec<SessionArchiveMember>,
126 }
127
128 /// Write one session as a full-fidelity `.tar.xz` archive.
129 ///
130 /// `session` is typically loaded with
131 /// [`SessionManager::load_session_snapshot`](crate::session_manager::SessionManager::load_session_snapshot)
132 /// so the archive reflects the durable record without applying resume-time
133 /// repair. `sessions_dir` is the trusted session store root; pass `None` (or clear
134 /// [`SessionArchiveOptions::include_artifacts`]) to export the transcript
135 /// only.
136 ///
137 /// The archive is streamed to a sibling temporary file and renamed into
138 /// place, so a failed export never leaves a truncated archive at `output`.
139 /// An existing `output` is replaced only when `options.overwrite` is set.
140 pub fn write_session_archive(
141 session: &SavedSession,
142 sessions_dir: Option<&Path>,
143 output: &Path,
144 options: SessionArchiveOptions,
145 ) -> io::Result<SessionArchiveSummary> {
146 if !is_valid_session_id(&session.metadata.id) {
147 return Err(io::Error::new(
148 io::ErrorKind::InvalidInput,
149 "invalid session id",
150 ));
151 }
152 if options.compression_level > 9 {
153 return Err(io::Error::new(
154 io::ErrorKind::InvalidInput,
155 format!(
156 "xz compression level {} is out of range 0-9",
157 options.compression_level
158 ),
159 ));
160 }
161 let session_json = session_json(session)?;
162 let container_json = container_json(session, sessions_dir)?;
163 let parent = output
164 .parent()
165 .filter(|parent| !parent.as_os_str().is_empty())
166 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
167 fs::create_dir_all(&parent)?;
168 let sessions_dir = sessions_dir.map(Path::canonicalize).transpose()?;
169 if let Some(root) = &sessions_dir
170 && parent.canonicalize()?.starts_with(root)
171 {
172 return Err(io::Error::new(
173 io::ErrorKind::InvalidInput,
174 "export output must be outside the session store",
175 ));
176 }
177 let artifact_files = match (options.include_artifacts, sessions_dir.as_deref()) {
178 (true, Some(root)) => match session_artifacts_dir(root, &session.metadata.id)? {
179 Some(dir) => collect_artifact_files(root, &dir)?,
180 None => Vec::new(),
181 },
182 _ => Vec::new(),
183 };
184 let mut temp = tempfile::Builder::new()
185 .prefix(".codewhale-session-export-")
186 .tempfile_in(&parent)?;
187
188 let mut summary = SessionArchiveSummary {
189 output: output.to_path_buf(),
190 session_id: session.metadata.id.clone(),
191 archive_format_version: SESSION_ARCHIVE_FORMAT_VERSION,
192 compression_level: options.compression_level,
193 includes_artifacts: !artifact_files.is_empty(),
194 members: Vec::new(),
195 };
196
197 {
198 let file = temp.as_file_mut();
199 let mut tar = Builder::new(XzEncoder::new(file, options.compression_level));
200 append_member(
201 &mut tar,
202 SESSION_RECORD_MEMBER,
203 MemberContents::Bytes(session_json.as_bytes()),
204 &mut summary.members,
205 )?;
206 append_member(
207 &mut tar,
208 SESSION_CONTAINER_MEMBER,
209 MemberContents::Bytes(container_json.as_bytes()),
210 &mut summary.members,
211 )?;
212 for (name, relative) in &artifact_files {
213 let root = sessions_dir
214 .as_deref()
215 .expect("artifact collection needs a store");
216 // Parent directories and the leaf are opened without following links.
217 // Stream this handle directly; never reopen a validated path.
218 let mut file = WorkspaceFile::open_resolved_root(root, relative, false)?.open_file()?;
219 append_member(
220 &mut tar,
221 name,
222 MemberContents::File(&mut file),
223 &mut summary.members,
224 )?;
225 }
226 let manifest_json = serde_json::to_string_pretty(&ArchiveManifest {
227 archive_format_version: SESSION_ARCHIVE_FORMAT_VERSION,
228 generator: env!("CARGO_PKG_NAME"),
229 generator_version: env!("CARGO_PKG_VERSION"),
230 exported_at: Utc::now().to_rfc3339(),
231 session: session.metadata.clone(),
232 members: summary.members.clone(),
233 })
234 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
235 append_member(
236 &mut tar,
237 ARCHIVE_MANIFEST_MEMBER,
238 MemberContents::Bytes(manifest_json.as_bytes()),
239 &mut Vec::new(),
240 )?;
241 let encoder = tar.into_inner()?;
242 let file = encoder.finish()?;
243 file.flush()?;
244 file.sync_all()?;
245 }
246 if options.overwrite {
247 temp.persist(output)
248 } else {
249 temp.persist_noclobber(output)
250 }
251 .map_err(|error| {
252 if error.error.kind() == io::ErrorKind::AlreadyExists {
253 io::Error::new(
254 io::ErrorKind::AlreadyExists,
255 format!(
256 "{} already exists; pass --force to overwrite it",
257 output.display()
258 ),
259 )
260 } else {
261 error.error
262 }
263 })?;
264
265 Ok(summary)
266 }
267
268 /// Directory holding this session's artifacts, when it exists. `session_id`
269 /// is re-checked against path traversal here because this helper is also the
270 /// boundary for callers that build the path from user-supplied ids.
271 pub fn session_artifacts_dir(sessions_dir: &Path, session_id: &str) -> io::Result<Option<PathBuf>> {
272 if !is_valid_session_id(session_id) {
273 return Err(io::Error::new(
274 io::ErrorKind::InvalidInput,
275 "invalid session id",
276 ));
277 }
278 let relative = Path::new(session_id).join(ARTIFACTS_DIR_NAME);
279 // Opening a confined file reference pins and validates its parent directory;
280 // this checks the artifact root without creating or opening the dummy leaf.
281 match WorkspaceFile::open_resolved_root(
282 sessions_dir,
283 &relative.join(".export-root-check"),
284 false,
285 ) {
286 Ok(_) => Ok(Some(sessions_dir.join(relative))),
287 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
288 Err(error) => Err(error),
289 }
290 }
291
292 pub fn export_recovery_hint(session_id: &str) -> String {
293 format!(
294 "To move it to a provider you still have, run `codewhale --provider <name> resume {session_id}`. To keep its history without that provider, run `codewhale sessions export {session_id}`."
295 )
296 }
297
298 /// Default archive file name for a session:
299 /// `codewhale-session-<short-id>.tar.xz`.
300 pub fn default_archive_file_name(metadata: &SessionMetadata) -> String {
301 format!(
302 "codewhale-session-{}.tar.xz",
303 crate::session_manager::truncate_id(&metadata.id)
304 )
305 }
306
307 fn session_json(session: &SavedSession) -> io::Result<String> {
308 serde_json::to_string_pretty(session)
309 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
310 }
311
312 /// The portable journal container. With a session store it also carries the
313 /// entries bounded saves moved into the journal archive (#6842), so an export
314 /// holds the full history, not only what the document still keeps.
315 fn container_json(session: &SavedSession, sessions_dir: Option<&Path>) -> io::Result<String> {
316 let mut container: SessionImportContainer = session.export_container("session-archive");
317 if let Some(root) = sessions_dir {
318 let archived = crate::session_manager::load_journal_archive(root, &session.metadata.id)?;
319 if !archived.is_empty() {
320 let present: std::collections::HashSet<String> =
321 container.entries.iter().map(|e| e.id.clone()).collect();
322 let mut entries: Vec<_> = archived
323 .into_iter()
324 .filter(|e| !present.contains(&e.id))
325 .collect();
326 entries.append(&mut container.entries);
327 container.entries = entries;
328 }
329 }
330 serde_json::to_string_pretty(&container)
331 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
332 }
333
334 /// Collect regular artifact files as `(archive member name, source path)`,
335 /// sorted by member name for stable ordering. Symlinks and other
336 /// non-regular entries are skipped so an export cannot reach outside the
337 /// session directory through a link.
338 fn collect_artifact_files(
339 sessions_dir: &Path,
340 artifacts_dir: &Path,
341 ) -> io::Result<Vec<(String, PathBuf)>> {
342 let mut files = Vec::new();
343 let mut entries = 0;
344 collect_artifact_files_recursive(
345 sessions_dir,
346 artifacts_dir,
347 ARTIFACTS_DIR_NAME,
348 0,
349 &mut entries,
350 &mut files,
351 )?;
352 files.sort_by(|left, right| left.0.cmp(&right.0));
353 Ok(files)
354 }
355
356 fn collect_artifact_files_recursive(
357 sessions_dir: &Path,
358 dir: &Path,
359 prefix: &str,
360 depth: usize,
361 entries: &mut usize,
362 files: &mut Vec<(String, PathBuf)>,
363 ) -> io::Result<()> {
364 if depth > MAX_ARTIFACT_DEPTH {
365 return Err(io::Error::new(
366 io::ErrorKind::InvalidData,
367 "artifact tree exceeds export depth limit",
368 ));
369 }
370 for entry in fs::read_dir(dir)? {
371 let entry = entry?;
372 *entries += 1;
373 if *entries > MAX_ARTIFACT_ENTRIES {
374 return Err(io::Error::new(
375 io::ErrorKind::InvalidData,
376 "artifact tree exceeds export entry limit",
377 ));
378 }
379 let file_type = entry.file_type()?;
380 if file_type.is_symlink() {
381 continue;
382 }
383 let child = entry.file_name();
384 let child = child
385 .to_str()
386 .filter(|name| !name.contains(['\\', ':']))
387 .ok_or_else(|| {
388 io::Error::new(
389 io::ErrorKind::InvalidData,
390 "artifact name is not portable UTF-8",
391 )
392 })?;
393 let member = format!("{prefix}/{child}");
394 let path = entry.path();
395 let relative = path.strip_prefix(sessions_dir).map_err(io::Error::other)?;
396 if file_type.is_dir() {
397 // Reject substituted parent directories before descending. The file
398 // read repeats confinement checks, so directory races cannot leak bytes.
399 WorkspaceFile::open_resolved_root(
400 sessions_dir,
401 &relative.join(".export-root-check"),
402 false,
403 )?;
404 collect_artifact_files_recursive(
405 sessions_dir,
406 &path,
407 &member,
408 depth + 1,
409 entries,
410 files,
411 )?;
412 } else if file_type.is_file() {
413 files.push((member, relative.to_path_buf()));
414 }
415 }
416 Ok(())
417 }
418
419 fn archive_header(size: u64) -> tar::Header {
420 let mut header = tar::Header::new_gnu();
421 header.set_size(size);
422 header.set_mode(0o600);
423 header.set_mtime(Utc::now().timestamp().max(0) as u64);
424 header.set_cksum();
425 header
426 }
427
428 /// Payload for one archive member: in-memory bytes or a filesystem file
429 /// streamed straight into the tar.
430 enum MemberContents<'a> {
431 Bytes(&'a [u8]),
432 File(&'a mut fs::File),
433 }
434
435 /// Append exactly `expected` bytes of `reader` under `name`. The bounded read
436 /// keeps the tar header and the member payload consistent when the source
437 /// file changes size mid-export: growth is capped at the snapshot size
438 /// (valid archive, prefix content), while shrinkage — which would otherwise
439 /// silently shift every following header and corrupt the archive — fails the
440 /// export instead.
441 fn append_sized<W: Write, R: Read>(
442 tar: &mut Builder<W>,
443 header: &mut tar::Header,
444 name: &str,
445 reader: R,
446 expected: u64,
447 ) -> io::Result<()> {
448 let mut limited = reader.take(expected);
449 tar.append_data(header, name, &mut limited)?;
450 if limited.limit() != 0 {
451 return Err(io::Error::new(
452 io::ErrorKind::UnexpectedEof,
453 format!(
454 "member {name} ended before its recorded size of {expected} bytes; the source changed during export"
455 ),
456 ));
457 }
458 Ok(())
459 }
460
461 fn append_member<W: Write>(
462 tar: &mut Builder<W>,
463 name: &str,
464 contents: MemberContents<'_>,
465 members: &mut Vec<SessionArchiveMember>,
466 ) -> io::Result<()> {
467 match contents {
468 MemberContents::Bytes(bytes) => {
469 let mut header = archive_header(bytes.len() as u64);
470 tar.append_data(&mut header, name, bytes)?;
471 members.push(SessionArchiveMember {
472 name: name.to_string(),
473 bytes: bytes.len() as u64,
474 });
475 }
476 MemberContents::File(file) => {
477 let size = file.metadata()?.len();
478 let mut header = archive_header(size);
479 append_sized(tar, &mut header, name, file, size)?;
480 members.push(SessionArchiveMember {
481 name: name.to_string(),
482 bytes: size,
483 });
484 }
485 }
486 Ok(())
487 }
488
489 #[cfg(test)]
490 mod tests {
491 use super::*;
492 use crate::session_manager::create_saved_session;
493 use codewhale_models::{ContentBlock, Message, Role};
494 use codewhale_runtime::session_tree::SessionJournal;
495 use std::io::Read;
496
497 fn fixture_session() -> SavedSession {
498 let messages = vec![
499 Message {
500 role: Role::User,
501 content: vec![ContentBlock::Text {
502 text: "list the files in src".to_string(),
503 cache_control: None,
504 }],
505 },
506 Message {
507 role: Role::Assistant,
508 content: vec![
509 ContentBlock::thinking("I should run ls first"),
510 ContentBlock::ToolUse {
511 execution_id: None,
512 id: "toolu_01".to_string(),
513 name: "shell".to_string(),
514 input: serde_json::json!({ "command": "ls src" }),
515 caller: None,
516 thought_signature: None,
517 },
518 ],
519 },
520 Message {
521 role: Role::User,
522 content: vec![ContentBlock::ToolResult {
523 execution_id: None,
524 tool_use_id: "toolu_01".to_string(),
525 content: "main.rs\nlib.rs".to_string(),
526 is_error: None,
527 content_blocks: None,
528 }],
529 },
530 ];
531 let mut session = create_saved_session(
532 &messages,
533 "test-model",
534 Path::new("/tmp/archive-fixture"),
535 128,
536 None,
537 );
538 session.system_prompt = Some("You are a careful coding agent.".to_string());
539 session.journal = Some(SessionJournal::from_messages(messages, 0));
540 session
541 }
542
543 fn read_archive_members(path: &Path) -> Vec<(String, Vec<u8>)> {
544 let file = fs::File::open(path).expect("archive opens");
545 let mut archive = tar::Archive::new(liblzma::read::XzDecoder::new(file));
546 archive
547 .entries()
548 .expect("archive entries")
549 .map(|entry| {
550 let mut entry = entry.expect("entry");
551 let name = entry.path().expect("path").to_string_lossy().into_owned();
552 let mut bytes = Vec::new();
553 entry.read_to_end(&mut bytes).expect("member bytes");
554 (name, bytes)
555 })
556 .collect()
557 }
558
559 #[test]
560 fn forkguard_session_archive_export_roundtrips_full_context() {
561 let session = fixture_session();
562 let dir = tempfile::tempdir().expect("tempdir");
563 let output = dir.path().join("session.tar.xz");
564
565 let summary =
566 write_session_archive(&session, None, &output, SessionArchiveOptions::default())
567 .expect("archive export");
568
569 assert_eq!(summary.session_id, session.metadata.id);
570 let mut members = read_archive_members(&output);
571 members.sort_by(|left, right| left.0.cmp(&right.0));
572 let names: Vec<&str> = members.iter().map(|(name, _)| name.as_str()).collect();
573 assert_eq!(
574 names,
575 vec!["container.json", "manifest.json", "session.json"]
576 );
577
578 // The raw session record restores the complete context: system
579 // prompt, thinking, tool call, and tool result.
580 let (_, session_bytes) = members
581 .iter()
582 .find(|(name, _)| name == SESSION_RECORD_MEMBER)
583 .expect("session.json member");
584 let restored: SavedSession =
585 serde_json::from_slice(session_bytes).expect("session.json parses");
586 assert_eq!(
587 restored.system_prompt.as_deref(),
588 Some("You are a careful coding agent.")
589 );
590 let mut saw_tool_use = false;
591 let mut saw_tool_result = false;
592 let mut saw_thinking = false;
593 for message in &restored.messages {
594 for block in &message.content {
595 match block {
596 ContentBlock::ToolUse { id, .. } => {
597 saw_tool_use = true;
598 assert_eq!(id, "toolu_01");
599 }
600 ContentBlock::ToolResult { tool_use_id, .. } => {
601 saw_tool_result = true;
602 assert_eq!(tool_use_id, "toolu_01");
603 }
604 ContentBlock::Thinking { .. } => saw_thinking = true,
605 _ => {}
606 }
607 }
608 }
609 assert!(saw_tool_use && saw_tool_result && saw_thinking);
610
611 // The portable container feeds the exact import path `/resume` uses
612 // for exported session JSON.
613 let (_, container_bytes) = members
614 .iter()
615 .find(|(name, _)| name == SESSION_CONTAINER_MEMBER)
616 .expect("container.json member");
617 let container = SessionImportContainer::from_json(
618 std::str::from_utf8(container_bytes).expect("container utf8"),
619 )
620 .expect("container parses");
621 let imported = SavedSession::import_foreign(
622 container,
623 PathBuf::from("/tmp/archive-fixture"),
624 "test-model".to_string(),
625 )
626 .expect("container imports");
627 assert!(
628 imported
629 .messages
630 .iter()
631 .any(|message| message.content.iter().any(
632 |block| matches!(block, ContentBlock::ToolUse { id, .. } if id == "toolu_01")
633 )),
634 "imported session keeps the tool call"
635 );
636 let manifest: serde_json::Value = serde_json::from_slice(
637 &members
638 .iter()
639 .find(|(name, _)| name == ARCHIVE_MANIFEST_MEMBER)
640 .expect("manifest member")
641 .1,
642 )
643 .expect("manifest parses");
644 assert_eq!(
645 manifest["archive_format_version"],
646 SESSION_ARCHIVE_FORMAT_VERSION
647 );
648 assert_eq!(manifest["session"]["id"], session.metadata.id);
649 }
650
651 #[test]
652 fn forkguard_session_archive_includes_artifacts_and_respects_skip() {
653 let session = fixture_session();
654 let dir = tempfile::tempdir().expect("tempdir");
655 let sessions_dir = dir.path().join("sessions");
656 let artifacts_dir = sessions_dir
657 .join(&session.metadata.id)
658 .join(ARTIFACTS_DIR_NAME);
659 fs::create_dir_all(&artifacts_dir).expect("artifacts dir");
660 fs::write(artifacts_dir.join("art_call-1.txt"), b"artifact body").expect("artifact");
661 assert!(
662 session_artifacts_dir(&sessions_dir, &session.metadata.id)
663 .unwrap()
664 .is_some(),
665 "artifacts dir is discovered for a valid session id"
666 );
667 assert!(
668 session_artifacts_dir(&sessions_dir, "../escape").is_err(),
669 "path traversal ids never resolve to an artifacts dir"
670 );
671
672 let with_artifacts = write_session_archive(
673 &session,
674 Some(&sessions_dir),
675 &dir.path().join("full.tar.xz"),
676 SessionArchiveOptions::default(),
677 )
678 .expect("archive with artifacts");
679 assert!(with_artifacts.includes_artifacts);
680 let names: Vec<&str> = with_artifacts
681 .members
682 .iter()
683 .map(|member| member.name.as_str())
684 .collect();
685 assert_eq!(
686 names,
687 vec!["session.json", "container.json", "artifacts/art_call-1.txt"]
688 );
689 let members = read_archive_members(&dir.path().join("full.tar.xz"));
690 let (_, artifact_bytes) = members
691 .iter()
692 .find(|(name, _)| name == "artifacts/art_call-1.txt")
693 .expect("artifact member");
694 assert_eq!(artifact_bytes, b"artifact body");
695
696 let transcript_only = write_session_archive(
697 &session,
698 Some(&sessions_dir),
699 &dir.path().join("lean.tar.xz"),
700 SessionArchiveOptions {
701 include_artifacts: false,
702 ..SessionArchiveOptions::default()
703 },
704 )
705 .expect("archive without artifacts");
706 assert!(!transcript_only.includes_artifacts);
707 assert!(
708 !transcript_only
709 .members
710 .iter()
711 .any(|member| member.name.starts_with(ARTIFACTS_DIR_NAME))
712 );
713 }
714
715 #[test]
716 fn forkguard_session_archive_rejects_artifact_shorter_than_recorded_size() {
717 // A member whose source shrank between stat and copy must fail the
718 // export instead of being zero-padded into a silently shifted
719 // archive (the growth direction is capped to the snapshot size).
720 let mut tar = Builder::new(Vec::new());
721 let mut header = archive_header(16);
722 let error = append_sized(
723 &mut tar,
724 &mut header,
725 "artifacts/shrinking.bin",
726 &b"only-nine"[..],
727 16,
728 )
729 .expect_err("short member must fail the export");
730 assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
731
732 let mut tar = Builder::new(Vec::new());
733 let mut header = archive_header(9);
734 append_sized(
735 &mut tar,
736 &mut header,
737 "artifacts/stable.bin",
738 &b"only-nine"[..],
739 9,
740 )
741 .expect("exact-size member succeeds");
742 }
743
744 #[test]
745 fn session_archive_rejects_out_of_range_compression_level() {
746 let session = fixture_session();
747 let dir = tempfile::tempdir().expect("tempdir");
748 let error = write_session_archive(
749 &session,
750 None,
751 &dir.path().join("out.tar.xz"),
752 SessionArchiveOptions {
753 compression_level: 10,
754 ..SessionArchiveOptions::default()
755 },
756 )
757 .expect_err("level 10 must be rejected");
758 assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
759 }
760
761 #[test]
762 fn session_archive_replaces_existing_output_atomically() {
763 let session = fixture_session();
764 let dir = tempfile::tempdir().expect("tempdir");
765 let output = dir.path().join("out.tar.xz");
766 write_session_archive(&session, None, &output, SessionArchiveOptions::default())
767 .expect("first export");
768 write_session_archive(
769 &session,
770 None,
771 &output,
772 SessionArchiveOptions {
773 overwrite: true,
774 ..SessionArchiveOptions::default()
775 },
776 )
777 .expect("second export replaces");
778 let members = read_archive_members(&output);
779 assert_eq!(members.len(), 3);
780 assert!(default_archive_file_name(&session.metadata).ends_with(".tar.xz"));
781 }
782
783 #[test]
784 fn session_archive_preserves_existing_output_without_force() {
785 let session = fixture_session();
786 let dir = tempfile::tempdir().unwrap();
787 let output = dir.path().join("out.tar.xz");
788 fs::write(&output, b"existing archive").unwrap();
789 let error =
790 write_session_archive(&session, None, &output, SessionArchiveOptions::default())
791 .unwrap_err();
792 assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
793 assert_eq!(fs::read(&output).unwrap(), b"existing archive");
794 assert_eq!(
795 fs::read_dir(dir.path()).unwrap().count(),
796 1,
797 "temporary file cleaned up"
798 );
799 }
800
801 #[test]
802 fn session_archive_rejects_output_inside_store_even_with_force() {
803 let session = fixture_session();
804 let dir = tempfile::tempdir().unwrap();
805 let output = dir.path().join(format!("{}.json", session.metadata.id));
806 fs::write(&output, b"durable session").unwrap();
807 let error = write_session_archive(
808 &session,
809 Some(dir.path()),
810 &output,
811 SessionArchiveOptions {
812 overwrite: true,
813 ..SessionArchiveOptions::default()
814 },
815 )
816 .unwrap_err();
817 assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
818 assert_eq!(fs::read(&output).unwrap(), b"durable session");
819 }
820
821 #[test]
822 fn session_archive_prefix_snapshot_keeps_unfinished_tool_call_and_journal() {
823 use crate::session_manager::SessionManager;
824 let mut session = fixture_session();
825 session.messages.pop();
826 session.journal = Some(SessionJournal::from_messages(session.messages.clone(), 0));
827 let dir = tempfile::tempdir().unwrap();
828 let manager = SessionManager::new(dir.path().join("sessions")).unwrap();
829 manager.save_session(&session).unwrap();
830 let durable_path = manager
831 .sessions_dir()
832 .join(format!("{}.json", session.metadata.id));
833 let before = fs::read(&durable_path).unwrap();
834 let id = manager
835 .resolve_session_id_prefix(&session.metadata.id[..8])
836 .unwrap();
837 let snapshot = manager.load_session_snapshot(&id).unwrap();
838 let output = dir.path().join("out.tar.xz");
839 write_session_archive(
840 &snapshot,
841 Some(manager.sessions_dir()),
842 &output,
843 SessionArchiveOptions::default(),
844 )
845 .unwrap();
846 let members = read_archive_members(&output);
847 let bytes = &members
848 .iter()
849 .find(|(name, _)| name == SESSION_RECORD_MEMBER)
850 .unwrap()
851 .1;
852 let restored: SavedSession = serde_json::from_slice(bytes).unwrap();
853 assert_eq!(restored.messages, session.messages);
854 assert_eq!(
855 serde_json::to_value(restored.journal).unwrap(),
856 serde_json::to_value(session.journal).unwrap()
857 );
858 assert_eq!(
859 fs::read(durable_path).unwrap(),
860 before,
861 "export must not rewrite the durable record"
862 );
863 }
864
865 #[test]
866 fn session_archive_hard_link_fails_without_replacing_output() {
867 let session = fixture_session();
868 let dir = tempfile::tempdir().unwrap();
869 let sessions = dir.path().join("sessions");
870 let artifacts = sessions.join(&session.metadata.id).join(ARTIFACTS_DIR_NAME);
871 fs::create_dir_all(&artifacts).unwrap();
872 let outside = dir.path().join("outside.txt");
873 fs::write(&outside, b"outside content").unwrap();
874 fs::hard_link(&outside, artifacts.join("linked.txt")).unwrap();
875 let output = dir.path().join("out.tar.xz");
876 fs::write(&output, b"original").unwrap();
877 assert!(
878 write_session_archive(
879 &session,
880 Some(&sessions),
881 &output,
882 SessionArchiveOptions {
883 overwrite: true,
884 ..SessionArchiveOptions::default()
885 }
886 )
887 .is_err()
888 );
889 assert_eq!(fs::read(output).unwrap(), b"original");
890 }
891
892 #[cfg(unix)]
893 #[test]
894 fn session_archive_rejects_linked_roots_and_skips_linked_members() {
895 use std::os::unix::fs::symlink;
896 let session = fixture_session();
897 let dir = tempfile::tempdir().unwrap();
898 let sessions = dir.path().join("sessions");
899 let artifacts = sessions.join(&session.metadata.id).join(ARTIFACTS_DIR_NAME);
900 let outside = dir.path().join("outside");
901 fs::create_dir_all(&outside).unwrap();
902 fs::write(outside.join("secret.txt"), b"outside content").unwrap();
903 fs::create_dir_all(artifacts.parent().unwrap()).unwrap();
904 symlink(&outside, &artifacts).unwrap();
905 let output = dir.path().join("out.tar.xz");
906 assert!(
907 write_session_archive(
908 &session,
909 Some(&sessions),
910 &output,
911 SessionArchiveOptions::default()
912 )
913 .is_err()
914 );
915 assert!(!output.exists());
916 fs::remove_file(&artifacts).unwrap();
917 fs::create_dir(&artifacts).unwrap();
918 symlink(&outside, artifacts.join("directory-link")).unwrap();
919 symlink(outside.join("secret.txt"), artifacts.join("file-link")).unwrap();
920 fs::write(artifacts.join("regular.txt"), b"owned content").unwrap();
921 let summary = write_session_archive(
922 &session,
923 Some(&sessions),
924 &output,
925 SessionArchiveOptions::default(),
926 )
927 .unwrap();
928 assert_eq!(summary.members.len(), 3);
929 assert_eq!(summary.members[2].name, "artifacts/regular.txt");
930 assert!(
931 !read_archive_members(&output)
932 .iter()
933 .any(|(_, bytes)| bytes == b"outside content")
934 );
935 }
936
937 #[cfg(unix)]
938 #[test]
939 fn session_archive_dangling_output_link_does_not_bypass_no_clobber() {
940 use std::os::unix::fs::symlink;
941 let session = fixture_session();
942 let dir = tempfile::tempdir().unwrap();
943 let output = dir.path().join("out.tar.xz");
944 let target = dir.path().join("missing");
945 symlink(&target, &output).unwrap();
946 assert!(!output.exists());
947 let error =
948 write_session_archive(&session, None, &output, SessionArchiveOptions::default())
949 .unwrap_err();
950 assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
951 assert_eq!(fs::read_link(&output).unwrap(), target);
952 write_session_archive(
953 &session,
954 None,
955 &output,
956 SessionArchiveOptions {
957 overwrite: true,
958 ..SessionArchiveOptions::default()
959 },
960 )
961 .unwrap();
962 assert!(!target.exists());
963 assert_eq!(read_archive_members(&output).len(), 3);
964 }
965
966 // APFS rejects invalid UTF-8 at file creation; Linux filesystems admit it.
967 #[cfg(target_os = "linux")]
968 #[test]
969 fn session_archive_rejects_non_utf8_names_without_lossy_rename() {
970 use std::os::unix::ffi::OsStringExt;
971 let session = fixture_session();
972 let dir = tempfile::tempdir().unwrap();
973 let sessions = dir.path().join("sessions");
974 let artifacts = sessions.join(&session.metadata.id).join(ARTIFACTS_DIR_NAME);
975 fs::create_dir_all(&artifacts).unwrap();
976 fs::write(
977 artifacts.join(std::ffi::OsString::from_vec(vec![0xff])),
978 b"owned content",
979 )
980 .unwrap();
981 let output = dir.path().join("out.tar.xz");
982 let error = write_session_archive(
983 &session,
984 Some(&sessions),
985 &output,
986 SessionArchiveOptions::default(),
987 )
988 .unwrap_err();
989 assert_eq!(error.kind(), io::ErrorKind::InvalidData);
990 assert!(!output.exists());
991 }
992
993 #[cfg(unix)]
994 #[test]
995 fn session_archive_rejects_nonportable_member_names() {
996 let session = fixture_session();
997 let dir = tempfile::tempdir().unwrap();
998 let sessions = dir.path().join("sessions");
999 let artifacts = sessions.join(&session.metadata.id).join(ARTIFACTS_DIR_NAME);
1000 fs::create_dir_all(&artifacts).unwrap();
1001 fs::write(artifacts.join("report:private"), b"owned content").unwrap();
1002 let output = dir.path().join("out.tar.xz");
1003 let error = write_session_archive(
1004 &session,
1005 Some(&sessions),
1006 &output,
1007 SessionArchiveOptions::default(),
1008 )
1009 .unwrap_err();
1010 assert_eq!(error.kind(), io::ErrorKind::InvalidData);
1011 assert!(!output.exists());
1012 }
1013
1014 #[cfg(unix)]
1015 #[test]
1016 fn session_archive_and_extracted_members_are_owner_only() {
1017 use std::os::unix::fs::PermissionsExt;
1018 let session = fixture_session();
1019 let dir = tempfile::tempdir().unwrap();
1020 let output = dir.path().join("out.tar.xz");
1021 write_session_archive(&session, None, &output, SessionArchiveOptions::default()).unwrap();
1022 assert_eq!(
1023 fs::metadata(&output).unwrap().permissions().mode() & 0o777,
1024 0o600
1025 );
1026 let mut archive = tar::Archive::new(liblzma::read::XzDecoder::new(
1027 fs::File::open(&output).unwrap(),
1028 ));
1029 let extracted = dir.path().join("extracted");
1030 archive.unpack(&extracted).unwrap();
1031 for name in [
1032 SESSION_RECORD_MEMBER,
1033 SESSION_CONTAINER_MEMBER,
1034 ARCHIVE_MANIFEST_MEMBER,
1035 ] {
1036 assert_eq!(
1037 fs::metadata(extracted.join(name))
1038 .unwrap()
1039 .permissions()
1040 .mode()
1041 & 0o777,
1042 0o600
1043 );
1044 }
1045 }
1046
1047 /// #6842: entries a bounded save archived travel with the export.
1048 #[test]
1049 fn container_includes_journal_archive_entries() {
1050 let dir = tempfile::tempdir().expect("tempdir");
1051 let sessions = dir.path().join("sessions");
1052 let session = fixture_session();
1053 let journal = session.journal.clone().expect("journal");
1054 let root = journal.entries[0].id.clone();
1055 let mut archived = journal.clone();
1056 archived.branch_to(&root).expect("branch");
1057 let extra = archived.append_message(Message {
1058 role: Role::User,
1059 content: vec![ContentBlock::Text {
1060 text: "archived alternative".to_string(),
1061 cache_control: None,
1062 }],
1063 });
1064 let entry = archived.entries.last().expect("entry").clone();
1065 assert_eq!(entry.id, extra);
1066 let archive_dir = sessions.join(crate::session_manager::JOURNAL_ARCHIVE_DIR);
1067 fs::create_dir_all(&archive_dir).expect("archive dir");
1068 let path = archive_dir.join(format!("{}.jsonl", session.metadata.id));
1069 fs::write(
1070 &path,
1071 format!("{}\n", serde_json::to_string(&entry).unwrap()),
1072 )
1073 .unwrap();
1074 #[cfg(unix)]
1075 {
1076 use std::os::unix::fs::PermissionsExt as _;
1077 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
1078 }
1079
1080 let without: SessionImportContainer =
1081 serde_json::from_str(&container_json(&session, None).unwrap()).unwrap();
1082 let with: SessionImportContainer =
1083 serde_json::from_str(&container_json(&session, Some(&sessions)).unwrap()).unwrap();
1084 assert_eq!(with.entries.len(), without.entries.len() + 1);
1085 assert!(with.entries.iter().any(|e| e.id == extra));
1086 with.into_journal().expect("merged container validates");
1087 }
1088 }
1089
1089 lines RUST