openlatch-client 0.1.14

The open-source security layer for AI agents — client forwarder
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
//! `openlatch doctor --restore` — reverse the last `--fix` run.
//!
//! Driven by the journal at `~/.openlatch/fix-journal.json`. Two
//! rollback strategies:
//!
//! - **Hook reinstalls** (`HookReinstall`): surgical merge on
//!   `~/.claude/settings.json`. We re-parse the live file, drop every
//!   entry tagged `_openlatch: true`, then re-insert the entries the
//!   `.bak` carried under the same marker. Any user edits to
//!   non-OpenLatch hook entries (or to other top-level keys) survive.
//! - **Everything else** (`ConfigRewrite`, `TokenRegenerate`,
//!   `AgentIdInsert`, `TelemetryReset`, `BinaryCopy`): blind file
//!   swap — copy the `.bak` back over the live path.
//!
//! `DaemonRestart` and `PidStaleRemove` are process-level actions and
//! are not reversible — they're logged but skipped.

use std::path::Path;

use crate::cli::commands::doctor_fix::{FixAction, FixKind, Journal};
use crate::cli::commands::lifecycle;
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::DoctorArgs;
use crate::config;
use crate::error::OlError;
use crate::hooks::jsonc;
use crate::telemetry::{self, Event};

/// Outcome of attempting to restore one [`FixAction`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RestoreOutcome {
    /// File was reverted from `.bak` (or surgically merged for hooks).
    Restored,
    /// Action skipped because it is not reversible (`DaemonRestart`,
    /// `PidStaleRemove`).
    NotReversible,
    /// `.bak` no longer exists on disk — nothing to restore from.
    BackupMissing,
    /// I/O error while restoring; the file was not touched.
    Failed(String),
}

/// Per-action result returned by [`restore_actions`].
#[derive(Debug, Clone)]
pub struct RestoreResult {
    pub action: FixAction,
    pub outcome: RestoreOutcome,
}

/// Entry point for `openlatch doctor --restore`.
///
/// Loads the journal from `<ol_dir>/fix-journal.json`, restores each
/// reversible action in reverse order, and prints a summary. If the
/// daemon is running it is stopped before file restores and restarted
/// afterwards (so the daemon never reads a half-restored config).
pub fn run(_args: &DoctorArgs, output: &OutputConfig) -> Result<(), OlError> {
    let started = std::time::Instant::now();
    let ol_dir = config::openlatch_dir();

    crate::cli::header::print(output, &["doctor", "--restore"]);
    if output.format == OutputFormat::Human && !output.quiet {
        eprintln!();
    }

    let journal = Journal::load(&ol_dir)?;

    if journal.actions.is_empty() {
        if output.format == OutputFormat::Json {
            output.print_json(&serde_json::json!({
                "command": "doctor_restore",
                "actions_reversed": 0,
                "results": [],
                "message": "no actions in last --fix run; nothing to restore",
            }));
        } else if !output.quiet {
            eprintln!("No actions in the last --fix run; nothing to restore.");
        }
        return Ok(());
    }

    // If the daemon is running, stop it before mutating any of its files.
    let port = config::Config::load(None, None, false)
        .map(|c| c.port)
        .unwrap_or(config::PORT_RANGE_START);
    let pid = lifecycle::read_pid_file();
    let daemon_was_running = pid.map(lifecycle::is_process_alive).unwrap_or(false);
    if daemon_was_running {
        stop_daemon(port, &ol_dir);
    }

    let results = restore_actions(&journal.actions, &ol_dir);

    // Restart the daemon if it was running (best-effort).
    let mut daemon_restart_required = daemon_was_running;
    if daemon_was_running {
        let token = std::fs::read_to_string(ol_dir.join("daemon.token"))
            .map(|s| s.trim().to_string())
            .unwrap_or_default();
        if !token.is_empty() {
            if let Ok(_pid) = lifecycle::spawn_daemon_background(port, &token) {
                if !lifecycle::wait_for_health(port, 3) {
                    daemon_restart_required = false; // surfaced via doctor checks
                    tracing::warn!(
                        "doctor --restore: daemon spawned but /health did not return 200 within 3s"
                    );
                }
            }
        }
    }

    let restored = results
        .iter()
        .filter(|r| matches!(r.outcome, RestoreOutcome::Restored))
        .count();
    let skipped = results.len() - restored;
    telemetry::capture_global(Event::doctor_restore_run(
        restored,
        skipped,
        daemon_restart_required,
        started.elapsed().as_millis() as u64,
    ));

    print_restore_results(&results, daemon_restart_required, output);
    Ok(())
}

/// Restore each reversible [`FixAction`] in reverse order.
///
/// Public so `doctor_fix::heal_daemon` can drive auto-rollback without
/// going through the journal-loading path.
pub fn restore_actions(actions: &[FixAction], _ol_dir: &Path) -> Vec<RestoreResult> {
    let mut results = Vec::with_capacity(actions.len());
    for action in actions.iter().rev() {
        let outcome = restore_one(action);
        results.push(RestoreResult {
            action: action.clone(),
            outcome,
        });
    }
    results
}

fn restore_one(action: &FixAction) -> RestoreOutcome {
    if !action.reversible {
        return RestoreOutcome::NotReversible;
    }
    let Some(backup) = action.backup.as_ref() else {
        return RestoreOutcome::NotReversible;
    };
    if !backup.exists() {
        return RestoreOutcome::BackupMissing;
    }

    match action.kind {
        FixKind::HookReinstall => match restore_hooks_surgical(&action.file, backup) {
            Ok(()) => RestoreOutcome::Restored,
            Err(e) => RestoreOutcome::Failed(format!("{}: {}", e.code, e.message)),
        },
        FixKind::ConfigRewrite
        | FixKind::TokenRegenerate
        | FixKind::AgentIdInsert
        | FixKind::TelemetryReset
        | FixKind::BinaryCopy => match std::fs::copy(backup, &action.file) {
            Ok(_) => RestoreOutcome::Restored,
            Err(e) => RestoreOutcome::Failed(e.to_string()),
        },
        FixKind::DaemonRestart | FixKind::PidStaleRemove | FixKind::SupervisionInstall => {
            RestoreOutcome::NotReversible
        }
    }
}

/// Surgically restore OpenLatch-owned hook entries from `bak_path` into
/// the live `settings.json` at `live_path`.
///
/// Algorithm:
/// 1. Drop every entry tagged `_openlatch: true` from the live file via
///    `jsonc::remove_owned_entries` (preserves comments, whitespace, and
///    every non-OpenLatch entry).
/// 2. Read the `.bak`, extract its `_openlatch: true` entries (one per
///    event type, by install_hooks's invariant).
/// 3. Re-insert those entries into the live string via
///    `jsonc::insert_hook_entries` (which appends to the right array,
///    creating it if needed).
///
/// This loses any hook-config edits a user made to OUR entries since
/// `--fix` ran, but preserves all edits to non-OpenLatch entries.
pub fn restore_hooks_surgical(live_path: &Path, bak_path: &Path) -> Result<(), OlError> {
    let live_raw = std::fs::read_to_string(live_path).unwrap_or_else(|_| "{}".to_string());
    let bak_raw = std::fs::read_to_string(bak_path).map_err(|e| {
        OlError::new(
            crate::error::ERR_HOOK_WRITE_FAILED,
            format!(
                "cannot read backup '{}' for hook restore: {e}",
                bak_path.display()
            ),
        )
    })?;

    let bak_value = jsonc::parse_settings_value(&bak_raw)?;
    let owned_entries = extract_owned_hook_entries(&bak_value);

    let live_no_owned = jsonc::remove_owned_entries(&live_raw)?;

    // If the .bak has no _openlatch entries (extremely unusual — the user
    // manually deleted them before --fix ran), we just write the cleaned
    // live string. The post-restore doctor pass will flag the missing
    // hooks and the user can re-init.
    let final_text = if owned_entries.is_empty() {
        live_no_owned
    } else {
        let (text, _) = jsonc::insert_hook_entries(&live_no_owned, &owned_entries)?;
        text
    };

    std::fs::write(live_path, final_text).map_err(|e| {
        OlError::new(
            crate::error::ERR_HOOK_WRITE_FAILED,
            format!(
                "cannot write restored settings.json '{}': {e}",
                live_path.display()
            ),
        )
    })?;
    Ok(())
}

/// Pull every `_openlatch: true` entry out of a parsed `settings.json`
/// value, paired with its event-type key (e.g. `"PreToolUse"`).
fn extract_owned_hook_entries(settings: &serde_json::Value) -> Vec<(String, serde_json::Value)> {
    let Some(hooks_obj) = settings.get("hooks").and_then(|v| v.as_object()) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for (event_type, arr) in hooks_obj {
        if let Some(entries) = arr.as_array() {
            for entry in entries {
                if entry.get("_openlatch").and_then(|v| v.as_bool()) == Some(true) {
                    out.push((event_type.clone(), entry.clone()));
                }
            }
        }
    }
    out
}

fn stop_daemon(port: u16, ol_dir: &Path) {
    let Some(pid) = lifecycle::read_pid_file() else {
        return;
    };
    let token = std::fs::read_to_string(ol_dir.join("daemon.token"))
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    if !token.is_empty() {
        let _ = lifecycle::send_shutdown_request(port, &token);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while std::time::Instant::now() < deadline && lifecycle::is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }
    if lifecycle::is_process_alive(pid) {
        lifecycle::force_kill(pid);
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
        while std::time::Instant::now() < deadline && lifecycle::is_process_alive(pid) {
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
    }
    let _ = std::fs::remove_file(ol_dir.join("daemon.pid"));
}

fn print_restore_results(
    results: &[RestoreResult],
    daemon_restart_required: bool,
    output: &OutputConfig,
) {
    let restored_count = results
        .iter()
        .filter(|r| matches!(r.outcome, RestoreOutcome::Restored))
        .count();
    let skipped_count = results
        .iter()
        .filter(|r| !matches!(r.outcome, RestoreOutcome::Restored))
        .count();

    if output.format == OutputFormat::Json {
        let results_json: Vec<serde_json::Value> = results
            .iter()
            .map(|r| {
                serde_json::json!({
                    "kind": r.action.kind,
                    "file": r.action.file.display().to_string(),
                    "outcome": format!("{:?}", r.outcome),
                })
            })
            .collect();
        output.print_json(&serde_json::json!({
            "command": "doctor_restore",
            "actions_reversed": restored_count,
            "actions_skipped": skipped_count,
            "daemon_restart_required": daemon_restart_required,
            "results": results_json,
        }));
        return;
    }

    if output.quiet {
        return;
    }

    for r in results {
        let label = match &r.outcome {
            RestoreOutcome::Restored => format!("restored {}", r.action.file.display()),
            RestoreOutcome::NotReversible => format!(
                "skipped {:?} (not reversible — {})",
                r.action.kind, r.action.note
            ),
            RestoreOutcome::BackupMissing => {
                format!(
                    "backup missing for {} — cannot restore",
                    r.action.file.display()
                )
            }
            RestoreOutcome::Failed(msg) => {
                format!("restore failed for {}: {msg}", r.action.file.display())
            }
        };
        eprintln!("{label}");
    }
    eprintln!();
    eprintln!(
        "Restored {restored_count} action{}, skipped {skipped_count}.",
        if restored_count == 1 { "" } else { "s" }
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::commands::doctor_fix::FixKind;
    use chrono::Utc;
    use serde_json::json;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn fixture_action(file: PathBuf, backup: Option<PathBuf>, kind: FixKind) -> FixAction {
        FixAction {
            ol_code: "OL-TEST".to_string(),
            kind,
            file,
            backup,
            reversible: true,
            applied_at: Utc::now(),
            note: "test".to_string(),
        }
    }

    #[test]
    fn test_restore_one_blind_swap_replaces_live_with_backup() {
        let tmp = TempDir::new().unwrap();
        let live = tmp.path().join("config.toml");
        let bak = tmp.path().join("config.toml.bak");
        std::fs::write(&live, "after = true").unwrap();
        std::fs::write(&bak, "before = true").unwrap();

        let action = fixture_action(live.clone(), Some(bak.clone()), FixKind::ConfigRewrite);
        let outcome = restore_one(&action);

        assert_eq!(outcome, RestoreOutcome::Restored);
        assert_eq!(std::fs::read_to_string(&live).unwrap(), "before = true");
    }

    #[test]
    fn test_restore_one_returns_backup_missing_when_bak_absent() {
        let tmp = TempDir::new().unwrap();
        let live = tmp.path().join("config.toml");
        let bak = tmp.path().join("config.toml.bak");
        std::fs::write(&live, "live").unwrap();
        // bak does NOT exist

        let action = fixture_action(live, Some(bak), FixKind::ConfigRewrite);
        let outcome = restore_one(&action);

        assert_eq!(outcome, RestoreOutcome::BackupMissing);
    }

    #[test]
    fn test_restore_one_skips_not_reversible_kinds() {
        let action = fixture_action(PathBuf::new(), None, FixKind::DaemonRestart);
        let outcome = restore_one(&action);
        assert_eq!(outcome, RestoreOutcome::NotReversible);
    }

    #[test]
    fn test_extract_owned_hook_entries_returns_only_marked_entries() {
        let v = json!({
            "hooks": {
                "PreToolUse": [
                    { "matcher": "Bash", "hooks": [] },
                    { "_openlatch": true, "matcher": "", "hooks": [] }
                ],
                "Stop": [
                    { "_openlatch": true, "hooks": [] }
                ]
            }
        });
        let owned = extract_owned_hook_entries(&v);
        assert_eq!(owned.len(), 2);
        let event_types: Vec<String> = owned.iter().map(|(k, _)| k.clone()).collect();
        assert!(event_types.contains(&"PreToolUse".to_string()));
        assert!(event_types.contains(&"Stop".to_string()));
    }

    #[test]
    fn test_restore_hooks_surgical_preserves_user_hooks_and_replaces_owned() {
        let tmp = TempDir::new().unwrap();
        let live = tmp.path().join("settings.json");
        let bak = tmp.path().join("settings.json.bak");

        // Live: user added their own hook AND modified our entry to bad URL.
        let live_raw = r#"{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [{ "type": "command", "command": "echo hi" }] },
      { "_openlatch": true, "matcher": "", "hooks": [{ "type": "http", "url": "http://wrong:9999/" }] }
    ]
  }
}"#;
        // Backup: our original install with the correct URL.
        let bak_raw = r#"{
  "hooks": {
    "PreToolUse": [
      { "_openlatch": true, "matcher": "", "hooks": [{ "type": "http", "url": "http://localhost:7443/" }] }
    ]
  }
}"#;
        std::fs::write(&live, live_raw).unwrap();
        std::fs::write(&bak, bak_raw).unwrap();

        restore_hooks_surgical(&live, &bak).expect("restore must succeed");

        let result_raw = std::fs::read_to_string(&live).unwrap();
        // The user's non-OpenLatch hook must survive.
        assert!(
            result_raw.contains("echo hi"),
            "user hook lost: {result_raw}"
        );
        // The OpenLatch entry must point at the correct URL again.
        assert!(
            result_raw.contains("http://localhost:7443/"),
            "owned entry not restored: {result_raw}"
        );
        assert!(
            !result_raw.contains("http://wrong:9999/"),
            "old entry leaked through: {result_raw}"
        );
    }

    #[test]
    fn test_restore_hooks_surgical_drops_owned_when_bak_has_none() {
        let tmp = TempDir::new().unwrap();
        let live = tmp.path().join("settings.json");
        let bak = tmp.path().join("settings.json.bak");

        std::fs::write(
            &live,
            r#"{
  "hooks": {
    "PreToolUse": [
      { "_openlatch": true, "matcher": "", "hooks": [] }
    ]
  }
}"#,
        )
        .unwrap();
        std::fs::write(&bak, r#"{ "hooks": {} }"#).unwrap();

        restore_hooks_surgical(&live, &bak).expect("restore must succeed");

        let result_raw = std::fs::read_to_string(&live).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&result_raw).unwrap();
        let arr = parsed["hooks"]["PreToolUse"].as_array();
        // Either the array is now empty or the key is gone; both are acceptable.
        assert!(
            arr.map(|a| a.is_empty()).unwrap_or(true),
            "owned entry survived removal: {result_raw}"
        );
    }

    #[test]
    fn test_restore_actions_iterates_in_reverse_order() {
        let tmp = TempDir::new().unwrap();
        let actions = vec![
            fixture_action(
                tmp.path().join("a"),
                Some(tmp.path().join("a.bak")),
                FixKind::ConfigRewrite,
            ),
            fixture_action(
                tmp.path().join("b"),
                Some(tmp.path().join("b.bak")),
                FixKind::ConfigRewrite,
            ),
        ];
        std::fs::write(tmp.path().join("a.bak"), "A").unwrap();
        std::fs::write(tmp.path().join("b.bak"), "B").unwrap();
        std::fs::write(tmp.path().join("a"), "X").unwrap();
        std::fs::write(tmp.path().join("b"), "X").unwrap();

        let results = restore_actions(&actions, tmp.path());
        // Reverse order: b first, then a
        assert_eq!(results.len(), 2);
        assert!(results[0].action.file.ends_with("b"));
        assert!(results[1].action.file.ends_with("a"));
        assert_eq!(std::fs::read_to_string(tmp.path().join("a")).unwrap(), "A");
        assert_eq!(std::fs::read_to_string(tmp.path().join("b")).unwrap(), "B");
    }
}