claude_storage_core 1.0.0

Core library for Claude Code filesystem storage access (zero dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Export functionality for Claude Code storage sessions
//!
//! Supports exporting sessions to multiple formats:
//! - Markdown: Human-readable conversation format
//! - JSON: Machine-readable structured format
//! - Text: Simple conversation transcript

use crate::{ Session, Entry, ContentBlock, MessageContent, EntryType, Result, Error };
use std::io::Write;
use std::path::Path;
use std::fs::File;

/// Export format specification
#[derive( Debug, Clone, Copy, PartialEq, Eq )]
pub enum ExportFormat
{
  /// Markdown format (.md)
  Markdown,

  /// JSON format (.json)
  Json,

  /// Plain text format (.txt)
  Text,
}

impl ExportFormat
{
  /// Get file extension for format
  #[must_use]
  #[inline]
  pub fn extension( &self ) -> &'static str
  {
    match self
    {
      ExportFormat::Markdown => "md",
      ExportFormat::Json => "json",
      ExportFormat::Text => "txt",
    }
  }

  /// Parse format from string
  ///
  /// Note: This is not the standard `FromStr` trait to avoid confusion with
  /// Result type mismatch. CLI code uses this method directly.
  /// # Errors
  ///
  /// Returns error if the string does not match a known export format name.
  #[ allow( clippy::should_implement_trait ) ]
  #[inline]
  pub fn from_str( s : &str ) -> Result< Self >
  {
    match s.to_lowercase().as_str()
    {
      "markdown" | "md" => Ok( ExportFormat::Markdown ),
      "json" => Ok( ExportFormat::Json ),
      "text" | "txt" => Ok( ExportFormat::Text ),
      // Fix(issue-019): Use crate Error type instead of std::io::Error for format validation.
      //
      // Root cause: `std::io::Error::new(InvalidInput, ...).into()` converts to
      // `Error::Io { context: "unknown operation", ... }` via the blanket From impl.
      // Display produces the misleading "I/O error during unknown operation: Unknown export
      // format: xml" instead of a clear validation message.
      //
      // Pitfall: Never use `std::io::Error` for non-I/O validation failures. The blanket
      // `From<io::Error> for Error` impl always sets context to "unknown operation", which
      // is confusing to users. Use the crate's semantic error types directly.
      _ =>
      {
        Err
        (
          Error::WriteFailed
          {
            target : "export format".into(),
            reason : format!
            (
              "unknown format '{s}'; valid values: markdown (or md), json, text (or txt)"
            ),
          }
        )
      }
    }
  }
}

/// Export a session to a writer
///
/// Streams session content to the provided writer in the specified format.
/// Memory-efficient for large sessions (doesn't load entire session into memory).
///
/// # Errors
///
/// Returns error if loading session entries fails or if writing to the writer fails.
#[inline]
pub fn export_session< W : Write >
(
  session : &mut Session,
  format : ExportFormat,
  writer : &mut W,
) -> Result< () >
{
  match format
  {
    ExportFormat::Markdown => export_markdown( session, writer ),
    ExportFormat::Json => export_json( session, writer ),
    ExportFormat::Text => export_text( session, writer ),
  }
}

/// Export a session to a file
///
/// Convenience function that creates a file and exports to it.
///
/// # Errors
///
/// Returns error if the output file cannot be created, if exporting fails,
/// or if flushing the file to disk fails.
#[inline]
pub fn export_session_to_file
(
  session : &mut Session,
  format : ExportFormat,
  output_path : &Path,
) -> Result< () >
{
  // Fix(issue-026): Use Error::io() with context instead of bare `?` on File::create.
  //
  // Root cause: The blanket `From<io::Error> for Error` sets context to "unknown operation",
  // producing "I/O error during unknown operation: No such file or directory". This gives no
  // indication that the file creation failed or which path was involved.
  //
  // Pitfall: Always use `.map_err(|e| Error::io(e, context))` when converting IO errors
  // that benefit from path context. The `?` operator silently strips path information.
  let mut file = File::create( output_path )
    .map_err( | e | Error::io( e, format!( "create output file '{}'", output_path.display() ) ) )?;
  export_session( session, format, &mut file )?;
  file.sync_all()
    .map_err( | e | Error::io( e, format!( "flush output file '{}'", output_path.display() ) ) )?;
  Ok( () )
}

/// Export session as markdown
fn export_markdown< W : Write >
(
  session : &mut Session,
  writer : &mut W,
) -> Result< () >
{
  // Get session metadata before loading entries (to avoid borrow issues)
  let session_id = session.id().to_string();
  let storage_path = session.storage_path().to_path_buf();

  // Get stats first (before entries to avoid double borrow)
  let stats = session.stats()?;
  let first_timestamp = stats.first_timestamp.clone();
  let last_timestamp = stats.last_timestamp.clone();
  let total_entries = stats.total_entries;

  // Load entries
  let entries = session.entries()?;

  // Write header
  writeln!( writer, "# Session: {session_id}\n" )?;
  writeln!( writer, "**Path**: `{}`", storage_path.display() )?;
  writeln!( writer, "**Entries**: {total_entries}" )?;

  if let Some( first ) = first_timestamp
  {
    writeln!( writer, "**Created**: {first}" )?;
  }

  if let Some( last ) = last_timestamp
  {
    writeln!( writer, "**Last Updated**: {last}" )?;
  }

  writeln!( writer, "\n---\n" )?;

  // Write entries
  for ( idx, entry ) in entries.iter().enumerate()
  {
    write_markdown_entry( writer, entry, idx + 1 )?;
  }

  Ok( () )
}

/// Write a single entry in markdown format
fn write_markdown_entry< W : Write >
(
  writer : &mut W,
  entry : &Entry,
  entry_num : usize,
) -> Result< () >
{
  let role_name = match entry.entry_type
  {
    EntryType::User => "User",
    EntryType::Assistant => "Assistant",
  };

  writeln!( writer, "## Entry {entry_num} - {role_name}" )?;
  writeln!( writer, "*{}*\n", entry.timestamp )?;

  match &entry.message
  {
    MessageContent::User( user_msg ) =>
    {
      writeln!( writer, "{}\n", user_msg.content )?;
    }
    MessageContent::Assistant( assistant_msg ) =>
    {
      // Process content blocks
      for block in &assistant_msg.content
      {
        match block
        {
          ContentBlock::Thinking { thinking, .. } =>
          {
            // Collapsible thinking block
            let token_count = thinking.split_whitespace().count();
            writeln!( writer, "<details>" )?;
            writeln!( writer, "<summary>Thinking ({token_count} tokens)</summary>\n" )?;
            writeln!( writer, "{thinking}" )?;
            writeln!( writer, "</details>\n" )?;
          }
          ContentBlock::Text { text } =>
          {
            writeln!( writer, "{text}\n" )?;
          }
          ContentBlock::ToolUse { name, input, .. } =>
          {
            writeln!( writer, "**Tool Use**: `{name}`" )?;
            writeln!( writer, "```json" )?;
            writeln!( writer, "{input:#?}" )?;
            writeln!( writer, "```\n" )?;
          }
          ContentBlock::ToolResult { content, .. } =>
          {
            writeln!( writer, "**Tool Result**:" )?;
            writeln!( writer, "```" )?;
            writeln!( writer, "{content}" )?;
            writeln!( writer, "```\n" )?;
          }
        }
      }
    }
  }

  writeln!( writer, "---\n" )?;

  Ok( () )
}

/// Export session as JSON
fn export_json< W : Write >
(
  session : &mut Session,
  writer : &mut W,
) -> Result< () >
{
  use std::io::{ BufRead, BufReader };
  use std::fs::File as StdFile;

  // Get session metadata before opening file (to avoid borrow issues)
  let session_id = session.id().to_string();
  let storage_path = session.storage_path().to_path_buf();

  // Open session file
  let file = StdFile::open( &storage_path )?;
  let reader = BufReader::new( file );

  // Write JSON array opening
  writeln!( writer, "{{" )?;
  writeln!( writer, "  \"session_id\": \"{session_id}\"," )?;
  writeln!( writer, "  \"storage_path\": \"{}\",", storage_path.display() )?;
  writeln!( writer, "  \"entries\": [" )?;

  let mut first = true;

  // Stream entries
  for line in reader.lines()
  {
    let line = line?;

    if !first
    {
      writeln!( writer, "," )?;
    }
    first = false;

    // Pretty-print the JSON line with indentation
    let parsed = crate::json::parse_json( &line )?;
    write_json_value( writer, &parsed, 4 )?;
  }

  writeln!( writer, "\n  ]" )?;
  writeln!( writer, "}}" )?;

  Ok( () )
}

/// Write JSON value with indentation
fn write_json_value< W : Write >
(
  writer : &mut W,
  value : &crate::JsonValue,
  indent : usize,
) -> Result< () >
{
  use crate::JsonValue;

  let indent_str = " ".repeat( indent );

  match value
  {
    JsonValue::Null => write!( writer, "null" )?,
    JsonValue::Bool( b ) => write!( writer, "{b}" )?,
    JsonValue::Number( n ) => write!( writer, "{n}" )?,
    JsonValue::String( s ) =>
    {
      // Escape string for JSON
      write!( writer, "\"" )?;
      for ch in s.chars()
      {
        match ch
        {
          '"' => write!( writer, "\\\"" )?,
          '\\' => write!( writer, "\\\\" )?,
          '\n' => write!( writer, "\\n" )?,
          '\r' => write!( writer, "\\r" )?,
          '\t' => write!( writer, "\\t" )?,
          _ => write!( writer, "{ch}" )?,
        }
      }
      write!( writer, "\"" )?;
    }
    JsonValue::Array( arr ) =>
    {
      writeln!( writer, "[" )?;
      for ( i, item ) in arr.iter().enumerate()
      {
        write!( writer, "{}", " ".repeat( indent + 2 ) )?;
        write_json_value( writer, item, indent + 2 )?;
        if i < arr.len() - 1
        {
          writeln!( writer, "," )?;
        }
        else
        {
          writeln!( writer )?;
        }
      }
      write!( writer, "{indent_str}]" )?;
    }
    JsonValue::Object( obj ) =>
    {
      writeln!( writer, "{{" )?;
      let keys : Vec< &String > = obj.keys().collect();
      for ( i, key ) in keys.iter().enumerate()
      {
        write!( writer, "{}\"{}\": ", " ".repeat( indent + 2 ), key )?;
        write_json_value( writer, &obj[ *key ], indent + 2 )?;
        if i < keys.len() - 1
        {
          writeln!( writer, "," )?;
        }
        else
        {
          writeln!( writer )?;
        }
      }
      write!( writer, "{indent_str}}}" )?;
    }
  }

  Ok( () )
}

/// Export session as plain text
fn export_text< W : Write >
(
  session : &mut Session,
  writer : &mut W,
) -> Result< () >
{
  // Get session metadata before loading entries (to avoid borrow issues)
  let session_id = session.id().to_string();
  let storage_path = session.storage_path().to_path_buf();

  // Get stats first (before entries to avoid double borrow)
  let stats = session.stats()?;
  let total_entries = stats.total_entries;

  // Load entries
  let entries = session.entries()?;

  // Write header
  writeln!( writer, "Session: {session_id}" )?;
  writeln!( writer, "Path: {}", storage_path.display() )?;
  writeln!( writer, "Entries: {total_entries}" )?;
  writeln!( writer, "\n---\n" )?;

  // Write entries
  for entry in entries
  {
    write_text_entry( writer, entry )?;
  }

  Ok( () )
}

/// Write a single entry in text format
fn write_text_entry< W : Write >
(
  writer : &mut W,
  entry : &Entry,
) -> Result< () >
{
  let role_name = match entry.entry_type
  {
    EntryType::User => "User",
    EntryType::Assistant => "Assistant",
  };

  writeln!( writer, "[{}] {}", role_name, entry.timestamp )?;

  match &entry.message
  {
    MessageContent::User( user_msg ) =>
    {
      writeln!( writer, "{}\n", user_msg.content )?;
    }
    MessageContent::Assistant( assistant_msg ) =>
    {
      // Extract text content only (skip thinking blocks and tool use)
      for block in &assistant_msg.content
      {
        if let ContentBlock::Text { text } = block
        {
          writeln!( writer, "{text}" )?;
        }
        // Skip thinking, tool use, tool results in text format
      }
      writeln!( writer )?;
    }
  }

  writeln!( writer, "---\n" )?;

  Ok( () )
}