openlatch-client 0.1.12

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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
//! `openlatch doctor --fix` — auto-heal common issues.
//!
//! Step 4 lands `heal_state` (config.toml, daemon.token, agent_id,
//! telemetry.json, daemon.pid). Steps 5–6 layer in `heal_hooks`,
//! `heal_binaries`, and `heal_daemon` (with auto-rollback on restart
//! failure). Each mutation writes a `.bak` sibling and appends a
//! `FixAction` to a journal at `~/.openlatch/fix-journal.json` so
//! `--restore` can reverse it.

use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::cli::commands::doctor::{print_diagnostic_results, run_all_checks, DoctorReport};
use crate::cli::commands::{doctor_restore, lifecycle};
use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::DoctorArgs;
use crate::config;
use crate::error::OlError;
use crate::hooks;
use crate::telemetry::{self, Event};

/// Filename of the per-run journal stored under the openlatch state dir.
pub(crate) const JOURNAL_FILENAME: &str = "fix-journal.json";

/// Categories of self-heal action recorded in the journal.
///
/// Used by `--restore` to dispatch the correct rollback strategy
/// (surgical merge for hooks, blind file swap for everything else,
/// process actions are not reversed).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum FixKind {
    /// `config.toml` rewritten from defaults (parse failure or missing).
    ConfigRewrite,
    /// `daemon.token` regenerated (missing or empty).
    TokenRegenerate,
    /// `[daemon] agent_id` inserted into `config.toml`.
    AgentIdInsert,
    /// `telemetry.json` reset to a safe default after a parse failure.
    TelemetryReset,
    /// Stale `daemon.pid` removed (PID no longer alive).
    PidStaleRemove,
    /// Hook entries rewritten in the agent's `settings.json`.
    HookReinstall,
    /// Daemon process cycled (stop → restart). Not reversible by `--restore`.
    DaemonRestart,
    /// `~/.openlatch/bin/openlatch-hook` re-staged from the resolved source.
    BinaryCopy,
    /// OS-native supervisor (launchd / systemd-user / Task Scheduler) reinstalled
    /// because config said `mode=active` but the OS artifact was missing. Not
    /// reversible by `--restore` — rerun `openlatch supervision uninstall` to undo.
    SupervisionInstall,
}

/// One self-heal action recorded in the journal.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FixAction {
    /// OL-XXXX code that motivated the fix (matches the diagnostic check).
    pub ol_code: String,
    /// What kind of mutation was performed.
    pub kind: FixKind,
    /// Path that was mutated (for rollback) or `""` for process actions.
    pub file: PathBuf,
    /// Path to the `.bak` sibling created before the mutation, if any.
    pub backup: Option<PathBuf>,
    /// Whether `--restore` can reverse this action.
    pub reversible: bool,
    /// UTC timestamp when the action was applied.
    pub applied_at: DateTime<Utc>,
    /// Human-readable note shown in the summary output.
    pub note: String,
}

/// The journal of fixes applied during a single `--fix` invocation.
///
/// Serialized to `~/.openlatch/fix-journal.json` at the end of every
/// `--fix` run (overwriting any prior journal). `--restore` reads this
/// file to reverse the most recent run's actions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Journal {
    /// Per-run identifier (UUIDv4 simple) for telemetry/log correlation.
    pub run_id: String,
    /// UTC timestamp of when the run began.
    pub started_at: DateTime<Utc>,
    /// Ordered list of fixes applied during this run.
    pub actions: Vec<FixAction>,
}

impl Journal {
    /// Start a fresh journal with a new `run_id`.
    pub fn new() -> Self {
        Self {
            run_id: uuid::Uuid::new_v4().simple().to_string(),
            started_at: Utc::now(),
            actions: Vec::new(),
        }
    }

    /// Persist the journal to `<ol_dir>/fix-journal.json`.
    ///
    /// Overwrites any prior journal — `--restore` only ever reverses the
    /// most recent run.
    pub fn save(&self, ol_dir: &Path) -> Result<PathBuf, OlError> {
        let path = ol_dir.join(JOURNAL_FILENAME);
        let raw = serde_json::to_string_pretty(self).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("cannot serialize fix journal: {e}"),
            )
        })?;
        std::fs::write(&path, raw).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("cannot write fix journal '{}': {e}", path.display()),
            )
        })?;
        Ok(path)
    }

    /// Read the journal from `<ol_dir>/fix-journal.json`.
    ///
    /// Returns `OL-1801` if the file is absent (no prior `--fix` to
    /// reverse) and `OL-1800` if it exists but cannot be parsed.
    pub fn load(ol_dir: &Path) -> Result<Self, OlError> {
        let path = ol_dir.join(JOURNAL_FILENAME);
        let raw = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Err(OlError::new(
                    crate::error::ERR_DOCTOR_RESTORE_NO_JOURNAL,
                    format!("no prior --fix run found at '{}'", path.display()),
                )
                .with_suggestion(
                    "Run `openlatch doctor --fix` first; --restore reverses the most recent run.",
                ));
            }
            Err(e) => {
                return Err(OlError::new(
                    crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                    format!("cannot read fix journal '{}': {e}", path.display()),
                ))
            }
        };
        serde_json::from_str(&raw).map_err(|e| {
            OlError::new(
                crate::error::ERR_DOCTOR_JOURNAL_CORRUPT,
                format!("fix journal at '{}' is malformed: {e}", path.display()),
            )
            .with_suggestion(
                "Delete `fix-journal.json` and re-run `openlatch init` to reset state.",
            )
        })
    }
}

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

/// Entry point for `openlatch doctor --fix`.
///
/// Pre-fix: snapshot diagnostic checks (best-effort — a totally broken
/// install may not even pass `Config::load`, in which case the snapshot
/// is `None` and the report only shows post-fix state).
///
/// Heal: state → (steps 5+: hooks, binaries, daemon).
///
/// Post-fix: re-run all diagnostic checks. Exit 0 if all pass; 1 if any
/// remain failing (lists the unfixable OL-XXXX codes in the output).
pub fn run(_args: &DoctorArgs, output: &OutputConfig) -> Result<(), OlError> {
    let started = std::time::Instant::now();
    let ol_dir = config::openlatch_dir();
    // Ensure the directory exists before any heal step touches it; without
    // this a brand-new install would error out on the first `.bak` write.
    std::fs::create_dir_all(&ol_dir).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!("cannot create openlatch dir '{}': {e}", ol_dir.display()),
        )
    })?;

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

    // Pre-fix snapshot — best-effort. A corrupt config.toml may make
    // run_all_checks itself error; that's expected and the fix run still
    // proceeds (heal_state will rewrite the bad config).
    let before = run_all_checks(output).ok();

    let pre_fix = capture_pre_fix_state(&ol_dir);
    let mut journal = Journal::new();

    // Stop the daemon before mutating files so it cannot reload a
    // half-written config. We only attempt a restart if it was running
    // before, OR if a fix touched config/token/hooks/binaries.
    if pre_fix.was_running {
        stop_daemon_for_fix(&pre_fix, &ol_dir);
    }

    journal.actions.extend(heal_state(&ol_dir));
    // Hooks and binaries depend on a healed config + token, so they run
    // after heal_state. heal_hooks no-ops when no agent is detected.
    journal.actions.extend(heal_binaries(&ol_dir));
    journal.actions.extend(heal_hooks(&ol_dir));
    journal.actions.extend(heal_supervision(&ol_dir));

    let mut auto_rollback_triggered = false;
    let (daemon_actions, restart_failed) = heal_daemon(&ol_dir, &pre_fix, &journal.actions);
    journal.actions.extend(daemon_actions);

    if restart_failed {
        auto_rollback_triggered = true;
        tracing::error!("doctor --fix: daemon restart failed — rolling back this run's actions");
        // Best-effort rollback. If this also fails the user is no worse
        // off than they would have been after a manual `--restore`.
        let _ = doctor_restore::restore_actions(&journal.actions, &ol_dir);
        if pre_fix.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() {
                let _ = lifecycle::spawn_daemon_background(pre_fix.port, &token);
            }
        }
    }

    // Persist the journal even when zero actions were taken — that way
    // `--restore` can give a precise "nothing to reverse" message instead
    // of falling through to OL-1801 ("no prior --fix").
    let journal_path = journal.save(&ol_dir)?;

    let after = run_all_checks(output)?;

    let categories: Vec<&str> = {
        let mut cats: Vec<&str> = Vec::new();
        for a in &journal.actions {
            let cat = match a.kind {
                FixKind::ConfigRewrite
                | FixKind::TokenRegenerate
                | FixKind::AgentIdInsert
                | FixKind::TelemetryReset
                | FixKind::PidStaleRemove => "state",
                FixKind::HookReinstall => "hooks",
                FixKind::DaemonRestart => "daemon",
                FixKind::BinaryCopy => "binary",
                FixKind::SupervisionInstall => "supervision",
            };
            if !cats.contains(&cat) {
                cats.push(cat);
            }
        }
        cats
    };
    let unfixable: Vec<&str> = after
        .checks
        .iter()
        .filter(|c| !c.pass)
        .map(|c| c.message.as_str())
        .collect();
    let (before_pass, before_fail) = before
        .as_ref()
        .map(|r| (r.checks.iter().filter(|c| c.pass).count(), r.fail_count()))
        .unwrap_or((0, 0));
    telemetry::capture_global(Event::doctor_fix_run(
        categories,
        before_pass,
        before_fail,
        after.checks.iter().filter(|c| c.pass).count(),
        after.fail_count(),
        unfixable,
        started.elapsed().as_millis() as u64,
        auto_rollback_triggered,
    ));

    print_fix_results(
        &journal,
        &journal_path,
        before.as_ref(),
        &after,
        auto_rollback_triggered,
        output,
    );

    if after.all_pass() && !auto_rollback_triggered {
        Ok(())
    } else {
        // Exit 1 without going through OlError so the caller's error
        // formatter doesn't double-print. Matches the brainstorm's
        // "exit 1 = unfixable remaining" contract.
        std::process::exit(1);
    }
}

/// Snapshot of the daemon's state before any `--fix` mutation.
///
/// Used to (a) decide whether a restart is necessary and (b) revert the
/// daemon to its pre-fix state if the post-fix restart fails.
#[derive(Debug, Clone)]
#[allow(dead_code)] // was_healthy is captured for telemetry / debug output (step 7)
pub(crate) struct PreFixState {
    pub was_running: bool,
    pub was_healthy: bool,
    pub port: u16,
    pub pid: Option<u32>,
}

/// Capture the daemon's pre-fix state.
pub(crate) fn capture_pre_fix_state(_ol_dir: &Path) -> PreFixState {
    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 was_running = pid.map(lifecycle::is_process_alive).unwrap_or(false);
    let was_healthy = if was_running {
        lifecycle::check_health(port)
    } else {
        false
    };
    PreFixState {
        was_running,
        was_healthy,
        port,
        pid,
    }
}

/// Stop the daemon ahead of file mutations.
///
/// Tries the bearer-authenticated POST /shutdown first (graceful), then
/// falls back to force-kill via the PID. Cleans up the PID file when
/// the process is confirmed dead. Best-effort — failures are logged and
/// allowed; heal_daemon's restart attempt will surface anything
/// genuinely broken.
fn stop_daemon_for_fix(state: &PreFixState, ol_dir: &Path) {
    let Some(pid) = state.pid else {
        return;
    };

    // Read the token to send the bearer-authenticated shutdown.
    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(state.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));
        }
    }

    // Best-effort PID file cleanup.
    let _ = std::fs::remove_file(ol_dir.join("daemon.pid"));
}

/// Restart the daemon when needed.
///
/// Returns `(actions, restart_failed)`:
/// - `actions` carries a `DaemonRestart` `FixAction` when a restart was
///   attempted AND `/health` came back 200 within 3 s.
/// - `restart_failed` is `true` only when a restart was attempted and
///   did not finish healthy. The caller then drives auto-rollback.
///
/// Skips the restart entirely when the daemon was off pre-fix AND no
/// fix touched a file the daemon reads on boot — pure churn isn't worth
/// disrupting in-flight hooks.
pub(crate) fn heal_daemon(
    ol_dir: &Path,
    pre_fix: &PreFixState,
    prior_actions: &[FixAction],
) -> (Vec<FixAction>, bool) {
    let mut actions = Vec::new();

    let touched_critical = prior_actions.iter().any(|a| {
        matches!(
            a.kind,
            FixKind::ConfigRewrite
                | FixKind::TokenRegenerate
                | FixKind::AgentIdInsert
                | FixKind::HookReinstall
        )
    });
    let should_restart = pre_fix.was_running || touched_critical;
    if !should_restart {
        return (actions, false);
    }

    // Re-probe in case our own port is now contested by something else
    // that grabbed it during the stop window. We start the probe at the
    // pre-fix port so the common case (still free) returns immediately.
    let port = config::probe_free_port(pre_fix.port, config::PORT_RANGE_END)
        .or_else(|_| config::probe_free_port(config::PORT_RANGE_START, config::PORT_RANGE_END))
        .unwrap_or(pre_fix.port);
    if port != pre_fix.port {
        let _ = config::write_port_file(port);
    }

    let token = match std::fs::read_to_string(ol_dir.join("daemon.token")) {
        Ok(s) if !s.trim().is_empty() => s.trim().to_string(),
        _ => {
            tracing::error!(
                "doctor --fix: cannot restart daemon — daemon.token missing/empty after heal_state"
            );
            return (actions, true);
        }
    };

    let pid = match lifecycle::spawn_daemon_background(port, &token) {
        Ok(pid) => pid,
        Err(e) => {
            tracing::error!(error = %e.message, code = e.code, "doctor --fix: daemon spawn failed");
            return (actions, true);
        }
    };

    if !lifecycle::wait_for_health(port, 3) {
        tracing::error!(
            pid = pid,
            port = port,
            "doctor --fix: daemon spawned but /health did not return 200 within 3s"
        );
        return (actions, true);
    }

    actions.push(FixAction {
        ol_code: crate::error::ERR_DAEMON_START_FAILED.to_string(),
        kind: FixKind::DaemonRestart,
        file: PathBuf::new(),
        backup: None,
        reversible: false,
        applied_at: Utc::now(),
        note: format!("daemon restarted on port {port} (PID {pid}, /health=200)"),
    });
    (actions, false)
}

/// Heal state files (config.toml, daemon.token, agent_id, telemetry.json,
/// daemon.pid).
///
/// Best-effort: a single mutation failure does not abort the rest of the
/// category. Each successful mutation appends a `FixAction`. Failures are
/// logged via `tracing::warn!` so the post-fix `run_all_checks` still
/// reports the underlying diagnostic.
///
/// Takes `&Path` rather than calling `openlatch_dir()` internally so
/// tests can drive the function with a tempdir without env-var
/// manipulation.
pub(crate) fn heal_state(ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    // 1. config.toml — parse-or-regenerate.
    let config_path = ol_dir.join("config.toml");
    let config_needs_rewrite = match std::fs::read_to_string(&config_path) {
        Ok(raw) => toml::from_str::<toml::Value>(&raw).is_err(),
        Err(_) => true,
    };
    if config_needs_rewrite {
        let backup = if config_path.exists() {
            backup_file(&config_path).ok()
        } else {
            None
        };
        let content = config::generate_default_config_toml(config::PORT_RANGE_START);
        if let Err(e) = std::fs::write(&config_path, content) {
            tracing::warn!(error = %e, path = %config_path.display(), "doctor --fix: config rewrite failed");
        } else {
            actions.push(FixAction {
                ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                kind: FixKind::ConfigRewrite,
                file: config_path.clone(),
                backup,
                reversible: true,
                applied_at: Utc::now(),
                note: format!("regenerated {} from defaults", config_path.display()),
            });
        }
    }

    // 2. daemon.token — regenerate if missing or empty.
    let token_path = ol_dir.join("daemon.token");
    let token_needs_regen = match std::fs::read_to_string(&token_path) {
        Ok(raw) => raw.trim().is_empty(),
        Err(_) => true,
    };
    if token_needs_regen {
        let backup = if token_path.exists() {
            backup_file(&token_path).ok()
        } else {
            None
        };
        // Force regeneration: ensure_token only generates when the file
        // is absent, so an empty file would otherwise survive.
        if token_path.exists() {
            let _ = std::fs::remove_file(&token_path);
        }
        match config::ensure_token(ol_dir) {
            Ok(_) => {
                actions.push(FixAction {
                    ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                    kind: FixKind::TokenRegenerate,
                    file: token_path.clone(),
                    backup,
                    reversible: true,
                    applied_at: Utc::now(),
                    note: format!("regenerated {} (mode 0600 on Unix)", token_path.display()),
                });
            }
            Err(e) => {
                tracing::warn!(error = %e.message, code = e.code, "doctor --fix: token regenerate failed");
            }
        }
    }

    // 3. agent_id — ensure inserted into [daemon] section.
    if config_path.exists() {
        let needs_insert = std::fs::read_to_string(&config_path)
            .map(|raw| !raw.contains("agent_id"))
            .unwrap_or(false);
        if needs_insert {
            let backup = backup_file(&config_path).ok();
            match config::ensure_agent_id(&config_path) {
                Ok(id) => {
                    actions.push(FixAction {
                        ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
                        kind: FixKind::AgentIdInsert,
                        file: config_path.clone(),
                        backup,
                        reversible: true,
                        applied_at: Utc::now(),
                        note: format!("inserted agent_id={id} into [daemon] section"),
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e.message, code = e.code, "doctor --fix: agent_id insert failed");
                }
            }
        }
    }

    // 4. telemetry.json — reset to a safe default if corrupt.
    //    Resetting to `enabled: false` requires re-consent via the next
    //    `openlatch init` invocation — never silently flips a user back
    //    to opted-in (telemetry.md invariant I9).
    let telem_path = ol_dir.join("telemetry.json");
    if telem_path.exists() {
        let valid = std::fs::read_to_string(&telem_path)
            .ok()
            .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
            .is_some();
        if !valid {
            let backup = backup_file(&telem_path).ok();
            let reset = serde_json::json!({
                "enabled": false,
                "schema_version": 1,
                "notice_shown_at": null,
            });
            match serde_json::to_string_pretty(&reset)
                .map_err(std::io::Error::other)
                .and_then(|s| std::fs::write(&telem_path, s))
            {
                Ok(_) => {
                    actions.push(FixAction {
                        ol_code: crate::error::ERR_TELEMETRY_CONFIG_CORRUPT.to_string(),
                        kind: FixKind::TelemetryReset,
                        file: telem_path.clone(),
                        backup,
                        reversible: true,
                        applied_at: Utc::now(),
                        note: format!(
                            "reset {} to enabled=false (re-consent required via init)",
                            telem_path.display()
                        ),
                    });
                }
                Err(e) => {
                    tracing::warn!(error = %e, "doctor --fix: telemetry reset failed");
                }
            }
        }
    }

    // 5. daemon.pid — remove if PID no longer alive.
    let pid_path = ol_dir.join("daemon.pid");
    if pid_path.exists() {
        let pid_alive = std::fs::read_to_string(&pid_path)
            .ok()
            .and_then(|s| s.trim().parse::<u32>().ok())
            .map(lifecycle::is_process_alive)
            .unwrap_or(false);
        if !pid_alive {
            if let Err(e) = std::fs::remove_file(&pid_path) {
                tracing::warn!(error = %e, path = %pid_path.display(), "doctor --fix: stale PID removal failed");
            } else {
                actions.push(FixAction {
                    ol_code: crate::error::ERR_ALREADY_RUNNING.to_string(),
                    kind: FixKind::PidStaleRemove,
                    file: pid_path.clone(),
                    backup: None,
                    reversible: false,
                    applied_at: Utc::now(),
                    note: format!("removed stale {} (process not alive)", pid_path.display()),
                });
            }
        }
    }

    actions
}

/// Heal the agent's hook installation.
///
/// Day 1 supports Claude Code only (matches the install scope). When no
/// supported agent is detected, this is a no-op. When the agent is
/// present but `settings.json` is missing one of the three load-bearing
/// `_openlatch: true` entries (PreToolUse, UserPromptSubmit, Stop), the
/// settings file is backed up and the full hook set is reinstalled via
/// the existing idempotent `hooks::install_hooks()` (which preserves
/// non-OpenLatch entries through the `_openlatch` marker contract).
///
/// Re-reads `port` and `token` from the freshly-healed state files so
/// the rewrite always uses the canonical pair.
pub(crate) fn heal_hooks(ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    let agent = match hooks::detect_agent() {
        Ok(a) => a,
        Err(_) => return actions, // OL-1400 surfaced by run_all_checks; no fix to apply
    };

    let token_path = ol_dir.join("daemon.token");
    let token = match std::fs::read_to_string(&token_path) {
        Ok(s) if !s.trim().is_empty() => s.trim().to_string(),
        _ => {
            tracing::warn!(
                path = %token_path.display(),
                "doctor --fix: skipping hook reinstall — daemon.token missing/empty after heal_state"
            );
            return actions;
        }
    };

    let port = config::Config::load(None, None, false)
        .map(|c| c.port)
        .unwrap_or(config::PORT_RANGE_START);

    let settings_path = match &agent {
        hooks::DetectedAgent::ClaudeCode { settings_path, .. } => settings_path.clone(),
    };

    // Mirror the diagnostic in doctor.rs: each load-bearing event must have
    // at least one entry tagged `_openlatch: true`. We read content as a
    // single string so the simple substring tests below match the marker
    // anywhere in the JSONC body.
    let needs_reinstall = match std::fs::read_to_string(&settings_path) {
        Ok(content) => {
            !content.contains("_openlatch")
                || !content.contains("PreToolUse")
                || !content.contains("UserPromptSubmit")
                || !content.contains("Stop")
        }
        Err(_) => true, // file absent → install_hooks creates it
    };

    if !needs_reinstall {
        return actions;
    }

    let backup = if settings_path.exists() {
        backup_file(&settings_path).ok()
    } else {
        None
    };

    match hooks::install_hooks(&agent, port, &token) {
        Ok(_) => {
            actions.push(FixAction {
                ol_code: crate::error::ERR_HOOK_WRITE_FAILED.to_string(),
                kind: FixKind::HookReinstall,
                file: settings_path.clone(),
                backup,
                reversible: true,
                applied_at: Utc::now(),
                note: format!("reinstalled hooks in {}", settings_path.display()),
            });
        }
        Err(e) => {
            tracing::warn!(
                error = %e.message,
                code = e.code,
                "doctor --fix: hook reinstall failed"
            );
        }
    }

    actions
}

/// Re-stage the `openlatch-hook` binary into the canonical install
/// location (`<ol_dir>/bin/openlatch-hook[.exe]`) when missing.
///
/// Only acts when (a) the canonical path is empty AND (b) a usable
/// source binary can be located. The source resolution prefers
/// `OPENLATCH_HOOK_BIN`, then a sibling next to the running `openlatch`
/// binary (typical for portable tarball / `cargo install` layouts).
/// When no source is locatable the function records nothing — the
/// post-fix diagnostics still surface the missing-binary check so the
/// user gets a clear remediation hint.
///
/// On Unix, the staged copy is `chmod +x`'d.
pub(crate) fn heal_binaries(ol_dir: &Path) -> Vec<FixAction> {
    let mut actions = Vec::new();

    let bin_name = if cfg!(windows) {
        "openlatch-hook.exe"
    } else {
        "openlatch-hook"
    };
    let target_dir = ol_dir.join("bin");
    let target = target_dir.join(bin_name);

    if target.exists() {
        return actions;
    }

    // Locate a source binary to copy from. We deliberately do NOT call
    // hooks::resolve_hook_binary_path() here: that helper falls back to
    // the canonical `<ol_dir>/bin/...` path itself, which is exactly the
    // path we're trying to populate. Instead we walk the same precedence
    // chain except for that fallback.
    let source = locate_hook_source_for_staging(bin_name);
    let Some(source) = source else {
        tracing::warn!(
            target = %target.display(),
            "doctor --fix: cannot stage hook binary — no source found (env, exe-sibling)"
        );
        return actions;
    };

    if let Err(e) = std::fs::create_dir_all(&target_dir) {
        tracing::warn!(error = %e, dir = %target_dir.display(), "doctor --fix: cannot create bin dir");
        return actions;
    }

    if let Err(e) = std::fs::copy(&source, &target) {
        tracing::warn!(
            error = %e,
            source = %source.display(),
            target = %target.display(),
            "doctor --fix: hook binary copy failed"
        );
        return actions;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)) {
            tracing::warn!(error = %e, path = %target.display(), "doctor --fix: chmod +x failed");
        }
    }

    actions.push(FixAction {
        ol_code: crate::error::ERR_HOOK_WRITE_FAILED.to_string(),
        kind: FixKind::BinaryCopy,
        file: target.clone(),
        backup: None, // freshly staged — no prior file to preserve
        reversible: true,
        applied_at: Utc::now(),
        note: format!("staged {} from {}", target.display(), source.display()),
    });

    actions
}

/// Find a source `openlatch-hook` binary to copy into the canonical
/// install location, skipping the canonical location itself.
fn locate_hook_source_for_staging(bin_name: &str) -> Option<PathBuf> {
    if let Ok(override_path) = std::env::var("OPENLATCH_HOOK_BIN") {
        if !override_path.is_empty() {
            let p = PathBuf::from(override_path);
            if p.exists() {
                return Some(p);
            }
        }
    }
    if let Ok(current_exe) = std::env::current_exe() {
        if let Some(dir) = current_exe.parent() {
            let candidate = dir.join(bin_name);
            if candidate.exists() {
                return Some(candidate);
            }
        }
    }
    None
}

/// Reinstall the OS supervisor when config says `mode=active` but the OS
/// artifact (plist / unit / Task Scheduler task) is missing. No-op in every
/// other state — keep the fix surgical so `--fix` never silently re-opts a
/// user back into persistence they disabled.
pub(crate) fn heal_supervision(ol_dir: &Path) -> Vec<FixAction> {
    use crate::supervision::{select_supervisor, SupervisionMode};
    let mut actions = Vec::new();

    let cfg = match config::Config::load(None, None, false) {
        Ok(c) => c,
        Err(_) => return actions,
    };

    if !matches!(cfg.supervision.mode, SupervisionMode::Active) {
        return actions;
    }

    let Some(supervisor) = select_supervisor() else {
        return actions;
    };

    let status_ok = supervisor.status().map(|s| s.installed).unwrap_or(false);
    if status_ok {
        return actions;
    }

    let exe_path =
        std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("openlatch"));
    if let Err(e) = supervisor.install(&exe_path) {
        tracing::warn!(error = %e.message, code = %e.code, "doctor --fix: supervisor reinstall failed");
        return actions;
    }

    let config_path = ol_dir.join("config.toml");
    let _ = config::persist_supervision_state(
        &config_path,
        &SupervisionMode::Active,
        &supervisor.kind(),
        None,
    );

    actions.push(FixAction {
        ol_code: crate::supervision::ERR_SUPERVISION_INSTALL_FAILED.to_string(),
        kind: FixKind::SupervisionInstall,
        file: std::path::PathBuf::new(),
        backup: None,
        reversible: false,
        applied_at: Utc::now(),
        note: "Reinstalled missing OS supervisor (config said active)".to_string(),
    });

    actions
}

/// Copy `path` to a sibling `<filename>.bak`, returning the backup path.
///
/// Single-level backup — overwrites any prior `.bak`. Multi-level history
/// is intentionally not kept (disk cost outweighs value; the journal
/// itself records intent and timestamps).
pub(crate) fn backup_file(path: &Path) -> Result<PathBuf, OlError> {
    let bak = bak_path_for(path);
    std::fs::copy(path, &bak).map_err(|e| {
        OlError::new(
            crate::error::ERR_INVALID_CONFIG,
            format!(
                "cannot create backup '{}' for '{}': {e}",
                bak.display(),
                path.display()
            ),
        )
    })?;
    Ok(bak)
}

/// Compute the `.bak` sibling path for an arbitrary file path.
///
/// Appends `.bak` to the file name (preserving any existing extension):
/// `config.toml` → `config.toml.bak`, `daemon.token` → `daemon.token.bak`.
pub(crate) fn bak_path_for(path: &Path) -> PathBuf {
    let mut bak = path.to_path_buf();
    let new_name = match path.file_name() {
        Some(name) => format!("{}.bak", name.to_string_lossy()),
        None => "unknown.bak".to_string(),
    };
    bak.set_file_name(new_name);
    bak
}

/// Render the fix run as either a JSON object (for scripting) or a
/// before/after delta (for human consumption).
fn print_fix_results(
    journal: &Journal,
    journal_path: &Path,
    before: Option<&DoctorReport>,
    after: &DoctorReport,
    auto_rollback_triggered: bool,
    output: &OutputConfig,
) {
    let unfixable: Vec<&str> = after
        .checks
        .iter()
        .filter(|c| !c.pass)
        .map(|c| c.message.as_str())
        .collect();

    if output.format == OutputFormat::Json {
        let actions_json: Vec<serde_json::Value> = journal
            .actions
            .iter()
            .map(|a| {
                serde_json::json!({
                    "ol_code": a.ol_code,
                    "kind": a.kind,
                    "file": a.file.display().to_string(),
                    "backup": a.backup.as_ref().map(|p| p.display().to_string()),
                    "reversible": a.reversible,
                    "applied_at": a.applied_at,
                    "note": a.note,
                })
            })
            .collect();
        let backups: Vec<String> = journal
            .actions
            .iter()
            .filter_map(|a| a.backup.as_ref().map(|p| p.display().to_string()))
            .collect();
        let exit_code = if after.all_pass() && !auto_rollback_triggered {
            0
        } else {
            1
        };
        output.print_json(&serde_json::json!({
            "command": "doctor_fix",
            "run_id": journal.run_id,
            "started_at": journal.started_at,
            "journal_path": journal_path.display().to_string(),
            "checks_before": before.map(|r| serde_json::json!({
                "pass": r.checks.iter().filter(|c| c.pass).count(),
                "fail": r.fail_count(),
            })),
            "checks_after": serde_json::json!({
                "pass": after.checks.iter().filter(|c| c.pass).count(),
                "fail": after.fail_count(),
            }),
            "fixes_applied": actions_json,
            "fixes_count": journal.actions.len(),
            "unfixable": unfixable,
            "backups": backups,
            "auto_rollback_triggered": auto_rollback_triggered,
            "exit_code": exit_code,
        }));
        return;
    }

    if output.quiet {
        return;
    }

    print_diagnostic_results(after, output);

    if auto_rollback_triggered {
        eprintln!();
        eprintln!("Fix attempted but daemon failed to restart — rolled back to pre-fix state.");
        eprintln!("  Run `openlatch doctor --rescue` to file a bug with diagnostics.");
        return;
    }

    if !journal.actions.is_empty() {
        eprintln!();
        eprintln!("Fixes applied ({}):", journal.actions.len());
        for action in &journal.actions {
            eprintln!("{} [{}]", action.note, action.ol_code);
        }
        let backups: Vec<String> = journal
            .actions
            .iter()
            .filter_map(|a| a.backup.as_ref().map(|p| p.display().to_string()))
            .collect();
        if !backups.is_empty() {
            eprintln!();
            eprintln!("Backups created: {}", backups.join(", "));
            eprintln!("Roll back with: openlatch doctor --restore");
        }
    }

    eprintln!();
    if after.all_pass() {
        eprintln!(
            "Summary: {} fix{} applied, 0 issues remaining.",
            journal.actions.len(),
            if journal.actions.len() == 1 { "" } else { "es" }
        );
    } else {
        eprintln!(
            "Summary: {} fix{} applied, {} issue{} remaining.",
            journal.actions.len(),
            if journal.actions.len() == 1 { "" } else { "es" },
            after.fail_count(),
            if after.fail_count() == 1 { "" } else { "s" }
        );
    }
}

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

    fn empty_dir() -> TempDir {
        TempDir::new().expect("tempdir must be created")
    }

    #[test]
    fn test_bak_path_for_appends_bak_suffix() {
        let p = Path::new("/tmp/config.toml");
        assert_eq!(bak_path_for(p), Path::new("/tmp/config.toml.bak"));
    }

    #[test]
    fn test_bak_path_for_handles_no_extension() {
        let p = Path::new("/tmp/daemon.token");
        assert_eq!(bak_path_for(p), Path::new("/tmp/daemon.token.bak"));
    }

    #[test]
    fn test_backup_file_round_trip() {
        let tmp = empty_dir();
        let src = tmp.path().join("config.toml");
        std::fs::write(&src, "port = 7443\n").unwrap();
        let bak = backup_file(&src).expect("backup must succeed");
        assert_eq!(bak, src.with_file_name("config.toml.bak"));
        assert_eq!(std::fs::read_to_string(&bak).unwrap(), "port = 7443\n");
    }

    #[test]
    fn test_heal_state_creates_config_when_missing() {
        let tmp = empty_dir();
        let actions = heal_state(tmp.path());
        let config_path = tmp.path().join("config.toml");
        assert!(config_path.exists(), "config.toml must be created");
        assert!(
            actions
                .iter()
                .any(|a| a.kind == FixKind::ConfigRewrite && a.backup.is_none()),
            "expected ConfigRewrite action with no backup (no prior file)"
        );
    }

    #[test]
    fn test_heal_state_rewrites_corrupt_config_with_backup() {
        let tmp = empty_dir();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "this is not valid TOML {{{").unwrap();
        let actions = heal_state(tmp.path());
        let bak = config_path.with_file_name("config.toml.bak");
        assert!(bak.exists(), ".bak must be created for corrupt config");
        // After rewrite the config must parse
        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(toml::from_str::<toml::Value>(&raw).is_ok());
        assert!(actions
            .iter()
            .any(|a| a.kind == FixKind::ConfigRewrite && a.backup.is_some()));
    }

    #[test]
    fn test_heal_state_regenerates_missing_token() {
        let tmp = empty_dir();
        let token_path = tmp.path().join("daemon.token");
        let actions = heal_state(tmp.path());
        assert!(token_path.exists(), "token must be regenerated");
        let token = std::fs::read_to_string(&token_path).unwrap();
        assert_eq!(token.trim().len(), 64, "token must be 64 hex chars");
        assert!(actions.iter().any(|a| a.kind == FixKind::TokenRegenerate));
    }

    #[test]
    fn test_heal_state_regenerates_empty_token_with_backup() {
        let tmp = empty_dir();
        let token_path = tmp.path().join("daemon.token");
        std::fs::write(&token_path, "").unwrap();
        let actions = heal_state(tmp.path());
        let bak = token_path.with_file_name("daemon.token.bak");
        assert!(bak.exists(), "empty token must be backed up");
        let token = std::fs::read_to_string(&token_path).unwrap();
        assert_eq!(token.trim().len(), 64);
        assert!(actions.iter().any(|a| a.kind == FixKind::TokenRegenerate));
    }

    #[test]
    fn test_heal_state_inserts_agent_id_into_existing_config() {
        let tmp = empty_dir();
        let config_path = tmp.path().join("config.toml");
        std::fs::write(&config_path, "[daemon]\nport = 7443\n").unwrap();
        let actions = heal_state(tmp.path());
        let raw = std::fs::read_to_string(&config_path).unwrap();
        assert!(raw.contains("agent_id"), "agent_id must be inserted");
        assert!(actions.iter().any(|a| a.kind == FixKind::AgentIdInsert));
    }

    #[test]
    fn test_heal_state_resets_corrupt_telemetry_json() {
        let tmp = empty_dir();
        let telem_path = tmp.path().join("telemetry.json");
        std::fs::write(&telem_path, "{ broken json").unwrap();
        let actions = heal_state(tmp.path());
        let raw = std::fs::read_to_string(&telem_path).unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&raw).expect("telemetry must be valid JSON");
        assert_eq!(parsed.get("enabled"), Some(&serde_json::json!(false)));
        assert!(actions.iter().any(|a| a.kind == FixKind::TelemetryReset));
    }

    #[test]
    fn test_heal_state_removes_stale_pid_file() {
        let tmp = empty_dir();
        let pid_path = tmp.path().join("daemon.pid");
        // Use PID 0 — guaranteed not alive on any platform (kernel-reserved).
        std::fs::write(&pid_path, "0").unwrap();
        let actions = heal_state(tmp.path());
        assert!(!pid_path.exists(), "stale PID file must be removed");
        assert!(actions.iter().any(|a| a.kind == FixKind::PidStaleRemove));
    }

    #[test]
    fn test_heal_state_idempotent_on_clean_install() {
        let tmp = empty_dir();
        // First run brings the install up from scratch.
        let first = heal_state(tmp.path());
        assert!(!first.is_empty(), "first run must apply at least one fix");
        // Second run on the same dir should be a no-op (or no-mutation: only
        // agent_id may already be set after the first run).
        let second = heal_state(tmp.path());
        assert!(
            second.is_empty(),
            "second run on a healthy install must apply zero fixes (got {second:?})"
        );
    }

    #[test]
    fn test_heal_binaries_noop_when_target_exists() {
        let tmp = empty_dir();
        let bin_dir = tmp.path().join("bin");
        std::fs::create_dir_all(&bin_dir).unwrap();
        let bin_name = if cfg!(windows) {
            "openlatch-hook.exe"
        } else {
            "openlatch-hook"
        };
        std::fs::write(bin_dir.join(bin_name), b"existing").unwrap();
        let actions = heal_binaries(tmp.path());
        assert!(actions.is_empty(), "no action when target already exists");
    }

    #[test]
    fn test_heal_binaries_copies_from_env_override() {
        let tmp = empty_dir();
        let src_dir = empty_dir();
        let bin_name = if cfg!(windows) {
            "openlatch-hook.exe"
        } else {
            "openlatch-hook"
        };
        let src = src_dir.path().join(bin_name);
        std::fs::write(&src, b"hook bytes").unwrap();

        // SAFETY: tests in this module are serialized via #[serial] in
        // heavier integration suites; for unit tests we use a unique env
        // var name per test by relying on cargo's per-test isolation.
        // For a stricter guarantee see tests/doctor_fix.rs.
        let prev = std::env::var("OPENLATCH_HOOK_BIN").ok();
        std::env::set_var("OPENLATCH_HOOK_BIN", &src);

        let actions = heal_binaries(tmp.path());

        if let Some(p) = prev {
            std::env::set_var("OPENLATCH_HOOK_BIN", p);
        } else {
            std::env::remove_var("OPENLATCH_HOOK_BIN");
        }

        let target = tmp.path().join("bin").join(bin_name);
        assert!(target.exists(), "binary must be staged");
        assert_eq!(std::fs::read(&target).unwrap(), b"hook bytes");
        assert!(actions.iter().any(|a| a.kind == FixKind::BinaryCopy));
    }

    #[test]
    fn test_heal_binaries_no_action_when_no_source_locatable() {
        let tmp = empty_dir();
        let prev = std::env::var("OPENLATCH_HOOK_BIN").ok();
        std::env::set_var("OPENLATCH_HOOK_BIN", "");
        let actions = heal_binaries(tmp.path());
        if let Some(p) = prev {
            std::env::set_var("OPENLATCH_HOOK_BIN", p);
        } else {
            std::env::remove_var("OPENLATCH_HOOK_BIN");
        }
        // We cannot assert strictly that actions is empty: the test runner
        // binary itself may sit next to an `openlatch-hook` artifact in the
        // target dir, in which case heal_binaries will (correctly) stage it.
        // We only assert the staged action, when present, points at the
        // tempdir target — never at a path outside.
        for a in &actions {
            assert!(a.file.starts_with(tmp.path()));
        }
    }

    #[test]
    fn test_journal_save_and_load_round_trip() {
        let tmp = empty_dir();
        let mut journal = Journal::new();
        journal.actions.push(FixAction {
            ol_code: crate::error::ERR_INVALID_CONFIG.to_string(),
            kind: FixKind::ConfigRewrite,
            file: tmp.path().join("config.toml"),
            backup: Some(tmp.path().join("config.toml.bak")),
            reversible: true,
            applied_at: Utc::now(),
            note: "test".to_string(),
        });
        journal.save(tmp.path()).expect("save must succeed");
        let loaded = Journal::load(tmp.path()).expect("load must succeed");
        assert_eq!(loaded.run_id, journal.run_id);
        assert_eq!(loaded.actions.len(), 1);
        assert_eq!(loaded.actions[0].kind, FixKind::ConfigRewrite);
    }

    #[test]
    fn test_journal_load_returns_no_journal_error_when_absent() {
        let tmp = empty_dir();
        let err = Journal::load(tmp.path()).expect_err("load must fail when absent");
        assert_eq!(err.code, crate::error::ERR_DOCTOR_RESTORE_NO_JOURNAL);
    }

    #[test]
    fn test_journal_load_returns_corrupt_error_when_unparsable() {
        let tmp = empty_dir();
        std::fs::write(tmp.path().join(JOURNAL_FILENAME), "{ broken").unwrap();
        let err = Journal::load(tmp.path()).expect_err("load must fail on bad JSON");
        assert_eq!(err.code, crate::error::ERR_DOCTOR_JOURNAL_CORRUPT);
    }
}