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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Project management - represents a project (directory containing sessions)

use std::
{
  fs,
  path::{ Path, PathBuf },
};

use crate::
{
  Session,
  Error,
  Result,
  stats::ProjectStats,
};

/// Identifier for a project (UUID or filesystem path)
#[derive( Debug, Clone, PartialEq, Eq )]
pub enum ProjectId
{
  /// UUID-based project (web/IDE sessions)
  Uuid( String ),

  /// Path-based project (CLI sessions)
  Path( PathBuf ),
}

/// A project (directory containing session JSONL files)
#[derive( Debug )]
pub struct Project
{
  /// Project identifier
  id : ProjectId,

  /// Storage directory path (e.g., ~/.claude/projects/{id}/)
  storage_dir : PathBuf,
}

impl Project
{
  /// Create a new project reference
  #[must_use]
  #[inline]
  pub fn new( id : ProjectId, storage_dir : PathBuf ) -> Self
  {
    Self
    {
      id,
      storage_dir,
    }
  }

  /// Load project from storage directory
  ///
  /// # Errors
  ///
  /// Returns error if the directory does not exist, is not a directory, has an
  /// invalid or non-UTF-8 name, or if the encoded path cannot be decoded.
  #[inline]
  pub fn load( storage_dir : &Path ) -> Result< Self >
  {
    if !storage_dir.exists()
    {
      return Err( Error::project_not_found
      (
        storage_dir.to_string_lossy().to_string()
      ));
    }

    if !storage_dir.is_dir()
    {
      return Err( Error::invalid_structure
      (
        storage_dir.to_path_buf(),
        "not a directory"
      ));
    }

    // Extract project ID from directory name
    let dir_name = storage_dir
      .file_name()
      .ok_or_else( || Error::invalid_structure
      (
        storage_dir.to_path_buf(),
        "missing directory name"
      ))?
      .to_str()
      .ok_or_else( || Error::invalid_structure
      (
        storage_dir.to_path_buf(),
        "directory name contains invalid UTF-8"
      ))?;

    // Determine if this is a UUID or path-based project
    let id = if dir_name.starts_with( '-' )
    {
      // Path-based project
      let decoded_path = crate::decode_path( dir_name )?;
      ProjectId::Path( decoded_path )
    }
    else
    {
      // UUID-based project
      ProjectId::Uuid( dir_name.to_string() )
    };

    Ok( Self
    {
      id,
      storage_dir : storage_dir.to_path_buf(),
    })
  }

  /// Helper to iterate session files with filtering
  ///
  /// Returns true to continue iteration, false to stop early.
  fn iter_session_files< F >( &self, include_agents : bool, mut action : F ) -> Result< () >
  where
    F : FnMut( PathBuf ) -> Result< bool >,
  {
    // Handle race condition: directory may have been deleted between list_projects()
    // and when we try to read it (e.g., concurrent test cleanup). Treat as empty.
    let entries = match fs::read_dir( &self.storage_dir )
    {
      Ok( entries ) => entries,
      Err( e ) if e.kind() == std::io::ErrorKind::NotFound =>
      {
        // Directory was deleted - treat as empty project (race condition)
        return Ok( () );
      }
      Err( e ) =>
      {
        return Err( Error::io( e, format!( "reading project directory: {}", self.storage_dir.display() ) ) );
      }
    };

    // Fix(issue-018): Also discover agent sessions in new-format subdirectories.
    //
    // Root cause: Claude Code v2.x changed the agent session storage format from
    // `{project_dir}/agent-{id}.jsonl` (old) to `{project_dir}/{uuid}/subagents/agent-*.jsonl`
    // (new). The iterator only scanned the top-level project directory, so new-format
    // agent sessions were completely invisible — `global_stats_fast()` reported Agent: 0
    // while 11,757 agent session files existed.
    //
    // Pitfall: Assuming a storage format is stable across Claude Code versions. Always
    // inspect the actual filesystem structure before implementing counters or iterators.
    for entry in entries
    {
      let entry = entry.map_err( | e | Error::io
      (
        e,
        format!( "reading directory entry in: {}", self.storage_dir.display() )
      ))?;

      let path = entry.path();

      // Top-level .jsonl files: main sessions (and old-format agent sessions)
      if path.extension().and_then( | s | s.to_str() ) == Some( "jsonl" )
      {
        // Apply agent session filter
        if !include_agents
        {
          if let Some( filename ) = path.file_name().and_then( | s | s.to_str() )
          {
            if filename.starts_with( "agent-" )
            {
              continue;
            }
          }
        }

        // Execute action callback, stop if it returns false
        if !action( path )?
        {
          return Ok( () );
        }
      }
      else if include_agents && path.is_dir()
      {
        // New-format: agent sessions live in {project_dir}/{uuid}/subagents/agent-*.jsonl
        // Check every subdirectory for a "subagents/" child directory
        let subagents_dir = path.join( "subagents" );
        if !subagents_dir.is_dir()
        {
          continue;
        }

        let Ok( sub_entries ) = fs::read_dir( &subagents_dir ) else { continue };

        for sub_entry in sub_entries
        {
          let Ok( sub_entry ) = sub_entry else { continue };

          let sub_path = sub_entry.path();
          if sub_path.extension().and_then( | s | s.to_str() ) == Some( "jsonl" )
            && !action( sub_path )?
          {
            return Ok( () );
          }
        }
      }
    }

    Ok( () )
  }

  /// Get project ID
  #[must_use] 
  #[inline]
  pub fn id( &self ) -> &ProjectId
  {
    &self.id
  }

  /// Get storage directory path
  #[must_use] 
  #[inline]
  pub fn storage_dir( &self ) -> &Path
  {
    &self.storage_dir
  }

  /// List all sessions in this project
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read.
  #[inline]
  pub fn sessions( &self ) -> Result< Vec< Session > >
  {
    let mut sessions = Vec::new();

    self.iter_session_files( false, | path |
    {
      match Session::load( &path )
      {
        Ok( session ) => sessions.push( session ),
        Err( e ) => eprintln!( "Warning: Failed to load session {}: {e}", path.display() ),
      }
      Ok( true )
    })?;

    Ok( sessions )
  }

  /// Check if project has any sessions
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read.
  #[inline]
  pub fn has_sessions( &self ) -> Result< bool >
  {
    let mut found = false;

    self.iter_session_files( false, | _path |
    {
      found = true;
      Ok( false ) // Stop early after finding first session
    })?;

    Ok( found )
  }

  /// Count sessions without loading them
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read.
  #[inline]
  pub fn count_sessions( &self ) -> Result< usize >
  {
    let mut count = 0;

    self.iter_session_files( false, | _path |
    {
      count += 1;
      Ok( true )
    })?;

    Ok( count )
  }

  /// Count sessions by type using filename inspection only — no JSONL parsing.
  ///
  /// Returns `(main_sessions, agent_sessions)`. Agent sessions are identified by
  /// the `agent-` filename prefix; all other sessions are main sessions.
  ///
  /// # Performance
  ///
  /// O(N) directory listing only. Suitable for status/stats commands that need
  /// session counts without entry-level detail.
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read.
  #[inline]
  pub fn count_sessions_split( &self ) -> Result< ( usize, usize ) >
  {
    let mut main_count = 0usize;
    let mut agent_count = 0usize;

    self.iter_session_files( true, | path |
    {
      let is_agent = path
        .file_name()
        .and_then( | n | n.to_str() )
        .is_some_and( | n | n.starts_with( "agent-" ) );

      if is_agent { agent_count += 1; } else { main_count += 1; }
      Ok( true )
    })?;

    Ok( ( main_count, agent_count ) )
  }

  /// List all sessions including agent sessions
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read.
  #[inline]
  pub fn all_sessions( &self ) -> Result< Vec< Session > >
  {
    let mut sessions = Vec::new();

    self.iter_session_files( true, | path |
    {
      match Session::load( &path )
      {
        Ok( session ) => sessions.push( session ),
        Err( e ) => eprintln!( "Warning: Failed to load session {}: {e}", path.display() ),
      }
      Ok( true )
    })?;

    Ok( sessions )
  }

  /// Compute project statistics
  ///
  /// Aggregates statistics from all sessions (main and agent) in this project.
  ///
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read or if a session
  /// file cannot be parsed.
  #[inline]
  pub fn project_stats( &self ) -> Result< ProjectStats >
  {
    let project_id = match &self.id
    {
      ProjectId::Uuid( uuid ) => uuid.clone(),
      ProjectId::Path( path ) => path.to_string_lossy().to_string(),
    };

    let mut stats = ProjectStats::new( project_id );

    // Get all sessions including agents
    let mut all_sessions = self.all_sessions()?;

    stats.session_count = all_sessions.len();

    // Compute stats for each session
    for session in &mut all_sessions
    {
      if session.is_agent_session()
      {
        stats.agent_session_count += 1;
      }
      else
      {
        stats.main_session_count += 1;
      }

      // Get session stats (skip corrupted sessions with warning)
      match session.stats()
      {
        Ok( session_stats ) =>
        {
          stats.total_entries += session_stats.total_entries;
          stats.total_user_entries += session_stats.user_entries;
          stats.total_assistant_entries += session_stats.assistant_entries;
          stats.total_input_tokens += session_stats.total_input_tokens;
          stats.total_output_tokens += session_stats.total_output_tokens;
        },
        Err( e ) =>
        {
          eprintln!( "Warning: Skipping corrupted session {}: {}", session.storage_path().display(), e );
        }
      }
    }

    Ok( stats )
  }

  /// List sessions matching filter
  ///
  /// ## Filtering Logic
  ///
  /// Returns only sessions that match ALL filter conditions (AND logic):
  /// - `agent_only`: Filter by agent/main session type
  /// - `min_entries`: Minimum entry count
  /// - `session_id_substring`: Session ID substring match (case-insensitive)
  ///
  /// ## Examples
  ///
  /// ```rust,no_run
  /// use claude_storage_core::{ Storage, SessionFilter };
  ///
  /// let storage = Storage::new().unwrap();
  /// let mut project = storage.list_projects().unwrap().into_iter().next().unwrap();
  ///
  /// // Filter for agent sessions with 10+ entries
  /// let filter = SessionFilter
  /// {
  ///   agent_only : Some( true ),
  ///   min_entries : Some( 10 ),
  ///   session_id_substring : None,
  /// };
  ///
  /// let sessions = project.sessions_filtered( &filter ).unwrap();
  /// ```
  /// # Errors
  ///
  /// Returns error if the project directory cannot be read or if session
  /// filtering fails (e.g., cannot read a session file for entry count).
  #[inline]
  pub fn sessions_filtered( &mut self, filter : &crate::SessionFilter ) -> Result< Vec< Session > >
  {
    // Optimization: skip filtering if default filter
    if filter.is_default()
    {
      return self.all_sessions();
    }

    let all_sessions = self.all_sessions()?;
    let mut filtered = Vec::new();

    for mut session in all_sessions
    {
      if session.matches_filter( filter )?
      {
        filtered.push( session );
      }
    }

    Ok( filtered )
  }

  /// Check if project matches filter
  ///
  /// ## Filtering Logic
  ///
  /// All filter conditions must match (AND logic):
  /// - `path_substring`: Path substring match (case-insensitive)
  /// - `min_entries`: Minimum total entries across all sessions
  /// - `min_sessions`: Minimum session count
  ///
  /// ## Examples
  ///
  /// ```rust,no_run
  /// use claude_storage_core::{ Storage, ProjectFilter };
  ///
  /// let storage = Storage::new().unwrap();
  /// let project = storage.list_projects().unwrap().into_iter().next().unwrap();
  ///
  /// let filter = ProjectFilter
  /// {
  ///   path_substring : Some( "myproject".to_string() ),
  ///   min_entries : None,
  ///   min_sessions : Some( 5 ),
  /// };
  ///
  /// assert!( project.matches_filter( &filter ).unwrap() );
  /// ```
  ///
  /// # Errors
  ///
  /// Returns error if reading session counts or project statistics fails.
  #[inline]
  pub fn matches_filter( &self, filter : &crate::ProjectFilter ) -> Result< bool >
  {
    // Path substring filter
    if let Some( ref substring ) = filter.path_substring
    {
      let path_str = match &self.id
      {
        ProjectId::Uuid( uuid ) => uuid.clone(),
        ProjectId::Path( path ) => path.to_string_lossy().to_string(),
      };

      let matcher = crate::StringMatcher::new( substring );
      if !matcher.matches( &path_str )
      {
        return Ok( false );
      }
    }

    // Minimum sessions filter
    if let Some( min_sessions ) = filter.min_sessions
    {
      let count = self.count_sessions()?;
      if count < min_sessions
      {
        return Ok( false );
      }
    }

    // Minimum entries filter (requires aggregation)
    if let Some( min_entries ) = filter.min_entries
    {
      let stats = self.project_stats()?;
      if stats.total_entries < min_entries
      {
        return Ok( false );
      }
    }

    Ok( true )
  }
}

impl ProjectId
{
  /// Create a path-based project ID
  #[inline]
  pub fn path< P : Into< PathBuf > >( path : P ) -> Self
  {
    ProjectId::Path( path.into() )
  }

  /// Create a UUID-based project ID
  #[inline]
  pub fn uuid< S : Into< String > >( uuid : S ) -> Self
  {
    ProjectId::Uuid( uuid.into() )
  }

  /// Get the original path (if path-based project)
  #[must_use] 
  #[inline]
  pub fn as_path( &self ) -> Option< &Path >
  {
    match self
    {
      ProjectId::Path( path ) => Some( path ),
      ProjectId::Uuid( _ ) => None,
    }
  }

  /// Get the UUID (if UUID-based project)
  #[must_use] 
  #[inline]
  pub fn as_uuid( &self ) -> Option< &str >
  {
    match self
    {
      ProjectId::Uuid( uuid ) => Some( uuid ),
      ProjectId::Path( _ ) => None,
    }
  }
}

#[cfg( test )]
mod tests
{
  use super::*;

  #[test]
  fn test_project_id_path()
  {
    let id = ProjectId::path( "/home/user/project" );
    assert!( id.as_path().is_some() );
    assert!( id.as_uuid().is_none() );
  }

  #[test]
  fn test_project_id_uuid()
  {
    let id = ProjectId::uuid( "550e8400-e29b-41d4-a716-446655440000" );
    assert!( id.as_uuid().is_some() );
    assert!( id.as_path().is_none() );
  }

  #[test]
  fn test_project_new()
  {
    let id = ProjectId::path( "/home/user/project" );
    let project = Project::new( id, PathBuf::from( "storage" ) );

    assert!( project.id().as_path().is_some() );
  }
}