logbrew-cli 0.1.27

Public command-line interface for LogBrew.
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
//! Native `LogBrew` command-line interface library.
//!
//! The CLI is intentionally small and predictable so coding agents can learn it
//! quickly: `read`, `watch`, `explain`, and `set` cover data access and state
//! changes, while `login`, `setup`, and `status` cover local configuration.

#![forbid(unsafe_code)]

#[doc(hidden)]
pub mod auth;
#[doc(hidden)]
pub mod auth_namespace;
#[doc(hidden)]
pub mod doctor;
mod error;
#[doc(hidden)]
pub mod flags;
pub mod help;
#[doc(hidden)]
pub mod ids;
#[doc(hidden)]
pub mod investigate;
mod native_debug_artifacts;
mod parser;
mod project_create;
mod projects;
#[doc(hidden)]
pub mod render;
#[doc(hidden)]
pub mod setup;
#[doc(hidden)]
pub mod status;
mod support;
mod usage;
#[doc(hidden)]
pub mod version;

use auth::{
    AuthCredential, execute_login, execute_logout, execute_whoami, send_authenticated_with_refresh,
    token_is_project_ingest_key,
};
pub use error::{
    CliError, RuntimeError, write_cli_error, write_native_debug_runtime_error, write_runtime_error,
};
use futures_util::StreamExt as _;
pub use parser::parse_command;
use render::write_api_success;
use setup::write_setup_plan;
use status::execute_status;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::{Error as WebSocketError, Message};
use version::execute_version;

/// Initial delay before reconnecting a live watch stream.
const WATCH_RECONNECT_INITIAL_DELAY: std::time::Duration = std::time::Duration::from_secs(1);
/// Maximum delay before reconnecting a live watch stream.
const WATCH_RECONNECT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);
/// Maximum jitter added to reconnect delays.
const WATCH_RECONNECT_JITTER_MAX_MILLIS: u64 = 250;

/// Accepted issue status values for generic recovery text.
pub(crate) const ISSUE_STATUS_VALUES_NEXT_STEP: &str =
    "use one of unresolved/open, resolved/closed, ignored";
/// Accepted issue status values for read filter recovery text.
pub(crate) const ISSUE_STATUS_FILTER_NEXT_STEP: &str =
    "use --status unresolved/open, --status resolved/closed, or --status ignored";
/// Accepted issue status values for missing mutation arguments.
pub(crate) const ISSUE_STATUS_ARGUMENT_NEXT_STEP: &str =
    "provide one of unresolved/open, resolved/closed, ignored";

/// OAuth provider used for native CLI browser login.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum LoginProvider {
    /// GitHub OAuth.
    #[default]
    GitHub,
    /// GitLab OAuth.
    GitLab,
    /// Bitbucket OAuth.
    Bitbucket,
}

impl LoginProvider {
    /// Returns the canonical provider slug used by the public auth API.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::GitHub => "github",
            Self::GitLab => "gitlab",
            Self::Bitbucket => "bitbucket",
        }
    }
}

impl std::str::FromStr for LoginProvider {
    type Err = CliError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "github" => Ok(Self::GitHub),
            "gitlab" => Ok(Self::GitLab),
            "bitbucket" => Ok(Self::Bitbucket),
            _ => Err(CliError::InvalidLoginProvider),
        }
    }
}

/// Parsed `LogBrew` command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    /// Shows command usage.
    Help {
        /// Help topic to display.
        topic: HelpTopic,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Opens browser-based authentication.
    Login {
        /// OAuth provider to use for browser authentication.
        provider: LoginProvider,
        /// Try to open the login URL in the default browser.
        open_browser: bool,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Removes the local CLI token.
    Logout {
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Detects the current project and prints a non-mutating SDK setup plan.
    Setup {
        /// Let the CLI pick the framework or runtime automatically.
        auto: bool,
        /// Suppress confirmation prompts.
        yes: bool,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Checks local auth and server reachability.
    Status {
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Returns the authenticated account identity.
    WhoAmI {
        /// Emit the exact validated server identity object.
        json: bool,
    },
    /// Checks one project through a bounded read-only diagnostic sequence.
    Doctor {
        /// Account-owned project UUID.
        project_id: String,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Creates one project and securely persists its one-time ingest key.
    ProjectCreate {
        /// Normalized project creation fields and local persistence choice.
        options: ProjectCreateOptions,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Lists active account-owned projects.
    Projects {
        /// Emit the exact validated bare server array.
        json: bool,
    },
    /// Reads authenticated account usage and configured limits.
    Usage {
        /// Emit the exact validated server object.
        json: bool,
    },
    /// Prints the installed CLI version.
    Version {
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Reads historical observability data.
    Read {
        /// Resource to read.
        target: ReadTarget,
        /// Read filters.
        options: Box<ReadOptions>,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Watches live observability data.
    Watch {
        /// Resource to watch.
        target: WatchTarget,
        /// Live watch filters applied client-side.
        options: WatchOptions,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Fetches context for an issue or trace so an agent can explain it.
    Explain {
        /// Resource to explain.
        target: ExplainTarget,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Follows the backend-directed, read-only investigation for one issue.
    InvestigateIssue {
        /// Grouped issue identifier.
        issue_id: String,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Uploads or verifies Apple native debug artifacts.
    NativeDebugArtifacts {
        /// Native debug-artifact operation.
        target: NativeDebugArtifactsTarget,
        /// Emit bounded machine-readable JSON.
        json: bool,
    },
    /// Mutates server-side state.
    Set {
        /// Target state mutation.
        target: SetTarget,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Marks backend-owned project setup as seen.
    ProjectSetupSeen {
        /// Project identifier.
        project_id: String,
        /// Optional setup metadata sent to the backend.
        options: ProjectSetupSeenOptions,
        /// Emit machine-readable JSON.
        json: bool,
    },
    /// Creates or reads account support tickets.
    Support {
        /// Support-ticket operation.
        target: SupportTarget,
        /// Emit machine-readable JSON.
        json: bool,
    },
}

/// Help topic for CLI usage output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HelpTopic {
    /// Root command overview.
    Root,
    /// Browser login command.
    Login,
    /// Local logout command.
    Logout,
    /// SDK setup command.
    Setup,
    /// Status check command.
    Status,
    /// Installed CLI version command.
    Version,
    /// Authentication workflow overview.
    Auth,
    /// Machine-readable output overview.
    Json,
    /// First-run examples and common workflows.
    Examples,
    /// Backend-owned project setup and ingest key workflow overview.
    Projects,
    /// Backend-owned account usage and quota workflow overview.
    Usage,
    /// Read command overview.
    Read,
    /// Log reading command.
    ReadLogs,
    /// Issue reading command.
    ReadIssues,
    /// Action reading command.
    ReadActions,
    /// Release reading command.
    ReadReleases,
    /// Recent trace discovery command.
    ReadTraces,
    /// Trace reading command.
    ReadTrace,
    /// Single issue reading command.
    ReadIssue,
    /// Live watch command.
    Watch,
    /// Explain command.
    Explain,
    /// Server-directed issue investigation command.
    Investigate,
    /// Apple native debug-artifact upload and lookup commands.
    NativeDebugArtifacts,
    /// State mutation command.
    Set,
    /// Support-ticket workflow.
    Support,
}

impl HelpTopic {
    /// Returns a stable machine-readable topic name.
    #[must_use]
    pub const fn key(self) -> &'static str {
        match self {
            Self::Root => "root",
            Self::Login => "login",
            Self::Logout => "logout",
            Self::Setup => "setup",
            Self::Status => "status",
            Self::Version => "version",
            Self::Auth => "auth",
            Self::Json => "json",
            Self::Examples => "examples",
            Self::Projects => "projects",
            Self::Usage => "usage",
            Self::Read => "read",
            Self::ReadLogs => "read_logs",
            Self::ReadIssues => "read_issues",
            Self::ReadActions => "read_actions",
            Self::ReadReleases => "read_releases",
            Self::ReadTraces => "read_traces",
            Self::ReadTrace => "read_trace",
            Self::ReadIssue => "read_issue",
            Self::Watch => "watch",
            Self::Explain => "explain",
            Self::Investigate => "investigate",
            Self::NativeDebugArtifacts => "debug_artifacts",
            Self::Set => "set",
            Self::Support => "support",
        }
    }
}

/// Historical data target for `read`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadTarget {
    /// Structured logs.
    Logs,
    /// Grouped issues.
    Issues,
    /// Product actions.
    Actions,
    /// Release summaries.
    Releases,
    /// Recent trace summaries.
    Traces,
    /// One trace by ID.
    Trace(String),
    /// One issue by ID.
    Issue(String),
}

/// Filters for historical read commands.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReadOptions {
    /// Optional action name filter.
    pub name: Option<String>,
    /// Optional service name filter.
    pub service: Option<String>,
    /// Optional relative or absolute lower time bound.
    pub since: Option<String>,
    /// Optional user or actor filter.
    pub user: Option<String>,
    /// Optional trace ID filter.
    pub trace: Option<String>,
    /// Optional log severity filter.
    pub level: Option<String>,
    /// Optional log message substring search.
    pub search: Option<String>,
    /// Optional project filter.
    pub project: Option<String>,
    /// Optional release filter.
    pub release: Option<String>,
    /// Optional environment filter.
    pub environment: Option<String>,
    /// Optional issue status filter.
    pub status: Option<String>,
    /// Optional row limit.
    pub limit: Option<String>,
    /// Optional minimum end-to-end trace duration in milliseconds.
    pub min_duration_ms: Option<String>,
    /// Optional pagination mode for endpoints with explicit page envelopes.
    pub pagination: Option<String>,
    /// Optional continuation timestamp.
    pub cursor_time: Option<String>,
    /// Optional continuation identifier.
    pub cursor_id: Option<String>,
}

impl ReadOptions {
    /// Returns the first filter that trace-detail reads cannot apply.
    #[must_use]
    pub(crate) fn first_trace_detail_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.service.is_some(), "--service"),
            (self.since.is_some(), "--since"),
            (self.user.is_some(), "--user"),
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.status.is_some(), "--status"),
            (self.limit.is_some(), "--limit"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
            (self.pagination.is_some(), "--pagination"),
            (self.cursor_time.is_some(), "--cursor-time"),
            (self.cursor_id.is_some(), "--cursor-id"),
        ])
    }

    /// Returns the first filter that issue-detail reads cannot apply.
    #[must_use]
    pub(crate) fn first_issue_detail_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.service.is_some(), "--service"),
            (self.since.is_some(), "--since"),
            (self.user.is_some(), "--user"),
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.project.is_some(), "--project"),
            (self.release.is_some(), "--release"),
            (self.environment.is_some(), "--environment"),
            (self.status.is_some(), "--status"),
            (self.limit.is_some(), "--limit"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
            (self.pagination.is_some(), "--pagination"),
            (self.cursor_time.is_some(), "--cursor-time"),
            (self.cursor_id.is_some(), "--cursor-id"),
        ])
    }

    /// Returns the first filter that log reads cannot apply.
    #[must_use]
    pub(crate) fn first_log_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.user.is_some(), "--user"),
            (self.status.is_some(), "--status"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
        ])
    }

    /// Returns the first filter that issue list reads cannot apply.
    #[must_use]
    pub(crate) fn first_issue_list_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.user.is_some(), "--user"),
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
        ])
    }

    /// Returns the first filter that action reads cannot apply.
    #[must_use]
    pub(crate) fn first_action_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.status.is_some(), "--status"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
        ])
    }

    /// Returns the first filter that release reads cannot apply.
    #[must_use]
    pub(crate) fn first_release_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.user.is_some(), "--user"),
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.status.is_some(), "--status"),
            (self.min_duration_ms.is_some(), "--min-duration-ms"),
            (self.pagination.is_some(), "--pagination"),
            (self.cursor_time.is_some(), "--cursor-time"),
            (self.cursor_id.is_some(), "--cursor-id"),
        ])
    }

    /// Returns the first filter that recent trace discovery cannot apply.
    #[must_use]
    pub(crate) fn first_trace_list_unsupported_flag(&self) -> Option<&'static str> {
        first_present_flag([
            (self.name.is_some(), "--name"),
            (self.user.is_some(), "--user"),
            (self.trace.is_some(), "--trace"),
            (self.level.is_some(), "--severity"),
            (self.search.is_some(), "--search"),
            (self.pagination.is_some(), "--pagination"),
            (self.cursor_time.is_some(), "--cursor-time"),
            (self.cursor_id.is_some(), "--cursor-id"),
        ])
    }
}

/// Returns the first present flag in declaration order.
fn first_present_flag<const N: usize>(flags: [(bool, &'static str); N]) -> Option<&'static str> {
    flags
        .iter()
        .find_map(|(present, flag)| present.then_some(*flag))
}

/// Live stream target for `watch`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatchTarget {
    /// All supported live event types.
    All,
    /// Structured logs.
    Logs,
    /// Grouped issues.
    Issues,
    /// Product actions.
    Actions,
}

/// Client-side filters for live watch commands.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WatchOptions {
    /// Canonical severity filters for logs and issues.
    pub severity: Vec<String>,
}

/// Optional metadata for backend-owned project setup tracking.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProjectSetupSeenOptions {
    /// Runtime or framework observed by setup.
    pub runtime: Option<String>,
    /// Setup source for account-token calls.
    pub source: Option<String>,
    /// Release environment observed by setup.
    pub environment: Option<String>,
}

/// Fields accepted by secure project creation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectCreateOptions {
    /// Trimmed project name.
    pub name: String,
    /// Optional trimmed runtime.
    pub runtime: Option<String>,
    /// Optional trimmed environment.
    pub environment: Option<String>,
    /// Owner-selected destination for the one-time ingest key.
    pub ingest_key_file: String,
    /// Explicitly discard a mismatched pending retry before creating.
    pub abandon_retry: bool,
}

/// Apple native debug-artifact operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeDebugArtifactsTarget {
    /// Validate, upload, and verify every supported object identity.
    Upload(NativeDebugUploadOptions),
    /// Verify one exact uploaded object identity.
    Lookup(NativeDebugLookupOptions),
}

/// Shared exact native debug-artifact lookup scope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeDebugLookupOptions {
    /// Account-owned project UUID.
    pub project_id: String,
    /// Exact release identifier.
    pub release: String,
    /// Exact environment identifier.
    pub environment: String,
    /// Exact service identifier.
    pub service: String,
    /// Canonical lowercase Mach-O image UUID.
    pub image_uuid: String,
    /// Supported canonical architecture.
    pub architecture: String,
}

/// Apple native debug-artifact upload options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeDebugUploadOptions {
    /// User-selected dSYM bundle, ZIP archive, or Mach-O debug object.
    pub path: String,
    /// Account-owned project UUID.
    pub project_id: String,
    /// Exact release identifier.
    pub release: String,
    /// Exact environment identifier.
    pub environment: String,
    /// Exact service identifier.
    pub service: String,
    /// Optional exact canonical image UUID gate for release automation.
    pub expected_image_uuids: Vec<String>,
    /// Validate locally without authentication or network mutation.
    pub dry_run: bool,
}

/// Support-ticket operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SupportTarget {
    /// Create one support ticket.
    Create(Box<SupportTicketCreateOptions>),
    /// List support-ticket history.
    List(Box<SupportTicketListOptions>),
    /// Read one support ticket by public identifier.
    Detail(String),
    /// Read public context history for one support ticket.
    ContextHistory {
        /// Public ticket identifier.
        ticket_id: String,
    },
    /// Add requested context to one support ticket.
    ReplyContext(Box<SupportContextReplyOptions>),
    /// Update one support ticket's public lifecycle status.
    UpdateStatus {
        /// Public ticket identifier.
        ticket_id: String,
        /// User-owned lifecycle status.
        status: SupportTicketLifecycleStatus,
    },
}

/// Fields accepted when replying with requested support context.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SupportContextReplyOptions {
    /// Public ticket identifier.
    pub ticket_id: String,
    /// User-provided support context.
    pub context: String,
    /// Required idempotency key used for exact retries.
    pub retry_key: String,
    /// Include bounded locally generated diagnostics.
    pub diagnostics: bool,
}

/// User-owned support-ticket lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SupportTicketLifecycleStatus {
    /// Reopen a ticket.
    Open,
    /// Close a ticket.
    Closed,
}

impl SupportTicketLifecycleStatus {
    /// Returns the canonical API status value.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::Closed => "closed",
        }
    }
}

/// Fields accepted when creating a support ticket.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SupportTicketCreateOptions {
    /// Public support category.
    pub category: String,
    /// Concise ticket title.
    pub title: String,
    /// Reproducible description supplied by the user.
    pub description: String,
    /// Optional project identifier.
    pub project_id: Option<String>,
    /// Optional deployment environment.
    pub environment: Option<String>,
    /// Optional runtime.
    pub runtime: Option<String>,
    /// Optional framework.
    pub framework: Option<String>,
    /// Optional SDK package.
    pub sdk_package: Option<String>,
    /// Optional SDK version.
    pub sdk_version: Option<String>,
    /// Optional release.
    pub release: Option<String>,
    /// Optional trace identifier.
    pub trace_id: Option<String>,
    /// Optional event identifier.
    pub event_id: Option<String>,
    /// Include bounded locally generated diagnostics.
    pub diagnostics: bool,
}

/// Filters for support-ticket history.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SupportTicketListOptions {
    /// Optional project identifier.
    pub project_id: Option<String>,
    /// Optional ticket status.
    pub status: Option<String>,
    /// Optional ticket source.
    pub source: Option<String>,
    /// Optional support category.
    pub category: Option<String>,
    /// Optional release.
    pub release: Option<String>,
    /// Optional result limit.
    pub limit: Option<String>,
    /// Optional explicit pagination mode.
    pub pagination: Option<String>,
    /// Optional continuation timestamp.
    pub cursor_time: Option<String>,
    /// Optional continuation identifier.
    pub cursor_id: Option<String>,
}

/// Context target for `explain`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExplainTarget {
    /// One issue by ID.
    Issue(String),
    /// One trace by ID.
    Trace(String),
}

/// Mutation target for `set`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SetTarget {
    /// Update one issue status.
    IssueStatus {
        /// Issue identifier.
        id: String,
        /// New issue status.
        status: String,
    },
}

/// Process environment needed by the CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliEnvironment {
    /// Base API URL.
    pub base_url: String,
    /// Optional bearer token.
    pub token: Option<String>,
    /// Optional home directory.
    pub home: Option<std::path::PathBuf>,
    /// Optional current working directory.
    pub cwd: Option<std::path::PathBuf>,
}

impl CliEnvironment {
    /// Loads CLI environment from process variables.
    #[must_use]
    pub fn from_process() -> Self {
        Self {
            base_url: std::env::var("LOGBREW_API_URL")
                .unwrap_or_else(|_| String::from("https://api.logbrew.co")),
            token: std::env::var("LOGBREW_TOKEN").ok(),
            home: std::env::var_os("HOME").map(std::path::PathBuf::from),
            cwd: std::env::current_dir().ok(),
        }
    }
}

impl Command {
    /// Returns the HTTP API path for commands backed by a single REST request.
    #[must_use]
    pub fn http_path(&self) -> Option<String> {
        match self {
            Self::Read {
                target, options, ..
            } => Some(read_path(
                target,
                &ReadPathFilters {
                    name: options.name.as_deref(),
                    service: options.service.as_deref(),
                    since: options.since.as_deref(),
                    user: options.user.as_deref(),
                    trace: options.trace.as_deref(),
                    level: options.level.as_deref(),
                    search: options.search.as_deref(),
                    project: options.project.as_deref(),
                    release: options.release.as_deref(),
                    environment: options.environment.as_deref(),
                    status: options.status.as_deref(),
                    limit: options.limit.as_deref(),
                    min_duration_ms: options.min_duration_ms.as_deref(),
                    pagination: options.pagination.as_deref(),
                    cursor_time: options.cursor_time.as_deref(),
                    cursor_id: options.cursor_id.as_deref(),
                },
            )),
            Self::Explain { target, .. } => Some(explain_path(target)),
            Self::Set { target, .. } => Some(set_path(target)),
            Self::ProjectSetupSeen { project_id, .. } => {
                Some(format!("/api/projects/{project_id}/setup/seen"))
            }
            Self::ProjectCreate { .. } | Self::Projects { .. } => {
                Some(String::from("/api/projects"))
            }
            Self::Support { target, .. } => Some(support::path(target)),
            Self::Help { .. }
            | Self::Login { .. }
            | Self::Logout { .. }
            | Self::Setup { .. }
            | Self::Status { .. }
            | Self::WhoAmI { .. }
            | Self::Doctor { .. }
            | Self::Usage { .. }
            | Self::Version { .. }
            | Self::InvestigateIssue { .. }
            | Self::NativeDebugArtifacts { .. }
            | Self::Watch { .. } => None,
        }
    }

    /// Returns whether command output should be JSON.
    #[must_use]
    pub const fn wants_json(&self) -> bool {
        match self {
            Self::Help { json, .. }
            | Self::Login { json, .. }
            | Self::Logout { json }
            | Self::Status { json }
            | Self::WhoAmI { json }
            | Self::Doctor { json, .. }
            | Self::ProjectCreate { json, .. }
            | Self::Projects { json }
            | Self::Usage { json }
            | Self::Version { json }
            | Self::Read { json, .. }
            | Self::Watch { json, .. }
            | Self::Explain { json, .. }
            | Self::InvestigateIssue { json, .. }
            | Self::NativeDebugArtifacts { json, .. }
            | Self::Set { json, .. }
            | Self::ProjectSetupSeen { json, .. }
            | Self::Support { json, .. }
            | Self::Setup { json, .. } => *json,
        }
    }

    /// Returns the HTTP method for commands backed by a REST request.
    #[must_use]
    pub const fn http_method(&self) -> Option<HttpMethod> {
        match self {
            Self::ProjectCreate { .. }
            | Self::ProjectSetupSeen { .. }
            | Self::Support {
                target: SupportTarget::Create(_),
                ..
            }
            | Self::Support {
                target: SupportTarget::ReplyContext(_),
                ..
            } => Some(HttpMethod::Post),
            Self::Support {
                target: SupportTarget::UpdateStatus { .. },
                ..
            }
            | Self::Set { .. } => Some(HttpMethod::Patch),
            Self::Projects { .. }
            | Self::Read { .. }
            | Self::Explain { .. }
            | Self::Support { .. } => Some(HttpMethod::Get),
            Self::Help { .. }
            | Self::Login { .. }
            | Self::Logout { .. }
            | Self::Setup { .. }
            | Self::Status { .. }
            | Self::WhoAmI { .. }
            | Self::Doctor { .. }
            | Self::Usage { .. }
            | Self::Version { .. }
            | Self::InvestigateIssue { .. }
            | Self::NativeDebugArtifacts { .. }
            | Self::Watch { .. } => None,
        }
    }

    /// Returns JSON request body for mutation commands.
    #[must_use]
    pub fn request_body(&self) -> Option<serde_json::Value> {
        self.request_body_for_token(None)
    }

    /// Returns JSON request body for mutation commands with auth-aware defaults.
    #[must_use]
    fn request_body_for_token(&self, token: Option<&str>) -> Option<serde_json::Value> {
        match self {
            Self::Set {
                target: SetTarget::IssueStatus { status, .. },
                ..
            } => Some(serde_json::json!({ "status": status })),
            Self::ProjectSetupSeen { options, .. } => Some(project_setup_seen_body(options, token)),
            Self::ProjectCreate { options, .. } => Some(project_create_body(options)),
            Self::Support {
                target: SupportTarget::Create(options),
                ..
            } => Some(support::create_body(options)),
            Self::Support {
                target: SupportTarget::ReplyContext(options),
                ..
            } => Some(support::context_body(options)),
            Self::Support {
                target: SupportTarget::UpdateStatus { status, .. },
                ..
            } => Some(serde_json::json!({"status": status.as_str()})),
            Self::Help { .. }
            | Self::Login { .. }
            | Self::Logout { .. }
            | Self::Setup { .. }
            | Self::Status { .. }
            | Self::WhoAmI { .. }
            | Self::Doctor { .. }
            | Self::Projects { .. }
            | Self::Usage { .. }
            | Self::Version { .. }
            | Self::Read { .. }
            | Self::Watch { .. }
            | Self::Explain { .. }
            | Self::InvestigateIssue { .. }
            | Self::NativeDebugArtifacts { .. }
            | Self::Support { .. } => None,
        }
    }

    /// Returns an idempotency key for support context replies.
    fn idempotency_key(&self) -> Option<&str> {
        match self {
            Self::Support {
                target: SupportTarget::ReplyContext(options),
                ..
            } => Some(options.retry_key.as_str()),
            Self::Help { .. }
            | Self::Login { .. }
            | Self::Logout { .. }
            | Self::Setup { .. }
            | Self::Status { .. }
            | Self::WhoAmI { .. }
            | Self::Doctor { .. }
            | Self::Usage { .. }
            | Self::Version { .. }
            | Self::Read { .. }
            | Self::Watch { .. }
            | Self::Explain { .. }
            | Self::InvestigateIssue { .. }
            | Self::NativeDebugArtifacts { .. }
            | Self::Set { .. }
            | Self::ProjectSetupSeen { .. }
            | Self::ProjectCreate { .. }
            | Self::Projects { .. }
            | Self::Support { .. } => None,
        }
    }
}

/// HTTP method used by a CLI command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    /// GET request.
    Get,
    /// POST request.
    Post,
    /// PATCH request.
    Patch,
}

/// Builds the `setup/seen` request body without local setup state.
fn project_setup_seen_body(
    options: &ProjectSetupSeenOptions,
    token: Option<&str>,
) -> serde_json::Value {
    let mut body = serde_json::Map::new();
    if let Some(runtime) = options.runtime.as_ref() {
        drop(body.insert(
            "runtime".to_owned(),
            serde_json::Value::String(runtime.clone()),
        ));
    }
    if let Some(source) = setup_seen_source(options, token) {
        drop(body.insert("source".to_owned(), serde_json::Value::String(source)));
    }
    if let Some(environment) = options.environment.as_ref() {
        drop(body.insert(
            "environment".to_owned(),
            serde_json::Value::String(environment.clone()),
        ));
    }
    serde_json::Value::Object(body)
}

/// Builds the byte-stable project creation request surface.
fn project_create_body(options: &ProjectCreateOptions) -> serde_json::Value {
    let mut body = serde_json::Map::new();
    drop(body.insert(
        "name".to_owned(),
        serde_json::Value::String(options.name.clone()),
    ));
    if let Some(runtime) = options.runtime.as_ref() {
        drop(body.insert(
            "runtime".to_owned(),
            serde_json::Value::String(runtime.clone()),
        ));
    }
    if let Some(environment) = options.environment.as_ref() {
        drop(body.insert(
            "environment".to_owned(),
            serde_json::Value::String(environment.clone()),
        ));
    }
    drop(body.insert(
        "source".to_owned(),
        serde_json::Value::String(String::from("cli")),
    ));
    serde_json::Value::Object(body)
}

/// Resolves setup source while preserving ingest-key identity derivation.
fn setup_seen_source(options: &ProjectSetupSeenOptions, token: Option<&str>) -> Option<String> {
    if token_is_project_ingest_key(token) {
        return None;
    }
    Some(options.source.as_deref().unwrap_or("cli").to_owned())
}

/// Executes a parsed command.
///
/// # Errors
///
/// Returns [`RuntimeError`] if output, browser launch, auth, or HTTP fails.
pub async fn execute_command<W: std::io::Write>(
    command: &Command,
    env: &CliEnvironment,
    output: &mut W,
) -> Result<(), RuntimeError> {
    match command {
        Command::Help { topic, json } => execute_help(*topic, *json, output),
        Command::Login {
            provider,
            open_browser,
            json,
        } => execute_login(env, *provider, *open_browser, *json, output).await,
        Command::Logout { json } => execute_logout(env, *json, output).await,
        Command::Setup { auto, yes, json } => execute_setup(env, *auto, *yes, *json, output),
        Command::Status { json } => execute_status(env, *json, output).await,
        Command::WhoAmI { json } => execute_whoami(env, *json, output).await,
        Command::Doctor { project_id, json } => {
            doctor::execute(env, project_id.as_str(), *json, output).await
        }
        Command::ProjectCreate { options, json } => {
            project_create::execute(env, options, *json, output).await
        }
        Command::Projects { json } => projects::execute(env, *json, output).await,
        Command::Usage { json } => usage::execute(env, *json, output).await,
        Command::Version { json } => execute_version(*json, output),
        Command::InvestigateIssue { issue_id, json } => {
            investigate::execute(env, issue_id.as_str(), *json, output).await
        }
        Command::NativeDebugArtifacts { target, json } => {
            native_debug_artifacts::execute(env, target, *json, output).await
        }
        Command::Read { .. }
        | Command::Explain { .. }
        | Command::Set { .. }
        | Command::ProjectSetupSeen { .. }
        | Command::Support { .. } => execute_http(command, env, output).await,
        Command::Watch {
            target,
            options,
            json,
        } => execute_watch(env, *target, options, *json, output).await,
    }
}

/// Emits CLI help.
fn execute_help<W: std::io::Write>(
    topic: HelpTopic,
    json: bool,
    output: &mut W,
) -> Result<(), RuntimeError> {
    let help = help::help_text(topic);
    if json {
        let body = serde_json::json!({
            "ok": true,
            "topic": topic.key(),
            "help": help,
        });
        writeln!(output, "{body}")?;
    } else {
        writeln!(output, "{help}")?;
    }
    Ok(())
}

/// Executes setup planning.
fn execute_setup<W: std::io::Write>(
    env: &CliEnvironment,
    auto: bool,
    yes: bool,
    json: bool,
    output: &mut W,
) -> Result<(), RuntimeError> {
    write_setup_plan(env.cwd.as_deref(), auto, yes, json, output)?;
    Ok(())
}

/// Executes commands backed by one HTTP request.
async fn execute_http<W: std::io::Write>(
    command: &Command,
    env: &CliEnvironment,
    output: &mut W,
) -> Result<(), RuntimeError> {
    let path = command.http_path().ok_or(CliError::UnknownCommand)?;
    let url = format!("{}{}", env.base_url.trim_end_matches('/'), path);
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .connect_timeout(std::time::Duration::from_secs(10))
        .build()?;

    let support_command = matches!(command, Command::Support { .. });
    let response_result = send_authenticated_with_refresh(&client, env, |client, credential| {
        build_command_request(client, command, url.as_str(), credential)
    })
    .await;
    let (response, credential) = match response_result {
        Ok(response) => response,
        Err(RuntimeError::Http(_)) if support_command => return Err(support_transport_error()),
        Err(error) => return Err(error),
    };
    let status = response.status();
    let body = match response.text().await {
        Ok(body) => body,
        Err(_) if support_command => return Err(support_transport_error()),
        Err(error) => return Err(RuntimeError::Http(error)),
    };

    if !status.is_success() {
        let body = if let Command::Support { target, .. } = command {
            support::safe_error_body(target, status.as_u16())
        } else {
            credential.redact_response_body(body.as_str())
        };
        return Err(RuntimeError::Api {
            status: status.as_u16(),
            body,
            auth_source: credential.source(),
            auth_label: credential.label(),
        });
    }

    write_api_success(command, body.as_str(), output)?;
    Ok(())
}

/// Returns a fixed, path-free support transport failure.
const fn support_transport_error() -> RuntimeError {
    RuntimeError::Unavailable {
        message: "support request could not be completed",
        next: "check network connectivity and retry the support command",
    }
}

/// Builds one command request with the supplied credential.
fn build_command_request(
    client: &reqwest::Client,
    command: &Command,
    url: &str,
    credential: &AuthCredential,
) -> reqwest::RequestBuilder {
    let mut request = match command.http_method().unwrap_or(HttpMethod::Get) {
        HttpMethod::Get => client.get(url),
        HttpMethod::Post => client.post(url),
        HttpMethod::Patch => client.patch(url),
    }
    .bearer_auth(credential.token());
    if let Some(body) = command.request_body_for_token(Some(credential.token())) {
        request = request.json(&body);
    }
    if let Some(key) = command.idempotency_key() {
        request = request.header("Idempotency-Key", key);
    }
    request
}

/// Executes the public live WebSocket watch flow.
async fn execute_watch<W: std::io::Write>(
    env: &CliEnvironment,
    target: WatchTarget,
    options: &WatchOptions,
    json: bool,
    output: &mut W,
) -> Result<(), RuntimeError> {
    if !json {
        return Err(RuntimeError::Unavailable {
            message: "watch streams JSON for agents",
            next: "run logbrew watch --json",
        });
    }

    let mut reconnect_backoff = WatchReconnectBackoff::default();
    loop {
        let ticket = match request_feed_ticket(env).await {
            Ok(ticket) => ticket,
            Err(error) if reconnect_backoff.connected_once() && !runtime_error_is_auth(&error) => {
                tokio::time::sleep(reconnect_backoff.next_delay()).await;
                continue;
            }
            Err(error) => return Err(error),
        };
        let live_url = feed_live_url(env.base_url.as_str(), ticket.as_str())?;
        let (mut websocket, _) = match connect_async(live_url.as_str()).await {
            Ok(connection) => connection,
            Err(error)
                if reconnect_backoff.connected_once() && !websocket_error_is_auth(&error) =>
            {
                tokio::time::sleep(reconnect_backoff.next_delay()).await;
                continue;
            }
            Err(error) => return Err(map_websocket_connect_error(error)),
        };
        reconnect_backoff.mark_connected();

        let mut emitted_before_disconnect = false;
        loop {
            let Some(message) = websocket.next().await else {
                break;
            };
            let message = match message {
                Ok(message) => message,
                Err(error) if websocket_error_is_auth(&error) => {
                    return Err(map_websocket_stream_error(error));
                }
                Err(_) => break,
            };
            match message {
                Message::Text(text) => {
                    let event = parse_live_event(text.as_str())?;
                    if watch_event_matches(target, options, &event) {
                        writeln!(output, "{event}")?;
                    }
                    emitted_before_disconnect = true;
                }
                Message::Binary(_) | Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => {}
                Message::Close(_) => return Ok(()),
            }
        }
        if emitted_before_disconnect {
            reconnect_backoff.reset();
        }
        tokio::time::sleep(reconnect_backoff.next_delay()).await;
    }
}

/// Reconnect state for long-running live watch streams.
#[derive(Debug, Default)]
struct WatchReconnectBackoff {
    /// Whether a live WebSocket connection has ever been established.
    connected_once: bool,
    /// Consecutive reconnect attempts since the last stable event.
    attempts: u32,
}

impl WatchReconnectBackoff {
    /// Returns whether the stream has connected at least once.
    const fn connected_once(&self) -> bool {
        self.connected_once
    }

    /// Records a successful WebSocket connection.
    const fn mark_connected(&mut self) {
        self.connected_once = true;
    }

    /// Resets retry delay after a stream successfully emits data.
    const fn reset(&mut self) {
        self.attempts = 0;
    }

    /// Returns the next capped exponential reconnect delay.
    fn next_delay(&mut self) -> std::time::Duration {
        let exponent = self.attempts.min(5);
        let multiplier = 1_u64 << exponent;
        self.attempts = self.attempts.saturating_add(1);
        let base = WATCH_RECONNECT_INITIAL_DELAY
            .as_secs()
            .saturating_mul(multiplier)
            .min(WATCH_RECONNECT_MAX_DELAY.as_secs());
        let delay = std::time::Duration::from_secs(base) + watch_reconnect_jitter();
        if delay > WATCH_RECONNECT_MAX_DELAY {
            WATCH_RECONNECT_MAX_DELAY
        } else {
            delay
        }
    }
}

/// Returns small jitter for reconnect delays without adding a random dependency.
fn watch_reconnect_jitter() -> std::time::Duration {
    let Ok(elapsed) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) else {
        return std::time::Duration::ZERO;
    };
    std::time::Duration::from_millis(
        u64::from(elapsed.subsec_millis()) % WATCH_RECONNECT_JITTER_MAX_MILLIS,
    )
}

/// Returns whether a runtime error should stop watch reconnect attempts.
const fn runtime_error_is_auth(error: &RuntimeError) -> bool {
    matches!(
        error,
        RuntimeError::MissingToken | RuntimeError::Api { status: 401, .. }
    )
}

/// Returns whether a WebSocket error is an auth failure.
fn websocket_error_is_auth(error: &WebSocketError) -> bool {
    matches!(error, WebSocketError::Http(response) if response.status().as_u16() == 401)
}

/// Requests a short-lived WebSocket feed ticket from the public API.
async fn request_feed_ticket(env: &CliEnvironment) -> Result<String, RuntimeError> {
    let url = format!("{}/api/feed/ticket", env.base_url.trim_end_matches('/'));
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30))
        .connect_timeout(std::time::Duration::from_secs(10))
        .build()?;
    let (response, credential) =
        send_authenticated_with_refresh(&client, env, |client, credential| {
            client.post(url.as_str()).bearer_auth(credential.token())
        })
        .await?;
    let status = response.status();
    let body = response.text().await?;
    if !status.is_success() {
        return Err(RuntimeError::Api {
            status: status.as_u16(),
            body: credential.redact_response_body(body.as_str()),
            auth_source: credential.source(),
            auth_label: credential.label(),
        });
    }

    let value = serde_json::from_str::<serde_json::Value>(body.as_str()).map_err(|_| {
        RuntimeError::Unavailable {
            message: "feed ticket response was not valid JSON",
            next: "retry logbrew watch or run logbrew status",
        }
    })?;
    value
        .get("ticket")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|ticket| !ticket.is_empty())
        .map(ToOwned::to_owned)
        .ok_or(RuntimeError::Unavailable {
            message: "feed ticket response did not include a ticket",
            next: "retry logbrew watch or run logbrew status",
        })
}

/// Builds the WebSocket live feed URL without exposing the opaque ticket elsewhere.
fn feed_live_url(base_url: &str, ticket: &str) -> Result<String, RuntimeError> {
    let trimmed = base_url.trim_end_matches('/');
    let (scheme, rest) = websocket_base_parts(trimmed).ok_or(RuntimeError::Unavailable {
        message: "LOGBREW_API_URL must start with http:// or https://",
        next: "check LOGBREW_API_URL or run logbrew status",
    })?;
    Ok(format!(
        "{scheme}://{rest}/api/feed/live?ticket={}",
        encode_component(ticket)
    ))
}

/// Converts an HTTP API base URL into WebSocket scheme and authority/path base parts.
fn websocket_base_parts(base_url: &str) -> Option<(&'static str, &str)> {
    base_url
        .strip_prefix("https://")
        .map(|rest| ("wss", rest))
        .or_else(|| base_url.strip_prefix("http://").map(|rest| ("ws", rest)))
}

/// Parses one backend live event object.
fn parse_live_event(text: &str) -> Result<serde_json::Value, RuntimeError> {
    serde_json::from_str::<serde_json::Value>(text).map_err(|_| RuntimeError::Unavailable {
        message: "live watch event was not valid JSON",
        next: "retry logbrew watch or check LOGBREW_API_URL",
    })
}

/// Returns whether an event should be emitted for the requested watch target and filters.
fn watch_event_matches(
    target: WatchTarget,
    options: &WatchOptions,
    event: &serde_json::Value,
) -> bool {
    target_matches_event(target, event) && severity_matches(options, event)
}

/// Returns whether the event type belongs to the selected target.
fn target_matches_event(target: WatchTarget, event: &serde_json::Value) -> bool {
    let event_type = event
        .get("type")
        .and_then(serde_json::Value::as_str)
        .unwrap_or_default();
    match target {
        WatchTarget::All => true,
        WatchTarget::Logs => event_type == "native_log",
        WatchTarget::Issues => event_type == "native_issue",
        WatchTarget::Actions => event_type == "native_action",
    }
}

/// Applies client-side severity filters to log and issue events.
fn severity_matches(options: &WatchOptions, event: &serde_json::Value) -> bool {
    if options.severity.is_empty() {
        return true;
    }
    let Some(severity) = event
        .get("data")
        .and_then(|data| data.get("severity").or_else(|| data.get("level")))
        .and_then(serde_json::Value::as_str)
    else {
        return false;
    };
    options
        .severity
        .iter()
        .any(|allowed| allowed.as_str() == severity)
}

/// Maps a WebSocket connection failure to a token-safe runtime error.
fn map_websocket_connect_error(error: WebSocketError) -> RuntimeError {
    match error {
        WebSocketError::Http(response) if response.status().as_u16() == 401 => {
            RuntimeError::Unavailable {
                message: "live watch ticket was rejected",
                next: "run logbrew login",
            }
        }
        WebSocketError::Http(_) => RuntimeError::Unavailable {
            message: "live watch websocket upgrade failed",
            next: "retry logbrew watch or check LOGBREW_API_URL",
        },
        WebSocketError::ConnectionClosed
        | WebSocketError::AlreadyClosed
        | WebSocketError::Io(_)
        | WebSocketError::Tls(_)
        | WebSocketError::Capacity(_)
        | WebSocketError::Protocol(_)
        | WebSocketError::WriteBufferFull(_)
        | WebSocketError::Utf8(_)
        | WebSocketError::AttackAttempt
        | WebSocketError::Url(_)
        | WebSocketError::HttpFormat(_) => RuntimeError::Unavailable {
            message: "live watch websocket failed",
            next: "retry logbrew watch or check LOGBREW_API_URL",
        },
    }
}

/// Maps an established WebSocket stream failure to a token-safe runtime error.
fn map_websocket_stream_error(error: WebSocketError) -> RuntimeError {
    match error {
        WebSocketError::ConnectionClosed | WebSocketError::AlreadyClosed => {
            RuntimeError::Unavailable {
                message: "live watch websocket closed",
                next: "retry logbrew watch",
            }
        }
        WebSocketError::Http(response) if response.status().as_u16() == 401 => {
            RuntimeError::Unavailable {
                message: "live watch ticket was rejected",
                next: "run logbrew login",
            }
        }
        WebSocketError::Http(_)
        | WebSocketError::Io(_)
        | WebSocketError::Tls(_)
        | WebSocketError::Capacity(_)
        | WebSocketError::Protocol(_)
        | WebSocketError::WriteBufferFull(_)
        | WebSocketError::Utf8(_)
        | WebSocketError::AttackAttempt
        | WebSocketError::Url(_)
        | WebSocketError::HttpFormat(_) => RuntimeError::Unavailable {
            message: "live watch websocket failed",
            next: "retry logbrew watch or check LOGBREW_API_URL",
        },
    }
}

/// Read endpoint filter values.
struct ReadPathFilters<'a> {
    /// Optional action name filter.
    name: Option<&'a str>,
    /// Optional service name filter.
    service: Option<&'a str>,
    /// Optional lower time bound.
    since: Option<&'a str>,
    /// Optional user or actor filter.
    user: Option<&'a str>,
    /// Optional trace ID filter.
    trace: Option<&'a str>,
    /// Optional log severity filter.
    level: Option<&'a str>,
    /// Optional log message substring search.
    search: Option<&'a str>,
    /// Optional project filter.
    project: Option<&'a str>,
    /// Optional release filter.
    release: Option<&'a str>,
    /// Optional environment filter.
    environment: Option<&'a str>,
    /// Optional issue status filter.
    status: Option<&'a str>,
    /// Optional row limit.
    limit: Option<&'a str>,
    /// Optional minimum end-to-end trace duration in milliseconds.
    min_duration_ms: Option<&'a str>,
    /// Optional pagination mode.
    pagination: Option<&'a str>,
    /// Optional continuation timestamp.
    cursor_time: Option<&'a str>,
    /// Optional continuation identifier.
    cursor_id: Option<&'a str>,
}

/// Builds a read endpoint path.
fn read_path(target: &ReadTarget, filters: &ReadPathFilters<'_>) -> String {
    match target {
        ReadTarget::Logs => path_with_query(
            "/api/logs",
            &[
                ("service_name", filters.service),
                ("severity", filters.level),
                ("search", filters.search),
                ("since", filters.since),
                ("trace_id", filters.trace),
                ("project_id", filters.project),
                ("release", filters.release),
                ("environment", filters.environment),
                ("pagination", filters.pagination),
                ("cursor_time", filters.cursor_time),
                ("cursor_id", filters.cursor_id),
                ("limit", filters.limit),
            ],
        ),
        ReadTarget::Issues => path_with_query(
            "/api/telemetry/issues",
            &[
                ("service_name", filters.service),
                ("since", filters.since),
                ("status", filters.status),
                ("project_id", filters.project),
                ("release", filters.release),
                ("environment", filters.environment),
                ("pagination", filters.pagination),
                ("cursor_time", filters.cursor_time),
                ("cursor_id", filters.cursor_id),
                ("limit", filters.limit),
            ],
        ),
        ReadTarget::Actions => path_with_query(
            "/api/telemetry/actions",
            &[
                ("service_name", filters.service),
                ("name", filters.name),
                ("since", filters.since),
                ("distinct_id", filters.user),
                ("project_id", filters.project),
                ("release", filters.release),
                ("environment", filters.environment),
                ("pagination", filters.pagination),
                ("cursor_time", filters.cursor_time),
                ("cursor_id", filters.cursor_id),
                ("limit", filters.limit),
            ],
        ),
        ReadTarget::Releases => path_with_query(
            "/api/telemetry/releases",
            &[
                ("service_name", filters.service),
                ("since", filters.since),
                ("project_id", filters.project),
                ("release", filters.release),
                ("environment", filters.environment),
                ("limit", filters.limit),
            ],
        ),
        ReadTarget::Traces => path_with_query(
            "/api/telemetry/traces",
            &[
                ("project_id", filters.project),
                ("service_name", filters.service),
                ("release", filters.release),
                ("environment", filters.environment),
                ("status", filters.status),
                ("since", filters.since),
                ("min_duration_ms", filters.min_duration_ms),
                ("limit", filters.limit),
            ],
        ),
        ReadTarget::Trace(id) => path_with_query(
            &format!("/api/telemetry/traces/{}", encode_component(id)),
            &[
                ("project_id", filters.project),
                ("release", filters.release),
                ("environment", filters.environment),
            ],
        ),
        ReadTarget::Issue(id) => format!("/api/telemetry/issues/{}", encode_component(id)),
    }
}

/// Builds an explain endpoint path.
fn explain_path(target: &ExplainTarget) -> String {
    match target {
        ExplainTarget::Issue(id) => format!("/api/telemetry/issues/{}", encode_component(id)),
        ExplainTarget::Trace(id) => format!("/api/telemetry/traces/{}", encode_component(id)),
    }
}

/// Builds a mutation endpoint path.
fn set_path(target: &SetTarget) -> String {
    match target {
        SetTarget::IssueStatus { id, .. } => {
            format!("/api/telemetry/issues/{}", encode_component(id))
        }
    }
}

/// Builds a path with query parameters.
fn path_with_query(path: &str, params: &[(&str, Option<&str>)]) -> String {
    let query = params
        .iter()
        .filter_map(|(name, value)| value.map(|v| format!("{name}={}", encode_component(v))))
        .collect::<Vec<_>>();

    if query.is_empty() {
        path.to_owned()
    } else {
        format!("{path}?{}", query.join("&"))
    }
}

/// Percent-encodes a path or query component without adding a dependency.
fn encode_component(value: &str) -> String {
    let mut encoded = String::new();
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
            encoded.push(char::from(byte));
        } else {
            encoded.push('%');
            encoded.push(hex_digit(byte >> 4));
            encoded.push(hex_digit(byte & 0x0f));
        }
    }
    encoded
}

/// Converts a nibble to an uppercase hexadecimal digit.
fn hex_digit(nibble: u8) -> char {
    match nibble {
        0..=9 => char::from(b'0' + nibble),
        10..=15 => char::from(b'A' + (nibble - 10)),
        _ => '?',
    }
}