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
//! Main storage interface - entry point for all storage operations

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

use crate::
{
  Project,
  ProjectId,
  Error,
  Result,
  stats::GlobalStats,
};

/// Main storage interface for Claude Code's filesystem database
#[derive( Debug )]
pub struct Storage
{
  /// Root storage directory (default: ~/.claude/)
  root : PathBuf,
}

impl Storage
{
  /// Create a new storage interface using default location (~/.claude/)
  ///
  /// # Errors
  ///
  /// Returns error if the `HOME` environment variable is not set.
  #[inline]
  pub fn new() -> Result< Self >
  {
    let home = env::var( "HOME" )
      .map_err( | e | Error::io
      (
        std::io::Error::new
        (
          std::io::ErrorKind::NotFound,
          format!( "HOME environment variable not set: {e}" )
        ),
        "resolving HOME directory"
      ))?;

    let root = PathBuf::from( home ).join( ".claude" );

    Ok( Self { root })
  }

  /// Create a storage interface with custom root directory
  #[inline]
  pub fn with_root< P : Into< PathBuf > >( root : P ) -> Self
  {
    Self
    {
      root : root.into(),
    }
  }

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

  /// Get projects directory path
  #[must_use]
  #[inline]
  pub fn projects_dir( &self ) -> PathBuf
  {
    self.root.join( "projects" )
  }

  /// List all projects in storage
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory exists but cannot be read.
  #[inline]
  pub fn list_projects( &self ) -> Result< Vec< Project > >
  {
    let projects_dir = self.projects_dir();

    if !projects_dir.exists()
    {
      return Ok( Vec::new() );
    }

    let entries = fs::read_dir( &projects_dir )
      .map_err( | e | Error::io
      (
        e,
        format!( "reading projects directory: {}", projects_dir.display() )
      ))?;

    let mut projects = Vec::new();

    for entry in entries
    {
      let entry = entry.map_err( | e | Error::io
      (
        e,
        format!( "reading directory entry in: {}", projects_dir.display() )
      ))?;

      let path = entry.path();

      if path.is_dir()
      {
        match Project::load( &path )
        {
          Ok( project ) => projects.push( project ),
          Err( e ) => eprintln!( "Warning: Failed to load project {}: {e}", path.display() ),
        }
      }
    }

    Ok( projects )
  }

  /// Load a specific project by ID
  ///
  /// # Errors
  ///
  /// Returns error if the project directory does not exist or cannot be loaded,
  /// or if a path-based ID cannot be encoded.
  #[inline]
  pub fn load_project( &self, id : &ProjectId ) -> Result< Project >
  {
    let storage_dir = match id
    {
      ProjectId::Uuid( uuid ) =>
      {
        self.projects_dir().join( uuid )
      }
      ProjectId::Path( path ) =>
      {
        let encoded = crate::encode_path( path )?;
        self.projects_dir().join( encoded )
      }
    };

    Project::load( &storage_dir )
  }

  /// Load project for current working directory
  ///
  /// # Errors
  ///
  /// Returns error if the current directory cannot be determined, or if no
  /// project is found for the current directory or any of its topic subdirectories.
  #[inline]
  pub fn load_project_for_cwd( &self ) -> Result< Project >
  {
    let cwd = env::current_dir()
      .map_err( | e | Error::io( e, "getting current directory" ))?;

    // Try exact path first
    if let Ok( project ) = self.load_project( &ProjectId::path( &cwd ) ) { Ok( project ) } else {
      // If exact path fails, look for topic subdirectories (e.g., /-default_topic, /-commit)
      if let Ok( entries ) = std::fs::read_dir( &cwd )
      {
        // Collect all topic subdirectories starting with hyphen
        let mut topic_dirs : Vec< PathBuf > = entries
          .filter_map( core::result::Result::ok )
          .filter( | entry |
          {
            if let Ok( file_name ) = entry.file_name().into_string()
            {
              file_name.starts_with( '-' ) && entry.path().is_dir()
            }
            else
            {
              false
            }
          })
          .map( | entry | entry.path() )
          .collect();

        // Sort to prefer -default_topic over other topics
        topic_dirs.sort_by( | a, b |
        {
          let a_name = a.file_name().and_then( | n | n.to_str() ).unwrap_or( "" );
          let b_name = b.file_name().and_then( | n | n.to_str() ).unwrap_or( "" );

          // Prioritize -default_topic
          match ( a_name, b_name )
          {
            ( "-default_topic", _ ) => core::cmp::Ordering::Less,
            ( _, "-default_topic" ) => core::cmp::Ordering::Greater,
            _ => a_name.cmp( b_name ),
          }
        });

        // Try each topic directory
        for topic_dir in topic_dirs
        {
          if let Ok( project ) = self.load_project( &ProjectId::path( &topic_dir ) )
          {
            return Ok( project );
          }
        }
      }

      // If no topic directories found or none have projects, return original error
      Err( Error::project_not_found( format!( "No project found for directory: {}", cwd.display() ) ) )
    }
  }

  /// Load project for a specific filesystem path
  ///
  /// # Errors
  ///
  /// Returns error if no project exists for the given path or if the project
  /// directory cannot be loaded.
  #[inline]
  pub fn load_project_for_path< P : AsRef< Path > >( &self, path : P ) -> Result< Project >
  {
    let path = path.as_ref();
    self.load_project( &ProjectId::path( path ) )
  }

  /// Check if a project exists for the given path
  #[inline]
  pub fn has_project_for_path< P : AsRef< Path > >( &self, path : P ) -> bool
  {
    let path = path.as_ref();

    match crate::encode_path( path )
    {
      Ok( encoded ) =>
      {
        let storage_dir = self.projects_dir().join( encoded );
        storage_dir.exists() && storage_dir.is_dir()
      }
      Err( _ ) => false,
    }
  }

  /// Check if a project has any sessions
  #[inline]
  pub fn has_sessions_for_path< P : AsRef< Path > >( &self, path : P ) -> bool
  {
    match self.load_project_for_path( path )
    {
      Ok( project ) => project.has_sessions().unwrap_or( false ),
      Err( _ ) => false,
    }
  }

  /// Count total projects
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory exists but cannot be read.
  #[inline]
  pub fn count_projects( &self ) -> Result< usize >
  {
    let projects_dir = self.projects_dir();

    if !projects_dir.exists()
    {
      return Ok( 0 );
    }

    let entries = fs::read_dir( &projects_dir )
      .map_err( | e | Error::io
      (
        e,
        format!( "reading projects directory: {}", projects_dir.display() )
      ))?;

    let mut count = 0;

    for entry in entries
    {
      let entry = entry.map_err( | e | Error::io
      (
        e,
        format!( "reading directory entry in: {}", projects_dir.display() )
      ))?;

      if entry.path().is_dir()
      {
        count += 1;
      }
    }

    Ok( count )
  }

  /// Compute global statistics across all projects
  ///
  /// Aggregates statistics from all projects, sessions, and entries in storage.
  /// This provides a comprehensive overview of Claude Code usage.
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory cannot be read or if computing
  /// statistics for any project fails.
  #[inline]
  pub fn global_stats( &self ) -> Result< GlobalStats >
  {
    let mut stats = GlobalStats::new();

    let projects = self.list_projects()?;
    stats.total_projects = projects.len();

    // Count UUID vs path projects
    for project in &projects
    {
      match project.id()
      {
        ProjectId::Uuid( _ ) => stats.uuid_projects += 1,
        ProjectId::Path( _ ) => stats.path_projects += 1,
      }
    }

    // Aggregate stats from each project
    for project in projects
    {
      let project_stats = project.project_stats()?;

      stats.total_sessions += project_stats.session_count;
      stats.main_sessions += project_stats.main_session_count;
      stats.agent_sessions += project_stats.agent_session_count;
      stats.total_entries += project_stats.total_entries;
      stats.total_user_entries += project_stats.total_user_entries;
      stats.total_assistant_entries += project_stats.total_assistant_entries;
      stats.total_input_tokens += project_stats.total_input_tokens;
      stats.total_output_tokens += project_stats.total_output_tokens;

      stats.project_breakdown.insert( project_stats.project_id.clone(), project_stats );
    }

    Ok( stats )
  }

  /// Compute global statistics using filesystem metadata only — no JSONL parsing.
  ///
  /// Returns project counts (UUID vs path) and session counts (main vs agent)
  /// by inspecting directory listings and session filenames. Entry counts and
  /// token totals are left at 0; use [`global_stats`] for those.
  ///
  /// # Performance
  ///
  /// O(P + S) where P = project count, S = total session file count.
  /// With 1903 projects / 2449 sessions this completes in < 1 second, whereas
  /// `global_stats` requires parsing ~7 GB of JSONL and takes > 2 minutes.
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory cannot be read.
  #[inline]
  pub fn global_stats_fast( &self ) -> Result< GlobalStats >
  {
    let mut stats = GlobalStats::new();

    let projects = self.list_projects()?;
    stats.total_projects = projects.len();

    for project in &projects
    {
      match project.id()
      {
        ProjectId::Uuid( _ ) => stats.uuid_projects += 1,
        ProjectId::Path( _ ) => stats.path_projects += 1,
      }

      // Count session files by type — no JSONL parsing
      let ( main, agent ) = project.count_sessions_split()?;
      stats.main_sessions += main;
      stats.agent_sessions += agent;
      stats.total_sessions += main + agent;
    }

    Ok( stats )
  }

  /// List all path-based projects (excludes UUID projects)
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory cannot be read.
  #[inline]
  pub fn list_path_projects( &self ) -> Result< Vec< Project > >
  {
    let all_projects = self.list_projects()?;

    Ok
    (
      all_projects
        .into_iter()
        .filter( | p | matches!( p.id(), ProjectId::Path( _ ) ) )
        .collect()
    )
  }

  /// List all UUID-based projects (excludes path projects)
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory cannot be read.
  #[inline]
  pub fn list_uuid_projects( &self ) -> Result< Vec< Project > >
  {
    let all_projects = self.list_projects()?;

    Ok
    (
      all_projects
        .into_iter()
        .filter( | p | matches!( p.id(), ProjectId::Uuid( _ ) ) )
        .collect()
    )
  }

  /// List projects matching filter
  ///
  /// ## Filtering Logic
  ///
  /// Returns only projects that match ALL filter conditions (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();
  ///
  /// // Filter for projects with "myproject" in path and 5+ sessions
  /// let filter = ProjectFilter
  /// {
  ///   path_substring : Some( "myproject".to_string() ),
  ///   min_entries : None,
  ///   min_sessions : Some( 5 ),
  /// };
  ///
  /// let projects = storage.list_projects_filtered( &filter ).unwrap();
  /// ```
  ///
  /// # Errors
  ///
  /// Returns error if the projects directory cannot be read or if filtering
  /// any project fails (e.g., cannot read session counts or entry statistics).
  #[inline]
  pub fn list_projects_filtered( &self, filter : &crate::ProjectFilter ) -> Result< Vec< Project > >
  {
    // Optimization: skip filtering if default filter
    if filter.is_default()
    {
      return self.list_projects();
    }

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

    for project in all_projects
    {
      if project.matches_filter( filter )?
      {
        filtered.push( project );
      }
    }

    Ok( filtered )
  }
}

impl Default for Storage
{
  #[inline]
  fn default() -> Self
  {
    Self::new().expect( "Failed to create default storage" )
  }
}

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

  #[test]
  fn test_storage_new()
  {
    let storage = Storage::new();
    assert!( storage.is_ok() );
  }

  #[test]
  fn test_storage_with_root()
  {
    let storage = Storage::with_root( "claude-test" );
    assert_eq!( storage.root(), Path::new( "claude-test" ) );
    assert_eq!( storage.projects_dir(), PathBuf::from( "claude-test" ).join( "projects" ) );
  }

  #[test]
  fn test_projects_dir()
  {
    let storage = Storage::with_root( "test-storage" );
    assert_eq!( storage.projects_dir(), PathBuf::from( "test-storage" ).join( "projects" ) );
  }
}