ignition-cli 1.2.0

ign — operate Ignition 8.3+ gateways from the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
//! Output rendering for the `ign` bin — the ONLY home of human-mode output
//! (never in core; ARCHITECTURE.md layering invariant).
//!
//! Stream discipline: success renders to stdout in every mode; errors render
//! to stderr in every mode (human-readable by default; the JSON envelope
//! under `--json`/`--compact`) — no crossover. JSON strings come from
//! `ignition_core::output` (pretty or compact per the LOCKED precedence:
//! `--compact` implies `--json`).
//!
//! CORE-01 human path (research Pattern 4): EVERY human-mode render —
//! success AND error — begins with an active-profile header line
//! `[profile: NAME]` when a profile resolved; the header is omitted when
//! none did (a fresh install keeps the bare version line). JSON/compact
//! modes are untouched — the envelope's top-level `profile` field is their
//! mechanism.

use ignition_core::actions::apicall::ApiCallOutcome;
use ignition_core::actions::backup::{BackupDownloadResult, BackupRestoreResult};
use ignition_core::actions::connections::ConnectionsResult;
use ignition_core::actions::diagnostics::{BundleDownloadResult, BundleStatusWire};
use ignition_core::actions::eam::{
    EamDeleteResult, EamHistoryResult, EamLifecycleResult, EamModifyResult, EamTaskCreateResult,
    EamTaskDetailResult, EamTaskForceResult, EamTasksResult,
};
use ignition_core::actions::gan::GanStatusResult;
use ignition_core::actions::inspect::{MetricsResult, ModulesResult, StatusResult};
use ignition_core::actions::license::LicenseStatusResult;
use ignition_core::actions::lint::LintResult;
use ignition_core::actions::logs::{
    DownloadResult, LogPage, ResetResult, SetLevelResult, TailResult,
};
use ignition_core::actions::projects::{
    ExportDecodedResult, ExportResult, ImportResult, ProjectCopyResult, ProjectDeleteResult,
    ProjectDiffResult, ProjectRenameResult, ProjectSetResult, ProjectSyncResult, ProjectsResult,
};
use ignition_core::actions::redundancy::RedundancyStatusResult;
use ignition_core::actions::resources::{
    ResourceDeleteResult, ResourceGetResult, ResourcePutResult, ResourcesResult,
};
use ignition_core::actions::rig::{
    RestoreResult, RigDownResult, RigLogsResult, RigResetResult, RigStatusResult, RigUpResult,
    SnapshotResult, TrialResetResult, TrialStatusResult,
};
use ignition_core::actions::script::ScriptRunResult;
use ignition_core::actions::sessions::{SessionsResult, TerminateResult};
use ignition_core::actions::tags::{
    BrowseRow, LossReport, TagBrowseFromExportResult, TagProvidersResult, TagsAlarmsAckResult,
    TagsAlarmsActiveResult, TagsAlarmsHistoryResult, TagsBrowseResult, TagsConfigGetResult,
    TagsExportResult, TagsHistoryQueryResult, TagsReadResult, TagsUdtDefResult, TagsUdtTypesResult,
    history_summary,
};
use ignition_core::actions::webdev::{WebdevDeployResult, WebdevStatusResult};
use ignition_core::actions::workspace::{
    CheckoutOutcome, PushOutcome, StatusKind, WorkspaceStatus,
};
use ignition_core::client::logs::LogEntry;
use ignition_core::client::query::ListEnvelope;
use ignition_core::error::CoreError;
use ignition_core::output::render_failure;

use crate::ActionOutput;

/// The three render modes. Resolved exactly once, in `main`, by
/// [`RenderMode::resolve`] — the single precedence decision.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderMode {
    /// Default: human-readable lines/tables, rendered here (bin-only).
    Human,
    /// `--json`: pretty-printed envelope on stdout.
    PrettyJson,
    /// `--compact`: one-line envelope on stdout. Implies `--json`.
    CompactJson,
}

impl RenderMode {
    /// The LOCKED precedence (Pitfall 6): `--compact` implies `--json`.
    pub fn resolve(json: bool, compact: bool) -> Self {
        if compact {
            Self::CompactJson
        } else if json {
            Self::PrettyJson
        } else {
            Self::Human
        }
    }

    fn is_json(self) -> bool {
        matches!(self, Self::PrettyJson | Self::CompactJson)
    }
}

/// Success path — ALWAYS stdout.
pub fn render_ok(out: &ActionOutput, profile: Option<&str>, mode: RenderMode) {
    // The ONE sanctioned stdout exception: completions print the raw
    // script regardless of --json (shells source stdout; see completions.rs
    // and the README contract note). No profile header either — the script
    // must stay clean for sourcing.
    if let ActionOutput::Completions { shell } = out {
        print!("{}", crate::completions::completions(*shell));
        return;
    }
    // The SECOND sanctioned stdout exception: a completed tail already
    // streamed every entry to stdout as it arrived (human lines or
    // NDJSON — README §Streaming); there is nothing left to render.
    // The THIRD is its sibling: `rig logs` already streamed its raw
    // compose lines in EVERY mode (passthrough — same exception).
    if matches!(out, ActionOutput::LogsTail(_) | ActionOutput::RigLogs(_)) {
        return;
    }
    // The FOURTH sanctioned stdout exception: a stdout-mode export
    // (`tags export -o -`) prints its payload RAW in EVERY mode —
    // the payload IS the product (piping `tags export -o -` into
    // `tags import --file -` is the round-trip); no envelope, no
    // profile header (README §Streaming). 11-05: xml/csv ride `raw`
    // (the gateway/generator bytes VERBATIM — no re-encoding, no
    // added trailing newline); json keeps the pretty payload. Human
    // mode adds a one-line artifact summary plus the csv lossy
    // warnings on STDERR — never stdout (the pipe stays pure; json
    // mode reads the same findings from data.loss_report).
    if let ActionOutput::TagsExport(result) = out
        && result.stdout
    {
        let bytes = result
            .raw
            .as_deref()
            .or(result.payload.as_deref())
            .unwrap_or_default();
        print!("{bytes}");
        if mode == RenderMode::Human && result.format != "json" {
            eprintln!(
                "exported {} path(s) → stdout ({}, {} tag(s))",
                result.paths.len(),
                result.format,
                result.tag_count
            );
            if let Some(report) = &result.loss_report {
                render_csv_loss_warnings(report);
            }
        }
        return;
    }
    // `ign tui` prints NOTHING on success in every mode (LOCKED Phase 6
    // stdout decision): the cockpit owned the alternate screen and
    // restored it; there is no envelope, no summary line.
    #[cfg(feature = "tui")]
    if matches!(out, ActionOutput::TuiExited) {
        return;
    }
    match mode {
        RenderMode::Human => render_human(out, profile),
        RenderMode::PrettyJson => {
            let rendered = out.render_json(profile, false);
            println!("{rendered}");
        }
        RenderMode::CompactJson => {
            let rendered = out.render_json(profile, true);
            println!("{rendered}");
        }
    }
}

/// Error path — ALWAYS stderr. Human-readable message + hint by default; the
/// JSON envelope under `--json`/`--compact`. The human form leads with the
/// active-profile header when one resolved (CORE-01).
pub fn render_error(err: &CoreError, profile: Option<&str>, mode: RenderMode) {
    if mode.is_json() {
        let envelope = err.envelope(profile);
        let rendered = render_failure(&envelope, mode == RenderMode::CompactJson);
        eprintln!("{rendered}");
    } else {
        if let Some(name) = profile {
            eprintln!("[profile: {name}]");
        }
        eprintln!("error: {err}");
        if let Some(hint) = err.hint() {
            eprintln!("hint: {hint}");
        }
    }
}

/// Human mode: active-profile header line first (CORE-01, Pattern 4), then
/// plain lines per command — always here, never in core.
fn render_human(out: &ActionOutput, profile: Option<&str>) {
    if let Some(name) = profile {
        println!("[profile: {name}]");
    }
    match out {
        ActionOutput::Version(result) => {
            println!("ign {} (ignition-cli)", result.cli_version);
            if let Some(gateway) = &result.gateway {
                let edition = gateway.edition.as_deref().unwrap_or("unknown edition");
                println!("gateway {} ({edition})", gateway.ignition_version);
            }
            for warning in &result.warnings {
                println!("warning: {warning}");
            }
        }
        ActionOutput::Status(result) => render_status_human(result),
        ActionOutput::Modules(result) => render_modules_human(result),
        ActionOutput::Metrics(result) => render_metrics_human(result),
        ActionOutput::Sessions(result) => render_sessions_human(result),
        ActionOutput::SessionsTerminate(result) => render_terminate_human(result),
        ActionOutput::Connections(result) => render_connections_human(result),
        ActionOutput::LogsList(result) => render_logs_list_human(result),
        // Unreachable: render_ok intercepts LogsTail before mode
        // dispatch (the streaming exception — entries already printed).
        ActionOutput::LogsTail(result) => render_tail_human(result),
        ActionOutput::LogsDownload(result) => render_download_human(result),
        ActionOutput::LoggersList(result) => render_loggers_human(result),
        ActionOutput::LoggerSet(result) => render_set_level_human(result),
        ActionOutput::LoggerReset(result) => render_reset_human(result),
        ActionOutput::Restart(result) => render_restart_human(result),
        ActionOutput::RestartWait(result) => render_restart_wait_human(result),
        ActionOutput::Wait(result) => render_wait_human(result),
        ActionOutput::Doctor(result) => render_doctor_human(result),
        ActionOutput::Adopt(result) => render_adopt_human(result),
        // Unreachable: render_ok intercepts Completions before mode
        // dispatch (the sanctioned stdout exception).
        ActionOutput::Completions { shell } => {
            print!("{}", crate::completions::completions(*shell));
        }
        ActionOutput::ProfileAdd(result) => {
            println!("added profile {} ({})", result.name, result.url);
            if result.active {
                println!("active profile set to {}", result.name);
            }
        }
        ActionOutput::ProfileList(result) => {
            for summary in &result.profiles {
                let label = summary.label.as_deref().unwrap_or(&summary.name);
                println!(
                    "{}  {}  {}  {}",
                    summary.name, label, summary.url, summary.auth_kind
                );
            }
        }
        ActionOutput::ProfileUse(result) => println!("active profile set to {}", result.active),
        ActionOutput::ProjectsList(result) => render_projects_list_human(result),
        ActionOutput::ProjectNew(result) => render_project_new_human(result),
        ActionOutput::ProjectCopy(result) => render_project_copy_human(result),
        ActionOutput::ProjectRename(result) => render_project_rename_human(result),
        ActionOutput::ProjectSet(result) => render_project_set_human(result),
        ActionOutput::ProjectDelete(result) => render_project_delete_human(result),
        ActionOutput::ProjectExport(result) => render_project_export_human(result),
        ActionOutput::ProjectExportDecoded(result) => render_project_export_decoded_human(result),
        ActionOutput::ProjectImport(result) => render_project_import_human(result),
        ActionOutput::ProjectDiff(result) => render_project_diff_human(result),
        ActionOutput::ProjectSync(result) => render_project_sync_human(result),
        ActionOutput::ResourcesList(result) => render_resources_list_human(result),
        ActionOutput::ResourceGet(result) => render_resource_get_human(result),
        ActionOutput::ResourcePut(result) => render_resource_put_human(result),
        ActionOutput::ResourceDelete(result) => render_resource_delete_human(result),
        ActionOutput::RigUp(result) => render_rig_up_human(result),
        ActionOutput::RigDown(result) => render_rig_down_human(result),
        ActionOutput::RigReset(result) => render_rig_reset_human(result),
        ActionOutput::RigStatus(result) => render_rig_status_human(result),
        // Unreachable: render_ok intercepts RigLogs before mode
        // dispatch (the third streaming exception — lines already
        // printed during execution).
        ActionOutput::RigLogs(result) => render_rig_logs_human(result),
        ActionOutput::RigSnapshot(result) => render_rig_snapshot_human(result),
        ActionOutput::RigRestore(result) => render_rig_restore_human(result),
        ActionOutput::BackupDownload(result) => render_backup_download_human(result),
        ActionOutput::BackupRestore(result) => render_backup_restore_human(result),
        ActionOutput::EamHistory(result) => render_eam_history_human(result),
        ActionOutput::EamTasks(result) => render_eam_tasks_human(result),
        ActionOutput::EamTaskDetail(result) => render_eam_task_detail_human(result),
        ActionOutput::EamTaskCreate(result) => render_eam_task_create_human(result),
        ActionOutput::EamTaskForce(result) => render_eam_task_force_human(result),
        ActionOutput::EamTaskLifecycle(result) => render_eam_task_lifecycle_human(result),
        ActionOutput::EamTaskModify(result) => render_eam_task_modify_human(result),
        ActionOutput::EamTaskDelete(result) => render_eam_task_delete_human(result),
        ActionOutput::ScriptRun(result) => render_script_run_human(result),
        ActionOutput::Lint(result) => render_lint_human(result),
        ActionOutput::ApiCall(result) => render_api_call_human(result),
        ActionOutput::LicenseStatus(result) => render_license_status_human(result),
        ActionOutput::RedundancyStatus(result) => render_redundancy_status_human(result),
        ActionOutput::GanStatus(result) => render_gan_status_human(result),
        ActionOutput::BundleGenerate(result) => {
            render_bundle_status_line("generation started", result)
        }
        ActionOutput::BundleStatus(result) => render_bundle_status_line("status", result),
        ActionOutput::BundleWait(result) => render_bundle_status_line("wait complete", result),
        ActionOutput::BundleDownload(result) => render_bundle_download_human(result),
        ActionOutput::RigTrialStatus(result) => render_trial_status_human(result),
        ActionOutput::RigTrialReset(result) => render_trial_reset_human(result),
        ActionOutput::WebdevDeploy(result) => render_webdev_deploy_human(result),
        ActionOutput::WebdevStatus(result) => render_webdev_status_human(result),
        ActionOutput::TagProviders(result) => render_tag_providers_human(result),
        ActionOutput::TagProviderCreate(result) => {
            println!("created tag provider {}", result.name);
        }
        ActionOutput::TagProviderDelete(result) => {
            println!("deleted tag provider {}", result.deleted);
        }
        ActionOutput::TagsBrowse(result) => render_tags_browse_human(result),
        ActionOutput::TagsBrowseFromExport(result) => render_tags_browse_from_export_human(result),
        ActionOutput::TagsRead(result) => render_tags_read_human(result),
        ActionOutput::TagsWrite(result) => {
            println!("wrote {}  quality: {}", result.path, result.quality);
        }
        ActionOutput::TagsConfigGet(result) => render_tags_config_get_human(result),
        ActionOutput::TagsConfigCreate(result) | ActionOutput::TagsConfigEdit(result) => {
            println!(
                "{} {}  quality: {}",
                result.operation, result.path, result.quality
            );
        }
        ActionOutput::TagsConfigDelete(result) => {
            println!("deleted {} tag config(s)", result.deleted);
        }
        ActionOutput::TagsUdtTypes(result) => render_tags_udt_types_human(result),
        ActionOutput::TagsUdtDef(result) => render_tags_udt_def_human(result),
        // Unreachable in practice (render_ok intercepts the
        // stdout-mode export before mode dispatch — the payload
        // already printed raw).
        ActionOutput::TagsExport(result) => render_tags_export_human(result),
        ActionOutput::TagsImport(result) => {
            println!(
                "imported {} tag(s) into {} ({})",
                result.imported, result.provider, result.collision_policy
            );
            // 11-05: a confirmed --yes import surfaces its scan
            // findings on STDERR (loss prose never touches stdout —
            // the stdout purity lock); json mode reads the same
            // findings from data.loss_report.
            if let Some(report) = &result.loss_report {
                for fact in &report.facts {
                    eprintln!("warning: [{}] {}", fact.code, fact.detail);
                }
            }
            // The server-side backstop (11-04): Bad_Failure/Error_*
            // QualityCode ELEMENTS ride the gateway answer — recording
            // them keeps the honest-failure posture; never silently
            // reported as success.
            for failure in &result.failed {
                eprintln!("warning: gateway reported: {failure}");
            }
        }
        ActionOutput::TagsAlarmsActive(result) => render_tags_alarms_active_human(result),
        ActionOutput::TagsAlarmsHistory(result) => render_tags_alarms_history_human(result),
        ActionOutput::TagsAlarmsAck(result) => render_tags_alarms_ack_human(result),
        ActionOutput::TagsHistoryQuery(result) => render_tags_history_query_human(result),
        ActionOutput::WorkspaceCheckout(result) => render_workspace_checkout_human(result),
        ActionOutput::WorkspaceStatus(result) => render_workspace_status_human(result),
        ActionOutput::WorkspacePush(result) => render_workspace_push_human(result),
        // Unreachable: render_ok intercepts TuiExited before mode
        // dispatch (the prints-nothing decision).
        #[cfg(feature = "tui")]
        ActionOutput::TuiExited => {}
    }
}

/// `ign workspace checkout` human lines (13-07): the outcome line
/// plus the decode note when the codec leg ran.
fn render_workspace_checkout_human(result: &CheckoutOutcome) {
    println!(
        "checked out {} members → {}",
        result.member_count,
        result.target.display()
    );
    if result.scripts_decoded {
        println!(
            "scripts decoded — *.py sidecars + scripts-manifest.json; an unedited \
             re-encode is byte-exact"
        );
    }
}

/// The push-relative STATE token for one status row (13-06's
/// [`StatusKind`] vocabulary, human form). Direction-bearing where
/// the direction matters: `deleted (local)` is push `--delete`
/// territory, `deleted (gateway)` is pull territory.
fn workspace_state_label(kind: &StatusKind) -> &'static str {
    match kind {
        StatusKind::Clean => "clean",
        StatusKind::LocalEdit => "local_edit",
        StatusKind::GatewayDrift => "gateway_drift",
        StatusKind::Conflict => "conflict",
        StatusKind::Added { local: false } => "added",
        StatusKind::Added { local: true } => "added (local)",
        StatusKind::Deleted { local: true } => "deleted (local)",
        StatusKind::Deleted { local: false } => "deleted (gateway)",
        StatusKind::Untracked => "untracked",
    }
}

/// `ign workspace status` human render (13-07): a stable two-column
/// PATH / STATE table (two-space join, the project-list table
/// convention), clean rows INCLUDED — agents diff full state — then
/// the four-counter summary line. Rows arrive from core in
/// deterministic order (manifest members sorted by gateway path,
/// then gateway-only additions, then untracked sorted) and render in
/// that order.
fn render_workspace_status_human(result: &WorkspaceStatus) {
    for row in &result.rows {
        println!("{}  {}", row.path, workspace_state_label(&row.kind));
    }
    let local_edits = result
        .rows
        .iter()
        .filter(|row| matches!(row.kind, StatusKind::LocalEdit))
        .count();
    let drift = result
        .rows
        .iter()
        .filter(|row| matches!(row.kind, StatusKind::GatewayDrift))
        .count();
    let conflicts = result
        .rows
        .iter()
        .filter(|row| matches!(row.kind, StatusKind::Conflict))
        .count();
    let untracked = result
        .rows
        .iter()
        .filter(|row| matches!(row.kind, StatusKind::Untracked))
        .count();
    println!(
        "{local_edits} local edits, {drift} gateway drift, {conflicts} conflicts, \
         {untracked} untracked"
    );
}

/// `ign workspace push` human render (13-07): the bookkeeping header
/// plus the wrote/deleted/skipped lists (only non-empty lists print
/// lines — a zero-write push stays one honest line).
fn render_workspace_push_human(result: &PushOutcome) {
    println!(
        "pushed {} — wrote {}, deleted {}, skipped {}",
        result.project,
        result.wrote.len(),
        result.deleted.len(),
        result.skipped.len()
    );
    for path in &result.wrote {
        println!("  wrote: {path}");
    }
    for path in &result.deleted {
        println!("  deleted: {path}");
    }
    for path in &result.skipped {
        println!("  skipped: {path}");
    }
}

/// `ign status` human lines: identity, state, platform, uptime,
/// cpu/mem/disk, license (incl. the trial countdown — the
/// research-recommended banner).
fn render_status_human(result: &StatusResult) {
    let gateway = &result.gateway;
    let name = gateway.name.as_deref().unwrap_or("gateway");
    let edition = gateway.edition.as_deref().unwrap_or("unknown edition");
    println!("{}  {}  {}", name, gateway.ignition_version, edition);
    println!("state: {}", result.state);

    let overview = &result.overview;
    // Platform: "Java <version> (<vendor>) on <os name> (<arch>)" from
    // whichever halves the gateway reported.
    let java = overview
        .java
        .as_ref()
        .map(|java| format!("Java {} ({})", java.version, java.vendor));
    let os = overview
        .os
        .as_ref()
        .map(|os| format!("on {} ({})", os.name, os.arch));
    match (java, os) {
        (Some(java), Some(os)) => println!("platform: {java} {os}"),
        (Some(java), None) => println!("platform: {java}"),
        (None, Some(os)) => println!("platform: {os}"),
        (None, None) => {}
    }

    println!("uptime: {}", humanize_duration_ms(overview.uptime_ms));

    // Overview cpu is a 0–1 FRACTION (documented at the model) — the
    // human line is percent; metrics' gauges row is already percent.
    let cpu = overview.cpu_fraction * 100.0;
    let memory = match overview.memory.as_slice() {
        [used, max] => format!("{}/{}", human_bytes(*used), human_bytes(*max)),
        _ => "-".to_string(),
    };
    let disk = overview
        .disk
        .as_ref()
        .map(|disk| format!("{}/{}", human_bytes(disk.used), human_bytes(disk.total)));
    match disk {
        Some(disk) => println!("cpu {cpu:.1}%  memory {memory}  disk {disk}"),
        None => println!("cpu {cpu:.1}%  memory {memory}"),
    }

    // License banner incl. the trial countdown; falls back to the
    // gateway-info license mode when overview carries no block.
    match &overview.license {
        Some(license) => match license.trial_remaining_s {
            Some(remaining_s) => println!(
                "license: {}, {} remaining",
                license.state,
                humanize_duration_ms(remaining_s * 1000)
            ),
            None => println!("license: {}", license.state),
        },
        None => {
            if let Some(license) = &gateway.license {
                println!("license: {}", license.mode);
            }
        }
    }
}

/// `ign modules` human rows: `id  name  version  state  licenseState`.
fn render_modules_human(result: &ModulesResult) {
    for module in &result.items {
        let state = module.state.as_deref().unwrap_or("-");
        let license = module.license_state.as_deref().unwrap_or("-");
        println!(
            "{}  {}  {}  {}  {}",
            module.id, module.name, module.version, state, license
        );
    }
    if result.items.is_empty() {
        let kind = if result.quarantined {
            "quarantined"
        } else {
            "healthy"
        };
        println!("(no {kind} modules)");
    }
}

/// `ign metrics` human lines: gauges row, threads row; `--history` adds
/// a first/last summary line per non-empty series.
fn render_metrics_human(result: &MetricsResult) {
    let gauges = &result.current;
    println!(
        "cpu {:.1}%  heap {}/{}",
        gauges.cpu,
        // f64 gauges (8.3.3 exponent form); whole byte counts cast
        // exact (≤2^53) — the datapoint.value precedent below.
        human_bytes(gauges.heap_memory as i64),
        human_bytes(gauges.max_memory as i64)
    );
    let threads = &result.threads;
    println!(
        "threads: {} running, {} waiting, {} timed-waiting, {} blocked",
        threads.running, threads.waiting, threads.timed_waiting, threads.blocked
    );
    if let Some(charts) = &result.history {
        // cpu datapoints are PERCENT; memory series are bytes.
        for (label, series, is_percent) in [
            ("cpu", &charts.cpu_datapoints, true),
            ("heap", &charts.heap_memory_datapoints, false),
            ("non-heap", &charts.non_heap_memory_datapoints, false),
        ] {
            if let Some(first) = series.first()
                && let Some(last) = series.last()
            {
                let fmt = |datapoint: &ignition_core::client::metrics::Datapoint| {
                    if is_percent {
                        format!("{:.1}% @ {}", datapoint.value, datapoint.timestamp)
                    } else {
                        format!(
                            "{} @ {}",
                            human_bytes(datapoint.value as i64),
                            datapoint.timestamp
                        )
                    }
                };
                println!("history {label}: first {}, last {}", fmt(first), fmt(last));
            }
        }
    }
}

/// `ign sessions` human lines: one section per family
/// (`designers (1)` / `perspective (2)` / `vision (0)`), a row per item
/// (`id  user/username  project  address  lastcomm`) — the webpage's
/// Sessions pages as terminal sections.
fn render_sessions_human(result: &SessionsResult) {
    println!("designers ({})", result.designers.len());
    for designer in &result.designers {
        println!(
            "{}  {}  {}  {}  {}",
            designer.id, designer.user, designer.project, designer.address, designer.lastcomm
        );
    }
    println!("perspective ({})", result.perspective.len());
    for session in &result.perspective {
        println!(
            "{}  {}  {}  {}  {}",
            session.id,
            session.username,
            session.project,
            session.client_address,
            session.last_comm
        );
    }
    println!("vision ({})", result.vision.len());
    for client in &result.vision {
        println!(
            "{}  {}  {}  {}  {}",
            client.id, client.user, client.project, client.address, client.lastcomm
        );
    }
}

/// `ign sessions terminate` human line.
fn render_terminate_human(result: &TerminateResult) {
    println!("terminated {} session {}", result.kind, result.id);
}

/// `ign connections` human lines: `database (N)` / `opc (N)` sections
/// with `name  enabled  healthchecks-as-reported` rows — healthchecks
/// render as compact JSON, verbatim (the shape is passthrough by
/// design; LOW-confidence populated detail).
fn render_connections_human(result: &ConnectionsResult) {
    println!("database ({})", result.database.len());
    for connection in &result.database {
        println!(
            "{}  {}  {}",
            connection.name,
            connection.enabled,
            serde_json::to_string(&connection.healthchecks).unwrap_or_default()
        );
    }
    println!("opc ({})", result.opc.len());
    for connection in &result.opc {
        println!(
            "{}  {}  {}",
            connection.name,
            connection.enabled,
            serde_json::to_string(&connection.healthchecks).unwrap_or_default()
        );
    }
}

/// One log entry as a human line — the SAME format the list and the
/// live tail print: `ISO-UTC  LEVEL  logger  message`. Timestamps are
/// UTC (rendered from epoch ms; the raw epoch-ms value is always in
/// --json) — no timezone machinery, deterministic everywhere.
pub fn render_log_entry_line(entry: &LogEntry) -> String {
    format!(
        "{}  {:>5}  {}  {}",
        iso_utc(entry.timestamp),
        entry.level,
        entry.logger_name,
        entry.message
    )
}

/// `ign logs` human lines: one row per entry, newest first (the query
/// sorts desc); the total from metadata grounds the limit note.
fn render_logs_list_human(result: &LogPage) {
    for entry in &result.items {
        println!("{}", render_log_entry_line(entry));
    }
    if result.items.is_empty() {
        println!("(no matching log entries)");
    }
}

/// Unreachable-in-practice tail summary (render_ok intercepts the
/// streaming output; kept for match totality and future reuse).
fn render_tail_human(result: &TailResult) {
    println!("({} entries streamed)", result.streamed);
}

/// `ign logs download` human line.
fn render_download_human(result: &DownloadResult) {
    println!("wrote {} ({} bytes)", result.file, result.bytes);
}

/// `ign logs loggers` human rows: `name  level  context`.
fn render_loggers_human(result: &ListEnvelope<ignition_core::client::logs::LoggerInfo>) {
    for logger in &result.items {
        let level = logger.level.as_deref().unwrap_or("-");
        let context = if logger.context.is_null() {
            "-".to_string()
        } else {
            serde_json::to_string(&logger.context).unwrap_or_default()
        };
        println!("{}  {}  {}", logger.name, level, context);
    }
    if result.items.is_empty() {
        println!("(no matching loggers)");
    }
}

/// `ign logs loggers set` human line.
fn render_set_level_human(result: &SetLevelResult) {
    println!("set logger {} to {}", result.logger, result.level);
}

/// `ign logs loggers reset` human line.
fn render_reset_human(result: &ResetResult) {
    if result.reset {
        println!("reset all logger levels to defaults");
    }
}

/// `ign restart` human line (no --wait): the research-mandated
/// advisory — the gateway answers the POST immediately, then goes down
/// for ~1 min; steer toward `--wait`.
fn render_restart_human(_result: &ignition_core::actions::restart::RestartResult) {
    println!("restarting; gateway READY in ~1 min; consider `ign restart --wait`");
}

/// `ign restart --wait` human line: progress-free success (the wait
/// printed nothing while polling — StatusPing is polled, not
/// streamed).
fn render_restart_wait_human(result: &ignition_core::actions::restart::RestartWaitResult) {
    println!("gateway {} after {}s", result.state, result.elapsed_secs);
}

/// `ign wait <target>` human line: final state + elapsed.
fn render_wait_human(result: &ignition_core::actions::restart::WaitResult) {
    println!(
        "{} {} after {}s",
        result.target, result.state, result.elapsed_secs
    );
}

/// `ign doctor` human table: one row per check
/// (`name  STATUS  detail`, hint line under failures), then the count
/// summary. The doctor exits 0 whenever the table prints — failing
/// checks are the product (README-documented).
fn render_doctor_human(result: &ignition_core::actions::doctor::DoctorResult) {
    use ignition_core::actions::doctor::CheckStatus;
    let mut ok = 0;
    let mut warn = 0;
    let mut fail = 0;
    let mut skip = 0;
    for check in &result.checks {
        match check.status {
            CheckStatus::Ok => ok += 1,
            CheckStatus::Warn => warn += 1,
            CheckStatus::Fail => fail += 1,
            CheckStatus::Skip => skip += 1,
        }
        let status = match check.status {
            CheckStatus::Ok => "OK",
            CheckStatus::Warn => "WARN",
            CheckStatus::Fail => "FAIL",
            CheckStatus::Skip => "SKIP",
        };
        println!("{:<12}  {:<4}  {}", check.name, status, check.detail);
        if check.status == CheckStatus::Fail
            && let Some(hint) = &check.hint
        {
            println!("  hint: {hint}");
        }
    }
    let mut summary = format!(
        "{} checks: {ok} ok, {warn} warn, {fail} fail",
        result.checks.len()
    );
    if skip > 0 {
        summary.push_str(&format!(", {skip} skip"));
    }
    println!("{summary}");
}

/// `ign adopt` human table: the doctor's step-row format (name
/// STATUS detail, hints under), then the credential outcome — and,
/// ONLY on the env-var fallback (no keyring), the one-time
/// `name:key` print: the plaintext appears here and nowhere else,
/// ever (the deliberate exposure site; ADOPT-02).
fn render_adopt_human(result: &ignition_core::actions::adopt::AdoptResult) {
    use ignition_core::actions::doctor::CheckStatus;
    for step in &result.steps {
        let status = match step.status {
            CheckStatus::Ok => "OK",
            CheckStatus::Warn => "WARN",
            CheckStatus::Fail => "FAIL",
            CheckStatus::Skip => "SKIP",
        };
        println!("{:<12}  {:<4}  {}", step.name, status, step.detail);
        if let Some(hint) = &step.hint {
            println!("  hint: {hint}");
        }
    }
    match (&result.stored, &result.token) {
        (Some(how), _) => println!("credential: {how}"),
        (None, _) => println!("credential: unchanged (key pre-existed)"),
    }
    if let Some(token) = &result.token {
        // THE one-time exposure (env-fallback only): boxed loudly so
        // it is impossible to miss, and never repeated anywhere.
        println!();
        println!("API token (shown ONCE — store it now):");
        println!("  {token}");
    }
}

/// `ign project list` human rows: `name  title  enabled  parent
/// inheritable` (absent title/parent/inheritable render as `-`) — the
/// webpage's project list as terminal rows.
fn render_projects_list_human(result: &ProjectsResult) {
    for project in &result.projects {
        let title = project.title.as_deref().unwrap_or("-");
        let parent = project.parent.as_deref().unwrap_or("-");
        let inheritable = match project.inheritable {
            Some(value) => value.to_string(),
            None => "-".to_string(),
        };
        println!(
            "{}  {}  {}  {}  {}",
            project.name, title, project.enabled, parent, inheritable
        );
    }
    if result.projects.is_empty() {
        println!("(no projects)");
    }
}

/// `ign project new` human line: the confirmation + the parent when
/// one was set.
fn render_project_new_human(result: &ignition_core::actions::projects::ProjectSummary) {
    match &result.parent {
        Some(parent) => println!("created {} (parent {})", result.name, parent),
        None => println!("created {}", result.name),
    }
}

/// `ign project copy` human line.
fn render_project_copy_human(result: &ProjectCopyResult) {
    println!("copied {} \u{2192} {}", result.from, result.project.name);
}

/// `ign project rename` human line.
fn render_project_rename_human(result: &ProjectRenameResult) {
    println!(
        "renamed {} \u{2192} {}",
        result.previous_name, result.project.name
    );
}

/// `ign project set` human line: which fields changed on which
/// project (the fields-touched list rides the result display-only).
fn render_project_set_human(result: &ProjectSetResult) {
    println!(
        "set {} on {}",
        result.fields.join(", "),
        result.project.name
    );
}

/// `ign project delete` human line.
fn render_project_delete_human(result: &ProjectDeleteResult) {
    println!("deleted {}", result.deleted);
}

/// `ign project export` human lines: the artifact line + the scope
/// summary — what the ZIP does and does not contain (roadmap
/// criterion 4, in prose form for humans; agents read the arrays).
fn render_project_export_human(result: &ExportResult) {
    println!(
        "exported {} \u{2192} {} ({} bytes)",
        result.project, result.file, result.bytes
    );
    println!(
        "scope: includes {} \u{b7} excludes {}",
        result.scope.includes.join("/"),
        result.scope.excludes.join("/")
    );
}

/// `ign project export --decode-scripts` human lines: the plan-locked
/// artifact line (members + decoded scripts + the directory), then
/// the scope summary (the shared export contract) — plus the editing
/// loop pointer (sidecars + manifest, re-import via --encode-scripts).
fn render_project_export_decoded_human(result: &ExportDecodedResult) {
    println!(
        "Exported {} members, {} scripts decoded to {}",
        result.members, result.scripts_decoded, result.dir
    );
    println!(
        "scope: includes {} \u{b7} excludes {}",
        result.scope.includes.join("/"),
        result.scope.excludes.join("/")
    );
    println!(
        "edit the <member>.<n>.py sidecars, then re-import with \
         `--encode-scripts --file {}`",
        result.dir
    );
}

/// `ign project import` human line: the byte count + the policy that
/// ran (scope rides the JSON data; humans saw it at export time).
fn render_project_import_human(result: &ImportResult) {
    println!(
        "imported {} ({} bytes, policy {})",
        result.name, result.bytes, result.collision_policy
    );
}

/// `ign project diff` human lines: the direction header (B
/// relative to A — the LOCKED semantics, stated on every render),
/// the `project.json` semantic-field deltas, the grouped
/// ADDED/REMOVED/CHANGED sections (one path per line; `same` members
/// ride the summary only), and the four-count summary line.
fn render_project_diff_human(result: &ProjectDiffResult) {
    use ignition_core::client::resources::MemberStatus;
    println!(
        "project {} · {} → {} · statuses are B-relative-to-A (scope {})",
        result.project, result.profile_a, result.profile_b, result.scope
    );
    if result.project_meta.is_empty() {
        println!("project.json: no title/enabled/parent differences");
    } else {
        for delta in &result.project_meta {
            println!("project.json {}: {} → {}", delta.field, delta.a, delta.b);
        }
    }
    for (word, status) in [
        ("ADDED", MemberStatus::Added),
        ("REMOVED", MemberStatus::Removed),
        ("CHANGED", MemberStatus::Changed),
    ] {
        let matching: Vec<&str> = result
            .entries
            .iter()
            .filter(|entry| entry.status == status)
            .map(|entry| entry.path.as_str())
            .collect();
        println!("{word} ({})", matching.len());
        for path in matching {
            println!("  {path}");
        }
    }
    println!(
        "{} same, {} added, {} removed, {} changed",
        result.summary.same, result.summary.added, result.summary.removed, result.summary.changed
    );
}

/// `ign project sync` human lines: the direction header (always A→B),
/// the promoted paths, and — only when any — the removed ones.
fn render_project_sync_human(result: &ProjectSyncResult) {
    println!(
        "synced {} resource(s) {} → {} · project {} (scope {})",
        result.synced.len(),
        result.profile_a,
        result.profile_b,
        result.project,
        result.scope
    );
    for path in &result.synced {
        println!("  + {path}");
    }
    if !result.removed.is_empty() {
        println!(
            "removed {} resource(s) on {}:",
            result.removed.len(),
            result.profile_b
        );
        for path in &result.removed {
            println!("  - {path}");
        }
    }
}

/// `ign resource list` human rows: one resource path per line — the
/// surgical loop's inventory (pathless entries render as `-`).
fn render_resources_list_human(result: &ResourcesResult) {
    for entry in &result.resources {
        println!("{}", entry.path.as_deref().unwrap_or("-"));
    }
    if result.resources.is_empty() {
        println!("(no resources)");
    }
}

/// `ign resource get` human output: pretty JSON when the sniff said
/// json, the raw text otherwise — ready to redirect into a file and
/// put back (the surgical edit loop).
fn render_resource_get_human(result: &ResourceGetResult) {
    if result.content_kind == "json" {
        println!(
            "{}",
            serde_json::to_string_pretty(&result.content).unwrap_or_default()
        );
    } else {
        println!("{}", result.content.as_str().unwrap_or_default());
    }
}

/// `ign resource put` human line: the path + the sniffed kind that
/// rode the wire.
fn render_resource_put_human(result: &ResourcePutResult) {
    println!("put {} ({})", result.path, result.content_kind);
}

/// `ign resource delete` human line.
fn render_resource_delete_human(result: &ResourceDeleteResult) {
    println!("deleted {}", result.deleted);
}

/// `ign rig up` human line: the state-forward confirmation (RUNNING,
/// uncommissioned-with-wizard, or compose-wait-satisfied when no
/// gateway port was derivable); warnings follow as their own lines
/// (data-level, never stderr).
fn render_rig_up_human(result: &RigUpResult) {
    match result.state.as_str() {
        "uncommissioned" => {
            let url = result.gateway_url.as_deref().unwrap_or("<gateway>");
            println!(
                "rig {} up — uncommissioned (open {url}/welcome)",
                result.rig
            );
        }
        _ => match result.gateway_url.as_deref() {
            Some(url) => println!("rig {} up — gateway RUNNING ({url})", result.rig),
            None => println!("rig {} up — compose --wait satisfied", result.rig),
        },
    }
    for warning in &result.warnings {
        println!("warning: {warning}");
    }
}

/// `ign rig down` human line.
fn render_rig_down_human(result: &RigDownResult) {
    println!("rig {} down", result.rig);
}

/// `ign rig reset` human lines: what the teardown removed (the volume
/// preview, reported as it acted), then the state-forward confirmation
/// — the fresh volume usually boots into the wizard (warnings carry
/// the URL).
fn render_rig_reset_human(result: &RigResetResult) {
    if result.removed_volumes.is_empty() {
        println!(
            "rig {} reset — no named volumes found to remove",
            result.rig
        );
    } else {
        println!("rig {} reset — removed volumes:", result.rig);
        for volume in &result.removed_volumes {
            println!("  - {volume}");
        }
    }
    match result.state.as_str() {
        "uncommissioned" => println!("gateway up — uncommissioned (fresh volume)"),
        _ => println!("gateway RUNNING"),
    }
    for warning in &result.warnings {
        println!("warning: {warning}");
    }
}

/// `ign rig logs` human tail — unreachable (the lines already streamed
/// raw during execution; kept for match totality, the render_tail
/// precedent).
fn render_rig_logs_human(result: &RigLogsResult) {
    println!("({} lines streamed)", result.streamed);
}

/// `ign rig snapshot` human lines: the directory + gwbk size, the
/// exported projects, and the manifest — the composition at a glance.
fn render_rig_snapshot_human(result: &SnapshotResult) {
    println!(
        "snapshot {} — gwbk {} ({} bytes)",
        result.dir,
        human_bytes(result.gwbk_bytes as i64),
        result.gwbk_bytes
    );
    if result.projects.is_empty() {
        println!("projects: (none on the gateway)");
    } else {
        println!("projects:");
        for project in &result.projects {
            println!("  - {project}");
        }
    }
    println!("manifest: {}", result.manifest_path);
}

/// `ign rig restore` human lines: restored-from + the WITNESSED state,
/// then the warnings — the token-clobber warning (Pitfall 5) is
/// always first and must be VISIBLE to humans, not buried in data.
fn render_rig_restore_human(result: &RestoreResult) {
    println!(
        "restored from {} — gateway {}",
        result.restored_from, result.state
    );
    for warning in &result.warnings {
        println!("warning: {warning}");
    }
}

/// `ign backup download` human line — the file + the type that rode
/// the wire (07-02, BKUP-01).
fn render_backup_download_human(result: &BackupDownloadResult) {
    println!("Downloaded {} ({})", result.file, result.r#type);
}

/// `ign backup restore` human line — acceptance + the restart-block
/// honesty (the README owns the full window; humans get the one-liner
/// here, JSON stays the flat {restored: true}).
fn render_backup_restore_human(result: &BackupRestoreResult) {
    if result.restored {
        println!("Restored — the gateway restarts now (blocked for ~minutes)");
    }
}
/// `ign eam history` human table — the wire-faithful item rows:
/// taskName carries the forced marker, level/detail are DATA (a
/// Failed run is an exit-0 read — research Pitfall 3). Epoch-ms
/// times render ISO-UTC (the logs convention).
fn render_eam_history_human(result: &EamHistoryResult) {
    if result.items.is_empty() {
        println!("no EAM task history");
        return;
    }
    for item in &result.items {
        let start = iso_utc(item.task_start);
        let level = item.level.as_deref().unwrap_or("-");
        println!(
            "{}  {}  [{}]  target={}  {}",
            start,
            item.task_name,
            level,
            item.target.as_deref().unwrap_or("-"),
            item.detail.as_deref().unwrap_or("")
        );
    }
    println!("({} run(s))", result.count);
}

/// `ign eam tasks` human table — the agent-stable summary keys.
fn render_eam_tasks_human(result: &EamTasksResult) {
    if result.tasks.is_empty() {
        println!("no EAM task definitions");
        return;
    }
    for task in &result.tasks {
        println!(
            "{}  type={}  schedule={}  state={}",
            task.name,
            task.task_type.as_deref().unwrap_or("-"),
            task.schedule_mode.as_deref().unwrap_or("-"),
            task.current_state.as_deref().unwrap_or("-"),
        );
    }
}

/// `ign eam task new` human line — created + the composed
/// definition pretty-printed (the read-back of what rides the wire).
fn render_eam_task_create_human(result: &EamTaskCreateResult) {
    println!(
        "created {} ({} / {})",
        result.name, result.task_type, result.schedule_mode
    );
    println!(
        "{}",
        serde_json::to_string_pretty(&result.definition).unwrap_or_default()
    );
}

/// `ign eam task force` human shape — dispatch acceptance + the
/// honest history read-back (a Failed level with GNET detail is the
/// truth of an unconfigured agent, printed as data).
fn render_eam_task_force_human(result: &EamTaskForceResult) {
    println!(
        "dispatched {} (owner {}) — run outcomes:",
        result.task, result.owner
    );
    match &result.history {
        Some(item) => {
            println!(
                "  [{}] {}",
                item.level.as_deref().unwrap_or("-"),
                item.detail.as_deref().unwrap_or("(no detail)")
            );
        }
        None => println!("  (no history entry visible yet)"),
    }
}

/// `ign eam task suspend|resume|cancel` human shape (10-04) — the
/// action word + the read-back proofs: the previous runtime state,
/// the persisted `config.profile.isSuspended` flag (lifecycle
/// persistence, Decision 1), and the cancel no-op honesty
/// (`fired: false` + the reason — a write we declined is reported,
/// never disguised).
fn render_eam_task_lifecycle_human(result: &EamLifecycleResult) {
    println!(
        "{} {}  previous-state: {}",
        result.action,
        result.task,
        result.previous_state.as_deref().unwrap_or("-")
    );
    if let Some(suspended) = result.config_suspended {
        println!("config.profile.isSuspended: {suspended}");
    }
    if let Some(pending) = &result.pending {
        println!(
            "pending remains: {}  canCancel: {}",
            if pending.task_state.is_empty() {
                "-"
            } else {
                &pending.task_state
            },
            pending.can_cancel
        );
    }
    if !result.fired {
        println!(
            "not fired: {}",
            result.reason.as_deref().unwrap_or("(no reason given)")
        );
    }
}

/// `ign eam task modify` human shape (10-04) — the targeted keys that
/// changed + the authoritative post-PUT signature (the NEXT mutation
/// must quote it; capture §6a). The full PUT body + read-back stay
/// JSON-mode data.
fn render_eam_task_modify_human(result: &EamModifyResult) {
    let changed = if result.changed.is_empty() {
        "(none)".to_string()
    } else {
        result.changed.join(", ")
    };
    println!("modified {}  changed: {changed}", result.task);
    let signature = result
        .put_outcome
        .as_ref()
        .and_then(|outcome| outcome.changes.first())
        .map(|change| change.new_signature.as_deref().unwrap_or("-"));
    println!("new signature: {}", signature.unwrap_or("-"));
}

/// `ign eam task delete` human shape (10-04) — landed (or honestly
/// not) + the affected-resource names the gateway reported.
fn render_eam_task_delete_human(result: &EamDeleteResult) {
    if result.deleted {
        let affected = if result.affected.is_empty() {
            "(none reported)".to_string()
        } else {
            result.affected.join(", ")
        };
        println!("deleted {}  affected: {affected}", result.task);
    } else {
        println!("delete did NOT land for {}", result.task);
    }
}

/// `ign script run` human shape — the stdout block VERBATIM (the
/// route captured exactly what the script printed), then the value
/// and the route-measured wall time (the plan's three-part render:
/// `ign lint` human lines (07-04, INTR-02): the doctor-posture
/// summary — issue count + child exit, the parsed report's summary
/// object (compact), then the child's stderr diagnostics passthrough
/// (preview). JSON mode carries the full shape.
fn render_lint_human(result: &LintResult) {
    println!(
        "lint: {} issue(s), child exit {}",
        result.issues_found,
        result
            .child_exit_code
            .map_or("signal".to_string(), |code| code.to_string())
    );
    if let Some(report) = &result.report
        && let Some(summary) = report.get("summary")
    {
        let compact = serde_json::to_string(summary).unwrap_or_default();
        println!("summary: {compact}");
    } else {
        println!("(no JSON report parsed — stdout rides the JSON data)");
    }
    if !result.stderr_preview.is_empty() {
        for line in result.stderr_preview.lines() {
            println!("{line}");
        }
    }
}

/// stdout block, `result:` line, `elapsed:` line).
fn render_script_run_human(result: &ScriptRunResult) {
    println!("stdout:");
    print!("{}", result.stdout);
    if !result.stdout.is_empty() && !result.stdout.ends_with('\n') {
        println!();
    }
    println!("result: {}", result.result);
    println!("elapsed: {} ms", result.elapsed_ms);
}

/// `ign api call` human shape: one verdict line, then the body — the
/// body IS the answer (a table is meaningless for arbitrary gateway
/// shapes), so it prints pretty-printed. Display-only prettifying:
/// the JSON envelope's `data.result.data` stays gateway-verbatim
/// (RawValue passthrough — the README's documented contract
/// exception); a body that somehow fails to re-parse prints verbatim.
fn render_api_call_human(result: &ApiCallOutcome) {
    println!(
        "api call → {} {} (HTTP {})",
        result.method, result.path, result.result.status
    );
    let raw = result.result.data.get();
    match serde_json::from_str::<serde_json::Value>(raw) {
        Ok(value) => match serde_json::to_string_pretty(&value) {
            Ok(pretty) => println!("{pretty}"),
            Err(_) => println!("{raw}"),
        },
        // Unreachable by construction (RawValue::from_string already
        // validated the JSON at the client boundary) — degrade to the
        // raw text rather than hiding the answer.
        Err(_) => println!("{raw}"),
    }
}

/// `ign license status` human shape (09-04): the trial
/// mode/countdown line (the mode lives on the trial companion —
/// capture fact), then per-hardware-key item rows
/// (`name  title  version`).
fn render_license_status_human(result: &LicenseStatusResult) {
    let trial = &result.trial;
    let countdown = if trial.expired {
        "expired".to_string()
    } else {
        format!(
            "{} remaining",
            humanize_duration_ms(trial.trial_seconds_left * 1000)
        )
    };
    println!("license: {}, {}", trial.license_mode, countdown);

    let license = &result.license;
    if license.hardware.is_empty() {
        println!("hardware: (no entries)");
    }
    for entry in &license.hardware {
        let key = entry.key.as_deref().unwrap_or("-");
        println!("{key}: {} item(s)", entry.items.len());
        for item in &entry.items {
            println!(
                "  {}  {}  {}",
                item.name.as_deref().unwrap_or("-"),
                item.title.as_deref().unwrap_or("-"),
                item.version.as_deref().unwrap_or("-"),
            );
        }
    }
}

/// `ign redundancy status` human shape (09-04): role/peer/
/// project-state/sync rows, then uptime + last-sync with the units
/// AS CAPTURED (uptime = ms since gateway start, wall-clock-proven;
/// lastSyncTimestamp = the -1 never-synced sentinel on fresh rigs —
/// a non-negative value reads epoch-ms flagged as inference, never
/// presented as proven).
fn render_redundancy_status_human(result: &RedundancyStatusResult) {
    let status = &result.status;
    println!("role: {}", status.role);
    if let Some(state) = &status.project_state {
        println!("project state: {state}");
    }
    if let Some(level) = &status.activity_level {
        println!("activity: {level}");
    }
    match &status.peer_id {
        Some(peer) => println!(
            "peer: {} ({})",
            peer,
            if status.peer_connected {
                "connected"
            } else {
                "disconnected"
            }
        ),
        None => println!("peer: none"),
    }
    println!(
        "config access: {}  sync pending: {}  failover pending: {}",
        if status.has_config_access {
            "yes"
        } else {
            "no"
        },
        status.sync_pending,
        status.failover_pending
    );
    if let Some(uptime) = status.uptime {
        println!(
            "uptime: {} (ms since gateway start)",
            humanize_duration_ms(uptime)
        );
    }
    match status.last_sync_epoch_ms() {
        Some(ms) => println!("last sync: {ms} epoch-ms (unit inferred, not capture-proven)"),
        None => println!("last sync: never (-1 sentinel)"),
    }
}

/// `ign gan status` human shape (09-04): connections + remote
/// gateways, then the in/out byte rates (the fresh-rig capture is the
/// zero-connection canonical shape — zeros are healthy data).
fn render_gan_status_human(result: &GanStatusResult) {
    let gan = &result.status;
    println!(
        "connections: {}/{} running  remote gateways: {}",
        gan.running_connections, gan.total_connections, gan.remote_gateways
    );
    println!(
        "byte rate in {:.0} B/s  out {:.0} B/s",
        gan.incoming_byte_rate, gan.outgoing_byte_rate
    );
}

/// `ign diagnostics bundle generate|status|wait` human shape (09-05):
/// ONE status line carrying the CAPTURED vocabulary verbatim plus the
/// byte size when `Valid` (absent while generating — the key is
/// missing on the wire, not zero).
fn render_bundle_status_line(verb: &str, wire: &BundleStatusWire) {
    match wire.file_size {
        Some(bytes) => println!("bundle {verb}: {} ({bytes} bytes)", wire.state),
        None => println!("bundle {verb}: {}", wire.state),
    }
}

/// `ign diagnostics bundle download` human shape (09-05) — the
/// logs-download line: file + bytes.
fn render_bundle_download_human(result: &BundleDownloadResult) {
    println!("wrote {} ({} bytes)", result.file, result.bytes);
}

/// `ign eam tasks <NAME>` human shape — the definition pretty-printed
/// with the scheduled state beside it.
fn render_eam_task_detail_human(result: &EamTaskDetailResult) {
    println!(
        "{}  state={}",
        result.name,
        result
            .state
            .get("currentState")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("-")
    );
    println!(
        "{}",
        serde_json::to_string_pretty(&result.definition).unwrap_or_default()
    );
}

/// `ign rig trial status` human lines: the license banner first (the
/// `ign status` banner style — mode + countdown), then the cross-check
/// line, warnings last. An expired trial leads with EXPIRED.
fn render_trial_status_human(result: &TrialStatusResult) {
    let banner = if result.expired {
        "trial EXPIRED".to_string()
    } else {
        format!(
            "trial active, {} remaining",
            humanize_duration_ms(result.trial_remaining_s * 1000)
        )
    };
    println!(
        "license: {} ({}), {}",
        result.license_mode, result.trial_state, banner
    );
    let expire = match result.banners.expire_time_ms {
        Some(ms) => iso_utc(ms),
        None => "-".to_string(),
    };
    println!(
        "banners: severity {}, expires {}, cross-check {}",
        result.banners.severity.as_deref().unwrap_or("-"),
        expire,
        if result.banners.active {
            "active"
        } else {
            "inactive"
        }
    );
    for warning in &result.warnings {
        println!("warning: {warning}");
    }
}

/// `ign rig trial reset` human line: the mechanism that landed + the
/// before/after flip + the fresh countdown.
fn render_trial_reset_human(result: &TrialResetResult) {
    println!(
        "trial reset via {} — expired {} → {}, {} remaining ({})",
        result.mechanism,
        result.expired_before,
        result.expired_after,
        humanize_duration_ms(result.trial_remaining_s * 1000),
        result.rig_url
    );
}

/// `ign webdev deploy` human lines: the routes + the import outcome.
/// The scriptExec secret NEVER prints — only its lifecycle state
/// (generated/stored or reused).
fn render_webdev_deploy_human(result: &WebdevDeployResult) {
    println!(
        "deployed {} routes to project {} (overwrite import)",
        result.routes.len(),
        result.project
    );
    println!("routes: {}", result.routes.join(", "));
    if result.script_exec {
        if result.secret_rotated {
            println!(
                "scriptExec: deployed (secret generated — stored in the profile config at 0600)"
            );
        } else {
            println!("scriptExec: deployed (reusing the stored profile secret)");
        }
    }
    println!(
        "import: {}",
        serde_json::to_string(&result.import).unwrap_or_else(|_| "{}".to_string())
    );
}

/// `ign webdev status` human lines: one row per route plus the ok
/// summary — a READ (degradation is data, the doctor precedent; the
/// ok=false summary names the fix).
fn render_webdev_status_human(result: &WebdevStatusResult) {
    for row in &result.routes {
        println!(
            "{:<12} {:<16} {}",
            row.route,
            route_status_word(row.status),
            row.deployed_version.as_deref().unwrap_or("-")
        );
    }
    if result.ok {
        println!("ok: all always-on routes present with matching versions");
    } else {
        println!("degraded: run `ign webdev deploy` to install/refresh the routes");
    }
}

/// The status word — exactly the serialized snake_case value (agents
/// and humans read the same vocabulary).
fn route_status_word(status: ignition_core::actions::webdev::RouteStatus) -> &'static str {
    use ignition_core::actions::webdev::RouteStatus;
    match status {
        RouteStatus::Present => "present",
        RouteStatus::Absent => "absent",
        RouteStatus::Unlicensed => "unlicensed",
        RouteStatus::AuthGated => "auth_gated",
        RouteStatus::SecretMismatch => "secret_mismatch",
        RouteStatus::VersionMismatch => "version_mismatch",
    }
}

/// `ign tags provider list` human table: name / enabled / tags /
/// health, the managed marker trailing (the native seam's healthy
/// data — tag counts the route can't offer).
fn render_tag_providers_human(result: &TagProvidersResult) {
    println!("{:<20} {:<8} {:>5}  health", "name", "enabled", "tags");
    for provider in &result.providers {
        let tags = provider
            .tag_count
            .map(|count| count.to_string())
            .unwrap_or_else(|| "-".to_string());
        let health = provider.health.as_deref().unwrap_or("-");
        let managed = if provider.managed { "  (managed)" } else { "" };
        println!(
            "{:<20} {:<8} {:>5}  {}{}",
            provider.name, provider.enabled, tags, health, managed
        );
    }
}

/// Tree depth from a bracket-qualified fullPath: the leading
/// `[provider]` segment is depth 0; each following segment (split on
/// `/`, the first riding DIRECTLY after the bracket with no slash)
/// adds one.
fn browse_depth(path: &str) -> usize {
    match path.find(']') {
        Some(close) => {
            let rest = &path[close + 1..];
            if rest.is_empty() {
                0
            } else {
                1 + rest.matches('/').count()
            }
        }
        // Unbracketed paths (defensive): segments by slash.
        None => path.matches('/').count(),
    }
}

/// `ign tags browse` human mode: an INDENTED TREE derived from
/// fullPath nesting (providers at the root) with tagType badges (+
/// dataType where present). JSON mode keeps the stable flat list —
/// agents get the flat shape, humans get the hierarchy.
fn render_tags_browse_human(result: &TagsBrowseResult) {
    let root = if result.path.is_empty() {
        "root".to_string()
    } else {
        result.path.clone()
    };
    match &result.filter {
        Some(filter) => println!("browsing {root} (filter: {filter})"),
        None => println!("browsing {root}"),
    }
    print_browse_tree(&result.entries);
}

/// `ign tags browse --from-export` human mode: the SAME tree over
/// the offline rows, headed by the export's origin (07-04 — zero
/// new render surface: the tree loop is the shared helper).
fn render_tags_browse_from_export_human(result: &TagBrowseFromExportResult) {
    println!("browsing export {}", result.origin);
    print_browse_tree(&result.entries);
}

/// The shared indented-tree loop (browse_depth derives nesting from
/// the bracketed fullPath).
fn print_browse_tree(entries: &[BrowseRow]) {
    for entry in entries {
        let depth = browse_depth(&entry.path);
        let data_type = entry.data_type.as_deref().unwrap_or_default();
        let badge = if data_type.is_empty() {
            entry.tag_type.clone()
        } else {
            format!("{} {}", entry.tag_type, data_type)
        };
        println!("{}{}  {}", "  ".repeat(depth), entry.name, badge);
    }
}

/// `ign tags read` human rows: path / value / quality / timestamp,
/// aligned (the verbatim passthrough — quality strings carry their
/// own detail and are never re-parsed).
fn render_tags_read_human(result: &TagsReadResult) {
    for row in &result.results {
        let value = serde_json::to_string(&row.value).unwrap_or_default();
        println!(
            "{}  =  {}  [{}]  {}",
            row.path, value, row.quality, row.timestamp
        );
    }
}

/// `ign tags config get` human mode: the path + tagType header then
/// the config as PRETTY JSON (agents and humans both want the
/// object — the stringified re-parse already applied upstream).
/// TAGS-13: when the config carries history-binding keys, an
/// additive `history:` block follows (captured field names only —
/// the 13-01 field-set table); absence of history keys renders
/// BYTE-IDENTICAL to the pre-TAGS-13 shape (the pinned contract).
fn render_tags_config_get_human(result: &TagsConfigGetResult) {
    let tag_type = result.tag_type.as_deref().unwrap_or("-");
    println!("{}  {}", result.path, tag_type);
    let pretty = serde_json::to_string_pretty(&result.config).unwrap_or_default();
    println!("{pretty}");
    if let Some(summary) = history_summary(&result.config) {
        println!("history:");
        if let Some(enabled) = summary.enabled {
            println!("  enabled: {enabled}");
        }
        if let Some(provider) = &summary.provider {
            println!("  provider: {provider}");
        }
        if let Some(sample_mode) = &summary.sample_mode {
            println!("  sample mode: {sample_mode}");
        }
        if let Some(group) = &summary.historical_group {
            println!("  historical group: {group}");
        }
    }
}

/// `ign tags udt types` human mode: the provider header then one
/// name + tagType row per type.
fn render_tags_udt_types_human(result: &TagsUdtTypesResult) {
    println!("provider {}", result.provider);
    for row in &result.types {
        println!("{}  {}", row.name, row.tag_type);
    }
}

/// `ign tags udt def` human mode: the `_types_` path header then
/// the recursive definition as PRETTY JSON.
fn render_tags_udt_def_human(result: &TagsUdtDefResult) {
    println!("[{}]_types_/{}", result.provider, result.name);
    let pretty = serde_json::to_string_pretty(&result.definition).unwrap_or_default();
    println!("{pretty}");
}

/// `ign tags export` human mode: the artifact line (stdout-mode
/// exports are intercepted in render_ok — the payload already
/// printed). json keeps the pre-11-05 line byte-identical; xml/csv
/// name the format, and csv adds the lossy-generation warnings on
/// stderr (warn-and-continue — never gated).
fn render_tags_export_human(result: &TagsExportResult) {
    let file = result.file.as_deref().unwrap_or("stdout");
    if result.format == "json" {
        println!(
            "exported {} path(s) → {} ({} tag(s))",
            result.paths.len(),
            file,
            result.tag_count
        );
    } else {
        println!(
            "exported {} path(s) → {} ({}, {} tag(s))",
            result.paths.len(),
            file,
            result.format,
            result.tag_count
        );
    }
    if let Some(report) = &result.loss_report {
        render_csv_loss_warnings(report);
    }
}

/// The csv-generation warnings (11-05): the command prints exactly
/// what was dropped or coerced on STDERR — generation is
/// warn-and-continue (exit 0), the structured twin rides
/// `data.loss_report`.
fn render_csv_loss_warnings(report: &LossReport) {
    if !report.dropped_keys.is_empty() {
        eprintln!(
            "warning: csv export dropped field(s): {}",
            report.dropped_keys.join(", ")
        );
    }
    for line in &report.coerced {
        eprintln!("warning: {line}");
    }
}

/// One dataset cell → display text: strings unquoted, null as
/// `null`, structured values as compact JSON (the t_stamp/quality
/// strings carry their own meaning — never re-parsed).
fn cell_text(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(text) => text.clone(),
        serde_json::Value::Null => "null".to_string(),
        other => serde_json::to_string(other).unwrap_or_default(),
    }
}

/// The aligned columns/rows table shared by the history renderers
/// (alarms history + history query): header row, then rows padded to
/// the column widths (the LAST column rides unpadded — no trailing
/// whitespace).
fn render_aligned_columns(columns: &[String], rows: &[Vec<String>]) {
    let mut widths: Vec<usize> = columns.iter().map(String::len).collect();
    for row in rows {
        for (idx, cell) in row.iter().enumerate() {
            widths[idx] = widths[idx].max(cell.len());
        }
    }
    let header: Vec<String> = columns
        .iter()
        .enumerate()
        .map(|(idx, name)| {
            if idx + 1 == columns.len() {
                name.clone()
            } else {
                format!("{:<width$}", name, width = widths[idx])
            }
        })
        .collect();
    println!("{}", header.join("  "));
    for row in rows {
        let line: Vec<String> = row
            .iter()
            .enumerate()
            .map(|(idx, cell)| {
                if idx + 1 == row.len() {
                    cell.clone()
                } else {
                    format!("{:<width$}", cell, width = widths[idx])
                }
            })
            .collect();
        println!("{}", line.join("  "));
    }
}

/// `ign tags alarms active` human table: the FULL eventId (the
/// UUID VERBATIM — what `tags alarms ack` accepts as a copy-paste
/// input; short prefixes also ack via expansion, but the table
/// prints the canonical form), source, state, priority, name.
fn render_tags_alarms_active_human(result: &TagsAlarmsActiveResult) {
    println!(
        "{:<38} {:<44} {:<24} {:<8} name",
        "eventId", "source", "state", "priority"
    );
    for alarm in &result.alarms {
        let name = alarm.name.as_deref().unwrap_or("-");
        println!(
            "{:<38} {:<44} {:<24} {:<8} {}",
            alarm.event_id, alarm.source, alarm.state, alarm.priority, name
        );
    }
}

/// `ign tags alarms history` human mode: the journal dataset as an
/// aligned table (the wire shape is journal-dataset-dependent — the
/// header IS the column list) + the row count.
fn render_tags_alarms_history_human(result: &TagsAlarmsHistoryResult) {
    let rows: Vec<Vec<String>> = result
        .rows
        .iter()
        .map(|row| {
            result
                .columns
                .iter()
                .map(|column| cell_text(&row[column]))
                .collect()
        })
        .collect();
    render_aligned_columns(&result.columns, &rows);
    println!("{} row(s)", result.count);
}

/// `ign tags alarms ack` human mode: the honest count + the
/// unacknowledged remainder (the route's own return).
fn render_tags_alarms_ack_human(result: &TagsAlarmsAckResult) {
    if result.unacknowledged.is_empty() {
        println!("acknowledged {} alarm(s)", result.acknowledged);
    } else {
        println!(
            "acknowledged {} alarm(s); unacknowledged: {}",
            result.acknowledged,
            result.unacknowledged.join(", ")
        );
    }
}

/// `ign tags history query` human mode: the dataset as an aligned
/// table — `t_stamp` first (preserved EXACTLY), one column per tag
/// path — + the row count.
fn render_tags_history_query_human(result: &TagsHistoryQueryResult) {
    let rows: Vec<Vec<String>> = result
        .rows
        .iter()
        .map(|row| row.iter().map(cell_text).collect())
        .collect();
    render_aligned_columns(&result.columns, &rows);
    println!("{} row(s)", result.row_count);
}

/// `ign rig status` human table: identity header, one row per service
/// (`service  state  health  published->target/proto`), volumes, and
/// the ports occupancy line — a down rig prints its emptiness as data
/// (exit 0).
fn render_rig_status_human(result: &RigStatusResult) {
    println!("rig {} ({})", result.rig, result.compose_file);
    for service in &result.services {
        let health = service.health.as_deref().unwrap_or("-");
        let ports = if service.publishers.is_empty() {
            "-".to_string()
        } else {
            service
                .publishers
                .iter()
                .map(|publisher| {
                    let protocol = publisher.protocol.as_deref().unwrap_or("tcp");
                    match (publisher.published_port, publisher.target_port) {
                        (Some(published), Some(target)) => {
                            format!("{published}\u{2192}{target}/{protocol}")
                        }
                        (Some(published), None) => format!("{published}/{protocol}"),
                        _ => "-".to_string(),
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        };
        println!(
            "{:<16} {:<8} {:<9} {}",
            service.name, service.state, health, ports
        );
    }
    if result.services.is_empty() {
        println!("(no running services — rig is down)");
    }
    let volumes = if result.volumes.is_empty() {
        "-".to_string()
    } else {
        result.volumes.join(", ")
    };
    println!("volumes: {volumes}");
    println!(
        "ports {}",
        if result.ports_free { "free" } else { "in use" }
    );
}

/// Epoch milliseconds → an ISO-8601 UTC string
/// (`2026-08-22T03:07:40.123Z`), zero timezone machinery: the
/// civil-from-days algorithm (Howard Hinnant) over the well-known
/// shift; deterministic across machines.
fn iso_utc(ms: i64) -> String {
    let secs = ms.div_euclid(1000);
    let millis = ms.rem_euclid(1000);
    let days = secs.div_euclid(86_400);
    let time_of_day = secs.rem_euclid(86_400);
    let (year, month, day) = civil_from_days(days);
    let hour = time_of_day / 3600;
    let minute = (time_of_day % 3600) / 60;
    let second = time_of_day % 60;
    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
}

/// Days since 1970-01-01 → (year, month, day) — Howard Hinnant's
/// `civil_from_days`, the standard compact conversion.
fn civil_from_days(days: i64) -> (i64, u32, u32) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097); // day of era [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // year of era
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year [0, 365]
    let mp = (5 * doy + 2) / 153; // month index [0, 11] from March
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // day of month [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // month [1, 12]
    (if m <= 2 { y + 1 } else { y }, m, d)
}

/// Milliseconds → compact human duration with the two most significant
/// non-zero units ("3d 4h", "1h 56m", "5m 38s", "12s"); "0s" when empty.
fn humanize_duration_ms(ms: i64) -> String {
    let total_s = ms / 1000;
    let units = [
        (total_s / 86400, "d"),
        ((total_s % 86400) / 3600, "h"),
        ((total_s % 3600) / 60, "m"),
        (total_s % 60, "s"),
    ];
    let mut parts = units
        .iter()
        .filter(|(value, _)| *value > 0)
        .map(|(value, unit)| format!("{value}{unit}"));
    match (parts.next(), parts.next()) {
        (Some(first), Some(second)) => format!("{first} {second}"),
        (Some(first), None) => first,
        (None, _) => "0s".to_string(),
    }
}

/// Bytes → compact human size (binary units, at most one decimal, none
/// when whole: "338MB", "322.5MB", "1GB", "11.4GB").
fn human_bytes(bytes: i64) -> String {
    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if value.fract() == 0.0 {
        format!("{value:.0}{}", UNITS[unit])
    } else {
        format!("{value:.1}{}", UNITS[unit])
    }
}

#[cfg(test)]
mod tests {
    use super::{civil_from_days, iso_utc};

    /// Known instants: the epoch, a recent date, a pre-epoch value
    /// (negative ms must still render, via euclidean division), and
    /// leap-day handling.
    #[test]
    fn iso_utc_known_instants() {
        assert_eq!(iso_utc(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(iso_utc(1_787_346_747_022), "2026-08-21T21:12:27.022Z");
        assert_eq!(iso_utc(1_709_164_800_000), "2024-02-29T00:00:00.000Z");
        assert_eq!(iso_utc(-1), "1969-12-31T23:59:59.999Z");
        assert_eq!(iso_utc(951_782_400_000), "2000-02-29T00:00:00.000Z");
    }

    /// The epoch and a handful of dates round-trip through the civil
    /// conversion.
    #[test]
    fn civil_from_days_matches_known_dates() {
        assert_eq!(civil_from_days(0), (1970, 1, 1));
        assert_eq!(civil_from_days(19_723), (2024, 1, 1));
        assert_eq!(civil_from_days(19_782), (2024, 2, 29));
        assert_eq!(civil_from_days(-1), (1969, 12, 31));
    }
}