ryo-storage 0.1.0

Persistent storage and transaction log for RYO
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
//! TxLog: In-memory transaction log with replay capability
//!
//! Provides:
//! - In-memory storage of all actions
//! - Serialization to JSON/bincode
//! - Replay iterator
//! - Undo/Redo support via checkpoints

use super::entry::{TxAction, TxEntry};
use ryo_analysis::SymbolPath;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::Instant;

/// Summary of a transaction log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TxSummary {
    /// Total number of entries in the log.
    pub total_entries: usize,
    /// Subset of entries classified as mutations (`is_mutation()`).
    pub total_mutations: usize,
    /// Sum of `changes` across all mutation entries.
    pub total_changes: usize,
    /// Number of distinct files modified across the log.
    pub files_modified: usize,
    /// Wall-clock duration of the session in milliseconds.
    pub duration_ms: u64,
    /// Names of every `Checkpoint` entry encountered, in log order.
    pub checkpoints: Vec<String>,
}

/// Transaction log container
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TxLog {
    /// All entries in order
    entries: Vec<TxEntry>,

    /// Session metadata
    pub session_id: String,
    /// Absolute (or workspace-relative) project root path the session
    /// operates on.
    pub project_path: String,
    /// Session start time, ISO 8601 string.
    pub started_at: String, // ISO 8601
    /// Session end time, ISO 8601 string; `None` while the session is
    /// still active.
    pub ended_at: Option<String>,

    /// Runtime state (not serialized)
    #[serde(skip)]
    session_start: Option<Instant>,
}

impl Default for TxLog {
    fn default() -> Self {
        Self::new()
    }
}

impl TxLog {
    /// Create a new empty log
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            session_id: uuid_v4(),
            project_path: String::new(),
            started_at: chrono_now(),
            ended_at: None,
            session_start: Some(Instant::now()),
        }
    }

    /// Create with project path
    pub fn with_project(project_path: impl Into<String>) -> Self {
        let mut log = Self::new();
        log.project_path = project_path.into();
        log
    }

    /// Add an entry to the log
    pub fn push(&mut self, entry: TxEntry) {
        self.entries.push(entry);
    }

    /// Create and add a new entry
    pub fn log(&mut self, action: TxAction) -> u64 {
        let id = self.entries.len() as u64;
        let timestamp_ms = self
            .session_start
            .map(|s| s.elapsed().as_millis() as u64)
            .unwrap_or(0);

        self.entries.push(TxEntry::new(id, timestamp_ms, action));
        id
    }

    /// Get all entries
    pub fn entries(&self) -> &[TxEntry] {
        &self.entries
    }

    /// Get entry by ID
    pub fn get(&self, id: u64) -> Option<&TxEntry> {
        self.entries.get(id as usize)
    }

    /// Number of entries
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Iterate over entries
    pub fn iter(&self) -> impl Iterator<Item = &TxEntry> {
        self.entries.iter()
    }

    /// Iterate over replayable entries only
    pub fn iter_replayable(&self) -> impl Iterator<Item = &TxEntry> {
        self.entries.iter().filter(|e| e.action.is_replayable())
    }

    /// Iterate over mutation entries only
    pub fn iter_mutations(&self) -> impl Iterator<Item = &TxEntry> {
        self.entries.iter().filter(|e| e.action.is_mutation())
    }

    /// Get mutations affecting a specific symbol
    ///
    /// Returns all mutation entries where `affected_symbols` contains
    /// the given symbol or one of its ancestors.
    pub fn mutations_affecting(&self, symbol: &SymbolPath) -> Vec<&TxEntry> {
        self.entries
            .iter()
            .filter(|e| match &e.action {
                TxAction::MutationApplied {
                    affected_symbols, ..
                } => affected_symbols
                    .iter()
                    .any(|s| s == symbol || s.is_ancestor_of(symbol)),
                _ => false,
            })
            .collect()
    }

    /// Get mutations affecting a symbol and all its descendants
    ///
    /// Returns all mutation entries where `affected_symbols` contains
    /// any symbol in the subtree rooted at the given symbol.
    pub fn mutations_affecting_subtree(&self, symbol: &SymbolPath) -> Vec<&TxEntry> {
        self.entries
            .iter()
            .filter(|e| match &e.action {
                TxAction::MutationApplied {
                    affected_symbols, ..
                } => affected_symbols
                    .iter()
                    .any(|s| s == symbol || s.is_ancestor_of(symbol) || s.is_descendant_of(symbol)),
                _ => false,
            })
            .collect()
    }

    /// Get entries since a checkpoint
    pub fn entries_since_checkpoint(&self, checkpoint_name: &str) -> Vec<&TxEntry> {
        let checkpoint_idx = self.entries.iter().rposition(
            |e| matches!(&e.action, TxAction::Checkpoint { name } if name == checkpoint_name),
        );

        match checkpoint_idx {
            Some(idx) => self.entries[idx + 1..].iter().collect(),
            None => Vec::new(),
        }
    }

    /// Get the last N entries
    pub fn last_n(&self, n: usize) -> &[TxEntry] {
        let start = self.entries.len().saturating_sub(n);
        &self.entries[start..]
    }

    /// Mark session as ended
    pub fn end_session(&mut self) {
        self.ended_at = Some(chrono_now());
    }

    /// Generate summary
    pub fn summary(&self) -> TxSummary {
        let total_mutations = self
            .entries
            .iter()
            .filter(|e| e.action.is_mutation())
            .count();

        let total_changes: usize = self
            .entries
            .iter()
            .map(|e| match &e.action {
                TxAction::MutationApplied { changes, .. } => *changes,
                TxAction::MutationBatch { total_changes, .. } => *total_changes,
                TxAction::FileModified { changes, .. } => *changes,
                _ => 0,
            })
            .sum();

        let files_modified: usize = self
            .entries
            .iter()
            .filter(|e| {
                matches!(
                    &e.action,
                    TxAction::FileModified { .. } | TxAction::FileWritten { .. }
                )
            })
            .count();

        let checkpoints: Vec<String> = self
            .entries
            .iter()
            .filter_map(|e| match &e.action {
                TxAction::Checkpoint { name } => Some(name.clone()),
                _ => None,
            })
            .collect();

        let duration_ms = self.entries.last().map(|e| e.timestamp_ms).unwrap_or(0);

        TxSummary {
            total_entries: self.entries.len(),
            total_mutations,
            total_changes,
            files_modified,
            duration_ms,
            checkpoints,
        }
    }

    // =========================================================================
    // Serialization
    // =========================================================================

    /// Dump to JSON file
    pub fn dump_json(&self, path: &Path) -> std::io::Result<()> {
        let json = serde_json::to_string_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, json)
    }

    /// Dump to compact JSON (single line)
    pub fn dump_json_compact(&self, path: &Path) -> std::io::Result<()> {
        let json = serde_json::to_string(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, json)
    }

    /// Load from JSON file
    pub fn load_json(path: &Path) -> std::io::Result<Self> {
        let json = std::fs::read_to_string(path)?;
        serde_json::from_str(&json)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    /// Convert to JSON string
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Parse from JSON string
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }
}

// ============================================================================
// Replay Support (test-only)
// ============================================================================

/// Replay state for stepping through a log (used in tests)
#[cfg(test)]
pub struct TxReplay<'a> {
    log: &'a TxLog,
    position: usize,
}

#[cfg(test)]
impl<'a> TxReplay<'a> {
    pub fn new(log: &'a TxLog) -> Self {
        Self { log, position: 0 }
    }

    pub fn position(&self) -> usize {
        self.position
    }

    pub fn step(&mut self) -> Option<&'a TxEntry> {
        if self.position < self.log.len() {
            let entry = &self.log.entries[self.position];
            self.position += 1;
            Some(entry)
        } else {
            None
        }
    }

    pub fn seek_checkpoint(&mut self, name: &str) -> bool {
        for (i, entry) in self.log.entries.iter().enumerate() {
            if matches!(&entry.action, TxAction::Checkpoint { name: n } if n == name) {
                self.position = i;
                return true;
            }
        }
        false
    }
}

// ============================================================================
// Helper functions
// ============================================================================

/// Generate a simple UUID v4
fn uuid_v4() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    format!(
        "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
        now.as_secs() as u32,
        ((now.as_nanos() >> 16) as u16),
        (now.as_nanos() >> 32) as u16 & 0x0FFF,
        ((now.as_nanos() >> 48) as u16 & 0x3FFF) | 0x8000,
        now.as_nanos() as u64 & 0xFFFFFFFFFFFF,
    )
}

/// Get current time as ISO 8601 string
fn chrono_now() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    // Simple ISO 8601 format (not perfect but good enough)
    format!("{}Z", now.as_secs())
}

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

    #[test]
    fn test_log_basic() {
        let mut log = TxLog::new();

        log.log(TxAction::SessionStart {
            project_path: "/test".into(),
            file_count: 10,
        });

        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "foo -> bar".to_string(),
            changes: 5,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        assert_eq!(log.len(), 2);
        assert_eq!(log.iter_mutations().count(), 1);
    }

    #[test]
    fn test_log_serialization() {
        let mut log = TxLog::with_project("/test/project");

        log.log(TxAction::GoalSet {
            query: "rename test".to_string(),
            intent_type: "RenameIdent".to_string(),
            confidence: 0.9,
        });

        let json = log.to_json().unwrap();
        let loaded = TxLog::from_json(&json).unwrap();

        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded.project_path, "/test/project");
    }

    #[test]
    fn test_replay() {
        let mut log = TxLog::new();

        log.log(TxAction::Checkpoint {
            name: "start".to_string(),
        });
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "a".to_string(),
            changes: 1,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "b".to_string(),
            changes: 2,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });

        let mut replay = TxReplay::new(&log);
        assert_eq!(replay.position(), 0);

        replay.step();
        assert_eq!(replay.position(), 1);

        replay.seek_checkpoint("start");
        assert_eq!(replay.position(), 0);
    }

    #[test]
    fn test_summary() {
        let mut log = TxLog::new();

        log.log(TxAction::MutationApplied {
            mutation_type: "Rename".to_string(),
            target: "a".to_string(),
            changes: 5,
            mutation_data: None,
            file_path: None,
            pre_state: None,
            post_state: None,
            affected_symbols: vec![],
        });
        log.log(TxAction::FileModified {
            path: "/test.rs".into(),
            changes: 3,
        });
        log.log(TxAction::Checkpoint {
            name: "mid".to_string(),
        });

        let summary = log.summary();
        assert_eq!(summary.total_entries, 3);
        assert_eq!(summary.total_mutations, 1);
        assert_eq!(summary.total_changes, 8); // 5 + 3
        assert_eq!(summary.checkpoints, vec!["mid"]);
    }
}