forked from OpenCoven/coven-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsettings_sync.rs
More file actions
599 lines (525 loc) · 21.3 KB
/
Copy pathsettings_sync.rs
File metadata and controls
599 lines (525 loc) · 21.3 KB
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
595
596
597
598
599
// settings_sync.rs — Settings Sync
//
// Port of src/services/settingsSync/index.ts
//
// Syncs user settings and AGENTS.md memory files between a local Coven Code
// installation and claude.ai via:
// - Upload (interactive CLI, fire-and-forget at startup)
// - Download (CCR / COVEN_CODE_REMOTE=1, blocking before plugin load)
//
// Authentication requires OAuth (Bearer token). API-key-only users are
// skipped silently — the TypeScript side gates on `isUsingOAuth()`.
//
// The sync API stores a flat key→value map where keys are canonical file paths
// and values are the UTF-8 file contents (JSON or Markdown).
use crate::hosted_review::{hosted_project_id, HostedReviewScope};
use crate::team_memory_sync::scan_for_secrets;
use anyhow::Result;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use tracing::{debug, warn};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const SYNC_TIMEOUT_SECS: u64 = 10;
#[allow(dead_code)]
const DEFAULT_MAX_RETRIES: u32 = 3;
/// 500 KB per-file size limit (matches backend enforcement).
const MAX_FILE_SIZE_BYTES: u64 = 500 * 1024;
// ---------------------------------------------------------------------------
// Sync key helpers (mirrors SYNC_KEYS in types.ts)
// ---------------------------------------------------------------------------
/// Canonical sync key for the global user settings file.
pub const SYNC_KEY_USER_SETTINGS: &str = "~/.coven-code/settings.json";
/// Canonical sync key for the global user memory file.
pub const SYNC_KEY_USER_MEMORY: &str = "~/.coven-code/AGENTS.md";
/// Canonical sync key for per-project settings (keyed by git-remote hash).
pub fn sync_key_project_settings(project_id: &str) -> String {
format!("projects/{project_id}/.coven-code/settings.local.json")
}
/// Canonical sync key for per-project memory (keyed by git-remote hash).
pub fn sync_key_project_memory(project_id: &str) -> String {
format!("projects/{project_id}/AGENTS.local.md")
}
/// Canonical hosted project settings key. The project id is derived from
/// tenant, installation, and repo id rather than accepted from a caller.
pub fn sync_key_hosted_project_settings(scope: &HostedReviewScope) -> String {
sync_key_project_settings(&hosted_project_id(scope))
}
/// Canonical hosted project memory key. The project id is derived from
/// tenant, installation, and repo id rather than accepted from a caller.
pub fn sync_key_hosted_project_memory(scope: &HostedReviewScope) -> String {
sync_key_project_memory(&hosted_project_id(scope))
}
// ---------------------------------------------------------------------------
// API wire types
// ---------------------------------------------------------------------------
/// Content field in the GET response — flat string key/value map.
#[derive(Debug, Deserialize)]
struct UserSyncContent {
entries: HashMap<String, String>,
}
/// Full GET /api/claude_code/user_settings response.
#[derive(Debug, Deserialize)]
struct UserSyncData {
#[allow(dead_code)]
#[serde(rename = "userId")]
user_id: Option<String>,
#[allow(dead_code)]
version: Option<u64>,
#[allow(dead_code)]
#[serde(rename = "lastModified")]
last_modified: Option<String>,
#[allow(dead_code)]
checksum: Option<String>,
content: UserSyncContent,
}
/// PUT response (partial — only fields we care about).
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct UploadResponse {
checksum: Option<String>,
#[serde(rename = "lastModified")]
last_modified: Option<String>,
}
// ---------------------------------------------------------------------------
// Public output types
// ---------------------------------------------------------------------------
/// Data returned by a successful download.
#[derive(Debug, Clone, Default)]
pub struct SyncedData {
/// Parsed user settings JSON (if the `user_settings` key was present).
pub settings: Option<Value>,
/// Raw file contents keyed by their sync keys.
pub memory_files: HashMap<String, String>,
}
// ---------------------------------------------------------------------------
// SettingsSyncManager
// ---------------------------------------------------------------------------
/// Manages uploading and downloading settings/memory files to/from claude.ai.
pub struct SettingsSyncManager {
/// OAuth bearer token for authentication.
pub oauth_token: String,
/// Base API URL (default: https://api.anthropic.com).
pub base_url: String,
http: reqwest::Client,
}
impl SettingsSyncManager {
/// Create a new manager.
pub fn new(oauth_token: String, base_url: String) -> Self {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(SYNC_TIMEOUT_SECS))
.build()
.unwrap_or_default();
Self {
oauth_token,
base_url,
http,
}
}
fn endpoint(&self) -> String {
format!("{}/api/claude_code/user_settings", self.base_url)
}
#[allow(dead_code)]
fn auth_headers(&self) -> [(&'static str, String); 2] {
[
("Authorization", format!("Bearer {}", self.oauth_token)),
("anthropic-beta", "oauth-2025-04-20".to_string()),
]
}
// -----------------------------------------------------------------------
// Download
// -----------------------------------------------------------------------
/// Download remote settings and memory files.
///
/// Returns `Ok(None)` when the server has no data for this user (404).
/// Fails open — callers should treat errors as "no remote data".
pub async fn download(&self) -> Result<Option<SyncedData>> {
let resp = self
.http
.get(self.endpoint())
.header("Authorization", format!("Bearer {}", self.oauth_token))
.header("anthropic-beta", "oauth-2025-04-20")
.send()
.await?;
let status = resp.status().as_u16();
if status == 404 {
debug!("Settings sync: no remote data (404)");
return Ok(None);
}
if status != 200 {
anyhow::bail!("Settings sync download: unexpected status {}", status);
}
let data: UserSyncData = resp.json().await?;
Ok(Some(entries_to_synced_data(data.content.entries)))
}
/// Download with exponential-backoff retry.
#[allow(dead_code)]
async fn download_with_retry(&self) -> Result<Option<SyncedData>> {
let mut last_err = anyhow::anyhow!("No attempts made");
for attempt in 1..=(DEFAULT_MAX_RETRIES + 1) {
match self.download().await {
Ok(v) => return Ok(v),
Err(e) => {
let msg = e.to_string();
// Auth failures are terminal
if msg.contains("401") || msg.contains("403") {
return Err(e);
}
warn!(
attempt,
max = DEFAULT_MAX_RETRIES,
error = %e,
"Settings sync download failed, will retry"
);
last_err = e;
if attempt <= DEFAULT_MAX_RETRIES {
tokio::time::sleep(retry_delay(attempt)).await;
}
}
}
}
Err(last_err)
}
/// Apply downloaded entries to local files.
///
/// Writes settings and memory files to the appropriate local paths,
/// enforcing the 500 KB per-file size limit.
pub async fn apply_to_local(&self, data: &SyncedData, project_id: Option<&str>) -> ApplyResult {
let mut result = ApplyResult::default();
// Global user settings
if let Some(ref settings_json) = data.settings {
let path = claude_config_dir().join("settings.json");
let content = serde_json::to_string_pretty(settings_json).unwrap_or_default();
match write_file_for_sync(&path, &content).await {
Ok(()) => {
result.settings_written = true;
result.applied_count += 1;
}
Err(e) => warn!("Settings sync: failed to write user settings: {}", e),
}
}
// Global user memory
if let Some(memory) = data.memory_files.get(SYNC_KEY_USER_MEMORY) {
let path = claude_config_dir().join("AGENTS.md");
match write_file_for_sync(&path, memory).await {
Ok(()) => {
result.memory_written = true;
result.applied_count += 1;
}
Err(e) => warn!("Settings sync: failed to write user memory: {}", e),
}
}
// Project-specific files
if let Some(pid) = project_id {
let proj_settings_key = sync_key_project_settings(pid);
if let Some(content) = data.memory_files.get(&proj_settings_key) {
let path = std::env::current_dir()
.unwrap_or_default()
.join(".coven-code")
.join("settings.local.json");
match write_file_for_sync(&path, content).await {
Ok(()) => {
result.settings_written = true;
result.applied_count += 1;
}
Err(e) => {
warn!("Settings sync: failed to write project settings: {}", e)
}
}
}
let proj_memory_key = sync_key_project_memory(pid);
if let Some(content) = data.memory_files.get(&proj_memory_key) {
let path = std::env::current_dir()
.unwrap_or_default()
.join("AGENTS.local.md");
match write_file_for_sync(&path, content).await {
Ok(()) => {
result.memory_written = true;
result.applied_count += 1;
}
Err(e) => {
warn!("Settings sync: failed to write project memory: {}", e)
}
}
}
}
result
}
// -----------------------------------------------------------------------
// Upload
// -----------------------------------------------------------------------
/// Upload local settings and memory files to remote.
///
/// Compares with existing remote entries and only uploads changed keys.
pub async fn upload(&self, local_entries: HashMap<String, String>) -> Result<()> {
let local_entries = filter_entries_with_secrets(local_entries, "Settings sync");
// Fetch current remote state for diff
let remote_entries = match self.download().await? {
Some(data) => data.memory_files,
None => HashMap::new(),
};
// Only send keys that have changed
let changed: HashMap<String, String> = local_entries
.into_iter()
.filter(|(k, v)| remote_entries.get(k).map(|rv| rv != v).unwrap_or(true))
.collect();
if changed.is_empty() {
debug!("Settings sync: no changes to upload");
return Ok(());
}
debug!(
count = changed.len(),
"Settings sync: uploading changed entries"
);
self.put_entries(changed).await
}
async fn put_entries(&self, entries: HashMap<String, String>) -> Result<()> {
let body = serde_json::json!({ "entries": entries });
let resp = self
.http
.put(self.endpoint())
.header("Authorization", format!("Bearer {}", self.oauth_token))
.header("anthropic-beta", "oauth-2025-04-20")
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
let status = resp.status().as_u16();
if !(200..300).contains(&status) {
anyhow::bail!("Settings sync upload: unexpected status {}", status);
}
Ok(())
}
// -----------------------------------------------------------------------
// Fire-and-forget background upload (called from startup)
// -----------------------------------------------------------------------
/// Spawn a fire-and-forget upload task. Errors are logged but not propagated.
///
/// Call this right after auth is established. The task will:
/// 1. Read local settings and AGENTS.md files
/// 2. Fetch current remote state for diffing
/// 3. Upload only changed entries
pub fn upload_in_background(token: String, base_url: String) {
tokio::spawn(async move {
let mgr = SettingsSyncManager::new(token, base_url);
let entries = collect_local_entries(None).await;
if let Err(e) = mgr.upload(entries).await {
warn!("Settings sync: background upload failed: {}", e);
}
});
}
}
fn filter_entries_with_secrets(
entries: HashMap<String, String>,
context: &str,
) -> HashMap<String, String> {
entries
.into_iter()
.filter_map(|(key, value)| {
let secrets = scan_for_secrets(&value);
if secrets.is_empty() {
return Some((key, value));
}
let labels: Vec<&str> = secrets.iter().map(|m| m.label.as_str()).collect();
warn!(
"{}: blocking {:?} from upload: detected {} ({} secret pattern(s))",
context,
key,
labels.join(", "),
labels.len(),
);
None
})
.collect()
}
// ---------------------------------------------------------------------------
// Apply result
// ---------------------------------------------------------------------------
/// Summary of what `apply_to_local` wrote.
#[derive(Debug, Default)]
pub struct ApplyResult {
pub applied_count: usize,
pub settings_written: bool,
pub memory_written: bool,
}
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
/// Convert raw sync entries into the `SyncedData` structure.
///
/// The user settings entry is parsed as JSON; memory files are kept as-is.
fn entries_to_synced_data(entries: HashMap<String, String>) -> SyncedData {
let mut data = SyncedData::default();
for (key, value) in entries {
if key == SYNC_KEY_USER_SETTINGS {
data.settings = serde_json::from_str(&value).ok();
} else {
data.memory_files.insert(key, value);
}
}
data
}
/// Collect local files that should be uploaded.
///
/// Reads global user settings and AGENTS.md, plus (if `project_id` is given)
/// project-local settings and AGENTS.local.md. Files larger than 500 KB or
/// that cannot be read are silently omitted.
pub async fn collect_local_entries(project_id: Option<&str>) -> HashMap<String, String> {
let mut entries = HashMap::new();
// Global user settings
let settings_path = claude_config_dir().join("settings.json");
if let Some(content) = try_read_for_sync(&settings_path).await {
entries.insert(SYNC_KEY_USER_SETTINGS.to_string(), content);
}
// Global user memory
let memory_path = claude_config_dir().join("AGENTS.md");
if let Some(content) = try_read_for_sync(&memory_path).await {
entries.insert(SYNC_KEY_USER_MEMORY.to_string(), content);
}
// Project-specific files
if let Some(pid) = project_id {
let cwd = std::env::current_dir().unwrap_or_default();
let local_settings = cwd.join(".coven-code").join("settings.local.json");
if let Some(content) = try_read_for_sync(&local_settings).await {
entries.insert(sync_key_project_settings(pid), content);
}
let local_memory = cwd.join("AGENTS.local.md");
if let Some(content) = try_read_for_sync(&local_memory).await {
entries.insert(sync_key_project_memory(pid), content);
}
}
entries
}
pub async fn collect_hosted_entries(scope: &HostedReviewScope) -> HashMap<String, String> {
let project_id = hosted_project_id(scope);
collect_local_entries(Some(&project_id)).await
}
/// Try to read a file, applying the 500 KB size limit.
/// Returns `None` if the file doesn't exist, is empty, or exceeds the limit.
async fn try_read_for_sync(path: &PathBuf) -> Option<String> {
let meta = tokio::fs::metadata(path).await.ok()?;
if meta.len() > MAX_FILE_SIZE_BYTES {
debug!(path = %path.display(), "Settings sync: file exceeds 500 KB limit, skipping");
return None;
}
let content = tokio::fs::read_to_string(path).await.ok()?;
if content.trim().is_empty() {
return None;
}
Some(content)
}
/// Write `content` to `path`, creating parent directories as needed.
async fn write_file_for_sync(path: &PathBuf, content: &str) -> Result<()> {
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
tokio::fs::write(path, content).await?;
Ok(())
}
/// Return the ~/.coven-code directory.
fn claude_config_dir() -> PathBuf {
dirs::home_dir()
.map(|h| h.join(".coven-code"))
.unwrap_or_else(|| PathBuf::from(".coven-code"))
}
/// Exponential backoff delay for retry attempt `n` (1-indexed), capped at 30 s.
#[allow(dead_code)]
fn retry_delay(attempt: u32) -> Duration {
let shift = attempt.saturating_sub(1).min(30);
let secs: u64 = 1u64.checked_shl(shift).unwrap_or(u64::MAX).min(30);
Duration::from_secs(secs)
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_sync_keys() {
assert_eq!(SYNC_KEY_USER_SETTINGS, "~/.coven-code/settings.json");
assert_eq!(SYNC_KEY_USER_MEMORY, "~/.coven-code/AGENTS.md");
assert_eq!(
sync_key_project_settings("abc123"),
"projects/abc123/.coven-code/settings.local.json"
);
assert_eq!(
sync_key_project_memory("abc123"),
"projects/abc123/AGENTS.local.md"
);
}
#[test]
fn hosted_sync_keys_derive_project_id_from_scope() {
let scope = HostedReviewScope::new(
"tenant-a".to_string(),
"install-1".to_string(),
"repo-99".to_string(),
"OpenCoven/coven-code".to_string(),
);
assert_eq!(
sync_key_hosted_project_settings(&scope),
"projects/hosted-tenant-tenant-a-installation-install-1-repo-repo-99/.coven-code/settings.local.json"
);
assert_eq!(
sync_key_hosted_project_memory(&scope),
"projects/hosted-tenant-tenant-a-installation-install-1-repo-repo-99/AGENTS.local.md"
);
}
#[test]
fn test_entries_to_synced_data_settings_parsed() {
let mut entries = HashMap::new();
entries.insert(
SYNC_KEY_USER_SETTINGS.to_string(),
r#"{"model":"claude-3"}"#.to_string(),
);
entries.insert(SYNC_KEY_USER_MEMORY.to_string(), "# My notes".to_string());
let data = entries_to_synced_data(entries);
assert!(data.settings.is_some());
assert_eq!(data.settings.unwrap()["model"], json!("claude-3"));
assert_eq!(
data.memory_files.get(SYNC_KEY_USER_MEMORY).unwrap(),
"# My notes"
);
}
#[test]
fn test_entries_to_synced_data_invalid_json_settings() {
let mut entries = HashMap::new();
entries.insert(SYNC_KEY_USER_SETTINGS.to_string(), "not-json".to_string());
let data = entries_to_synced_data(entries);
// Malformed settings JSON → field is None (graceful degradation)
assert!(data.settings.is_none());
}
#[test]
fn test_entries_to_synced_data_empty() {
let data = entries_to_synced_data(HashMap::new());
assert!(data.settings.is_none());
assert!(data.memory_files.is_empty());
}
#[test]
fn filter_entries_with_secrets_blocks_secret_values() {
let mut entries = HashMap::new();
let secret = format!("ghp_{}", "A".repeat(36));
entries.insert(SYNC_KEY_USER_MEMORY.to_string(), format!("token={secret}"));
entries.insert("safe.md".to_string(), "# Safe".to_string());
let filtered = filter_entries_with_secrets(entries, "test");
assert!(filtered.contains_key("safe.md"));
assert!(!filtered.contains_key(SYNC_KEY_USER_MEMORY));
assert!(!filtered.values().any(|value| value.contains(&secret)));
}
#[test]
fn test_retry_delay_progression() {
assert_eq!(retry_delay(1), Duration::from_secs(1));
assert_eq!(retry_delay(2), Duration::from_secs(2));
assert_eq!(retry_delay(3), Duration::from_secs(4));
assert_eq!(retry_delay(4), Duration::from_secs(8));
assert_eq!(retry_delay(5), Duration::from_secs(16));
// Capped at 30 s
assert_eq!(retry_delay(6), Duration::from_secs(30));
assert_eq!(retry_delay(10), Duration::from_secs(30));
}
}