sysknife-cli 0.2.9

Approval-gated AI system administration CLI and MCP server
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
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
//! Top-level dispatch for all `sysknife` CLI commands.
//!
//! Each public `run_*` function corresponds to one subcommand or the
//! free-form intent path.  All printed output goes through [`Logger`] so
//! that `--log-to` tee works transparently.
//!
//! ## Approval flow
//!
//! Without `--step-by-step`: [`ApprovalPolicy::decide_plan`] is called once
//! for the whole plan.  If a single confirmation is needed the user is asked
//! once, then all steps execute in sequence.
//!
//! With `--step-by-step`: [`ApprovalPolicy::decide_step`] is called before
//! each step so the user can approve or reject them individually.
//!
//! `--dry-run` short-circuits before any execution: the plan is printed and
//! the function returns `Ok(())`.

use std::io::{self, IsTerminal, Write as _};
use std::path::PathBuf;

use clap::CommandFactory;
use serde_json::{json, Value};
use sysknife_brain::config::BrainConfig;
use sysknife_brain::planner::{LlmPlanner, PlanRiskLevel};
use sysknife_brain::PlanEvent;
use sysknife_types::{
    DistroHint, RiskLevel, DISTRO_FAMILY_DEBIAN, DISTRO_FAMILY_FEDORA, DISTRO_FAMILY_OTHER,
};

use sysknife_brain::state_client::StateClient as _;

use crate::approval::{ApprovalDecision, ApprovalPolicy, MaxRisk};
use crate::cli::{AuditVerifyArgs, Cli, HistoryArgs};
use crate::client::{DaemonClient, SocketTarget};
use crate::error::CliError;

// ---------------------------------------------------------------------------
// distro_id_to_hint — DistroId → DistroHint conversion
// ---------------------------------------------------------------------------

/// Convert a `sysknife_core::distro::DistroId` to a `DistroHint` for the planner.
///
/// This is the single place where the CLI bridges the detection layer
/// (`sysknife-core`) and the planning layer (`sysknife-brain`), keeping each
/// side independent of the other.
pub fn distro_id_to_hint(distro: &sysknife_core::distro::DistroId) -> DistroHint {
    use sysknife_core::distro::DistroFamily;
    let family = match distro.family() {
        DistroFamily::Fedora => DISTRO_FAMILY_FEDORA,
        DistroFamily::Debian => DISTRO_FAMILY_DEBIAN,
        DistroFamily::Other => DISTRO_FAMILY_OTHER,
    };
    DistroHint {
        family,
        version: Some(distro.to_string()),
    }
}

// ---------------------------------------------------------------------------
// resolve_socket / resolve_socket_target
// ---------------------------------------------------------------------------

/// Resolve the daemon [`SocketTarget`] the CLI (and MCP server) should dial.
///
/// Precedence:
/// 1. `$SYSKNIFE_SOCKET` — explicit override; accepts `unix://`, `vsock://`, or
///    a bare path.
/// 2. Otherwise [`sysknife_core::default_listen_uri`] — the *same* resolver the
///    daemon and Tauri GUI use (`$SYSKNIFE_LISTEN_URI` →
///    `$XDG_RUNTIME_DIR/sysknife/daemon.sock` → `/tmp/sysknife-$UID.sock`). This
///    keeps the CLI pointed at wherever the daemon actually bound in both dev
///    and production, rather than a hardcoded production path that only matches
///    under systemd.
///
/// Exits the process if the resolved target string is unparseable.
pub fn resolve_socket_target() -> SocketTarget {
    let raw =
        std::env::var("SYSKNIFE_SOCKET").unwrap_or_else(|_| sysknife_core::default_listen_uri());
    SocketTarget::try_from_str(&raw).unwrap_or_else(|e| {
        eprintln!("sysknife: invalid socket target {raw:?}: {e}");
        std::process::exit(1);
    })
}

// ---------------------------------------------------------------------------
// since_to_hours
// ---------------------------------------------------------------------------

/// Parse an RFC 3339 / ISO-8601 UTC datetime string and return the number of
/// whole hours that have elapsed since that moment.
///
/// Returns `None` when:
/// - the string is not a valid UTC timestamp (`Z` or `+00:00` suffix),
/// - the datetime is in the future, or
/// - the value is too large to fit in `u32`.
///
/// Sub-second precision (`.NNN`) is accepted and truncated.  Non-zero UTC
/// offsets are not supported and return `None`.
pub fn since_to_hours(s: &str) -> Option<u32> {
    let epoch = rfc3339_to_unix(s)?;
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs() as i64;
    if epoch > now {
        return None;
    }
    u32::try_from((now - epoch) / 3600).ok()
}

/// Parse a UTC RFC 3339 string to seconds since Unix epoch (no external dep).
///
/// Supports `YYYY-MM-DDThh:mm:ssZ` and `YYYY-MM-DDThh:mm:ss+00:00`.
/// Sub-second fractions are stripped.
///
/// Uses Howard Hinnant's civil day algorithm to convert a proleptic-Gregorian
/// date to a day count, then scales to seconds.
fn rfc3339_to_unix(s: &str) -> Option<i64> {
    let s = s.strip_suffix('Z').or_else(|| s.strip_suffix("+00:00"))?;

    // Split on the 'T' separator.
    let (date_part, time_and_frac) = s.split_once('T')?;

    // Drop sub-second fractions: keep only up to "hh:mm:ss".
    let time_part = &time_and_frac[..time_and_frac.find('.').unwrap_or(time_and_frac.len())];
    if time_part.len() < 8 {
        return None;
    }

    // Parse date components.
    let mut date_iter = date_part.splitn(4, '-');
    let y: i64 = date_iter.next()?.parse().ok()?;
    let m: i64 = date_iter.next()?.parse().ok()?;
    let d: i64 = date_iter.next()?.parse().ok()?;
    if date_iter.next().is_some() {
        return None; // extra segments → reject
    }

    // Parse time components.
    let mut time_iter = time_part.splitn(4, ':');
    let h: i64 = time_iter.next()?.parse().ok()?;
    let mn: i64 = time_iter.next()?.parse().ok()?;
    let sec: i64 = time_iter.next()?.parse().ok()?;
    if time_iter.next().is_some() {
        return None; // extra segments → reject
    }

    // Range validation.
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) || h > 23 || mn > 59 || sec > 60
    // allow leap second
    {
        return None;
    }

    // Howard Hinnant's civil_from_days: compute days since 1970-01-01.
    //
    // Reference: https://howardhinnant.github.io/date_algorithms.html
    // The civil epoch starts on 0000-03-01; shift y back by 1 for Jan/Feb so
    // Feb 29 falls at the end of its civil year.
    let z = if m > 2 { y } else { y - 1 };
    let era = (if z >= 0 { z } else { z - 399 }) / 400;
    let yoe = z - era * 400; // year-of-era [0, 399]
    let m_adj = if m > 2 { m - 3 } else { m + 9 }; // month-of-civil-year [0, 11]
    let doy = (153 * m_adj + 2) / 5 + d - 1; // day-of-year from Mar 1
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // day-of-era
    let days = era * 146097 + doe - 719468; // days since 1970-01-01

    Some(days * 86_400 + h * 3600 + mn * 60 + sec)
}

// ---------------------------------------------------------------------------
// highest_risk
// ---------------------------------------------------------------------------

/// Return the highest risk level present in `plan`.
///
/// Returns `None` only if the plan has no steps; in practice `Plan::new`
/// enforces at least one step, so callers may safely `.expect` the result.
pub fn highest_risk(plan: &sysknife_brain::planner::Plan) -> Option<&PlanRiskLevel> {
    plan.steps()
        .iter()
        .max_by_key(|s| plan_risk_rank(s.risk_level()))
        .map(|s| s.risk_level())
}

// ---------------------------------------------------------------------------
// authoritative_plan_risk + risk-consistency helpers
// ---------------------------------------------------------------------------

/// Map the daemon's `RiskLevel` into the planner's risk enum.
fn plan_risk_of(risk: RiskLevel) -> PlanRiskLevel {
    match risk {
        RiskLevel::Low => PlanRiskLevel::Low,
        RiskLevel::Medium => PlanRiskLevel::Medium,
        RiskLevel::High => PlanRiskLevel::High,
    }
}

fn plan_risk_rank(risk: &PlanRiskLevel) -> u8 {
    match risk {
        PlanRiskLevel::Low => 0,
        PlanRiskLevel::Medium => 1,
        PlanRiskLevel::High => 2,
    }
}

/// The authoritative risk for a plan step's action: the daemon's
/// `ActionSpec`-derived gate risk ([`sysknife_daemon::preview::gate_risk`]),
/// mapped into the planner's risk enum.
///
/// The CLI substitutes this for the LLM's *proposed* per-step risk (see
/// [`run_intent`]) so the plan the operator sees and the `--yes` / `--max-risk`
/// auto-approval decision derive from the single source of truth rather than a
/// model guess. Unknown actions map to `High` — `gate_risk`'s conservative
/// fallback — so a missing spec can never downgrade the CLI's approval friction.
///
/// Note: this reads the CLI binary's *own* linked `sysknife-daemon` catalogue,
/// which equals the running daemon's only when both are the same build. The
/// execution loop re-validates against the live daemon preview via
/// [`daemon_risk_within_approved`] so a version skew can never execute a step at
/// higher risk than was approved.
fn authoritative_plan_risk(action_name: &str) -> PlanRiskLevel {
    plan_risk_of(sysknife_daemon::preview::gate_risk(action_name))
}

/// Fail-closed check run at execution time: is the live daemon's risk for a step
/// no higher than the risk the CLI approved it at?
///
/// The plan-level/step-level approval decisions use the CLI's locally linked
/// [`authoritative_plan_risk`]. If the connected daemon is a *different* build
/// that reclassified an action upward (e.g. Medium → High, the same shape as a
/// past security fix), the CLI could have auto-approved at the stale lower tier.
/// Before minting a receipt we compare against the daemon's live preview risk and
/// refuse to proceed when it is higher — the CLI must never execute a step at a
/// higher risk than the operator approved.
fn daemon_risk_within_approved(approved: &PlanRiskLevel, daemon: &PlanRiskLevel) -> bool {
    plan_risk_rank(daemon) <= plan_risk_rank(approved)
}

pub async fn run_approve(
    transaction_id: &str,
    socket: SocketTarget,
    json: bool,
    log: &Logger,
) -> Result<(), CliError> {
    if !std::io::stdin().is_terminal() {
        return Err(CliError::NonInteractive);
    }
    let client = DaemonClient::new(socket);
    let details = client.approval_details(transaction_id).await?;
    log.print_stderr(&format!(
        "Action:  {}\nRisk:    {:?}\nSummary: {}\nProposed change:\n{}",
        details.action_name,
        details.preview.risk_level,
        details.preview.summary,
        serde_json::to_string_pretty(&details.preview.proposed_change)
            .unwrap_or_else(|_| "<unavailable>".to_string())
    ));
    let approved = if details.preview.risk_level == RiskLevel::High {
        prompt_exact(
            "High-risk action. Type the exact action name to approve",
            &details.action_name,
        )
        .await
    } else {
        prompt_confirm(&format!("Approve transaction {}?", details.transaction_id)).await
    };
    if !approved {
        return Err(CliError::Rejected);
    }

    let receipt = client.approve(transaction_id).await?;
    if json {
        log.println(
            &serde_json::json!({
                "transaction_id": transaction_id,
                "approval_receipt": receipt,
            })
            .to_string(),
        );
    } else {
        log.println(&format!("Approval receipt: {receipt}"));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// build_history_params (private helper)
// ---------------------------------------------------------------------------

pub(crate) fn build_history_params(
    limit: u32,
    status: Option<&str>,
    action: Option<&str>,
    since_hours: Option<u32>,
) -> Value {
    let mut params = json!({ "limit": limit });
    if let Some(s) = status {
        params["status_filter"] = json!(s);
    }
    if let Some(a) = action {
        params["action_filter"] = json!(a);
    }
    if let Some(h) = since_hours {
        params["since_hours"] = json!(h);
    }
    params
}

// ---------------------------------------------------------------------------
// Logger
// ---------------------------------------------------------------------------

/// Tees all output to stdout and optionally to a log file.
///
/// `Mutex` makes `Logger` `Send + Sync` so it can be shared across the async
/// executor boundary without requiring a separate Arc.
pub struct Logger {
    file: std::sync::Mutex<Option<std::fs::File>>,
}

impl Logger {
    /// Construct.  Pass `None` to disable file tee.
    pub fn new(path: Option<&std::path::Path>) -> Result<Self, CliError> {
        let file = match path {
            None => None,
            Some(p) => Some(
                std::fs::OpenOptions::new()
                    .append(true)
                    .create(true)
                    .open(p)
                    .map_err(|e| CliError::ConfigOrDaemon(format!("open log file: {e}")))?,
            ),
        };
        Ok(Self {
            file: std::sync::Mutex::new(file),
        })
    }

    /// Print `line` to stdout and, if a log file is configured, also append it
    /// to that file.
    ///
    /// On the first file-write failure a warning is emitted to stderr and the
    /// file tee is permanently disabled so that subsequent writes do not spin
    /// on a dead handle.  The stdout print always succeeds (or panics, which is
    /// the correct response to a broken stdout in a CLI tool).
    pub fn println(&self, line: &str) {
        println!("{line}");
        let mut guard = self.file.lock().expect("Logger mutex poisoned");
        if let Some(f) = guard.as_mut() {
            if let Err(e) = writeln!(f, "{line}") {
                eprintln!("sysknife: log write failed ({e}); --log-to tee disabled");
                *guard = None;
            }
        }
    }

    /// Print `line` to stderr only.  Not teed to the log file — errors belong
    /// on stderr and must not be mixed into a structured log meant for parsing.
    pub fn print_stderr(&self, line: &str) {
        eprintln!("{line}");
    }
}

// ---------------------------------------------------------------------------
// run_completions
// ---------------------------------------------------------------------------

/// Write a shell completion script for `shell` to stdout.
pub fn run_completions(shell: clap_complete::Shell) {
    clap_complete::generate(shell, &mut Cli::command(), "sysknife", &mut io::stdout());
}

// ---------------------------------------------------------------------------
// run_doctor
// ---------------------------------------------------------------------------

/// Check daemon connectivity and print configuration summary.
pub async fn run_doctor(
    socket: SocketTarget,
    json_out: bool,
    log: &Logger,
) -> Result<(), CliError> {
    let config = BrainConfig::from_env().map_err(|e| CliError::ConfigOrDaemon(e.to_string()))?;

    let socket_label = format!("{socket:?}");
    let client = DaemonClient::new(socket);

    // Detect the running distro once; failure is non-fatal for doctor.
    let distro_label = match sysknife_core::distro::detect() {
        Ok(d) => d.to_string(),
        Err(e) => format!("unknown ({})", e),
    };

    // `curated_state` is a blocking sync call; use spawn_blocking so the
    // multi-threaded runtime is not blocked on one thread indefinitely.
    let state_result = tokio::task::spawn_blocking(move || client.curated_state())
        .await
        .map_err(|e| CliError::ConfigOrDaemon(format!("join: {e}")))?;

    match state_result {
        Ok(state) => {
            if json_out {
                let out = json!({
                    "ok": true,
                    "socket": socket_label,
                    "host": state.host_name(),
                    "provider": config.provider_name(),
                    "model": config.model_name(),
                    "distro": distro_label,
                });
                log.println(&serde_json::to_string(&out).expect("static JSON"));
            } else {
                crate::render::print_doctor_ok(
                    &socket_label,
                    state.host_name(),
                    config.provider_name(),
                    config.model_name(),
                    &distro_label,
                    log,
                );
            }
            Ok(())
        }
        Err(e) => {
            if json_out {
                let out = json!({ "ok": false, "error": e.to_string() });
                log.println(&serde_json::to_string(&out).expect("static JSON"));
            } else {
                crate::render::print_doctor_fail(&e.to_string());
            }
            Err(CliError::ConfigOrDaemon(e.to_string()))
        }
    }
}

// ---------------------------------------------------------------------------
// run_history
// ---------------------------------------------------------------------------

/// Query past SysKnife execution history via `ListJobHistory`.
pub async fn run_history(
    args: HistoryArgs,
    socket: SocketTarget,
    log: &Logger,
) -> Result<(), CliError> {
    let since_hours = match args.since.as_deref() {
        None => None,
        Some(s) => {
            // Distinguish the two failure modes so the user knows how to fix each.
            if rfc3339_to_unix(s).is_none() {
                return Err(CliError::ConfigOrDaemon(format!(
                    "--since: {s:?} is not a valid UTC RFC 3339 timestamp \
                     (accepted formats: 2026-01-15T10:30:00Z or 2026-01-15T10:30:00+00:00)"
                )));
            }
            match since_to_hours(s) {
                Some(h) => Some(h),
                None => {
                    return Err(CliError::ConfigOrDaemon(format!(
                        "--since: {s:?} is in the future"
                    )));
                }
            }
        }
    };

    let params = build_history_params(
        args.limit,
        args.status.as_deref(),
        args.action.as_deref(),
        since_hours,
    );

    let client = DaemonClient::new(socket);
    let output =
        tokio::task::spawn_blocking(move || client.query_action("ListJobHistory", &params))
            .await
            .map_err(|e| CliError::ConfigOrDaemon(format!("join: {e}")))?
            .map_err(|e| CliError::ConfigOrDaemon(e.to_string()))?;

    log.println(&output);
    Ok(())
}

// ---------------------------------------------------------------------------
// RunOpts
// ---------------------------------------------------------------------------

/// Options derived from global CLI flags; threaded into `run_intent` and
/// `run_repl` so callers do not have to pass each flag individually.
pub struct RunOpts {
    pub socket: SocketTarget,
    pub yes: bool,
    pub max_risk: Option<MaxRisk>,
    pub non_interactive: bool,
    pub dry_run: bool,
    pub json: bool,
    pub step_by_step: bool,
}

impl RunOpts {
    /// Build the `ApprovalPolicy` for this set of flags.
    pub fn approval_policy(&self) -> ApprovalPolicy {
        ApprovalPolicy::new(self.yes, self.max_risk, self.non_interactive, self.dry_run)
    }
}

// ---------------------------------------------------------------------------
// run_audit_verify
// ---------------------------------------------------------------------------

/// Walk the audit log hash chain and report integrity status.
///
/// Resolves the database path via [`sysknife_core::default_database_path`]
/// (same precedence as the daemon: `$SYSKNIFE_DATABASE_PATH` →
/// `$XDG_STATE_HOME/sysknife/daemon.sqlite` → fallbacks). Loads the audit
/// key from the path the daemon would generate it at (sibling of the DB,
/// or `$SYSKNIFE_AUDIT_KEY_PATH`).
///
/// Exit codes:
/// - 0 — chain intact across all rows
/// - 1 — chain broken; first offending row is reported
/// - 2 — verification could not be completed (missing key, unreadable DB,
///   retired key not on disk, etc.)
///
/// On exit code 2, do **not** treat the audit log as either intact or
/// tampered — the result is unknown until the operator resolves the
/// underlying access problem.
pub async fn run_audit_verify(args: AuditVerifyArgs, log: &Logger) -> Result<(), CliError> {
    use sysknife_core::config::LacsConfig;
    use sysknife_daemon::audit_chain::{self, AuditKey, VerifyOutcome};

    // Honour the same `[storage]` config the daemon uses, so `sysknife audit
    // verify` works against whichever backend is in production. Without this,
    // a Postgres-backed deployment can never verify its chain from the CLI.
    let lacs_config = LacsConfig::load();

    let label_for_diag = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => "postgres".to_string(),
        _ => sysknife_core::default_database_path().display().to_string(),
    };

    let db_path = sysknife_core::default_database_path();

    // Build the verifier. With `--pubkey`, verify using only the exported
    // public key (the auditor path, no private key). Otherwise load the private
    // signing key from its file (sibling of the SQLite path, or
    // `$SYSKNIFE_AUDIT_KEY_PATH`).
    let verifier = if let Some(pubkey_path) = args.pubkey.as_ref() {
        match std::fs::read_to_string(pubkey_path) {
            Ok(contents) => Verifier::Public(contents.trim().to_string()),
            Err(e) => {
                let reason = format!(
                    "public key file {} could not be read: {e}",
                    pubkey_path.display()
                );
                emit_verify_outcome(
                    &args,
                    log,
                    &VerifyOutcome::CannotVerify { reason },
                    &label_for_diag,
                );
                return Err(CliError::Exit(2));
            }
        }
    } else {
        let key_path = sysknife_daemon::audit_chain::resolve_audit_key_path(&db_path);

        if !key_path.exists() {
            let reason = format!(
                "audit key not found at {}; the daemon generates this on first run, \
                 set $SYSKNIFE_AUDIT_KEY_PATH, or pass --pubkey <FILE> to verify with \
                 the exported public key",
                key_path.display()
            );
            emit_verify_outcome(
                &args,
                log,
                &VerifyOutcome::CannotVerify { reason },
                &label_for_diag,
            );
            return Err(CliError::Exit(2));
        }

        match AuditKey::load_or_generate(&key_path) {
            Ok(k) => Verifier::Private(Box::new(k)),
            Err(e) => {
                let reason = format!("audit key load failed: {e}");
                emit_verify_outcome(
                    &args,
                    log,
                    &VerifyOutcome::CannotVerify { reason },
                    &label_for_diag,
                );
                return Err(CliError::Exit(2));
            }
        }
    };

    // Branch on storage backend. SQLite: open the local file read-only.
    // Postgres: connect via sqlx and verify against the remote chain.
    let outcome = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => {
            verify_postgres(s, &verifier).await
        }
        _ => verify_sqlite(&db_path, &verifier).await,
    };

    let exit_code = audit_chain::outcome_to_exit_code(&outcome);
    emit_verify_outcome(&args, log, &outcome, &label_for_diag);
    if exit_code == 0 {
        Ok(())
    } else {
        Err(CliError::Exit(exit_code))
    }
}

/// `sysknife audit checkpoint`: sign the current chain tip and anchor it to an
/// external append-only database, then verify all anchored checkpoints against
/// the local chain. Anchoring off-box is what makes truncation/rewrite of the
/// local chain detectable.
pub async fn run_audit_checkpoint(
    args: crate::cli::AuditCheckpointArgs,
    _log: &Logger,
) -> Result<(), CliError> {
    use sysknife_daemon::audit_chain::{
        checkpoint_outcome_to_exit_code, outcome_to_exit_code, verify_chain, verify_checkpoints,
        AuditKey, CheckpointOutcome, VerifyOutcome,
    };
    use sysknife_daemon::checkpoint_sink::{CheckpointSink, PostgresCheckpointSink};
    use sysknife_daemon::transactions::TransactionStore;

    // Resolve the checkpoint database URL. Prefer the env var so credentials
    // are not exposed on the command line (visible via `ps` / shell history).
    let db_url = match args
        .db
        .clone()
        .or_else(|| std::env::var("SYSKNIFE_CHECKPOINT_DB").ok())
    {
        Some(u) => u,
        None => {
            eprintln!(
                "no checkpoint database configured; pass --db <URL> or set \
                 SYSKNIFE_CHECKPOINT_DB (preferred, keeps credentials off argv)"
            );
            return Err(CliError::Exit(2));
        }
    };

    let db_path = sysknife_core::default_database_path();

    // Load the private signing key (same location rules as `verify`).
    let key_path = sysknife_daemon::audit_chain::resolve_audit_key_path(&db_path);
    require_exists(&key_path, "audit key")?;
    let key = AuditKey::load_or_generate(&key_path).map_err(|e| {
        eprintln!("audit key load failed: {e}");
        CliError::Exit(2)
    })?;

    // Read the current chain tip from the local sqlite store.
    require_exists(&db_path, "audit database")?;
    let store = TransactionStore::open_read_only(&db_path).map_err(|e| {
        eprintln!("opening audit database failed: {e}");
        CliError::Exit(2)
    })?;
    let rows = store.fetch_chain_rows().map_err(|e| {
        eprintln!("reading audit chain failed: {e}");
        CliError::Exit(2)
    })?;
    let tip = match rows.last() {
        Some(t) => t,
        None => {
            eprintln!("audit chain is empty; nothing to checkpoint");
            return Err(CliError::Exit(2));
        }
    };

    // Refuse to anchor a chain that does not verify: anchoring the tip of a
    // tampered chain would launder it into a signed checkpoint.
    match verify_chain(&key, &rows) {
        VerifyOutcome::Intact { .. } => {}
        broken => {
            eprintln!("refusing to anchor: local audit chain does not verify: {broken:?}");
            return Err(CliError::Exit(outcome_to_exit_code(&broken)));
        }
    }

    let created_at = chrono::Utc::now().to_rfc3339();
    let checkpoint = key.sign_checkpoint(tip.seq, &tip.chain_hash, &created_at);

    // Anchor to the external append-only database.
    let sink = PostgresCheckpointSink::connect(&db_url)
        .await
        .map_err(|e| {
            eprintln!("connecting to checkpoint database failed: {e}");
            CliError::Exit(2)
        })?;
    sink.append(&checkpoint).await.map_err(|e| {
        eprintln!("anchoring checkpoint failed: {e}");
        CliError::Exit(2)
    })?;
    let tip_prefix = &checkpoint.chain_tip[..checkpoint.chain_tip.len().min(12)];
    println!(
        "anchored checkpoint: seq={} tip={tip_prefix}… -> external database",
        checkpoint.seq
    );

    // Read the anchored checkpoints back and confirm our write is actually
    // present, guarding against a lagging read replica or a wrong database
    // silently returning an empty/stale set (which would otherwise render as a
    // misleading "consistent (0 verified)").
    let anchored = sink.load_all().await.map_err(|e| {
        eprintln!("loading anchored checkpoints failed: {e}");
        CliError::Exit(2)
    })?;
    if !anchored.contains(&checkpoint) {
        eprintln!(
            "anchored checkpoint not found on read-back; the checkpoint database \
             may be a lagging replica or a different database than the write hit"
        );
        return Err(CliError::Exit(2));
    }

    // Verify every anchored checkpoint against the local chain.
    match verify_checkpoints(&key.verifying_key_hex(), &rows, &anchored) {
        CheckpointOutcome::Consistent {
            checkpoints_checked,
        } => {
            println!("checkpoints consistent ({checkpoints_checked} verified)");
            Ok(())
        }
        other => {
            eprintln!("checkpoint verification FAILED: {other:?}");
            Err(CliError::Exit(checkpoint_outcome_to_exit_code(&other)))
        }
    }
}

/// What the audit chain is verified against.
pub(crate) enum Verifier {
    /// The private signing key (also derives the public key used to verify).
    Private(Box<sysknife_daemon::audit_chain::AuditKey>),
    /// Only the hex-encoded Ed25519 public key — the auditor path, which proves
    /// the chain without the ability to forge it.
    Public(String),
}

pub(crate) async fn verify_sqlite(
    db_path: &std::path::Path,
    verifier: &Verifier,
) -> sysknife_daemon::audit_chain::VerifyOutcome {
    use sysknife_daemon::audit_chain::VerifyOutcome;
    use sysknife_daemon::transactions::TransactionStore;

    if !db_path.exists() {
        return VerifyOutcome::CannotVerify {
            reason: format!(
                "audit database not found at {}; set $SYSKNIFE_DATABASE_PATH \
                 or run the daemon first",
                db_path.display()
            ),
        };
    }
    let store = match TransactionStore::open_read_only(db_path) {
        Ok(s) => s,
        Err(e) => {
            return VerifyOutcome::CannotVerify {
                reason: format!("opening audit database failed: {e}"),
            };
        }
    };
    let result = match verifier {
        Verifier::Private(key) => store.verify_audit_chain(key),
        Verifier::Public(vk_hex) => store.verify_audit_chain_with_pubkey(vk_hex),
    };
    match result {
        Ok(o) => o,
        Err(e) => VerifyOutcome::CannotVerify {
            reason: format!("audit chain query failed: {e}"),
        },
    }
}

pub(crate) async fn verify_postgres(
    storage: &sysknife_core::config::StorageSection,
    verifier: &Verifier,
) -> sysknife_daemon::audit_chain::VerifyOutcome {
    use sysknife_core::config::StorageBackend;
    use sysknife_daemon::audit_chain::VerifyOutcome;
    use sysknife_daemon::store::postgres::{PostgresConfig, PostgresStore};
    use sysknife_daemon::store::AuditStore;

    // Project the relaxed config form into the type-state-checked enum;
    // the match below makes future backends a compile-time decision.
    let parsed = match storage.parsed() {
        Ok(p) => p,
        Err(reason) => return VerifyOutcome::CannotVerify { reason },
    };
    let (url, pool) =
        match parsed {
            StorageBackend::Sqlite => return VerifyOutcome::CannotVerify {
                reason:
                    "verify_postgres called with backend = \"sqlite\" — caller picks the wrong path"
                        .to_string(),
            },
            StorageBackend::Postgres { url, pool } => (url, pool),
        };

    let mut cfg = PostgresConfig {
        url,
        ..PostgresConfig::default()
    };
    {
        if let Some(n) = pool.max_connections {
            cfg.max_connections = n;
        }
        if let Some(s) = pool.acquire_timeout_secs {
            cfg.acquire_timeout = std::time::Duration::from_secs(s);
        }
        if let Some(c) = pool.statement_cache_capacity {
            cfg.statement_cache_capacity = c;
        }
    }

    match verifier {
        Verifier::Private(key) => {
            let store =
                match PostgresStore::connect(&cfg, std::sync::Arc::new((**key).clone())).await {
                    Ok(s) => s,
                    Err(e) => {
                        return VerifyOutcome::CannotVerify {
                            reason: format!("postgres connect failed: {e}"),
                        };
                    }
                };
            match store.verify_audit_chain(key).await {
                Ok(outcome) => outcome,
                Err(e) => VerifyOutcome::CannotVerify {
                    reason: format!("postgres audit chain query failed: {e}"),
                },
            }
        }
        Verifier::Public(verifying_key_hex) => {
            match PostgresStore::verify_with_pubkey(&cfg, verifying_key_hex).await {
                Ok(outcome) => outcome,
                Err(e) => VerifyOutcome::CannotVerify {
                    reason: format!("postgres audit chain query failed: {e}"),
                },
            }
        }
    }
}

fn emit_verify_outcome(
    args: &AuditVerifyArgs,
    log: &Logger,
    outcome: &sysknife_daemon::audit_chain::VerifyOutcome,
    backend_label: &str,
) {
    use sysknife_daemon::audit_chain::VerifyOutcome;
    if args.json {
        let payload = match outcome {
            VerifyOutcome::Intact { rows_checked } => json!({
                "status": "intact",
                "rows_checked": rows_checked,
                "backend": backend_label,
            }),
            VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq,
                first_broken_transaction_id,
                expected,
                actual,
            } => json!({
                "status": "broken",
                "rows_checked": rows_checked,
                "first_broken_seq": first_broken_seq,
                "first_broken_transaction_id": first_broken_transaction_id,
                "expected": expected,
                "actual": actual,
                "backend": backend_label,
            }),
            VerifyOutcome::CannotVerify { reason } => json!({
                "status": "cannot_verify",
                "reason": reason,
                "backend": backend_label,
            }),
        };
        log.println(
            &serde_json::to_string_pretty(&payload)
                .expect("verify outcome payload is serializable"),
        );
    } else {
        match outcome {
            VerifyOutcome::Intact { rows_checked } => {
                log.println(&format!(
                    "OK: {rows_checked} row(s) verified in {backend_label}"
                ));
            }
            VerifyOutcome::Broken {
                rows_checked,
                first_broken_seq,
                first_broken_transaction_id,
                expected,
                actual,
            } => {
                log.println(&format!(
                    "BROKEN: chain intact for first {rows_checked} row(s); \
                     row seq={first_broken_seq} (transaction {first_broken_transaction_id}) \
                     does not chain.\n  expected: {expected}\n  actual:   {actual}"
                ));
            }
            VerifyOutcome::CannotVerify { reason } => {
                log.println(&format!("CANNOT VERIFY: {reason}"));
            }
        }
    }
}

// ---------------------------------------------------------------------------
// run_intent
// ---------------------------------------------------------------------------

/// Plan and (optionally) execute a single natural-language intent.
pub async fn run_intent(intent: String, opts: &RunOpts, log: &Logger) -> Result<(), CliError> {
    let config = BrainConfig::from_env().map_err(|e| CliError::ConfigOrDaemon(e.to_string()))?;

    // Detect the running distro once at intent startup.
    // Failure is non-fatal: routing checks are skipped when detection fails
    // (the daemon will produce its own error at execution time).
    let distro = sysknife_core::distro::detect().ok();

    let plan_client = DaemonClient::new(opts.socket.clone());

    // Layer 3: planning event channel — planner emits PlanEvent as it works;
    // the CLI subscribes and updates the spinner message in real time.
    let (progress_tx, mut progress_rx) = tokio::sync::mpsc::unbounded_channel::<PlanEvent>();

    let mut planner = LlmPlanner::from_config(config, Box::new(plan_client))
        .map_err(CliError::ConfigOrDaemon)?
        .with_prefs_path(sysknife_core::config::prefs_path())
        .with_progress(progress_tx);
    if let Some(ref d) = distro {
        planner = planner.with_distro(distro_id_to_hint(d));
    }

    // Layer 1: spinner — auto-hidden by indicatif when stderr is not a TTY.
    let spinner =
        (!opts.json).then(|| crate::render::make_spinner(format!("Planning \"{intent}\"…")));

    // Spawn event updater: receives PlanEvent and updates the spinner message.
    // The task exits naturally when the channel closes (i.e. when the planner
    // is dropped after plan_intent returns).
    let spinner_for_task = spinner.clone();
    let event_task = tokio::spawn(async move {
        while let Some(event) = progress_rx.recv().await {
            if let Some(ref pb) = spinner_for_task {
                match event {
                    PlanEvent::Thinking => pb.set_message("Thinking…"),
                    PlanEvent::QueryingTool(ref name) => {
                        pb.set_message(format!("Querying {name}…"))
                    }
                    PlanEvent::ProposingPlan => pb.set_message("Proposing plan…"),
                }
            }
        }
    });

    // `plan_intent` may call `StateClient::curated_state()` (a blocking sync
    // Unix socket call) on the current async thread.  This is tolerable on
    // the multi-threaded runtime: the call is bounded by SOCKET_TIMEOUT (10 s)
    // and ties up one worker thread for at most that duration.
    let plan_result = planner.plan_intent(&intent).await;

    // Drop the planner to close the UnboundedSender, which closes the channel
    // and allows event_task to drain and exit.
    drop(planner);
    if let Err(e) = event_task.await {
        eprintln!("sysknife: event task panicked: {e}");
    }

    finish_spinner(&spinner);

    let plan = plan_result.map_err(|e| CliError::PlanningFailed(e.to_string()))?;

    // Surface any step where the planner's proposed risk disagreed with the
    // authoritative ActionSpec risk. A mismatch is a useful signal in its own
    // right — the model may be confused about this action (and could have gotten
    // its params wrong too), which the operator is well-placed to notice before
    // approving. Emitted to stderr so it never pollutes `--json` stdout.
    for step in plan.steps() {
        let authoritative = authoritative_plan_risk(step.action_name());
        if *step.risk_level() != authoritative {
            log.print_stderr(&format!(
                "sysknife: {} — planner rated {} risk; using {} (ActionSpec-derived)",
                step.action_name(),
                step.risk_level().as_str(),
                authoritative.as_str(),
            ));
        }
    }

    // Substitute the daemon's ActionSpec-derived risk (the single source of
    // truth) for the planner's proposed per-step risk, so the plan the operator
    // sees below and the auto-approval gate both reflect authoritative risk.
    // Without this, a planner that under-rates an action could let
    // `--yes --max-risk medium` auto-approve a step that is actually High risk.
    // This uses the CLI's *own* linked catalogue; the execution loop below
    // re-validates each step against the live daemon preview so a CLI/daemon
    // version skew can never execute above the approved risk.
    let plan = plan.with_authoritative_risks(authoritative_plan_risk);

    // ---- print plan --------------------------------------------------------

    if opts.json {
        let steps: Vec<Value> = plan
            .steps()
            .iter()
            .map(|s| {
                json!({
                    "action": s.action_name(),
                    "summary": s.summary(),
                    "risk": s.risk_level().as_str(),
                    "params": s.params(),
                })
            })
            .collect();
        log.println(
            &serde_json::to_string(&json!({
                "plan": { "intent": plan.intent(), "summary": plan.summary(), "steps": steps }
            }))
            .expect("static JSON"),
        );
    } else {
        crate::render::print_plan(&plan, log);
    }

    if opts.dry_run {
        if opts.step_by_step {
            log.print_stderr("warning: --step-by-step has no effect with --dry-run");
        }
        return Ok(());
    }

    // ---- plan-level approval (non-step-by-step) ----------------------------

    let policy = opts.approval_policy();

    if !opts.step_by_step {
        match policy.decide_plan(&plan) {
            ApprovalDecision::AutoApproved => {}
            ApprovalDecision::RequiresPrompt => {
                let n = plan.steps().len();
                let highest = highest_risk(&plan).expect("plan has steps");
                let msg = if opts.json {
                    "Execute this plan?".to_owned()
                } else {
                    format!(
                        "  {} step{}, {} risk — execute?",
                        n,
                        if n == 1 { "" } else { "s" },
                        crate::render::risk_colored(highest),
                    )
                };
                if !prompt_confirm(&msg).await {
                    return Err(CliError::Rejected);
                }
            }
            ApprovalDecision::RequiresInteraction => return Err(CliError::NonInteractive),
            ApprovalDecision::ExceedsCeiling => {
                let highest =
                    highest_risk(&plan).expect("ExceedsCeiling implies at least one step");
                return Err(CliError::RiskCeilingExceeded {
                    highest: highest.clone(),
                    ceiling: opts
                        .max_risk
                        .expect("ExceedsCeiling implies --max-risk was set"),
                });
            }
        }
    }

    // ---- distro routing guard ---------------------------------------------
    // Validate every step's action against the detected distro before
    // executing anything.  This surfaces a clear error for obviously wrong
    // plans (e.g. AptInstall on Fedora) without touching the daemon.
    if !opts.dry_run {
        for step in plan.steps() {
            if let Err(msg) =
                crate::distro_routing::check_action_distro(step.action_name(), distro.as_ref())
            {
                return Err(CliError::ConfigOrDaemon(msg));
            }
        }
    }

    // ---- execute steps -----------------------------------------------------

    let exec_client = DaemonClient::new(opts.socket.clone());
    let start = std::time::Instant::now();

    for step in plan.steps() {
        // Step-by-step: approve each step before previewing it.
        if opts.step_by_step {
            match policy.decide_step(step.risk_level()) {
                ApprovalDecision::AutoApproved => {}
                ApprovalDecision::RequiresPrompt => {
                    let msg = if opts.json {
                        format!("Execute {} ({})?", step.action_name(), step.summary())
                    } else {
                        format!(
                            "Execute {} ({} risk)?",
                            step.action_name(),
                            crate::render::risk_colored(step.risk_level()),
                        )
                    };
                    if !prompt_confirm(&msg).await {
                        return Err(CliError::Rejected);
                    }
                }
                ApprovalDecision::RequiresInteraction => return Err(CliError::NonInteractive),
                ApprovalDecision::ExceedsCeiling => {
                    return Err(CliError::RiskCeilingExceeded {
                        highest: step.risk_level().clone(),
                        ceiling: opts
                            .max_risk
                            .expect("ExceedsCeiling implies --max-risk was set"),
                    });
                }
            }
        }

        // Preview the step.
        let prepared = exec_client
            .preview(step.action_name(), step.params())
            .await?;
        let preview = &prepared.preview;

        // Fail closed on CLI/daemon risk skew: the approval decision above used
        // the CLI's own linked catalogue. If the live daemon rates this step
        // higher than we approved it at, refuse to mint a receipt rather than
        // execute above the approved risk (see `daemon_risk_within_approved`).
        let daemon_risk = plan_risk_of(preview.risk_level);
        if !daemon_risk_within_approved(step.risk_level(), &daemon_risk) {
            return Err(CliError::ConfigOrDaemon(format!(
                "{}: the running daemon rates this {} risk, above the {} the CLI approved — \
                 the CLI and daemon builds may differ. Aborting without executing; upgrade the \
                 CLI (or re-run with a matching --max-risk) so risk gating agrees.",
                step.action_name(),
                daemon_risk.as_str(),
                step.risk_level().as_str(),
            )));
        }

        if opts.json {
            log.println(&serde_json::to_string(preview).expect("PreviewEnvelope is Serialize"));
        } else {
            crate::render::print_step_header(step.action_name(), preview);
        }

        // Spinner clears on the first output line so execution output
        // streams naturally without a spinner in the way.
        let exec_spinner: Option<indicatif::ProgressBar> = (!opts.json)
            .then(|| crate::render::make_spinner(format!("Executing {}…", step.action_name())));
        let exec_spinner_ref = exec_spinner.clone();
        let mut first_line = true;

        let approval_receipt = exec_client.approve(&prepared.transaction_id).await?;
        let exec_result = exec_client
            .execute(
                &prepared.transaction_id,
                step.action_name(),
                step.params(),
                &approval_receipt,
                |line| {
                    if first_line {
                        finish_spinner(&exec_spinner_ref);
                        first_line = false;
                    }
                    if opts.json {
                        log.println(line);
                    } else {
                        crate::render::print_output_line(line, log);
                    }
                },
            )
            .await;

        // Always clear the exec spinner regardless of success or error.
        // finish_spinner() is idempotent, so this is safe even if the callback
        // already fired. If execute() errored before the first output line,
        // this prevents the spinner artifact from being left on the terminal.
        finish_spinner(&exec_spinner);

        exec_result.map(|result| {
            if opts.json {
                log.println(&serde_json::to_string(&result).expect("ResultEnvelope is Serialize"));
            } else {
                crate::render::print_step_done(&result, log);
            }
        })?;
    }

    if !opts.json {
        crate::render::print_success(start.elapsed().as_secs_f32(), log);
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// run_repl
// ---------------------------------------------------------------------------

/// Interactive REPL — reads intents with rustyline (arrow-key history,
/// Ctrl+R reverse search, Ctrl+C to cancel input, Ctrl+D to exit).
///
/// History persists across sessions in `~/.local/share/sysknife/history`.
///
/// `tokio::task::block_in_place` parks the current worker thread during each
/// blocking `readline()` call so other tasks on the multi-thread runtime can
/// run freely.  rustyline does not need to be `Send` with this approach.
pub async fn run_repl(opts: &RunOpts, log: &Logger) -> Result<(), CliError> {
    use rustyline::{error::ReadlineError, DefaultEditor};

    let history_path =
        std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share/sysknife/history"));

    let mut rl = DefaultEditor::new()
        .map_err(|e| CliError::ExecutionFailed(format!("readline init: {e}")))?;

    if let Some(ref p) = history_path {
        // Ensure the parent directory exists before the first load/save.
        if let Some(parent) = p.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                eprintln!(
                    "sysknife: failed to create history directory {}: {e}",
                    parent.display()
                );
            }
        }
        // Absence of the history file is not an error; any other failure is.
        match rl.load_history(p) {
            Ok(()) => {}
            Err(rustyline::error::ReadlineError::Io(e))
                if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                eprintln!("sysknife: failed to load history from {}: {e}", p.display());
            }
        }
    }

    loop {
        // Block the worker thread only during the blocking readline call.
        // Other tokio threads continue executing tasks unaffected.
        let readline_result = tokio::task::block_in_place(|| rl.readline("sysknife> "));

        match readline_result {
            Ok(line) => {
                let intent = line.trim().to_string();
                // Ignore the result: duplicates are silently skipped by rustyline.
                let _ = rl.add_history_entry(line.as_str());
                if intent.is_empty() {
                    continue;
                }
                if matches!(intent.as_str(), "exit" | "quit") {
                    break;
                }
                if let Err(e) = run_intent(intent, opts, log).await {
                    log.print_stderr(&format!("error: {e}"));
                }
            }
            Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break,
            Err(e) => {
                log.print_stderr(&format!("readline error: {e}"));
                break;
            }
        }
    }

    if let Some(ref p) = history_path {
        if let Err(e) = rl.save_history(p) {
            eprintln!("sysknife: failed to save history to {}: {e}", p.display());
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Clear `spinner` if one is present. A no-op when `spinner` is `None` (e.g.
/// `--json` mode, where no spinner was ever created) or already finished.
fn finish_spinner(spinner: &Option<indicatif::ProgressBar>) {
    if let Some(pb) = spinner {
        pb.finish_and_clear();
    }
}

/// Check that `path` exists; if not, print `"{what} not found at <path>"` to
/// stderr and fail with exit code 2 (used by `run_audit_checkpoint`, which
/// checks both the audit key file and the audit database file this way).
fn require_exists(path: &std::path::Path, what: &str) -> Result<(), CliError> {
    if path.exists() {
        Ok(())
    } else {
        eprintln!("{what} not found at {}", path.display());
        Err(CliError::Exit(2))
    }
}

/// Ask the user a yes/no question on stderr; return `true` iff they answer "y"
/// or "yes" (case-insensitive).
///
/// Uses `tokio::io::stdin` to keep the async executor free while waiting for
/// input.  On EOF or an I/O error a warning is printed to stderr and the
/// function returns `false` (safe default: do not execute).
async fn prompt_confirm(msg: &str) -> bool {
    use tokio::io::AsyncBufReadExt as _;

    eprint!("{msg} [y/N] ");
    let _ = io::stderr().flush();

    let stdin = tokio::io::stdin();
    let mut reader = tokio::io::BufReader::new(stdin);
    let mut buf = String::new();

    match reader.read_line(&mut buf).await {
        Ok(0) => {
            eprintln!("\nsysknife: stdin closed (EOF) — treating as 'no'");
            false
        }
        Err(e) => {
            eprintln!("\nsysknife: stdin read error ({e}) — treating as 'no'");
            false
        }
        Ok(_) => matches!(buf.trim().to_ascii_lowercase().as_str(), "y" | "yes"),
    }
}

async fn prompt_exact(msg: &str, expected: &str) -> bool {
    use tokio::io::AsyncBufReadExt as _;

    eprint!("{msg} ({expected}): ");
    let _ = io::stderr().flush();
    let mut reader = tokio::io::BufReader::new(tokio::io::stdin());
    let mut buf = String::new();
    match reader.read_line(&mut buf).await {
        Ok(0) | Err(_) => false,
        Ok(_) => buf.trim() == expected,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use sysknife_brain::action_name::ActionName;
    use sysknife_brain::planner::{Plan, PlanStep};

    /// Serialize env-var mutations so concurrent tests do not race on
    /// `SYSKNIFE_SOCKET`.  All tests that call `set_var` / `remove_var` must
    /// hold this lock for the full duration of the env read.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    // -----------------------------------------------------------------------
    // rfc3339_to_unix — pure function, tests against known epoch values
    // -----------------------------------------------------------------------

    #[test]
    fn rfc3339_unix_epoch_z() {
        assert_eq!(rfc3339_to_unix("1970-01-01T00:00:00Z"), Some(0));
    }

    #[test]
    fn rfc3339_unix_epoch_plus00() {
        assert_eq!(rfc3339_to_unix("1970-01-01T00:00:00+00:00"), Some(0));
    }

    #[test]
    fn rfc3339_unix_one_day() {
        assert_eq!(rfc3339_to_unix("1970-01-02T00:00:00Z"), Some(86_400));
    }

    #[test]
    fn rfc3339_unix_y2k() {
        // 2000-01-01T00:00:00Z = 946684800
        assert_eq!(rfc3339_to_unix("2000-01-01T00:00:00Z"), Some(946_684_800));
    }

    #[test]
    fn rfc3339_unix_leap_day_2000() {
        // 2000-02-29: Jan has 31 days, then 28 more days = 59 days from 2000-01-01.
        // 946684800 + 59 * 86400 = 946684800 + 5097600 = 951782400
        assert_eq!(rfc3339_to_unix("2000-02-29T00:00:00Z"), Some(951_782_400));
    }

    #[test]
    fn rfc3339_unix_with_subseconds() {
        // Sub-second fraction should be stripped.
        assert_eq!(
            rfc3339_to_unix("2000-01-01T00:00:00.123456Z"),
            Some(946_684_800)
        );
    }

    #[test]
    fn rfc3339_unix_non_utc_returns_none() {
        assert!(rfc3339_to_unix("2000-01-01T00:00:00+05:00").is_none());
    }

    #[test]
    fn rfc3339_unix_no_suffix_returns_none() {
        assert!(rfc3339_to_unix("2000-01-01T00:00:00").is_none());
    }

    #[test]
    fn rfc3339_unix_garbage_returns_none() {
        assert!(rfc3339_to_unix("not-a-date").is_none());
        assert!(rfc3339_to_unix("").is_none());
    }

    #[test]
    fn rfc3339_unix_invalid_month_returns_none() {
        assert!(rfc3339_to_unix("2000-13-01T00:00:00Z").is_none());
    }

    #[test]
    fn rfc3339_unix_invalid_hour_returns_none() {
        assert!(rfc3339_to_unix("2000-01-01T25:00:00Z").is_none());
    }

    #[test]
    fn rfc3339_unix_day_zero_returns_none() {
        // Day 0 is out of range; the lower bound of the `!(1..=31)` check.
        assert!(rfc3339_to_unix("2000-01-00T00:00:00Z").is_none());
    }

    // -----------------------------------------------------------------------
    // since_to_hours
    // -----------------------------------------------------------------------

    #[test]
    fn since_to_hours_y2k_is_many_hours_ago() {
        // Y2K was well over 200_000 hours ago (as of 2026).
        let h = since_to_hours("2000-01-01T00:00:00Z").expect("should parse");
        assert!(h > 200_000, "expected >200000 hours, got {h}");
    }

    #[test]
    fn since_to_hours_far_future_returns_none() {
        // Year 9999 is in the future.
        assert!(since_to_hours("9999-12-31T23:59:59Z").is_none());
    }

    #[test]
    fn since_to_hours_garbage_returns_none() {
        assert!(since_to_hours("not-a-date").is_none());
    }

    #[test]
    fn since_to_hours_epoch_returns_many_hours() {
        // Unix epoch (1970-01-01) is always ≥ 486000 hours ago (as of 2026).
        let h = since_to_hours("1970-01-01T00:00:00Z").expect("should parse");
        assert!(h > 486_000, "expected >486000, got {h}");
    }

    #[test]
    fn since_to_hours_integer_division_not_modulo() {
        // Two timestamps exactly 1 hour apart must differ by 1 in since_to_hours.
        // A `% 3600` regression would produce wildly different results for these.
        let h0 = since_to_hours("1970-01-01T00:00:00Z").unwrap();
        let h1 = since_to_hours("1970-01-01T01:00:00Z").unwrap();
        assert_eq!(h0, h1 + 1, "timestamps 1 h apart must differ by exactly 1");
    }

    // -----------------------------------------------------------------------
    // highest_risk
    // -----------------------------------------------------------------------

    fn make_step(risk: PlanRiskLevel) -> PlanStep {
        PlanStep::new(
            ActionName::parse("GetDiskUsage").unwrap(),
            "test".into(),
            risk,
            serde_json::json!({}),
        )
        .unwrap()
    }

    fn make_plan(risks: &[PlanRiskLevel]) -> Plan {
        Plan::new(
            "test".into(),
            "test plan".into(),
            "explanation".into(),
            risks.iter().map(|r| make_step(r.clone())).collect(),
        )
        .unwrap()
    }

    // Note: Plan::new rejects empty step lists (PlanValidationError), so
    // `highest_risk` is never called on an empty plan in practice.  The return
    // type is `Option<_>` purely for type-safety against future API changes.

    #[test]
    fn highest_risk_single_low() {
        let plan = make_plan(&[PlanRiskLevel::Low]);
        assert_eq!(highest_risk(&plan), Some(&PlanRiskLevel::Low));
    }

    #[test]
    fn highest_risk_all_high() {
        let plan = make_plan(&[PlanRiskLevel::High, PlanRiskLevel::High]);
        assert_eq!(highest_risk(&plan), Some(&PlanRiskLevel::High));
    }

    #[test]
    fn highest_risk_mixed_picks_highest() {
        let plan = make_plan(&[
            PlanRiskLevel::Low,
            PlanRiskLevel::High,
            PlanRiskLevel::Medium,
        ]);
        assert_eq!(highest_risk(&plan), Some(&PlanRiskLevel::High));
    }

    #[test]
    fn highest_risk_low_medium_picks_medium() {
        let plan = make_plan(&[PlanRiskLevel::Low, PlanRiskLevel::Medium]);
        assert_eq!(highest_risk(&plan), Some(&PlanRiskLevel::Medium));
    }

    // -----------------------------------------------------------------------
    // authoritative_plan_risk — CLI approval gates on the daemon's spec risk
    // -----------------------------------------------------------------------

    #[test]
    fn authoritative_plan_risk_maps_spec_gate_risk() {
        // Values come from each action's ActionSpec via preview::gate_risk.
        assert_eq!(authoritative_plan_risk("GetDiskUsage"), PlanRiskLevel::Low);
        assert_eq!(
            authoritative_plan_risk("RestartService"),
            PlanRiskLevel::Medium
        );
        assert_eq!(authoritative_plan_risk("RebootSystem"), PlanRiskLevel::High);
        // No spec → conservative High (a missing spec never downgrades friction).
        assert_eq!(
            authoritative_plan_risk("DefinitelyNotARealAction"),
            PlanRiskLevel::High
        );
    }

    #[test]
    fn authoritative_risks_close_the_llm_under_rating_gate() {
        let mk = |name: &str, risk| {
            PlanStep::new(
                ActionName::parse(name).unwrap(),
                "s".into(),
                risk,
                serde_json::json!({}),
            )
            .unwrap()
        };
        // An LLM that under-rates a truly High-risk action (RebootSystem) as Low
        // would let `--yes --max-risk medium` auto-approve it...
        let under_rated = Plan::new(
            "i".into(),
            "s".into(),
            "e".into(),
            vec![mk("RebootSystem", PlanRiskLevel::Low)],
        )
        .unwrap();
        let policy = ApprovalPolicy::new(true, Some(MaxRisk::Medium), false, false);
        assert_eq!(
            policy.decide_plan(&under_rated),
            ApprovalDecision::AutoApproved,
            "sanity: the LLM's Low rating alone would have auto-approved"
        );

        // ...but substituting the spec-derived risk restores the gate: RebootSystem
        // is High, which exceeds the Medium auto-approval ceiling.
        let corrected = under_rated.with_authoritative_risks(authoritative_plan_risk);
        assert_eq!(
            policy.decide_plan(&corrected),
            ApprovalDecision::ExceedsCeiling,
            "spec-derived High must not auto-approve under --max-risk medium"
        );
    }

    #[test]
    fn authoritative_risks_close_the_under_rating_gate_for_bare_yes() {
        // The most common invocation: `--yes` with no `--max-risk` (auto-ceiling
        // defaults to Low). A planner under-rating a Medium action as Low would
        // otherwise auto-execute it with zero confirmation.
        let mk = |name: &str, risk| {
            PlanStep::new(
                ActionName::parse(name).unwrap(),
                "s".into(),
                risk,
                serde_json::json!({}),
            )
            .unwrap()
        };
        let plan = Plan::new(
            "i".into(),
            "s".into(),
            "e".into(),
            vec![mk("RestartService", PlanRiskLevel::Low)],
        )
        .unwrap();
        let policy = ApprovalPolicy::new(true, None, false, false);
        assert_eq!(
            policy.decide_plan(&plan),
            ApprovalDecision::AutoApproved,
            "sanity: bare --yes would auto-approve the Low the planner claimed"
        );
        let corrected = plan.with_authoritative_risks(authoritative_plan_risk);
        assert_eq!(
            policy.decide_plan(&corrected),
            ApprovalDecision::RequiresPrompt,
            "spec-derived Medium must prompt under bare --yes"
        );
    }

    #[test]
    fn authoritative_risks_force_interaction_for_under_rated_action_non_interactive() {
        // Scripted/non-interactive runs have no human watching: an under-rated
        // action must hard-fail (RequiresInteraction), never auto-run.
        let mk = |name: &str, risk| {
            PlanStep::new(
                ActionName::parse(name).unwrap(),
                "s".into(),
                risk,
                serde_json::json!({}),
            )
            .unwrap()
        };
        let plan = Plan::new(
            "i".into(),
            "s".into(),
            "e".into(),
            vec![mk("RestartService", PlanRiskLevel::Low)],
        )
        .unwrap();
        let policy = ApprovalPolicy::new(true, None, true, false);
        assert_eq!(
            policy.decide_plan(&plan),
            ApprovalDecision::AutoApproved,
            "sanity: the planner's Low would have auto-run unattended"
        );
        let corrected = plan.with_authoritative_risks(authoritative_plan_risk);
        assert_eq!(
            policy.decide_plan(&corrected),
            ApprovalDecision::RequiresInteraction,
            "under-rated Medium must abort a non-interactive run"
        );
    }

    #[test]
    fn authoritative_risks_open_the_over_rating_gate() {
        // Over-rating direction: a truly-Low action the planner flagged High must
        // NOT be needlessly blocked after substitution — proves the substitution
        // is a pure override, not max(planner, spec).
        let mk = |name: &str, risk| {
            PlanStep::new(
                ActionName::parse(name).unwrap(),
                "s".into(),
                risk,
                serde_json::json!({}),
            )
            .unwrap()
        };
        let plan = Plan::new(
            "i".into(),
            "s".into(),
            "e".into(),
            vec![mk("GetDiskUsage", PlanRiskLevel::High)],
        )
        .unwrap();
        let policy = ApprovalPolicy::new(true, Some(MaxRisk::Low), false, false);
        assert_eq!(
            policy.decide_plan(&plan),
            ApprovalDecision::ExceedsCeiling,
            "sanity: the planner's inflated High would block a safe read-only action"
        );
        let corrected = plan.with_authoritative_risks(authoritative_plan_risk);
        assert_eq!(
            policy.decide_plan(&corrected),
            ApprovalDecision::AutoApproved,
            "spec-derived Low must auto-approve under --max-risk low"
        );
    }

    #[test]
    fn daemon_risk_within_approved_fails_closed_on_upward_skew() {
        use PlanRiskLevel::{High, Low, Medium};
        // Daemon risk == or < approved → allowed.
        assert!(daemon_risk_within_approved(&Medium, &Medium));
        assert!(daemon_risk_within_approved(&High, &Low));
        assert!(daemon_risk_within_approved(&Medium, &Low));
        // Daemon rates HIGHER than approved → must fail closed.
        assert!(!daemon_risk_within_approved(&Medium, &High));
        assert!(!daemon_risk_within_approved(&Low, &Medium));
        assert!(!daemon_risk_within_approved(&Low, &High));
    }

    // -----------------------------------------------------------------------
    // build_history_params
    // -----------------------------------------------------------------------

    #[test]
    fn build_history_params_minimal() {
        let p = build_history_params(20, None, None, None);
        assert_eq!(p["limit"], json!(20));
        assert!(p.get("status_filter").is_none());
        assert!(p.get("action_filter").is_none());
        assert!(p.get("since_hours").is_none());
    }

    #[test]
    fn build_history_params_all_fields() {
        let p = build_history_params(5, Some("succeeded"), Some("InstallPackages"), Some(48));
        assert_eq!(p["limit"], json!(5));
        assert_eq!(p["status_filter"], json!("succeeded"));
        assert_eq!(p["action_filter"], json!("InstallPackages"));
        assert_eq!(p["since_hours"], json!(48));
    }

    #[test]
    fn build_history_params_status_only() {
        let p = build_history_params(10, Some("failed"), None, None);
        assert_eq!(p["limit"], json!(10));
        assert_eq!(p["status_filter"], json!("failed"));
        assert!(p.get("action_filter").is_none());
        assert!(p.get("since_hours").is_none());
    }

    // -----------------------------------------------------------------------
    // run_history --since error mapping
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn run_history_invalid_since_returns_config_error() {
        // An unparseable --since must return CliError::ConfigOrDaemon without
        // ever touching the daemon socket (the socket path here is unused).
        let args = HistoryArgs {
            status: None,
            action: None,
            since: Some("not-a-date".into()),
            limit: 20,
        };
        let log = Logger::new(None).unwrap();
        let result = run_history(
            args,
            SocketTarget::Unix(PathBuf::from("/nonexistent.sock")),
            &log,
        )
        .await;
        match result {
            Err(CliError::ConfigOrDaemon(msg)) => {
                assert!(
                    msg.contains("--since"),
                    "error message must reference --since"
                );
            }
            other => panic!("expected ConfigOrDaemon, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn run_history_future_since_returns_config_error() {
        let args = HistoryArgs {
            status: None,
            action: None,
            since: Some("9999-12-31T23:59:59Z".into()),
            limit: 20,
        };
        let log = Logger::new(None).unwrap();
        let result = run_history(
            args,
            SocketTarget::Unix(PathBuf::from("/nonexistent.sock")),
            &log,
        )
        .await;
        match result {
            Err(CliError::ConfigOrDaemon(msg)) => {
                assert!(msg.contains("future"), "error must say 'future'");
            }
            other => panic!("expected ConfigOrDaemon, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // resolve_socket_target uses SYSKNIFE_SOCKET env var
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_socket_target_falls_back_to_core_default_listen_uri() {
        // With no explicit SYSKNIFE_SOCKET override, the CLI must resolve to the
        // same target the daemon binds — sysknife_core::default_listen_uri(),
        // whose top precedence is SYSKNIFE_LISTEN_URI. Regression guard for the
        // dev/non-systemd socket mismatch (the production path used to be
        // hardcoded here, so `sysknife doctor` could not reach a dev daemon).
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::remove_var("SYSKNIFE_SOCKET");
            std::env::set_var(
                "SYSKNIFE_LISTEN_URI",
                "unix:///run/user/4242/sysknife/daemon.sock",
            );
        }
        let t = resolve_socket_target();
        unsafe { std::env::remove_var("SYSKNIFE_LISTEN_URI") };
        assert_eq!(
            t,
            crate::client::SocketTarget::Unix(PathBuf::from("/run/user/4242/sysknife/daemon.sock"))
        );
    }

    #[test]
    fn resolve_socket_target_parses_unix_uri() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var("SYSKNIFE_SOCKET", "unix:///tmp/custom.sock") };
        let t = resolve_socket_target();
        unsafe { std::env::remove_var("SYSKNIFE_SOCKET") };
        assert_eq!(
            t,
            crate::client::SocketTarget::Unix(PathBuf::from("/tmp/custom.sock"))
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn resolve_socket_target_parses_vsock_uri() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var("SYSKNIFE_SOCKET", "vsock://3:7777") };
        let t = resolve_socket_target();
        unsafe { std::env::remove_var("SYSKNIFE_SOCKET") };
        assert_eq!(t, crate::client::SocketTarget::Vsock { cid: 3, port: 7777 });
    }
}