synaps-core 0.11.0

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

use super::account::{Account, AccountSummary, CredentialRef};
use super::provider::OAuthProviderId;
use super::{AuthFile, OAuthCredentials};

/// Get the path to auth.json (~/.synaps-cli/auth.json).
pub fn auth_file_path() -> PathBuf {
    crate::config::resolve_read_path("auth.json")
}

/// Load credentials from auth.json.
pub fn load_auth() -> std::result::Result<Option<AuthFile>, String> {
    let path = auth_file_path();
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let auth: AuthFile = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    Ok(Some(auth))
}

/// Load one provider's OAuth credential from auth.json.
///
/// `provider` is a storage key: the bare provider id for the default account
/// or `<provider>@<label>` for a named account (see [`CredentialRef`]).
pub fn load_provider_auth(provider: &str) -> std::result::Result<Option<OAuthCredentials>, String> {
    load_provider_auth_at(&auth_file_path(), provider)
}

pub(crate) fn load_provider_auth_at(
    path: &Path,
    provider: &str,
) -> std::result::Result<Option<OAuthCredentials>, String> {
    load_provider_auth_typed_at(path, provider).map_err(String::from)
}

/// [`load_provider_auth_at`] that reports an unparseable store as
/// [`StoreError::Corrupt`].
pub(crate) fn load_provider_auth_typed_at(
    path: &Path,
    provider: &str,
) -> std::result::Result<Option<OAuthCredentials>, StoreError> {
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let value: serde_json::Value =
        serde_json::from_str(&content).map_err(|e| corrupt_store(path, &e))?;
    let Some(raw) = value.get(provider) else {
        return Ok(None);
    };
    let creds: OAuthCredentials = serde_json::from_value(raw.clone())
        .map_err(|e| format!("Failed to parse {} credential: {}", provider, e))?;
    Ok(Some(creds))
}

// ── Account-addressed API (additive; bare keys are the `default` account) ────

/// Load the credential stored in one account slot.
pub fn load_credential(
    cred: &CredentialRef,
) -> std::result::Result<Option<OAuthCredentials>, String> {
    load_provider_auth(&cred.storage_key())
}

/// Persist a credential into exactly one account slot. Other slots (including
/// the provider's default slot) and any non-secret metadata already stored in
/// this slot are preserved. A corrupt store is an error — the account path
/// never resets the file (that would wipe every other slot); the legacy
/// single-credential [`save_provider_auth`] resets only an empty file.
pub fn save_credential(
    cred: &CredentialRef,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    save_credential_at(&path, cred, creds)
}

pub(crate) fn save_credential_at(
    path: &Path,
    cred: &CredentialRef,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    let encoded =
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?;
    let fields = encoded
        .as_object()
        .cloned()
        .ok_or_else(|| "credential did not serialize to an object".to_string())?;
    let key = cred.storage_key();
    with_locked_root(path, false, |root| {
        let mut slot = root
            .remove(&key)
            .filter(serde_json::Value::is_object)
            .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
        if let Some(target) = slot.as_object_mut() {
            for (k, v) in &fields {
                target.insert(k.clone(), v.clone());
            }
        }
        root.insert(key.clone(), slot);
        Ok((true, ()))
    })
}

/// Remove one account slot. Returns `true` if a key was removed. Never leaves
/// a partial file and never touches any other key. A corrupt file is an error
/// (nothing is reset on a removal path).
///
/// Profiles: listings and loads read through [`auth_file_path`], which falls
/// back to the base `auth.json` when the active profile has none. Removal
/// refuses to act on such an *inherited* file rather than silently
/// "succeeding" against an empty profile file or deleting from the base
/// store on the profile's behalf.
pub fn remove_credential(cred: &CredentialRef) -> std::result::Result<bool, String> {
    let read_path = auth_file_path();
    let write_path = crate::config::resolve_write_path("auth.json");
    if read_path != write_path {
        return Err(format!(
            "{} is stored in {} which the active profile inherits; re-run without --profile \
             (or with the profile that owns that file) to remove it",
            cred,
            read_path.display()
        ));
    }
    remove_key_at(&write_path, &cred.storage_key())
}

pub(crate) fn remove_key_at(path: &Path, key: &str) -> std::result::Result<bool, String> {
    // NOTE: the per-credential refresh lock file (`<auth>.<key>.refresh.lock`)
    // is deliberately NOT unlinked here: unlinking a lock file another
    // process may hold defeats flock (a re-created file is a new inode).
    // The parked-refresh sidecar IS removed: it is a regular file holding a
    // live refresh token for the account being removed.
    let removed = if path.exists() {
        with_locked_root(path, false, |root| {
            let removed = root.remove(key).is_some();
            Ok((removed, removed))
        })?
    } else {
        false
    };
    let _ = std::fs::remove_file(refresh_pending_path(path, key));
    Ok(removed)
}

/// `<auth>.<key>.refresh.pending`: a rotation whose save failed, parked
/// beside the account's refresh lock (see `token.rs`).
pub(crate) fn refresh_pending_path(auth_path: &Path, key: &str) -> PathBuf {
    let file_name = auth_path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("auth.json");
    auth_path.with_file_name(format!("{file_name}.{key}.refresh.pending"))
}

/// Non-secret metadata stored beside a credential (`label`, `identity`,
/// `addedAt`). Kept separate from [`OAuthCredentials`] so refresh writes,
/// which only carry token fields, never clobber it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountMetadata {
    /// Display-only provider identity (e.g. an email claim). Never a secret.
    pub identity: Option<String>,
    /// Epoch seconds when the slot was created.
    pub added_at: Option<u64>,
}

/// Merge non-secret metadata into an account slot (which must already exist).
pub fn save_account_metadata(
    cred: &CredentialRef,
    metadata: &AccountMetadata,
) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    save_account_metadata_at(&path, cred, metadata)
}

pub(crate) fn save_account_metadata_at(
    path: &Path,
    cred: &CredentialRef,
    metadata: &AccountMetadata,
) -> std::result::Result<(), String> {
    let key = cred.storage_key();
    with_locked_root(path, false, |root| {
        let Some(entry) = root.get_mut(&key).and_then(serde_json::Value::as_object_mut) else {
            return Err(format!("no credential stored for {key}"));
        };
        match &cred.account {
            Account::Default => {
                entry.remove("label");
            }
            Account::Named(label) => {
                entry.insert("label".into(), serde_json::Value::String(label.as_str().into()));
            }
        }
        match &metadata.identity {
            Some(identity) if !identity.trim().is_empty() => {
                entry.insert(
                    "identity".into(),
                    serde_json::Value::String(identity.trim().to_string()),
                );
            }
            _ => {}
        }
        if let Some(added_at) = metadata.added_at {
            entry.insert("addedAt".into(), serde_json::Value::from(added_at));
        }
        Ok((true, ()))
    })
}

/// Record the provider seat identity on an EXISTING OAuth slot: sets
/// `accountId` (the full provider account id) and, when given, the display
/// `identity`. Used by the `auth identify` backfill for slots whose login
/// predates identity acquisition (Anthropic tokens are opaque; the seat
/// comes from the profile endpoint after the fact).
///
/// Touches no other field — a `refresh`/`access` rotated by another process
/// between the caller's read and this write is never clobbered, because the
/// write happens under the store lock and only inserts the two identity
/// keys into the entry read under that same lock. A missing slot, a
/// non-OAuth entry, or an empty `account_id` is an error and writes nothing.
///
/// Profiles: like [`remove_credential`], this refuses to act on an auth.json
/// the active profile merely inherits.
pub fn set_slot_identity(
    cred: &CredentialRef,
    account_id: &str,
    identity: Option<&str>,
) -> std::result::Result<(), String> {
    let read_path = auth_file_path();
    let write_path = crate::config::resolve_write_path("auth.json");
    if read_path != write_path {
        return Err(format!(
            "{} is stored in {} which the active profile inherits; re-run without --profile \
             (or with the profile that owns that file) to record its identity",
            cred,
            read_path.display()
        ));
    }
    set_slot_identity_at(&write_path, cred, account_id, identity)
}

pub(crate) fn set_slot_identity_at(
    path: &Path,
    cred: &CredentialRef,
    account_id: &str,
    identity: Option<&str>,
) -> std::result::Result<(), String> {
    let account_id = account_id.trim();
    if account_id.is_empty() {
        return Err("account id is empty; nothing recorded".into());
    }
    let key = cred.storage_key();
    if !path.exists() {
        return Err(format!("no credential stored for {key}"));
    }
    let identity = identity.map(str::trim).filter(|s| !s.is_empty());
    with_locked_root(path, false, |root| {
        let Some(entry) = root
            .get_mut(&key)
            .and_then(serde_json::Value::as_object_mut)
        else {
            return Err(format!("no credential stored for {key}"));
        };
        if entry.get("type").and_then(|t| t.as_str()) != Some("oauth") {
            return Err(format!(
                "{key} is not an OAuth credential; nothing recorded"
            ));
        }
        entry.insert(
            "accountId".into(),
            serde_json::Value::String(account_id.to_string()),
        );
        if let Some(identity) = identity {
            entry.insert(
                "identity".into(),
                serde_json::Value::String(identity.to_string()),
            );
        }
        Ok((true, ()))
    })
}

/// Outcome of a compare-and-swap credential write (refresh rotation).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CasOutcome {
    /// The stored refresh token matched; the rotated credential was written.
    Saved,
    /// The slot no longer exists (removed while the refresh was in flight).
    Removed,
    /// The slot now holds a different credential (re-login while the refresh
    /// was in flight). Nothing was written.
    Replaced,
    /// The credential file itself is gone (e.g. moved aside by the user).
    /// Nothing was written.
    StoreMissing,
}

/// Write a rotated credential only if the slot still holds the credential
/// the rotation started from (identified by its refresh token). Preserves
/// metadata and, when the rotated credential omits `accountId`, the stored
/// one. Used by the refresh path so a concurrent removal or re-login is never
/// overwritten by a stale rotation.
#[cfg(test)]
pub(crate) fn save_provider_auth_if_refresh_matches_at(
    path: &Path,
    key: &str,
    expected_refresh: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<CasOutcome, String> {
    save_provider_auth_if_refresh_matches_typed_at(path, key, expected_refresh, creds, STORE_LOCK_WAIT)
        .map_err(String::from)
}

/// [`save_provider_auth_if_refresh_matches_at`] that tells a busy store
/// lock apart from other failures. `wait` bounds the `auth.json.lock` wait.
pub(crate) fn save_provider_auth_if_refresh_matches_typed_at(
    path: &Path,
    key: &str,
    expected_refresh: &str,
    creds: &OAuthCredentials,
    wait: std::time::Duration,
) -> std::result::Result<CasOutcome, StoreError> {
    let encoded =
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?;
    let fields = encoded
        .as_object()
        .cloned()
        .ok_or_else(|| "credential did not serialize to an object".to_string())?;
    if !path.exists() {
        return Ok(CasOutcome::StoreMissing);
    }
    with_locked_root_typed(path, false, wait, |root| {
        let Some(entry) = root.get_mut(key).and_then(serde_json::Value::as_object_mut) else {
            return Ok((false, CasOutcome::Removed));
        };
        let stored_refresh = entry.get("refresh").and_then(|v| v.as_str()).unwrap_or("");
        if stored_refresh != expected_refresh {
            return Ok((false, CasOutcome::Replaced));
        }
        for (k, v) in &fields {
            entry.insert(k.clone(), v.clone());
        }
        Ok((true, CasOutcome::Saved))
    })
}

/// Listing of one provider's stored accounts plus any sibling keys that look
/// like accounts of this provider but fail validation (never loaded).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountInventory {
    pub accounts: Vec<AccountSummary>,
    pub malformed_keys: Vec<String>,
    /// Storage keys of slots that share a provider `accountId` with another
    /// slot of the same provider (two refresh owners for one seat).
    pub duplicate_identity_keys: Vec<String>,
}

/// Enumerate stored OAuth accounts for `provider` (non-secret rows;
/// `selected` is left `false` for the caller to annotate).
pub fn list_accounts(provider: OAuthProviderId) -> std::result::Result<Vec<AccountSummary>, String> {
    Ok(list_accounts_detailed_at(&auth_file_path(), Some(provider))?.accounts)
}

/// Enumerate stored OAuth accounts for every provider.
pub fn list_all_accounts() -> std::result::Result<Vec<AccountSummary>, String> {
    Ok(list_accounts_detailed_at(&auth_file_path(), None)?.accounts)
}

/// Enumerate with malformed-key diagnostics (for `auth list`).
pub fn list_accounts_detailed(
    provider: Option<OAuthProviderId>,
) -> std::result::Result<AccountInventory, String> {
    list_accounts_detailed_at(&auth_file_path(), provider)
}

pub(crate) fn list_accounts_detailed_at(
    path: &Path,
    provider: Option<OAuthProviderId>,
) -> std::result::Result<AccountInventory, String> {
    let mut inventory = AccountInventory::default();
    if !path.exists() {
        return Ok(inventory);
    }
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let root: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    for (key, entry) in &root {
        let belongs = match provider {
            Some(p) => CredentialRef::key_belongs_to(key, p),
            None => super::provider::DESCRIPTORS
                .iter()
                .any(|d| CredentialRef::key_belongs_to(key, d.id)),
        };
        if !belongs {
            continue;
        }
        let Some(cred) = CredentialRef::parse_storage_key(key) else {
            tracing::warn!(key_len = key.len(), "ignoring malformed account key in auth.json");
            inventory.malformed_keys.push(display_key(key));
            continue;
        };
        let Some(obj) = entry.as_object() else {
            inventory.malformed_keys.push(display_key(key));
            continue;
        };
        if obj.get("type").and_then(|t| t.as_str()) != Some("oauth") {
            // Bare provider keys may legitimately hold non-OAuth state; only
            // OAuth entries are accounts.
            continue;
        }
        // An OAuth entry is only "configured" when it actually carries token
        // material (same rule as `oauth_provider_logged_in`). Entries with
        // missing/non-string tokens are reported by KEY ONLY — never values.
        let token_present = |field: &str| {
            obj.get(field)
                .and_then(|v| v.as_str())
                .is_some_and(|v| !v.is_empty())
        };
        let tokens_typed = ["access", "refresh"]
            .iter()
            .all(|f| matches!(obj.get(*f), None | Some(serde_json::Value::String(_))));
        if !tokens_typed || !(token_present("access") || token_present("refresh")) {
            tracing::warn!(key_len = key.len(), "oauth entry without usable token fields");
            inventory.malformed_keys.push(display_key(key));
            continue;
        }
        inventory.accounts.push(AccountSummary {
            identity: obj
                .get("identity")
                .and_then(|v| v.as_str())
                .filter(|s| !s.trim().is_empty())
                .map(|s| s.trim().to_string()),
            expires: obj.get("expires").and_then(|v| v.as_u64()).unwrap_or(0),
            added_at: obj.get("addedAt").and_then(|v| v.as_u64()),
            ..AccountSummary::new(cred.provider, &cred.account)
                .with_account_id(obj.get("accountId").and_then(|v| v.as_str()))
        });
    }
    inventory
        .accounts
        .sort_by(|a, b| (&a.provider, a.label != "default", &a.label).cmp(&(&b.provider, b.label != "default", &b.label)));
    // Duplicate seats: same provider + same full accountId in two slots.
    let mut seen: std::collections::BTreeMap<(String, String), Vec<String>> =
        std::collections::BTreeMap::new();
    for (key, entry) in &root {
        let Some(cred) = CredentialRef::parse_storage_key(key) else {
            continue;
        };
        if let Some(id) = entry
            .get("accountId")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
        {
            if provider.is_none_or(|p| p == cred.provider) {
                seen.entry((cred.provider.as_str().to_string(), id.to_string()))
                    .or_default()
                    .push(key.clone());
            }
        }
    }
    for keys in seen.into_values() {
        if keys.len() > 1 {
            inventory.duplicate_identity_keys.extend(keys);
        }
    }
    inventory.duplicate_identity_keys.sort();
    Ok(inventory)
}

/// Bounded key text for diagnostics (keys are labels, never token material,
/// but a hand-edited file could put anything there).
fn display_key(key: &str) -> String {
    crate::truncate_str(key, 64).to_string()
}

/// True if auth.json holds at least one OAuth credential of ANY provider or
/// account. Used for broker startup/health so non-Anthropic-only
/// installations work.
pub fn any_oauth_credential_present() -> std::result::Result<bool, String> {
    any_oauth_credential_present_at(&auth_file_path())
}

pub(crate) fn any_oauth_credential_present_at(path: &Path) -> std::result::Result<bool, String> {
    Ok(!list_accounts_detailed_at(path, None)?.accounts.is_empty())
}

/// What the duplicate-identity guard could establish for a new login.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IdentityEvidence {
    /// The provider exposes no trustworthy identity for this credential, so
    /// a duplicate seat under another label CANNOT be detected.
    NoEvidence,
    /// Identity known; no other slot of this provider holds the same seat.
    NoDuplicate,
    /// Another slot of this provider already holds this seat.
    Duplicate(Account),
}

/// Outcome of [`save_credential_unless_duplicate`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoginPersistOutcome {
    pub evidence: IdentityEvidence,
    /// False iff a duplicate was found (nothing was written).
    pub saved: bool,
}

/// Login persistence: duplicate scan and write happen inside ONE locked
/// read-modify-write of auth.json, so two concurrent logins (or a login
/// racing a remove/re-login) can never create two slots owning the same
/// seat. A duplicate is another slot of the same provider with the same
/// non-empty `accountId`, or with an identical refresh token.
///
/// Metadata is rewritten atomically with the credential: `label` follows the
/// slot, `identity` is set or CLEARED (a re-login with a different seat never
/// keeps the old identity), `addedAt` is set to `metadata.added_at`.
///
/// A corrupt store is an error (never reset: that would wipe every other
/// slot). With an active profile that has no own auth.json while the base
/// store exists, the write is REFUSED: creating a profile file would hide
/// every inherited account from that profile, and tokens are never copied.
pub fn save_credential_unless_duplicate(
    cred: &CredentialRef,
    creds: &OAuthCredentials,
    metadata: &AccountMetadata,
) -> std::result::Result<LoginPersistOutcome, String> {
    let read_path = auth_file_path();
    let write_path = crate::config::resolve_write_path("auth.json");
    if read_path != write_path && read_path.exists() {
        return Err(format!(
            "the active profile has no auth.json of its own and inherits {}; logging in here would \
             create a profile store that hides every inherited account (tokens are never copied). \
             Re-run without --profile to add the account to the shared store.",
            read_path.display()
        ));
    }
    save_credential_unless_duplicate_at(&write_path, cred, creds, metadata)
}

pub(crate) fn save_credential_unless_duplicate_at(
    path: &Path,
    cred: &CredentialRef,
    creds: &OAuthCredentials,
    metadata: &AccountMetadata,
) -> std::result::Result<LoginPersistOutcome, String> {
    let encoded =
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?;
    let fields = encoded
        .as_object()
        .cloned()
        .ok_or_else(|| "credential did not serialize to an object".to_string())?;
    let key = cred.storage_key();
    let account_id = creds
        .account_id
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty());
    with_locked_root(path, false, |root| {
        // Scan sibling slots of the same provider under the lock.
        let mut duplicate: Option<Account> = None;
        for (other_key, entry) in root.iter() {
            if other_key == &key {
                continue;
            }
            let Some(other) = CredentialRef::parse_storage_key(other_key) else {
                continue;
            };
            if other.provider != cred.provider {
                continue;
            }
            let stored_id = entry
                .get("accountId")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .unwrap_or("");
            let stored_refresh = entry.get("refresh").and_then(|v| v.as_str()).unwrap_or("");
            let same_seat = account_id.is_some_and(|id| id == stored_id)
                || (!creds.refresh.is_empty() && creds.refresh == stored_refresh);
            if same_seat {
                duplicate = Some(other.account);
                break;
            }
        }
        if let Some(account) = duplicate {
            return Ok((
                false,
                LoginPersistOutcome {
                    evidence: IdentityEvidence::Duplicate(account),
                    saved: false,
                },
            ));
        }
        let mut slot = root
            .remove(&key)
            .filter(serde_json::Value::is_object)
            .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
        if let Some(target) = slot.as_object_mut() {
            for (k, v) in &fields {
                target.insert(k.clone(), v.clone());
            }
            if account_id.is_none() {
                // The new credential carries no identity: never keep a stale
                // one from a previous login into this slot.
                target.remove("accountId");
            }
            match &cred.account {
                Account::Default => {
                    target.remove("label");
                }
                Account::Named(label) => {
                    target.insert("label".into(), serde_json::Value::String(label.as_str().into()));
                }
            }
            match metadata.identity.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
                Some(identity) => {
                    target.insert("identity".into(), serde_json::Value::String(identity.into()));
                }
                None => {
                    target.remove("identity");
                }
            }
            match metadata.added_at {
                Some(added_at) => {
                    target.insert("addedAt".into(), serde_json::Value::from(added_at));
                }
                None => {
                    target.remove("addedAt");
                }
            }
        }
        root.insert(key.clone(), slot);
        Ok((
            true,
            LoginPersistOutcome {
                evidence: if account_id.is_some() {
                    IdentityEvidence::NoDuplicate
                } else {
                    IdentityEvidence::NoEvidence
                },
                saved: true,
            },
        ))
    })
}

/// Duplicate-identity guard for login: returns the account (of the same
/// provider, other than `except`) that already stores `account_id`.
pub fn find_duplicate_identity(
    provider: OAuthProviderId,
    account_id: &str,
    except: &Account,
) -> std::result::Result<Option<Account>, String> {
    find_duplicate_identity_at(&auth_file_path(), provider, account_id, except)
}

pub(crate) fn find_duplicate_identity_at(
    path: &Path,
    provider: OAuthProviderId,
    account_id: &str,
    except: &Account,
) -> std::result::Result<Option<Account>, String> {
    let account_id = account_id.trim();
    if account_id.is_empty() || !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let root: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    for (key, entry) in &root {
        let Some(cred) = CredentialRef::parse_storage_key(key) else {
            continue;
        };
        if cred.provider != provider || &cred.account == except {
            continue;
        }
        let stored = entry
            .get("accountId")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .unwrap_or("");
        if !stored.is_empty() && stored == account_id {
            return Ok(Some(cred.account));
        }
    }
    Ok(None)
}

/// Save credentials to auth.json.
pub fn save_auth(creds: &OAuthCredentials) -> std::result::Result<(), String> {
    save_provider_auth("anthropic", creds)
}

/// Save one provider credential while preserving other auth.json entries.
pub fn save_provider_auth(
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    save_provider_auth_at(&path, provider, creds)
}

/// Load an opaque broker-owned cloud provider state object.
pub fn load_cloud_state(provider: &str) -> std::result::Result<Option<serde_json::Value>, String> {
    let path = auth_file_path();
    if !path.exists() {
        return Ok(None);
    }
    let root: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(&path)
            .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?,
    )
    .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    Ok(root
        .get(provider)
        .and_then(|v| v.get("cloud_state"))
        .cloned())
}

/// Atomically persist opaque cloud state while preserving every unrelated field.
pub fn save_cloud_state(
    provider: &str,
    state: &serde_json::Value,
) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    let mut fields = serde_json::Map::new();
    fields.insert("type".into(), serde_json::Value::String("cloud".into()));
    fields.insert("cloud_state".into(), state.clone());
    save_provider_fields_at(&path, provider, &fields)
}

/// Load one provider's broker-owned static API key from auth.json.
///
/// Static keys are persisted as `{"type":"api_key","key":"…"}` entries in the
/// same open JSON object as OAuth credentials, so unknown providers and
/// provider metadata round-trip through the exact same merge writer.
pub fn load_static_key(provider: &str) -> std::result::Result<Option<String>, String> {
    load_static_key_at(&auth_file_path(), provider)
}

pub(crate) fn load_static_key_at(
    path: &std::path::Path,
    provider: &str,
) -> std::result::Result<Option<String>, String> {
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?;
    let Some(entry) = value.get(provider) else {
        return Ok(None);
    };
    if entry.get("type").and_then(|t| t.as_str()) != Some("api_key") {
        return Ok(None);
    }
    Ok(entry
        .get("key")
        .and_then(|k| k.as_str())
        .filter(|k| !k.is_empty())
        .map(str::to_string))
}

/// Persist a broker-owned static API key while preserving every other
/// auth.json entry and any provider metadata.
pub fn save_static_key(provider: &str, key: &str) -> std::result::Result<(), String> {
    let path = crate::config::resolve_write_path("auth.json");
    save_static_key_at(&path, provider, key)
}

pub(crate) fn save_static_key_at(
    path: &std::path::Path,
    provider: &str,
    key: &str,
) -> std::result::Result<(), String> {
    let mut fields = serde_json::Map::new();
    fields.insert(
        "type".to_string(),
        serde_json::Value::String("api_key".to_string()),
    );
    fields.insert(
        "key".to_string(),
        serde_json::Value::String(key.to_string()),
    );
    save_provider_fields_at(path, provider, &fields)
}

/// Path-explicit variant of `save_provider_auth`. Splits out the I/O so
/// the corrupt-file fallback path can be unit-tested without touching the
/// user's real `~/.synaps-cli/auth.json`.
/// [`save_provider_auth`] that reports a corrupt store as
/// [`StoreError::Corrupt`] (provider logins with typed errors).
pub(crate) fn save_provider_auth_typed(
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), StoreError> {
    let path = crate::config::resolve_write_path("auth.json");
    save_provider_auth_typed_at(&path, provider, creds)
}

pub(crate) fn save_provider_auth_typed_at(
    path: &std::path::Path,
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), StoreError> {
    let encoded =
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?;
    let fields = encoded
        .as_object()
        .ok_or_else(|| "credential did not serialize to an object".to_string())?;
    with_locked_root_typed(path, true, STORE_LOCK_WAIT, |root| {
        merge_provider_fields(root, provider, fields);
        Ok((true, ()))
    })
}

pub(crate) fn save_provider_auth_at(
    path: &std::path::Path,
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    let encoded =
        serde_json::to_value(creds).map_err(|e| format!("Failed to serialize auth: {}", e))?;
    let fields = encoded
        .as_object()
        .ok_or_else(|| "credential did not serialize to an object".to_string())?;
    save_provider_fields_at(path, provider, fields)
}

/// Shared merge writer: lock, read-merge every provider entry, merge `fields`
/// into the one provider object (preserving unknown metadata), atomic rename.
fn save_provider_fields_at(
    path: &std::path::Path,
    provider: &str,
    fields: &serde_json::Map<String, serde_json::Value>,
) -> std::result::Result<(), String> {
    with_locked_root(path, true, |root| {
        merge_provider_fields(root, provider, fields);
        Ok((true, ()))
    })
}

/// Merge known credential fields into an existing provider object rather
/// than replacing it. Providers may add metadata (including nested objects)
/// that must survive refresh/login writes.
fn merge_provider_fields(
    root: &mut serde_json::Map<String, serde_json::Value>,
    provider: &str,
    fields: &serde_json::Map<String, serde_json::Value>,
) {
    let mut provider_value = root
        .remove(provider)
        .filter(serde_json::Value::is_object)
        .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
    if let Some(target) = provider_value.as_object_mut() {
        for (key, value) in fields {
            target.insert(key.clone(), value.clone());
        }
    }
    root.insert(provider.to_string(), provider_value);
}

/// Locked read-modify-write over the auth.json root object.
///
/// Holds the exclusive `auth.json.lock` for the whole cycle, hands the parsed
/// root to `edit`, and — when `edit` returns `(true, _)` — writes the result
/// atomically (0600 tmp + rename). `recover_corrupt` lets the legacy
/// single-credential writers reset an EMPTY file (with a backup); any other
/// unparseable content is always an error.
fn with_locked_root<T>(
    path: &std::path::Path,
    recover_corrupt: bool,
    edit: impl FnOnce(
        &mut serde_json::Map<String, serde_json::Value>,
    ) -> std::result::Result<(bool, T), String>,
) -> std::result::Result<T, String> {
    with_locked_root_typed(path, recover_corrupt, STORE_LOCK_WAIT, edit).map_err(String::from)
}

/// Longest wait for `auth.json.lock`. A healthy holder keeps it for one
/// read-merge-fsync-rename (milliseconds); a stopped or wedged process must
/// not block every saver (and the refresh runtime's workers) forever.
pub(crate) const STORE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(15);

/// Why a locked store edit failed: the lock stayed held past the deadline,
/// or anything else (I/O, parse, the edit itself).
#[derive(Debug)]
pub(crate) enum StoreError {
    Busy(String),
    /// auth.json exists but does not parse; the message names the file and
    /// the exact command to move it aside (see [`corrupt_store`]).
    Corrupt(String),
    Failed(String),
}

impl From<StoreError> for String {
    fn from(e: StoreError) -> Self {
        match e {
            StoreError::Busy(m) | StoreError::Corrupt(m) | StoreError::Failed(m) => m,
        }
    }
}

/// The corrupt-store error: names the file, says why it is not reset, and
/// gives the exact command to move it aside. Never suggests `synaps login`
/// on its own: login fails on the same file until it is moved.
pub(crate) fn corrupt_store(path: &Path, err: &serde_json::Error) -> StoreError {
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let p = path.display().to_string();
    StoreError::Corrupt(format!(
        "{p} is not valid JSON ({err}); synaps will not overwrite it because it may hold other \
         accounts. Move it aside with `mv {} {}`, then log in again (or repair it by hand).",
        shell_quote(&p),
        shell_quote(&format!("{p}.broken-{ts}"))
    ))
}

/// POSIX single-quote `s` for a copy-pasteable command.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

impl From<String> for StoreError {
    fn from(m: String) -> Self {
        StoreError::Failed(m)
    }
}

/// Poll `try_lock_exclusive` until `wait` runs out.
fn lock_store_exclusive(
    lock_file: &std::fs::File,
    lock_path: &std::path::Path,
    wait: std::time::Duration,
) -> std::result::Result<(), StoreError> {
    use fs4::fs_std::FileExt;
    let deadline = std::time::Instant::now() + wait;
    loop {
        match FileExt::try_lock_exclusive(lock_file) {
            Ok(true) => return Ok(()),
            Ok(false) => {}
            Err(e) => {
                return Err(StoreError::Failed(format!(
                    "Failed to lock {}: {}",
                    lock_path.display(),
                    e
                )))
            }
        }
        if std::time::Instant::now() >= deadline {
            return Err(StoreError::Busy(format!(
                "timed out after {}s waiting for {} (another synaps process holds it)",
                wait.as_secs(),
                lock_path.display()
            )));
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    }
}

fn with_locked_root_typed<T>(
    path: &std::path::Path,
    recover_corrupt: bool,
    wait: std::time::Duration,
    edit: impl FnOnce(
        &mut serde_json::Map<String, serde_json::Value>,
    ) -> std::result::Result<(bool, T), String>,
) -> std::result::Result<T, StoreError> {
    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("Failed to create {}: {}", parent.display(), e))?;
    }

    // Hold an exclusive lock for the entire read-modify-write cycle.
    // Without this, two concurrent `synaps login` processes can race:
    // both read the same file, each adds their provider, second write
    // silently drops the first's credential.
    let lock_path = path.with_extension("json.lock");
    let lock_file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&lock_path)
        .map_err(|e| format!("Failed to open lock file {}: {}", lock_path.display(), e))?;
    lock_store_exclusive(&lock_file, &lock_path, wait)?;

    let mut root = if path.exists() {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
        // Corrupt-file recovery is limited to a file with nothing in it
        // (zero-length or whitespace, e.g. a crash before the first write):
        // that holds no account to lose. Anything else that does not parse
        // (a truncated write, a manual edit error) may still hold every
        // named slot's refresh token; resetting it would log the user out
        // of all of them, so it is an error for the user to repair.
        match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&content) {
            Ok(map) => map,
            Err(e) if !recover_corrupt || !content.trim().is_empty() => {
                return Err(corrupt_store(path, &e));
            }
            Err(e) => {
                tracing::warn!(
                    path = %path.display(),
                    error = %e,
                    "auth.json could not be parsed as a JSON object; replacing with a fresh structure"
                );
                // Back up the corrupt file so credentials are potentially recoverable.
                let ts = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                let backup = path.with_extension(format!("json.corrupt.{}", ts));
                match std::fs::copy(path, &backup) {
                    Ok(_) => {
                        eprintln!(
                            "[warn] auth.json was corrupt and has been reset. Backup saved to: {}",
                            backup.display()
                        );
                    }
                    Err(copy_err) => {
                        eprintln!(
                            "[warn] auth.json was corrupt and has been reset, but backup failed: {}",
                            copy_err
                        );
                    }
                }
                serde_json::Map::new()
            }
        }
    } else {
        serde_json::Map::new()
    };

    let (write, result) = edit(&mut root)?;
    if !write {
        return Ok(result);
    }

    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| format!("Failed to serialize auth: {}", e))?;

    // Atomic write: write to .tmp then rename. rename(2) is atomic on POSIX.
    // This prevents a crash/kill between truncate and write from zeroing auth.json.
    // Create with restrictive permissions from the start so credentials are never
    // world-readable, even briefly.
    let tmp_path = path.with_extension("json.tmp");
    {
        use std::io::Write;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&tmp_path)
            .map_err(|e| format!("Failed to create {}: {}", tmp_path.display(), e))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o600);
            file.set_permissions(perms).map_err(|e| {
                format!("Failed to set permissions on {}: {}", tmp_path.display(), e)
            })?;
        }

        file.write_all(json.as_bytes())
            .map_err(|e| format!("Failed to write {}: {}", tmp_path.display(), e))?;
        file.sync_all()
            .map_err(|e| format!("Failed to fsync {}: {}", tmp_path.display(), e))?;
    }

    std::fs::rename(&tmp_path, path)
        .map_err(|e| format!("Failed to atomically replace {}: {}", path.display(), e))?;

    Ok(result)
}

/// Test-only re-export of `save_provider_auth_at` so that `token::tests`
/// can exercise the same function `ensure_fresh_token` now delegates to,
/// without making the path-explicit variant part of the public API.
#[cfg(test)]
pub(super) fn save_provider_auth_at_test_hook(
    path: &std::path::Path,
    provider: &str,
    creds: &OAuthCredentials,
) -> std::result::Result<(), String> {
    save_provider_auth_at(path, provider, creds)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fresh_creds() -> OAuthCredentials {
        OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "r".to_string(),
            access: "a".to_string(),
            expires: 1,
            account_id: None,
        }
    }

    #[test]
    fn save_preserves_unknown_nested_provider_metadata() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(&path, r#"{"openai-codex":{"type":"oauth","refresh":"old","access":"old","expires":1,"metadata":{"tenant":"t1","flags":{"beta":true}}}}"#).unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).unwrap();
        let value: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
        assert_eq!(value["openai-codex"]["metadata"]["tenant"], "t1");
        assert_eq!(value["openai-codex"]["metadata"]["flags"]["beta"], true);
        assert_eq!(value["openai-codex"]["access"], "a");
    }

    #[test]
    fn save_provider_auth_at_creates_file_when_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed.get("openai-codex").is_some());
    }

    #[test]
    fn save_provider_auth_at_preserves_other_providers() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(
            &path,
            r#"{"anthropic":{"type":"oauth","refresh":"r2","access":"a2","expires":2}}"#,
        )
        .unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save");
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(
            parsed.get("anthropic").is_some(),
            "must keep anthropic entry"
        );
        assert!(parsed.get("openai-codex").is_some());
    }

    /// 147 I4: a corrupt multi-account store is never reset by a legacy
    /// save (it would drop every named slot). The save fails and the file is
    /// left exactly as it was, for the user to repair.
    #[test]
    fn legacy_save_refuses_to_reset_a_corrupt_store() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        // A truncated multi-account store.
        let corrupt = r#"{"anthropic":{"type":"oauth","refresh":"r1"},"anthropic@work":{"type":"oau"#;
        std::fs::write(&path, corrupt).unwrap();
        for save in [
            save_provider_auth_at(&path, "openai-codex", &fresh_creds()),
            save_static_key_at(&path, "groq", "gsk-1"),
        ] {
            let err = save.expect_err("must not reset a corrupt store");
            assert!(err.contains("not valid JSON"), "{err}");
            assert!(err.contains("other accounts"), "{err}");
        }
        assert_eq!(std::fs::read_to_string(&path).unwrap(), corrupt, "file untouched");
        let backups = std::fs::read_dir(dir.path())
            .unwrap()
            .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".corrupt."))
            .count();
        assert_eq!(backups, 0, "nothing reset, nothing to back up");
    }

    #[test]
    fn legacy_save_refuses_a_non_object_root() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "[1, 2, 3]").unwrap();
        save_provider_auth_at(&path, "openai-codex", &fresh_creds())
            .expect_err("a non-object root may still hold data");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[1, 2, 3]");
    }

    /// An empty / whitespace-only file holds nothing to lose: it is reset
    /// (with the usual `.corrupt.<ts>` backup) so `synaps login` still works.
    #[test]
    fn legacy_save_resets_an_empty_store_with_a_backup() {
        for content in ["", "  \n\t "] {
            let dir = tempfile::tempdir().expect("tempdir");
            let path = dir.path().join("auth.json");
            std::fs::write(&path, content).unwrap();
            save_provider_auth_at(&path, "openai-codex", &fresh_creds())
                .expect("empty store is reset");
            let parsed: serde_json::Value =
                serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
            assert!(parsed.get("openai-codex").is_some());
            let backups = std::fs::read_dir(dir.path())
                .unwrap()
                .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".corrupt."))
                .count();
            assert_eq!(backups, 1, "{content:?}");
        }
    }

    // ── Broker-owned static-key storage ──────────────────────────────────────

    /// Saving a static key must preserve existing OAuth entries (cross-provider
    /// isolation at the storage layer), and vice versa.
    #[test]
    fn static_key_save_preserves_oauth_entries_and_roundtrips() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "anthropic", &fresh_creds()).expect("save oauth");
        save_static_key_at(&path, "groq", "gsk-secret-1").expect("save static key");

        assert_eq!(
            load_static_key_at(&path, "groq").unwrap().as_deref(),
            Some("gsk-secret-1")
        );
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(
            parsed["anthropic"]["refresh"], "r",
            "OAuth entry must survive"
        );
        assert_eq!(parsed["groq"]["type"], "api_key");
    }

    /// An OAuth save must not disturb a broker-owned static key.
    #[test]
    fn oauth_save_preserves_static_key_entries() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        save_static_key_at(&path, "openrouter", "sk-or-1").expect("save static key");
        save_provider_auth_at(&path, "openai-codex", &fresh_creds()).expect("save oauth");
        assert_eq!(
            load_static_key_at(&path, "openrouter").unwrap().as_deref(),
            Some("sk-or-1")
        );
    }

    /// Static-key updates merge in place and keep unknown metadata on the entry.
    #[test]
    fn static_key_upsert_preserves_entry_metadata() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        std::fs::write(
            &path,
            r#"{"groq":{"type":"api_key","key":"old","note":{"source":"migrated"}}}"#,
        )
        .unwrap();
        save_static_key_at(&path, "groq", "new-key").expect("upsert");
        let parsed: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(parsed["groq"]["key"], "new-key");
        assert_eq!(parsed["groq"]["note"]["source"], "migrated");
    }

    /// Loading a static key from an OAuth entry must return None — the two
    /// credential kinds never blur (cross-kind isolation).
    #[test]
    fn load_static_key_ignores_oauth_entries() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "anthropic", &fresh_creds()).expect("save oauth");
        assert_eq!(load_static_key_at(&path, "anthropic").unwrap(), None);
        assert_eq!(load_static_key_at(&path, "missing").unwrap(), None);
    }

    // ── Bug #159 regression suite ────────────────────────────────────────────
    //
    // Repro: `synaps login --provider openai-codex` (saves "openai-codex"),
    // then `synaps login` (Anthropic OAuth, saves "anthropic") → the first
    // provider's credential was wiped because save_auth() rebuilt AuthFile
    // with only the new entry and did a whole-file overwrite.
    //
    // Root cause (pre-fix): src/core/auth/storage.rs @ 90f8f71 — save_auth()
    // constructed `AuthFile { anthropic: creds }` (no read of existing file)
    // then called `fs::write(path, json)`, discarding every other provider.
    //
    // All three multi-provider tests below would FAIL against that code.

    /// Primary repro (bug #159): save openai-codex, then save anthropic via
    /// the same write path `synaps login` (Anthropic OAuth) takes.
    /// openai-codex MUST survive the second login.
    #[test]
    fn bug159_anthropic_login_preserves_existing_openai_codex() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        // Step 1: user runs `synaps login --provider openai-codex`
        let codex_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "codex-refresh".to_string(),
            access: "codex-access".to_string(),
            expires: 9_999_999_999_000,
            account_id: Some("acct_codex_123".to_string()),
        };
        save_provider_auth_at(&path, "openai-codex", &codex_creds).expect("save openai-codex");

        // Step 2: user then runs `synaps login` (Anthropic Claude OAuth)
        let anthropic_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "anth-refresh".to_string(),
            access: "anth-access".to_string(),
            expires: 9_999_999_999_000,
            account_id: None,
        };
        save_provider_auth_at(&path, "anthropic", &anthropic_creds).expect("save anthropic");

        // Both providers must be present — bug #159 would wipe openai-codex here
        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(
            parsed.get("anthropic").is_some(),
            "anthropic credential must be present after login"
        );
        assert!(
            parsed.get("openai-codex").is_some(),
            "bug #159: openai-codex credential must NOT be wiped when logging in as anthropic"
        );
        assert_eq!(
            parsed["openai-codex"]["refresh"].as_str(),
            Some("codex-refresh"),
            "openai-codex refresh token must be unchanged"
        );
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("anth-refresh"),
            "anthropic refresh token must be correctly saved"
        );
    }

    /// Reverse of primary repro: anthropic first, then openai-codex login.
    /// anthropic MUST survive.
    #[test]
    fn bug159_openai_codex_login_preserves_existing_anthropic() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        // Step 1: anthropic already logged in
        let anthropic_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "anth-refresh-first".to_string(),
            access: "anth-access-first".to_string(),
            expires: 9_999_999_999_000,
            account_id: None,
        };
        save_provider_auth_at(&path, "anthropic", &anthropic_creds).expect("save anthropic");

        // Step 2: user runs `synaps login --provider openai-codex`
        let codex_creds = OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: "codex-refresh-second".to_string(),
            access: "codex-access-second".to_string(),
            expires: 9_999_999_999_000,
            account_id: Some("acct_456".to_string()),
        };
        save_provider_auth_at(&path, "openai-codex", &codex_creds).expect("save openai-codex");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(
            parsed.get("anthropic").is_some(),
            "anthropic credential must survive openai-codex login"
        );
        assert!(
            parsed.get("openai-codex").is_some(),
            "openai-codex credential must be present"
        );
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("anth-refresh-first"),
            "anthropic refresh token must be unchanged"
        );
    }

    /// Three-provider scenario: saving a third provider preserves the first two.
    /// Guards against regressions if/when more OAuth providers are added.
    #[test]
    fn bug159_third_provider_login_preserves_both_existing_providers() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        save_provider_auth_at(
            &path,
            "anthropic",
            &OAuthCredentials {
                auth_type: "oauth".to_string(),
                refresh: "anth-r".to_string(),
                access: "anth-a".to_string(),
                expires: 1,
                account_id: None,
            },
        )
        .expect("save anthropic");

        save_provider_auth_at(
            &path,
            "openai-codex",
            &OAuthCredentials {
                auth_type: "oauth".to_string(),
                refresh: "codex-r".to_string(),
                access: "codex-a".to_string(),
                expires: 1,
                account_id: Some("acct_codex".to_string()),
            },
        )
        .expect("save openai-codex");

        save_provider_auth_at(
            &path,
            "future-provider",
            &OAuthCredentials {
                auth_type: "oauth".to_string(),
                refresh: "future-r".to_string(),
                access: "future-a".to_string(),
                expires: 1,
                account_id: None,
            },
        )
        .expect("save future-provider");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        assert!(parsed.get("anthropic").is_some(), "anthropic must survive");
        assert!(
            parsed.get("openai-codex").is_some(),
            "openai-codex must survive"
        );
        assert!(
            parsed.get("future-provider").is_some(),
            "future-provider must be present"
        );
    }

    /// Upsert: saving the same provider twice updates the credential in place
    /// without duplicating or corrupting the entry.
    #[test]
    fn bug159_same_provider_login_upserts_in_place() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("auth.json");

        save_provider_auth_at(
            &path,
            "anthropic",
            &OAuthCredentials {
                auth_type: "oauth".to_string(),
                refresh: "old-refresh".to_string(),
                access: "old-access".to_string(),
                expires: 1,
                account_id: None,
            },
        )
        .expect("initial save");

        save_provider_auth_at(
            &path,
            "anthropic",
            &OAuthCredentials {
                auth_type: "oauth".to_string(),
                refresh: "new-refresh".to_string(),
                access: "new-access".to_string(),
                expires: 2,
                account_id: None,
            },
        )
        .expect("upsert save");

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let obj = parsed.as_object().unwrap();

        assert_eq!(obj.len(), 1, "only one anthropic entry — no duplicates");
        assert_eq!(
            parsed["anthropic"]["refresh"].as_str(),
            Some("new-refresh"),
            "credential must be updated to latest value"
        );
    }

    // ── Multi-account slots (G1) ─────────────────────────────────────────────

    fn creds(refresh: &str, account_id: Option<&str>) -> OAuthCredentials {
        OAuthCredentials {
            auth_type: "oauth".to_string(),
            refresh: refresh.to_string(),
            access: format!("{refresh}-access"),
            expires: 5,
            account_id: account_id.map(str::to_string),
        }
    }

    fn named(provider: OAuthProviderId, label: &str) -> CredentialRef {
        CredentialRef::new(provider, Account::named(label).unwrap())
    }

    fn read_root(path: &Path) -> serde_json::Map<String, serde_json::Value> {
        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
    }

    #[test]
    fn named_slot_save_never_touches_default_slot() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        // Legacy single-account file, written exactly as older versions do.
        std::fs::write(
            &path,
            r#"{"openai-codex":{"type":"oauth","refresh":"legacy-r","access":"legacy-a","expires":1,"accountId":"acct-legacy"}}"#,
        )
        .unwrap();
        let astra2 = named(OAuthProviderId::OpenAiCodex, "astra2");
        save_provider_auth_at(&path, &astra2.storage_key(), &creds("r2", Some("acct-2"))).unwrap();
        let root = read_root(&path);
        assert_eq!(root["openai-codex"]["refresh"], "legacy-r", "default slot untouched");
        assert_eq!(root["openai-codex"]["accountId"], "acct-legacy");
        assert_eq!(root["openai-codex@astra2"]["refresh"], "r2");
        assert_eq!(root.len(), 2);

        // Legacy readers keep resolving the bare key.
        let legacy = load_provider_auth_at(&path, "openai-codex").unwrap().unwrap();
        assert_eq!(legacy.refresh, "legacy-r");
        let slot = load_provider_auth_at(&path, &astra2.storage_key()).unwrap().unwrap();
        assert_eq!(slot.refresh, "r2");
        // The named slot is invisible under the bare key and vice versa.
        assert!(load_provider_auth_at(&path, "openai-codex@missing").unwrap().is_none());
    }

    #[test]
    fn list_accounts_reports_default_named_and_malformed_without_secrets() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        std::fs::write(
            &path,
            r#"{
              "openai-codex": {"type":"oauth","refresh":"R0","access":"A0","expires":10,"accountId":"2b2f0000-1111"},
              "openai-codex@astra2": {"type":"oauth","refresh":"R1","access":"A1","expires":20,"accountId":"7f530000-2222","label":"astra2","identity":"a@example.com","addedAt":99},
              "openai-codex@Bad Label": {"type":"oauth","refresh":"R2","access":"A2","expires":0},
              "openai-codex@default": {"type":"oauth","refresh":"R3","access":"A3","expires":0},
              "openai-codex@notoken": {"type":"oauth","expires":5},
              "openai-codex@badtype": {"type":"oauth","refresh":{"nested":"SECRET-VALUE"},"access":"A5","expires":5},
              "openai-codex@empty": {"type":"oauth","refresh":"","access":"","expires":5},
              "anthropic": {"type":"oauth","refresh":"R4","access":"A4","expires":30},
              "groq": {"type":"api_key","key":"gsk-secret"},
              "aws-bedrock": {"type":"cloud","cloud_state":{}}
            }"#,
        )
        .unwrap();
        let inv = list_accounts_detailed_at(&path, Some(OAuthProviderId::OpenAiCodex)).unwrap();
        assert_eq!(inv.accounts.len(), 2, "{:?}", inv.accounts);
        assert_eq!(inv.accounts[0].label, "default");
        assert_eq!(inv.accounts[0].account_id_prefix.as_deref(), Some("2b2f0000"));
        assert_eq!(
            inv.accounts[0].seat_fingerprint,
            super::super::account::seat_fingerprint(OAuthProviderId::OpenAiCodex, "2b2f0000-1111")
        );
        assert_ne!(inv.accounts[0].seat_fingerprint, inv.accounts[1].seat_fingerprint);
        assert_eq!(inv.accounts[0].expires, 10);
        assert_eq!(inv.accounts[1].label, "astra2");
        assert_eq!(inv.accounts[1].identity.as_deref(), Some("a@example.com"));
        assert_eq!(inv.accounts[1].added_at, Some(99));
        assert_eq!(inv.malformed_keys.len(), 5, "{:?}", inv.malformed_keys);
        for key in [
            "openai-codex@Bad Label",
            "openai-codex@default",
            "openai-codex@notoken",
            "openai-codex@badtype",
            "openai-codex@empty",
        ] {
            assert!(inv.malformed_keys.contains(&key.to_string()), "{key}");
        }
        let diag = format!("{:?}", inv);
        assert!(!diag.contains("SECRET-VALUE"), "diagnostics must not dump values");

        let all = list_accounts_detailed_at(&path, None).unwrap();
        assert_eq!(all.accounts.len(), 3);
        assert!(all.accounts.iter().all(|a| a.provider != "groq" && a.provider != "aws-bedrock"));
        let json = serde_json::to_string(&all.accounts).unwrap();
        for secret in ["R0", "R1", "R4", "A0", "A1", "A4", "A5", "gsk-secret", "SECRET-VALUE"] {
            assert!(!json.contains(secret), "listing leaked {secret}: {json}");
        }
        assert!(!json.contains("2b2f0000-1111"), "full account id must not be exposed");
        assert!(any_oauth_credential_present_at(&path).unwrap());
    }

    #[test]
    fn any_oauth_credential_present_accepts_non_anthropic_only_and_rejects_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        assert!(!any_oauth_credential_present_at(&path).unwrap(), "missing file");
        std::fs::write(&path, r#"{"groq":{"type":"api_key","key":"k"}}"#).unwrap();
        assert!(!any_oauth_credential_present_at(&path).unwrap(), "static keys are not OAuth");
        std::fs::write(
            &path,
            r#"{"kimi-code@m27":{"type":"oauth","refresh":"r","access":"a","expires":1}}"#,
        )
        .unwrap();
        assert!(any_oauth_credential_present_at(&path).unwrap(), "named Kimi-only install");
        std::fs::write(&path, "not json").unwrap();
        assert!(any_oauth_credential_present_at(&path).is_err());
    }

    #[test]
    fn remove_credential_removes_exactly_one_key() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &creds("r0", None)).unwrap();
        save_provider_auth_at(&path, "openai-codex@a", &creds("ra", None)).unwrap();
        save_provider_auth_at(&path, "openai-codex@b", &creds("rb", None)).unwrap();
        assert!(remove_key_at(&path, "openai-codex@a").unwrap());
        let root = read_root(&path);
        assert_eq!(root.len(), 2);
        assert_eq!(root["openai-codex"]["refresh"], "r0");
        assert_eq!(root["openai-codex@b"]["refresh"], "rb");
        assert!(!remove_key_at(&path, "openai-codex@a").unwrap(), "idempotent");
        assert!(!path.with_extension("json.tmp").exists());
        // Removal never resets a corrupt file.
        std::fs::write(&path, "garbage{").unwrap();
        assert!(remove_key_at(&path, "openai-codex").is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "garbage{");
    }

    #[test]
    fn metadata_round_trip_and_preserved_across_refresh_write() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        let cred = named(OAuthProviderId::Anthropic, "work");
        save_provider_auth_at(&path, &cred.storage_key(), &creds("r1", None)).unwrap();
        save_account_metadata_at(
            &path,
            &cred,
            &AccountMetadata {
                identity: Some("me@example.com".into()),
                added_at: Some(1234),
            },
        )
        .unwrap();
        // A refresh-style write carries only token fields.
        save_provider_auth_at(&path, &cred.storage_key(), &creds("r2", None)).unwrap();
        let root = read_root(&path);
        assert_eq!(root["anthropic@work"]["label"], "work");
        assert_eq!(root["anthropic@work"]["identity"], "me@example.com");
        assert_eq!(root["anthropic@work"]["addedAt"], 1234);
        assert_eq!(root["anthropic@work"]["refresh"], "r2");
        // Metadata on a missing slot is an error, not a phantom entry.
        assert!(save_account_metadata_at(
            &path,
            &named(OAuthProviderId::Anthropic, "nope"),
            &AccountMetadata::default()
        )
        .is_err());
        assert!(read_root(&path).get("anthropic@nope").is_none());
    }

    #[test]
    fn set_slot_identity_sets_only_identity_fields_on_existing_slot() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        // Hand-written entry with every field a real slot carries, plus
        // provider metadata that must survive untouched.
        std::fs::write(
            &path,
            r#"{
              "anthropic@claude1": {"type":"oauth","refresh":"R-claude1","access":"A-claude1","expires":1234567,"label":"claude1","addedAt":99,"identity":"old@example.com","metadata":{"tenant":"t1"}},
              "anthropic": {"type":"oauth","refresh":"R-default","access":"A-default","expires":7},
              "groq": {"type":"api_key","key":"gsk-secret"}
            }"#,
        )
        .unwrap();
        let before = read_root(&path);
        let cred = named(OAuthProviderId::Anthropic, "claude1");

        set_slot_identity_at(
            &path,
            &cred,
            "  b8a1448d-0000-4000-8000-00000000000a  ",
            Some("  jr@example.com "),
        )
        .unwrap();
        let after = read_root(&path);
        let slot = after["anthropic@claude1"].as_object().unwrap();
        assert_eq!(
            slot["accountId"], "b8a1448d-0000-4000-8000-00000000000a",
            "trimmed"
        );
        assert_eq!(slot["identity"], "jr@example.com", "trimmed");
        // Every other field is byte-identical to what was stored.
        for field in [
            "type", "refresh", "access", "expires", "label", "addedAt", "metadata",
        ] {
            assert_eq!(
                slot.get(field),
                before["anthropic@claude1"].get(field),
                "{field} must be untouched"
            );
        }
        assert_eq!(
            slot.len(),
            before["anthropic@claude1"].as_object().unwrap().len() + 1,
            "exactly one new key (accountId); identity was overwritten in place"
        );
        // Sibling slots and non-OAuth entries are untouched.
        assert_eq!(after["anthropic"], before["anthropic"]);
        assert_eq!(after["groq"], before["groq"]);
        assert_eq!(after.len(), before.len());
        // The listing now sees the seat.
        let inv = list_accounts_detailed_at(&path, Some(OAuthProviderId::Anthropic)).unwrap();
        let row = inv.accounts.iter().find(|a| a.label == "claude1").unwrap();
        assert_eq!(row.account_id_prefix.as_deref(), Some("b8a1448d"));
        assert_eq!(row.identity.as_deref(), Some("jr@example.com"));
        assert!(row.seat_fingerprint.is_some());

        // identity None keeps the stored identity; accountId is updated.
        set_slot_identity_at(&path, &cred, "other-seat", None).unwrap();
        let slot = &read_root(&path)["anthropic@claude1"];
        assert_eq!(slot["accountId"], "other-seat");
        assert_eq!(slot["identity"], "jr@example.com");
        // Empty/blank identity is ignored, never written as "".
        set_slot_identity_at(&path, &cred, "other-seat", Some("   ")).unwrap();
        assert_eq!(
            read_root(&path)["anthropic@claude1"]["identity"],
            "jr@example.com"
        );

        // Backfilling the default slot makes the duplicate visible.
        set_slot_identity_at(
            &path,
            &CredentialRef::default_for(OAuthProviderId::Anthropic),
            "other-seat",
            None,
        )
        .unwrap();
        let inv = list_accounts_detailed_at(&path, Some(OAuthProviderId::Anthropic)).unwrap();
        assert_eq!(
            inv.duplicate_identity_keys,
            vec!["anthropic".to_string(), "anthropic@claude1".to_string()]
        );
        assert_eq!(read_root(&path)["anthropic"]["refresh"], "R-default");
    }

    #[test]
    fn set_slot_identity_fails_closed_and_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        let cred = named(OAuthProviderId::Anthropic, "claude1");
        // Missing store: error, and no file/lock/dir side effects.
        assert!(set_slot_identity_at(&path, &cred, "seat", None).is_err());
        assert!(!path.exists());
        assert!(!path.with_extension("json.lock").exists());

        std::fs::write(
            &path,
            r#"{"anthropic":{"type":"oauth","refresh":"R","access":"A","expires":1},"groq":{"type":"api_key","key":"k"}}"#,
        )
        .unwrap();
        let before = std::fs::read_to_string(&path).unwrap();
        // Missing slot.
        assert!(set_slot_identity_at(&path, &cred, "seat", Some("x@example.com")).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), before);
        assert!(
            read_root(&path).get("anthropic@claude1").is_none(),
            "no phantom slot"
        );
        // Empty / blank account id.
        let default = CredentialRef::default_for(OAuthProviderId::Anthropic);
        assert!(set_slot_identity_at(&path, &default, "", None).is_err());
        assert!(set_slot_identity_at(&path, &default, "   ", Some("x@example.com")).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), before);
        assert!(read_root(&path)["anthropic"].get("accountId").is_none());
        // Corrupt store: refused, never reset.
        std::fs::write(&path, "{{not json").unwrap();
        assert!(set_slot_identity_at(&path, &default, "seat", None).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{{not json");
    }

    #[test]
    fn cas_save_saved_removed_replaced() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        let key = "openai-codex@astra2";
        save_provider_auth_at(&path, key, &creds("old", Some("acct-1"))).unwrap();

        // Rotated credential without accountId must keep the stored one.
        let rotated = creds("old-rotated", None);
        assert_eq!(
            save_provider_auth_if_refresh_matches_at(&path, key, "old", &rotated).unwrap(),
            CasOutcome::Saved
        );
        let root = read_root(&path);
        assert_eq!(root[key]["refresh"], "old-rotated");
        assert_eq!(root[key]["accountId"], "acct-1", "accountId preserved");

        // Re-login replaced the slot meanwhile: stale rotation must not win.
        save_provider_auth_at(&path, key, &creds("fresh-login", Some("acct-9"))).unwrap();
        assert_eq!(
            save_provider_auth_if_refresh_matches_at(&path, key, "old-rotated", &creds("stale", None))
                .unwrap(),
            CasOutcome::Replaced
        );
        assert_eq!(read_root(&path)[key]["refresh"], "fresh-login");

        // Slot removed meanwhile: nothing is resurrected.
        remove_key_at(&path, key).unwrap();
        assert_eq!(
            save_provider_auth_if_refresh_matches_at(&path, key, "fresh-login", &creds("x", None))
                .unwrap(),
            CasOutcome::Removed
        );
        assert!(read_root(&path).get(key).is_none());
        // Missing file: nothing is created either (and the caller can tell
        // a missing store from a removed slot).
        std::fs::remove_file(&path).unwrap();
        assert_eq!(
            save_provider_auth_if_refresh_matches_at(&path, key, "x", &creds("x", None)).unwrap(),
            CasOutcome::StoreMissing
        );
        assert!(!path.exists());
    }

    #[test]
    fn locked_login_persist_refuses_duplicate_seat_and_writes_metadata_atomically() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &creds("r0", Some("acct-A"))).unwrap();
        let astra2 = named(OAuthProviderId::OpenAiCodex, "astra2");
        let meta = AccountMetadata {
            identity: Some("a@example.com".into()),
            added_at: Some(100),
        };
        // Same seat under a new label: refused, nothing written.
        let out = save_credential_unless_duplicate_at(&path, &astra2, &creds("rx", Some("acct-A")), &meta)
            .unwrap();
        assert_eq!(out.evidence, IdentityEvidence::Duplicate(Account::Default));
        assert!(!out.saved);
        assert!(read_root(&path).get("openai-codex@astra2").is_none());
        // Same refresh token (identical login) under a new label: refused too.
        let out = save_credential_unless_duplicate_at(&path, &astra2, &creds("r0", None), &meta).unwrap();
        assert_eq!(out.evidence, IdentityEvidence::Duplicate(Account::Default));
        assert!(!out.saved);
        // Distinct seat: saved with label/identity/addedAt.
        let out = save_credential_unless_duplicate_at(&path, &astra2, &creds("r2", Some("acct-B")), &meta)
            .unwrap();
        assert_eq!(out.evidence, IdentityEvidence::NoDuplicate);
        assert!(out.saved);
        let root = read_root(&path);
        assert_eq!(root["openai-codex@astra2"]["label"], "astra2");
        assert_eq!(root["openai-codex@astra2"]["identity"], "a@example.com");
        assert_eq!(root["openai-codex@astra2"]["addedAt"], 100);
        assert_eq!(root["openai-codex"]["refresh"], "r0", "default slot untouched");
        // Re-login into the same slot with a different seat and no identity:
        // stale identity/accountId are cleared, addedAt updated.
        let out = save_credential_unless_duplicate_at(
            &path,
            &astra2,
            &creds("r3", None),
            &AccountMetadata {
                identity: None,
                added_at: Some(200),
            },
        )
        .unwrap();
        assert_eq!(out.evidence, IdentityEvidence::NoEvidence);
        assert!(out.saved);
        let root = read_root(&path);
        assert!(root["openai-codex@astra2"].get("identity").is_none());
        assert!(root["openai-codex@astra2"].get("accountId").is_none());
        assert_eq!(root["openai-codex@astra2"]["addedAt"], 200);
        assert_eq!(root["openai-codex@astra2"]["refresh"], "r3");
        // Corrupt store: refused, never reset.
        std::fs::write(&path, "{{not json").unwrap();
        assert!(save_credential_unless_duplicate_at(&path, &astra2, &creds("r4", None), &meta).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{{not json");
        assert!(save_credential_at(&path, &astra2, &creds("r4", None)).is_err());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{{not json");
    }

    #[test]
    fn inventory_flags_duplicate_seats() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &creds("r0", Some("acct-A"))).unwrap();
        save_provider_auth_at(&path, "openai-codex@b", &creds("rb", Some("acct-A"))).unwrap();
        save_provider_auth_at(&path, "openai-codex@c", &creds("rc", Some("acct-C"))).unwrap();
        let inv = list_accounts_detailed_at(&path, Some(OAuthProviderId::OpenAiCodex)).unwrap();
        assert_eq!(
            inv.duplicate_identity_keys,
            vec!["openai-codex".to_string(), "openai-codex@b".to_string()]
        );
    }

    #[test]
    fn duplicate_identity_detects_same_seat_under_other_label() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        save_provider_auth_at(&path, "openai-codex", &creds("r0", Some("acct-A"))).unwrap();
        save_provider_auth_at(&path, "openai-codex@b", &creds("rb", Some("acct-B"))).unwrap();
        save_provider_auth_at(&path, "anthropic@x", &creds("rx", Some("acct-A"))).unwrap();
        let dup = find_duplicate_identity_at(
            &path,
            OAuthProviderId::OpenAiCodex,
            "acct-A",
            &Account::named("new").unwrap(),
        )
        .unwrap();
        assert_eq!(dup, Some(Account::Default));
        // Re-login into the same slot is not a duplicate of itself.
        assert_eq!(
            find_duplicate_identity_at(&path, OAuthProviderId::OpenAiCodex, "acct-A", &Account::Default)
                .unwrap(),
            None
        );
        // Other providers never collide; unknown ids never match; empty never matches.
        assert_eq!(
            find_duplicate_identity_at(&path, OAuthProviderId::OpenAiCodex, "acct-Z", &Account::Default)
                .unwrap(),
            None
        );
        assert_eq!(
            find_duplicate_identity_at(&path, OAuthProviderId::OpenAiCodex, "", &Account::Default)
                .unwrap(),
            None
        );
    }
}

/// m2: a wedged process holding `auth.json.lock` must not block a saver
/// (and with it a refresh-runtime worker) forever.
#[cfg(test)]
mod store_lock_wait_tests {
    use super::*;
    use std::time::{Duration, Instant};

    fn hold_store_lock(path: &Path) -> std::fs::File {
        use fs4::fs_std::FileExt;
        let lock = std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(path.with_extension("json.lock"))
            .unwrap();
        assert!(FileExt::try_lock_exclusive(&lock).unwrap());
        lock
    }

    #[test]
    fn store_lock_wait_has_a_deadline() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "{}").unwrap();
        let _held = hold_store_lock(&path);
        let started = Instant::now();
        let err = with_locked_root_typed(&path, false, Duration::from_millis(200), |_| {
            Ok((false, ()))
        })
        .unwrap_err();
        assert!(matches!(err, StoreError::Busy(_)), "{err:?}");
        assert!(started.elapsed() < Duration::from_secs(5));
        assert!(String::from(err).contains("auth.json.lock"));
    }

    #[test]
    fn store_lock_is_taken_once_free() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "{}").unwrap();
        let held = hold_store_lock(&path);
        let release = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(100));
            drop(held);
        });
        with_locked_root_typed(&path, false, Duration::from_secs(10), |_| Ok((false, ())))
            .expect("lock is acquired after the holder lets go");
        release.join().unwrap();
    }

    #[test]
    fn production_store_lock_wait_is_bounded() {
        assert!(STORE_LOCK_WAIT >= Duration::from_secs(5));
        assert!(STORE_LOCK_WAIT <= Duration::from_secs(30));
    }
}

/// Round-2 I2: a corrupt store is a typed error that names the file and the
/// exact command to move it aside, on the legacy, account and load paths.
#[cfg(test)]
mod corrupt_store_error_tests {
    use super::*;

    fn assert_actionable(msg: &str, path: &Path) {
        let p = path.display().to_string();
        assert!(msg.contains(&format!("mv '{p}' '{p}.broken-")), "{msg}");
        assert!(msg.contains("not valid JSON"), "{msg}");
        assert!(!msg.contains("synaps login"), "{msg}");
    }

    #[test]
    fn corrupt_store_error_names_the_file_and_the_mv_command() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        std::fs::write(&path, "{\"anthropic\":{").unwrap();
        let cred = CredentialRef::parse_storage_key("anthropic@work").unwrap();
        let creds = OAuthCredentials {
            auth_type: "oauth".into(),
            refresh: "r".into(),
            access: "a".into(),
            expires: 1,
            account_id: None,
        };
        // Legacy (login) save and account-scoped save: same text.
        assert_actionable(&save_provider_auth_at(&path, "kimi-code", &creds).unwrap_err(), &path);
        assert_actionable(&save_credential_at(&path, &cred, &creds).unwrap_err(), &path);
        // Typed: both the login save and the load say Corrupt.
        for err in [
            save_provider_auth_typed_at(&path, "muse", &creds).unwrap_err(),
            load_provider_auth_typed_at(&path, "anthropic").unwrap_err(),
        ] {
            let StoreError::Corrupt(msg) = err else {
                panic!("expected Corrupt, got {err:?}");
            };
            assert_actionable(&msg, &path);
        }
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"anthropic\":{");
    }

    #[test]
    fn shell_quoting_survives_a_quote_in_the_path() {
        assert_eq!(shell_quote("/a/it's/auth.json"), r#"'/a/it'\''s/auth.json'"#);
    }
}

/// R2-m1: removing an account also removes its parked refresh sidecar (a
/// live refresh token for an account the user removed).
#[cfg(test)]
mod remove_sidecar_tests {
    use super::*;

    #[test]
    fn removing_a_slot_deletes_its_refresh_sidecar() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.json");
        std::fs::write(&path, r#"{"anthropic@work":{"type":"oauth"},"anthropic":{"type":"oauth"}}"#)
            .unwrap();
        let work = refresh_pending_path(&path, "anthropic@work");
        let other = refresh_pending_path(&path, "anthropic");
        assert_eq!(
            work,
            dir.path().join("auth.json.anthropic@work.refresh.pending")
        );
        std::fs::write(&work, "{}").unwrap();
        std::fs::write(&other, "{}").unwrap();
        assert!(remove_key_at(&path, "anthropic@work").unwrap());
        assert!(!work.exists(), "removed slot's sidecar is gone");
        assert!(other.exists(), "other slots keep theirs");
        // Even when the slot was already gone from the store.
        std::fs::write(&work, "{}").unwrap();
        assert!(!remove_key_at(&path, "anthropic@work").unwrap());
        assert!(!work.exists());
    }
}