yandex-tracker-cli 2.0.0

Token-efficient Yandex Tracker CLI for humans and AI agents
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
//! Account and profile commands.
//!
//! `login` is the only command that touches a secret, and it reads it from a
//! prompt or stdin — never from an argument, because arguments are visible in
//! `ps` and in shell history. There is deliberately no command that prints a
//! stored token.

use std::fmt::Write as _;
use std::io::Write as _;

use clap::{Args, Subcommand};

use crate::api::{Client, ClientConfig};
use crate::cli::{Session, emit, guidance, report, wizard};
use crate::config::{OrgKind, Profile, store};
use crate::exit::ExitCode;
use crate::oauth;
use crate::render::style::{Painter, Palette};
use crate::secrets;

#[derive(Debug, Subcommand)]
pub enum AuthCommand {
    /// Store a token for an account, and set up a profile to use it with.
    #[command(long_about = crate::cli::guidance::login_help())]
    Login(LoginArgs),
    /// Renew a token that `auth login` got by signing in through the browser.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_REFRESH))]
    Refresh {
        /// Account whose token to renew; the active profile's when omitted.
        #[arg(long, short = 'a')]
        account: Option<String>,
    },
    /// Remove a stored token.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_LOGOUT))]
    Logout {
        #[arg(long, short = 'a')]
        account: String,
    },
    /// List configured accounts and profiles.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_LIST))]
    List,
    /// Make a profile the default one.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_USE))]
    Use {
        /// Profile name, as `auth list` prints it.
        profile: String,
    },
    /// Change an existing profile: its name, its note, the organisation it points at.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_EDIT))]
    Edit(EditArgs),
    /// Delete a profile from the config file. The account and its token stay.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_REMOVE))]
    Remove {
        /// Profile name, as `auth list` prints it.
        profile: String,
    },
    /// Check every profile: who the token belongs to, and what it can see.
    #[command(long_about = crate::cli::help::md(crate::cli::help::AUTH_STATUS))]
    Status {
        /// Identity only — skip the counts, and the requests behind them.
        #[arg(long)]
        brief: bool,
        /// Check only the active profile instead of all of them.
        #[arg(long)]
        active_only: bool,
    },
}

/// Arguments for `auth login`.
///
/// The token is deliberately absent: it is read from a prompt or from stdin,
/// never from an argument, because arguments are visible in `ps` and land in
/// shell history.
// Each bool is an independent command-line switch; folding them into an enum
// would only make clap's flags harder to read.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Args)]
pub struct LoginArgs {
    /// Account name to store the token under. Asked for when omitted.
    #[arg(long, short = 'a')]
    pub account: Option<String>,

    /// Organisation id. Given this, login also writes a profile.
    #[arg(long)]
    pub org_id: Option<String>,

    /// Which header carries the organisation id. Detected when omitted.
    #[arg(long, value_enum)]
    pub org_kind: Option<OrgKind>,

    /// Profile name to create; defaults to the account name.
    #[arg(long, short = 'p')]
    pub profile: Option<String>,

    /// Queue this profile assumes when a command needs one.
    #[arg(long, short = 'q')]
    pub queue: Option<String>,

    /// Note saying which organisation this profile is; shown wherever the
    /// profile is named. Asked for in a terminal, and left as it was when a
    /// re-login omits it.
    #[arg(long)]
    pub description: Option<String>,

    /// Make this the default profile even if another one already is.
    #[arg(long)]
    pub default: bool,

    /// Skip the check that the token and organisation actually work.
    #[arg(long)]
    pub no_verify: bool,

    /// Sign in through the browser even without a terminal: print a code and
    /// wait until it is confirmed. What an agent runs on someone's behalf.
    #[arg(long)]
    pub device: bool,

    /// Ask for read access only (`tracker:read wiki:read`) when signing in
    /// through the browser.
    #[arg(long)]
    pub read_only: bool,
}

/// Arguments for `auth edit`.
///
/// Everything is optional except the profile, and anything not passed is left
/// exactly as it was: this command exists to change one thing without having to
/// restate the rest of a profile that already works.
#[derive(Debug, Args)]
pub struct EditArgs {
    /// Profile to change, as `auth list` prints it.
    pub profile: String,

    /// Rename it. `default_profile` follows; a committed `.tracker.toml` does not.
    #[arg(long)]
    pub name: Option<String>,

    /// Note saying which organisation this is.
    #[arg(long)]
    pub description: Option<String>,

    /// Remove the note.
    #[arg(long, conflicts_with = "description")]
    pub clear_description: bool,

    /// Account whose credential this profile uses.
    #[arg(long, short = 'a')]
    pub account: Option<String>,

    /// Organisation id.
    #[arg(long)]
    pub org_id: Option<String>,

    /// Which header carries the organisation id.
    #[arg(long, value_enum)]
    pub org_kind: Option<OrgKind>,

    /// Queue assumed when a command needs one and none was given.
    #[arg(long, short = 'q')]
    pub queue: Option<String>,

    /// Stop assuming a queue.
    #[arg(long, conflicts_with = "queue")]
    pub clear_queue: bool,
}

/// Run an auth subcommand.
pub async fn run(command: &AuthCommand, session: &Session) -> ExitCode {
    match command {
        AuthCommand::Status { brief, active_only } => status(session, *brief, *active_only).await,
        AuthCommand::Login(args) => login(args, session).await,
        AuthCommand::Refresh { account } => refresh(session, account.as_deref()).await,
        AuthCommand::Logout { account } => logout(account),
        AuthCommand::List => list(session),
        AuthCommand::Use { profile } => use_profile(session, profile),
        AuthCommand::Edit(args) => edit(args, session),
        AuthCommand::Remove { profile } => remove(session, profile),
    }
}

/// Report on the configured profiles.
///
/// This is the command someone runs when something is wrong, so it answers the
/// questions that actually get asked: which profile is in play and where that
/// choice came from, whether the token works, who it belongs to, and what it can
/// reach. Checking every profile rather than only the active one is deliberate —
/// "it works with my other login" is the usual next question.
///
/// The counts cost a handful of requests per profile. That is fine for a
/// diagnostic and wrong for a hot path, which is what `--brief` is for.
async fn status(session: &Session, brief: bool, active_only: bool) -> ExitCode {
    let mut out = anstream::stdout();
    let mut err = anstream::stderr();
    let paint = session.render.painter();

    if session.config.profiles.is_empty() {
        let _ = writeln!(err, "no profiles configured yet.\n");
        let _ = writeln!(err, "{}", guidance::full());
        let _ = writeln!(
            err,
            "Then: ytcli auth login --account <name> --org-id <id> [--queue <QUEUE>]"
        );
        return ExitCode::Auth;
    }

    report_sources(session, paint, &mut out);

    let active = session
        .resolved
        .as_ref()
        .map(|resolved| resolved.name.clone());
    let mut active_failure = None;
    let mut any_success = false;
    let mut last_failure = None;
    // Which profiles can see each queue key, so the ambiguity can be reported.
    let mut queues_seen: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();

    for (name, profile) in &session.config.profiles {
        let is_active = active.as_deref() == Some(name.as_str());
        if active_only && !is_active {
            continue;
        }

        let source = if is_active {
            session
                .resolved
                .as_ref()
                .map_or_else(String::new, |resolved| {
                    format!(" (from {})", resolved.source)
                })
        } else {
            String::new()
        };
        let marks = if is_active { "  [active]" } else { "" };

        let _ = writeln!(
            out,
            "{} {}{}{}",
            paint.paint("profile", Palette::label()),
            paint.paint(name, Palette::key()),
            paint.paint(&source, Palette::label()),
            paint.paint(marks, Palette::ok()),
        );
        describe_profile(profile, paint, &mut out);

        let code = report_profile(
            profile,
            brief,
            paint,
            name,
            &mut queues_seen,
            &mut out,
            &mut err,
        )
        .await;
        if code == ExitCode::Success {
            any_success = true;
        } else {
            last_failure = Some(code);
            if is_active {
                active_failure = Some(code);
            }
        }
    }

    remember_queues(session, brief, active_only, active.as_deref(), &queues_seen);
    warn_about_collisions(session, paint, &queues_seen);

    // A shell that exports YTCLI_TOKEN on entering a directory — the oh-my-zsh
    // `dotenv` plugin does exactly this — makes every profile authenticate as
    // one person, and the rows then agree with each other for a reason that has
    // nothing to do with the configuration being read.
    if secrets::overridden() && session.config.profiles.len() > 1 {
        let _ = writeln!(
            err,
            "{} YTCLI_TOKEN is set, so every profile above was read through that one token, whatever account it names",
            paint.paint("warning:", Palette::warn()),
        );
    }

    // The command someone runs to find out which profile is in play is the
    // command that should say how to change it.
    if session.config.profiles.len() > 1 {
        let _ = writeln!(
            err,
            "{}",
            paint.paint(
                "change the default with: ytcli auth use <profile>",
                Palette::label()
            )
        );
    }

    // The active profile decides the outcome — a broken profile nobody is using
    // should not make a script think the tool is unusable. But if *nothing*
    // worked, saying so beats reporting success for a run that found none.
    active_failure
        .or_else(|| (!any_success).then_some(last_failure).flatten())
        .unwrap_or(ExitCode::Success)
}

/// The two lines under a profile heading: its note, then what it points at.
fn describe_profile(
    profile: &crate::config::Profile,
    paint: Painter,
    out: &mut impl std::io::Write,
) {
    if let Some(description) = profile.description.as_deref() {
        let _ = writeln!(
            out,
            "  {} {description}",
            paint.paint("note:", Palette::label()),
        );
    }

    let _ = writeln!(
        out,
        "  {} {}   {} {} ({:?})   {} {}",
        paint.paint("account:", Palette::label()),
        profile.account,
        paint.paint("org:", Palette::label()),
        profile.org_id,
        profile.org_kind,
        paint.paint("queue:", Palette::label()),
        profile.default_queue.as_deref().unwrap_or("-"),
    );
}

/// Persist the queue map, so a later bare key can be judged without a request.
fn remember_queues(
    session: &Session,
    brief: bool,
    active_only: bool,
    active: Option<&str>,
    queues_seen: &std::collections::BTreeMap<String, Vec<String>>,
) {
    if brief {
        return;
    }

    let cache_path = crate::config::cache::path_for(&session.config_file);
    let mut cache = crate::config::cache::Cache::load(&cache_path);

    for name in session
        .config
        .profiles
        .keys()
        .filter(|name| !active_only || active == Some(name.as_str()))
    {
        let keys: Vec<String> = queues_seen
            .iter()
            .filter(|(_, profiles)| profiles.iter().any(|profile| profile == name))
            .map(|(key, _)| key.clone())
            .collect();
        cache.record(name, &keys);
    }

    cache.save(&cache_path);
}

/// Where the configuration itself came from, before anything about profiles.
///
/// Two questions get asked whenever this command surprises somebody: which file
/// was read, and what in the environment is overriding it. Both are cheap to
/// answer and neither is guessable from the rows below — a token from the
/// environment and a token from the keychain produce identical-looking output
/// until one of them is named.
///
/// Variable **names** only. One of them holds a token, and a diagnostic that
/// prints credentials is a diagnostic nobody can paste into a bug report.
fn report_sources(session: &Session, paint: Painter, out: &mut impl std::io::Write) {
    let from = match std::env::var("YTCLI_CONFIG") {
        Ok(path) if session.config_file == std::path::Path::new(&path) => "from YTCLI_CONFIG",
        _ if session.global.config.is_some() => "from --config",
        _ => "default location",
    };

    let _ = writeln!(
        out,
        "{} {} ({})",
        paint.paint("config:", Palette::label()),
        session.config_file.display(),
        paint.paint(from, Palette::label()),
    );

    // Everything `YTCLI_`-prefixed: figment merges these over the file, so a
    // value in the config that does not match what the tool is doing is usually
    // one of these.
    let mut overriding: Vec<String> = std::env::vars()
        .map(|(name, _)| name)
        .filter(|name| name.starts_with("YTCLI_") && !name.is_empty())
        .collect();
    overriding.sort();

    if !overriding.is_empty() {
        let _ = writeln!(
            out,
            "{} {}",
            paint.paint("environment:", Palette::label()),
            overriding.join(", "),
        );
    }
}

/// Say which queue keys mean two different things.
///
/// Two profiles seeing one queue key is only a problem when they are looking at
/// two different organisations: then `FINANSY-1` names two issues and the tool
/// refuses to choose. Inside one organisation it names one issue seen through
/// two logins, either of which fetches it — warning about that would be telling
/// the reader their setup is broken when it is working as designed.
///
/// Better heard here than discovered by commenting on the wrong issue.
fn warn_about_collisions(
    session: &Session,
    paint: Painter,
    queues_seen: &std::collections::BTreeMap<String, Vec<String>>,
) {
    let mut err = anstream::stderr();

    let organisation = |name: &str| {
        session
            .config
            .profiles
            .get(name)
            .map(|profile| profile.org_id.clone())
    };

    let ambiguous: Vec<(&String, &Vec<String>)> = queues_seen
        .iter()
        .filter(|(_, profiles)| {
            profiles.len() > 1
                && profiles
                    .iter()
                    .filter_map(|name| organisation(name))
                    .collect::<std::collections::BTreeSet<_>>()
                    .len()
                    > 1
        })
        .collect();
    if ambiguous.is_empty() {
        return;
    }

    let _ = writeln!(err);
    for (key, profiles) in ambiguous {
        let _ = writeln!(
            err,
            "{} queue {key} is visible in {} — in different organisations, so a bare {key}-1 will be refused; write {}/{key}-1",
            paint.paint("warning:", Palette::warn()),
            profiles.join(" and "),
            profiles.first().map_or("profile", String::as_str),
        );
    }
}

/// Everything that needs the network, for one profile.
async fn report_profile(
    profile: &crate::config::Profile,
    brief: bool,
    paint: Painter,
    profile_name: &str,
    queues_seen: &mut std::collections::BTreeMap<String, Vec<String>>,
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let (token, origin) = match secrets::token_from(&profile.account) {
        Ok(pair) => pair,
        Err(error) => {
            let _ = writeln!(
                out,
                "  {} {}",
                paint.paint("token:", Palette::label()),
                paint.paint("missing", Palette::bad())
            );
            let _ = writeln!(err, "  {error}");
            return ExitCode::Auth;
        }
    };

    let mut config = ClientConfig::new(token, profile.org_id.clone(), profile.org_kind);
    if let Ok(base) = std::env::var("YTCLI_BASE_URL") {
        config.base_url = base;
    }
    if let Ok(wiki) = std::env::var("YTCLI_WIKI_URL") {
        config.wiki_url = wiki;
    }
    let client = match Client::new(&config) {
        Ok(client) => client,
        Err(error) => {
            let _ = writeln!(err, "  {error}");
            return error.exit_code();
        }
    };

    // Which token answered, when it is not the one this profile's account
    // holds. Without this the reader has no way to tell that every profile is
    // being read through one identity.
    let via = match origin {
        secrets::Origin::Environment => " (from YTCLI_TOKEN)",
        // Named rather than left blank: "where did this credential come from"
        // is the question, and an unlabelled answer is only obvious to whoever
        // wrote the tool.
        secrets::Origin::Keychain => " (from keychain)",
    };

    match client.myself().await {
        Ok(user) => {
            let _ = writeln!(
                out,
                "  {} {}{via}   {} {}{}",
                paint.paint("token:", Palette::label()),
                paint.paint("ok", Palette::ok()),
                paint.paint("user:", Palette::label()),
                user.login.as_deref().unwrap_or(&user.id),
                user.display
                    .as_deref()
                    .map_or_else(String::new, |display| format!(" ({display})")),
            );
        }
        Err(error) => {
            let _ = writeln!(
                out,
                "  {} {}",
                paint.paint("token:", Palette::label()),
                paint.paint("rejected", Palette::bad())
            );
            let _ = writeln!(err, "  {error}");
            if matches!(error, crate::api::error::ApiError::Unauthorized) {
                let _ = writeln!(err, "\n{}", guidance::block(guidance::TOKEN));
            }
            return error.exit_code();
        }
    }

    if brief {
        return ExitCode::Success;
    }

    reach(&client, paint, profile_name, queues_seen, out).await;
    ExitCode::Success
}

/// What this profile can actually see.
///
/// Every lookup is best-effort: a profile without access to projects should
/// still report its queues rather than losing the whole line.
async fn reach(
    client: &Client,
    paint: Painter,
    profile_name: &str,
    queues_seen: &mut std::collections::BTreeMap<String, Vec<String>>,
    out: &mut impl std::io::Write,
) {
    let queues = client.queues().await.ok();
    let projects = client.entities("project", None, 1, 5).await.ok();
    let goals = client.entities("goal", None, 1, 1).await.ok();
    let mine = client
        .count("Assignee: me() AND Resolution: empty()")
        .await
        .ok();

    let _ = writeln!(
        out,
        "  {} {}   {} {}   {} {}   {} {}",
        paint.paint("queues:", Palette::label()),
        queues
            .as_ref()
            .map_or_else(|| "-".to_owned(), |queues| queues.len().to_string()),
        paint.paint("projects:", Palette::label()),
        projects.as_ref().map_or_else(|| "-".to_owned(), count_of),
        paint.paint("goals:", Palette::label()),
        goals.as_ref().map_or_else(|| "-".to_owned(), count_of),
        paint.paint("my open issues:", Palette::label()),
        mine.map_or_else(|| "-".to_owned(), |count| count.to_string()),
    );

    if let Some(projects) = projects.filter(|page| !page.items.is_empty()) {
        let names: Vec<String> = projects
            .items
            .iter()
            .map(|project| {
                project.short_id.map_or_else(
                    || project.summary.clone(),
                    |id| format!("{} ({id})", project.summary),
                )
            })
            .collect();
        let more = projects
            .total
            .unwrap_or(names.len() as u64)
            .saturating_sub(names.len() as u64);
        let suffix = if more > 0 {
            format!(", +{more} more")
        } else {
            String::new()
        };
        let _ = writeln!(
            out,
            "  {} {}{suffix}",
            paint.paint("projects:", Palette::label()),
            names.join(", ")
        );
    }

    if let Some(queues) = queues.filter(|queues| !queues.is_empty()) {
        for queue in &queues {
            queues_seen
                .entry(queue.key.clone())
                .or_default()
                .push(profile_name.to_owned());
        }

        let keys: Vec<&str> = queues
            .iter()
            .take(8)
            .map(|queue| queue.key.as_str())
            .collect();
        let more = queues.len().saturating_sub(keys.len());
        let suffix = if more > 0 {
            format!(", +{more} more")
        } else {
            String::new()
        };
        let _ = writeln!(
            out,
            "  {} {}{suffix}",
            paint.paint("queues:", Palette::label()),
            keys.join(", ")
        );
    }

    // One request, answering what people need before their first `wiki`
    // command: whether this token was granted the Wiki at all.
    let wiki = match client.wiki_reachable().await {
        Ok(()) => paint.paint("ok", Palette::ok()),
        Err(crate::api::error::ApiError::WikiForbidden) => paint.paint(
            "no access — the token lacks wiki:read; sign in again with `ytcli auth login`",
            Palette::warn(),
        ),
        Err(crate::api::error::ApiError::WikiNotEnabled) => paint.paint(
            "not set up in this organisation — open https://wiki.yandex.ru once to start it",
            Palette::warn(),
        ),
        Err(_) => "-".to_owned(),
    };
    let _ = writeln!(out, "  {} {wiki}", paint.paint("wiki:", Palette::label()));
}

fn count_of<T>(page: &crate::api::models::Page<T>) -> String {
    page.total
        .map_or_else(|| page.items.len().to_string(), |total| total.to_string())
}

/// Read the token, check it, store it, and write the config to use it.
///
/// Flags and prompts are the same path: whatever was passed is taken as given,
/// and anything missing is asked for — but only when someone is there to answer.
/// Outside a terminal the flags are all there is, and a gap is an error rather
/// than a prompt nobody will ever see.
async fn login(args: &LoginArgs, session: &Session) -> ExitCode {
    let interactive = wizard::is_interactive();
    let mut err = anstream::stderr();

    // Without a way to sign in, interactive login always asks for a pasted
    // token — there is no flag to pass one in, on purpose — so the procedure is
    // needed up front. With one, it is shown only if pasting is chosen.
    if interactive && !oauth::App::is_configured() {
        wizard::introduce();
    }

    let Identity {
        account,
        token,
        refresh,
        org_id,
        org_kind: verified,
    } = match identity(args, session, interactive).await {
        Ok(identity) => identity,
        Err(code) => return code,
    };

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would store a token for `{account}` in the OS keychain"
        );
    } else {
        if let Err(error) = secrets::store(&account, &token) {
            return report(&error, ExitCode::Auth);
        }
        // A pasted token replaces the grant before it, so that grant's refresh
        // token goes too: spending it later would bring the old token back.
        if let Err(error) = secrets::store_refresh(&account, refresh.as_deref()) {
            return report(&error, ExitCode::Auth);
        }
        let _ = writeln!(
            err,
            "stored a token for `{account}` in the OS keychain{}",
            if refresh.is_some() {
                ", with what renews it"
            } else {
                ""
            }
        );
    }

    let Some(org_id) = org_id else {
        let _ = writeln!(
            err,
            "no --org-id given, so no profile was written and nothing can be queried yet.\n"
        );
        let _ = writeln!(err, "{}", guidance::block(guidance::ORG));
        let _ = writeln!(
            err,
            "\nThen: ytcli auth login --account {account} --org-id <id> [--queue <QUEUE>]"
        );
        return ExitCode::Success;
    };

    let org_kind = verified.unwrap_or(OrgKind::Cloud);

    let shape = Shape {
        account: &account,
        token: &token,
        org_id: &org_id,
        org_kind,
        interactive,
    };
    let (profile_name, profile, make_default) = match shape_profile(args, session, &shape).await {
        Ok(shaped) => shaped,
        Err(code) => return code,
    };

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would write profile `{profile_name}` (account={}, org={}, {:?}{}{}) to {}",
            profile.account,
            profile.org_id,
            profile.org_kind,
            profile
                .description
                .as_deref()
                .map_or_else(String::new, |note| format!(", {note}")),
            if make_default { ", default" } else { "" },
            session.config_file.display(),
        );
        return ExitCode::Success;
    }

    match store::upsert(
        &session.config_file,
        &account,
        None,
        Some((&profile_name, &profile)),
        make_default,
    ) {
        Ok(_) => {
            let _ = writeln!(
                err,
                "wrote profile `{profile_name}` to {}{}",
                session.config_file.display(),
                if make_default { " (default)" } else { "" },
            );
            let _ = writeln!(err, "try it: ytcli auth status --active-only");
            emit(&format!("{profile_name}\n"));
            ExitCode::Success
        }
        Err(error) => report(&error, ExitCode::Failure),
    }
}

/// Who is logging in, where, and with what — everything settled before anything
/// is written.
struct Identity {
    account: String,
    token: String,
    /// What renews the token; only a signed-in token has one.
    refresh: Option<String>,
    org_id: Option<String>,
    /// The organisation flavour that answered, once verified.
    org_kind: Option<OrgKind>,
}

/// Collect and check the credentials.
///
/// Flags win; a terminal fills the gaps; outside one, a gap is an error rather
/// than a prompt nobody will see.
async fn identity(
    args: &LoginArgs,
    session: &Session,
    interactive: bool,
) -> Result<Identity, ExitCode> {
    let mut err = anstream::stderr();

    let account = match args.account.clone() {
        Some(account) => account,
        None if interactive => {
            let existing: Vec<String> = session.config.accounts.keys().cloned().collect();
            wizard::account(&existing).map_err(|error| report(&error, error.exit_code()))?
        }
        None => {
            return Err(report(
                &"--account is required when not running in a terminal",
                ExitCode::ConfirmationRequired,
            ));
        }
    };

    let (token, refresh) = obtain_token(args, &account, interactive).await?;

    // The organisation decides whether a profile can be written at all, so it is
    // asked for rather than skipped when someone is there to answer.
    let (org_id, org_kind) = match (&args.org_id, interactive) {
        (Some(org_id), _) => (Some(org_id.clone()), args.org_kind),
        (None, true) => wizard::organisation()
            .map(|(id, kind)| (Some(id), kind))
            .map_err(|error| report(&error, error.exit_code()))?,
        (None, false) => (None, None),
    };

    let verified = match (&org_id, args.no_verify) {
        (Some(org_id), false) => {
            let (kind, who) = verify(&token, org_id, org_kind).await?;
            let _ = writeln!(err, "verified as {who} in org {org_id} ({kind:?})");
            Some(kind)
        }
        (Some(_), true) => Some(org_kind.unwrap_or(OrgKind::Cloud)),
        (None, _) => None,
    };

    Ok(Identity {
        account,
        token,
        refresh,
        org_id,
        org_kind: verified,
    })
}

/// Get a token: by signing in through the browser, or as pasted text.
///
/// Signing in is offered first whenever this build can do it, because it is the
/// path with nothing to register and nothing to copy. Pasting stays for CI and
/// for organisations that do not allow third-party applications.
async fn obtain_token(
    args: &LoginArgs,
    account: &str,
    interactive: bool,
) -> Result<(String, Option<String>), ExitCode> {
    let configured = oauth::App::is_configured();
    let browser = args.device
        || (interactive
            && configured
            && wizard::sign_in_in_browser().map_err(|error| report(&error, error.exit_code()))?);

    if browser {
        let grant = sign_in(args.read_only, interactive).await?;
        if interactive && args.org_id.is_none() {
            let mut err = anstream::stderr();
            let _ = writeln!(err, "\n{}", guidance::block(guidance::ORG));
        }
        return Ok((grant.access_token, grant.refresh_token));
    }

    if interactive && configured {
        wizard::introduce();
    }
    read_token(account, interactive).map(|token| (token, None))
}

/// The device-code sign-in: show a code, wait for it to be confirmed.
async fn sign_in(read_only: bool, interactive: bool) -> Result<oauth::Grant, ExitCode> {
    let fail = |error: oauth::OAuthError| report(&error, error.exit_code());
    let mut err = anstream::stderr();

    let app = oauth::App::from_environment().map_err(fail)?;
    let code = app
        .request_code(read_only.then_some(oauth::READ_ONLY_SCOPE))
        .await
        .map_err(fail)?;

    // Three steps someone new to this can follow without knowing what a device
    // code is: the code on a line of its own, where it can be found and
    // double-clicked, and the page as a link a terminal will actually open.
    let paint = Painter::for_stream(std::io::IsTerminal::is_terminal(&std::io::stderr()));
    let expires = code.expires_in.map_or_else(String::new, |seconds| {
        format!("   (expires in {} min)", seconds.div_ceil(60))
    });
    let _ = writeln!(
        err,
        "\n{}\n\n  1. Copy the code   {}\n  2. Open the page   {}{}\n  3. Paste the code there and allow access for ytcli\n\n  {}\n",
        paint.paint("Sign in with Yandex", Palette::heading()),
        paint.paint(&code.user_code, Palette::key()),
        paint.link(&code.verification_url),
        paint.paint(&expires, Palette::label()),
        // The one way this flow is abused: someone else's code, sent with a
        // plausible reason, grants them the token.
        paint.paint(
            "Only confirm a code you started here yourself.",
            Palette::label()
        ),
    );

    let early = if interactive {
        wizard::press_enter("Press Enter to open the page in your browser… ")
            .map_err(|error| report(&error, error.exit_code()))?;
        // Someone who followed the steps first and pressed Enter afterwards has
        // confirmed already, and a second tab asking again would only confuse.
        let early = app.try_grant(&code).await.map_err(fail)?;
        if early.is_none() {
            open_browser(&code.verification_url);
        }
        early
    } else {
        None
    };

    let grant = if let Some(grant) = early {
        grant
    } else {
        let _ = writeln!(err, "waiting for the code to be confirmed…");
        app.await_grant(&code).await.map_err(fail)?
    };
    let _ = writeln!(
        err,
        "signed in{}",
        if grant.refresh_token.is_some() {
            "; renew later with `ytcli auth refresh`"
        } else {
            ""
        }
    );
    Ok(grant)
}

/// Open the confirmation page, when it is the page it should be.
///
/// The address comes from the network, and on Windows it goes through `cmd`,
/// where `&` starts a second command. Anything but a plain Yandex address is
/// left printed for the person to open themselves. Yandex answers with
/// `https://ya.ru/device` today, and documents `oauth.yandex.*`.
fn open_browser(url: &str) {
    let plain = ["https://ya.ru/", "https://oauth.yandex."]
        .iter()
        .any(|prefix| url.starts_with(prefix))
        && url
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b":/.-_".contains(&byte));
    if !plain {
        return;
    }

    let mut command = if cfg!(target_os = "macos") {
        std::process::Command::new("open")
    } else if cfg!(windows) {
        let mut command = std::process::Command::new("cmd");
        command.args(["/C", "start", ""]);
        command
    } else {
        std::process::Command::new("xdg-open")
    };
    let _ = command
        .arg(url)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();
}

/// Renew a token through its refresh token.
///
/// Only a token that came from signing in has one. A pasted token is renewed by
/// pasting again, and saying so beats a bare "not found".
async fn refresh(session: &Session, account: Option<&str>) -> ExitCode {
    let mut err = anstream::stderr();

    let Some(account) = account.map(ToOwned::to_owned).or_else(|| {
        session
            .resolved
            .as_ref()
            .map(|resolved| resolved.profile.account.clone())
    }) else {
        return report(
            &"no --account given, and no active profile to take one from",
            ExitCode::Auth,
        );
    };

    // Renewing touches no organisation, but every profile on this account
    // changes identity with it, so they are named before anything happens.
    let using: Vec<String> = session
        .config
        .profiles
        .iter()
        .filter(|(_, profile)| profile.account == account)
        .map(|(name, profile)| format!("{name} (org {})", profile.org_id))
        .collect();
    let _ = writeln!(
        err,
        "renewing the token of account `{account}`, used by: {}",
        if using.is_empty() {
            "no profile".to_owned()
        } else {
            using.join(", ")
        }
    );

    let refresh_token = match secrets::refresh_token(&account) {
        Ok(Some(token)) => token,
        Ok(None) => {
            return report(
                &format!(
                    "`{account}` has nothing to renew it with: its token was pasted, not signed in for. \
                     Run `ytcli auth login --account {account}`"
                ),
                ExitCode::Auth,
            );
        }
        Err(error) => return report(&error, ExitCode::Auth),
    };

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would exchange the refresh token of `{account}` for a new token"
        );
        return ExitCode::Success;
    }

    let grant = match oauth::App::from_environment() {
        Ok(app) => app.refresh(&refresh_token).await,
        Err(error) => Err(error),
    };
    let grant = match grant {
        Ok(grant) => grant,
        Err(error) => return report(&error, error.exit_code()),
    };

    let unchanged = secrets::token(&account).is_ok_and(|current| current == grant.access_token);
    if let Err(error) = secrets::store(&account, &grant.access_token) {
        return report(&error, ExitCode::Auth);
    }
    let renews = grant.refresh_token.as_deref().unwrap_or(&refresh_token);
    if let Err(error) = secrets::store_refresh(&account, Some(renews)) {
        return report(&error, ExitCode::Auth);
    }

    if unchanged {
        let _ = writeln!(
            err,
            "Yandex kept the same token for `{account}`: it has long enough left to run"
        );
    } else {
        let _ = writeln!(err, "stored a renewed token for `{account}`");
    }
    ExitCode::Success
}

/// What the profile is being built from, once identity is settled.
struct Shape<'a> {
    account: &'a str,
    token: &'a str,
    org_id: &'a str,
    org_kind: OrgKind,
    interactive: bool,
}

/// Decide the profile's name, its queue and whether it becomes the default.
///
/// Split out so each half of login stays readable: this one asks questions and
/// touches nothing.
async fn shape_profile(
    args: &LoginArgs,
    session: &Session,
    shape: &Shape<'_>,
) -> Result<(String, Profile, bool), ExitCode> {
    let profile_name = match args.profile.clone() {
        Some(name) => name,
        None if shape.interactive => {
            wizard::profile(shape.account).map_err(|error| report(&error, error.exit_code()))?
        }
        None => shape.account.to_owned(),
    };

    // Offer the queues this token can actually see. Verifying first is what makes
    // that possible, and turns a spelling test into a choice.
    let queue = match args.queue.clone() {
        Some(queue) => Some(queue),
        None if shape.interactive => {
            let available = queue_keys(shape.token, shape.org_id, shape.org_kind).await;

            // Listing them anyway makes recording them free, and a collision
            // with an existing profile can then be caught on the next command
            // rather than after acting on the wrong issue.
            if !session.global.dry_run {
                let cache_path = crate::config::cache::path_for(&session.config_file);
                let mut cache = crate::config::cache::Cache::load(&cache_path);
                cache.record(&profile_name, &available);
                cache.save(&cache_path);
            }

            wizard::queue(&available).map_err(|error| report(&error, error.exit_code()))?
        }
        None => None,
    };

    // Kept when a re-login does not mention it: the note is about the
    // organisation, which has not changed just because the token was renewed.
    let existing = session
        .config
        .profiles
        .get(&profile_name)
        .and_then(|profile| profile.description.clone());
    let description = match (args.description.clone(), shape.interactive) {
        (Some(text), _) => Some(text),
        (None, true) => wizard::description(existing.as_deref())
            .map_err(|error| report(&error, error.exit_code()))?
            .or(existing),
        (None, false) => existing,
    };

    let current_default = session.config.default_profile.as_deref();
    let make_default = if args.default || current_default.is_none() {
        true
    } else if shape.interactive {
        wizard::make_default(&profile_name, current_default)
            .map_err(|error| report(&error, error.exit_code()))?
    } else {
        false
    };

    Ok((
        profile_name,
        Profile {
            account: shape.account.to_owned(),
            org_id: shape.org_id.to_owned(),
            org_kind: shape.org_kind,
            description,
            default_queue: queue,
            display: crate::config::Display::default(),
        },
        make_default,
    ))
}

/// Queue keys this token can see, for the picker. Best-effort: failing to list
/// them costs a dropdown, not the login.
async fn queue_keys(token: &str, org_id: &str, kind: OrgKind) -> Vec<String> {
    let mut config = ClientConfig::new(token.to_owned(), org_id.to_owned(), kind);
    if let Ok(base) = std::env::var("YTCLI_BASE_URL") {
        config.base_url = base;
    }

    let Ok(client) = Client::new(&config) else {
        return Vec::new();
    };

    client.queues().await.map_or_else(
        |_| Vec::new(),
        |queues| queues.into_iter().map(|queue| queue.key).collect(),
    )
}

/// Read the token: a hidden prompt when someone is typing, stdin when piped.
fn read_token(account: &str, interactive: bool) -> Result<String, ExitCode> {
    if interactive {
        return wizard::token(account).map_err(|error| report(&error, error.exit_code()));
    }

    let mut piped = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut piped)
        .map_err(|error| report(&error, ExitCode::Failure))?;

    let token = piped.trim().to_owned();
    if token.is_empty() {
        return Err(report(&"no token given", ExitCode::Auth));
    }
    Ok(token)
}

/// Check the token against the API, working out which organisation header it
/// needs if that was not said.
///
/// The two header forms are not interchangeable and the wrong one answers 403,
/// which reads like a permissions problem rather than a configuration mistake.
/// Trying both here is one extra request, once, against an afternoon of
/// confusion later.
async fn verify(
    token: &str,
    org_id: &str,
    kind: Option<OrgKind>,
) -> Result<(OrgKind, String), ExitCode> {
    let candidates: Vec<OrgKind> = match kind {
        Some(kind) => vec![kind],
        None => vec![OrgKind::Cloud, OrgKind::Yandex360],
    };

    let mut last: Option<crate::api::error::ApiError> = None;

    for candidate in candidates {
        let mut config = ClientConfig::new(token.to_owned(), org_id.to_owned(), candidate);
        if let Ok(base) = std::env::var("YTCLI_BASE_URL") {
            config.base_url = base;
        }

        let client = match Client::new(&config) {
            Ok(client) => client,
            Err(error) => {
                let code = error.exit_code();
                return Err(report(&error, code));
            }
        };

        match client.myself().await {
            Ok(user) => {
                let who = user.login.or(user.display).unwrap_or(user.id);
                return Ok((candidate, who));
            }
            // A rejected token is rejected under either header; only an
            // organisation mismatch is worth retrying the other way.
            Err(error @ crate::api::error::ApiError::Unauthorized) => {
                let code = error.exit_code();
                let reported = report(&error, code);
                let mut err = anstream::stderr();
                let _ = writeln!(err, "\n{}", guidance::block(guidance::TOKEN));
                return Err(reported);
            }
            Err(error) => last = Some(error),
        }
    }

    let error = last.unwrap_or(crate::api::error::ApiError::Forbidden);
    let code = error.exit_code();
    let reported = report(
        &format!("{error} — checked both organisation header forms"),
        code,
    );
    let mut err = anstream::stderr();
    let _ = writeln!(err, "\n{}", guidance::block(guidance::ORG));
    Err(reported)
}

/// "That name is not in the config, and here are the ones that are."
///
/// The list matters more than the refusal: the usual cause is a typo or a
/// profile from another machine, and both are answered by seeing the names.
fn unknown<'a>(what: &str, name: &str, configured: impl Iterator<Item = &'a String>) -> ExitCode {
    let known: Vec<&str> = configured.map(String::as_str).collect();
    report(
        &format!(
            "no {what} called `{name}`; configured: {}",
            if known.is_empty() {
                "none — run `ytcli auth login`".to_owned()
            } else {
                known.join(", ")
            }
        ),
        ExitCode::NotFound,
    )
}

/// Point `default_profile` at another profile.
///
/// A local edit and nothing else: no token is read, no request is made. The
/// profile has to exist, because a default naming a profile that does not is a
/// config every later command fails on with a worse message than this one.
fn use_profile(session: &Session, profile: &str) -> ExitCode {
    let mut err = anstream::stderr();

    if !session.config.profiles.contains_key(profile) {
        return unknown("profile", profile, session.config.profiles.keys());
    }

    let previous = session.config.default_profile.clone();
    if previous.as_deref() == Some(profile) {
        let _ = writeln!(err, "`{profile}` is already the default profile");
        return ExitCode::Success;
    }

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would make `{profile}` the default profile in {}",
            session.config_file.display()
        );
        return ExitCode::Success;
    }

    match store::set_default(&session.config_file, profile) {
        Ok(_) => {
            let _ = writeln!(
                err,
                "default profile: {} → {profile}",
                previous.as_deref().unwrap_or("none"),
            );
            ExitCode::Success
        }
        Err(error) => report(&error, ExitCode::Failure),
    }
}

/// Change an existing profile.
///
/// Like `auth use`, a local edit: no token is read and no request is made, so a
/// profile can be corrected whether or not its credentials currently work. What
/// is not passed is not touched — the point of the command is changing one
/// thing without restating a profile that already works.
fn edit(args: &EditArgs, session: &Session) -> ExitCode {
    let mut err = anstream::stderr();

    if !session.config.profiles.contains_key(&args.profile) {
        return unknown("profile", &args.profile, session.config.profiles.keys());
    }

    // An account nobody has logged into is a profile that fails on every later
    // command, with a message about the account rather than about this edit.
    if let Some(account) = args
        .account
        .as_deref()
        .filter(|account| !session.config.accounts.contains_key(*account))
    {
        return unknown("account", account, session.config.accounts.keys());
    }

    // An empty string is how a shell says "nothing", so it means the same as
    // --clear-description rather than writing a note nobody can read.
    let description = if args.clear_description {
        Some(None)
    } else {
        args.description
            .as_deref()
            .map(str::trim)
            .map(|text| (!text.is_empty()).then_some(text))
    };

    let edits = store::Edits {
        name: args.name.as_deref(),
        account: args.account.as_deref(),
        org_id: args.org_id.as_deref(),
        org_kind: args.org_kind,
        description,
        default_queue: if args.clear_queue {
            Some(None)
        } else {
            args.queue.as_deref().map(Some)
        },
    };

    if edits.is_empty() {
        return report(
            &format!(
                "nothing to change; pass --name, --description, --account, --org-id, --org-kind or --queue (see `ytcli auth edit --help`)\ncurrently: {}",
                describe_current(session, &args.profile)
            ),
            ExitCode::ConfirmationRequired,
        );
    }

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would change profile `{}` in {}",
            args.profile,
            session.config_file.display()
        );
        return ExitCode::Success;
    }

    match store::edit(&session.config_file, &args.profile, &edits) {
        Ok(_) => {
            let name = args.name.as_deref().unwrap_or(&args.profile);
            if let Some(new_name) = args.name.as_deref().filter(|name| *name != args.profile) {
                rename_side_effects(session, &args.profile, new_name, &mut err);
            }
            let _ = writeln!(
                err,
                "profile `{name}`: {}",
                describe_after(session, &args.profile, &edits)
            );
            if args.org_id.is_some() || args.org_kind.is_some() || args.account.is_some() {
                let _ = writeln!(
                    err,
                    "check it: ytcli auth status --profile {name} --active-only"
                );
            }
            emit(&format!("{name}\n"));
            ExitCode::Success
        }
        Err(error) => {
            let code = match error {
                store::EditError::Unknown(_) => ExitCode::NotFound,
                // Neither is ApiRejected: nothing was sent. A name already in
                // use, and a file that will not parse, are both plain failures
                // of this local edit.
                store::EditError::NameTaken(_) | store::EditError::Store(_) => ExitCode::Failure,
            };
            report(&error, code)
        }
    }
}

/// Delete a profile.
///
/// The counterpart to `auth login`, and deliberately not the counterpart to
/// `auth logout`: logout forgets a credential, this forgets an organisation
/// someone was reaching through one. The token stays in the keychain, because
/// one account usually backs several profiles.
///
/// `--yes` is required even for one profile. Nothing here is sent anywhere, but
/// the `[profiles.x]` table carries display settings and pinned custom fields
/// that only exist in this file, and re-logging in does not bring them back.
fn remove(session: &Session, profile: &str) -> ExitCode {
    let mut err = anstream::stderr();

    let Some(current) = session.config.profiles.get(profile) else {
        return unknown("profile", profile, session.config.profiles.keys());
    };

    // The same promise every write makes: say which organisation this is about
    // before touching it. Here it matters more than usual — profile names are
    // short and similar, and organisation ids are what actually differ.
    let about = format!(
        "account={} org={} ({:?})",
        current.account, current.org_id, current.org_kind
    );

    if session.global.dry_run {
        let _ = writeln!(
            err,
            "dry run: would remove profile `{profile}` ({about}) from {}",
            session.config_file.display()
        );
        return ExitCode::Success;
    }

    if !session.global.yes {
        let _ = writeln!(
            err,
            "refusing to remove profile `{profile}` ({about}) without --yes: \
             its display settings and pinned fields live only in {}",
            session.config_file.display()
        );
        return ExitCode::ConfirmationRequired;
    }

    let account = current.account.clone();

    match store::remove(&session.config_file, profile) {
        Ok(removed) => {
            let _ = writeln!(err, "removed profile `{profile}` ({about})");
            removal_side_effects(
                session,
                profile,
                &account,
                removed.cleared_default,
                &mut err,
            );
            emit(&format!("{profile}\n"));
            ExitCode::Success
        }
        Err(error) => {
            let code = match error {
                store::EditError::Unknown(_) => ExitCode::NotFound,
                store::EditError::NameTaken(_) | store::EditError::Store(_) => ExitCode::Failure,
            };
            report(&error, code)
        }
    }
}

/// Everything outside the profile table that a removal leaves dangling.
///
/// Each of these is something the user would otherwise meet later, as a failure
/// with a worse message than this one.
fn removal_side_effects(
    session: &Session,
    profile: &str,
    account: &str,
    cleared_default: bool,
    err: &mut impl std::io::Write,
) {
    let cache_path = crate::config::cache::path_for(&session.config_file);
    let mut cache = crate::config::cache::Cache::load(&cache_path);
    if cache.forget(profile) {
        cache.save(&cache_path);
    }

    if cleared_default {
        let remaining: Vec<&str> = session
            .config
            .profiles
            .keys()
            .map(String::as_str)
            .filter(|name| *name != profile)
            .collect();
        let _ = writeln!(err, "default profile: {profile} → none");
        match remaining.as_slice() {
            [] => {
                let _ = writeln!(err, "no profiles left; `ytcli auth login` makes another");
            }
            [only] => {
                let _ = writeln!(err, "pick the next one: ytcli auth use {only}");
            }
            names => {
                let _ = writeln!(
                    err,
                    "pick the next one: ytcli auth use <{}>",
                    names.join("|")
                );
            }
        }
    }

    // The credential outlives the profile on purpose; saying so is what keeps
    // "I deleted it" from meaning two different things.
    let still_used = session
        .config
        .profiles
        .iter()
        .any(|(name, other)| name != profile && other.account == account);
    if !still_used && secrets::is_stored(account) {
        let _ = writeln!(
            err,
            "note: account `{account}` still holds a token; ytcli auth logout --account {account} forgets it"
        );
    }

    // Committed and shared with other checkouts, so it is reported rather than
    // rewritten — the same rule a rename follows.
    if let Some((path, _)) =
        crate::config::paths::find_project_pin(&std::env::current_dir().unwrap_or_default())
            .filter(|(_, pin)| pin.profile.as_deref() == Some(profile))
    {
        let _ = writeln!(
            err,
            "note: {} still names `{profile}`; update it by hand",
            path.display()
        );
    }
}

/// Carry a rename through the things outside the profile table that name it,
/// and say what a local edit cannot reach.
fn rename_side_effects(session: &Session, from: &str, to: &str, err: &mut impl std::io::Write) {
    let cache_path = crate::config::cache::path_for(&session.config_file);
    let mut cache = crate::config::cache::Cache::load(&cache_path);
    if cache.rename(from, to) {
        cache.save(&cache_path);
    }

    let _ = writeln!(err, "renamed profile `{from}` → `{to}`");

    // A committed `.tracker.toml` is shared with other people and other
    // checkouts; rewriting it from here would change what a colleague's next
    // command does, so it is reported instead.
    if let Some((path, _)) =
        crate::config::paths::find_project_pin(&std::env::current_dir().unwrap_or_default())
            .filter(|(_, pin)| pin.profile.as_deref() == Some(from))
    {
        let _ = writeln!(
            err,
            "note: {} still names `{from}`; update it by hand",
            path.display()
        );
    }

    if session.config.default_profile.as_deref() == Some(from) {
        let _ = writeln!(err, "default profile: {from} → {to}");
    }
}

/// The profile as it stands, for the message that says nothing was asked for.
fn describe_current(session: &Session, profile: &str) -> String {
    session
        .config
        .profiles
        .get(profile)
        .map_or_else(String::new, |current| {
            format!(
                "account={} org={} ({:?}) queue={} description={}",
                current.account,
                current.org_id,
                current.org_kind,
                current.default_queue.as_deref().unwrap_or("-"),
                current.description.as_deref().unwrap_or("-"),
            )
        })
}

/// What this edit changed, named key by key so the line is about the change and
/// not about the profile.
fn describe_after(session: &Session, profile: &str, edits: &store::Edits<'_>) -> String {
    let current = session.config.profiles.get(profile);
    let mut parts: Vec<String> = Vec::new();

    if let Some(account) = edits.account {
        parts.push(format!("account={account}"));
    }
    if let Some(org_id) = edits.org_id {
        parts.push(format!("org={org_id}"));
    }
    if let Some(org_kind) = edits.org_kind {
        parts.push(format!("org_kind={org_kind:?}"));
    }
    match edits.default_queue {
        Some(Some(queue)) => parts.push(format!("queue={queue}")),
        Some(None) => parts.push("queue removed".to_owned()),
        None => {}
    }
    match edits.description {
        Some(Some(text)) => parts.push(format!("description=\"{text}\"")),
        Some(None) => parts.push("description removed".to_owned()),
        None => {}
    }

    if parts.is_empty() {
        // A rename on its own: say what the profile is now, since its identity
        // is exactly what just changed.
        return current.map_or_else(String::new, |current| {
            format!("account={} org={}", current.account, current.org_id)
        });
    }

    parts.join(" ")
}

fn logout(account: &str) -> ExitCode {
    match secrets::forget(account) {
        Ok(()) => {
            let mut err = anstream::stderr();
            let _ = writeln!(err, "forgot the token for `{account}`");
            ExitCode::Success
        }
        Err(error) => report(&error, ExitCode::Auth),
    }
}

/// Accounts and the profiles pointing at them.
///
/// Whether a token exists is shown; the token never is.
fn list(session: &Session) -> ExitCode {
    let mut out = String::with_capacity(256);

    let active = session
        .resolved
        .as_ref()
        .map(|resolved| resolved.name.clone());

    for (name, account) in &session.config.accounts {
        let _ = writeln!(
            out,
            "account {name}  token: {}  {}",
            if secrets::is_stored(name) {
                "stored"
            } else {
                "missing"
            },
            account.description.as_deref().unwrap_or(""),
        );
    }

    for (name, profile) in &session.config.profiles {
        let marks = [
            (session.config.default_profile.as_deref() == Some(name.as_str())).then_some("default"),
            (active.as_deref() == Some(name.as_str())).then_some("active"),
        ];
        let marks: Vec<&str> = marks.into_iter().flatten().collect();
        let suffix = if marks.is_empty() {
            String::new()
        } else {
            format!("  [{}]", marks.join(", "))
        };

        let note = profile
            .description
            .as_deref()
            .map_or_else(String::new, |description| format!("  {description}"));

        let _ = writeln!(
            out,
            "profile {name}  account: {}  org: {} ({:?}){suffix}{note}",
            profile.account, profile.org_id, profile.org_kind,
        );
    }

    if out.is_empty() {
        return report(
            &"no accounts or profiles configured yet; see `ytcli auth login --help`",
            ExitCode::Auth,
        );
    }

    emit(&out);
    ExitCode::Success
}