claude_storage_core 1.5.1

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
453
454
455
456
457
458
459
460
461
//! Export functionality integration tests
//!
//! Tests for exporting sessions to markdown, JSON, and text formats.
#![ cfg( unix ) ]

use claude_storage_core::{ Storage, ExportFormat, export_session };
use std::io::Cursor;

/// Test markdown export format
#[test]
fn export_markdown_basic()
{
  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  let project = projects.into_iter().next().unwrap();
  let mut sessions = project.sessions().expect( "Failed to get sessions" );

  if sessions.is_empty()
  {
    println!( "Skipping test: no sessions found" );
    return;
  }

  // Try to export the first valid session (skip sessions with parse errors)
  let mut found_valid = false;

  for session in &mut sessions
  {
    let mut output = Cursor::new( Vec::new() );

    if export_session( session, ExportFormat::Markdown, &mut output ).is_err()
    {
      continue; // Skip sessions with parse errors
    }

    let result = String::from_utf8( output.into_inner() ).expect( "Invalid UTF-8" );

    // Check for expected markdown elements
    if result.contains( "# Session:" ) && result.contains( "## Entry" )
    {
      found_valid = true;
      assert!( result.contains( "**Path**:" ), "Missing path" );
      assert!( result.contains( "**Entries**:" ), "Missing entry count" );
      assert!( result.contains( "---" ), "Missing separator" );
      break;
    }
  }

  if !found_valid
  {
    println!( "Skipping test: no valid sessions found for markdown export" );
  }
}

/// Test JSON export format
#[test]
fn export_json_basic()
{
  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  let project = projects.into_iter().next().unwrap();
  let mut sessions = project.sessions().expect( "Failed to get sessions" );

  if sessions.is_empty()
  {
    println!( "Skipping test: no sessions found" );
    return;
  }

  let session = sessions.first_mut().unwrap();

  // Export to JSON
  let mut output = Cursor::new( Vec::new() );
  export_session( session, ExportFormat::Json, &mut output )
    .expect( "Failed to export session" );

  // Verify output
  let result = String::from_utf8( output.into_inner() ).expect( "Invalid UTF-8" );

  // Check for expected JSON elements
  assert!( result.contains( "\"session_id\":" ), "Missing session_id" );
  assert!( result.contains( "\"storage_path\":" ), "Missing storage_path" );
  assert!( result.contains( "\"entries\":" ), "Missing entries array" );
  assert!( result.starts_with( '{' ), "Should start with open brace" );
  assert!( result.trim().ends_with( '}' ), "Should end with close brace" );
}

/// Test text export format
#[test]
fn export_text_basic()
{
  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  let project = projects.into_iter().next().unwrap();
  let mut sessions = project.sessions().expect( "Failed to get sessions" );

  if sessions.is_empty()
  {
    println!( "Skipping test: no sessions found" );
    return;
  }

  // Try to export the first valid session (skip sessions with parse errors)
  let mut found_valid = false;

  for session in &mut sessions
  {
    let mut output = Cursor::new( Vec::new() );

    if export_session( session, ExportFormat::Text, &mut output ).is_err()
    {
      continue; // Skip sessions with parse errors
    }

    let result = String::from_utf8( output.into_inner() ).expect( "Invalid UTF-8" );

    // Check for expected text elements
    if result.contains( "Session:" ) && ( result.contains( "[User]" ) || result.contains( "[Assistant]" ) )
    {
      found_valid = true;
      assert!( result.contains( "Path:" ), "Missing path" );
      assert!( result.contains( "Entries:" ), "Missing entry count" );
      assert!( result.contains( "---" ), "Missing separator" );
      break;
    }
  }

  if !found_valid
  {
    println!( "Skipping test: no valid sessions found for text export" );
  }
}

/// Test `ExportFormat::from_str`
#[test]
fn export_format_from_str()
{
  // Test valid formats
  assert_eq!
  (
    ExportFormat::from_str( "markdown" ).unwrap(),
    ExportFormat::Markdown
  );

  assert_eq!
  (
    ExportFormat::from_str( "md" ).unwrap(),
    ExportFormat::Markdown
  );

  assert_eq!
  (
    ExportFormat::from_str( "json" ).unwrap(),
    ExportFormat::Json
  );

  assert_eq!
  (
    ExportFormat::from_str( "text" ).unwrap(),
    ExportFormat::Text
  );

  assert_eq!
  (
    ExportFormat::from_str( "txt" ).unwrap(),
    ExportFormat::Text
  );

  // Test case insensitivity
  assert_eq!
  (
    ExportFormat::from_str( "MARKDOWN" ).unwrap(),
    ExportFormat::Markdown
  );

  // Test invalid format
  assert!( ExportFormat::from_str( "invalid" ).is_err() );
}

/// Test `ExportFormat::extension`
#[test]
fn export_format_extension()
{
  assert_eq!( ExportFormat::Markdown.extension(), "md" );
  assert_eq!( ExportFormat::Json.extension(), "json" );
  assert_eq!( ExportFormat::Text.extension(), "txt" );
}

/// Test export to file
#[test]
fn export_to_file()
{
  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  let project = projects.into_iter().next().unwrap();
  let mut sessions = project.sessions().expect( "Failed to get sessions" );

  if sessions.is_empty()
  {
    println!( "Skipping test: no sessions found" );
    return;
  }

  let session = sessions.first_mut().unwrap();

  // Create output file path in /tmp
  let output_path = std::path::PathBuf::from( "/tmp/test_export.md" );

  // Export to file
  claude_storage_core::export_session_to_file
  (
    session,
    ExportFormat::Markdown,
    &output_path
  ).expect( "Failed to export to file" );

  // Verify file exists and has content
  assert!( output_path.exists(), "Output file not created" );

  let content = std::fs::read_to_string( &output_path )
    .expect( "Failed to read output file" );

  assert!( !content.is_empty(), "Output file is empty" );
  assert!( content.contains( "# Session:" ), "Missing session header" );
}

/// Test markdown with thinking blocks
#[test]
fn export_markdown_with_thinking()
{
  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  let project = projects.into_iter().next().unwrap();
  let mut sessions = project.sessions().expect( "Failed to get sessions" );

  if sessions.is_empty()
  {
    println!( "Skipping test: no sessions found" );
    return;
  }

  // Find a session with thinking blocks (try all sessions)
  let mut found_thinking = false;

  for session in &mut sessions
  {
    let mut output = Cursor::new( Vec::new() );

    // Skip sessions that fail to export (e.g., parse errors)
    if export_session( session, ExportFormat::Markdown, &mut output ).is_err()
    {
      continue;
    }

    let result = String::from_utf8( output.into_inner() ).expect( "Invalid UTF-8" );

    if result.contains( "<details>" ) && result.contains( "Thinking" )
    {
      found_thinking = true;

      // Verify thinking block structure
      assert!( result.contains( "<summary>Thinking" ), "Missing thinking summary" );
      assert!( result.contains( "</details>" ), "Missing details close tag" );
      break;
    }
  }

  // Note: Not all sessions have thinking blocks, so we dont assert found_thinking
  // This test just verifies the format when thinking blocks are present
  if !found_thinking
  {
    println!( "No sessions with thinking blocks found (this is ok)" );
  }
}

/// Test export of sessions containing non-conversation metadata entries
///
/// Real Claude Code sessions may contain metadata entries like:
/// - queue-operation: Commands queued for execution
/// - summary: Session summaries
/// - file-history-snapshot: File state snapshots
///
/// These entries should be gracefully skipped during export, allowing
/// export to succeed and showing only conversation entries.
#[test]
fn export_with_metadata_entries()
{
  use std::io::Cursor;

  let storage = Storage::with_root( "/tmp/claude_tests_empty" );
  let projects = storage.list_projects().expect( "Failed to list projects" );

  if projects.is_empty()
  {
    println!( "Skipping test: no projects found" );
    return;
  }

  // Find a session that contains metadata entries
  // In real storage, many sessions have queue-operation or summary entries
  let mut found_session_with_metadata = false;

  for project in projects
  {
    let Ok( mut sessions ) = project.sessions() else { continue };

    for session in &mut sessions
    {
      // Try to read the raw JSONL to check for metadata entries
      let path = session.storage_path();
      let Ok( content ) = std::fs::read_to_string( path ) else { continue };

      // Check if this session has metadata entries (queue-operation or summary)
      let has_metadata = content.lines().any( | line |
      {
        line.contains( r#""type":"queue-operation"# )
          || line.contains( r#""type":"summary"# )
          || line.contains( r#""type":"file-history-snapshot"# )
      });

      if !has_metadata
      {
        continue;
      }

      // Found a session with metadata entries - test export
      found_session_with_metadata = true;

      let mut output = Cursor::new( Vec::new() );

      // Export should succeed even with metadata entries
      export_session( session, ExportFormat::Markdown, &mut output )
        .expect( "Export failed for session with metadata entries" );

      let result = String::from_utf8( output.into_inner() ).expect( "Invalid UTF-8" );

      // Verify export contains session header
      assert!( result.contains( "# Session:" ), "Missing session header" );
      assert!( result.contains( "**Path**:" ), "Missing path" );

      // Note: Entry count may be 0 if session only has metadata entries
      // (e.g., queue-operation only), which is valid

      let sid = session.id();
      println!( "Successfully exported session with metadata entries: {sid}" );
      break;
    }

    if found_session_with_metadata
    {
      break;
    }
  }

  if !found_session_with_metadata
  {
    println!( "Skipping test: no sessions with metadata entries found" );
    println!( "This is expected if testing on a minimal storage instance" );
  }
}

/// Bug Reproducer (issue-019): `ExportFormat::from_str()` returned `std::io::Error`, producing
/// "I/O error during unknown operation: Unknown export format: xml" for invalid format strings.
///
/// ## Root Cause
///
/// `from_str()` used `std::io::Error::new(InvalidInput, "...").into()` for the validation
/// failure. The blanket `From<io::Error> for Error` impl sets context to "unknown operation",
/// so the error displayed as "I/O error during unknown operation: Unknown export format: xml"
/// — misleading because no I/O operation was attempted.
///
/// ## Why Not Caught
///
/// Tests only tested valid format strings (markdown, json, text). No test verified the
/// error message content for invalid formats, only that `from_str()` returned `Err`.
///
/// ## Fix Applied
///
/// Changed the `_` match arm in `from_str()` to return `Error::WriteFailed` with a clear
/// message listing valid format options, instead of wrapping in `std::io::Error`.
///
/// ## Prevention
///
/// Never use `std::io::Error` for non-I/O validation failures. The blanket `From<io::Error>`
/// impl always produces "unknown operation" context, which obscures the actual error.
///
/// ## Pitfall
///
/// The `.into()` shorthand on a `std::io::Error` silently goes through `From<io::Error> for
/// crate::Error`, setting a generic "unknown operation" context. Always use crate-level
/// error constructors for semantic errors — reserve `std::io::Error` for actual file I/O.
// test_kind: bug_reproducer(issue-019)
#[ test ]
fn export_format_invalid_string_returns_clear_error()
{
  // Before fix: "I/O error during unknown operation: Unknown export format: xml"
  // After fix: clear message listing valid options, no "I/O error" prefix

  let result = ExportFormat::from_str( "xml" );
  assert!( result.is_err(), "Unknown format 'xml' must return Err" );

  let err_msg = result.unwrap_err().to_string();

  // Must NOT contain the confusing "I/O error" prefix
  assert!(
    !err_msg.contains( "I/O error" ),
    "Error for invalid format should not say 'I/O error'. Got: {err_msg}"
  );

  // Must contain the invalid format name so user knows what they typed
  assert!(
    err_msg.contains( "xml" ),
    "Error must reference the invalid format value. Got: {err_msg}"
  );

  // Verify all valid format aliases still parse correctly
  assert!( ExportFormat::from_str( "markdown" ).is_ok() );
  assert!( ExportFormat::from_str( "md" ).is_ok() );
  assert!( ExportFormat::from_str( "json" ).is_ok() );
  assert!( ExportFormat::from_str( "text" ).is_ok() );
  assert!( ExportFormat::from_str( "txt" ).is_ok() );

  // Case insensitive
  assert!( ExportFormat::from_str( "Markdown" ).is_ok() );
  assert!( ExportFormat::from_str( "JSON" ).is_ok() );
}