lore-cli 0.1.13

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
464
465
466
467
468
469
470
471
//! HTTP client for cloud API communication.
//!
//! Provides the `CloudClient` for interacting with the Lore cloud service,
//! including sync operations (push/pull) and status queries.

use chrono::{DateTime, Utc};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use std::time::Duration;

use super::{CloudError, DEFAULT_CLOUD_URL};

/// Timeout for establishing a connection (30 seconds).
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Timeout for the entire request including response (60 seconds).
const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);

/// Cloud API client for sync operations.
pub struct CloudClient {
    /// HTTP client instance.
    client: Client,
    /// Base URL of the cloud service.
    base_url: String,
    /// API key for authentication (if logged in).
    api_key: Option<String>,
}

impl CloudClient {
    /// Creates a new cloud client with the default URL.
    pub fn new() -> Self {
        Self {
            client: Self::build_client(),
            base_url: DEFAULT_CLOUD_URL.to_string(),
            api_key: None,
        }
    }

    /// Creates a new cloud client with a custom URL.
    pub fn with_url(base_url: &str) -> Self {
        Self {
            client: Self::build_client(),
            base_url: base_url.trim_end_matches('/').to_string(),
            api_key: None,
        }
    }

    /// Builds the HTTP client with configured timeouts.
    fn build_client() -> Client {
        Client::builder()
            .connect_timeout(CONNECT_TIMEOUT)
            .timeout(REQUEST_TIMEOUT)
            .build()
            .expect("Failed to build HTTP client")
    }

    /// Sets the API key for authentication.
    pub fn with_api_key(mut self, api_key: &str) -> Self {
        self.api_key = Some(api_key.to_string());
        self
    }

    /// Returns the configured base URL.
    #[allow(dead_code)]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Gets the sync status from the cloud service.
    ///
    /// Returns information about the user's sync state including session count,
    /// storage usage, and last sync time.
    pub fn status(&self) -> Result<SyncStatus, CloudError> {
        let api_key = self.api_key.as_ref().ok_or(CloudError::NotLoggedIn)?;

        let url = format!("{}/api/sync/status", self.base_url);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {api_key}"))
            .send()?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let message = response
                .text()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(CloudError::ServerError { status, message });
        }

        let body: ApiResponse<SyncStatus> = response.json()?;
        Ok(body.data)
    }

    /// Pushes sessions to the cloud service.
    ///
    /// Uploads encrypted session data to the cloud. Session metadata is stored
    /// unencrypted for display purposes, while message content is encrypted.
    pub fn push(&self, sessions: Vec<PushSession>) -> Result<PushResponse, CloudError> {
        let api_key = self.api_key.as_ref().ok_or(CloudError::NotLoggedIn)?;

        let url = format!("{}/api/sync/push", self.base_url);
        let payload = PushRequest { sessions };

        let response = self
            .client
            .post(&url)
            .header("Authorization", format!("Bearer {api_key}"))
            .json(&payload)
            .send()?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let message = response
                .text()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(CloudError::ServerError { status, message });
        }

        let body: ApiResponse<PushResponse> = response.json()?;
        Ok(body.data)
    }

    /// Pulls sessions from the cloud service.
    ///
    /// Downloads sessions that have been modified since the given timestamp.
    /// Session message content is encrypted and must be decrypted by the caller.
    pub fn pull(&self, since: Option<DateTime<Utc>>) -> Result<PullResponse, CloudError> {
        let api_key = self.api_key.as_ref().ok_or(CloudError::NotLoggedIn)?;

        let mut url = format!("{}/api/sync/pull", self.base_url);
        if let Some(since) = since {
            url = format!("{}?since={}", url, since.to_rfc3339());
        }

        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {api_key}"))
            .send()?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let message = response
                .text()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(CloudError::ServerError { status, message });
        }

        let body: ApiResponse<PullResponse> = response.json()?;
        Ok(body.data)
    }

    /// Gets the encryption salt from the cloud service.
    ///
    /// Returns the base64-encoded salt if set, or None if not yet configured.
    /// Returns Ok(None) for 404 responses (salt not set), Err for other failures.
    pub fn get_salt(&self) -> Result<Option<String>, CloudError> {
        let api_key = self.api_key.as_ref().ok_or(CloudError::NotLoggedIn)?;

        let url = format!("{}/api/sync/salt", self.base_url);
        let response = self
            .client
            .get(&url)
            .header("Authorization", format!("Bearer {api_key}"))
            .send()?;

        let status = response.status();
        if status.as_u16() == 404 {
            return Ok(None);
        }

        if !status.is_success() {
            let message = response
                .text()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(CloudError::ServerError {
                status: status.as_u16(),
                message,
            });
        }

        let body: ApiResponse<SaltResponse> = response.json()?;
        Ok(body.data.salt)
    }

    /// Sets the encryption salt on the cloud service.
    ///
    /// This should only be called once during initial setup. The server will
    /// reject attempts to overwrite an existing salt.
    pub fn set_salt(&self, salt: &str) -> Result<(), CloudError> {
        let api_key = self.api_key.as_ref().ok_or(CloudError::NotLoggedIn)?;

        let url = format!("{}/api/sync/salt", self.base_url);
        let response = self
            .client
            .put(&url)
            .header("Authorization", format!("Bearer {api_key}"))
            .json(&SaltRequest {
                salt: salt.to_string(),
            })
            .send()?;

        if !response.status().is_success() {
            let status = response.status().as_u16();
            let message = response
                .text()
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(CloudError::ServerError { status, message });
        }

        Ok(())
    }
}

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

// ==================== API Types ====================

/// Generic API response wrapper.
#[derive(Debug, Deserialize)]
pub struct ApiResponse<T> {
    /// The response data.
    pub data: T,
}

/// Sync status response from the cloud service.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncStatus {
    /// Number of sessions stored in the cloud.
    pub session_count: i64,

    /// Timestamp of the last sync operation.
    pub last_sync_at: Option<DateTime<Utc>>,

    /// Storage used in bytes.
    pub storage_used_bytes: i64,
}

/// Request payload for pushing sessions.
#[derive(Debug, Serialize)]
pub struct PushRequest {
    /// Sessions to push.
    pub sessions: Vec<PushSession>,
}

/// A session prepared for pushing to the cloud.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSession {
    /// Session UUID.
    pub id: String,

    /// Machine UUID that created this session.
    pub machine_id: String,

    /// Base64-encoded encrypted message data.
    pub encrypted_data: String,

    /// Unencrypted session metadata.
    pub metadata: SessionMetadata,

    /// When this session was last updated locally.
    pub updated_at: DateTime<Utc>,
}

/// Unencrypted session metadata for cloud display.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMetadata {
    /// Tool that created this session (e.g., "claude-code").
    pub tool_name: String,

    /// Working directory path.
    pub project_path: String,

    /// When the session started.
    pub started_at: DateTime<Utc>,

    /// When the session ended (if completed).
    pub ended_at: Option<DateTime<Utc>>,

    /// Number of messages in the session.
    pub message_count: i32,
}

/// Response from pushing sessions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushResponse {
    /// Number of sessions successfully synced.
    pub synced_count: i64,

    /// Server timestamp for recording sync time.
    pub server_time: DateTime<Utc>,
}

/// Response from getting the encryption salt.
#[derive(Debug, Clone, Deserialize)]
pub struct SaltResponse {
    /// The base64-encoded encryption salt, or None if not set.
    pub salt: Option<String>,
}

/// Request for setting the encryption salt.
#[derive(Debug, Clone, Serialize)]
pub struct SaltRequest {
    /// The base64-encoded encryption salt.
    pub salt: String,
}

/// Response from pulling sessions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PullResponse {
    /// Sessions to import.
    pub sessions: Vec<PullSession>,

    /// Server timestamp for recording sync time.
    pub server_time: DateTime<Utc>,
}

/// A session returned from the cloud for pulling.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PullSession {
    /// Session UUID.
    pub id: String,

    /// Machine UUID that created this session.
    pub machine_id: String,

    /// Base64-encoded encrypted message data.
    pub encrypted_data: String,

    /// Unencrypted session metadata.
    pub metadata: SessionMetadata,

    /// When this session was last updated on the server.
    pub updated_at: DateTime<Utc>,
}

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

    #[test]
    fn test_cloud_client_new() {
        let client = CloudClient::new();
        assert_eq!(client.base_url(), DEFAULT_CLOUD_URL);
    }

    #[test]
    fn test_cloud_client_with_url() {
        let client = CloudClient::with_url("https://custom.example.com/");
        assert_eq!(client.base_url(), "https://custom.example.com");
    }

    #[test]
    fn test_cloud_client_with_url_no_trailing_slash() {
        let client = CloudClient::with_url("https://custom.example.com");
        assert_eq!(client.base_url(), "https://custom.example.com");
    }

    #[test]
    fn test_cloud_client_with_api_key() {
        let client = CloudClient::new().with_api_key("test_key");
        assert_eq!(client.api_key, Some("test_key".to_string()));
    }

    #[test]
    fn test_sync_status_deserialize() {
        let json = r#"{
            "sessionCount": 42,
            "lastSyncAt": "2024-01-01T00:00:00Z",
            "storageUsedBytes": 1234567
        }"#;

        let status: SyncStatus = serde_json::from_str(json).unwrap();
        assert_eq!(status.session_count, 42);
        assert!(status.last_sync_at.is_some());
        assert_eq!(status.storage_used_bytes, 1234567);
    }

    #[test]
    fn test_sync_status_deserialize_null_last_sync() {
        let json = r#"{
            "sessionCount": 0,
            "lastSyncAt": null,
            "storageUsedBytes": 0
        }"#;

        let status: SyncStatus = serde_json::from_str(json).unwrap();
        assert_eq!(status.session_count, 0);
        assert!(status.last_sync_at.is_none());
    }

    #[test]
    fn test_push_session_serialize() {
        let session = PushSession {
            id: "550e8400-e29b-41d4-a716-446655440000".to_string(),
            machine_id: "machine-uuid".to_string(),
            encrypted_data: "base64encodeddata".to_string(),
            metadata: SessionMetadata {
                tool_name: "claude-code".to_string(),
                project_path: "/path/to/project".to_string(),
                started_at: Utc::now(),
                ended_at: None,
                message_count: 10,
            },
            updated_at: Utc::now(),
        };

        let json = serde_json::to_string(&session).unwrap();
        assert!(json.contains("encryptedData"));
        assert!(json.contains("toolName"));
        assert!(json.contains("projectPath"));
    }

    #[test]
    fn test_session_metadata_serialize() {
        let metadata = SessionMetadata {
            tool_name: "aider".to_string(),
            project_path: "/home/user/project".to_string(),
            started_at: DateTime::parse_from_rfc3339("2024-01-01T12:00:00Z")
                .unwrap()
                .with_timezone(&Utc),
            ended_at: Some(
                DateTime::parse_from_rfc3339("2024-01-01T13:00:00Z")
                    .unwrap()
                    .with_timezone(&Utc),
            ),
            message_count: 25,
        };

        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains("\"toolName\":\"aider\""));
        assert!(json.contains("\"messageCount\":25"));
    }

    #[test]
    fn test_api_response_deserialize() {
        let json = r#"{
            "data": {
                "sessionCount": 5,
                "lastSyncAt": null,
                "storageUsedBytes": 1000
            }
        }"#;

        let response: ApiResponse<SyncStatus> = serde_json::from_str(json).unwrap();
        assert_eq!(response.data.session_count, 5);
    }

    #[test]
    fn test_cloud_client_uses_timeouts() {
        assert_eq!(CONNECT_TIMEOUT.as_secs(), 30);
        assert_eq!(REQUEST_TIMEOUT.as_secs(), 60);

        let client = CloudClient::new();
        assert_eq!(client.base_url(), DEFAULT_CLOUD_URL);

        let client = CloudClient::with_url("https://example.com");
        assert_eq!(client.base_url(), "https://example.com");
    }
}