lore-cli 0.2.0

Capture AI coding sessions and link them to git commits
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
//! Consolidated session-blob pipeline for git-ref sync.
//!
//! A [`SessionRecord`] holds the complete reasoning record for a single
//! session: the session row itself plus its messages, commit links, tags,
//! annotations, and optional summary. Encrypting the full record means a
//! teammate who pulls the repo can run `lore blame` and recover the
//! commit-to-reasoning linkage.
//!
//! The on-disk blob pipeline is `serde_json -> gzip -> encrypt`. Compression
//! happens before encryption because ciphertext does not compress. The output
//! is raw bytes suitable for writing directly as a git blob (no base64).

use std::io::{Read, Write};

use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use serde::{Deserialize, Serialize};

use super::encryption::{decrypt_data, encrypt_data};
use super::SyncError;
use crate::storage::models::{Annotation, Message, Session, SessionLink, Summary, Tag, Tombstone};

/// The complete reasoning record for a single session.
///
/// This is the unit that gets serialized, compressed, encrypted, and written as
/// a single git blob (`sessions/<uuid>.enc`). It is reconstructed verbatim on
/// the receiving machine so the full reasoning history, including commit links,
/// rides along with the code.
#[derive(Clone, Serialize, Deserialize)]
pub struct SessionRecord {
    /// The session metadata row.
    pub session: Session,

    /// All messages belonging to the session, in conversation order.
    pub messages: Vec<Message>,

    /// Links from the session to git commits, branches, or pull requests.
    pub links: Vec<SessionLink>,

    /// User-applied tags categorizing the session.
    pub tags: Vec<Tag>,

    /// User-created annotations attached to the session.
    pub annotations: Vec<Annotation>,

    /// The session summary, if one has been generated.
    pub summary: Option<Summary>,
}

/// Manual `Debug` that prints only non-sensitive metadata.
///
/// The derived `Debug` would print plaintext message content, annotation text,
/// and summary text. Because a `SessionRecord` holds the full decrypted
/// reasoning history, a future failure log that formatted one could leak private
/// reasoning. This impl emits only counts and identifiers, never user content.
impl std::fmt::Debug for SessionRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SessionRecord")
            .field("session_id", &self.session.id)
            .field("tool", &self.session.tool)
            .field("message_count", &self.messages.len())
            .field("link_count", &self.links.len())
            .field("tag_count", &self.tags.len())
            .field("annotation_count", &self.annotations.len())
            .field("has_summary", &self.summary.is_some())
            .finish()
    }
}

/// Serializes and encrypts a session record into a git-blob-ready byte buffer.
///
/// The pipeline is `serde_json -> gzip -> encrypt_data`. The returned bytes are
/// the raw blob contents to hand to `git hash-object`.
///
/// # Arguments
///
/// * `record` - The full reasoning record to encode
/// * `key` - The 32-byte encryption key derived from the store passphrase
pub fn encrypt_session_record(record: &SessionRecord, key: &[u8]) -> Result<Vec<u8>, SyncError> {
    let json = serde_json::to_vec(record)
        .map_err(|e| SyncError::Serialization(format!("Failed to serialize record: {e}")))?;

    let compressed = gzip_compress(&json)?;

    encrypt_data(&compressed, key)
}

/// Decrypts and deserializes a session record from git-blob bytes.
///
/// Inverse of [`encrypt_session_record`]: `decrypt_data -> gunzip ->
/// serde_json`.
///
/// # Arguments
///
/// * `blob` - The raw blob bytes as read from `git cat-file blob`
/// * `key` - The 32-byte encryption key derived from the store passphrase
pub fn decrypt_session_record(blob: &[u8], key: &[u8]) -> Result<SessionRecord, SyncError> {
    let compressed = decrypt_data(blob, key)?;

    let json = gzip_decompress(&compressed)?;

    serde_json::from_slice(&json)
        .map_err(|e| SyncError::Serialization(format!("Failed to deserialize record: {e}")))
}

/// Serializes and encrypts the tombstone set into a git-blob-ready buffer.
///
/// Stored at `meta/tombstones` in the store tree so deletions of child records
/// propagate across machines alongside the session blobs. Uses the identical
/// `serde_json -> gzip -> encrypt_data` pipeline as [`encrypt_session_record`].
pub fn encrypt_tombstones(tombstones: &[Tombstone], key: &[u8]) -> Result<Vec<u8>, SyncError> {
    let json = serde_json::to_vec(tombstones)
        .map_err(|e| SyncError::Serialization(format!("Failed to serialize tombstones: {e}")))?;

    let compressed = gzip_compress(&json)?;

    encrypt_data(&compressed, key)
}

/// Decrypts and deserializes the tombstone set from git-blob bytes.
///
/// Inverse of [`encrypt_tombstones`].
pub fn decrypt_tombstones(blob: &[u8], key: &[u8]) -> Result<Vec<Tombstone>, SyncError> {
    let compressed = decrypt_data(blob, key)?;

    let json = gzip_decompress(&compressed)?;

    serde_json::from_slice(&json)
        .map_err(|e| SyncError::Serialization(format!("Failed to deserialize tombstones: {e}")))
}

/// Compresses bytes with gzip at the default compression level.
fn gzip_compress(data: &[u8]) -> Result<Vec<u8>, SyncError> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    encoder
        .write_all(data)
        .map_err(|e| SyncError::Compression(format!("Gzip write failed: {e}")))?;
    encoder
        .finish()
        .map_err(|e| SyncError::Compression(format!("Gzip finish failed: {e}")))
}

/// Decompresses gzip bytes produced by [`gzip_compress`].
fn gzip_decompress(data: &[u8]) -> Result<Vec<u8>, SyncError> {
    let mut decoder = GzDecoder::new(data);
    let mut out = Vec::new();
    decoder
        .read_to_end(&mut out)
        .map_err(|e| SyncError::Compression(format!("Gzip read failed: {e}")))?;
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::models::{LinkCreator, LinkType, MessageContent, MessageRole};
    use crate::sync::encryption::{derive_key, generate_salt};
    use chrono::Utc;
    use uuid::Uuid;

    fn sample_record() -> SessionRecord {
        let session_id = Uuid::new_v4();
        let session = Session {
            id: session_id,
            tool: "claude-code".to_string(),
            tool_version: Some("2.0.0".to_string()),
            started_at: Utc::now(),
            ended_at: Some(Utc::now()),
            model: Some("claude-opus".to_string()),
            working_directory: "/home/user/project".to_string(),
            git_branch: Some("main".to_string()),
            source_path: Some("/sessions/a.jsonl".to_string()),
            message_count: 2,
            machine_id: Some("machine-1".to_string()),
        };

        let messages = vec![
            Message {
                id: Uuid::new_v4(),
                session_id,
                parent_id: None,
                index: 0,
                timestamp: Utc::now(),
                role: MessageRole::User,
                content: MessageContent::Text("Fix the bug".to_string()),
                model: None,
                git_branch: Some("main".to_string()),
                cwd: Some("/home/user/project".to_string()),
            },
            Message {
                id: Uuid::new_v4(),
                session_id,
                parent_id: None,
                index: 1,
                timestamp: Utc::now(),
                role: MessageRole::Assistant,
                content: MessageContent::Text("Done.".to_string()),
                model: Some("claude-opus".to_string()),
                git_branch: Some("main".to_string()),
                cwd: Some("/home/user/project".to_string()),
            },
        ];

        let links = vec![SessionLink {
            id: Uuid::new_v4(),
            session_id,
            link_type: LinkType::Commit,
            commit_sha: Some("abc123".to_string()),
            branch: Some("main".to_string()),
            remote: Some("origin".to_string()),
            created_at: Utc::now(),
            created_by: LinkCreator::User,
            confidence: Some(0.95),
        }];

        let tags = vec![Tag {
            id: Uuid::new_v4(),
            session_id,
            label: "bug-fix".to_string(),
            created_at: Utc::now(),
        }];

        let annotations = vec![Annotation {
            id: Uuid::new_v4(),
            session_id,
            content: "Important fix".to_string(),
            created_at: Utc::now(),
        }];

        let summary = Some(Summary {
            id: Uuid::new_v4(),
            session_id,
            content: "Fixed a bug in the parser".to_string(),
            generated_at: Utc::now(),
        });

        SessionRecord {
            session,
            messages,
            links,
            tags,
            annotations,
            summary,
        }
    }

    #[test]
    fn test_gzip_roundtrip() {
        let data = b"the quick brown fox jumps over the lazy dog".repeat(100);
        let compressed = gzip_compress(&data).unwrap();
        let decompressed = gzip_decompress(&compressed).unwrap();
        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_gzip_compresses_repetitive_data() {
        // Highly repetitive data should shrink under gzip.
        let data = vec![b'a'; 10_000];
        let compressed = gzip_compress(&data).unwrap();
        assert!(compressed.len() < data.len());
    }

    #[test]
    fn test_encrypt_decrypt_record_roundtrip() {
        let salt = generate_salt();
        let key = derive_key("test passphrase", &salt).unwrap();

        let record = sample_record();
        let blob = encrypt_session_record(&record, &key).unwrap();
        let restored = decrypt_session_record(&blob, &key).unwrap();

        assert_eq!(restored.session.id, record.session.id);
        assert_eq!(restored.messages.len(), record.messages.len());
        assert_eq!(restored.messages[0].content.text(), "Fix the bug");
        assert_eq!(restored.links.len(), 1);
        assert_eq!(restored.links[0].commit_sha, Some("abc123".to_string()));
        assert_eq!(restored.tags[0].label, "bug-fix");
        assert_eq!(restored.annotations[0].content, "Important fix");
        assert_eq!(
            restored.summary.unwrap().content,
            "Fixed a bug in the parser"
        );
    }

    #[test]
    fn test_full_record_serialization_preserves_all_fields() {
        // Serialize to JSON and back without the crypto layer to verify the
        // record type captures every part of the reasoning record.
        let record = sample_record();
        let json = serde_json::to_vec(&record).unwrap();
        let restored: SessionRecord = serde_json::from_slice(&json).unwrap();

        assert_eq!(restored.session.tool, "claude-code");
        assert_eq!(restored.messages.len(), 2);
        assert_eq!(restored.links.len(), 1);
        assert_eq!(restored.tags.len(), 1);
        assert_eq!(restored.annotations.len(), 1);
        assert!(restored.summary.is_some());
    }

    #[test]
    fn test_decrypt_record_wrong_key_fails() {
        let salt = generate_salt();
        let key = derive_key("passphrase1", &salt).unwrap();
        let wrong_key = derive_key("passphrase2", &salt).unwrap();

        let record = sample_record();
        let blob = encrypt_session_record(&record, &key).unwrap();

        let result = decrypt_session_record(&blob, &wrong_key);
        assert!(result.is_err());
    }

    #[test]
    fn test_debug_does_not_leak_plaintext() {
        // The manual Debug impl must not expose message content, annotation
        // text, or summary text, which would leak private reasoning into logs.
        let record = sample_record();
        let debug = format!("{record:?}");

        assert!(!debug.contains("Fix the bug"));
        assert!(!debug.contains("Important fix"));
        assert!(!debug.contains("Fixed a bug in the parser"));

        // It should still surface harmless metadata for diagnostics.
        assert!(debug.contains("SessionRecord"));
        assert!(debug.contains("claude-code"));
        assert!(debug.contains("message_count"));
        assert!(debug.contains("has_summary"));
    }

    /// Initializes a temp git repo for tests that cross the git blob boundary.
    ///
    /// Signing is irrelevant here (no commits are made), but identity is set for
    /// consistency with the gitref test helpers.
    fn init_test_repo(repo: &std::path::Path) {
        for args in [
            vec!["init", "-q"],
            vec!["config", "user.name", "Lore Test"],
            vec!["config", "user.email", "test@example.com"],
        ] {
            let status = std::process::Command::new("git")
                .current_dir(repo)
                .args(&args)
                .status()
                .expect("failed to spawn git");
            assert!(status.success(), "git {args:?} failed");
        }
    }

    #[test]
    fn test_cross_module_round_trip_through_git_blob() {
        use crate::sync::gitref;

        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        init_test_repo(repo);

        let salt = generate_salt();
        let key = derive_key("cross module passphrase", &salt).unwrap();

        let record = sample_record();
        let blob = encrypt_session_record(&record, &key).unwrap();

        // Cross the real git object boundary: hash-object then cat-file.
        let sha = gitref::write_blob(repo, &blob).unwrap();
        let read_back = gitref::read_blob(repo, &sha).unwrap();
        assert_eq!(read_back, blob, "git blob round-trip must be byte-exact");

        let restored = decrypt_session_record(&read_back, &key).unwrap();
        assert_eq!(restored.session.id, record.session.id);
        assert_eq!(restored.messages.len(), record.messages.len());
        assert_eq!(restored.messages[0].content.text(), "Fix the bug");
        assert_eq!(restored.links[0].commit_sha, Some("abc123".to_string()));
        assert_eq!(
            restored.summary.unwrap().content,
            "Fixed a bug in the parser"
        );
    }

    #[test]
    fn test_binary_blob_round_trip_through_git() {
        use crate::sync::gitref;

        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        init_test_repo(repo);

        // Bytes that would be mangled by trimming or a UTF-8 decode of cat-file
        // output: leading/trailing NUL, embedded newlines, and high-bit bytes.
        let fixture: Vec<u8> = vec![
            0x00, 0x0a, 0x0d, 0xff, 0x80, b'a', 0x00, 0x81, 0xfe, 0x0a, 0x20, 0x00,
        ];

        let sha = gitref::write_blob(repo, &fixture).unwrap();
        let read_back = gitref::read_blob(repo, &sha).unwrap();
        assert_eq!(read_back, fixture, "binary blob must survive byte-for-byte");
    }

    #[test]
    fn test_encrypt_decrypt_tombstones_roundtrip() {
        let salt = generate_salt();
        let key = derive_key("tombstone passphrase", &salt).unwrap();

        let tombstones = vec![
            Tombstone {
                child_id: Uuid::new_v4().to_string(),
                kind: "link".to_string(),
                session_id: Some(Uuid::new_v4().to_string()),
                deleted_at: Utc::now(),
            },
            Tombstone {
                child_id: Uuid::new_v4().to_string(),
                kind: "summary".to_string(),
                session_id: None,
                deleted_at: Utc::now(),
            },
        ];

        let blob = encrypt_tombstones(&tombstones, &key).unwrap();
        let restored = decrypt_tombstones(&blob, &key).unwrap();

        assert_eq!(restored, tombstones);
    }

    #[test]
    fn test_decrypt_tombstones_wrong_key_fails() {
        let salt = generate_salt();
        let key = derive_key("right", &salt).unwrap();
        let wrong = derive_key("wrong", &salt).unwrap();

        let tombstones = vec![Tombstone {
            child_id: Uuid::new_v4().to_string(),
            kind: "tag".to_string(),
            session_id: None,
            deleted_at: Utc::now(),
        }];
        let blob = encrypt_tombstones(&tombstones, &key).unwrap();

        assert!(decrypt_tombstones(&blob, &wrong).is_err());
    }

    #[test]
    fn test_record_with_no_summary() {
        let salt = generate_salt();
        let key = derive_key("passphrase", &salt).unwrap();

        let mut record = sample_record();
        record.summary = None;
        record.links.clear();
        record.tags.clear();
        record.annotations.clear();

        let blob = encrypt_session_record(&record, &key).unwrap();
        let restored = decrypt_session_record(&blob, &key).unwrap();

        assert!(restored.summary.is_none());
        assert!(restored.links.is_empty());
        assert!(restored.tags.is_empty());
        assert!(restored.annotations.is_empty());
    }
}