kai-tool 0.1.29

CLI helpers for AI coding, Codex credentials, and git worktree management.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
use std::env;
use std::fmt;
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use anyhow::{Context, Result, anyhow, bail};
use clap::{Args, Subcommand};

use crate::codex::AccountRotation;

mod auth;
mod auth_lock;
mod enroll;
mod isolated_home;
mod paths;
mod quota;
mod rollout;
mod store;
mod ui;

use self::auth::{Credential, CredentialFacts, validate_email};
use self::paths::RuntimePaths;
use self::store::{Profile, Store, ensure_codex_uses_file_credentials};
use self::ui::{AccountStatus, AccountView, ListView, QuotaStatus};

#[derive(Debug, Args)]
#[command(after_help = concat!(
    "Examples:\n",
    "  kai cred add\n",
    "  kai cred add --device-auth\n",
    "  kai cred add --force\n",
    "  kai cred fix\n",
    "  kai cred list\n",
    "  kai cred tickle\n",
    "  kai next\n",
    "  kai cred activate personal@example.com\n",
    "  kai cred remove work@example.com",
))]
pub struct CredArgs {
    #[command(subcommand)]
    pub command: CredCommand,
}

#[derive(Debug, Subcommand)]
pub enum CredCommand {
    #[command(
        visible_alias = "ls",
        about = "List enrolled accounts with their live quota and active state."
    )]
    List(ListArgs),

    #[command(
        about = "Start any untouched seven-day quota countdowns.",
        long_about = concat!(
            "Find enrolled credentials whose quota reset time is still exactly seven days, ",
            "temporarily activate each one, and ask Codex for the current system GCC version ",
            "from the user's home directory. The original active credential is restored ",
            "afterward, including when a request fails.",
        )
    )]
    Tickle,

    #[command(about = "Activate the next usable enrolled account.")]
    Next,

    #[command(about = "Activate an enrolled account.")]
    Activate(AccountArgs),

    #[command(
        about = "Enroll an account through an isolated Codex login.",
        long_about = concat!(
            "Enroll an account through an isolated Codex login. Kai reads the account email ",
            "from the file-backed credential produced by Codex rather than requiring it as a ",
            "command-line argument. If Codex is already using an unenrolled account, Kai imports ",
            "the current credential without opening a browser. Kai ",
            "automatically uses device-code authentication in SSH, CI, and headless Linux ",
            "sessions; use --browser-auth or --device-auth to override detection. The new ",
            "account is activated when no account is active or the managed active account has ",
            "no remaining quota. For an already-enrolled account, --force runs a fresh isolated ",
            "login and safely replaces its credential.",
        )
    )]
    Add(AddArgs),

    #[command(
        about = "Find and reauthenticate broken enrolled credentials.",
        long_about = concat!(
            "Check every enrolled account and reauthenticate credentials that are invalid or ",
            "rejected by the Codex quota service. Each replacement is imported through an isolated ",
            "Codex login and must match the enrolled email and account/workspace ID. Repairs run ",
            "one at a time and wait for Enter before opening each account's sign-in.",
        )
    )]
    Fix(FixArgs),

    #[command(about = "Remove an enrolled account.")]
    Remove(RemoveArgs),
}

#[derive(Debug, Args)]
pub struct ListArgs {
    /// Emit stable machine-readable output without terminal styling.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct AccountArgs {
    /// Email address of the enrolled Codex account.
    #[arg(value_name = "EMAIL")]
    pub email: String,
}

#[derive(Debug, Args)]
pub struct AuthFlowArgs {
    /// Force Codex's device-code authentication flow.
    #[arg(long, conflicts_with = "browser_auth")]
    pub device_auth: bool,

    /// Use Codex's browser authentication flow, overriding environment detection.
    #[arg(long, conflicts_with = "device_auth")]
    pub browser_auth: bool,
}

#[derive(Debug, Args)]
pub struct AddArgs {
    #[command(flatten)]
    pub auth: AuthFlowArgs,

    /// Activate after enrollment even if the current account has remaining quota.
    #[arg(long)]
    pub activate: bool,

    /// Reauthenticate and replace the credential if the account is already enrolled.
    #[arg(long)]
    pub force: bool,
}

#[derive(Debug, Args)]
pub struct FixArgs {
    #[command(flatten)]
    pub auth: AuthFlowArgs,
}

#[derive(Debug, Args)]
pub struct RemoveArgs {
    /// Email address of the enrolled Codex account.
    #[arg(value_name = "EMAIL")]
    pub email: String,

    /// Skip the destructive confirmation prompt.
    #[arg(short = 'y', long)]
    pub yes: bool,
}

enum LiveAuth {
    Absent,
    Present(Credential),
    Invalid(anyhow::Error),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuotaAvailability {
    Remaining,
    Resettable,
    Exhausted,
    Unknown,
    Unusable,
}

#[derive(Debug)]
struct NoUsableQuota(String);

impl fmt::Display for NoUsableQuota {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl std::error::Error for NoUsableQuota {}

/// The account selected by one quota rotation, together with whether its quota was
/// positively confirmed.  Supervised recovery uses this to decide whether the selected
/// credential should also become the systemwide credential.
#[derive(Debug)]
struct NextSelection {
    target: Profile,
    changed: bool,
    target_has_remaining_quota: bool,
}

fn resolve_sqlite_home(cwd: &Path, codex_home: &Path, configured: Option<&str>) -> PathBuf {
    configured
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .map(|path| {
            if path.is_absolute() {
                path
            } else {
                cwd.join(path)
            }
        })
        .unwrap_or_else(|| codex_home.to_owned())
}

#[derive(Default)]
pub(crate) struct QuotaRecovery {
    source_paths: Option<RuntimePaths>,
    active_auth_file: Option<PathBuf>,
    sqlite_home: Option<PathBuf>,
}

impl QuotaRecovery {
    pub(crate) fn prepare(&mut self, cwd: &Path) -> Result<()> {
        if self.source_paths.is_some() {
            return Ok(());
        }
        let _invocation_lock = capulus::acquire("kai-cred", true)?;
        let store = open_store()?;
        let source_paths = store.paths().clone();
        let configured_sqlite_home = env::var("CODEX_SQLITE_HOME").ok();
        let sqlite_home = resolve_sqlite_home(
            cwd,
            &source_paths.codex_home,
            configured_sqlite_home.as_deref(),
        );
        rollout::normalize_rollout_paths(
            &sqlite_home,
            &source_paths.credentials_home,
            &source_paths.codex_home,
        )
        .context("could not repair stale supervised Codex rollout paths")?;
        let active_auth_file = load_live_strict(&store)?
            .and_then(|credential| managed_profile(&store, &credential))
            .map(|profile| store.profile_auth_path(profile));
        self.source_paths = Some(source_paths);
        self.active_auth_file = active_auth_file;
        self.sqlite_home = Some(sqlite_home);
        Ok(())
    }

    pub(crate) fn codex_home(&self) -> Result<&Path> {
        Ok(&self
            .source_paths
            .as_ref()
            .context("quota recovery was not prepared")?
            .codex_home)
    }

    /// The canonical enrolled auth file used by a supervised downstream child, if there is a
    /// managed active credential. All non-auth Codex state remains under codex_home.
    pub(crate) fn auth_file(&self) -> Option<PathBuf> {
        self.active_auth_file.clone()
    }

    pub(crate) fn sqlite_home(&self) -> Result<&Path> {
        self.sqlite_home
            .as_deref()
            .context("quota recovery was not prepared")
    }

    pub(crate) fn rotate(&mut self) -> Result<AccountRotation> {
        classify_account_rotation(credential_runtime()?.block_on(self.rotate_async()))
    }

    async fn rotate_async(&mut self) -> Result<PathBuf> {
        let _invocation_lock = capulus::acquire("kai-cred", true)?;
        let mut store = self.open_store()?;
        let current_profile = self.active_auth_file.as_ref().and_then(|auth_file| {
            store
                .profiles()
                .iter()
                .find(|profile| store.profile_auth_path(profile) == *auth_file)
                .cloned()
        });
        let selection = choose_next_selection_from(&mut store, current_profile.as_ref()).await?;
        // Keep the systemwide promotion in this same critical section as the canonical path switch.
        self.promote_systemwide_if_exhausted(&selection).await?;
        let auth_file = store.profile_auth_path(&selection.target);
        self.active_auth_file = Some(auth_file.clone());
        Ok(auth_file)
    }

    /// A supervised run normally changes only the selected canonical auth file. When recovery
    /// found a confirmed-capacity account, also move the user's systemwide account if that account is
    /// currently exhausted.  This runs from [`Self::rotate_async`], while the `kai-cred`
    /// invocation lock is held, so the live credential cannot be switched by another Kai
    /// credential operation between the quota check and the install.
    async fn promote_systemwide_if_exhausted(&self, selection: &NextSelection) -> Result<()> {
        if !selection.changed || !selection.target_has_remaining_quota {
            return Ok(());
        }

        let mut primary = self.open_primary_store()?;
        let live = match load_live(&primary) {
            LiveAuth::Present(credential) => credential,
            LiveAuth::Absent | LiveAuth::Invalid(_) => return Ok(()),
        };
        let active = match managed_profile(&primary, &live).cloned() {
            Some(profile) => profile,
            None => return Ok(()),
        };
        if active.account_id == selection.target.account_id {
            return Ok(());
        }

        let active_quota = match fetch_credential_quota(&primary, &live).await {
            Ok(snapshot) => snapshot,
            Err(err) => {
                ui::warn(&format!(
                    "Could not check whether {} has remaining quota; leaving it active: {err:#}",
                    active.email
                ));
                return Ok(());
            }
        };
        if active_quota.remaining_percent > 0.0 {
            return Ok(());
        }

        // Re-read the live credential after the quota worker finishes.  A non-Kai Codex process
        // may have changed it while the isolated request was in flight; never overwrite that
        // newer account based on the stale account's quota result.
        match load_live(&primary) {
            LiveAuth::Present(credential) if credential.facts.account_id == active.account_id => {}
            LiveAuth::Absent | LiveAuth::Invalid(_) | LiveAuth::Present(_) => return Ok(()),
        }

        let target = match primary
            .find_profile_by_account(&selection.target.account_id)
            .cloned()
        {
            Some(profile) => profile,
            None => return Ok(()),
        };
        activate(&mut primary, &target)?;
        Ok(())
    }

    fn open_store(&self) -> Result<Store> {
        let source_paths = self
            .source_paths
            .as_ref()
            .context("quota recovery was not prepared")?;
        ensure_codex_uses_file_credentials(source_paths)?;
        Store::open(source_paths.clone())
    }

    fn open_primary_store(&self) -> Result<Store> {
        let source_paths = self
            .source_paths
            .as_ref()
            .context("quota recovery was not prepared")?;
        ensure_codex_uses_file_credentials(source_paths)?;
        Store::open(source_paths.clone())
    }
}

fn classify_account_rotation(result: Result<PathBuf>) -> Result<AccountRotation> {
    match result {
        Ok(auth_file) => Ok(AccountRotation::Rotated { auth_file }),
        Err(error) if error.downcast_ref::<NoUsableQuota>().is_some() => {
            Ok(AccountRotation::NoQuota(format!("{error:#}")))
        }
        Err(error) => Err(error),
    }
}

pub fn run(command: CredCommand) -> Result<()> {
    credential_runtime()?.block_on(run_async(command))
}

async fn run_async(command: CredCommand) -> Result<()> {
    let _invocation_lock = capulus::acquire("kai-cred", true)?;
    let mut store = open_store()?;
    match command {
        CredCommand::List(args) => cmd_list(&store, args).await,
        CredCommand::Tickle => cmd_tickle(&mut store).await,
        CredCommand::Next => cmd_next(&mut store).await,
        CredCommand::Activate(args) => cmd_activate(&mut store, &args.email),
        CredCommand::Add(args) => cmd_add(&mut store, args).await,
        CredCommand::Fix(args) => cmd_fix(&mut store, args).await,
        CredCommand::Remove(args) => cmd_remove(&mut store, args),
    }
}

fn credential_runtime() -> Result<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .context("could not initialize the credential runtime")
}

fn open_store() -> Result<Store> {
    let paths = RuntimePaths::from_env()?;
    ensure_codex_uses_file_credentials(&paths)?;
    let store = Store::open(paths)?;
    store.ensure_canonical_active()?;
    Ok(store)
}

async fn cmd_list(store: &Store, args: ListArgs) -> Result<()> {
    let live = load_live(store);
    let active_profile = match &live {
        LiveAuth::Present(credential) => managed_profile(store, credential),
        _ => None,
    };
    let active_id = active_profile.map(|profile| profile.id.as_str());
    let active_index = active_profile.and_then(|active| {
        store
            .profiles()
            .iter()
            .position(|profile| profile.id == active.id)
    });
    let can_select_next = matches!(&live, LiveAuth::Absent) || active_profile.is_some();
    let quota_client = quota::Client::new(store.paths()).map_err(|err| format!("{err:#}"));
    let mut quota_tasks = tokio::task::JoinSet::new();
    let mut accounts = Vec::with_capacity(store.profiles().len());
    for profile in store.profiles() {
        let active = active_id == Some(profile.id.as_str());
        let credential = if active {
            match &live {
                LiveAuth::Present(credential) => {
                    Credential::from_bytes(credential.as_bytes().to_vec())
                }
                _ => unreachable!(),
            }
        } else {
            store.credential(profile)
        };
        let (mut account, credential) = match credential {
            Ok(credential) => {
                let facts = credential.facts.clone();
                (
                    ready_account_view(profile, active, facts, QuotaStatus::Loading),
                    Some(credential),
                )
            }
            Err(err) => (
                AccountView {
                    email: profile.email.clone(),
                    active,
                    plan: None,
                    last_refresh: None,
                    status: AccountStatus::Invalid {
                        error: format!("{err:#}"),
                    },
                    quota: QuotaStatus::Unavailable {
                        error: "credential is invalid".to_owned(),
                        authentication_required: true,
                    },
                },
                None,
            ),
        };
        let index = accounts.len();
        if let Some(credential) = credential {
            match &quota_client {
                Ok(client) => {
                    let client = client.clone();
                    let auth_file = store.profile_auth_path(profile);
                    quota_tasks
                        .spawn(async move { (index, client.fetch(credential, auth_file).await) });
                }
                Err(error) => {
                    account.quota = QuotaStatus::Unavailable {
                        error: error.clone(),
                        authentication_required: false,
                    };
                }
            }
        }
        accounts.push(account);
    }
    let active = active_profile.map(|profile| profile.email.clone());
    let mut view = ListView {
        active,
        next: None,
        accounts,
    };
    let live_list = if args.json {
        None
    } else {
        ui::LiveList::start(&view)
    };
    while let Some(result) = quota_tasks.join_next().await {
        let (index, outcome) = result.context("a quota lookup task stopped unexpectedly")?;
        persist_quota_credential(store, &store.profiles()[index], &outcome)?;
        view.accounts[index].last_refresh = outcome.credential.facts.last_refresh.clone();
        view.accounts[index].set_quota(outcome.snapshot);
        if let Some(live_list) = &live_list {
            live_list.update(index, &view.accounts[index]);
        }
    }
    if can_select_next {
        let order = rotation_order(store.profiles().len(), active_index);
        view.next = preferred_rotation_index(order.iter().copied().map(|index| {
            (
                index,
                quota_status_availability(&view.accounts[index].quota),
            )
        }))
        .map(|index| store.profiles()[index].email.clone());
    }
    if let Some(live_list) = live_list {
        live_list.finish(&view)?;
    } else {
        ui::print_list(&view, args.json)?;
    }

    if !args.json {
        match live {
            LiveAuth::Present(credential) if active_profile.is_none() => ui::warn(&format!(
                concat!(
                    "Codex is signed in as {}, but that account is not enrolled. ",
                    "Run `kai cred add` to preserve it before switching.",
                ),
                credential.facts.email
            )),
            LiveAuth::Invalid(err) => ui::warn(&format!(
                "The active Codex credential could not be read: {err:#}"
            )),
            _ => {}
        }
    }
    Ok(())
}

async fn cmd_tickle(store: &mut Store) -> Result<()> {
    if store.profiles().is_empty() {
        bail!("no accounts are enrolled; run `kai cred add` first");
    }

    let live = load_live_strict(store)?;
    let original_active = match &live {
        Some(credential) => {
            let profile = require_managed_profile(store, credential)?.clone();
            Some(profile)
        }
        None => None,
    };
    let profile_indices = (0..store.profiles().len()).collect::<Vec<_>>();
    ui::stage("Checking enrolled account quotas");
    let checks = fetch_profile_quotas(store, &profile_indices, live.as_ref()).await?;
    let now = chrono::Utc::now().timestamp();
    let mut targets = Vec::new();
    for (index, result) in checks {
        match result {
            Ok(snapshot) if quota::countdown_has_not_started(&snapshot, now) => {
                targets.push(store.profiles()[index].clone());
            }
            Ok(_) => {}
            Err(err) => ui::warn(&format!(
                "Could not retrieve quota for {}: {err:#}",
                store.profiles()[index].email
            )),
        }
    }

    if targets.is_empty() {
        ui::success("No enrolled credentials have an untouched seven-day countdown.");
        return Ok(());
    }

    let codex = which::which("codex").context("could not find `codex` on PATH")?;
    let home = capulus::paths::home_dir()
        .context("could not determine the current user's home directory")?;
    let noun = if targets.len() == 1 {
        "credential"
    } else {
        "credentials"
    };
    ui::stage(&format!(
        "Starting {} untouched seven-day quota {noun}",
        targets.len()
    ));

    let tickle_result = tickle_profiles(store, &targets, &codex, &home);
    let restore_result = restore_original_active(store, original_active.as_ref());
    match (tickle_result, restore_result) {
        (Ok(()), Ok(())) => {
            ui::success(&format!(
                "Tickled {} {noun} and restored the original Codex credential.",
                targets.len()
            ));
            Ok(())
        }
        (Err(err), Ok(())) => Err(err),
        (Ok(()), Err(restore_err)) => Err(restore_err)
            .context("Codex requests completed, but the original credential was not restored"),
        (Err(tickle_err), Err(restore_err)) => bail!(
            "{tickle_err:#}; additionally, could not restore the original credential: \
             {restore_err:#}"
        ),
    }
}

fn tickle_profiles(
    store: &mut Store,
    targets: &[Profile],
    codex: &Path,
    home: &Path,
) -> Result<()> {
    let mut failures = Vec::new();
    for target in targets {
        activate(store, target)
            .with_context(|| format!("could not temporarily activate {}", target.email))?;
        ui::detail(&format!("Tickling {}...", target.email));
        if let Err(err) = run_codex_tickle(codex, home) {
            ui::warn(&format!("Could not tickle {}: {err:#}", target.email));
            failures.push(target.email.clone());
        }
    }
    if failures.is_empty() {
        Ok(())
    } else {
        bail!("Codex request failed for {}", failures.join(", "))
    }
}

fn run_codex_tickle(codex: &Path, home: &Path) -> Result<()> {
    let output = Command::new(codex)
        .args([
            "exec",
            "--skip-git-repo-check",
            "--ephemeral",
            "What is the current system `gcc` version? (Reply with only the version number.)",
        ])
        .env_remove("CODEX_AUTH_FILE")
        .current_dir(home)
        .stdin(Stdio::null())
        .output()
        .with_context(|| format!("could not start {}", codex.display()))?;
    if output.status.success() {
        return Ok(());
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stderr = stderr.trim();
    if stderr.is_empty() {
        bail!("Codex exited with {}", output.status);
    }
    bail!("Codex exited with {}: {stderr}", output.status)
}

fn ready_account_view(
    profile: &Profile,
    active: bool,
    facts: CredentialFacts,
    quota: QuotaStatus,
) -> AccountView {
    AccountView {
        email: profile.email.clone(),
        active,
        plan: facts.plan,
        last_refresh: facts.last_refresh,
        status: AccountStatus::Ready,
        quota,
    }
}

async fn cmd_next(store: &mut Store) -> Result<()> {
    let selection = choose_next_selection_from(store, None).await?;
    let changed = activate(store, &selection.target)?;
    if changed {
        ui::success(&format!("Codex is now using {}.", selection.target.email));
        if store.uses_primary_codex_home() {
            warn_running_codex();
        }
    }
    Ok(())
}

async fn choose_next_selection_from(
    store: &mut Store,
    selected_active: Option<&Profile>,
) -> Result<NextSelection> {
    if store.profiles().is_empty() {
        return Err(
            NoUsableQuota("no accounts are enrolled; run `kai cred add` first".to_owned()).into(),
        );
    }
    let (live, active_index) = match selected_active {
        Some(active) => {
            let active_index = store
                .profiles()
                .iter()
                .position(|profile| profile.id == active.id)
                .context("active profile disappeared while selecting the next account")?;
            let live = store.credential(active)?;
            (Some(live), Some(active_index))
        }
        None => {
            let live = load_live_strict(store)?;
            let active_index = match &live {
                None => None,
                Some(credential) => {
                    let active = require_managed_profile(store, credential)?;
                    Some(
                        store
                            .profiles()
                            .iter()
                            .position(|profile| profile.id == active.id)
                            .context(
                                "active profile disappeared while selecting the next account",
                            )?,
                    )
                }
            };
            (live, active_index)
        }
    };
    let order = rotation_order(store.profiles().len(), active_index);
    ui::stage("Checking enrolled account quotas");
    let checks = fetch_profile_quotas(store, &order, live.as_ref()).await?;
    let candidates = checks
        .iter()
        .map(|(index, result)| (*index, quota_result_availability(result)));
    let target_index = preferred_rotation_index(candidates);
    let Some(target_index) = target_index else {
        let scope = if active_index.is_some() && store.profiles().len() > 1 {
            "no other enrolled account has remaining Codex quota or usable reset credits"
        } else {
            "no enrolled account has remaining Codex quota or usable reset credits"
        };
        return Err(NoUsableQuota(format!(
            "{scope}; checked: {}",
            quota_check_summary(store, &checks)
        ))
        .into());
    };
    let target = store.profiles()[target_index].clone();
    let quota = checks
        .into_iter()
        .find_map(|(index, result)| (index == target_index).then_some(result))
        .context("selected account quota result disappeared")?;
    let changed = active_index.is_none_or(|index| store.profiles()[index].id != target.id);
    let target_has_remaining_quota = quota
        .as_ref()
        .is_ok_and(|snapshot| snapshot.remaining_percent > 0.0);
    match &quota {
        Ok(snapshot) => {
            ui::print_quota(snapshot);
            if snapshot.remaining_percent <= 0.0
                && let Some(reset_credits) = &snapshot.rate_limit_reset_credits
            {
                ui::print_reset_credit_notice(&target.email, reset_credits);
            }
        }
        Err(err) => ui::warn(&format!(
            "Could not retrieve quota for {}: {err:#}",
            target.email
        )),
    }
    Ok(NextSelection {
        target,
        changed,
        target_has_remaining_quota,
    })
}

async fn fetch_profile_quotas(
    store: &Store,
    profile_indices: &[usize],
    live: Option<&Credential>,
) -> Result<Vec<(usize, Result<quota::Snapshot>)>> {
    let client = match quota::Client::new(store.paths()) {
        Ok(client) => client,
        Err(err) => {
            let message = format!("{err:#}");
            return Ok(profile_indices
                .iter()
                .map(|index| (*index, Err(anyhow!(message.clone()))))
                .collect());
        }
    };
    let mut results = std::iter::repeat_with(|| None)
        .take(profile_indices.len())
        .collect::<Vec<Option<Result<quota::Snapshot>>>>();
    let mut tasks = tokio::task::JoinSet::new();
    for (slot, index) in profile_indices.iter().copied().enumerate() {
        let profile = &store.profiles()[index];
        let credential = match live {
            Some(credential) if credential.facts.account_id == profile.account_id => {
                Credential::from_bytes(credential.as_bytes().to_vec())?
            }
            _ => store.credential(profile)?,
        };
        let auth_file = store.profile_auth_path(profile);
        let client = client.clone();
        tasks.spawn(async move { (slot, client.fetch(credential, auth_file).await) });
    }
    while let Some(result) = tasks.join_next().await {
        let (slot, outcome) = result.context("a quota lookup task stopped unexpectedly")?;
        let profile_index = profile_indices[slot];
        persist_quota_credential(store, &store.profiles()[profile_index], &outcome)?;
        results[slot] = Some(outcome.snapshot);
    }
    Ok(profile_indices
        .iter()
        .copied()
        .zip(results.into_iter().map(|result| {
            result.expect("every quota result is set directly or by a completed task")
        }))
        .collect())
}

/// The quota worker already writes the canonical profile through the downstream auth manager.
/// Keep this hook as a consistency check, but never copy an outcome back over a newer canonical
/// credential after the app-server exits.
fn persist_quota_credential(
    store: &Store,
    profile: &Profile,
    outcome: &quota::Outcome,
) -> Result<()> {
    let current = store.credential(profile)?;
    if outcome.credential_changed() && outcome.source_matches(&current) {
        bail!(
            "Codex quota worker changed {} credentials without persisting the canonical profile",
            profile.email
        );
    }
    Ok(())
}

fn rotation_order(profile_count: usize, active_index: Option<usize>) -> Vec<usize> {
    if profile_count == 0 {
        return Vec::new();
    }
    match active_index {
        None => (0..profile_count).collect(),
        Some(active_index) if profile_count == 1 => vec![active_index],
        Some(active_index) => (1..profile_count)
            .map(|offset| (active_index + offset) % profile_count)
            .collect(),
    }
}

fn preferred_rotation_index(
    candidates: impl IntoIterator<Item = (usize, QuotaAvailability)>,
) -> Option<usize> {
    let mut first_resettable = None;
    let mut first_unknown = None;
    for (index, availability) in candidates {
        match availability {
            QuotaAvailability::Remaining => return Some(index),
            QuotaAvailability::Resettable => {
                first_resettable.get_or_insert(index);
            }
            QuotaAvailability::Unknown => {
                first_unknown.get_or_insert(index);
            }
            QuotaAvailability::Exhausted | QuotaAvailability::Unusable => {}
        }
    }
    first_resettable.or(first_unknown)
}

fn quota_result_availability(result: &Result<quota::Snapshot>) -> QuotaAvailability {
    match result {
        Ok(snapshot) if snapshot.remaining_percent > 0.0 => QuotaAvailability::Remaining,
        Ok(snapshot) if snapshot.rate_limit_reset_credits.is_some() => {
            QuotaAvailability::Resettable
        }
        Ok(_) => QuotaAvailability::Exhausted,
        Err(err) if quota::requires_authentication(err) => QuotaAvailability::Unusable,
        Err(_) => QuotaAvailability::Unknown,
    }
}

fn quota_check_summary(store: &Store, checks: &[(usize, Result<quota::Snapshot>)]) -> String {
    checks
        .iter()
        .map(|(index, result)| {
            let status = match result {
                Ok(snapshot) if snapshot.remaining_percent > 0.0 => "quota remaining".to_owned(),
                Ok(snapshot) if snapshot.rate_limit_reset_credits.is_some() => {
                    "reset credit available".to_owned()
                }
                Ok(_) => "quota exhausted".to_owned(),
                Err(err) if quota::requires_authentication(err) => {
                    format!("authentication failed: {err:#}")
                }
                Err(err) => format!("quota unavailable: {err:#}"),
            };
            format!("{} ({status})", store.profiles()[*index].email)
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn quota_status_availability(status: &QuotaStatus) -> QuotaAvailability {
    match status {
        QuotaStatus::Available { snapshot } if snapshot.remaining_percent > 0.0 => {
            QuotaAvailability::Remaining
        }
        QuotaStatus::Available { snapshot } if snapshot.rate_limit_reset_credits.is_some() => {
            QuotaAvailability::Resettable
        }
        QuotaStatus::Available { .. } => QuotaAvailability::Exhausted,
        QuotaStatus::Unavailable {
            authentication_required: true,
            ..
        } => QuotaAvailability::Unusable,
        QuotaStatus::Loading | QuotaStatus::Unavailable { .. } => QuotaAvailability::Unknown,
    }
}

fn cmd_activate(store: &mut Store, email: &str) -> Result<()> {
    validate_email(email)?;
    let target = store
        .find_profile(email)
        .with_context(|| format!("{email} is not enrolled; run `kai cred add` first"))?
        .clone();
    let changed = activate(store, &target)?;
    if changed {
        ui::success(&format!("Codex is now using {}.", target.email));
        warn_running_codex();
    } else {
        ui::success(&format!("{} is already active.", target.email));
    }
    Ok(())
}

async fn cmd_add(store: &mut Store, args: AddArgs) -> Result<()> {
    let live = load_live(store);
    // Preserve the existing signed-in account without forcing the user through another browser
    // login when it is not enrolled yet.  Once an account is already managed, a plain `add`
    // starts an isolated login so the user can select another account; `--force` then determines
    // whether a credential returned for an enrolled account may replace it.
    if let LiveAuth::Present(credential) = &live
        && managed_profile(store, credential).is_none()
        && store.find_profile(&credential.facts.email).is_none()
    {
        let profile = store.insert_profile(credential)?;
        store.activate_profile(&profile)?;
        ui::success(&format!(
            "Imported the active Codex account {}.",
            profile.email
        ));
        return Ok(());
    }

    // Only a currently managed account may be replaced automatically. Capture this before
    // inserting the new profile so enrollment cannot make an unrelated live credential appear
    // managed merely because it happens to share an account ID.
    let managed_account_before_add = match &live {
        LiveAuth::Present(credential) if managed_profile(store, credential).is_some() => {
            Some(credential.facts.account_id.clone())
        }
        _ => None,
    };

    if args.activate {
        ensure_live_can_be_replaced(store, &live)?;
    }

    // Plain enrollment trusts the email embedded in the credential file written by Codex.  The
    // repair paths used by `cred fix` and `--force` retain strict profile identity checks.
    let credential = enroll::run(store.paths(), args.auth.auth_preference())?;
    let enrolled_email = credential.facts.email.clone();
    if let Some(target) = store.find_profile(&enrolled_email).cloned() {
        if !args.force {
            bail!(
                "{enrolled_email} is already enrolled; rerun with `kai cred add --force` to reauthenticate it"
            );
        }
        return repair_profile_with_credential(store, &target, credential, args.activate);
    }
    if let Some(target) = store
        .find_profile_by_account(&credential.facts.account_id)
        .cloned()
    {
        if !args.force {
            bail!(
                "this Codex account is already enrolled as {}; rerun with `kai cred add --force` to reauthenticate it",
                target.email
            );
        }
        return repair_profile_with_credential(store, &target, credential, args.activate);
    }
    let profile = store.insert_profile(&credential)?;
    let active_for_quota = if !args.activate {
        match (managed_account_before_add.as_deref(), load_live(store)) {
            (Some(expected_account_id), LiveAuth::Present(active))
                if active.facts.account_id == expected_account_id =>
            {
                Some(active)
            }
            _ => None,
        }
    } else {
        None
    };
    let exhausted_active = if let Some(active) = active_for_quota {
        match fetch_credential_quota(store, &active).await {
            Ok(snapshot) if snapshot.remaining_percent <= 0.0 => Some(active.facts.email.clone()),
            Ok(_) => None,
            Err(err) => {
                ui::warn(&format!(
                    "Could not check whether {} has remaining quota; leaving it active: {err:#}",
                    active.facts.email
                ));
                None
            }
        }
    } else {
        None
    };
    let activate_after_add =
        args.activate || matches!(&live, LiveAuth::Absent) || exhausted_active.is_some();
    if activate_after_add {
        activate(store, &profile)?;
        if let Some(active_email) = exhausted_active {
            ui::success(&format!(
                "Enrolled and activated {} because {} has no remaining quota.",
                profile.email, active_email
            ));
        } else {
            ui::success(&format!("Enrolled and activated {}.", profile.email));
        }
        warn_running_codex();
    } else {
        ui::success(&format!("Enrolled {}.", profile.email));
        match live {
            LiveAuth::Present(active) if managed_profile(store, &active).is_some() => {
                ui::detail(&format!(
                    "{} remains active. Run `kai cred activate {}` when ready.",
                    active.facts.email, profile.email
                ))
            }
            LiveAuth::Present(active) => ui::detail(&format!(
                concat!(
                    "{} remains active but is not enrolled. Run `kai cred add` before switching ",
                    "so its latest refresh token is preserved.",
                ),
                active.facts.email
            )),
            LiveAuth::Invalid(_) => ui::detail(&format!(
                "Run `kai cred activate {}` after resolving the unreadable active Codex credential.",
                profile.email
            )),
            LiveAuth::Absent => unreachable!(),
        }
    }
    Ok(())
}

async fn cmd_fix(store: &mut Store, args: FixArgs) -> Result<()> {
    if store.profiles().is_empty() {
        bail!("no accounts are enrolled; run `kai cred add` first");
    }

    ui::stage("Checking enrolled account credentials");
    let live = load_live(store);
    let unreadable_active = if let LiveAuth::Invalid(err) = &live {
        ui::warn(&format!(
            "The active Codex credential is unreadable and cannot be matched to an enrolled account: {err:#}"
        ));
        Some(format!("{err:#}"))
    } else {
        None
    };
    let mut needs_repair = vec![false; store.profiles().len()];
    let mut indeterminate = 0;
    let mut check_indices = Vec::new();
    let active_profile = match &live {
        LiveAuth::Present(credential) => managed_profile(store, credential),
        LiveAuth::Absent | LiveAuth::Invalid(_) => None,
    };
    for (index, profile) in store.profiles().iter().enumerate() {
        let is_active_profile = active_profile.is_some_and(|active| active.id == profile.id);
        let structurally_valid = if is_active_profile {
            matches!(
                &live,
                LiveAuth::Present(credential)
                    if credential.facts.account_id == profile.account_id
                        && credential.matches_email(&profile.email)
            )
        } else {
            store.credential(profile).is_ok()
        };
        if structurally_valid {
            check_indices.push(index);
        } else {
            needs_repair[index] = true;
        }
    }
    let live_credential = match &live {
        LiveAuth::Present(credential) => Some(credential),
        LiveAuth::Absent | LiveAuth::Invalid(_) => None,
    };
    let checks = fetch_profile_quotas(store, &check_indices, live_credential).await?;
    for (index, result) in checks {
        if let Err(err) = result {
            if quota::requires_authentication(&err) {
                needs_repair[index] = true;
            } else {
                indeterminate += 1;
                ui::warn(&format!(
                    "Could not determine whether {} needs authentication repair: {err:#}",
                    store.profiles()[index].email
                ));
            }
        }
    }

    let targets = store
        .profiles()
        .iter()
        .zip(needs_repair)
        .filter(|(_, needs_repair)| *needs_repair)
        .map(|(profile, _)| profile.clone())
        .collect::<Vec<_>>();
    if targets.is_empty() {
        if indeterminate == 0 && unreadable_active.is_none() {
            ui::success("All enrolled account credentials appear usable.");
        } else {
            ui::detail("No credentials were repaired.");
        }
    } else {
        let noun = if targets.len() == 1 {
            "credential"
        } else {
            "credentials"
        };
        ui::detail(&format!("Repairing {} broken {noun}.", targets.len()));
        let preference = args.auth.auth_preference();
        for target in targets {
            confirm_fix_account(&target.email)?;
            repair_profile(store, &target, preference, false)?;
        }
    }
    if let Some(err) = unreadable_active {
        bail!(
            concat!(
                "the active Codex credential remains unreadable and cannot be repaired ",
                "automatically ({}); run `kai cred add --force --activate` for the ",
                "intended active account",
            ),
            err
        );
    }
    Ok(())
}

fn confirm_fix_account(email: &str) -> Result<()> {
    eprint!(
        "Press Enter to open sign-in for {email}; select this account in the browser (Ctrl-C to stop): "
    );
    io::stderr()
        .flush()
        .context("could not display the credential repair confirmation")?;

    let mut confirmation = String::new();
    let bytes_read = io::stdin()
        .read_line(&mut confirmation)
        .context("could not read the credential repair confirmation")?;
    if bytes_read == 0 {
        bail!("confirmation ended before sign-in started for {email}");
    }
    if !io::stdin().is_terminal() {
        eprintln!();
    }
    Ok(())
}

fn repair_profile(
    store: &mut Store,
    target: &Profile,
    auth_preference: enroll::AuthPreference,
    activate_target: bool,
) -> Result<()> {
    let live = load_live(store);
    let target_is_active = matches!(
        &live,
        LiveAuth::Present(credential) if credential.facts.account_id == target.account_id
    );
    if activate_target && !target_is_active {
        ensure_live_can_be_replaced(store, &live)?;
    }
    let credential = enroll::run_for_email(store.paths(), &target.email, auth_preference)?;
    repair_profile_with_credential(store, target, credential, activate_target)
}

fn repair_profile_with_credential(
    store: &mut Store,
    target: &Profile,
    credential: Credential,
    activate_target: bool,
) -> Result<()> {
    if credential.facts.account_id != target.account_id {
        bail!(
            concat!(
                "signed in as {}, but its account/workspace ID does not match the enrolled profile; ",
                "the new credential was discarded and no credentials were changed",
            ),
            credential.facts.email
        );
    }

    if !credential.matches_email(&target.email) {
        bail!(
            concat!(
                "signed in as {}, but the credential email does not match the enrolled profile ",
                "{}; the new credential was discarded and no credentials were changed",
            ),
            credential.facts.email,
            target.email
        );
    }

    let live = load_live(store);
    store.sync_profile(target, &credential)?;
    let target_is_active = matches!(
        &live,
        LiveAuth::Present(active)
            if active.facts.account_id == target.account_id
    );
    if target_is_active {
        ui::success(&format!(
            "Updated credentials for {} and refreshed the active Codex credential.",
            target.email
        ));
        warn_running_codex();
    } else if activate_target {
        activate(store, target)?;
        ui::success(&format!(
            "Updated credentials for {} and activated it.",
            target.email
        ));
        warn_running_codex();
    } else {
        ui::success(&format!("Updated credentials for {}.", target.email));
    }
    Ok(())
}

impl AuthFlowArgs {
    fn auth_preference(&self) -> enroll::AuthPreference {
        if self.device_auth {
            enroll::AuthPreference::Device
        } else if self.browser_auth {
            enroll::AuthPreference::Browser
        } else {
            enroll::AuthPreference::Auto
        }
    }
}

async fn fetch_credential_quota(store: &Store, credential: &Credential) -> Result<quota::Snapshot> {
    let index = store
        .profiles()
        .iter()
        .position(|profile| profile.account_id == credential.facts.account_id)
        .context("active credential is not enrolled and cannot be checked safely")?;
    fetch_profile_quotas(store, &[index], Some(credential))
        .await?
        .pop()
        .context("quota result disappeared")?
        .1
}

fn cmd_remove(store: &mut Store, args: RemoveArgs) -> Result<()> {
    validate_email(&args.email)?;
    let target = store
        .find_profile(&args.email)
        .with_context(|| format!("{} is not enrolled", args.email))?
        .clone();
    if !args.yes
        && !capulus::ui::prompt_confirm(
            &format!("Remove {} from Kai's credential vault?", target.email),
            false,
        )?
    {
        ui::detail("No changes made.");
        return Ok(());
    }

    let live = load_live(store);
    let active = match &live {
        LiveAuth::Present(credential) => managed_profile(store, credential),
        LiveAuth::Invalid(err) => {
            bail!(
                "cannot safely remove an account while the active Codex credential is unreadable: {err:#}"
            )
        }
        LiveAuth::Absent => None,
    };
    let target_is_active = active.is_some_and(|profile| profile.id == target.id);

    if target_is_active {
        if let Some(successor) = next_profile_excluding(store, &target) {
            let successor = successor.clone();
            activate(store, &successor)?;
            store.remove_profile(&target.id)?;
            ui::success(&format!(
                "Removed {}. Codex is now using {}.",
                target.email, successor.email
            ));
            warn_running_codex();
            return Ok(());
        }
        store.remove_active()?;
    }

    store.remove_profile(&target.id)?;
    ui::success(&format!("Removed {}.", target.email));
    if target_is_active {
        ui::detail("No accounts remain; Codex is locally signed out.");
    }
    Ok(())
}

fn activate(store: &mut Store, target: &Profile) -> Result<bool> {
    if let Some(live) = load_live_strict(store)? {
        let active = require_managed_profile(store, &live)?;
        if active.id == target.id {
            return Ok(false);
        }
    }
    install_profile(store, target)?;
    Ok(true)
}

fn install_profile(store: &Store, target: &Profile) -> Result<()> {
    store.activate_profile(target)?;
    let installed = store.credential(target)?;
    if installed.facts.account_id != target.account_id {
        bail!(
            "credential activation verification failed for {}",
            target.email
        );
    }
    Ok(())
}

fn restore_original_active(store: &Store, original: Option<&Profile>) -> Result<()> {
    match original {
        Some(profile) => install_profile(store, profile),
        None => store.remove_active(),
    }
}

fn load_live(store: &Store) -> LiveAuth {
    match fs::symlink_metadata(store.paths().active_auth()) {
        Ok(_) => match store.active_profile_path().and_then(|path| {
            let _lock = auth_lock::acquire(&path)?;
            Credential::read(&path)
        }) {
            Ok(credential) => LiveAuth::Present(credential),
            Err(err) => LiveAuth::Invalid(err),
        },
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => LiveAuth::Absent,
        Err(err) => LiveAuth::Invalid(err.into()),
    }
}

fn load_live_strict(store: &Store) -> Result<Option<Credential>> {
    match load_live(store) {
        LiveAuth::Absent => Ok(None),
        LiveAuth::Present(credential) => Ok(Some(credential)),
        LiveAuth::Invalid(err) => {
            Err(err).context("cannot safely replace the active Codex credential")
        }
    }
}

fn managed_profile<'a>(store: &'a Store, credential: &Credential) -> Option<&'a Profile> {
    store.find_profile_by_account(&credential.facts.account_id)
}

fn require_managed_profile<'a>(store: &'a Store, credential: &Credential) -> Result<&'a Profile> {
    if let Some(profile) = managed_profile(store, credential) {
        return Ok(profile);
    }
    if let Some(profile) = store.find_profile(&credential.facts.email) {
        bail!(
            concat!(
                "Codex is using {} with a different account/workspace ID than the enrolled ",
                "profile; remove and re-enroll it before switching",
            ),
            profile.email
        );
    }
    bail!(
        concat!(
            "Codex is using {}, which is not enrolled. Run `kai cred add` before switching ",
            "so its latest refresh token is preserved",
        ),
        credential.facts.email,
    )
}

fn ensure_live_can_be_replaced(store: &Store, live: &LiveAuth) -> Result<()> {
    match live {
        LiveAuth::Absent => Ok(()),
        LiveAuth::Present(credential) => {
            require_managed_profile(store, credential)?;
            Ok(())
        }
        LiveAuth::Invalid(err) => bail!(
            "cannot activate a new account while the active Codex credential is unreadable: {err:#}"
        ),
    }
}

fn next_profile_excluding<'a>(store: &'a Store, removed: &Profile) -> Option<&'a Profile> {
    if store.profiles().len() <= 1 {
        return None;
    }
    let index = store
        .profiles()
        .iter()
        .position(|profile| profile.id == removed.id)?;
    store.profiles().get((index + 1) % store.profiles().len())
}

fn warn_running_codex() {
    if let Some(count) = running_codex_process_count()
        && count > 0
    {
        let noun = if count == 1 { "process" } else { "processes" };
        ui::warn(&format!(
            concat!(
                "{} running Codex {} may still hold the previous credential in memory; ",
                "restart them before continuing work.",
            ),
            count, noun,
        ));
    }
}

#[cfg(target_os = "linux")]
fn running_codex_process_count() -> Option<usize> {
    let current = std::process::id();
    let entries = fs::read_dir("/proc").ok()?;
    Some(
        entries
            .filter_map(Result::ok)
            .filter_map(|entry| entry.file_name().to_string_lossy().parse::<u32>().ok())
            .filter(|pid| *pid != current)
            .filter(|pid| {
                fs::read_to_string(format!("/proc/{pid}/comm"))
                    .is_ok_and(|name| name.trim() == "codex")
            })
            .count(),
    )
}

#[cfg(not(target_os = "linux"))]
fn running_codex_process_count() -> Option<usize> {
    None
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::auth::tests::auth_json;
    use super::*;

    fn setup() -> (tempfile::TempDir, Store) {
        let root = tempdir().unwrap();
        let paths =
            RuntimePaths::new(root.path().join("credentials"), root.path().join("codex")).unwrap();
        let store = Store::open(paths).unwrap();
        (root, store)
    }

    fn credential(email: &str, account: &str, refresh: &str) -> Credential {
        Credential::from_bytes(auth_json(email, account, "pro", 2_000_000_000, refresh)).unwrap()
    }

    #[test]
    fn supervised_sqlite_home_matches_codex_environment_resolution() {
        let root = tempdir().unwrap();
        let cwd = root.path().join("workspace");
        let codex_home = root.path().join("codex");
        let shared_home = root.path().join("shared-state");

        assert_eq!(
            resolve_sqlite_home(&cwd, &codex_home, Some(" state ")),
            cwd.join("state")
        );
        assert_eq!(
            resolve_sqlite_home(
                &cwd,
                &codex_home,
                Some(&format!(" {} ", shared_home.display())),
            ),
            shared_home
        );
        assert_eq!(
            resolve_sqlite_home(&cwd, &codex_home, Some("  ")),
            codex_home
        );
        assert_eq!(resolve_sqlite_home(&cwd, &codex_home, None), codex_home);
    }

    #[test]
    fn switching_reuses_the_canonical_profile_without_reconciliation() {
        let (_root, mut store) = setup();
        let alice = store
            .insert_profile(&credential("alice@example.com", "alice-id", "alice-old"))
            .unwrap();
        let bob = store
            .insert_profile(&credential("bob@example.com", "bob-id", "bob-token"))
            .unwrap();
        store.activate_profile(&alice).unwrap();
        store
            .write_active(&credential("alice@example.com", "alice-id", "alice-new"))
            .unwrap();

        assert!(activate(&mut store, &bob).unwrap());
        assert_eq!(
            store.credential(&alice).unwrap().as_bytes(),
            auth_json(
                "alice@example.com",
                "alice-id",
                "pro",
                2_000_000_000,
                "alice-new"
            )
        );
        assert!(activate(&mut store, &alice).unwrap());
        assert_eq!(
            Credential::read(&store.active_profile_path().unwrap())
                .unwrap()
                .facts
                .account_id,
            "alice-id"
        );
    }

    #[test]
    fn supervised_recovery_uses_the_profile_as_its_canonical_auth_file() {
        let (_root, mut store) = setup();
        let alice = store
            .insert_profile(&credential("alice@example.com", "alice-id", "alice-source"))
            .unwrap();
        assert!(activate(&mut store, &alice).unwrap());

        assert_eq!(
            store.active_profile_path().unwrap(),
            store.profile_auth_path(&alice)
        );
        let refreshed = credential("alice@example.com", "alice-id", "alice-refreshed");
        store.sync_profile(&alice, &refreshed).unwrap();
        assert_eq!(
            Credential::read(&store.active_profile_path().unwrap())
                .unwrap()
                .as_bytes(),
            refreshed.as_bytes()
        );
    }

    #[test]
    fn switching_refuses_to_overwrite_an_unenrolled_live_account() {
        let (_root, mut store) = setup();
        let bob = store
            .insert_profile(&credential("bob@example.com", "bob-id", "bob-token"))
            .unwrap();
        store
            .write_active(&credential(
                "outside@example.com",
                "outside-id",
                "outside-token",
            ))
            .unwrap();

        let error = activate(&mut store, &bob).unwrap_err();

        assert!(format!("{error:#}").contains("not enrolled"));
        assert_eq!(
            Credential::read(&store.active_profile_path().unwrap())
                .unwrap()
                .facts
                .account_id,
            "outside-id"
        );
    }

    #[test]
    fn rotation_order_starts_after_the_active_account_and_wraps() {
        assert_eq!(rotation_order(0, None), Vec::<usize>::new());
        assert_eq!(rotation_order(3, None), vec![0, 1, 2]);
        assert_eq!(rotation_order(3, Some(1)), vec![2, 0]);
        assert_eq!(rotation_order(1, Some(0)), vec![0]);
    }

    #[test]
    fn supervised_rotation_classifies_only_no_usable_quota() {
        assert_eq!(
            classify_account_rotation(Err(NoUsableQuota("none available".to_owned()).into()))
                .unwrap(),
            AccountRotation::NoQuota("none available".to_owned())
        );

        let error =
            classify_account_rotation(Err(anyhow!("could not read auth.json"))).unwrap_err();
        assert_eq!(error.to_string(), "could not read auth.json");
    }

    #[test]
    fn rotation_skips_exhausted_accounts_and_prefers_confirmed_capacity() {
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Exhausted),
                (2, QuotaAvailability::Remaining),
            ]),
            Some(2)
        );
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Unknown),
                (2, QuotaAvailability::Remaining),
            ]),
            Some(2)
        );
    }

    #[test]
    fn rotation_uses_reset_credits_after_remaining_quota_but_before_unknown_quota() {
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Resettable),
                (2, QuotaAvailability::Remaining),
            ]),
            Some(2)
        );
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Unknown),
                (2, QuotaAvailability::Resettable),
            ]),
            Some(2)
        );
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Unusable),
                (2, QuotaAvailability::Exhausted),
            ]),
            None
        );
    }

    #[test]
    fn rotation_falls_back_to_unknown_quota_but_never_to_known_exhaustion() {
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Exhausted),
                (2, QuotaAvailability::Unknown),
                (3, QuotaAvailability::Unknown),
            ]),
            Some(2)
        );
        assert_eq!(
            preferred_rotation_index([
                (1, QuotaAvailability::Exhausted),
                (2, QuotaAvailability::Exhausted),
            ]),
            None
        );
    }

    #[test]
    fn removing_the_active_profile_activates_its_successor() {
        let (_root, mut store) = setup();
        let alice = store
            .insert_profile(&credential("alice@example.com", "alice-id", "alice-token"))
            .unwrap();
        store
            .insert_profile(&credential("bob@example.com", "bob-id", "bob-token"))
            .unwrap();
        store
            .write_active(&credential("alice@example.com", "alice-id", "alice-live"))
            .unwrap();

        cmd_remove(
            &mut store,
            RemoveArgs {
                email: alice.email,
                yes: true,
            },
        )
        .unwrap();

        assert_eq!(store.profiles().len(), 1);
        assert_eq!(store.profiles()[0].email, "bob@example.com");
        assert_eq!(
            Credential::read(&store.active_profile_path().unwrap())
                .unwrap()
                .facts
                .account_id,
            "bob-id"
        );
    }
}